使用 Spring Boot 創(chuàng)建自己的 ChatGPT 應(yīng)用程序
在本篇文中,將解釋如何與OpenAI聊天完成 API 集成以使用它們并創(chuàng)建自己的 ChatGPT 版本。將使用Spring Boot程序與ChatGPT的 開放API集成。
我們將Spring Boot程序公開一個 REST 端點,它將以requestParam的形式發(fā)起請求,然后對其進(jìn)行處理,并以可讀的文本格式返回響應(yīng)。
讓我們按照以下步驟操作:
前提條件
我們將使用OpenAI的ChatGPT完成API在我們程序里的調(diào)用。
該API的各個重要參數(shù)描述如下:
模型: 我們將向“gpt-3.5-turbo”發(fā)送請求
GPT-3.5 Turbo是一種極其強(qiáng)大的人工智能驅(qū)動的語言模型。它擁有 8192 個處理器核心和多達(dá) 3000 億個參數(shù),是迄今為止最大的語言模型之一。在廣泛的自然語言處理任務(wù)中表現(xiàn)優(yōu)秀,可以用于生成文章、回答問題、對話、翻譯和編程等多種應(yīng)用場景。它的能力使得人們可以通過自然語言與計算機(jī)進(jìn)行更加自然、靈活和高效的交互。
Messages: 這表示發(fā)送到模型的實際請求類,以便模型可以解析消息并以人們可讀的格式生成相應(yīng)的響應(yīng)。
包含兩個子屬性:
role: 指定消息的發(fā)送者(請求時為“user”,響應(yīng)時為“assistant”)。
content: 這才是真正的消息。
Message DTO 如下所示:
public class Message {
private String role;
private String content;
// getters & setters
}
話不多說,讓我們開始與我們的 Spring Boot 應(yīng)用程序集成。
創(chuàng)建一個基本的 Spring Boot 應(yīng)用程序。為此,請前往start.spring.io并使用以下選擇:
我們只需要 Spring Web 依賴項:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
創(chuàng)建一個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) {
// 創(chuàng)建請求
ChatRequest request = new ChatRequest(model, prompt, 1, 1.1);
// 調(diào)用API
ChatResponse response = restTemplate.postForObject(apiUrl, request, ChatResponse.class);
if (response == null || response.getChoices() == null || response.getChoices().isEmpty()) {
return "No response";
}
// 返回響應(yīng)
return response.getChoices().get(0).getMessage().getContent();
}
}
創(chuàng)建一個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;// 如果我們想增加要生成的響應(yīng)的數(shù)量,可以指定。默認(rèn)值為1。
private double temperature;// 控制響應(yīng)的隨機(jī)性。默認(rèn)值為1 (大多數(shù)隨機(jī))。
// 構(gòu)造方法, 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>
重要提示:關(guān)于 OpenAI API 密鑰的說明:
OpenAI 允許生成唯一的 API 密鑰來使用 OpenAI API。為此,請點擊(
https://platform.openai.com/account/api-keys)。在這里,需要注冊并創(chuàng)建 API 密鑰(如下面的快照所示)。確保保證其安全,一定保存好!
單擊“創(chuàng)建新密鑰”并按照屏幕上的步驟操作。就可以擁有了自己的 OpenAI API 密鑰。如果沒有注冊過,想體驗一下的話,私信我發(fā)你體key。
接下來,我們用于RestTemplate調(diào)用 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 密鑰添加到請求標(biāo)頭中。
就是這樣,現(xiàn)在我們可以簡單地使用主類運行應(yīng)用程序并開始調(diào)用 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 進(jìn)行演示。將想要問的問題傳遞給該模型。
例子#1
http://localhost:8080/chat?prompt=what are some good Spring Boot libraries。
例子#2
GPT 3.5 Turbo 模型足夠先進(jìn),可以表現(xiàn)出高度真實的響應(yīng)。(由于有數(shù)十億行文本,該模型已經(jīng)過訓(xùn)練)。
注意:對 OpenAI API curl 的實際調(diào)用如下所示:
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!"
}
]
}'
注意事項
在開發(fā)應(yīng)用程序時,以下是可能遇到的常見問題。
問題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"])
確保創(chuàng)建一個無參數(shù)構(gòu)造函數(shù),并為以下對象提供 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 提供了基本配額。當(dāng)前電子郵件 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>"
一段時間后嘗試調(diào)用 API。(為了安全起見,良好的工作時間是 30 分鐘)。
總結(jié)
在這篇短文中,我們了解了 OpenAI 的 GPT 3.5 Turbo 模型。如何生成供個人使用的密鑰。
然后,我們還研究了將常用的 Spring Boot 應(yīng)用程序與 OpenAI 聊天完成 API 集成、對端點進(jìn)行實際調(diào)用,并驗證了響應(yīng)。
注意事項
OpenAI 的 API 是受監(jiān)管的資源。我們對 API 的調(diào)用量是有限的,可以在此處進(jìn)行跟蹤。