Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

split tokens into input and output #3477

Merged
merged 3 commits into from
Dec 29, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/global/core/ai/model.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export type LLMModelItemType = {
maxTemperature: number;

charsPointsPrice: number; // 1k chars=n points
inputPrice?: number; // 1k tokens=n points
outputPrice?: number; // 1k tokens=n points

censor?: boolean;
vision?: boolean;
Expand Down
4 changes: 3 additions & 1 deletion packages/global/core/workflow/runtime/type.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,9 @@ export type DispatchNodeResponseType = {
mergeSignId?: string;

// bill
tokens?: number;
tokens?: number; // deprecated
inputTokens?: number;
outputTokens?: number;
model?: string;
contextTotalLen?: number;
totalPoints?: number;
Expand Down
6 changes: 5 additions & 1 deletion packages/global/support/wallet/bill/type.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,14 @@ export type BillSchemaType = {
};

export type ChatNodeUsageType = {
tokens?: number;
inputTokens?: number;
outputTokens?: number;
totalPoints: number;
moduleName: string;
model?: string;

// deprecated
tokens?: number;
};

export type InvoiceType = {
Expand Down
6 changes: 5 additions & 1 deletion packages/global/support/wallet/usage/type.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ import { CreateUsageProps } from './api';
import { UsageSourceEnum } from './constants';

export type UsageListItemCountType = {
tokens?: number;
inputTokens?: number;
outputTokens?: number;
charsLength?: number;
duration?: number;

// deprecated
tokens?: number;
};
export type UsageListItemType = UsageListItemCountType & {
moduleName: string;
Expand Down
3 changes: 3 additions & 0 deletions packages/service/core/ai/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ export const getLLMModel = (model?: string) => {
global.llmModels[0]
);
};
export const getLLMModelPriceType = () => {
return global.llmModels.some((item) => item.inputPrice || item.outputPrice);
};
export const getDatasetModel = (model?: string) => {
return (
global.llmModels
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const dispatchClassifyQuestion = async (props: Props): Promise<CQResponse

const chatHistories = getHistories(history, histories);

const { arg, tokens } = await completions({
const { arg, inputTokens, outputTokens } = await completions({
...props,
histories: chatHistories,
cqModel
Expand All @@ -59,7 +59,8 @@ export const dispatchClassifyQuestion = async (props: Props): Promise<CQResponse

const { totalPoints, modelName } = formatModelChars2Points({
model: cqModel.model,
tokens,
inputTokens: inputTokens,
outputTokens: outputTokens,
modelType: ModelTypeEnum.llm
});

Expand All @@ -72,7 +73,8 @@ export const dispatchClassifyQuestion = async (props: Props): Promise<CQResponse
totalPoints: externalProvider.openaiAccount?.key ? 0 : totalPoints,
model: modelName,
query: userChatInput,
tokens,
inputTokens: inputTokens,
outputTokens: outputTokens,
cqList: agents,
cqResult: result.value,
contextTotalLen: chatHistories.length + 2
Expand All @@ -82,7 +84,8 @@ export const dispatchClassifyQuestion = async (props: Props): Promise<CQResponse
moduleName: name,
totalPoints: externalProvider.openaiAccount?.key ? 0 : totalPoints,
model: modelName,
tokens
inputTokens: inputTokens,
outputTokens: outputTokens
}
]
};
Expand Down Expand Up @@ -148,7 +151,8 @@ const completions = async ({
}

return {
tokens: await countMessagesTokens(messages),
inputTokens: data.usage?.prompt_tokens || 0,
outputTokens: data.usage?.completion_tokens || 0,
arg: { type: id }
};
};
42 changes: 28 additions & 14 deletions packages/service/core/workflow/dispatch/agent/extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export async function dispatchContentExtract(props: Props): Promise<Response> {
const extractModel = getLLMModel(model);
const chatHistories = getHistories(history, histories);

const { arg, tokens } = await (async () => {
const { arg, inputTokens, outputTokens } = await (async () => {
if (extractModel.toolChoice) {
return toolChoice({
...props,
Expand Down Expand Up @@ -114,7 +114,8 @@ export async function dispatchContentExtract(props: Props): Promise<Response> {

const { totalPoints, modelName } = formatModelChars2Points({
model: extractModel.model,
tokens,
inputTokens: inputTokens,
outputTokens: outputTokens,
modelType: ModelTypeEnum.llm
});

Expand All @@ -126,7 +127,8 @@ export async function dispatchContentExtract(props: Props): Promise<Response> {
totalPoints: externalProvider.openaiAccount?.key ? 0 : totalPoints,
model: modelName,
query: content,
tokens,
inputTokens,
outputTokens,
extractDescription: description,
extractResult: arg,
contextTotalLen: chatHistories.length + 2
Expand All @@ -136,7 +138,8 @@ export async function dispatchContentExtract(props: Props): Promise<Response> {
moduleName: name,
totalPoints: externalProvider.openaiAccount?.key ? 0 : totalPoints,
model: modelName,
tokens
inputTokens,
outputTokens
}
]
};
Expand Down Expand Up @@ -249,15 +252,18 @@ const toolChoice = async (props: ActionProps) => {
}
})();

const completeMessages: ChatCompletionMessageParam[] = [
...filterMessages,
const AIMessages: ChatCompletionMessageParam[] = [
{
role: ChatCompletionRequestMessageRoleEnum.Assistant,
tool_calls: response.choices?.[0]?.message?.tool_calls
}
];

const inputTokens = await countGptMessagesTokens(filterMessages, tools);
const outputTokens = await countGptMessagesTokens(AIMessages);
return {
tokens: await countGptMessagesTokens(completeMessages, tools),
inputTokens,
outputTokens,
arg
};
};
Expand Down Expand Up @@ -286,17 +292,21 @@ const functionCall = async (props: ActionProps) => {

try {
const arg = JSON.parse(response?.choices?.[0]?.message?.function_call?.arguments || '');
const completeMessages: ChatCompletionMessageParam[] = [
...filterMessages,

const AIMessages: ChatCompletionMessageParam[] = [
{
role: ChatCompletionRequestMessageRoleEnum.Assistant,
function_call: response.choices?.[0]?.message?.function_call
}
];

const inputTokens = await countGptMessagesTokens(filterMessages, undefined, functions);
const outputTokens = await countGptMessagesTokens(AIMessages, undefined, functions);
newfish-cmyk marked this conversation as resolved.
Show resolved Hide resolved

return {
arg,
tokens: await countGptMessagesTokens(completeMessages, undefined, functions)
inputTokens,
outputTokens
};
} catch (error) {
console.log(response.choices?.[0]?.message);
Expand All @@ -305,7 +315,8 @@ const functionCall = async (props: ActionProps) => {

return {
arg: {},
tokens: 0
inputTokens: 0,
outputTokens: 0
};
}
};
Expand Down Expand Up @@ -370,23 +381,26 @@ Human: ${content}`
if (!jsonStr) {
return {
rawResponse: answer,
tokens: await countMessagesTokens(messages),
inputTokens: await countMessagesTokens(messages),
outputTokens: 0,
arg: {}
};
}

try {
return {
rawResponse: answer,
tokens: await countMessagesTokens(messages),
inputTokens: data.usage?.prompt_tokens || 0,
outputTokens: data.usage?.completion_tokens || 0,
arg: json5.parse(jsonStr) as Record<string, any>
};
} catch (error) {
console.log('Extract error, ai answer:', answer);
console.log(error);
return {
rawResponse: answer,
tokens: await countMessagesTokens(messages),
inputTokens: await countMessagesTokens(messages),
outputTokens: 0,
arg: {}
};
}
Expand Down
31 changes: 22 additions & 9 deletions packages/service/core/workflow/dispatch/chat/oneapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import { ChatRoleEnum } from '@fastgpt/global/core/chat/constants';
import { SseResponseEventEnum } from '@fastgpt/global/core/workflow/runtime/constants';
import { textAdaptGptResponse } from '@fastgpt/global/core/workflow/runtime/utils';
import { createChatCompletion } from '../../../ai/config';
import type { ChatCompletion, StreamChatType } from '@fastgpt/global/core/ai/type.d';
import type {
ChatCompletion,
ChatCompletionMessageParam,
StreamChatType
} from '@fastgpt/global/core/ai/type.d';
import { formatModelChars2Points } from '../../../../support/wallet/usage/utils';
import type { LLMModelItemType } from '@fastgpt/global/core/ai/model.d';
import { postTextCensor } from '../../../../common/api/requestPlusApi';
Expand Down Expand Up @@ -214,16 +218,23 @@ export const dispatchChatCompletion = async (props: ChatProps): Promise<ChatResp
return Promise.reject(getEmptyResponseTip());
}

const completeMessages = requestMessages.concat({
role: ChatCompletionRequestMessageRoleEnum.Assistant,
content: answerText
});
const AIMessages: ChatCompletionMessageParam[] = [
{
role: ChatCompletionRequestMessageRoleEnum.Assistant,
content: answerText
}
];

const completeMessages = [...requestMessages, ...AIMessages];
const chatCompleteMessages = GPTMessages2Chats(completeMessages);

const tokens = await countMessagesTokens(chatCompleteMessages);
const inputTokens = await countMessagesTokens(GPTMessages2Chats(requestMessages));
const outputTokens = await countMessagesTokens(GPTMessages2Chats(AIMessages));

const { totalPoints, modelName } = formatModelChars2Points({
model,
tokens,
inputTokens,
outputTokens,
modelType: ModelTypeEnum.llm
});

Expand All @@ -232,7 +243,8 @@ export const dispatchChatCompletion = async (props: ChatProps): Promise<ChatResp
[DispatchNodeResponseKeyEnum.nodeResponse]: {
totalPoints: externalProvider.openaiAccount?.key ? 0 : totalPoints,
model: modelName,
tokens,
inputTokens: inputTokens,
outputTokens: outputTokens,
query: `${userChatInput}`,
maxToken: max_tokens,
historyPreview: getHistoryPreview(
Expand All @@ -247,7 +259,8 @@ export const dispatchChatCompletion = async (props: ChatProps): Promise<ChatResp
moduleName: name,
totalPoints: externalProvider.openaiAccount?.key ? 0 : totalPoints,
model: modelName,
tokens
inputTokens: inputTokens,
outputTokens: outputTokens
}
],
[DispatchNodeResponseKeyEnum.toolResponses]: answerText,
Expand Down
18 changes: 14 additions & 4 deletions packages/service/support/wallet/usage/utils.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,35 @@
import { ModelTypeEnum, getModelMap } from '../../../core/ai/model';
import { LLMModelItemType } from '@fastgpt/global/core/ai/model.d';
import { ModelTypeEnum, getLLMModelPriceType, getModelMap } from '../../../core/ai/model';

export const formatModelChars2Points = ({
model,
tokens = 0,
inputTokens = 0,
outputTokens = 0,
modelType,
multiple = 1000
}: {
model: string;
tokens: number;
tokens?: number;
inputTokens?: number;
outputTokens?: number;
modelType: `${ModelTypeEnum}`;
multiple?: number;
}) => {
const modelData = getModelMap?.[modelType]?.(model);
const modelData = getModelMap?.[modelType]?.(model) as LLMModelItemType;
if (!modelData) {
return {
totalPoints: 0,
modelName: ''
};
}

const totalPoints = (modelData.charsPointsPrice || 0) * (tokens / multiple);
const isIOType = modelType === ModelTypeEnum.llm && getLLMModelPriceType();

const totalPoints = isIOType
? ((modelData as LLMModelItemType).inputPrice || 0) * (inputTokens / multiple) +
((modelData as LLMModelItemType).outputPrice || 0) * (outputTokens / multiple)
: (modelData.charsPointsPrice || 0) * ((tokens || inputTokens + outputTokens) / multiple);

return {
modelName: modelData.name,
Expand Down
4 changes: 3 additions & 1 deletion packages/web/i18n/en/account_usage.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
"details": "Details",
"duration_seconds": "Duration (seconds)",
"generation_time": "Generation time",
"input_token_length": "input tokens",
"member": "member",
"member_name": "Member name",
"module_name": "module name",
"month": "moon",
"no_usage_records": "No usage record yet",
"order_number": "Order number",
"output_token_length": "output tokens",
"project_name": "Project name",
"source": "source",
"text_length": "text length",
Expand All @@ -20,4 +22,4 @@
"total_points_consumed": "AI points consumption",
"usage_detail": "Usage details",
"user_type": "type"
}
}
4 changes: 4 additions & 0 deletions packages/web/i18n/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -460,10 +460,12 @@
"core.chat.response.module historyPreview": "History Preview (Only Partial Content Displayed)",
"core.chat.response.module http result": "Response Body",
"core.chat.response.module if else Result": "Condition Result",
"core.chat.response.module input tokens": "input tokens",
"core.chat.response.module limit": "Single Search Limit",
"core.chat.response.module maxToken": "Max Response Tokens",
"core.chat.response.module model": "Model",
"core.chat.response.module name": "Model Name",
"core.chat.response.module output tokens": "output tokens",
"core.chat.response.module query": "Question/Search Term",
"core.chat.response.module quoteList": "Quote Content",
"core.chat.response.module similarity": "Similarity",
Expand Down Expand Up @@ -1042,6 +1044,8 @@
"support.user.team.Team Tags Async Success": "Sync Completed",
"support.user.team.member": "Member",
"support.wallet.Ai point every thousand tokens": "{{points}} Points/1K Tokens",
"support.wallet.Ai point every thousand tokens_input": "Input:{{points}} points/1K tokens",
"support.wallet.Ai point every thousand tokens_output": "Output:{{points}} points/1K tokens",
"support.wallet.Amount": "Amount",
"support.wallet.Buy": "Buy",
"support.wallet.Not sufficient": "Insufficient AI Points, Please Upgrade Your Package or Purchase Additional AI Points to Continue Using.",
Expand Down
Loading
Loading