Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(chat): send the operation id with client-runtime chat requests (#22411)

YuTengjinge433a0f6d3ed
diff --git a/locales/en-US/spend.json b/locales/en-US/spend.json
index 51809d4939f..6f12c922344 100644
--- a/locales/en-US/spend.json
+++ b/locales/en-US/spend.json
@@ -79,6 +79,9 @@
"table.filters.reset": "Reset",
"table.filters.searchModel": "Search model",
"table.filters.startDate": "Start date",
+ "table.group.agentRun": "Agent run",
+ "table.group.calls": "{{count}} calls",
+ "table.group.moreModels": "+{{count}}",
"table.pagination.next": "Next page",
"table.pagination.perPage": "{{size}} / page",
"table.pagination.prev": "Previous page",
diff --git a/locales/zh-CN/spend.json b/locales/zh-CN/spend.json
index 571d32ec248..32b8ee06171 100644
--- a/locales/zh-CN/spend.json
+++ b/locales/zh-CN/spend.json
@@ -79,6 +79,9 @@
"table.filters.reset": "重置",
"table.filters.searchModel": "搜索模型",
"table.filters.startDate": "开始日期",
+ "table.group.agentRun": "Agent 执行",
+ "table.group.calls": "{{count}} 次调用",
+ "table.group.moreModels": "+{{count}}",
"table.pagination.next": "下一页",
"table.pagination.perPage": "{{size}} 条/页",
"table.pagination.prev": "上一页",
diff --git a/packages/const/src/fetch.ts b/packages/const/src/fetch.ts
index aec260107e9..71452602635 100644
--- a/packages/const/src/fetch.ts
+++ b/packages/const/src/fetch.ts
@@ -1,4 +1,6 @@
export const REQUEST_TRIGGER_HEADER = 'x-lobechat-request-trigger';
export const REQUEST_AGENT_ID_HEADER = 'x-agent-id';
export const REQUEST_TOPIC_ID_HEADER = 'x-topic-id';
+/** The agent operation a client-runtime model call belongs to, so its usage groups with the run. */
+export const REQUEST_OPERATION_ID_HEADER = 'x-operation-id';
export const CLIENT_VERSION_HEADER = 'x-lobe-client-version';
diff --git a/packages/locales/src/default/spend.ts b/packages/locales/src/default/spend.ts
index 1685850e644..bd3025f4c64 100644
--- a/packages/locales/src/default/spend.ts
+++ b/packages/locales/src/default/spend.ts
@@ -72,6 +72,9 @@ export default {
'table.empty.filteredDescription': 'Try a different model, type, or date range.',
'table.empty.filteredTitle': 'No matching records',
'table.empty.title': 'No spend yet',
+ 'table.group.agentRun': 'Agent run',
+ 'table.group.calls': '{{count}} calls',
+ 'table.group.moreModels': '+{{count}}',
'table.error.description': 'Check your connection and try again.',
'table.error.title': "Couldn't load the breakdown",
'table.filters.allTypes': 'All types',
diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.ts
index 37ce8d45593..8acd42797a4 100644
--- a/src/services/chat/chat.test.ts
+++ b/src/services/chat/chat.test.ts
@@ -1,6 +1,6 @@
import { AgentBuilderIdentifier } from '@lobechat/builtin-tool-agent-builder';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
-import { REQUEST_TRIGGER_HEADER } from '@lobechat/const';
+import { REQUEST_OPERATION_ID_HEADER, REQUEST_TRIGGER_HEADER } from '@lobechat/const';
import { createMediaFileRef } from '@lobechat/const/mediaRef';
import type { ChatStreamPayload, LobeTool, UIChatMessage } from '@lobechat/types';
import { ChatErrorType, RequestTrigger } from '@lobechat/types';
@@ -1803,7 +1803,11 @@ describe('ChatService', () => {
request({ channel: 'llmcall:user-1:abcdefgh', headers: {} }),
);
const relayedError = {
- error: { message: "model 'gpt-oss:20b' not found", name: 'ResponseError', status_code: 404 },
+ error: {
+ message: "model 'gpt-oss:20b' not found",
+ name: 'ResponseError',
+ status_code: 404,
+ },
errorType: 'OllamaBizError',
provider: 'ollama',
};
@@ -1871,24 +1875,17 @@ describe('ChatService', () => {
);
});
- it('should send request trigger as a header without adding it to the model payload', async () => {
- const params: Partial<ChatStreamPayload> = {
- messages: [],
- model: 'test-model',
- };
+ it('should send request trigger and operation id as headers, not in the model payload', async () => {
+ const params: Partial<ChatStreamPayload> = { messages: [], model: 'test-model' };
await chatService.getChatCompletion(params, {
metadata: { trigger: RequestTrigger.MultimodalAnalysis },
+ operationId: 'op_client_1',
});
- expect(mockFetchSSE).toHaveBeenCalledWith(
- expect.any(String),
- expect.objectContaining({
- headers: expect.objectContaining({
- [REQUEST_TRIGGER_HEADER]: RequestTrigger.MultimodalAnalysis,
- }),
- }),
- );
+ const { headers } = mockFetchSSE.mock.calls[0][1];
+ expect(headers[REQUEST_OPERATION_ID_HEADER]).toBe('op_client_1');
+ expect(headers[REQUEST_TRIGGER_HEADER]).toBe(RequestTrigger.MultimodalAnalysis);
const payload = JSON.parse(mockFetchSSE.mock.calls[0][1].body);
expect(payload).not.toHaveProperty('requestTrigger');
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index e1ac46afada..870466c79f9 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -1,6 +1,7 @@
import { stripAssistantReasoningForReplay } from '@lobechat/agent-runtime';
import {
REQUEST_AGENT_ID_HEADER,
+ REQUEST_OPERATION_ID_HEADER,
REQUEST_TOPIC_ID_HEADER,
REQUEST_TRIGGER_HEADER,
} from '@lobechat/const';
@@ -310,7 +311,7 @@ class ChatService {
mapChatTrace = (trace?: TracePayload): TracePayload => this.mapTrace(trace, TraceTagMap.Chat);
getChatCompletion = async (params: Partial<ChatStreamPayload>, options?: FetchOptions) => {
- const { agentId, metadata, signal, responseAnimation, topicId } = options ?? {};
+ const { agentId, metadata, operationId, signal, responseAnimation, topicId } = options ?? {};
const requestTrigger = metadata?.trigger;
const { provider = ModelProvider.OpenAI, ...res } = params;
@@ -421,6 +422,7 @@ class ChatService {
...(agentId && { [REQUEST_AGENT_ID_HEADER]: agentId }),
...(requestTrigger && { [REQUEST_TRIGGER_HEADER]: requestTrigger }),
...(topicId && { [REQUEST_TOPIC_ID_HEADER]: topicId }),
+ ...(operationId && { [REQUEST_OPERATION_ID_HEADER]: operationId }),
},
provider,
});
diff --git a/src/services/chat/types.ts b/src/services/chat/types.ts
index 67a495f6275..b4437a45df1 100644
--- a/src/services/chat/types.ts
+++ b/src/services/chat/types.ts
@@ -16,6 +16,8 @@ export interface FetchOptions extends FetchSSEOptions {
/** Initial context for page editor (captured at operation start) */
initialContext?: RuntimeInitialContext;
metadata?: ChatRequestMetadata;
+ /** The agent operation this call runs in; sent so the call's usage groups with its run. */
+ operationId?: string;
signal?: AbortSignal | undefined;
/** Step context for page editor (updated each step) */
stepContext?: RuntimeStepContext;
diff --git a/src/store/chat/agents/transports/ClientLLMTransport.test.ts b/src/store/chat/agents/transports/ClientLLMTransport.test.ts
index bb83badcbf6..c86a7faca78 100644
--- a/src/store/chat/agents/transports/ClientLLMTransport.test.ts
+++ b/src/store/chat/agents/transports/ClientLLMTransport.test.ts
@@ -120,10 +120,21 @@ describe('ClientLLMTransport.stream · conversation affinity', () => {
expect(chatService.getChatCompletion).toHaveBeenCalledTimes(2);
for (const [, options] of vi.mocked(chatService.getChatCompletion).mock.calls) {
expect(options?.topicId).toBe('topic-1');
+ // The summary's usage groups with the run that compressed its context.
+ expect(options?.operationId).toBe('op-1');
}
});
});
+describe('ClientLLMTransport.runAttempt · usage attribution', () => {
+ it('sends the run operation id so the call usage groups with its run', async () => {
+ vi.mocked(chatService.getChatCompletion).mockClear();
+ await createTransport().transport.runAttempt(input);
+
+ expect(vi.mocked(chatService.getChatCompletion).mock.calls[0][1]?.operationId).toBe('op-1');
+ });
+});
+
describe('ClientLLMTransport.runAttempt · empty-completion grounding guard', () => {
beforeEach(() => {
finishGrounding = grounding;
diff --git a/src/store/chat/agents/transports/ClientLLMTransport.ts b/src/store/chat/agents/transports/ClientLLMTransport.ts
index 67b1494f485..eb9464a642c 100644
--- a/src/store/chat/agents/transports/ClientLLMTransport.ts
+++ b/src/store/chat/agents/transports/ClientLLMTransport.ts
@@ -310,6 +310,7 @@ export class ClientLLMTransport implements LLMTransport {
{
...modelParameters.options,
metadata: this.context.metadata,
+ operationId: this.context.operationId,
onErrorHandle: (error) => {
streamError = createStreamExecutionError(error);
},
@@ -401,6 +402,8 @@ export class ClientLLMTransport implements LLMTransport {
let streamError: unknown;
await chatService.getChatCompletion(payload as any, {
+ // Context-compression summaries bill under the run that triggered them.
+ operationId: this.context.operationId,
onErrorHandle: (error) => {
streamError = createStreamExecutionError(error);
handlers?.onError?.(streamError);