Spring AI OpenAI ChatCompletion响应JSON解析错误求助
问题原因与解决方案
核心原因
- 无效的OpenAI API密钥:配置文件中
spring.ai.openai.api-key=key是占位符,未替换为真实有效的API密钥。密钥无效时,OpenAI返回的响应并非预期的JSON格式(可能为空或错误内容),导致Jackson解析时触发EOF异常。 - Spring AI版本问题:使用的
1.0.0-M2是里程碑预览版本,存在潜在的兼容性或功能bug,尤其是在处理JSON Schema响应格式的场景下。 - 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
相关产品推荐
相关产品推荐

