grok2api icon indicating copy to clipboard operation
grok2api copied to clipboard

bug: Streaming tool_calls delta missing 'index' field causing AI_TypeValidationError

Open double2tea opened this issue 9 months ago • 0 comments

Bug 描述

流式响应中的 tool_calls delta 对象缺少必需的 index 字段,导致使用 Pydantic/严格模式验证的客户端抛出类型验证错误。

错误信息

AI_TypeValidationError: Type validation failed: Value: {\"id\":\"dfa23594-257f-4be3-8e23-a30e4423f9b7\",\"object\":\"chat.completion.chunk\",\"created\":1772105061,\"model\":\"grok-4.20-beta\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"id\":\"call_93236a2792f54f87ba85ba56\",\"type\":\"function\",\"function\":{\"name\":\"MiniMax-Voice_list_voices\",\"arguments\":\"{\\\"voice_type\\\": \\\"all\\\"}\"}}]}...\"}

错误详情: [{\"code\":\"invalid_union\",\"errors\":[[{\"expected\":\"number\",\"code\":\"invalid_type\",\"path\":[\"choices\",0,\"delta\",\"tool_calls\",0,\"index\"],\"message\":\"Invalid input: expected number, received undefined\"}]...

复现步骤

  1. 启用流式模式调用任意工具(如 MiniMax-Voice_list_voices,设置 stream: true)
  2. 观察流式返回的 chunks
  3. 发现 choices[0].delta.tool_calls[0].index 字段缺失

根因分析

根据 OpenAI 流式 tool_calls 规范,每个 tool_calls delta 项应包含:

  • index: 工具调用的索引号(number 类型,必需)
  • id: 工具调用 ID
  • type: 固定为 "function"
  • function: 函数对象,包含 name 和 arguments

当前 API 返回的 tool_calls delta 缺少 index 字段,导致严格遵循 schema 的客户端验证失败。

修复建议

在构建流式响应时,为每个 tool_calls delta 项添加 index 字段:

# 流式响应构建器中
tool_call_delta = {
    \"index\": 0,  # 添加此字段
    \"id\": tool_call.id,
    \"type\": \"function\",
    \"function\": {
        \"name\": tool_call.function.name,
        \"arguments\": tool_call.function.arguments
    }
}

环境信息

  • 模型: grok-4.20-beta
  • 客户端: OpenCode + Quotio 代理
  • API: 流式响应 (streaming)

double2tea avatar Feb 26 '26 11:02 double2tea