SpringAI是一个AI工程应用框架,旨在将Spring生态系统的设计原则(如可移植性和模块化设计)应用于AI领域。它推广使用Plain Old Java Object(POJO)作为AI应用程序的构建块,从而为Java开发者提供了一种更简洁的方式与人工智能进行交互。SpringAI的推出被认为是Java开发领域的一大福音,因为它结合了Spring生态系统的设计原则和模块化的概念,降低了接入大型语言模型(LLM)的学习成本。
下面演示如何基于springBoot和OpenAi接口实现ChatGPT:
1、创建Spring Ai工程
2、添加api配置
spring:
application:
name: spring-ai-chatgpt
ai:
openai:
api-key: xxxxxxxxxxxxxxxxxxxxxx(自己的api-key)
base-url: xxxxxxxxxxxxxxxxxxxxxx(自己的中转地址)
3、在controller里调用api
(1)使用chatClient
@Autowired
private ChatClient chatClient;
//chatclient
@GetMapping("/chat")
public String chat(@RequestParam("message") String message) {
return this.chatClient.prompt()
.user(message)
.call()
.content();
}
//chatclient流式访问
@GetMapping(value = "/stream", produces = "text/html;charset=UTF-8")
public Flux<String> chatStream(@RequestParam("message") String message) {
Flux<String> output = chatClient.prompt()
.user(message)
.stream()
.content();
return output;
}
@Configuration
public class AIConfig {
@Bean
ChatClient chatClient(ChatClient.Builder builder) {
return builder.defaultSystem("You are a friendly chat bot that answers question in the voice of a Pirate")
.build();
}
}
(2)使用chatModel
@Autowired
private ChatModel chatModel;
//ChatModel
@GetMapping(value = "/chat/model", produces = "text/html;charset=UTF-8")
public String chatModel(@RequestParam("message") String message) {
ChatResponse response = chatModel.call(
new Prompt(
message,
OpenAiChatOptions.builder()
.withModel("gpt-4-32k")
.withTemperature(0.8F)
.build()
));
return response.getResult().getOutput().getContent();
}
(3)文生图
@Autowired
private OpenAiImageModel openAiImageModel;
//文生图
@GetMapping(value = "/text2Img", produces = "text/html;charset=UTF-8")
public String text2Img(@RequestParam("message") String message) {
ImageResponse response = openAiImageModel.call(
new ImagePrompt(message,
OpenAiImageOptions.builder()
.withQuality("hd")
.withN(1)
.withHeight(1024)
.withWidth(1024).build())
);
return response.getResult().getOutput().getUrl();
}
(4)文生语音
@Autowired
private OpenAiAudioSpeechModel openAiAudioSpeechModel;
//文生语音
@GetMapping(value = "/text2audio", produces = "text/html;charset=UTF-8")
public String text2audit(@RequestParam("message") String message) {
OpenAiAudioSpeechOptions speechOptions = OpenAiAudioSpeechOptions.builder()
.withModel("tts-1")
.withVoice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY)
.withResponseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3)
.withSpeed(1.0f)
.build();
SpeechPrompt speechPrompt = new SpeechPrompt("大家下午好,我叫王大锤", speechOptions);
SpeechResponse response = openAiAudioSpeechModel.call(speechPrompt);
byte[] body = response.getResult().getOutput();
//将byte[]存为MP3文件
try {
writeByteArrayToMp3(body, System.getProperty("user.dir"));
} catch (IOException e) {
throw new RuntimeException(e);
}
return "ok";
}
public static void writeByteArrayToMp3(byte[] audioBytes, String outputFilePath) throws IOException {
//创建FileOutputStream实例
FileOutputStream fos = new FileOutputStream(outputFilePath + "/yuyin.mp3");
//将字节数组写入文件
fos.write(audioBytes);
//关闭文件输入流
fos.close();
}
(5)语音转文本
@Autowired
private OpenAiAudioTranscriptionModel openAiAudioTranscriptionModel;
//语音转文本
@GetMapping(value = "/text2audio", produces = "text/html;charset=UTF-8")
public String audio2text(@RequestParam("message") String message) {
OpenAiAudioApi.TranscriptResponseFormat responseFormat = OpenAiAudioApi.TranscriptResponseFormat.VTT;
OpenAiAudioTranscriptionOptions transcriptionOptions = OpenAiAudioTranscriptionOptions.builder()
.withResponseFormat(OpenAiAudioApi.TranscriptResponseFormat.TEXT)
.withTemperature(0f)
.withResponseFormat(responseFormat)
.build();
var audioFile = new ClassPathResource("/hello.mp3");
AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioFile, transcriptionOptions);
AudioTranscriptionResponse response = openAiAudioTranscriptionModel.call(transcriptionRequest);
return response.getResult().getOutput();
}
(6)多模态
@GetMapping("/mutil")
public String mutilModel(@RequestParam(value = "message", defaultValue = "你从这个图片中看到了什么呢") String message) throws IOException {
// 图片的二进制流
byte[] imageData = new ClassPathResource("/test.png").getContentAsByteArray();
var userMessage = new UserMessage(
message,
List.of(new Media(MimeTypeUtils.IMAGE_PNG, imageData))); //media
OpenAiChatOptions aiChatOptions = OpenAiChatOptions.builder()
.withModel(OpenAiApi.ChatModel.GPT_4_TURBO_PREVIEW.getValue())
.build();
ChatResponse response = chatModel.call(new Prompt(userMessage, aiChatOptions));
return response.getResult().getOutput().getContent();
}