Skip to content
250 changes: 250 additions & 0 deletions packages/core/src/core/baseLlmClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,12 @@ vi.mock('../models/content-generator-config.js', () => ({
}));

const mockGenerateContent = vi.fn();
const mockGenerateContentStream = vi.fn();
const mockEmbedContent = vi.fn();

const mockContentGenerator = {
generateContent: mockGenerateContent,
generateContentStream: mockGenerateContentStream,
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
embedContent: mockEmbedContent,
} as unknown as Mocked<ContentGenerator>;

Expand Down Expand Up @@ -130,6 +132,21 @@ const createMockTextResponse = (text: string): GenerateContentResponse =>
],
}) as GenerateContentResponse;

// Builds an async generator that yields one response per text delta, then an
// optional trailing usage-only chunk — mirroring how the streaming pipeline
// emits content deltas followed by a final chunk carrying usageMetadata.
async function* mockTextStream(
chunks: string[],
usage?: GenerateContentResponse['usageMetadata'],
): AsyncGenerator<GenerateContentResponse> {
for (const text of chunks) {
yield createMockTextResponse(text);
}
if (usage) {
yield { usageMetadata: usage } as GenerateContentResponse;
}
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
}

describe('BaseLlmClient', () => {
let client: BaseLlmClient;
let abortController: AbortController;
Expand Down Expand Up @@ -554,11 +571,199 @@ describe('BaseLlmClient', () => {
});
});

describe('generateText - streaming', () => {
it('routes through generateContentStream, concatenates deltas, trims once, and captures final-chunk usage', async () => {
const usage = {
promptTokenCount: 11,
candidatesTokenCount: 7,
totalTokenCount: 18,
};
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
mockGenerateContentStream.mockImplementation(async () =>
mockTextStream([' Hello', ', ', 'world '], usage),
);

const result = await client.generateText({
contents: [{ role: 'user', parts: [{ text: 'hi' }] }],
model: 'test-model',
abortSignal: abortController.signal,
promptId: 'p',
stream: true,
});

expect(mockGenerateContentStream).toHaveBeenCalledTimes(1);
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
// The streaming branch builds the same request object as the non-stream
// path: resolved model, contents, and a config carrying the abortSignal.
expect(mockGenerateContentStream).toHaveBeenCalledWith(
expect.objectContaining({
model: 'test-model',
contents: [{ role: 'user', parts: [{ text: 'hi' }] }],
config: expect.objectContaining({
abortSignal: abortController.signal,
}),
}),
'p',
);
expect(mockGenerateContent).not.toHaveBeenCalled();
// Deltas are concatenated, then trimmed once at the end.
expect(result.text).toBe('Hello, world');
expect(result.usage).toEqual(usage);
});

it('drops thought parts and tolerates a stream that omits usage', async () => {
async function* streamWithThought(): AsyncGenerator<GenerateContentResponse> {
yield createMockTextResponse('answer');
yield {
candidates: [
{
content: {
role: 'model',
parts: [{ text: 'reasoning', thought: true }],
},
index: 0,
},
],
} as unknown as GenerateContentResponse;
}
mockGenerateContentStream.mockImplementation(async () =>
streamWithThought(),
);

const result = await client.generateText({
contents: [{ role: 'user', parts: [{ text: 'hi' }] }],
model: 'test-model',
abortSignal: abortController.signal,
promptId: 'p',
stream: true,
});

expect(result.text).toBe('answer');
expect(result.usage).toBeUndefined();
});

it('does not stream when stream is omitted (non-streaming path, still trimmed)', async () => {
mockGenerateContent.mockResolvedValue(
createMockTextResponse(' plain '),
);

const result = await client.generateText({
contents: [{ role: 'user', parts: [{ text: 'hi' }] }],
model: 'test-model',
abortSignal: abortController.signal,
promptId: 'p',
});

expect(mockGenerateContent).toHaveBeenCalledTimes(1);
expect(mockGenerateContentStream).not.toHaveBeenCalled();
expect(result.text).toBe('plain');
});

it('propagates a mid-stream error and never returns the partial text', async () => {
async function* failingStream(): AsyncGenerator<GenerateContentResponse> {
yield createMockTextResponse('partial');
throw new Error('connection reset');
}
mockGenerateContentStream.mockImplementation(async () => failingStream());

// A failure after some deltas have arrived rejects the whole call — the
// accumulated 'partial' text is never surfaced as a success — and, since
// the signal isn't aborted, the error is reported like the non-streaming
// path. This is the gateway-timeout-mid-inference scenario the PR targets.
await expect(
client.generateText({
contents: [{ role: 'user', parts: [{ text: 'hi' }] }],
model: 'test-model',
abortSignal: abortController.signal,
promptId: 'p',
stream: true,
}),
).rejects.toThrow('connection reset');
expect(vi.mocked(reportError)).toHaveBeenCalled();
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
});

it('surfaces an abort that fires mid-stream and skips error reporting', async () => {
async function* abortingStream(): AsyncGenerator<GenerateContentResponse> {
yield createMockTextResponse('chunk');
abortController.abort();
throw new DOMException('The operation was aborted.', 'AbortError');
}
mockGenerateContentStream.mockImplementation(async () =>
abortingStream(),
);

// The `abortSignal.aborted` guard in the catch block rethrows the original
// error unwrapped and skips reportError, so a user-initiated cancellation
// mid-stream surfaces verbatim and is not logged as an API failure.
await expect(
client.generateText({
contents: [{ role: 'user', parts: [{ text: 'hi' }] }],
model: 'test-model',
abortSignal: abortController.signal,
promptId: 'p',
stream: true,
}),
).rejects.toThrow('The operation was aborted.');
expect(vi.mocked(reportError)).not.toHaveBeenCalled();
});

it('returns an empty result for a stream that yields no chunks', async () => {
// A stream that closes immediately (no content, no usage) must resolve to
// an empty string rather than throw — the boundary the streaming branch
// introduces. mockTextStream([]) yields nothing.
mockGenerateContentStream.mockImplementation(async () =>
mockTextStream([]),
);

const result = await client.generateText({
contents: [{ role: 'user', parts: [{ text: 'hi' }] }],
model: 'test-model',
abortSignal: abortController.signal,
promptId: 'p',
stream: true,
});

expect(result.text).toBe('');
expect(result.usage).toBeUndefined();
});

it('captures usage that rides the final content-bearing chunk', async () => {
// Realistic Gemini/OpenAI shape: usageMetadata arrives on the last chunk
// that *also* carries a text delta. Text and usage are read independently
// per chunk, so the trailing text must not be dropped when usage is read.
const usage = {
promptTokenCount: 5,
candidatesTokenCount: 3,
totalTokenCount: 8,
};
async function* usageOnTextChunk(): AsyncGenerator<GenerateContentResponse> {
yield createMockTextResponse('Hello, ');
const finalChunk = createMockTextResponse('world');
finalChunk.usageMetadata = usage;
yield finalChunk;
}
mockGenerateContentStream.mockImplementation(async () =>
usageOnTextChunk(),
);

const result = await client.generateText({
contents: [{ role: 'user', parts: [{ text: 'hi' }] }],
model: 'test-model',
abortSignal: abortController.signal,
promptId: 'p',
stream: true,
});

expect(result.text).toBe('Hello, world');
expect(result.usage).toEqual(usage);
});
});

describe('per-model resolution', () => {
const fastModel = 'fast-model';
const fastGenerateContent = vi.fn();
const fastGenerateContentStream = vi.fn();
const fastContentGenerator = {
generateContent: fastGenerateContent,
generateContentStream: fastGenerateContentStream,
embedContent: vi.fn(),
} as unknown as Mocked<ContentGenerator>;

Expand All @@ -570,6 +775,7 @@ describe('BaseLlmClient', () => {
async (fn) => await (fn as () => Promise<unknown>)(),
);
fastGenerateContent.mockReset();
fastGenerateContentStream.mockReset();
mockCreateContentGenerator.mockReset();
mockBuildAgentContentGeneratorConfig.mockReset();
getResolvedModel.mockReset();
Expand Down Expand Up @@ -667,6 +873,50 @@ describe('BaseLlmClient', () => {
expect(mockCreateContentGenerator).toHaveBeenCalledTimes(1);
});

it('streams through a per-model generator resolved by model (compression path)', async () => {
// chatCompressionService passes both `model` and `stream: true`, so the
// streaming branch must run on the resolveForModel-selected generator,
// not the constructor-injected default.
getResolvedModel.mockReturnValue({
authType: AuthType.USE_ANTHROPIC,
envKey: 'ANTHROPIC_API_KEY',
});
const usage = {
promptTokenCount: 2,
candidatesTokenCount: 2,
totalTokenCount: 4,
};
fastGenerateContentStream.mockImplementation(async () =>
mockTextStream(['fast ', 'stream'], usage),
);

const c = new BaseLlmClient(mockContentGenerator, crossProviderConfig);
const result = await c.generateText({
contents: [{ role: 'user', parts: [{ text: 'hi' }] }],
model: fastModel,
abortSignal: abortController.signal,
promptId: 'p',
stream: true,
});

expect(fastGenerateContentStream).toHaveBeenCalledTimes(1);
// Streamed against the resolved per-model identity, not the main model.
expect(fastGenerateContentStream).toHaveBeenCalledWith(
expect.objectContaining({
model: fastModel,
contents: [{ role: 'user', parts: [{ text: 'hi' }] }],
config: expect.objectContaining({
abortSignal: abortController.signal,
}),
}),
'p',
);
// The constructor-injected default generator must not be touched.
expect(mockGenerateContentStream).not.toHaveBeenCalled();
expect(result.text).toBe('fast stream');
expect(result.usage).toEqual(usage);
});

it('caches the per-model generator across resolveForModel calls', async () => {
getResolvedModel.mockReturnValue({
authType: AuthType.USE_ANTHROPIC,
Expand Down
66 changes: 54 additions & 12 deletions packages/core/src/core/baseLlmClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,14 @@ export interface GenerateTextOptions {
* The maximum number of attempts for the request.
*/
maxAttempts?: number;
/**
Comment thread
doudouOUC marked this conversation as resolved.
Resolved
* Stream the response instead of awaiting the whole non-streaming body.
* Defaults to `false` (unchanged non-streaming behavior). Opt in to keep the
* HTTP connection alive against BFF gateways whose `proxy_read_timeout` would
* otherwise kill a slow inference before the first byte arrives. The streamed
* deltas are collected into the same `{ text, usage }` result.
*/
stream?: boolean;
}

/**
Expand Down Expand Up @@ -325,6 +333,7 @@ export class BaseLlmClient {
systemInstruction,
promptId,
maxAttempts,
stream,
} = options;

const requestConfig: GenerateContentConfig = {
Expand All @@ -341,15 +350,46 @@ export class BaseLlmClient {
} = await this.resolveForModel(model);

try {
const apiCall = () =>
contentGenerator.generateContent(
{
model: requestModel,
config: requestConfig,
contents,
},
promptId ?? '',
);
const request = {
model: requestModel,
config: requestConfig,
contents,
};

// Both branches resolve to the same `{ text, usage }` shape so a single
// retryWithBackoff governs the whole request (a mid-stream failure retries
// the entire call — side queries are idempotent). Streaming keeps the HTTP
// connection alive so a slow inference can't be killed by a gateway's
// `proxy_read_timeout`; non-streaming is the unchanged default.
const apiCall: () => Promise<GenerateTextResult> = stream
? async () => {
const responseStream = await contentGenerator.generateContentStream(
request,
promptId ?? '',
);
// Chunks are deltas, not cumulative snapshots, so concatenate.
// getResponseText already drops thought parts; usageMetadata rides
// the final chunk (last one wins), matching the non-streaming read.
let text = '';
let usage: GenerateContentResponseUsageMetadata | undefined;
for await (const chunk of responseStream) {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks — I checked this carefully. Two parts of the observation are correct, but the severity premise isn't, so I've corrected the PR description rather than adding the wrapper.

Correct: withStreamInactivityTimeout lives only in the OpenAI pipeline (openaiContentGenerator/pipeline.ts:120, applied at :265); GeminiContentGenerator.generateContentStream returns the raw googleGenAI stream and AnthropicContentGenerator returns a raw Anthropic stream — neither has a per-chunk idle timeout.

But the motivating path is not Gemini. The DataWorks ACP / DQ_AGENT BFF is OpenAI-compatible — issue #5861's own trace shows openai.chat.completions.create. That resolves to OpenAIContentGenerator (or QwenContentGenerator, whose generateContentStream override just wraps super.generateContentStream in credential management — qwenContentGenerator.ts:167), so compression behind the BFF does route through the pipeline and is covered by the watchdog. The "blocks indefinitely / worse than pre-PR" scenario doesn't apply where this PR actually runs, and the 60s gateway timeout you cite only exists in that BFF deployment.

For native USE_GEMINI / USE_ANTHROPIC: the raw-stream point is fair, but that's the exact contract the main chat loop already consumes on every turn (geminiChat.ts iterates the same generateContentStream, e.g. :2013, :2994), bounded by the SDK transport timeout + abortSignal. This side-query reuses that existing invariant; it isn't a new exposure introduced here.

Changed: corrected the PR description's risk note, which overclaimed a universal 120s watchdog — it's now scoped to the OpenAI/Qwen pipeline, with the Gemini/Anthropic contract spelled out.

Not changed: I didn't wrap responseStream at the baseLlmClient level. A provider-agnostic idle timeout belongs at the ContentGenerator layer so the main loop benefits too; adding it only to this side-query would double-wrap OpenAI/Qwen and give the side-query a guarantee the main turn doesn't have. Happy to do that as a separate, broader change if maintainers want it — leaving this thread open for a maintainer to weigh in.

🤖 Addressed by Qwen Code

text += getResponseText(chunk) ?? '';
if (chunk.usageMetadata) {
usage = chunk.usageMetadata;
}
}
return { text, usage };
}
: async () => {
const result = await contentGenerator.generateContent(
request,
promptId ?? '',
);
return {
text: getResponseText(result) ?? '',
usage: result.usageMetadata,
};
};

const result = await retryWithBackoff(apiCall, {
maxAttempts: maxAttempts ?? DEFAULT_MAX_ATTEMPTS,
Expand Down Expand Up @@ -379,8 +419,8 @@ export class BaseLlmClient {
});

return {
text: (getResponseText(result) ?? '').trim(),
usage: result.usageMetadata,
text: result.text.trim(),
usage: result.usage,
};
} catch (error) {
if (abortSignal.aborted) {
Expand All @@ -389,7 +429,9 @@ export class BaseLlmClient {

await reportError(
error,
'Error generating text content via API.',
// Mark streaming failures so an oncall can tell a mid-stream error
// apart from the original non-streaming gateway timeout (#5861).
`Error generating text content via API${stream ? ' [streaming]' : ''}.`,
contents,
'generateText-api',
);
Expand Down
Loading
Loading