1. 概述
在本教程中,我們將學習如何在 Spring Boot 中調用 OpenAI ChatGPT API。我們將創建一個 Spring Boot 應用程序,該應用程序通過調用 OpenAI ChatGPT API 來生成對提示的響應。
注意: 本文使用 <em>RestTemplate</em> 客户端直接與 OpenAI API 交互。您現在可以使用 Spring AI 項目作為更健壯的替代方案。
2. OpenAI ChatGPT API
在開始教程之前,讓我們先探索一下我們將在此教程中使用的一項 OpenAI ChatGPT API。我們將使用 創建聊天完成 API 來生成響應,這些響應將基於給定的提示。
2.1 API 參數和身份驗證
讓我們看一下 API 的強制請求參數:
- model – 這是我們將發送請求的模型版本。 有幾個模型版本可用。 我們將使用 gpt-3.5-turbo 模型,它是目前公開可用的最新模型版本。
- messages – 消息是發送給模型的提示。 每個消息需要兩個字段:角色 和 內容。 角色 字段指定消息的發送者。 請求中將是 “user”,響應中將是 “assistant”。 內容 字段是實際的消息。
為了使用 API 進行身份驗證,我們將生成一個 OpenAI API 密鑰。 我們將在調用 API 時將此密鑰設置為 Authorization 標頭。
以下是 cURL 格式的示例請求:
$ curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "Hello!"}]
}'
此外,API 還可以接受多種可選參數來修改響應。
在下面的部分,我們將重點介紹一個簡單的請求,但讓我們先看看一些可以幫助調整響應的選項參數:
- n – 如果我們想增加要生成的響應數量,則可以指定它。默認值為 1。
- temperature – 控制響應的隨機性。默認值為 1(最隨機)。
- max_tokens – 用於限制響應中的最大 token 數量。默認值為 infinity,這意味着響應將盡可能長,直到模型可以生成為止。通常,建議將其設置為一個合理的數值,以避免生成過長的響應併產生高昂的成本。
2.2 API 響應
API 響應將是一個包含元數據和 <em >choices</em> 字段的 JSON 對象。<em >choices</em> 字段將是一個對象數組。每個對象將包含一個 <em >text</em> 字段,該字段將包含對提示的響應。
<em >choices</em> 數組中的對象數量將等於請求中的可選 <em >n</em> 參數。如果未指定 <em >n</em> 參數,則 <em >choices</em> 數組將包含一個單獨的對象。
以下是一個示例響應:
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "\n\nHello there, how may I assist you today?"
},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 9,
"completion_tokens": 12,
"total_tokens": 21
}
}
響應中的用法字段將包含提示和響應中使用的 token 數量。這用於計算 API 調用成本。
3. 代碼示例
我們將創建一個使用 OpenAI ChatGPT API 的 Spring Boot 應用程序。為此,我們將創建一個 Spring Boot REST API,該 API 接受提示作為請求參數,將其傳遞給 OpenAI ChatGPT API,並將響應作為響應主體返回。
3.1. 依賴項
首先,讓我們創建一個 Spring Boot 項目。對於該項目,我們需要以下依賴項:Spring Boot Starter Web 依賴項:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3.2. DTOs
接下來,讓我們創建一個與 OpenAI ChatGPT API 請求參數相對應的 DTO:
public class ChatRequest {
private String model;
private List<Message> messages;
private int n;
private double temperature;
public ChatRequest(String model, String prompt) {
this.model = model;
this.messages = new ArrayList<>();
this.messages.add(new Message("user", prompt));
}
// getters and setters
}
讓我們也定義 Message 類:
public class Message {
private String role;
private String content;
// constructor, getters and setters
}
同樣,我們來創建一個用於響應的 DTO:
public class ChatResponse {
private List<Choice> choices;
// constructors, getters and setters
public static class Choice {
private int index;
private Message message;
// constructors, getters and setters
}
}
3.3. 控制器
接下來,讓我們創建一個控制器,該控制器將提示作為請求參數接受,並將響應作為響應主體返回:
@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) {
// create a request
ChatRequest request = new ChatRequest(model, prompt);
// call the API
ChatResponse response = restTemplate.postForObject(apiUrl, request, ChatResponse.class);
if (response == null || response.getChoices() == null || response.getChoices().isEmpty()) {
return "No response";
}
// return the first response
return response.getChoices().get(0).getMessage().getContent();
}
}讓我們來查看代碼中的一些重要部分:
- 我們使用了 @Qualifier 註解來注入一個將在下一部分創建的 RestTemplate Bean
- 使用 RestTemplate Bean,我們使用 postForObject() 方法調用 OpenAI ChatGPT API。 postForObject() 方法接受 URL、請求對象和響應類作為參數
- 最後,我們讀取 響應選擇列表 並返回第一個回覆
3.4. RestTemplate
以下我們定義一個自定義的 RestTemplate Bean,用於使用 OpenAI API 密鑰進行身份驗證:
@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;
}
}在這裏,我們為基礎的RestTemplate添加了攔截器,並添加了Authorization頭。
3.5. 屬性
最後,讓我們在 application.properties 文件中提供 API 的屬性:
openai.model=gpt-3.5-turbo
openai.api.url=https://api.openai.com/v1/chat/completions
openai.api.key=your-api-key
4. 運行應用程序
我們可以現在運行應用程序並在瀏覽器中進行測試:
正如您所看到的,應用程序已對提示生成了響應。請注意,響應可能會因其由模型生成而異。
5. 結論
在本教程中,我們探討了 OpenAI ChatGPT API 以生成響應提示的方式。我們創建了一個 Spring Boot 應用程序,該應用程序調用 API 以生成響應提示。