You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Spring-AI与OpenRouter的Gemini模型实现工具调用?

问题:Spring-AI + OpenRouter 调用Gemini模型工具时出错

我使用spring-ai-openai-spring-boot-starter结合OpenRouter兼容OpenAI的统一API,实现工具调用并集成MCP服务器。测试Filesystem MCP Server时,openai/gpt-4o-mini模型可正常工作,但切换至google/gemini-2.5-pro-exp-03-25:free模型时,出现No choices returned警告,返回结果为null。

调用代码(Kotlin)

@Configuration
class Testing {
    @Bean
    fun demo(chat: ChatClient.Builder, provider: ToolCallbackProvider): ApplicationRunner {
        return ApplicationRunner {
            println(
                chat
                    .build()
                    .prompt("What folders does the current active user have on the desktop?")
                    .tools(provider)
                    .call()
                    .entity(Files::class.java)
            )
        }
    }

    data class Files(
        val desktopLocation: String,
        val files: List<String>
    )
}

配置文件(application.properties)

spring.ai.openai.chat.options.model=google/gemini-2.5-pro-exp-03-25:free
spring.ai.openai.base-url=https://openrouter.ai/api
spring.ai.openai.api-key=MY_TOKEN
spring.ai.mcp.client.stdio.servers-configuration=classpath:fs-config.json

注释掉最后一行MCP配置后,请求可正常返回但结果存在幻觉。原本两款模型均支持工具调用,现询问是否可配置Spring-AI使其支持除openai/gpt-4o-mini外的模型调用工具。

排查到的错误信息

{
  "error": {
    "code": 400,
    "message": "* GenerateContentRequest.tools[0].function_declarations[10].parameters.properties: should be non-empty for OBJECT type",
    "status": "INVALID_ARGUMENT"
  }
}

疑问:该问题属于Spring-AI的问题还是OpenRouter的问题?


解答

这个问题本质是Spring-AI生成的工具调用请求格式,未完全适配Gemini模型通过OpenRouter暴露的API要求:

  • Gemini的工具调用规范(经OpenRouter中转时)要求,OBJECT类型的参数必须包含非空的properties字段;
  • Spring-AI默认的工具格式转换逻辑是针对OpenAI模型优化的,未兼容Gemini的这一严格校验规则;
  • OpenRouter仅作为中转层转发请求,返回的是Gemini原生的错误提示,本身未修改请求结构,因此问题根源不在OpenRouter。

解决方向:

  • 升级Spring-AI至最新稳定版,查看是否已适配多模型工具调用格式;
  • 自定义工具描述生成逻辑,确保OBJECT类型参数的properties字段非空,覆盖Spring-AI默认转换;
  • 参考OpenRouter对应Gemini模型的文档,手动调整请求结构以匹配格式要求。

内容的提问来源于stack exchange,提问作者alturkovic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 15:54:58