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 all commits
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
6 changes: 5 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 Expand Up @@ -157,6 +159,8 @@ export type DispatchNodeResponseType = {

// tool
toolCallTokens?: number;
toolCallInputTokens?: number;
toolCallOutputTokens?: number;
toolDetail?: ChatHistoryItemResType[];
toolStop?: boolean;

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
2 changes: 1 addition & 1 deletion packages/plugins/src/feishu/template.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"author": "",
"version": "488",
"name": "飞书 webhook",
"avatar": "/appMarketTemplates/plugin-feishu/avatar.svg",
"avatar": "core/app/templates/plugin-feishu",
"intro": "向飞书机器人发起 webhook 请求。",
"courseUrl": "https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot#f62e72d5",
"showStatus": false,
Expand Down
15 changes: 10 additions & 5 deletions packages/service/core/ai/functions/createQuestionGuide.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ export async function createQuestionGuide({
customPrompt?: string;
}): Promise<{
result: string[];
tokens: number;
inputTokens: number;
outputTokens: number;
}> {
const concatMessages: ChatCompletionMessageParam[] = [
...messages,
Expand Down Expand Up @@ -51,13 +52,15 @@ export async function createQuestionGuide({
const start = answer.indexOf('[');
const end = answer.lastIndexOf(']');

const tokens = await countGptMessagesTokens(concatMessages);
const inputTokens = data.usage?.prompt_tokens || 0;
const outputTokens = data.usage?.completion_tokens || 0;

if (start === -1 || end === -1) {
addLog.warn('Create question guide error', { answer });
return {
result: [],
tokens: 0
inputTokens: 0,
outputTokens: 0
};
}

Expand All @@ -69,14 +72,16 @@ export async function createQuestionGuide({
try {
return {
result: json5.parse(jsonStr),
tokens
inputTokens,
outputTokens
};
} catch (error) {
console.log(error);

return {
result: [],
tokens: 0
inputTokens: 0,
outputTokens: 0
};
}
}
12 changes: 8 additions & 4 deletions packages/service/core/ai/functions/queryExtension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ export const queryExtension = async ({
rawQuery: string;
extensionQueries: string[];
model: string;
tokens: number;
inputTokens: number;
outputTokens: number;
}> => {
const systemFewShot = chatBg
? `Q: 对话背景。
Expand Down Expand Up @@ -166,7 +167,8 @@ A: ${chatBg}
rawQuery: query,
extensionQueries: [],
model,
tokens: 0
inputTokens: 0,
outputTokens: 0
};
}

Expand All @@ -181,15 +183,17 @@ A: ${chatBg}
rawQuery: query,
extensionQueries: Array.isArray(queries) ? queries : [],
model,
tokens: await countGptMessagesTokens(messages)
inputTokens: result.usage?.prompt_tokens || 0,
outputTokens: result.usage?.completion_tokens || 0
};
} catch (error) {
addLog.error(`Query extension error`, error);
return {
rawQuery: query,
extensionQueries: [],
model,
tokens: 0
inputTokens: 0,
outputTokens: 0
};
}
};
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
Loading
Loading