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

Spring AI OpenAI ChatCompletion响应JSON解析错误求助

问题原因与解决方案

核心原因

  1. 无效的OpenAI API密钥:配置文件中spring.ai.openai.api-key=key是占位符,未替换为真实有效的API密钥。密钥无效时,OpenAI返回的响应并非预期的JSON格式(可能为空或错误内容),导致Jackson解析时触发EOF异常。
  2. Spring AI版本问题:使用的1.0.0-M2是里程碑预览版本,存在潜在的兼容性或功能bug,尤其是在处理JSON Schema响应格式的场景下。
  3. DTO字段拼写错误:OpenAiResponseDto中firstFeield存在拼写错误(应为firstField),虽不是当前解析错误的直接原因,但会导致后续字段映射失败。

解决方案

  • 替换真实API密钥:将application.properties中的spring.ai.openai.api-key=key替换为OpenAI平台获取的有效API密钥,确保密钥有足够的调用额度和权限。
  • 升级Spring AI到稳定版:修改build.gradle中的springAiVersion为稳定版本(如1.0.0或最新正式版),避免预览版的bug:
    ext {
        set('springAiVersion', "1.0.0")
    }
    
  • 修复DTO字段拼写:修正OpenAiResponseDto中的字段拼写错误:
    @JsonIgnoreProperties(ignoreUnknown = true)
    @Builder
    public record OpenAiResponseDto(
            @JsonProperty(required = true, value = "firstField")
            String firstField,
            @JsonProperty(required = true, value = "secondField")
            String secondField,
            @JsonProperty(required = true, value = "thirdField")
            String thirdField,
            @JsonProperty(required = true, value = "fourthField")
            String fourthField
    ) {
    }
    
  • 调试原始响应:添加日志打印OpenAI返回的原始响应内容,确认响应格式是否正确:
    ChatResponse response = openAiChatModel.call(prompt);
    // 打印原始响应
    System.out.println("Raw response: " + response.getResult().getOutput().getContent());
    String content = response.getResult().getOutput().getContent();
    return outputConverter.convert(content);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 16:03:17