Skip to content

Commit 30256cb

Browse files
author
Zoo (VP)
committed
fix(mimo): retry once without strict tool schemas on endpoint rejection
MiMo sends tools through convertToolsForOpenAI(), which attaches a strict flag to every function tool. An OpenAI-compatible endpoint that doesn't support structured outputs rejects the request with a 400 and the turn fails outright. Mirror the existing parallel_tool_calls fallback: detect schema-rejection errors narrowly (400 status plus a mention of strict/additionalProperties in a tools context, so unrelated 400s like MiMo's missing-reasoning_content rejection are not retried) and retry once with the original schemas and no strict flag.
1 parent 8267250 commit 30256cb

2 files changed

Lines changed: 190 additions & 0 deletions

File tree

‎src/api/providers/__tests__/mimo.spec.ts‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,145 @@ describe("MimoHandler", () => {
489489
expect(textChunks[0].text).toBe("Retried")
490490
})
491491

492+
it("should retry without the strict flag when the endpoint rejects strict tool schemas", async () => {
493+
// First call rejects with a 400 error naming the strict field
494+
const rejectionError = Object.assign(new Error("400 - Unknown parameter: tools[0].function.strict"), {
495+
status: 400,
496+
})
497+
mockCreate.mockRejectedValueOnce(rejectionError)
498+
499+
// Second call (retry) succeeds
500+
mockCreate.mockImplementationOnce(async () => ({
501+
[Symbol.asyncIterator]: async function* () {
502+
yield {
503+
choices: [{ delta: { content: "Retried" }, index: 0 }],
504+
usage: null,
505+
}
506+
yield {
507+
choices: [{ delta: {}, index: 0, finish_reason: "stop" }],
508+
usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
509+
}
510+
},
511+
}))
512+
513+
const tools: OpenAI.Chat.ChatCompletionTool[] = [
514+
{
515+
type: "function",
516+
function: {
517+
name: "read_file",
518+
description: "Read a file",
519+
parameters: {
520+
type: "object",
521+
properties: { path: { type: "string" } },
522+
required: ["path"],
523+
},
524+
},
525+
},
526+
]
527+
528+
const messages: Anthropic.Messages.MessageParam[] = [
529+
{ role: "user", content: [{ type: "text", text: "Hello" }] },
530+
]
531+
532+
const chunks: ApiStreamChunk[] = []
533+
const stream = handler.createMessage("System prompt", messages, { taskId: "test-task", tools })
534+
for await (const chunk of stream) {
535+
chunks.push(chunk)
536+
}
537+
538+
expect(mockCreate).toHaveBeenCalledTimes(2)
539+
540+
// First call sent tools with the strict flag applied
541+
const firstCallParams = mockCreate.mock.calls[0][0]
542+
expect(firstCallParams.tools[0].function).toHaveProperty("strict")
543+
544+
// Retry stripped the strict flag but kept the original schema
545+
const retryCallParams = mockCreate.mock.calls[1][0]
546+
expect(retryCallParams.tools).toHaveLength(1)
547+
expect(retryCallParams.tools[0].function.name).toBe("read_file")
548+
expect(retryCallParams.tools[0].function).not.toHaveProperty("strict")
549+
expect(retryCallParams.tools[0].function.parameters).toEqual({
550+
type: "object",
551+
properties: { path: { type: "string" } },
552+
required: ["path"],
553+
})
554+
555+
const textChunks = chunks.filter((c) => c.type === "text")
556+
expect(textChunks[0].text).toBe("Retried")
557+
})
558+
559+
it("should retry without the strict flag when the endpoint rejects hardened schema fields", async () => {
560+
// 400 naming additionalProperties in a tools context
561+
const rejectionError = Object.assign(
562+
new Error("400 - Invalid tools: additionalProperties is not a supported field"),
563+
{ status: 400 },
564+
)
565+
mockCreate.mockRejectedValueOnce(rejectionError)
566+
567+
mockCreate.mockImplementationOnce(async () => ({
568+
[Symbol.asyncIterator]: async function* () {
569+
yield {
570+
choices: [{ delta: { content: "Retried" }, index: 0 }],
571+
usage: null,
572+
}
573+
yield {
574+
choices: [{ delta: {}, index: 0, finish_reason: "stop" }],
575+
usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
576+
}
577+
},
578+
}))
579+
580+
const tools: OpenAI.Chat.ChatCompletionTool[] = [
581+
{
582+
type: "function",
583+
function: { name: "read_file", description: "Read", parameters: {} },
584+
},
585+
]
586+
587+
const messages: Anthropic.Messages.MessageParam[] = [
588+
{ role: "user", content: [{ type: "text", text: "Hello" }] },
589+
]
590+
591+
const stream = handler.createMessage("System prompt", messages, { taskId: "test-task", tools })
592+
for await (const _chunk of stream) {
593+
// drain
594+
}
595+
596+
expect(mockCreate).toHaveBeenCalledTimes(2)
597+
const retryCallParams = mockCreate.mock.calls[1][0]
598+
expect(retryCallParams.tools[0].function).not.toHaveProperty("strict")
599+
})
600+
601+
it("should not retry schema-unrelated 400 errors", async () => {
602+
// A 400 about reasoning_content (not tool schemas) must NOT trigger
603+
// the strict-schema fallback.
604+
const rejectionError = Object.assign(
605+
new Error("400 - reasoning_content is required in multi-turn tool call conversations"),
606+
{ status: 400 },
607+
)
608+
mockCreate.mockRejectedValueOnce(rejectionError)
609+
610+
const tools: OpenAI.Chat.ChatCompletionTool[] = [
611+
{
612+
type: "function",
613+
function: { name: "read_file", description: "Read", parameters: {} },
614+
},
615+
]
616+
617+
const messages: Anthropic.Messages.MessageParam[] = [
618+
{ role: "user", content: [{ type: "text", text: "Hello" }] },
619+
]
620+
621+
await expect(async () => {
622+
const stream = handler.createMessage("System prompt", messages, { taskId: "test-task", tools })
623+
for await (const _chunk of stream) {
624+
// drain
625+
}
626+
}).rejects.toThrow()
627+
628+
expect(mockCreate).toHaveBeenCalledTimes(1)
629+
})
630+
492631
it("should send stream_options with include_usage", async () => {
493632
const messages: Anthropic.Messages.MessageParam[] = [
494633
{ role: "user", content: [{ type: "text", text: "Hello" }] },

‎src/api/providers/mimo.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,50 @@ function isParallelToolCallsRejected(error: unknown): boolean {
3434
return false
3535
}
3636

37+
/**
38+
* Detects whether an API error is specifically caused by the endpoint
39+
* rejecting the `strict` tool flag or a hardened strict-mode schema
40+
* (`additionalProperties: false`, forced `required`, ...). OpenAI-compatible
41+
* endpoints that don't support structured outputs typically return a 400
42+
* Bad Request naming the offending field.
43+
*
44+
* Detection is intentionally narrow (400 status plus a schema-specific
45+
* keyword) so unrelated 400s — e.g. MiMo's missing-reasoning_content
46+
* rejection — are NOT mistaken for schema rejections and retried pointlessly.
47+
*/
48+
function isStrictToolSchemaRejected(error: unknown): boolean {
49+
if (error instanceof Error) {
50+
const message = error.message.toLowerCase()
51+
const status = (error as { status?: number }).status
52+
if (status !== 400) {
53+
return false
54+
}
55+
if (message.includes("strict")) {
56+
return true
57+
}
58+
const mentionsTools = message.includes("tool") || message.includes("function")
59+
const mentionsSchemaField =
60+
message.includes("additionalproperties") || message.includes("additional_properties")
61+
return mentionsTools && mentionsSchemaField
62+
}
63+
return false
64+
}
65+
66+
/**
67+
* Removes the `strict` flag from function tools, keeping their original
68+
* (non-hardened) schemas. Used by the one-time retry fallback when an
69+
* endpoint rejects strict tool schemas.
70+
*/
71+
function stripStrictFromTools(tools: OpenAI.Chat.ChatCompletionTool[]): OpenAI.Chat.ChatCompletionTool[] {
72+
return tools.map((tool) => {
73+
if (tool.type !== "function") {
74+
return tool
75+
}
76+
const { strict: _omit, ...functionWithoutStrict } = tool.function
77+
return { ...tool, function: functionWithoutStrict }
78+
})
79+
}
80+
3781
/**
3882
* Filters a streamed delta so that only the FIRST tool call (index 0) survives.
3983
* MiMo v2.5 Pro ignores `parallel_tool_calls: false` and may emit multiple
@@ -205,6 +249,13 @@ export class MimoHandler extends OpenAiHandler {
205249
if (params.parallel_tool_calls !== undefined && isParallelToolCallsRejected(error)) {
206250
const { parallel_tool_calls: _omit, ...paramsWithoutParallel } = params
207251
stream = await this.client.chat.completions.create(paramsWithoutParallel as MiMoCompletionParams)
252+
} else if (params.tools !== undefined && isStrictToolSchemaRejected(error)) {
253+
// Fallback: if the endpoint rejects the strict tool flag or a
254+
// hardened strict-mode schema, retry once with the original
255+
// schemas and no strict flag. Build a new params object so the
256+
// rejected request is left untouched.
257+
const paramsWithoutStrict = { ...params, tools: stripStrictFromTools(tools ?? []) }
258+
stream = await this.client.chat.completions.create(paramsWithoutStrict)
208259
} else {
209260
throw handleProviderError(error, "MiMo")
210261
}

0 commit comments

Comments
 (0)