π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(model-runtime): preserve LLM finishReason through callbacks transformer (#14336)
Arvin Xu156a870cf309
diff --git a/packages/model-runtime/src/core/streams/protocol.test.ts b/packages/model-runtime/src/core/streams/protocol.test.tsindex 0ce1f208ef5..2865217eefa 100644--- a/packages/model-runtime/src/core/streams/protocol.test.ts+++ b/packages/model-runtime/src/core/streams/protocol.test.ts@@ -592,6 +592,78 @@ describe('createCallbacksTransformer', () => {expect(onFinal).toHaveBeenCalledWith(expectedData);});+ it('should capture finishReason from stop chunks and include in final data', async () => {+ const onCompletion = vi.fn();+ const onFinal = vi.fn();+ const transformer = createCallbacksTransformer({ onCompletion, onFinal });++ // Simulates the Gemini "soft interrupt" path: empty content + non-STOP finishReason+ // (e.g. RECITATION / MAX_TOKENS) β we MUST capture the reason so downstream+ // tracing/UI can surface it instead of silently rendering empty.+ const chunks = [+ 'event: stop\n',+ `data: ${JSON.stringify('RECITATION')}\n\n`,+ 'event: usage\n',+ `data: ${JSON.stringify({ totalTokens: 10 })}\n\n`,+ ];++ await processChunks(transformer, chunks);++ expect(onCompletion).toHaveBeenCalledWith(+ expect.objectContaining({ finishReason: 'RECITATION' }),+ );+ expect(onFinal).toHaveBeenCalledWith(expect.objectContaining({ finishReason: 'RECITATION' }));+ });++ it('should keep the first finishReason when multiple stop chunks are emitted', async () => {+ // Anthropic emits message_delta (carrying real stop_reason) followed by a+ // message_stop sentinel β the meaningful reason must not be clobbered.+ const onCompletion = vi.fn();+ const transformer = createCallbacksTransformer({ onCompletion });++ const chunks = [+ 'event: stop\n',+ `data: ${JSON.stringify('max_tokens')}\n\n`,+ 'event: stop\n',+ `data: ${JSON.stringify('message_stop')}\n\n`,+ ];++ await processChunks(transformer, chunks);++ expect(onCompletion).toHaveBeenCalledWith(+ expect.objectContaining({ finishReason: 'max_tokens' }),+ );+ });++ it('should fall back to a later stop chunk when the first one is empty', async () => {+ const onCompletion = vi.fn();+ const transformer = createCallbacksTransformer({ onCompletion });++ const chunks = [+ 'event: stop\n',+ `data: ${JSON.stringify('')}\n\n`,+ 'event: stop\n',+ `data: ${JSON.stringify('end_turn')}\n\n`,+ ];++ await processChunks(transformer, chunks);++ expect(onCompletion).toHaveBeenCalledWith(+ expect.objectContaining({ finishReason: 'end_turn' }),+ );+ });++ it('should leave finishReason undefined when no stop chunk is received', async () => {+ const onFinal = vi.fn();+ const transformer = createCallbacksTransformer({ onFinal });++ const chunks = ['event: text\n', 'data: "Hi"\n\n'];++ await processChunks(transformer, chunks);++ expect(onFinal).toHaveBeenCalledWith(expect.objectContaining({ finishReason: undefined }));+ });+it('should handle speed chunks and include in final data', async () => {const onFinal = vi.fn();const transformer = createCallbacksTransformer({ onFinal });diff --git a/packages/model-runtime/src/core/streams/protocol.ts b/packages/model-runtime/src/core/streams/protocol.tsindex 8b8ed328163..e52998a55d0 100644--- a/packages/model-runtime/src/core/streams/protocol.ts+++ b/packages/model-runtime/src/core/streams/protocol.ts@@ -268,6 +268,7 @@ export function createCallbacksTransformer(cb: ChatStreamCallbacks | undefined)let grounding: any;let toolsCalling: any;let streamError: any;+ let finishReason: string | undefined;// Track base64 images for accumulationconst base64Images: Array<{ data: string; id: string }> = [];@@ -278,6 +279,7 @@ export function createCallbacksTransformer(cb: ChatStreamCallbacks | undefined)async flush(): Promise<void> {const data = {error: streamError,+ finishReason,grounding,speed,text: aggregatedText,@@ -391,6 +393,22 @@ export function createCallbacksTransformer(cb: ChatStreamCallbacks | undefined)break;}+ case 'stop': {+ // Provider's terminal finishReason (e.g. Google's RECITATION / MAX_TOKENS,+ // OpenAI's length, Anthropic's end_turn). Capture so downstream consumers+ // can detect soft interrupts where content is empty but tokens were billed.+ //+ // Some providers emit multiple stop chunks per stream β Anthropic sends+ // `message_delta` (carrying the real `stop_reason` like `end_turn` /+ // `max_tokens` / `tool_use`) followed by a `message_stop` sentinel.+ // Keep the FIRST non-empty value so the meaningful reason is not+ // clobbered by the trailing sentinel.+ if (typeof data === 'string' && data && !finishReason) {+ finishReason = data;+ }+ break;+ }+case 'error': {streamError = data;await callbacks.onError?.(data);diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.tsindex ca172bd2ae7..c6fc7567988 100644--- a/packages/model-runtime/src/types/chat.ts+++ b/packages/model-runtime/src/types/chat.ts@@ -225,6 +225,13 @@ export interface ChatCompletionTool {export interface OnFinishData {error?: any;+ /**+ * The terminal finishReason emitted by the provider in the `stop` SSE chunk+ * (e.g. Google: STOP / SAFETY / RECITATION / MAX_TOKENS; OpenAI: stop / length;+ * Anthropic: end_turn / max_tokens / tool_use). Used to detect "soft interrupts"+ * where the provider returns empty content with a non-normal finishReason.+ */+ finishReason?: string;grounding?: any;speed?: ModelPerformance;text: string;diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex 5929f349fd9..3877aba6efe 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -690,6 +690,7 @@ export const createRuntimeExecutors = (const imageList: any[] = [];let grounding: any = null;let currentStepUsage: any = undefined;+ let currentStepFinishReason: string | undefined = undefined;let streamError: any = undefined;const contentParts: ContentPart[] = [];const reasoningParts: ContentPart[] = [];@@ -731,6 +732,12 @@ export const createRuntimeExecutors = (if (data.usage) {currentStepUsage = data.usage;}+ // Capture provider's terminal finishReason so soft interrupts+ // (e.g. Gemini RECITATION / MAX_TOKENS with empty content)+ // are visible in tracing instead of being silently swallowed.+ if (data.finishReason) {+ currentStepFinishReason = data.finishReason;+ }},onGrounding: async (groundingData) => {log(`[${operationLogId}][grounding] %O`, groundingData);@@ -869,7 +876,13 @@ export const createRuntimeExecutors = (// Add a complete llm_stream event (including all streaming chunks)events.push({- result: { content, reasoning: thinkingContent, tool_calls, usage: currentStepUsage },+ result: {+ content,+ finishReason: currentStepFinishReason,+ reasoning: thinkingContent,+ tool_calls,+ usage: currentStepUsage,+ },type: 'llm_result',});