SpringBoot整合OpenAI实现AI聊天 (精简demo)

1. OpenAI官网


    /**
     * 官网获取密钥基本条件
     * 
     * 1. , 能访问外网
     * 2. 拥有国外手机号码
     * 3. 注册账号
     * 4. 获取密钥
     */


https://openai.com/

2. 获取OpenAI密钥 (怎么简单怎么来)
// 直接在淘宝上购买, 买多几个随机访问 
sk-xxxx
 
  

3. 依赖

	com.alibaba.fastjson2
	fastjson2
	2.0.32


	cn.hutool
	hutool-all
	5.3.3

4. Message
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Message {

    private String role;
    private String content;
}

5. Choices
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Choices {

    private Message message;
}

6. RequestBody
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;


@Data
@AllArgsConstructor
@NoArgsConstructor
public class RequestBody {

    private String model;
    private List messages;
}

7. ResponseBody
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResponseBody {

    private List choices;
}

8. OpenAiUtils
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Component
public class OpenAiUtils {


    private static final String URL = "https://api.openai.com/v1/chat/completions";
    private static final String API_KEY = "sk-xxx";

    public String getAiRespondBody(String content) {
        log.info("用户提问内容: {}", content);
        // 代理IP地址
        String proxyHost = "127.0.0.1";
        // 代理端口号
        int proxyPort = 2802;
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        List list = new ArrayList<>();
        Message message = new Message();
        message.setRole("user");
        message.setContent(content);
        list.add(message);
        RequestBody requestBody = new RequestBody();
        requestBody.setModel("gpt-3.5-turbo");
        requestBody.setMessages(list);
        String data = JSON.toJSONString(requestBody);
        String resJSON = HttpRequest.post(URL)
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + API_KEY)
                .body(data)
                .setProxy(proxy)
                .execute()
                .body();
        ResponseBody body = JSON.parseObject(resJSON, ResponseBody.class);
        String outputContent = body.getChoices().get(0).getMessage().getContent();
        log.info("AI回复结果: {}",outputContent);
        return outputContent;
    }
}
后的代理服务器

SpringBoot整合OpenAI实现AI聊天 (精简demo)_第1张图片

9. OpenAIController
import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * OpenAI 聊天
 */
@RestController
public class OpenAIController {

    @Autowired
    private OpenAiUtils openAiUtils;

    @ApiOperation("用户提问-AI回复")
    @PostMapping("/auth/ai")
    public AjaxResult getAiRespondBody(@RequestBody String content){
        String respContent =openAiUtils.getAiRespondBody(content);
        return AjaxResult.success("操作成功",respContent);
    }
}

10. 测试, 响应结果
用户提问内容: {	"content":"现在的食盐还能吃吗?"}

AI回复结果: 现在的食盐是可以安全食用的。食盐主要由钠和氯化物组成,经过加工和质量控制确保无害。然而,过量摄入盐可能对健康有害,因此应遵循适量食用的原则。根据世界卫生组织的建议,成年人每天的钠摄入量不应超过5克。适量食用食盐可以满足身体对钠的需求,但过量食用可能与高血压、心脏病和中风风险增加相关。如果你有特殊的健康状况或需求,建议咨询医生或营养师的建议。

SpringBoot整合OpenAI实现AI聊天 (精简demo)_第2张图片

你可能感兴趣的:(OpenAI,人工智能,java)