小工具知识网

当前位置: 首页 > 行业知识 > 超级详细Spring AI+ChatGPT(java接入OpenAI大模型)

行业知识

超级详细Spring AI+ChatGPT(java接入OpenAI大模型)

2026-12-04 19:44:43 来源:互联网转载

Spring AI

对接各种AI大模型(AI工程领域的应用程序框架)

前期准备

API-Key:sk-3sfER03LDLG3SDFsdlwe283JSdw023lkrmrHDND32fmREKFD

(格式长这样,这个不可用)

免费使用

  • 申请领取内测免费API Key
  • 免费版支持gpt-3.5-turbo, embedding, gpt-4。其中gpt-4由于价格过高,每24小时限制10次调用,且不支持流式传输。需要更稳定快速的gpt-4请使用付费版。
  • 转发Host1: https://api.chatanywhere.tech (国内中转,延时更低,host1和host2二选一)
  • 转发Host2: https://api.chatanywhere.com.cn (国内中转,延时更低,host1和host2二选一)
  • 转发Host3: https://api.chatanywhere.cn (国外使用,国内需要全局代理)

    创建项目

    ​

    ​

    pom文件配置

        4.0.0            org.springframework.boot        spring-boot-starter-parent        3.2.5                 com.zzq    spring-ai-chat01        1.0.1-SNAPSHOT    spring-ai-chat01    spring-ai-chat01            17        1.0.0-SNAPSHOT                            org.springframework.boot            spring-boot-starter-web                            org.springframework.ai            spring-ai-openai-spring-boot-starter                            org.springframework.boot            spring-boot-devtools            runtime            true                            org.projectlombok            lombok            true                            org.springframework.boot            spring-boot-starter-test            test                                                    org.springframework.ai                spring-ai-bom                ${spring-ai.version}                pom                import                                                                org.springframework.boot                spring-boot-maven-plugin                                                                                        org.projectlombok                            lombok                                                                                                                spring-snapshot            Spring Snapshots            https://repo.spring.io/snapshot                            false                        

    ​

    配置application文件

    文件内容: 

    spring:  application:     name:spring-ai-01-chat  ai:    openai:     api-key: ${OPENAI_API_KEY}     base-url: ${OPENAI_API_URL}     chat:       option:         #model:gpt-4-32k         model:gpt-3.5-turbo         temperature:0.3F

    http://t.csdnimg.cn/32fqr小白如何设置openai api key的环境变量

    controller文件内容:

    生成文字

    package com.zzq.controller; import jakarta.annotation.Resource;import org.springframework.ai.chat.ChatResponse;import org.springframework.ai.chat.prompt.Prompt;import org.springframework.ai.openai.OpenAiChatClient;import org.springframework.ai.openai.OpenAiChatOptions;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import reactor.core.publisher.Flux; @RestControllerpublic class ChatController {    /**     * OpenAi自动装配,可以直接注入使用     */    @Resource    private OpenAiChatClient openAiChatClient;     /**     * 调用OpenAi的接口,call方法为同步的api     * @param msg 你要问的问题     * @return     */    @RequestMapping("/ai/chat")    public String chat(@RequestParam("msg") String msg) {        String called = openAiChatClient.call(msg);        return called;    }     /**     * 调用OpenAi的接口     * @param msg 你要问的问题     * @return  Object--json对象     */    @RequestMapping ("/ai/chat1")    public Object chat1(@RequestParam("msg") String msg) {        ChatResponse response = openAiChatClient.call(new Prompt(msg));        return response;//        return response.getResult().getOutput().getContent();//只拿到内容    }     /**     * 调用OpenAi的接口     * @param msg 你要问的问题     * @return     */    @RequestMapping ("/ai/chat3")    public String chat3(@RequestParam("msg") String msg) {        //可选参数在yml配置,同时在代码中也配置,那么会以代码为准        ChatResponse response = openAiChatClient.call(new Prompt(msg, OpenAiChatOptions.builder()//                .withModel("gpt-4-32k")//使用的模型,32k是参数量//参数量越高,准确率越高                .withTemperature(0.3F)//温度越高回答越慢,温度越低回答越快                .build()));        return response.getResult().getOutput().getContent();    }     /**     * 调用OpenAi的接口 stream是流式的api     * @param msg 你要问的问题     * @return     */    @RequestMapping ("/ai/chat4")    public Object chat4(@RequestParam("msg") String msg) {        //可选参数在yml配置,同时在代码中也配置,那么会以代码为准        Flux flux = openAiChatClient.stream(new Prompt(msg, OpenAiChatOptions.builder()//                .withModel("gpt-3.5")//使用的模型                .withTemperature(0.3F)//温度越高回答越慢,温度越低回答越快                .build()));        flux.toStream().forEach(chatResponse ->{            System.out.println(chatResponse.getResult().getOutput().getContent());        });        return flux.collectList();//数据的序列,一序列的数据,一个一个的数据返回    }} 

    spring-ai-02-image

    application文件内容(代码配置的会覆盖yml文件中的)

    更改可以生成image的api-key

    画图模型版本

    n:1(生成图片两张)

    height:1024(高度)

    width:1024(宽度)

    quality:hd(高清)

    spring:  application:     name:spring-ai-02-image  ai:    openai:     api-key: ${OPENAI_API_KEY}     base-url: ${OPENAI_API_URL}     image:        options:           model:gpt-4-dalle    

    controller内容:

    生成图片

    图片无法使用流式api

    package com.zzq.controller;import jakarta.annotation.Resource;import org.springframework.ai.image.ImageOptionsBuilder;import org.springframework.ai.image.ImagePrompt;import org.springframework.ai.image.ImageResponse;import org.springframework.ai.openai.OpenAiImageClient;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class ImageController {    @Resource    private OpenAiImageClient openAiImageClient;    @RequestMapping("/ai/image")    private Object image(@RequestParam(value="msg")String msg){        ImageResponse imageResponse=openAiImageClient.call(new ImagePrompt(msg));        System.out.println(imageResonse);//把图片进行业务处理        String imageUrl=return response.getResult().getOutput().getUrl();     return response.getResult().getOutput().getUrl();  /*  @GetMapping("/ai/draw")    public String drawImage(@RequestParam(value = "msg") String msg){        ImageResponse response = openAiImageClient.call(new ImagePrompt(msg,                ImageOptionsBuilder                        .builder()                        .withQuality("hd")//高清图像                        .withModel("dall-e-3") //绘画模型                        .withN(1) //生成图像的个数                        .withWidth(1024) //图像宽度 默认值                        .withHeight(1024) //图像高度 默认值                        .build()                )        );        //返回结果图片的地址        return response.getResult().getOutput().getUrl();*/    }}

    生成语音

    Ai音频转文本

    spring-ai-03-transcription

    更改可以生成声音的api-key

    声音模型版本

    application文件内容

    spring:  application:     name:spring-ai-03-trascription  ai:    openai:     api-key: ${OPENAI_API_KEY}     base-url: ${OPENAI_API_URL}    
    import jakarta.annotation.Resource;import org.springframework.ai.openai.OpenAiAudioSpeechClient;import org.springframework.ai.openai.OpenAiAudioTranscriptionClient;import org.springframework.core.io.ClassPathResource;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import static com.ysl.utisl.save2File.save2File;@RestControllerpublic class TranscriptionController {    @Resource    private OpenAiudioTranscriptionClient openAiAudioTranscriptionClient;    @RequestMapping(value="/ai/transcription")    public Object transcription(){          org,springframework.core.io.Resourse audioFile = new ClassPathResourse("文件名jfk.mp3")    String called = openAiAudioTranscriptiomClient.call(audioFile)    System.out.println(called);    return called;}/*@RestControllerpublic class TranscriptionController {    //将音频转文字时使用    @Resource    private OpenAiAudioTranscriptionClient transcriptionClient;    //将文字转语音时使用    @Resource    private OpenAiAudioSpeechClient speechClient;    /**     * 将音频转文字     * @return     */   /* @RequestMapping("/ai/transcription")    public Object transcription() {    //读取的是磁盘的路径    //FileSystemResource audioFile = new FileSystemResource("C:\Users\DELL\Desktop\luyin.m4a");        //读取的是classpath静态资源下的文件        ClassPathResource audioFile = new ClassPathResource("luyin.m4a");        String call = transcriptionClient.call(audioFile);        System.out.println(call);        return call;    }    /**     * 将文字转音频     * @return     */   /* @RequestMapping("/ai/tts")    public Object tts() {        String text = "Spring AI 是 AI 工程的应用框架。其目标是将 Spring 生态系统设计原则(如可移植性和模块化设计)应用于 AI,并推广使用 POJO 作为 AI 领域应用程序的构建块。 跨 AI 提供商的可移植 API 支持,适用于聊天、文本到图像和嵌入模型。支持同步和流 API 选项。还支持下拉以访问特定于模型的功能";        byte[] bytes = speechClient.call(text);        save2File("C:\Users\DELL\Desktop\test.mp3",bytes);        return "OK";    }*//*@RequestMapping("/ai/tts")    public Object tts() {        String text = "Spring AI 是 AI 工程的应用框架。其目标是将 Spring 生态系统设计原则(如可移植性和模块化设计)应用于 AI,并推广使用 POJO 作为 AI 领域应用程序的构建块。 跨 AI 提供商的可移植 API 支持,适用于聊天、文本到图像和嵌入模型。支持同步和流 API 选项。还支持下拉以访问特定于模型的功能";        byte[] bytes = openAiAudioSpeechClient..call(text);        FileUtilssave2File("C:\Users\DELL\Desktop\test.mp3",bytes);        return "OK";}*/}

    Spring Ai---多模态

    多模态API

    多模态是指模型同时理解和处理来自各种来源信息的能力,包括文本、图像、音频和其他数据格式

    多模型大语言(LLM)特征使模型能够结合其他模态(如图像、音频或视频)来处理和生成文本

    spring-ai-05-multimodel

    package com.zzq.controller;import jakarta.annotation.Resource;import org.springframework.ai.chat.ChatClient;import org.springframework.ai.chat.ChatResponse;import org.springframework.ai.chat.messages.Media;import org.springframework.ai.chat.messages.UserMessage;import org.springframework.ai.chat.prompt.Prompt;import org.springframework.ai.openai.OpenAiChatOptions;import org.springframework.ai.openai.api.OpenAiApi;import org.springframework.util.MimeTypeUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestControllerpublic class MultiModelController {@Resource    private ChatClient chatClient;@RequestMapping(value = "/ai/multi")    public  Object multi(String msg,String imageUrl){    UserMessage userMessage=new UserMessage(msg,            List.of(new Media(MimeTypeUtils.IMAGE_PNG,imageUrl))            );    ChatResponse response=chatClient.call(new Prompt(List.of(userMessage),            OpenAiChatOptions.builder()                    .withModel(OpenAiApi.ChatModel.GPT_4_VISION_PREVIEW.getValue())                    .build()            ));    return response.getResult().getOutput().getContent();}}

上一篇:Visual Studio Code配置Tomcat运行Java Web项目

下一篇:服务器nat怎么关闭?