Skip to content

Commit aae904f

Browse files
fix: OpenRouter tool_calls validation error with kimi-k2 model
Fixes AI_TypeValidationError when using OpenRouter's moonshotai/kimi-k2 model. The model returns tool_calls with type="" instead of type="function", causing validation failures in the AI SDK. Added response transformation to fix empty tool_call types in streaming responses. Fixes anomalyco#914 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 17fa8c1 commit aae904f

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

‎packages/opencode/src/provider/provider.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,60 @@ export namespace Provider {
202202
"HTTP-Referer": "https://opencode.ai/",
203203
"X-Title": "opencode",
204204
},
205+
async fetch(input: any, init: any) {
206+
const response = await fetch(input, init)
207+
208+
// For streaming responses, we need to transform the stream
209+
if (response.body && (response.headers.get('content-type')?.includes('text/plain') || response.headers.get('content-type')?.includes('text/event-stream'))) {
210+
const reader = response.body.getReader()
211+
const stream = new ReadableStream({
212+
start(controller) {
213+
function pump(): Promise<void> {
214+
return reader.read().then(({ done, value }) => {
215+
if (done) {
216+
controller.close()
217+
return
218+
}
219+
220+
// Parse and fix tool_calls type
221+
const text = new TextDecoder().decode(value)
222+
const lines = text.split('\n')
223+
const fixedLines = lines.map(line => {
224+
if (line.startsWith('data: ') && line !== 'data: [DONE]') {
225+
try {
226+
const data = JSON.parse(line.slice(6))
227+
if (data.choices?.[0]?.delta?.tool_calls) {
228+
for (const toolCall of data.choices[0].delta.tool_calls) {
229+
if (toolCall.type === "") {
230+
toolCall.type = "function"
231+
}
232+
}
233+
}
234+
return 'data: ' + JSON.stringify(data)
235+
} catch (e) {
236+
return line
237+
}
238+
}
239+
return line
240+
})
241+
242+
controller.enqueue(new TextEncoder().encode(fixedLines.join('\n')))
243+
return pump()
244+
})
245+
}
246+
return pump()
247+
},
248+
})
249+
250+
return new Response(stream, {
251+
status: response.status,
252+
statusText: response.statusText,
253+
headers: response.headers,
254+
})
255+
}
256+
257+
return response
258+
},
205259
},
206260
}
207261
},

0 commit comments

Comments
 (0)