7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
fix(responses): end a truncated turn as incomplete, not completed (#1624)
Jay Hemnanib32a9bfdab03
diff --git a/server/src/__tests__/routes/agent-web-search.test.ts b/server/src/__tests__/routes/agent-web-search.test.tsindex 024b0d1c..b4b1fa8e 100644--- a/server/src/__tests__/routes/agent-web-search.test.ts+++ b/server/src/__tests__/routes/agent-web-search.test.ts@@ -302,6 +302,19 @@ describe('agent web search served from the search pool', () => {expect(seq).toEqual([...seq].sort((a, b) => a - b));});+ it('keeps a final answer cut off at the token limit incomplete', async () => {+ addSearchKey();+ const cut = answer('Version 9 shi');+ cut.choices[0].finish_reason = 'length';+ mockGroq([searchCall('version 9 release'), cut]);+ const { text } = await post('/v1/responses', request({ stream: true }), bearer());++ const names = sseEvents(text).map(e => e.event);+ expect(names).not.toContain('response.completed');+ const final = sseEvents(text).find(e => e.event === 'response.incomplete')!.data.response;+ expect(final).toMatchObject({ status: 'incomplete', incomplete_details: { reason: 'max_output_tokens' } });+ });+it('drops the tool as before when no search key is configured', async () => {const bodies = mockGroq([answer('Plain answer.')]);const { status, body } = await post('/v1/responses', request(), bearer());diff --git a/server/src/__tests__/routes/responses.test.ts b/server/src/__tests__/routes/responses.test.tsindex 109cea01..da488e62 100644--- a/server/src/__tests__/routes/responses.test.ts+++ b/server/src/__tests__/routes/responses.test.ts@@ -264,6 +264,44 @@ describe('POST /v1/responses (#96)', () => {expect(completed).toContain('"output_text":"Hello"');});+ it('stream: a turn cut off at the token limit ends as response.incomplete', async () => {+ mockRouteRequest.mockReturnValue(fakeRoute({+ async chatCompletion() { throw new Error('should not be called'); },+ async *streamChatCompletion() {+ yield { id: 'c', object: 'chat.completion.chunk', created: 0, model: 'fake-model', choices: [{ index: 0, delta: { role: 'assistant', content: 'Partial answ' }, finish_reason: null }] };+ yield { id: 'c', object: 'chat.completion.chunk', created: 0, model: 'fake-model', choices: [{ index: 0, delta: {}, finish_reason: 'length' }] };+ },+ }));++ const { status, text } = await post(app, '/v1/responses', { input: 'hi', stream: true }, key);+ expect(status).toBe(200);+ expect(text).not.toContain('event: response.completed');+ const terminal = JSON.parse(text.split('event: response.incomplete\ndata: ')[1].split('\n')[0]);+ expect(terminal.response).toMatchObject({+ status: 'incomplete',+ incomplete_details: { reason: 'max_output_tokens' },+ output_text: 'Partial answ',+ });+ expect(terminal.response.output[0].status).toBe('incomplete');+ });++ it('non-stream: a turn cut off at the token limit is incomplete', async () => {+ mockRouteRequest.mockReturnValue(fakeRoute({+ async chatCompletion() {+ return {+ id: 'x', object: 'chat.completion', created: 0, model: 'fake-model',+ choices: [{ index: 0, message: { role: 'assistant', content: 'Partial answ' }, finish_reason: 'length' }],+ usage: { prompt_tokens: 3, completion_tokens: 4, total_tokens: 7 },+ };+ },+ async *streamChatCompletion() { /* unused */ },+ }));++ const { status, text } = await post(app, '/v1/responses', { input: 'hi', stream: false }, key);+ expect(status).toBe(200);+ expect(JSON.parse(text)).toMatchObject({ status: 'incomplete', incomplete_details: { reason: 'max_output_tokens' } });+ });+it('stream: records ttfb on the first reasoning token, not the first visible text (#764)', async () => {mockRouteRequest.mockReturnValue(fakeRoute({async chatCompletion() { throw new Error('should not be called'); },diff --git a/server/src/lib/responses-web-search.ts b/server/src/lib/responses-web-search.tsindex e519e080..2ba9aa37 100644--- a/server/src/lib/responses-web-search.ts+++ b/server/src/lib/responses-web-search.ts@@ -136,7 +136,7 @@ class ResponsesSse {complete(response: Item): void {this.stopHeartbeat();- this.write('response.completed', { response });+ this.write(response.status === 'incomplete' ? 'response.incomplete' : 'response.completed', { response });try { this.res.end(); } catch { /* already closed */ }}@@ -246,7 +246,8 @@ export async function maybeServeResponsesWebSearch(const finalResponse = {...reply,id: responseId,- status: 'completed',+ // Keep a token-limit or content-filter cut visible (see routes/responses.ts).+ status: reply.status === 'incomplete' ? 'incomplete' : 'completed',output: assembled,output_text: assembled.map(itemText).join(''),usage: {diff --git a/server/src/routes/responses.ts b/server/src/routes/responses.tsindex 6aa66fc7..e7232fc1 100644--- a/server/src/routes/responses.ts+++ b/server/src/routes/responses.ts@@ -510,6 +510,16 @@ function requestDeclaresToolUse(req: ResponsesRequest): boolean {}// ── Build the final (non-stream) Responses object ─────────────────────────+/**+ * Responses-API `incomplete_details.reason` for an upstream chat finish+ * reason, or undefined when the response ran to completion.+ */+export function incompleteReason(finishReason: string | null | undefined): 'max_output_tokens' | 'content_filter' | undefined {+ if (finishReason === 'length') return 'max_output_tokens';+ if (finishReason === 'content_filter') return 'content_filter';+ return undefined;+}+export function buildResponseObject(opts: {id: string;model: string;@@ -519,13 +529,14 @@ export function buildResponseObject(opts: {completionTokens: number;reasoningTokens?: number;metadata?: Record<string, string>;+ incompleteReason?: 'max_output_tokens' | 'content_filter';}) {const output: any[] = [];if (opts.text.length > 0) {output.push({type: 'message',id: newId('msg'),- status: 'completed',+ status: opts.incompleteReason ? 'incomplete' : 'completed',role: 'assistant',content: [{ type: 'output_text', text: opts.text, annotations: [] }],});@@ -545,7 +556,8 @@ export function buildResponseObject(opts: {id: opts.id,object: 'response',created_at: nowUnix(),- status: 'completed',+ status: opts.incompleteReason ? 'incomplete' : 'completed',+ ...(opts.incompleteReason ? { incomplete_details: { reason: opts.incompleteReason } } : {}),model: opts.model,output,output_text: opts.text,@@ -1471,11 +1483,15 @@ export async function handleResponses(req: Request, res: Response): Promise<void);}+ // A truncated or filtered turn ends as `incomplete`, not `completed`,+ // so clients don't take a cut-off answer as the whole answer.+ const incomplete = incompleteReason(upstreamFinish);+// Finalize any open text item.if (msgItemId !== null) {sse('response.output_text.done', { item_id: msgItemId, output_index: textOutputIndex, content_index: 0, text: msgText });sse('response.content_part.done', { item_id: msgItemId, output_index: textOutputIndex, content_index: 0, part: { type: 'output_text', text: msgText, annotations: [] } });- sse('response.output_item.done', { output_index: textOutputIndex, item: { id: msgItemId, type: 'message', status: 'completed', role: 'assistant', content: [{ type: 'output_text', text: msgText, annotations: [] }] } });+ sse('response.output_item.done', { output_index: textOutputIndex, item: { id: msgItemId, type: 'message', status: incomplete ? 'incomplete' : 'completed', role: 'assistant', content: [{ type: 'output_text', text: msgText, annotations: [] }] } });}// Finalize tool-call items. Arguments are repaired against the tool's// parameter schema at this point (after the full string accumulated):@@ -1505,9 +1521,9 @@ export async function handleResponses(req: Request, res: Response): Promise<voidconst finalResponse = buildResponseObject({id: responseId, model: route.modelId, text: msgText,toolCalls: finalToolCalls, promptTokens: estimatedInputTokens, completionTokens: totalOutputTokens,- reasoningTokens: totalReasoningTokens,+ reasoningTokens: totalReasoningTokens, incompleteReason: incomplete,});- sse('response.completed', { response: finalResponse });+ sse(incomplete ? 'response.incomplete' : 'response.completed', { response: finalResponse });res.end();recordUpstreamSuccess(route, estimatedInputTokens + totalOutputTokens, state);@@ -1651,6 +1667,7 @@ export async function handleResponses(req: Request, res: Response): Promise<voidres.json(buildResponseObject({id: responseId, model: route.modelId, text, toolCalls,promptTokens, completionTokens, reasoningTokens,+ incompleteReason: incompleteReason(result.choices[0]?.finish_reason),}));traceRouteEvent('Responses', {