Skip to content
Open
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
89 changes: 82 additions & 7 deletions packages/outpost/ai/src/generator.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
import type Anthropic from '@anthropic-ai/sdk';
import { LLMock } from '@copilotkit/aimock';
import {
GROUNDING_RULES,
SYSTEM_PROMPT_PREFIX,
ResponseGenerator,
EmptyModelResponseError,
buildChannelGuidance,
extractResponseText,
} from './generator.js';
Expand Down Expand Up @@ -564,15 +565,89 @@ describe('ResponseGenerator', () => {
expect(chunks.length).toBeGreaterThanOrEqual(1);
});

it('should yield error message on stream failure', async () => {
mock.nextRequestError(500, { message: 'Stream interrupted' });
it.each(['', ' \n '])(
'rejects a completed stream with no usable text (%j)',
async (content) => {
mock.onMessage(/./, {
content,
usage: { input_tokens: 100, output_tokens: 2 },
});

const chunks: string[] = [];
await expect(
(async () => {
for await (const chunk of generator.generateStream(
{ question: 'test' },
sampleSources,
)) {
chunks.push(chunk);
}
})(),
).rejects.toThrow(EmptyModelResponseError);
expect(chunks.join('').trim()).toBe('');
},
);

it('rethrows provider stream failures instead of yielding them as content', async () => {
const client = (
generator as unknown as {
client: { messages: { stream: (...args: unknown[]) => unknown } };
}
).client;
const stream = vi.spyOn(client.messages, 'stream').mockImplementation(() => {
throw new Error('Stream interrupted');
});

const chunks: string[] = [];
for await (const chunk of generator.generateStream({ question: 'test' }, [])) {
chunks.push(chunk);
try {
const chunks: string[] = [];
await expect(
(async () => {
for await (const chunk of generator.generateStream(
{ question: 'test' },
[],
)) {
chunks.push(chunk);
}
})(),
).rejects.toThrow('Stream interrupted');
expect(chunks.join('')).not.toContain('Error generating response');
} finally {
stream.mockRestore();
}
});

expect(chunks.join('')).toContain('Error generating response');
it('rethrows a provider failure after partial text without converting it to content', async () => {
const client = (
generator as unknown as {
client: { messages: { stream: (...args: unknown[]) => unknown } };
}
).client;
const stream = vi.spyOn(client.messages, 'stream').mockReturnValue(
(async function* () {
yield {
type: 'content_block_delta',
delta: { type: 'text_delta', text: 'partial draft' },
};
throw new Error('Stream interrupted mid-response');
})() as never,
);

try {
const chunks: string[] = [];
await expect(
(async () => {
for await (const chunk of generator.generateStream(
{ question: 'test' },
[],
)) {
chunks.push(chunk);
}
})(),
).rejects.toThrow('Stream interrupted mid-response');
expect(chunks).toEqual(['partial draft']);
} finally {
stream.mockRestore();
}
});
});
});
22 changes: 21 additions & 1 deletion packages/outpost/ai/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,14 @@ export function extractResponseText(content: Anthropic.ContentBlock[]): string {
.join('\n\n');
}

/** A completed model stream produced no publishable text. */
export class EmptyModelResponseError extends Error {
constructor(message = 'Model response contained no usable text') {
super(message);
this.name = 'EmptyModelResponseError';
}
}

/**
* Claude response generator for the AI support pipeline.
*
Expand Down Expand Up @@ -248,6 +256,11 @@ export class ResponseGenerator {

/**
* Generate a response in streaming mode, yielding text chunks as they arrive.
*
* A completed stream with no usable text rejects with
* {@link EmptyModelResponseError}; provider failures reject with the original
* error. Neither case is response content: callers that buffer the stream
* must not publish an empty success or a raw provider error as the answer.
*/
async *generateStream(
pipelineContext: PipelineContext,
Expand All @@ -256,6 +269,7 @@ export class ResponseGenerator {
): AsyncIterable<string> {
const systemPrompt = this.buildSystemPrompt(sources, pipelineContext.source);
const messages = this.buildMessages(pipelineContext, conversationHistory);
let hasUsableText = false;

try {
const stream = this.client.messages.stream({
Expand All @@ -268,11 +282,17 @@ export class ResponseGenerator {

for await (const event of stream) {
if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
hasUsableText ||= event.delta.text.trim().length > 0;
yield event.delta.text;
}
}

if (!hasUsableText) {
throw new EmptyModelResponseError();
}
} catch (error) {
yield `\n\n_Error generating response: ${error instanceof Error ? error.message : String(error)}_`;
console.error(`[Generator] Streaming response generation failed:`, error);
throw error;
}
}

Expand Down
36 changes: 36 additions & 0 deletions packages/outpost/ai/src/pipeline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ vi.mock('./config.js', async (importOriginal) => ({

import { AI_CONFIDENCE } from '@copilotkit/outpost/shared';
import { AIPipeline, SUPPRESSED_RESPONSE_TEXT } from './pipeline.js';
import { EmptyModelResponseError } from './generator.js';
import { assessGroundedness } from './groundedness.js';
import { describeVerdict, lintDraft } from './eval/linter.js';
import { AI_DISCLAIMER, AI_DISCLAIMER_ESCALATED, AI_DISCLAIMER_REVIEWED } from './formatter.js';
Expand Down Expand Up @@ -1410,6 +1411,41 @@ describe('AIPipeline', () => {
expect(chunks).toEqual([SUPPRESSED_RESPONSE_TEXT]);
});

it('replaces an empty completed stream with the handoff', async () => {
mockGenerateStream.mockReturnValue(
(async function* (): AsyncIterable<string> {
yield* streamOf();
throw new EmptyModelResponseError();
})(),
);

const chunks = await collect(
pipeline.generateStreamingResponse('q', { source: 'web' }),
);
expect(chunks).toEqual([SUPPRESSED_RESPONSE_TEXT]);
});

it('propagates provider stream failures without publishing a partial draft', async () => {
mockGenerateStream.mockReturnValue(
(async function* (): AsyncIterable<string> {
yield 'partial draft';
throw new Error('provider stream failed');
})(),
);

const chunks: string[] = [];
await expect(
(async () => {
for await (const chunk of pipeline.generateStreamingResponse('q', {
source: 'web',
})) {
chunks.push(chunk);
}
})(),
).rejects.toThrow('provider stream failed');
expect(chunks).toEqual([]);
});

it('passes the retrieved sources and history through to the generator', async () => {
mockGenerateStream.mockReturnValue(streamOf('ok'));
const history = [{ role: 'user' as const, content: 'hi' }];
Expand Down
25 changes: 18 additions & 7 deletions packages/outpost/ai/src/pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
import { supportReplyText } from './support-reply.js';
import type { SupportReply } from './support-reply.js';
import { lintDraft, describeVerdict } from './eval/linter.js';
import { ResponseGenerator } from './generator.js';
import { EmptyModelResponseError, ResponseGenerator } from './generator.js';
import { ConfidenceScorer } from './confidence.js';
import { TicketClassifier } from './classifier.js';
import {
Expand Down Expand Up @@ -541,12 +541,23 @@ export class AIPipeline {

// Buffer the whole draft — the gate needs the complete text.
const chunks: string[] = [];
for await (const chunk of this.legacyGenerator().generateStream(
pipelineContext,
searchResults,
options.conversationHistory,
)) {
chunks.push(chunk);
try {
for await (const chunk of this.legacyGenerator().generateStream(
pipelineContext,
searchResults,
options.conversationHistory,
)) {
chunks.push(chunk);
}
} catch (error) {
if (!(error instanceof EmptyModelResponseError)) {
// Provider/transport failures keep the worker retry contract.
throw error;
}
// An empty completed stream has no draft to gate. Publish only the
// handoff rather than a successful empty response.
yield SUPPRESSED_RESPONSE_TEXT;
return;
}

const text = chunks.join('');
Expand Down