在本篇文中,將解釋如何與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;@RestControllerpublic 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-turboopenai.api.url=https://api.openai.com/v1/chat/completionsopenai.api.key=<generated_key_goes_here>
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;@Configurationpublic 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;@SpringBootApplicationpublic class MyChatGptApplication { public static void main(String[] args) { SpringApplication.run(MyChatGptApplication.class, args); }}
本次使用Postman 進行演示。將想要問的問題傳遞給該模型。
http://localhost:8080/chat?prompt=what are some good Spring Boot libraries。
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 的調用量是有限的,可以在此處進行跟蹤。
本文鏈接:http://www.www897cc.com/showinfo-26-64509-0.html使用 Spring Boot 創建自己的 ChatGPT 應用程序
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 深入探討API網關APISIX中自定義Java插件在真實項目中的運用
下一篇: Swift 枚舉類型,你知道幾個?