使用Spring AI 1.0.0-M1调用GPT-4o生成图片描述遇问题求助
问题诊断与修复
你的代码核心问题在于:你构造了包含图片媒体的UserMessage对象,但调用chatClient时只传递了消息的文本内容,图片媒体信息并没有被发送给GPT-4o,导致模型无法接收图片,因此返回无法查看的提示。
修正后的代码
将调用chatClient的代码行替换为直接传入完整的UserMessage对象,而不是仅传入文本内容:
@Autowired final ChatClient chatClient; @Override public String getDescription(MultipartFile file) throws IOException { OpenAiChatOptions chatOptions = OpenAiChatOptions.builder() .withModel(OpenAiApi.ChatModel.GPT_4_O.getValue()) .build(); Resource resource = new ByteArrayResource(file.getBytes()); var userMessage = new UserMessage( "Explain what do you see in this picture?", List.of(new Media(MimeTypeUtils.IMAGE_JPEG, resource))); // 修正:直接传入userMessage,而非仅文本内容 var response = chatClient.prompt().user(userMessage).call().chatResponse(); return response.getResult().getOutput().getContent(); }
额外注意事项
- 确保上传的文件确实是JPEG格式,若需支持多种图片类型,可通过
file.getContentType()动态获取MIME类型,避免硬编码MimeTypeUtils.IMAGE_JPEG。 - 检查Spring AI配置是否正确,包括OpenAI API密钥、端点地址等,确保密钥拥有GPT-4o的调用权限。
- Spring AI 1.0.0-M1是里程碑预览版本,可能存在未修复的bug,若问题仍存在,可考虑升级到后续稳定版本。
内容的提问来源于stack exchange,提问作者user2693135
相关产品推荐
相关产品推荐

