spring boot 嵌入chatGPT步骤

一、需要良好的网络

二、需要在OpenAI官网https://openai.com/注册用户,并获取一个api-key,sk开头的

验证是否可用网站:http://tools.lbbit.top/check_key_valid/

三、spring boot 配置文件

复制代码
openai.proxyHost=127.0.0.1
openai.proxyPort=7890
openai.keys=sk-xxxxxxxxxx
openai.proxy=https://xxxxxxx/

四、新建配置类AiServiceFactory

复制代码
import com.fasterxml.jackson.databind.ObjectMapper;
import com.theokanning.openai.client.OpenAiApi;
import com.theokanning.openai.service.OpenAiService;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import retrofit2.Retrofit;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.time.Duration;

@Component
public class AiServiceFactory {


    @Value("${openai.proxyHost}")
    private String proxyHost;
    /**
     * 代理端口
     */
    @Value("${openai.proxyPort}")
    private Integer proxyPort;
    /**
     * openai apikey
     */
    @Value("${openai.keys}")
    private String token;

    @Value("${openai.proxy}")
    private String proxyIp;

    private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10L);

    public OpenAiService createService() {

        ObjectMapper mapper = OpenAiService.defaultObjectMapper();
        // 设置代理
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        OkHttpClient client = OpenAiService.defaultClient(token, DEFAULT_TIMEOUT).newBuilder()
                .proxy(proxy)
                .build();
        Retrofit retrofit = OpenAiService.defaultRetrofit(client, mapper).newBuilder().baseUrl(proxyIp).build();
        return new OpenAiService(retrofit.create(OpenAiApi.class), client.dispatcher().executorService());

    }
}

如果需要中转站代理的话,该类里面的方法如下

复制代码
public OpenAiService createService() {

        ObjectMapper mapper = OpenAiService.defaultObjectMapper();
        // 设置代理
//        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
//        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, 8080));
        OkHttpClient client = OpenAiService.defaultClient(token, DEFAULT_TIMEOUT).newBuilder()
//                .proxy(proxy)
                .build();
        Retrofit retrofit = OpenAiService.defaultRetrofit(client, mapper).newBuilder().baseUrl(proxyIp).build();
        //代理服务器,中转站
        return new OpenAiService(retrofit.create(OpenAiApi.class), client.dispatcher().executorService());

    }

五、测试控制器,当然也可以写进service层

复制代码
package com.example.springbootest3_2.controller;

import com.example.springbootest3_2.config.AiServiceFactory;
import com.theokanning.openai.completion.chat.*;
import com.theokanning.openai.service.OpenAiService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class OpenAiController {

    @Resource
    private AiServiceFactory aiServiceFactory;

    @PostMapping("/testChat")
    public String testChat(@RequestBody Map<String,String> params) throws UnsupportedEncodingException {

        OpenAiService service = aiServiceFactory.createService();
        final List<ChatMessage> messages = new ArrayList<>();
        final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.USER.value(),
                URLDecoder.decode(params.get("contents"),
                "UTF-8"));

        messages.add(systemMessage);
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest
                .builder()
                .model("gpt-3.5-turbo")
                .messages(messages)
                .temperature(0.5)
//                .n(1)
//                .maxTokens(50)
//                .logitBias(new HashMap<>())
                .build();


        ChatCompletionResult chatCompletionResult=service.createChatCompletion(chatCompletionRequest);
        List<ChatCompletionChoice> compList=chatCompletionResult.getChoices();
        StringBuilder sb = new StringBuilder();
        for (ChatCompletionChoice comp : compList) {
            sb.append(comp.getMessage().getContent());
        }
        return sb.toString();
    }

}
相关推荐
计算机毕设VX:Fegn08955 分钟前
计算机毕业设计|基于springboot + vue个人博客系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
独自破碎E23 分钟前
Spring Boot 3.x和2.x版本相比有哪些区别与改进?
java·spring boot·后端
幽络源小助理37 分钟前
SpringBoot+Vue美食网站系统源码 | Java餐饮项目免费下载 – 幽络源
java·vue.js·spring boot
Cache技术分享1 小时前
280. Java Stream API - Debugging Streams:如何调试 Java 流处理过程?
前端·后端
Charlie_Byte1 小时前
在 Kratos 中设置自定义 HTTP 响应格式
后端·go
Coder_Boy_1 小时前
基于SpringAI企业级智能教学考试平台考试模块全业务闭环方案
java·人工智能·spring boot·aiops
辜月十1 小时前
Conda配置文件.condarc
后端
真是他1 小时前
C# UDP 基本使用
后端
今天没有盐1 小时前
Python字符串操作全解析:从基础定义到高级格式化
后端·scala·编程语言
IT 行者1 小时前
Spring Framework 6.x 异常国际化完全指南:让错误信息“说“多国语言
java·后端·spring·异常处理·problemdetail·国际化i18n