Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(ai-proxy): strip refusal, retry on sampling 400, drop orphan tool msgs

Louis Beaumontee62f6112950
diff --git a/packages/ai-gateway/src/providers/openai.ts b/packages/ai-gateway/src/providers/openai.ts
index f7378fff8..15fea9e62 100644
--- a/packages/ai-gateway/src/providers/openai.ts
+++ b/packages/ai-gateway/src/providers/openai.ts
@@ -54,6 +54,34 @@ export class OpenAIProvider implements AIProvider {
params.temperature = body.temperature;
}
+ // OpenAI keeps adding model families that reject `temperature` (and a few
+ // other sampling knobs). When upstream returns 400 "Unsupported value:
+ // 'temperature'" we drop the offending field and retry once instead of
+ // blowing up — much more robust than chasing the prefix allowlist as
+ // OpenAI ships new model names.
+ private isUnsupportedSamplingParamError(error: any): string | null {
+ if (error?.status !== 400) return null;
+ const msg = String(error?.message ?? error?.error?.message ?? '');
+ const match = msg.match(/Unsupported value: '(\w+)'/i);
+ return match?.[1] ?? null;
+ }
+
+ private async createWithUnsupportedParamRetry<T>(
+ params: ChatCompletionCreateParams,
+ invoke: (p: ChatCompletionCreateParams) => Promise<T>,
+ ): Promise<T> {
+ try {
+ return await invoke(params);
+ } catch (error: any) {
+ const unsupported = this.isUnsupportedSamplingParamError(error);
+ if (!unsupported) throw error;
+ const next = params as ChatCompletionCreateParams & Record<string, unknown>;
+ if (next[unsupported] === undefined) throw error;
+ delete next[unsupported];
+ return await invoke(next);
+ }
+ }
+
private applyTokenLimit(params: ChatCompletionCreateParams, body: RequestBody): void {
const maxTokens = body.max_completion_tokens ?? body.max_tokens;
if (maxTokens === undefined) return;
@@ -81,7 +109,9 @@ export class OpenAIProvider implements AIProvider {
this.applyGenerationOptions(params, body);
this.applyTokenLimit(params, body);
- const response = await this.client.chat.completions.create(params);
+ const response = await this.createWithUnsupportedParamRetry(params, (p) =>
+ this.client.chat.completions.create(p),
+ );
return new Response(JSON.stringify(this.formatResponse(response)), {
headers: { 'Content-Type': 'application/json' },
});
@@ -99,7 +129,9 @@ export class OpenAIProvider implements AIProvider {
this.applyGenerationOptions(params, body);
this.applyTokenLimit(params, body);
- const stream = await this.client.chat.completions.create(params);
+ const stream = await this.createWithUnsupportedParamRetry(params, (p) =>
+ this.client.chat.completions.create(p),
+ );
// Capture scope fields for the error path below — `this` inside the
// ReadableStream start() refers to the controller, not the provider.
@@ -183,7 +215,24 @@ export class OpenAIProvider implements AIProvider {
}
formatMessages(messages: Message[]): ChatCompletionMessage[] {
- return messages.map(
+ // Strip orphan tool-role messages (tool_call_id with no matching
+ // assistant tool_calls earlier in the array). Happens after Pi/chat
+ // history pruning or edits and triggers OpenAI 400 "messages with role
+ // 'tool' must be a response to a preceding message with 'tool_calls'".
+ const knownToolCallIds = new Set<string>();
+ const filtered: Message[] = [];
+ for (const msg of messages) {
+ if (msg.role === 'assistant' && Array.isArray((msg as any).tool_calls)) {
+ for (const call of (msg as any).tool_calls) {
+ if (call?.id) knownToolCallIds.add(call.id);
+ }
+ }
+ if (msg.role === 'tool' && msg.tool_call_id && !knownToolCallIds.has(msg.tool_call_id)) {
+ continue;
+ }
+ filtered.push(msg);
+ }
+ return filtered.map(
(msg) =>
({
role: msg.role,
@@ -233,8 +282,8 @@ export class OpenAIProvider implements AIProvider {
})
: msg.content,
tool_calls: msg.tool_calls,
+ tool_call_id: msg.tool_call_id,
name: msg.name,
- refusal: null,
} as ChatCompletionMessage)
);
}
diff --git a/packages/ai-gateway/src/providers/openrouter.ts b/packages/ai-gateway/src/providers/openrouter.ts
index 04efc17e6..e58f14495 100644
--- a/packages/ai-gateway/src/providers/openrouter.ts
+++ b/packages/ai-gateway/src/providers/openrouter.ts
@@ -180,8 +180,8 @@ export class OpenRouterProvider implements AIProvider {
})
: msg.content,
tool_calls: msg.tool_calls,
+ tool_call_id: msg.tool_call_id,
name: msg.name,
- refusal: null,
} as ChatCompletionMessage)
);
}
diff --git a/packages/ai-gateway/src/providers/vertex-maas.ts b/packages/ai-gateway/src/providers/vertex-maas.ts
index 8934b957d..04c877599 100644
--- a/packages/ai-gateway/src/providers/vertex-maas.ts
+++ b/packages/ai-gateway/src/providers/vertex-maas.ts
@@ -330,7 +330,44 @@ export class VertexMaasProvider implements AIProvider {
}
formatMessages(messages: Message[]): any[] {
- return messages.map((msg) => ({
+ // Drop orphan tool messages (tool_call_id with no matching assistant
+ // tool_calls earlier in the array, or a content `tool_result` part on
+ // a user/tool message whose id was never emitted). Vertex MaaS rejects
+ // the whole batch with 400 "No tool calls but found tool output" if
+ // even one orphan slips through — typically after chat history pruning
+ // or message edits.
+ const knownToolCallIds = new Set<string>();
+ const collectIds = (msg: Message) => {
+ if (msg.role !== 'assistant') return;
+ for (const call of ((msg as any).tool_calls ?? [])) {
+ if (call?.id) knownToolCallIds.add(call.id);
+ }
+ if (Array.isArray(msg.content)) {
+ for (const part of msg.content as any[]) {
+ if (part?.type === 'tool_use' && part.id) knownToolCallIds.add(part.id);
+ }
+ }
+ };
+ const isOrphanToolMessage = (msg: Message): boolean => {
+ if (msg.role === 'tool') {
+ return !!msg.tool_call_id && !knownToolCallIds.has(msg.tool_call_id);
+ }
+ if (Array.isArray(msg.content)) {
+ const hasToolResult = (msg.content as any[]).some((p) => p?.type === 'tool_result');
+ if (!hasToolResult) return false;
+ return (msg.content as any[]).every(
+ (p) => p?.type !== 'tool_result' || (p?.tool_use_id && !knownToolCallIds.has(p.tool_use_id)),
+ );
+ }
+ return false;
+ };
+ const filtered: Message[] = [];
+ for (const msg of messages) {
+ collectIds(msg);
+ if (isOrphanToolMessage(msg)) continue;
+ filtered.push(msg);
+ }
+ return filtered.map((msg) => ({
role: msg.role,
...this.formatMessageContent(msg),
...(msg.tool_call_id && { tool_call_id: msg.tool_call_id }),
diff --git a/packages/ai-gateway/src/test/openai-models.unit.test.ts b/packages/ai-gateway/src/test/openai-models.unit.test.ts
index e487ee881..c4f867d66 100644
--- a/packages/ai-gateway/src/test/openai-models.unit.test.ts
+++ b/packages/ai-gateway/src/test/openai-models.unit.test.ts
@@ -182,4 +182,82 @@ describe('OpenAI API accounting and routing', () => {
expect(params['temperature']).toBe(0.7);
expect(params['max_tokens']).toBe(32);
});
+
+ // Sentry SCREENPIPE-AI-PROXY-Z + -X: OpenAI 400 "Unknown parameter:
+ // 'messages[1].refusal'". The provider used to inject `refusal: null` on
+ // every outbound message — that field belongs to assistant *responses*,
+ // not request bodies, and newer endpoints reject it strictly.
+ it('does not inject refusal field on outbound messages', () => {
+ const provider = new OpenAIProvider('sk-test') as any;
+ const formatted = provider.formatMessages([
+ { role: 'user', content: 'hi' },
+ { role: 'assistant', content: 'hello' },
+ ]);
+ for (const msg of formatted) {
+ expect('refusal' in msg).toBe(false);
+ }
+ });
+
+ // Sentry SCREENPIPE-CLI / orphan tool messages — when chat history is
+ // pruned a tool-role message can survive without its originating
+ // assistant tool_calls, which OpenAI rejects with a 400.
+ it('drops orphan tool messages whose tool_call_id never appeared', () => {
+ const provider = new OpenAIProvider('sk-test') as any;
+ const formatted = provider.formatMessages([
+ { role: 'user', content: 'hi' },
+ { role: 'tool', content: 'ghost result', tool_call_id: 'call_ghost' },
+ { role: 'user', content: 'continue' },
+ ]);
+ expect(formatted).toHaveLength(2);
+ expect(formatted.map((m: any) => m.role)).toEqual(['user', 'user']);
+ });
+
+ // Sentry SCREENPIPE-AI-PROXY-Y: "400 Unsupported value: 'temperature'
+ // does not support 0.7 with this model. Only the default (1) is supported."
+ // New OpenAI models keep being added to the temperature-locked list. The
+ // retry strips the offending field and re-tries once, so we don't have to
+ // chase every new model prefix.
+ it('retries without temperature when OpenAI rejects it with 400', async () => {
+ const provider = new OpenAIProvider('sk-test') as any;
+ let attempts = 0;
+ let lastParams: Record<string, unknown> | null = null;
+ provider.client.chat.completions.create = mock(async (params: Record<string, unknown>) => {
+ attempts += 1;
+ lastParams = params;
+ if (attempts === 1) {
+ const err: any = new Error("400 Unsupported value: 'temperature' does not support 0.7 with this model. Only the default (1) value is supported.");
+ err.status = 400;
+ throw err;
+ }
+ return { choices: [{ message: { content: 'ok' } }] };
+ });
+
+ await provider.createCompletion({
+ model: 'gpt-future-reasoning',
+ messages: [{ role: 'user', content: 'hi' }],
+ temperature: 0.7,
+ });
+
+ expect(attempts).toBe(2);
+ expect(lastParams).not.toBeNull();
+ expect((lastParams as Record<string, unknown>)['temperature']).toBeUndefined();
+ });
+
+ it('does not retry when the 400 is about a different param than what was set', async () => {
+ const provider = new OpenAIProvider('sk-test') as any;
+ let attempts = 0;
+ provider.client.chat.completions.create = mock(async () => {
+ attempts += 1;
+ const err: any = new Error("400 Unsupported value: 'top_p' not allowed.");
+ err.status = 400;
+ throw err;
+ });
+
+ await expect(provider.createCompletion({
+ model: 'gpt-future-reasoning',
+ messages: [{ role: 'user', content: 'hi' }],
+ temperature: 0.7,
+ })).rejects.toThrow();
+ expect(attempts).toBe(1);
+ });
});
diff --git a/packages/ai-gateway/src/test/vertex-maas.unit.test.ts b/packages/ai-gateway/src/test/vertex-maas.unit.test.ts
index 606d32198..a961172a6 100644
--- a/packages/ai-gateway/src/test/vertex-maas.unit.test.ts
+++ b/packages/ai-gateway/src/test/vertex-maas.unit.test.ts
@@ -174,6 +174,45 @@ describe('VertexMaasProvider.formatMessages', () => {
expect(result[0].content).toEqual([{ type: 'text', text: 'hello' }]);
});
+
+ // Vertex MaaS 400 "No tool calls but found tool output" — see Sentry
+ // SCREENPIPE-AI-PROXY-13 (escalating, 22 users / 7d). Pi chats can prune
+ // or edit history mid-conversation, leaving a tool-role reply whose
+ // originating assistant tool_calls turn is gone. Vertex rejects the whole
+ // batch unless we drop the orphan.
+ it('drops orphan tool messages whose tool_call_id never appeared', () => {
+ const result = provider.formatMessages([
+ { role: 'user', content: 'hi' },
+ { role: 'tool', content: 'ghost result', tool_call_id: 'call_ghost' } as any,
+ { role: 'user', content: 'are you there?' },
+ ]);
+ expect(result).toHaveLength(2);
+ expect(result.map((m: any) => m.role)).toEqual(['user', 'user']);
+ });
+
+ it('keeps tool messages that reference a prior assistant tool_call', () => {
+ const result = provider.formatMessages([
+ { role: 'user', content: 'list files' },
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [{ id: 'call_42', type: 'function', function: { name: 'ls', arguments: '{}' } }],
+ } as any,
+ { role: 'tool', content: 'a.txt', tool_call_id: 'call_42' } as any,
+ { role: 'assistant', content: 'found a.txt' },
+ ]);
+ expect(result).toHaveLength(4);
+ expect(result[2]).toMatchObject({ role: 'tool', tool_call_id: 'call_42' });
+ });
+
+ it('drops orphan tool_result content parts on user messages', () => {
+ const result = provider.formatMessages([
+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'call_ghost', content: 'gone' }] as any },
+ { role: 'user', content: 'continue' },
+ ]);
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({ role: 'user' });
+ });
});
describe('promoteReasoningStream', () => {