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

Spring AI配置OpenAI JSON响应报错:无ResponseFormat转换器

问题解析与解决方案

错误原因

spring.ai.openai.chat.options.responseFormat对应的ResponseFormat是一个复合对象(包含type及可选的json_schema字段),而非单纯的枚举字符串。直接配置JSON_SCHEMA或json_schema无法完成Spring属性绑定,导致类型转换失败。


场景1:仅要求返回合法JSON(无需自定义Schema)

如果只需要确保OpenAI返回有效的JSON格式,无需匹配特定结构,使用json_object类型即可,两种配置方式任选:

简化配置(Spring AI支持的快捷写法)

spring:
  ai:
    openai:
      chat:
        options:
          model: gpt-4o-mini
          temperature: 0.0
          response-format: json_object

注:Spring Boot属性绑定支持短横线命名(response-format)与Java类驼峰属性(responseFormat)自动映射。

完整对象配置

spring:
  ai:
    openai:
      chat:
        options:
          model: gpt-4o-mini
          temperature: 0.0
          responseFormat:
            type: json_object

场景2:需要匹配自定义JSON Schema(使用JSON_SCHEMA)

若要求响应严格匹配自定义Schema,必须完整配置ResponseFormat对象,包含type和json_schema字段:

spring:
  ai:
    openai:
      chat:
        options:
          model: gpt-4o-mini
          temperature: 0.0
          responseFormat:
            type: json_schema
            json_schema:
              name: "自定义内容结构"
              schema: |
                {
                  "type": "object",
                  "properties": {
                    "title": {"type": "string"},
                    "content": {"type": "string"},
                    "tags": {"type": "array", "items": {"type": "string"}}
                  },
                  "required": ["title", "content"]
                }

结合BeanOutputConverter的最优方案

你提到的编程式配置与BeanOutputConverter冲突问题,可通过**放弃配置文件手动设置responseFormat**解决:BeanOutputConverter会自动从Java类生成JSON Schema,并自动配置OpenAI的响应格式,既保留动态生成Schema的能力,又确保返回结构化JSON。示例代码:

@Service
public class AiContentService {

    private final OpenAiChatClient chatClient;

    public AiContentService(OpenAiChatClient chatClient) {
        this.chatClient = chatClient;
    }

    public Article generateArticle(String prompt) {
        Prompt aiPrompt = new Prompt(prompt);
        // 转换器自动处理Schema生成与响应格式配置
        return chatClient.call(aiPrompt, new BeanOutputConverter<>(Article.class));
    }

    // 目标结构化输出的Java类
    public static class Article {
        private String title;
        private String content;
        private List<String> tags;

        // Getter、Setter方法省略
    }
}

此方式下,配置文件仅需保留模型、温度等基础配置,无需设置responseFormat。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 20:03:16