Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(openai-compat): retry on the route another turn already picked (#7664)

Ooi Pin Junf0bcf6840eff
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index dc723fdc71..9b4b08ac1f 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -465,15 +465,15 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
onUsage?: TextGenerationOptions["onUsage"], variant?: string, threadId?: string,
): Promise<Completion> => {
for (;;) {
- let replied = false;
+ const attemptedRoute = routes.routeFor(model, tools.length > 0); let replied = false;
try {
- return await completeOn(routes.routeFor(model, tools.length > 0), messages, model, stream, signal, onDelta && ((text, kind) => {
+ return await completeOn(attemptedRoute, messages, model, stream, signal, onDelta && ((text, kind) => {
replied = true;
onDelta(text, kind);
}), tools, onUsage, variant, threadId);
} catch (error) {
if (!(error instanceof ModelRouteRefused) || replied || signal?.aborted) throw error;
- if (!routes.advance(model, error.refusal)) throw new ChatProtocolError(noRouteLeft(error.message));
+ if (routes.routeFor(model, tools.length > 0) === attemptedRoute && !routes.advance(model, error.refusal)) throw new ChatProtocolError(noRouteLeft(error.message));
console.warn(`${options.driverKind}: ${model} answered ${error.refusal}; now on ${routes.routeFor(model, true)}`);
}
}
diff --git a/server/drivers/openai-responses.test.ts b/server/drivers/openai-responses.test.ts
index 9e4c895692..5d5420dc4e 100644
--- a/server/drivers/openai-responses.test.ts
+++ b/server/drivers/openai-responses.test.ts
@@ -140,14 +140,15 @@ async function fixture(script: Script, apiUrl = OPENAI, models: unknown[] = [])
instance, recorder, calls, threadId, directory,
paths: () => calls.map((call) => call.path),
turn: async (input: Partial<SendTurnInput> = {}) => {
+ const id = input.threadId ?? threadId;
const seen = recorder.events.length;
- await instance.adapter.sendTurn({ threadId, text: "Store the receipt.", model: MODEL, integrations, approvalMode: "full", ...input });
+ await instance.adapter.sendTurn({ threadId: id, text: "Store the receipt.", model: MODEL, integrations, approvalMode: "full", ...input });
const end = await vi.waitFor(() => {
- const found = recorder.events.slice(seen).find((event) => event.type === "turn.completed");
+ const found = recorder.events.slice(seen).find((event) => event.type === "turn.completed" && event.threadId === id);
if (!found) throw new Error("turn still running");
return found;
}, { timeout: 10_000, interval: 10 });
- return { end, events: recorder.events.slice(seen) };
+ return { end, events: recorder.events.slice(seen).filter((event) => event.threadId === id) };
},
};
}
@@ -247,6 +248,68 @@ describe("a model that refuses tools over Chat Completions, at OpenAI's address"
expect(f.paths()).toEqual(["/v1/chat/completions", "/v1/responses", "/v1/responses"]);
});
+ it("retries a chat refusal on the route another turn already picked", async () => {
+ let held: ServerResponse | null = null;
+ let chats = 0;
+ const f = await fixture((call, response) => {
+ if (call.path.endsWith("/chat/completions")) {
+ chats += 1;
+ if (chats === 1) { held = response; return; }
+ const first = held;
+ held = response;
+ if (first) reject(first, 400, refusalOf(MODEL));
+ return;
+ }
+ answer(response, "Hello there.");
+ if (held) {
+ const loser = held;
+ held = null;
+ reject(loser, 400, refusalOf(MODEL));
+ }
+ });
+ const [left, right] = await Promise.all([f.turn({ threadId: randomUUID() }), f.turn({ threadId: randomUUID() })]);
+ expect([left, right].map((turn) => ({ ok: turn.end.type === "turn.completed" && turn.end.ok, error: failureOf(turn.events) }))).toEqual([{ ok: true, error: "" }, { ok: true, error: "" }]);
+ expect(f.paths()).toEqual(["/v1/chat/completions", "/v1/chat/completions", "/v1/responses", "/v1/responses"]);
+ });
+
+ it("retries a missing Responses route on the route another turn already picked", async () => {
+ let primed = false;
+ let held: ServerResponse | null = null;
+ let responses = 0;
+ const plain = (response: ServerResponse) => {
+ response.writeHead(200, { "content-type": "text/event-stream" });
+ response.write(`data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: "Plain." }, finish_reason: "stop" }] })}\n\n`);
+ response.end("data: [DONE]\n\n");
+ };
+ const f = await fixture((call, response) => {
+ if (!primed) {
+ if (call.path.endsWith("/chat/completions")) return reject(response, 400, refusalOf(MODEL));
+ primed = true;
+ return answer(response, "Primed.");
+ }
+ if (call.path.endsWith("/responses")) {
+ responses += 1;
+ if (responses === 1) { held = response; return; }
+ const first = held;
+ held = response;
+ if (first) reject(first, 404, "<html>Not found</html>");
+ return;
+ }
+ plain(response);
+ if (held) {
+ const loser = held;
+ held = null;
+ reject(loser, 404, "<html>Not found</html>");
+ }
+ });
+ expect(await f.turn()).toMatchObject({ end: { ok: true } });
+ const [left, right] = await Promise.all([f.turn({ threadId: randomUUID() }), f.turn({ threadId: randomUUID() })]);
+ expect([left, right].map((turn) => ({ ok: turn.end.type === "turn.completed" && turn.end.ok, error: failureOf(turn.events) }))).toEqual([{ ok: true, error: "" }, { ok: true, error: "" }]);
+ const raced = f.calls.slice(2);
+ expect(raced.map((call) => call.path)).toEqual(["/v1/responses", "/v1/responses", "/v1/chat/completions", "/v1/chat/completions"]);
+ expect(raced.slice(2).map((call) => call.body.reasoning_effort)).toEqual(["none", "none"]);
+ });
+
it("keeps the reasoning level the person picked when it moves to Responses", async () => {
const f = await fixture((call, response) => {
if (call.path.endsWith("/chat/completions")) reject(response, 400, refusalOf(MODEL));