一、前言
Spring AI实战初体验——实现可切换模型AI聊天助手-CSDN博客

如上,在上一篇博客,我们已经实现了spring ai对接本地大模型实现了聊天机器人,但是目前有个新需求:
- 上传某场所的图片,通过AI进行分析,描述图片里的内容以及存在的安全隐患
- 进一步通过AI分析场所的安全隐患如何治理,需要依据法律法规(联网)分析
最终效果如下所示:


由于目前了解到的本地大模型都无法实现上述的需求,于是这次借助了火山引擎平台来实现
https://console.volcengine.com/ark/
火山引擎目前新用户会赠送每个模型50万token的体验量,对于学习、测试用还是足够的
如下所示,本次对接的模型有 doubao-vision-pro(图片识别)和 deepseek-v3(联网分析)

整体的逻辑:
- 先传入图片到doubao模型,分析图片里的场所和存在的隐患
- 然后将1分析的文字结果传到deepseek-v3模型联网结合法律法规分析隐患的整改措施
二、创建应用
https://console.volcengine.com/ark/
如下所示,创建2个零代码应用


-
图片识别

-
联网分析

三、后端
1.SDK集成
如下图所示,火山引擎里部分模型像deepseek-v3是可以直接集成SDK来对接的

代码示例
@RestController
@RequestMapping("/huoShan")
public class HuoShanController {
private final ArkService service;
private final String imageAnalyzeBotId;
public HuoShanController(@Value("${ai.ark.apiKey}") String apiKey, @Value("${ai.ark.base-url}") String baseUrl, @Value("${ai.ark.image-analyze-botId}") String imageAnalyzeBotId) {
this.imageAnalyzeBotId = imageAnalyzeBotId;
this.service = ArkService.builder()
.dispatcher(new Dispatcher())
.connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS))
.baseUrl(baseUrl)
.apiKey(apiKey)
.build();
}
@PostMapping("/image/chat")
public ResponseEntity<String> imageChat(@RequestBody String userMessage) {
List<ChatMessage> messages = new ArrayList<>();
messages.add(ChatMessage.builder().role(ChatMessageRole.SYSTEM).content("你是一个对中国法律法规有深入理解的专家").build());
messages.add(ChatMessage.builder().role(ChatMessageRole.USER).content(userMessage).build());
BotChatCompletionRequest chatCompletionRequest = BotChatCompletionRequest.builder()
.botId(imageAnalyzeBotId)
.messages(messages)
.build();
BotChatCompletionResult chatCompletionResult = service.createBotChatCompletion(chatCompletionRequest);
StringBuilder result = new StringBuilder();
chatCompletionResult.getChoices().forEach(choice -> result.append(choice.getMessage().getContent()));
return ResponseEntity.ok(result.toString());
}
}
相关的apiKey、base-url、botId都可以从火山的API调用指南获取,获取完我们配置在application.yml里就可以从上面的代码获取
2.调用Rest API
有些模型例如doubao-pro-vision就没提供java SDK,所以需要采用直接调用rest api的方式来对接

代码示例
@PostMapping("/notStream")
public Mono<String> imageAnalysis(MultipartFile file) {
return imageAiService.imageAnalysisNotStream(file);
}
@Service
@Slf4j
public class ImageAiService {
@Value("${ai.ark.image-botId}")
private String MODEL;
private final WebClient webClient;
public ImageAiService(@Value("${ai.ark.apiKey}") String apiKey, @Value("${ai.ark.base-url}") String baseUrl) {
this.webClient = WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(HttpClient.create()))
.baseUrl(baseUrl)
.defaultHeader("Authorization", "Bearer "+ apiKey)
.build();
public Mono<String> imageAnalysisNotStream(MultipartFile file) {
// 压缩图片并转成 Base64 格式
String base64 = ImageCompressor.compressImageFileToBase64UnderSize(file, 400, 400, 100);
if (base64 == null || base64.isEmpty()) {
log.error("图片压缩失败");
return Mono.just("图片压缩失败");
}
// 构造请求体
Map<String, Object> body = new HashMap<>();
body.put("model", MODEL);
// 非流式返回
body.put("stream", false);
body.put("stream_options", Map.of("include_usage", true));
Map<String, Object> imageContent = Map.of(
"type", "image_url",
"image_url", Map.of("url", base64)
);
Map<String, Object> message = Map.of(
"role", "user",
"content", List.of(imageContent)
);
body.put("messages", List.of(message));
// 调用非流式接口,直接返回拼接后的完整结果字符串
return webClient.post()
.uri("/bots/chat/completions")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(body)
// 此时接口返回的是 JSON 数据,所以指定 JSON 类型
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(String.class)
.map(responseStr -> {
try {
// 解析返回结果,取出 assistant 返回的内容
JsonNode jsonNode = new ObjectMapper().readTree(responseStr);
// 此处根据实际返回结构调整解析逻辑
JsonNode contentNode = jsonNode.path("choices")
.get(0)
.path("message")
.path("content");
return contentNode.asText();
} catch (Exception e) {
8618



被折叠的 条评论
为什么被折叠?



