Skip to content

fix: Robust handling of array-based tool responses for Gemini compatibility - #17

Merged
bbbugg merged 2 commits into
mainfrom
fix/openai-tool
Jan 14, 2026
Merged

fix: Robust handling of array-based tool responses for Gemini compatibility#17
bbbugg merged 2 commits into
mainfrom
fix/openai-tool

Conversation

@bbbugg

@bbbugg bbbugg commented Jan 14, 2026

Copy link
Copy Markdown
Member

English Version

Problem

Gemini API requires the functionResponse.response field to be a JSON Object (Struct), but many tools (like MCP) return an Array [...]. This mismatch caused a 400 INVALID_ARGUMENT error, especially when the tool response contained multiple items or mixed content types (e.g., text + images).

Solution

Updated FormatConverter.js to intelligently handle array-based responses:

  1. Single Item:

    • If the array contains a single valid object, it is unwrapped and used directly. This preserves the cleanest structure for Gemini.
  2. Multiple/Mixed Items:

    • If the array contains multiple items or mixed types, the entire array is JSON-stringified and wrapped in a { result: "..." } object.
    • Benefit: prevents data loss (e.g., images, logs) and ensures valid API requests (200 OK).

中文版本

问题

Gemini API 要求 functionResponse.response 字段必须是一个 JSON 对象(Struct),但许多工具(如 MCP)返回的是数组 [...]。这种格式不匹配导致了 400 INVALID_ARGUMENT 错误,特别是在工具响应包含多个项目或混合内容类型(如文本+图片)时。

解决方案

更新了 FormatConverter.js 以智能处理数组格式的响应:

  1. 单项数据 (Single Item):

    • 如果数组包含单个有效对象,直接将其解包使用。这为 Gemini 保留了最清晰的结构。
  2. 多项/混合数据 (Multiple/Mixed Items):

    • 如果数组包含多个项目或混合类型,将整个数组 JSON 序列化并封装在 { result: "..." } 对象中。
    • 优势:防止数据丢失(如图片、日志),并确保 API 请求合法(200 OK)。

@bbbugg
bbbugg requested a review from Copilot January 14, 2026 10:24

This comment was marked as resolved.

@bbbugg
bbbugg requested a review from Copilot January 14, 2026 10:43

This comment was marked as resolved.

@bbbugg
bbbugg merged commit a959661 into main Jan 14, 2026
1 check passed
@bbbugg
bbbugg deleted the fix/openai-tool branch January 14, 2026 18:51
@bbbugg bbbugg added the 🐛 Bug Something isn't working label Jan 16, 2026
@github-actions

Copy link
Copy Markdown

🎉 此 PR 的修改已在版本 v0.4.0 中发布。
🎉 The changes in this PR have been released in version v0.4.0.

@iBUHub iBUHub deleted a comment from github-actions Bot Jan 18, 2026
ouni3 pushed a commit to ouni3/AIStudioToAPI that referenced this pull request Aug 20, 2026
…bility (iBUHub#17)

* fix: enhance tool response handling for array formats in FormatConverter

* fix: improve robustness of tool response handling in FormatConverter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐛 Bug Something isn't working

Projects

None yet

2 participants