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: capture provider-native stream diagnostics (#19643)

YuTengjingb3f55110f031
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index f8cb33beb61..1d13f3af871 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -75,12 +75,14 @@ vi.mock('@/server/services/message', () => ({
// @lobechat/model-runtime resolves to @cloud/business-model-runtime which has
// cloud-specific dependencies that are unavailable in the test environment
vi.mock('@lobechat/model-runtime', async () => {
- // ModelEmptyError + isEmptyModelCompletion are pure (they only depend on
+ // Completion errors + isEmptyModelCompletion are pure (they only depend on
// @lobechat/types), so import the real implementations directly from source —
// bypassing this cloud-package mock — so the executor's empty-completion
// retry path and these tests share a single class identity for instanceof.
const { isEmptyModelCompletion, ModelEmptyError } =
await import('../../../../../../packages/model-runtime/src/errors/modelEmptyCompletion');
+ const { ModelRefusalError } =
+ await import('../../../../../../packages/model-runtime/src/errors/modelRefusal');
// Same treatment: the reasoning-config merge is pure, and the replay gate
// reads its output (e.g. the DeepSeek V4 thinking opt-out), so use the real
// implementation instead of a drifting stub.
@@ -109,6 +111,7 @@ vi.mock('@lobechat/model-runtime', async () => {
isKimiAlwaysPreserveThinkingModel: (model: string) =>
/^kimi-k2\.(?:[7-9]|\d{2,})-code(?:$|-)/.test(model),
ModelEmptyError,
+ ModelRefusalError,
refineErrorCode: () => undefined,
};
});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts
index 5c334b2193b..541d220ef5d 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts
@@ -246,8 +246,15 @@ describe('ServerCallLlmAttempt', () => {
expect(metadata.userAgent).toBeUndefined();
});
- it('keeps partial output and usage readable after a stream error', async () => {
- const { attempt } = createAttempt(async ({ callback }) => {
+ it('records provider evidence while keeping partial output readable after a stream error', async () => {
+ const providerEvidence = {
+ providerResponse: {
+ apiMode: 'google_generate_content',
+ rawEvents: [{ candidates: [], responseId: 'response-1' }],
+ },
+ };
+ const { attempt } = createAttempt(async ({ callback, diagnostics }) => {
+ Object.assign(diagnostics!, providerEvidence);
await callback?.onText?.('Partial answer');
await callback?.onCompletion?.({
text: '',
@@ -273,6 +280,45 @@ describe('ServerCallLlmAttempt', () => {
usage: { totalOutputTokens: 3 },
}),
);
+ expect(recordModelCompletionFailureMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ reason: 'stream_error',
+ response: expect.objectContaining({
+ streamError: {
+ errorType: 'ProviderBizError',
+ message: 'provider stream failed',
+ status: 503,
+ },
+ }),
+ runtime: expect.objectContaining({ provider: providerEvidence }),
+ }),
+ );
+ });
+
+ it('records a provider error raised before any response event', async () => {
+ const { attempt } = createAttempt(async () => {
+ throw new Error('upstream request failed');
+ });
+
+ await expect(attempt.execute()).rejects.toThrow('upstream request failed');
+ expect(recordModelCompletionFailureMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ reason: 'provider_error',
+ response: expect.objectContaining({
+ error: { message: 'upstream request failed', name: 'Error' },
+ }),
+ }),
+ );
+ });
+
+ it('does not record an aborted provider request as a failure', async () => {
+ const { attempt } = createAttempt(async ({ diagnostics }) => {
+ Object.assign(diagnostics!, { providerResponse: { aborted: true } });
+ throw new Error('Request aborted');
+ });
+
+ await expect(attempt.execute()).rejects.toThrow('Request aborted');
+ expect(recordModelCompletionFailureMock).not.toHaveBeenCalled();
});
it('salvages a natural-stop answer emitted only in reasoning', async () => {
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
index ff496052408..79392e0d947 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts
@@ -209,6 +209,27 @@ export class ServerCallLlmAttempt {
}
async execute(): Promise<void> {
+ try {
+ await this.executeModelCall();
+ } catch (error) {
+ const isAlreadyRecorded =
+ error instanceof ModelEmptyError || error instanceof ModelRefusalError;
+ const isAborted = this.runtimeDiagnostics.providerResponse?.aborted;
+ if (!isAlreadyRecorded && !isAborted && !(await isOperationInterrupted(this.ctx))) {
+ const receivedProviderOutput =
+ this.streamError !== undefined ||
+ this.runtimeDiagnostics.providerResponse?.firstEventAt !== undefined;
+ await this.recordCompletionFailure(
+ receivedProviderOutput ? 'stream_error' : 'provider_error',
+ error,
+ );
+ }
+
+ throw error;
+ }
+ }
+
+ private async executeModelCall(): Promise<void> {
log(
'[%s][call_llm] calling model-runtime chat (attempt %d/%d, model: %s, messages: %d, tools: %d)',
this.operationLogId,
@@ -422,7 +443,7 @@ export class ServerCallLlmAttempt {
return this.imageList.length + contentPartImageCount;
}
- private async recordCompletionFailure(reason: ModelCompletionFailureReason) {
+ private async recordCompletionFailure(reason: ModelCompletionFailureReason, error?: unknown) {
try {
const providerEvidence =
this.runtimeDiagnostics.providerRequest || this.runtimeDiagnostics.providerResponse
@@ -447,8 +468,17 @@ export class ServerCallLlmAttempt {
base64ImageEvents: [...this.base64ImageEvents],
completion: this.completion,
contentPartEvents: [...this.contentPartEvents],
+ ...(error === undefined
+ ? {}
+ : {
+ error:
+ error instanceof Error
+ ? { message: error.message.slice(0, 500), name: error.name }
+ : { message: String(error).slice(0, 500) },
+ }),
output: this.snapshot(),
reasoningPartEvents: [...this.reasoningPartEvents],
+ ...(this.streamError === undefined ? {} : { streamError: this.streamError }),
},
...(runtimeEvidence ? { runtime: runtimeEvidence } : {}),
stepIndex: this.ctx.stepIndex,
diff --git a/packages/business-server/src/recordModelCompletionFailure.ts b/packages/business-server/src/recordModelCompletionFailure.ts
index 896602ac6ea..ae7bf023e71 100644
--- a/packages/business-server/src/recordModelCompletionFailure.ts
+++ b/packages/business-server/src/recordModelCompletionFailure.ts
@@ -1,4 +1,5 @@
-export type ModelCompletionFailureReason = 'empty_completion' | 'refusal';
+export type ModelCompletionFailureReason =
+ 'empty_completion' | 'provider_error' | 'refusal' | 'stream_error';
export interface ModelCompletionFailureRuntimeEvidence {
provider?: unknown;
diff --git a/packages/model-runtime/src/core/providerDiagnostics.ts b/packages/model-runtime/src/core/providerDiagnostics.ts
index ffa1bb51290..04bc8cd7278 100644
--- a/packages/model-runtime/src/core/providerDiagnostics.ts
+++ b/packages/model-runtime/src/core/providerDiagnostics.ts
@@ -1,6 +1,11 @@
-import type { ProviderResponseDiagnostics } from '../types/providerDiagnostics';
+import type {
+ ModelRuntimeDiagnostics,
+ ProviderResponseDiagnostics,
+ ProviderResponseEventDiagnostics,
+} from '../types/providerDiagnostics';
const MAX_RECORDED_ERROR_MESSAGE_LENGTH = 500;
+const MAX_RECORDED_PROVIDER_EVENTS = 128;
const MAX_RECORDED_RAW_EVENT_BYTES = 256 * 1024;
const MAX_RECORDED_RAW_EVENTS = 128;
const MAX_RECORDED_RAW_RESPONSE_BYTES = 256 * 1024;
@@ -46,12 +51,14 @@ export const appendRawProviderEvent = (
diagnostics: ProviderResponseDiagnostics,
event: unknown,
) => {
+ if (diagnostics.rawEvents.length >= MAX_RECORDED_RAW_EVENTS) {
+ diagnostics.droppedRawEventCount = (diagnostics.droppedRawEventCount ?? 0) + 1;
+ return;
+ }
+
const serializedEvent = serializeProviderEvent(event);
const recordedByteLength = diagnostics.rawEventByteLength ?? 0;
- if (
- diagnostics.rawEvents.length >= MAX_RECORDED_RAW_EVENTS ||
- recordedByteLength + serializedEvent.byteLength > MAX_RECORDED_RAW_EVENT_BYTES
- ) {
+ if (recordedByteLength + serializedEvent.byteLength > MAX_RECORDED_RAW_EVENT_BYTES) {
diagnostics.droppedRawEventCount = (diagnostics.droppedRawEventCount ?? 0) + 1;
return;
}
@@ -60,6 +67,192 @@ export const appendRawProviderEvent = (
diagnostics.rawEventByteLength = recordedByteLength + serializedEvent.byteLength;
};
+interface InitializeProviderDiagnosticsParams {
+ apiMode: string;
+ diagnostics?: ModelRuntimeDiagnostics;
+ endpoint?: string;
+ payload: unknown;
+ sentAt: number;
+}
+
+/** Initialize the shared diagnostic envelope used by custom provider adapters. */
+export const initializeProviderDiagnostics = ({
+ apiMode,
+ diagnostics,
+ endpoint,
+ payload,
+ sentAt,
+}: InitializeProviderDiagnosticsParams): ProviderResponseDiagnostics | undefined => {
+ if (!diagnostics) return;
+
+ const providerResponse: ProviderResponseDiagnostics = {
+ apiMode,
+ droppedEventCount: 0,
+ endpoint,
+ eventCount: 0,
+ eventCounts: {},
+ events: [],
+ hasNonWhitespaceText: false,
+ hasNonWhitespaceThinking: false,
+ rawEvents: [],
+ rawResponse: { status: 'unavailable' },
+ signatureChars: 0,
+ terminalEventReceived: false,
+ textChars: 0,
+ thinkingChars: 0,
+ toolInputChars: 0,
+ toolUseCount: 0,
+ };
+ diagnostics.providerRequest = { apiMode, endpoint, payload, sentAt };
+ diagnostics.providerResponse = providerResponse;
+
+ return providerResponse;
+};
+
+export const appendProviderResponseEvent = (
+ diagnostics: ProviderResponseDiagnostics,
+ event: Omit<ProviderResponseEventDiagnostics, 'index'>,
+) => {
+ const indexedEvent = { ...event, index: diagnostics.eventCount };
+ diagnostics.eventCount += 1;
+
+ const eventKey = [event.type, event.blockType, event.deltaType].filter(Boolean).join(':');
+ diagnostics.eventCounts[eventKey] = (diagnostics.eventCounts[eventKey] ?? 0) + 1;
+
+ if (diagnostics.events.length >= MAX_RECORDED_PROVIDER_EVENTS) {
+ diagnostics.events.shift();
+ diagnostics.droppedEventCount += 1;
+ }
+ diagnostics.events.push(indexedEvent);
+};
+
+export const recordProviderStringContent = (
+ diagnostics: ProviderResponseDiagnostics,
+ event: Omit<ProviderResponseEventDiagnostics, 'index'>,
+ content: string,
+ kind: 'signature' | 'text' | 'thinking' | 'toolInput',
+) => {
+ const hasNonWhitespaceContent = content.trim().length > 0;
+ event.contentLength = (event.contentLength ?? 0) + content.length;
+ event.hasNonWhitespaceContent ||= hasNonWhitespaceContent;
+
+ if (kind === 'text') {
+ diagnostics.textChars += content.length;
+ diagnostics.hasNonWhitespaceText ||= hasNonWhitespaceContent;
+ }
+ if (kind === 'thinking') {
+ diagnostics.thinkingChars += content.length;
+ diagnostics.hasNonWhitespaceThinking ||= hasNonWhitespaceContent;
+ }
+ if (kind === 'signature') {
+ diagnostics.signatureChars += content.length;
+ event.signatureLength = (event.signatureLength ?? 0) + content.length;
+ }
+ if (kind === 'toolInput') diagnostics.toolInputChars += content.length;
+
+ if (hasNonWhitespaceContent && diagnostics.firstNonWhitespaceOutputAt === undefined) {
+ diagnostics.firstNonWhitespaceOutputAt = Date.now();
+ }
+};
+
+export const recordProviderError = (
+ diagnostics: ProviderResponseDiagnostics | undefined,
+ error: unknown,
+) => {
+ if (!diagnostics) return;
+
+ diagnostics.error = {
+ message:
+ error instanceof Error
+ ? error.message.slice(0, MAX_RECORDED_ERROR_MESSAGE_LENGTH)
+ : String(error).slice(0, MAX_RECORDED_ERROR_MESSAGE_LENGTH),
+ name: error instanceof Error ? error.name : undefined,
+ };
+};
+
+export const finalizeProviderResponse = async (
+ diagnostics: ProviderResponseDiagnostics | undefined,
+ signal?: AbortSignal,
+) => {
+ if (!diagnostics) return;
+
+ await waitForRawProviderResponse(diagnostics);
+ diagnostics.aborted = signal?.aborted || undefined;
+ diagnostics.completedAt ??= Date.now();
+};
+
+export const observeProviderAsyncIterable = async function* <T>(
+ stream: AsyncIterable<T>,
+ diagnostics: ProviderResponseDiagnostics | undefined,
+ recordEvent: (diagnostics: ProviderResponseDiagnostics, event: T) => void,
+ signal?: AbortSignal,
+) {
+ if (!diagnostics) {
+ yield* stream;
+ return;
+ }
+
+ try {
+ for await (const chunk of stream) {
+ recordEvent(diagnostics, chunk);
+ yield chunk;
+ }
+ } catch (error) {
+ recordProviderError(diagnostics, error);
+ throw error;
+ } finally {
+ await finalizeProviderResponse(diagnostics, signal);
+ }
+};
+
+/** Observe a Web stream without teeing or reading ahead of its consumer. */
+export const observeProviderReadableStream = <T>(
+ stream: ReadableStream<T>,
+ diagnostics: ProviderResponseDiagnostics | undefined,
+ recordEvent: (diagnostics: ProviderResponseDiagnostics, event: T) => void,
+ signal?: AbortSignal,
+): ReadableStream<T> => {
+ if (!diagnostics) return stream;
+
+ const reader = stream.getReader();
+ let finalized = false;
+ const finalize = async () => {
+ if (finalized) return;
+ finalized = true;
+ await finalizeProviderResponse(diagnostics, signal);
+ };
+
+ return new ReadableStream<T>(
+ {
+ async cancel(reason) {
+ try {
+ await reader.cancel(reason);
+ } finally {
+ await finalize();
+ }
+ },
+ async pull(controller) {
+ try {
+ const { done, value } = await reader.read();
+ if (done) {
+ await finalize();
+ controller.close();
+ return;
+ }
+
+ recordEvent(diagnostics, value);
+ controller.enqueue(value);
+ } catch (error) {
+ recordProviderError(diagnostics, error);
+ await finalize();
+ controller.error(error);
+ }
+ },
+ },
+ { highWaterMark: 0 },
+ );
+};
+
/** Read only a bounded prefix so diagnostic capture cannot buffer an unbounded clone. */
const readRawResponseBody = async (response: Response) => {
const reader = response.body!.getReader();
diff --git a/packages/model-runtime/src/providers/azureai/index.test.ts b/packages/model-runtime/src/providers/azureai/index.test.ts
index 24537e4898b..b445f6d6228 100644
--- a/packages/model-runtime/src/providers/azureai/index.test.ts
+++ b/packages/model-runtime/src/providers/azureai/index.test.ts
@@ -2,6 +2,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentRuntimeErrorType } from '../../types/error';
+import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';
import { LobeAzureAI } from './index';
describe('LobeAzureAI', () => {
@@ -64,15 +65,25 @@ describe('LobeAzureAI', () => {
post: mockPost,
} as any);
- const result = await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: 'gpt-4',
- stream: false,
- });
+ const diagnostics: ModelRuntimeDiagnostics = {};
+ const result = await instance.chat(
+ {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gpt-4',
+ stream: false,
+ },
+ { diagnostics },
+ );
expect(result).toBeDefined();
expect(instance.client.path).toHaveBeenCalledWith('/chat/completions');
expect(mockPost).toHaveBeenCalled();
+ expect(diagnostics.providerResponse).toMatchObject({
+ apiMode: 'azure_ai_chat_completions',
+ eventCount: 1,
+ rawEvents: [mockResponse],
+ terminalEventReceived: true,
+ });
});
it('should handle generic errors', async () => {
diff --git a/packages/model-runtime/src/providers/azureai/index.ts b/packages/model-runtime/src/providers/azureai/index.ts
index cd46e834e05..f598da051bf 100644
--- a/packages/model-runtime/src/providers/azureai/index.ts
+++ b/packages/model-runtime/src/providers/azureai/index.ts
@@ -8,6 +8,14 @@ import type OpenAI from 'openai';
import type { LobeRuntimeAI } from '../../core/BaseAI';
import { transformResponseToStream } from '../../core/openaiCompatibleFactory';
+import {
+ appendProviderResponseEvent,
+ appendRawProviderEvent,
+ finalizeProviderResponse,
+ initializeProviderDiagnostics,
+ observeProviderReadableStream,
+ recordProviderError,
+} from '../../core/providerDiagnostics';
import { createSSEDataExtractor, OpenAIStream } from '../../core/streams';
import type { ChatMethodOptions, ChatStreamPayload } from '../../types';
import { AgentRuntimeErrorType } from '../../types/error';
@@ -16,6 +24,7 @@ import { debugStream } from '../../utils/debugStream';
import { StreamingResponse } from '../../utils/response';
import { sanitizeError } from '../../utils/sanitizeError';
import { systemToUserModels } from '../openai/modelId';
+import { createAzureAIStreamChunkRecorder } from './providerDiagnostics';
interface AzureAIParams {
apiKey?: string;
@@ -62,18 +71,26 @@ export class LobeAzureAI implements LobeRuntimeAI {
: 'developer'
: message.role,
}));
+ const requestBody = {
+ messages: updatedMessages as OpenAI.ChatCompletionMessageParam[],
+ model,
+ ...params,
+ stream: enableStreaming,
+ temperature: model.includes('o3') || model.includes('o4') ? undefined : temperature,
+ tool_choice: params.tools ? 'auto' : undefined,
+ top_p: model.includes('o3') || model.includes('o4') ? undefined : top_p,
+ };
+ const providerResponseDiagnostics = initializeProviderDiagnostics({
+ apiMode: 'azure_ai_chat_completions',
+ diagnostics: options?.diagnostics,
+ endpoint: this.maskSensitiveUrl(this.baseURL),
+ payload: requestBody,
+ sentAt: Date.now(),
+ });
try {
const response = this.client.path('/chat/completions').post({
- body: {
- messages: updatedMessages as OpenAI.ChatCompletionMessageParam[],
- model,
- ...params,
- stream: enableStreaming,
- temperature: model.includes('o3') || model.includes('o4') ? undefined : temperature,
- tool_choice: params.tools ? 'auto' : undefined,
- top_p: model.includes('o3') || model.includes('o4') ? undefined : top_p,
- },
+ body: requestBody,
});
if (enableStreaming) {
@@ -110,9 +127,17 @@ export class LobeAzureAI implements LobeRuntimeAI {
return browserStream;
})();
- const [prod, debug] = unifiedStream.tee();
+ const observedStream = observeProviderReadableStream(
+ unifiedStream,
+ providerResponseDiagnostics,
+ createAzureAIStreamChunkRecorder(),
+ options?.signal,
+ );
+ let prod = observedStream;
if (process.env.DEBUG_AZURE_AI_CHAT_COMPLETION === '1') {
+ const [productionStream, debug] = observedStream.tee();
+ prod = productionStream;
debugStream(debug).catch(console.error);
}
@@ -126,6 +151,16 @@ export class LobeAzureAI implements LobeRuntimeAI {
);
} else {
const res = await response;
+ if (providerResponseDiagnostics) {
+ appendRawProviderEvent(providerResponseDiagnostics, res.body);
+ providerResponseDiagnostics.firstEventAt ??= Date.now();
+ providerResponseDiagnostics.responseReceivedAt ??= Date.now();
+ providerResponseDiagnostics.terminalEventReceived = true;
+ appendProviderResponseEvent(providerResponseDiagnostics, {
+ type: 'azure_ai_chat_completion',
+ });
+ await finalizeProviderResponse(providerResponseDiagnostics, options?.signal);
+ }
// the azure AI inference response is openai compatible
const stream = transformResponseToStream(res.body as OpenAI.ChatCompletion);
@@ -137,6 +172,8 @@ export class LobeAzureAI implements LobeRuntimeAI {
);
}
} catch (e) {
+ recordProviderError(providerResponseDiagnostics, e);
+ await finalizeProviderResponse(providerResponseDiagnostics, options?.signal);
let error = e as { [key: string]: any; code: string; message: string };
if (error.code) {
diff --git a/packages/model-runtime/src/providers/azureai/providerDiagnostics.test.ts b/packages/model-runtime/src/providers/azureai/providerDiagnostics.test.ts
new file mode 100644
index 00000000000..28e4b09d6f1
--- /dev/null
+++ b/packages/model-runtime/src/providers/azureai/providerDiagnostics.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ProviderResponseDiagnostics } from '../../types/providerDiagnostics';
+import { createAzureAIStreamChunkRecorder } from './providerDiagnostics';
+
+describe('createAzureAIStreamChunkRecorder', () => {
+ it('retains raw SSE bytes before the OpenAI protocol transformer', () => {
+ const diagnostics: ProviderResponseDiagnostics = {
+ apiMode: 'azure_ai_chat_completions',
+ droppedEventCount: 0,
+ eventCount: 0,
+ eventCounts: {},
+ events: [],
+ hasNonWhitespaceText: false,
+ hasNonWhitespaceThinking: false,
+ rawEvents: [],
+ signatureChars: 0,
+ terminalEventReceived: false,
+ textChars: 0,
+ thinkingChars: 0,
+ toolInputChars: 0,
+ toolUseCount: 0,
+ };
+ const record = createAzureAIStreamChunkRecorder();
+
+ record(diagnostics, new TextEncoder().encode('data: {"choices":[]}\n\n'));
+
+ expect(diagnostics.rawEvents).toEqual(['data: {"choices":[]}\n\n']);
+ expect(diagnostics.eventCounts).toEqual({ azure_ai_sse_chunk: 1 });
+ });
+});
diff --git a/packages/model-runtime/src/providers/azureai/providerDiagnostics.ts b/packages/model-runtime/src/providers/azureai/providerDiagnostics.ts
new file mode 100644
index 00000000000..5b587e12a7a
--- /dev/null
+++ b/packages/model-runtime/src/providers/azureai/providerDiagnostics.ts
@@ -0,0 +1,21 @@
+import {
+ appendProviderResponseEvent,
+ appendRawProviderEvent,
+} from '../../core/providerDiagnostics';
+import type { ProviderResponseDiagnostics } from '../../types/providerDiagnostics';
+
+export const createAzureAIStreamChunkRecorder = () => {
+ const decoder = new TextDecoder();
+
+ return (diagnostics: ProviderResponseDiagnostics, chunk: unknown) => {
+ const rawChunk = chunk instanceof Uint8Array ? decoder.decode(chunk, { stream: true }) : chunk;
+ appendRawProviderEvent(diagnostics, rawChunk);
+ diagnostics.firstEventAt ??= Date.now();
+ diagnostics.responseReceivedAt ??= Date.now();
+ appendProviderResponseEvent(diagnostics, {
+ contentLength:
+ typeof rawChunk === 'string' ? rawChunk.length : JSON.stringify(rawChunk).length,
+ type: 'azure_ai_sse_chunk',
+ });
+ };
+};
diff --git a/packages/model-runtime/src/providers/bedrock/index.test.ts b/packages/model-runtime/src/providers/bedrock/index.test.ts
index 2a3bdf2f8fe..4b18a61c61a 100644
--- a/packages/model-runtime/src/providers/bedrock/index.test.ts
+++ b/packages/model-runtime/src/providers/bedrock/index.test.ts
@@ -8,6 +8,7 @@ import type { Mock } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentRuntimeErrorType } from '../../types/error';
+import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';
import * as debugStreamModule from '../../utils/debugStream';
import { experimental_buildLlama2Prompt, LobeBedrockAI } from './index';
@@ -169,6 +170,42 @@ describe('LobeBedrockAI', () => {
expect(result).toBeInstanceOf(Response);
});
+ it('captures decoded Bedrock events before protocol transformation', async () => {
+ const providerChunks = [
+ { generation: '', generation_token_count: 1 },
+ { generation: '', generation_token_count: 1, stop_reason: 'stop' },
+ ];
+ (instance['client'].send as Mock).mockResolvedValue({
+ $metadata: { httpStatusCode: 200, requestId: 'request-1' },
+ body: {
+ async *[Symbol.asyncIterator]() {
+ for (const chunk of providerChunks) {
+ yield { chunk: { bytes: new TextEncoder().encode(JSON.stringify(chunk)) } };
+ }
+ },
+ },
+ });
+ const diagnostics: ModelRuntimeDiagnostics = {};
+
+ const response = await instance.chat(
+ {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'meta.llama:1',
+ },
+ { diagnostics },
+ );
+ await response.text();
+
+ expect(diagnostics.providerResponse).toMatchObject({
+ apiMode: 'bedrock_llama',
+ rawEvents: providerChunks,
+ requestId: 'request-1',
+ status: 200,
+ stopReason: 'stop',
+ terminalEventReceived: true,
+ });
+ });
+
it('should handle text messages correctly', async () => {
// Arrange
const mockStream = new ReadableStream({
diff --git a/packages/model-runtime/src/providers/bedrock/index.ts b/packages/model-runtime/src/providers/bedrock/index.ts
index dd58f2b3667..da6ebd1ac9c 100644
--- a/packages/model-runtime/src/providers/bedrock/index.ts
+++ b/packages/model-runtime/src/providers/bedrock/index.ts
@@ -18,6 +18,12 @@ import { resolveClaudeThinkingConfig } from '../../core/anthropicCompatibleFacto
import type { LobeRuntimeAI } from '../../core/BaseAI';
import { buildAnthropicMessages, buildAnthropicTools } from '../../core/contextBuilders/anthropic';
import { resolveModelSamplingParameters } from '../../core/parameterResolver';
+import {
+ finalizeProviderResponse,
+ initializeProviderDiagnostics,
+ observeProviderReadableStream,
+ recordProviderError,
+} from '../../core/providerDiagnostics';
import {
AWSBedrockClaudeStream,
AWSBedrockLlamaStream,
@@ -34,6 +40,7 @@ import type {
GenerateObjectPayload,
} from '../../types';
import { AgentRuntimeErrorType } from '../../types/error';
+import type { ProviderResponseDiagnostics } from '../../types/providerDiagnostics';
import { AgentRuntimeError } from '../../utils/createError';
import { debugStream } from '../../utils/debugStream';
import { getModelPricing } from '../../utils/getModelPricing';
@@ -41,6 +48,7 @@ import { StreamingResponse } from '../../utils/response';
import { stripUnsupportedClaudeAssistantPrefill } from '../anthropic/claudePrefill';
import { normalizeClaudeThinkingHistoryMessages } from '../anthropic/claudeThinkingHistory';
import { rejectsDisabledThinkingAtEffort } from '../anthropic/modelId';
+import { recordBedrockResponseEvent } from './providerDiagnostics';
/**
* A prompt constructor for HuggingFace LLama 2 chat models.
@@ -369,16 +377,33 @@ export class LobeBedrockAI implements LobeRuntimeAI {
contentType: 'application/json',
modelId: this.resolveModelId(model),
});
+ const providerResponseDiagnostics = initializeProviderDiagnostics({
+ apiMode: 'bedrock_claude_messages',
+ diagnostics: options?.diagnostics,
+ endpoint: `bedrock:${this.region}`,
+ payload: anthropicPayload,
+ sentAt: Date.now(),
+ });
try {
// Ask Claude for a streaming chat completion given the prompt
const res = await this.client.send(command, { abortSignal: options?.signal });
- const claudeStream = createBedrockStream(res);
-
- const [prod, debug] = claudeStream.tee();
+ if (providerResponseDiagnostics) {
+ providerResponseDiagnostics.requestId = res.$metadata?.requestId;
+ providerResponseDiagnostics.status = res.$metadata?.httpStatusCode;
+ }
+ const claudeStream = observeProviderReadableStream(
+ createBedrockStream(res),
+ providerResponseDiagnostics,
+ recordBedrockResponseEvent,
+ options?.signal,
+ );
+ let prod = claudeStream;
if (process.env.DEBUG_BEDROCK_CHAT_COMPLETION === '1') {
+ const [productionStream, debug] = claudeStream.tee();
+ prod = productionStream;
debugStream(debug).catch(console.error);
}
@@ -399,6 +424,8 @@ export class LobeBedrockAI implements LobeRuntimeAI {
);
} catch (e) {
const err = e as Error & { $metadata: any };
+ recordProviderError(providerResponseDiagnostics, err);
+ await finalizeProviderResponse(providerResponseDiagnostics, options?.signal);
const errorType = ErrorClassifier.isExceededContextWindow(err.message)
? AgentRuntimeErrorType.ExceededContextWindow
: AgentRuntimeErrorType.ProviderBizError;
@@ -421,25 +448,44 @@ export class LobeBedrockAI implements LobeRuntimeAI {
options?: ChatMethodOptions,
): Promise<Response> => {
const { max_tokens, messages, model } = payload;
+ const llamaPayload = {
+ max_gen_len: max_tokens || 400,
+ prompt: experimental_buildLlama2Prompt(messages as any),
+ };
const command = new InvokeModelWithResponseStreamCommand({
accept: 'application/json',
- body: JSON.stringify({
- max_gen_len: max_tokens || 400,
- prompt: experimental_buildLlama2Prompt(messages as any),
- }),
+ body: JSON.stringify(llamaPayload),
contentType: 'application/json',
modelId: model,
});
+ const providerResponseDiagnostics: ProviderResponseDiagnostics | undefined =
+ initializeProviderDiagnostics({
+ apiMode: 'bedrock_llama',
+ diagnostics: options?.diagnostics,
+ endpoint: `bedrock:${this.region}`,
+ payload: llamaPayload,
+ sentAt: Date.now(),
+ });
try {
// Ask Claude for a streaming chat completion given the prompt
- const res = await this.client.send(command);
-
- const stream = createBedrockStream(res);
+ const res = await this.client.send(command, { abortSignal: options?.signal });
- const [prod, debug] = stream.tee();
+ if (providerResponseDiagnostics) {
+ providerResponseDiagnostics.requestId = res.$metadata?.requestId;
+ providerResponseDiagnostics.status = res.$metadata?.httpStatusCode;
+ }
+ const stream = observeProviderReadableStream(
+ createBedrockStream(res),
+ providerResponseDiagnostics,
+ recordBedrockResponseEvent,
+ options?.signal,
+ );
+ let prod = stream;
if (process.env.DEBUG_BEDROCK_CHAT_COMPLETION === '1') {
+ const [productionStream, debug] = stream.tee();
+ prod = productionStream;
debugStream(debug).catch(console.error);
}
// Respond with the stream
@@ -448,6 +494,8 @@ export class LobeBedrockAI implements LobeRuntimeAI {
});
} catch (e) {
const err = e as Error & { $metadata: any };
+ recordProviderError(providerResponseDiagnostics, err);
+ await finalizeProviderResponse(providerResponseDiagnostics, options?.signal);
throw AgentRuntimeError.chat({
error: {
diff --git a/packages/model-runtime/src/providers/bedrock/providerDiagnostics.test.ts b/packages/model-runtime/src/providers/bedrock/providerDiagnostics.test.ts
new file mode 100644
index 00000000000..602d636cdbb
--- /dev/null
+++ b/packages/model-runtime/src/providers/bedrock/providerDiagnostics.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ProviderResponseDiagnostics } from '../../types/providerDiagnostics';
+import { recordBedrockResponseEvent } from './providerDiagnostics';
+
+const createDiagnostics = (): ProviderResponseDiagnostics => ({
+ apiMode: 'bedrock_claude_messages',
+ droppedEventCount: 0,
+ eventCount: 0,
+ eventCounts: {},
+ events: [],
+ hasNonWhitespaceText: false,
+ hasNonWhitespaceThinking: false,
+ rawEvents: [],
+ signatureChars: 0,
+ terminalEventReceived: false,
+ textChars: 0,
+ thinkingChars: 0,
+ toolInputChars: 0,
+ toolUseCount: 0,
+});
+
+describe('recordBedrockResponseEvent', () => {
+ it('retains provider-native Claude chunks and terminal metadata', () => {
+ const diagnostics = createDiagnostics();
+ const chunks = [
+ {
+ message: { id: 'message-1', model: 'claude', usage: { input_tokens: 10 } },
+ type: 'message_start',
+ },
+ { delta: { text: '' }, type: 'content_block_delta' },
+ {
+ delta: { stop_reason: 'end_turn' },
+ type: 'message_delta',
+ usage: { output_tokens: 147 },
+ },
+ { type: 'message_stop' },
+ ];
+
+ for (const chunk of chunks) recordBedrockResponseEvent(diagnostics, chunk);
+
+ expect(diagnostics).toMatchObject({
+ eventCount: 4,
+ hasNonWhitespaceText: false,
+ messageId: 'message-1',
+ model: 'claude',
+ rawEvents: chunks,
+ stopReason: 'end_turn',
+ terminalEventReceived: true,
+ textChars: 0,
+ usage: { output_tokens: 147 },
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/bedrock/providerDiagnostics.ts b/packages/model-runtime/src/providers/bedrock/providerDiagnostics.ts
new file mode 100644
index 00000000000..7cb21c5ea54
--- /dev/null
+++ b/packages/model-runtime/src/providers/bedrock/providerDiagnostics.ts
@@ -0,0 +1,70 @@
+import { toRecord } from '@lobechat/utils/object';
+
+import {
+ appendProviderResponseEvent,
+ appendRawProviderEvent,
+ recordProviderStringContent,
+} from '../../core/providerDiagnostics';
+import type { ProviderResponseDiagnostics } from '../../types/providerDiagnostics';
+
+export const recordBedrockResponseEvent = (
+ diagnostics: ProviderResponseDiagnostics,
+ chunk: unknown,
+) => {
+ appendRawProviderEvent(diagnostics, chunk);
+ diagnostics.firstEventAt ??= Date.now();
+ diagnostics.responseReceivedAt ??= Date.now();
+
+ const raw = toRecord(chunk);
+ const type = typeof raw?.type === 'string' ? raw.type : 'bedrock_chunk';
+ const event = { type };
+
+ const message = toRecord(raw?.message);
+ if (message) {
+ if (typeof message.id === 'string') diagnostics.messageId ??= message.id;
+ if (typeof message.model === 'string') diagnostics.model ??= message.model;
+ if (message.usage !== undefined) diagnostics.usage = message.usage;
+ }
+
+ const contentBlock = toRecord(raw?.content_block);
+ if (contentBlock?.type === 'tool_use') {
+ diagnostics.toolUseCount += 1;
+ diagnostics.firstNonWhitespaceOutputAt ??= Date.now();
+ }
+ if (typeof contentBlock?.text === 'string') {
+ recordProviderStringContent(diagnostics, event, contentBlock.text, 'text');
+ }
+ if (typeof contentBlock?.thinking === 'string') {
+ recordProviderStringContent(diagnostics, event, contentBlock.thinking, 'thinking');
+ }
+
+ const delta = toRecord(raw?.delta);
+ if (typeof delta?.text === 'string') {
+ recordProviderStringContent(diagnostics, event, delta.text, 'text');
+ }
+ if (typeof delta?.thinking === 'string') {
+ recordProviderStringContent(diagnostics, event, delta.thinking, 'thinking');
+ }
+ if (typeof delta?.signature === 'string') {
+ recordProviderStringContent(diagnostics, event, delta.signature, 'signature');
+ }
+ if (typeof delta?.partial_json === 'string') {
+ recordProviderStringContent(diagnostics, event, delta.partial_json, 'toolInput');
+ }
+ if (typeof delta?.stop_reason === 'string') {
+ diagnostics.stopReason = delta.stop_reason;
+ diagnostics.terminalEventReceived = true;
+ }
+
+ if (typeof raw?.generation === 'string') {
+ recordProviderStringContent(diagnostics, event, raw.generation, 'text');
+ }
+ if (typeof raw?.stop_reason === 'string') {
+ diagnostics.stopReason = raw.stop_reason;
+ diagnostics.terminalEventReceived = true;
+ }
+ if (raw?.usage !== undefined) diagnostics.usage = raw.usage;
+ if (type === 'message_stop') diagnostics.terminalEventReceived = true;
+
+ appendProviderResponseEvent(diagnostics, event);
+};
diff --git a/packages/model-runtime/src/providers/cloudflare/index.test.ts b/packages/model-runtime/src/providers/cloudflare/index.test.ts
index babbe4ccc0d..b9c5fbe1089 100644
--- a/packages/model-runtime/src/providers/cloudflare/index.test.ts
+++ b/packages/model-runtime/src/providers/cloudflare/index.test.ts
@@ -3,6 +3,7 @@ import type { Mock } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ChatCompletionTool } from '../../types/chat';
+import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';
import * as debugStreamModule from '../../utils/debugStream';
import { LobeCloudflareAI } from './index';
@@ -79,6 +80,27 @@ describe('LobeCloudflareAI', () => {
expect(result).toBeInstanceOf(Response);
});
+ it('captures the bounded raw provider response when diagnostics are enabled', async () => {
+ const diagnostics: ModelRuntimeDiagnostics = {};
+ const result = await instance.chat(
+ {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: '@hf/meta-llama/meta-llama-3-8b-instruct',
+ },
+ { diagnostics },
+ );
+ await result.text();
+
+ expect(diagnostics.providerResponse).toMatchObject({
+ apiMode: 'cloudflare_workers_ai',
+ rawResponse: {
+ body: 'data: {"response": "Hello, world!"}\n\n',
+ status: 'captured',
+ },
+ status: 200,
+ });
+ });
+
it('should handle text messages correctly', async () => {
// Arrange
const textEncoder = new TextEncoder();
diff --git a/packages/model-runtime/src/providers/cloudflare/index.ts b/packages/model-runtime/src/providers/cloudflare/index.ts
index 6fad25c804b..5df40d02797 100644
--- a/packages/model-runtime/src/providers/cloudflare/index.ts
+++ b/packages/model-runtime/src/providers/cloudflare/index.ts
@@ -2,6 +2,13 @@ import type { ChatModelCard } from '@lobechat/types';
import { ModelProvider } from 'model-bank';
import type { LobeRuntimeAI } from '../../core/BaseAI';
+import {
+ captureRawProviderResponse,
+ finalizeProviderResponse,
+ initializeProviderDiagnostics,
+ observeProviderReadableStream,
+ recordProviderError,
+} from '../../core/providerDiagnostics';
import { createCallbacksTransformer } from '../../core/streams';
import {
CloudflareStreamTransformer,
@@ -14,6 +21,7 @@ import { AgentRuntimeErrorType } from '../../types/error';
import { AgentRuntimeError } from '../../utils/createError';
import { debugStream } from '../../utils/debugStream';
import { StreamingResponse } from '../../utils/response';
+import { recordCloudflareStreamChunk } from './providerDiagnostics';
export interface CloudflareModelCard {
description: string;
@@ -87,16 +95,26 @@ export class LobeCloudflareAI implements LobeRuntimeAI {
}
const url = new URL(model, this.baseURL);
const desensitizedEndpoint = desensitizeCloudflareUrl(url.toString());
+ const requestPayload = { tools: functions, ...restPayload };
+ const providerResponseDiagnostics = initializeProviderDiagnostics({
+ apiMode: 'cloudflare_workers_ai',
+ diagnostics: options?.diagnostics,
+ endpoint: desensitizedEndpoint,
+ payload: requestPayload,
+ sentAt: Date.now(),
+ });
let response: Response;
try {
response = await fetch(url, {
- body: JSON.stringify({ tools: functions, ...restPayload }),
+ body: JSON.stringify(requestPayload),
headers: { 'Content-Type': 'application/json', ...headers },
method: 'POST',
signal: options?.signal,
});
} catch (error) {
+ recordProviderError(providerResponseDiagnostics, error);
+ await finalizeProviderResponse(providerResponseDiagnostics, options?.signal);
throw AgentRuntimeError.chat({
endpoint: desensitizeCloudflareUrl(this.baseURL),
error: error as any,
@@ -105,6 +123,11 @@ export class LobeCloudflareAI implements LobeRuntimeAI {
provider: ModelProvider.Cloudflare,
});
}
+ if (providerResponseDiagnostics) {
+ providerResponseDiagnostics.responseReceivedAt = Date.now();
+ providerResponseDiagnostics.status = response.status;
+ captureRawProviderResponse(providerResponseDiagnostics, response);
+ }
if (response.status === 400) {
const bodyText = await response.text().catch(() => '');
@@ -116,7 +139,7 @@ export class LobeCloudflareAI implements LobeRuntimeAI {
// keep raw text
}
}
- throw AgentRuntimeError.chat({
+ const error = AgentRuntimeError.chat({
endpoint: desensitizedEndpoint,
error:
parsedBody && typeof parsedBody === 'object'
@@ -129,16 +152,25 @@ export class LobeCloudflareAI implements LobeRuntimeAI {
'Cloudflare API returned 400 Bad Request',
provider: ModelProvider.Cloudflare,
});
+ recordProviderError(providerResponseDiagnostics, error);
+ await finalizeProviderResponse(providerResponseDiagnostics, options?.signal);
+ throw error;
}
// Only tee when debugging
+ const observedBody = observeProviderReadableStream(
+ response.body!,
+ providerResponseDiagnostics,
+ recordCloudflareStreamChunk,
+ options?.signal,
+ );
let responseBody: ReadableStream;
if (process.env.DEBUG_CLOUDFLARE_CHAT_COMPLETION === '1') {
- const [prod, useForDebug] = response.body!.tee();
+ const [prod, useForDebug] = observedBody.tee();
debugStream(useForDebug).catch();
responseBody = prod;
} else {
- responseBody = response.body!;
+ responseBody = observedBody;
}
return StreamingResponse(
diff --git a/packages/model-runtime/src/providers/cloudflare/providerDiagnostics.ts b/packages/model-runtime/src/providers/cloudflare/providerDiagnostics.ts
new file mode 100644
index 00000000000..8c98e837ed1
--- /dev/null
+++ b/packages/model-runtime/src/providers/cloudflare/providerDiagnostics.ts
@@ -0,0 +1,19 @@
+import { appendProviderResponseEvent } from '../../core/providerDiagnostics';
+import type { ProviderResponseDiagnostics } from '../../types/providerDiagnostics';
+
+export const recordCloudflareStreamChunk = (
+ diagnostics: ProviderResponseDiagnostics,
+ chunk: unknown,
+) => {
+ diagnostics.firstEventAt ??= Date.now();
+ diagnostics.responseReceivedAt ??= Date.now();
+ appendProviderResponseEvent(diagnostics, {
+ contentLength:
+ chunk instanceof Uint8Array
+ ? chunk.byteLength
+ : typeof chunk === 'string'
+ ? chunk.length
+ : undefined,
+ type: 'cloudflare_stream_chunk',
+ });
+};
diff --git a/packages/model-runtime/src/providers/google/index.test.ts b/packages/model-runtime/src/providers/google/index.test.ts
index 4aa0f123d6a..dffa7d3b170 100644
--- a/packages/model-runtime/src/providers/google/index.test.ts
+++ b/packages/model-runtime/src/providers/google/index.test.ts
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { LOBE_ERROR_KEY } from '../../core/streams';
import { AgentRuntimeErrorType } from '../../types/error';
+import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';
import * as debugStreamModule from '../../utils/debugStream';
import {
createSignatureChannelId,
@@ -88,6 +89,43 @@ describe('LobeGoogleAI', () => {
expect(result).toBeInstanceOf(Response);
});
+ it('captures provider-native responses before Google protocol transformation', async () => {
+ const providerChunk = {
+ candidates: [{ content: { parts: [{ text: '' }] }, finishReason: 'STOP' }],
+ modelVersion: 'gemini-3.8-flash',
+ responseId: 'response-1',
+ usageMetadata: { candidatesTokenCount: 147 },
+ } as unknown as GenerateContentResponse;
+ vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(
+ (async function* () {
+ yield providerChunk;
+ })(),
+ );
+ const diagnostics: ModelRuntimeDiagnostics = {};
+
+ const response = await instance.chat(
+ {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gemini-3.8-flash',
+ },
+ { diagnostics },
+ );
+ await response.text();
+
+ expect(diagnostics.providerResponse).toMatchObject({
+ apiMode: 'google_generate_content',
+ eventCount: 1,
+ hasNonWhitespaceText: false,
+ model: 'gemini-3.8-flash',
+ rawEvents: [providerChunk],
+ requestId: 'response-1',
+ stopReason: 'STOP',
+ terminalEventReceived: true,
+ textChars: 0,
+ usage: { candidatesTokenCount: 147 },
+ });
+ });
+
it('should use mapped model id for upstream chat requests while keeping pricing on logical model', async () => {
const mappedInstance = new LobeGoogleAI({
apiKey: 'test',
diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.ts
index c461a747a39..2dc5e4b2891 100644
--- a/packages/model-runtime/src/providers/google/index.ts
+++ b/packages/model-runtime/src/providers/google/index.ts
@@ -9,6 +9,12 @@ import debug from 'debug';
import type { LobeRuntimeAI } from '../../core/BaseAI';
import { buildGoogleMessages, buildGoogleTools } from '../../core/contextBuilders/google';
+import {
+ finalizeProviderResponse,
+ initializeProviderDiagnostics,
+ observeProviderAsyncIterable,
+ recordProviderError,
+} from '../../core/providerDiagnostics';
import { GoogleGenerativeAIStream } from '../../core/streams';
import { LOBE_ERROR_KEY } from '../../core/streams/google';
import type {
@@ -24,6 +30,7 @@ import type {
} from '../../types';
import { AgentRuntimeErrorType } from '../../types/error';
import type { CreateImagePayload, CreateImageResponse } from '../../types/image';
+import type { ProviderResponseDiagnostics } from '../../types/providerDiagnostics';
import type { CreateVideoPayload, CreateVideoResponse } from '../../types/video';
import { AgentRuntimeError } from '../../utils/createError';
import { debugStream } from '../../utils/debugStream';
@@ -50,6 +57,7 @@ import {
shouldUseGoogleImageSearchTypes,
supportsGoogleSearchOnImageResponseModel,
} from './modelId';
+import { recordGoogleGenerateContentResponse } from './providerDiagnostics';
import { resolveGoogleThinkingConfig } from './thinkingResolver';
import { createGoogleTranscription } from './transcribe';
@@ -148,6 +156,8 @@ export class LobeGoogleAI implements LobeRuntimeAI {
}
async chat(rawPayload: ChatStreamPayload, options?: ChatMethodOptions) {
+ let providerResponseDiagnostics: ProviderResponseDiagnostics | undefined;
+
try {
const payload = this.buildPayload(rawPayload);
const { model, thinkingBudget, thinkingLevel, imageAspectRatio, imageResolution } = payload;
@@ -253,6 +263,13 @@ export class LobeGoogleAI implements LobeRuntimeAI {
const key = this.isVertexAi
? 'DEBUG_VERTEX_AI_CHAT_COMPLETION'
: 'DEBUG_GOOGLE_CHAT_COMPLETION';
+ providerResponseDiagnostics = initializeProviderDiagnostics({
+ apiMode: this.isVertexAi ? 'vertex_generate_content' : 'google_generate_content',
+ diagnostics: options?.diagnostics,
+ endpoint: this.baseURL,
+ payload: finalPayload,
+ sentAt: Date.now(),
+ });
if (process.env[key] === '1') {
log('[requestPayload]');
@@ -260,11 +277,19 @@ export class LobeGoogleAI implements LobeRuntimeAI {
}
const geminiStreamResponse = await this.client.models.generateContentStream(finalPayload);
+ const observedGeminiStream = observeProviderAsyncIterable(
+ geminiStreamResponse,
+ providerResponseDiagnostics,
+ recordGoogleGenerateContentResponse,
+ controller.signal,
+ );
- const googleStream = this.createEnhancedStream(geminiStreamResponse, controller.signal);
- const [prod, useForDebug] = googleStream.tee();
+ const googleStream = this.createEnhancedStream(observedGeminiStream, controller.signal);
+ let prod = googleStream;
if (process.env[key] === '1') {
+ const [productionStream, useForDebug] = googleStream.tee();
+ prod = productionStream;
debugStream(useForDebug).catch();
}
@@ -281,6 +306,8 @@ export class LobeGoogleAI implements LobeRuntimeAI {
return StreamingResponse(stream, { headers: options?.headers });
} catch (e) {
const err = e as Error;
+ recordProviderError(providerResponseDiagnostics, err);
+ await finalizeProviderResponse(providerResponseDiagnostics, options?.signal);
// Remove previous silent handling, throw error uniformly
if (isAbortError(err)) {
diff --git a/packages/model-runtime/src/providers/google/providerDiagnostics.ts b/packages/model-runtime/src/providers/google/providerDiagnostics.ts
new file mode 100644
index 00000000000..69814e12d8c
--- /dev/null
+++ b/packages/model-runtime/src/providers/google/providerDiagnostics.ts
@@ -0,0 +1,80 @@
+import type { GenerateContentResponse } from '@google/genai';
+
+import {
+ appendProviderResponseEvent,
+ appendRawProviderEvent,
+ recordProviderStringContent,
+} from '../../core/providerDiagnostics';
+import type { ProviderResponseDiagnostics } from '../../types/providerDiagnostics';
+
+interface GooglePart {
+ fileData?: unknown;
+ functionCall?: { args?: unknown; name?: string };
+ inlineData?: unknown;
+ text?: string;
+ thought?: boolean;
+ thoughtSignature?: string;
+}
+
+export const recordGoogleGenerateContentResponse = (
+ diagnostics: ProviderResponseDiagnostics,
+ response: GenerateContentResponse,
+) => {
+ appendRawProviderEvent(diagnostics, response);
+ diagnostics.firstEventAt ??= Date.now();
+ diagnostics.responseReceivedAt ??= Date.now();
+
+ const rawResponse = response as GenerateContentResponse & {
+ modelVersion?: string;
+ promptFeedback?: { blockReason?: string };
+ responseId?: string;
+ usageMetadata?: unknown;
+ };
+ diagnostics.messageId ??= rawResponse.responseId;
+ diagnostics.requestId ??= rawResponse.responseId;
+ diagnostics.model ??= rawResponse.modelVersion;
+ if (rawResponse.usageMetadata !== undefined) diagnostics.usage = rawResponse.usageMetadata;
+
+ const event = { type: 'generate_content_response' };
+ for (const candidate of rawResponse.candidates ?? []) {
+ if (candidate.finishReason) {
+ diagnostics.stopReason = candidate.finishReason;
+ diagnostics.terminalEventReceived = true;
+ }
+
+ for (const rawPart of candidate.content?.parts ?? []) {
+ const part = rawPart as GooglePart;
+ if (typeof part.text === 'string') {
+ recordProviderStringContent(
+ diagnostics,
+ event,
+ part.text,
+ part.thought ? 'thinking' : 'text',
+ );
+ }
+ if (typeof part.thoughtSignature === 'string') {
+ recordProviderStringContent(diagnostics, event, part.thoughtSignature, 'signature');
+ }
+ if (part.functionCall) {
+ diagnostics.toolUseCount += 1;
+ diagnostics.firstNonWhitespaceOutputAt ??= Date.now();
+ if (part.functionCall.args !== undefined) {
+ recordProviderStringContent(
+ diagnostics,
+ event,
+ JSON.stringify(part.functionCall.args),
+ 'toolInput',
+ );
+ }
+ }
+ if (part.inlineData || part.fileData) diagnostics.firstNonWhitespaceOutputAt ??= Date.now();
+ }
+ }
+
+ if (rawResponse.promptFeedback?.blockReason) {
+ diagnostics.stopReason ??= rawResponse.promptFeedback.blockReason;
+ diagnostics.terminalEventReceived = true;
+ }
+
+ appendProviderResponseEvent(diagnostics, event);
+};