使用 Spring Boot 创建自己的 ChatGPT 应用程序

开发 架构
在这篇短文中,我们了解了 OpenAI 的 GPT 3.5 Turbo 模型。如何生成供个人使用的密钥。然后,我们还研究了将常用的 Spring Boot 应用程序与 OpenAI 聊天完成 API 集成、对端点进行实际调用,并验证了响应。

在本篇文中,将解释如何与OpenAI聊天完成 API 集成以使用它们并创建自己的 ChatGPT 版本。将使用Spring Boot程序与ChatGPT的 开放API集成。

我们将Spring Boot程序公开一个 REST 端点,它将以requestParam的形式发起请求,然后对其进行处理,并以可读的文本格式返回响应。

让我们按照以下步骤操作:

前提条件

我们将使用OpenAI的ChatGPT完成API在我们程序里的调用。

该API的各个重要参数描述如下:

模型: 我们将向“gpt-3.5-turbo”发送请求

GPT-3.5 Turbo是一种极其强大的人工智能驱动的语言模型。它拥有 8192 个处理器核心和多达 3000 亿个参数,是迄今为止最大的语言模型之一。在广泛的自然语言处理任务中表现优秀,可以用于生成文章、回答问题、对话、翻译和编程等多种应用场景。它的能力使得人们可以通过自然语言与计算机进行更加自然、灵活和高效的交互。

Messages 这表示发送到模型的实际请求类,以便模型可以解析消息并以人们可读的格式生成相应的响应。

包含两个子属性:

role 指定消息的发送者(请求时为“user”,响应时为“assistant”)。

content: 这才是真正的消息。

Message DTO 如下所示:

public class Message {
    private String role;
    private String content;
    // getters & setters
}

话不多说,让我们开始与我们的 Spring Boot 应用程序集成。

创建一个基本的 Spring Boot 应用程序。为此,请前往start.spring.io并使用以下选择:
我们只需要 Spring Web 依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

创建一个Controller 代码:

package com.akash.mychatGPT.controller;

import com.akash.mychatGPT.dtos.ChatRequest;
import com.akash.mychatGPT.dtos.ChatResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ChatController {

    @Qualifier("openaiRestTemplate")
    @Autowired
    private RestTemplate restTemplate;

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

    @Value("${openai.api.url}")
    private String apiUrl;

    @GetMapping("/chat")
    public String chat(@RequestParam String prompt) {
        // 创建请求
        ChatRequest request = new ChatRequest(model, prompt, 1, 1.1);

        // 调用API
        ChatResponse response = restTemplate.postForObject(apiUrl, request, ChatResponse.class);

        if (response == null || response.getChoices() == null || response.getChoices().isEmpty()) {
            return "No response";
        }

        // 返回响应
        return response.getChoices().get(0).getMessage().getContent();
    }
}

创建一个ChatRequest类:

package com.akash.mychatGPT.dtos;

import java.util.ArrayList;
import java.util.List;

public class ChatRequest {

    private String model;
    private List<Message> messages;
    private int n;// 如果我们想增加要生成的响应的数量,可以指定。默认值为1。
    private double temperature;// 控制响应的随机性。默认值为1 (大多数随机)。
     
    // 构造方法, Getters & setters
}

在这里,我们使用以下属性,将其放入 application.properties 中:

openai.model=gpt-3.5-turbo
openai.api.url=https://api.openai.com/v1/chat/completions
openai.api.key=<generated_key_goes_here>

重要提示:关于 OpenAI API 密钥的说明:

OpenAI 允许生成唯一的 API 密钥来使用 OpenAI API。为此,请点击(
https://platform.openai.com/account/api-keys)。在这里,需要注册并创建 API 密钥(如下面的快照所示)。确保保证其安全,一定保存好!

单击“创建新密钥”并按照屏幕上的步骤操作。就可以拥有了自己的 OpenAI API 密钥。如果没有注册过,想体验一下的话,私信我发你体key。

接下来,我们用于RestTemplate调用 OpenAI API URL。因此,让我们添加一个拦截器,如下所示:

package com.akash.mychatGPT.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class OpenAIRestTemplateConfig {

    @Value("${openai.api.key}")
    private String openaiApiKey;

    @Bean
    @Qualifier("openaiRestTemplate")
    public RestTemplate openaiRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getInterceptors().add((request, body, execution) -> {
            request.getHeaders().add("Authorization", "Bearer " + openaiApiKey);
            return execution.execute(request, body);
        });
        return restTemplate;
    }
}

拦截器拦截请求并将 OpenAI API 密钥添加到请求标头中。

就是这样,现在我们可以简单地使用主类运行应用程序并开始调用 API。

package com.akash.mychatGPT;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyChatGptApplication {

	public static void main(String[] args) {
		SpringApplication.run(MyChatGptApplication.class, args);
	}

}

测试

本次使用Postman 进行演示。将想要问的问题传递给该模型。

例子#1

http://localhost:8080/chat?prompt=what are some good Spring Boot libraries。

例子#2

GPT 3.5 Turbo 模型足够先进,可以表现出高度真实的响应。(由于有数十亿行文本,该模型已经过训练)。

注意:对 OpenAI API curl 的实际调用如下所示:

curl --location 'https://api.openai.com/v1/chat/completions' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer $OPENAI_API_KEY' \
--data '{
    "model": "gpt-3.5-turbo",
    "messages": [
        {
            "role": "user",
            "content": "Hello!"
        }
    ]
}'

注意事项

在开发应用程序时,以下是可能遇到的常见问题。

问题1:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.akash.mychatGPT.Message` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 10, column: 9] (through reference chain: com.akash.mychatGPT.ChatResponse["choices"]->java.util.ArrayList[0]->com.akash.mychatGPT.ChatResponse$Choice["message"])

确保创建一个无参数构造函数,并为以下对象提供 getter 和 setter:

问题2:

org.springframework.web.client.HttpClientErrorException$TooManyRequests: 429 Too Many Requests: 
"{<EOL>    "error": {<EOL>        "message": "You exceeded your current quota, please check your plan and billing details.",<EOL>        "type": "insufficient_quota",<EOL>        "param": null,<EOL>        "code": null<EOL>    }<EOL>}<EOL>"

OpenAI 提供了基本配额。当前电子邮件 ID 的配额已用完,需要使用了新的电子邮件 ID。

问题3:

org.springframework.web.client.HttpClientErrorException$TooManyRequests: 429 Too Many Requests: "{<EOL>    "error": {<EOL>        "message": "Rate limit reached for default-gpt-3.5-turbo in organization org-V9XKg3mYkRRTJhHWq1lYjVtS on requests per min. Limit: 3 / min. Please try again in 20s. Contact us through our help center at help.openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method.",<EOL>        "type": "requests",<EOL>        "param": null,<EOL>        "code": null<EOL>    }<EOL>}<EOL>"

一段时间后尝试调用 API。(为了安全起见,良好的工作时间是 30 分钟)。

总结

在这篇短文中,我们了解了 OpenAI 的 GPT 3.5 Turbo 模型。如何生成供个人使用的密钥。

然后,我们还研究了将常用的 Spring Boot 应用程序与 OpenAI 聊天完成 API 集成、对端点进行实际调用,并验证了响应。

注意事项

OpenAI 的 API 是受监管的资源。我们对 API 的调用量是有限的,可以在此处进行跟踪。

责任编辑:姜华 来源: 今日头条
相关推荐

2023-04-18 10:47:32

2012-04-26 13:48:56

iPhone应用发布Ad Hoc

2023-12-10 14:43:30

PythonGUIeel

2023-09-21 08:00:00

ChatGPT编程工具

2023-04-11 16:04:19

Spring Boo端点运维

2011-07-21 15:37:40

jQuery MobiJQMJSON

2013-06-24 10:21:47

面向对象Web应用JavaScript

2023-03-01 13:54:53

Springpostion​继承

2024-01-05 07:38:55

2022-02-18 08:43:19

Spring Boo应用程序RabbitMQ

2020-10-18 08:51:18

Spring Boot

2023-05-11 12:40:00

Spring控制器HTTP

2013-06-26 08:52:12

2024-01-15 08:03:10

JVM内存工作效率

2009-01-19 11:07:42

C#Web.NET

2009-07-23 14:25:03

ASP.NET 2.0

2011-05-11 10:58:39

iOS

2009-06-22 09:06:31

Android用户应用程序

2011-06-21 10:28:17

Qt Visual C++

2021-08-30 20:19:55

应用程序
点赞
收藏

51CTO技术栈公众号