采用SpringCloudAliabaAI型式大模型LLM,进行生成式JavaAI应用开发,实现文生问答、图像和语音合成,Web应用页面交互展现。SpringBootGradle软件框架,Idea集成开发环境,API_Post嵌入插件一体测试。
1 工效展示[文生-答/图/音]
2 软件体系架构[SpringBootGradle]
3 Idea开发环境项目导入
4 SpringAlibabaAI依赖添加
5 application.yml调度配置
6 AI服务支撑
6.1 AI答/图/音服务接口编码
6.2 AI答/图/音服务实现编码
关键的LLM运用编码如下:
@Override
public String completion(String message) {
Prompt prompt = new Prompt(new UserMessage(message));
return chatClient.call(prompt).getResult().getOutput().getContent();
}
@Override
public ImageResponse genImg(String imgPrompt) {
var prompt = new ImagePrompt(imgPrompt);
return imageClient.call(prompt);
}
@Override
public Map<String, String> streamCompletion(String message) {
StringBuilder fullContent = new StringBuilder();
streamingChatClient.stream(new Prompt(message))
.flatMap(chatResponse -> Flux.fromIterable(chatResponse.getResults()))
.map(content -> content.getOutput().getContent())
.doOnNext(fullContent::append)
.last()
.map(lastContent -> Map.of(message, fullContent.toString()))
.block();
return Map.of(message, fullContent.toString());
}
@Override
public String genAudio(String text) {
var resWAV = speechClient.call(text);
return save(resWAV, SpeechSynthesisAudioFormat.WAV.getValue());
}
private String save(ByteBuffer audio, String type) { // 将语音保存到本地的方法
String currentPath = System.getProperty("user.dir");
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-HH-mm-ss");
String fileName = currentPath + File.separator + now.format(formatter) + "." + type;
File file = new File(fileName);
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(audio.array());
} catch (Exception e) {
throw new RuntimeException(e);
}
return fileName;
}
6.3 Saas服务/Web展现编码
核心的文生问答/音像部分的SaaS支撑编码如下:
private final TongYiService tongYiService;
public TongYiController(TongYiService tongYiService) {
this.tongYiService = tongYiService;
}
@GetMapping("/chat")
public String completion(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
return tongYiService.completion(message);
}
@GetMapping("/stream")
public Map<String, String> streamCompletion(@RequestParam(
value = "message", defaultValue = "请告诉我西红柿炖牛腩怎么做?") String message) {
return tongYiService.streamCompletion(message);
}
@GetMapping("/genImg")
public ImageResponse genImg(@RequestParam(value = "prompt",
defaultValue = "Painting a picture of blue water and blue sky.") String imgPrompt) {
return tongYiService.genImg(imgPrompt);
}
@GetMapping("/getImgUrl")
public String getImgUrl(@RequestParam(value = "prompt",
defaultValue = "Painting a picture of blue water and blue sky.") String imgPrompt) {
ImageResponse imageResponse =</