点击上方“程序员蜗牛g”,选择“设为星标”跟蜗牛哥一起,每天进步一点点
程序员蜗牛g大厂程序员一枚 跟蜗牛一起 每天进步一点点31篇原创内容**公众号
Spring AI 的 Message API(消息接口) 为多模态大型语言模型(LLMs)提供了所有必要的抽象层支持,开发者可通过该接口实现跨模态数据的无缝整合与交互,无需底层适配即可构建支持文本、图像、音频等多输入源的AI应用。
接下来,我们将通过实例演示有关图片识别的实例。
2.实战案例
准备环境
<dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-model-openai</artifactId></dependency>
配置文件
spring: ai: openai: api-key: sk-xxxooo base-url: https://api.xty.app chat: options: model: gpt-4
图片分析
首先,我们准备如下的这张图片,我们对该图片进行分析,看看大模型能分析出什么内容来:
示例代码:
private final ChatClient chatClient ;@GetMapping("/image")public String image() { return this.chatClient .prompt() .user(u -> u.text("你看到了什么?") .media(MimeTypeUtils.IMAGE_PNG, new ClassPathResource("static/multimodal.test.png"))) .call() .content() ;}
输出结果
正确的分析出图片中的内容。
身份证识别
准备一张身份证,看看是否能正确的读取出身份证中的内容信息。
示例代码:
@GetMapping("/sfz")public String sfz() { String text = """ 输出该身份证中的姓名(name), 性别(sex), 民族(nation), 出生(birth), 住址(address), 身份证号码(idNo)。 最终以json格式输出。 """; return this.chatClient .prompt() .user(u -> { u.text(text) .media(MimeTypeUtils.IMAGE_PNG, new ClassPathResource("static/sfz.jpg")); }) .call() .content() ;}
输出结果
正确识别出身份证中的所有信息。
结构化输出
以下示例将演示通过上传汽车图片方式分析图片,并由系统以结构化 JSON 格式返回分析结果(例如各颜色,总数)。
定义数据模型
public record CarCount(List<CarColorCount> counts, int total) {}public record CarColorCount(String color, int count) {}
接着,定义如下Service 发送图片到OpenAI进行分析
@Servicepublic class CarCountService { private final ChatClient chatClient; public CarCountService(ChatClient.Builder chatClientBuilder) { this.chatClient = chatClientBuilder.build(); } public CarCount getCarCount(InputStream imageInputStream, String contentType, String colors) { String text = """ 1.统计图像中不同颜色车辆的数量 2.用户通过提示词(prompt)提供图像,并指定需统计的颜色 3.仅统计用户提示词中明确指定的颜色(忽略其他颜色) 4.过滤用户提示词中的非颜色信息(如无关文本或无效描述) 5.若用户提示词中未指定任何颜色,直接返回总数为 0 """ ; return chatClient.prompt() .system(systemMessage -> systemMessage .text(text)) .user(userMessage -> userMessage .text(colors) .media(MimeTypeUtils.parseMimeType(contentType), new InputStreamResource(imageInputStream))) .call() .entity(CarCount.class); }}
REST接口
@PostMapping("/count")public ResponseEntity<?> getCarCounts(@RequestParam("colors") String colors, @RequestParam("file") MultipartFile file) { try (InputStream inputStream = file.getInputStream()) { var carCount = carCountService.getCarCount(inputStream, file.getContentType(), colors); return ResponseEntity.ok(carCount) ; } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("图片上传失败"); }}
接下来,我们准备如下的图片
输出结果
如果这篇文章对您有所帮助,或者有所启发的话,求一键三连:点赞、转发、在看。
关注公众号:woniuxgg,在公众号中回复:笔记 就可以获得蜗牛为你精心准备的java实战语雀笔记,回复面试、开发手册、有超赞的粉丝福利!