如何在?Spring?Boot?中使用?OpenAI?ChatGPT?API
1、開始咯
我們來看看如何在 Spring Boot 中調(diào)用 OpenAI ChatGPT API。
我們將創(chuàng)建一個 Spring Boot 應(yīng)用程序,該應(yīng)用程序?qū)⑼ㄟ^調(diào)用 OpenAI ChatGPT API 生成對提示的響應(yīng)。
2、OpenAI ChatGPT API
在開始具體講解之前,讓我們先探討一下我們將在本教程中使用的 OpenAI ChatGPT API。我們將調(diào)用創(chuàng)建聊天完成 API 來生成對提示的響應(yīng)。
2.1 API 參數(shù)與認證
我們看一下API的強制請求參數(shù):
- model:這是我們將向其發(fā)送請求的模型的版本。該模型有幾個版本可用。我們將使用 gpt-3.5-turbo 模型,這是該模型公開的最新版本;
- message:消息是對模型的提示。每條消息都需要兩個字段:角色和內(nèi)容。角色字段指定消息的發(fā)送者。請求中它將是“用戶”,響應(yīng)中它將是“助手”。內(nèi)容字段是實際的消息。
為了使用 API 進行身份驗證,我們將生成一個 OpenAI API 密鑰。我們將在調(diào)用 API 時在 Authorization 標頭中設(shè)置此密鑰。
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 還接受許多可選參數(shù)來修改響應(yīng)。
接著,我們將重點關(guān)注一個簡單的請求,但讓我們看一下一些有助于調(diào)整響應(yīng)的可選參數(shù):
- n:如果我們想增加生成的響應(yīng)數(shù)量,可以指定。默認值為 1;
- temperature:控制響應(yīng)的隨機性。默認值為 1(最隨機);
- max_tokens:用于限制響應(yīng)中令牌的最大數(shù)量。默認值是無窮大,這意味著響應(yīng)將與模型可以生成的一樣長。一般來說,最好將此值設(shè)置為合理的數(shù)字,以避免生成很長的響應(yīng)并產(chǎn)生很高的成本。
2.2 API Response
API 響應(yīng)將是一個帶有一些元數(shù)據(jù)和選擇字段的 JSON 對象。選擇字段將是一個對象數(shù)組。每個對象都有一個文本字段,其中包含對提示的響應(yīng)。
選擇數(shù)組中的對象數(shù)量將等于請求中的可選 n 參數(shù)。如果未指定 n 參數(shù),則選項數(shù)組將包含單個對象。
具體代碼:
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "\n\n 來啦,老弟……"
},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 9,
"completion_tokens": 12,
"total_tokens": 21
}
}響應(yīng)中的使用字段將包含提示和響應(yīng)中使用的令牌數(shù)量。這用于計算 API 調(diào)用的成本。
3、具體案例
我們將創(chuàng)建一個使用 OpenAI ChatGPT API 的 Spring Boot 應(yīng)用程序。
為此,我們將創(chuàng)建一個 Spring Boot Rest API,該 API 接受提示作為請求參數(shù),將其傳遞給 OpenAI ChatGPT API,并將響應(yīng)作為響應(yīng)正文返回。
3.1 添加依賴
首先,我們創(chuàng)建一個 Spring Boot 項目。我們需要該項目的 Spring Boot Starter Web 依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>3.2 DTO
接下來,我們創(chuàng)建一個與 OpenAI ChatGPT API 的請求參數(shù)對應(yīng)的 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
}繼續(xù)定義 Message 類:
public class Message {
private String role;
private String content;
// constructor, getters and setters
}然后,我們?yōu)轫憫?yīng)創(chuàng)建一個 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 控制器
我們創(chuàng)建一個控制器,它將接受提示作為請求參數(shù)并返回響應(yīng)作為響應(yīng)正文:
@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 注釋來注入我們將在下一節(jié)中創(chuàng)建的 RestTemplate bean;
- 使用 RestTemplate bean,我們使用 postForObject() 方法調(diào)用 OpenAI ChatGPT API。 postForObject() 方法將 URL、請求對象和響應(yīng)類作為參數(shù);
- 最后,我們讀取回復(fù)的選擇列表并返回第一個回復(fù)。
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;
}
}3.5 Properties
在 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、總結(jié)
我們探索了 OpenAI ChatGPT API 以生成對提示的響應(yīng)。我們創(chuàng)建了一個 Spring Boot 應(yīng)用程序,它調(diào)用 API 來生成對提示的響應(yīng)。
到此這篇關(guān)于如何在 Spring Boot 中使用 OpenAI ChatGPT API的文章就介紹到這了,更多相關(guān)Spring Boot使用 OpenAI ChatGPT API內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JDK21與IDE集成之以IntelliJ?IDEA為例講解
們在使用IDEA開發(fā)Java應(yīng)用時,一般第一步就是需要配置好我們的jdk環(huán)境,這篇文章主要介紹了JDK21與IDE集成之以IntelliJ?IDEA為例講解的相關(guān)資料,文中將步驟介紹的非常詳細,需要的朋友可以參考下2025-12-12
java之scan.next()與scan.nextline()函數(shù)的使用及區(qū)別
這篇文章主要介紹了java之scan.next()與scan.nextline()函數(shù)的使用及區(qū)別,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
Java實現(xiàn)ThreadLocal數(shù)據(jù)在線程池間傳遞的解決方案
隨著業(yè)務(wù)的發(fā)展,系統(tǒng)新增了一個需求:需要根據(jù)接口請求頭中的特定信息動態(tài)選擇數(shù)據(jù)庫實例進行查詢,這個上下文信息在請求進入后被存儲在ThreadLocal中,本文給大家介紹了Java實現(xiàn)ThreadLocal數(shù)據(jù)在線程池間傳遞的解決方案,需要的朋友可以參考下2025-07-07
Java中通過繼承Thread類創(chuàng)建線程的步驟
本文介紹了如何通過繼承Thread類創(chuàng)建線程,包括Thread類的定義、創(chuàng)建線程的步驟、優(yōu)缺點、使用場景和注意事項,通過示例代碼展示了多線程下載文件的實現(xiàn),感興趣的朋友跟隨小編一起看看吧2025-02-02
Java高效實現(xiàn)excel轉(zhuǎn)pdf(支持帶圖片的轉(zhuǎn)換)
這篇文章主要為大家詳細介紹了如何用java實現(xiàn)excel轉(zhuǎn)pdf文件,并且支持excel單元格中帶有圖片的轉(zhuǎn)換,文中的示例代碼講解詳細,需要的可以參考下2024-01-01

