-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "What is Apache APISIX?"}]
}'

以下是一個示例 JSON 響應(yīng):

{
"id": "chatcmpl-7PtycrYOTJGv4jw8FQPD7LCCw0tOE",
"object": "chat.completion",
"created": 1686407730,
"model": "gpt-3.5-turbo-0301",
"usage": {
"prompt_tokens": 15,
"completion_tokens": 104,
"total_tokens": 119
},
"choices": [
{
"message": {
"role": "assistant",
"content": "Apache APISIX is a dynamic, real-time, high-performance API gateway designed to facilitate the management and routing of microservices and APIs. It provides features such as load balancing, rate limiting, authentication, authorization, and traffic control, all of which help to simplify the management of microservices and APIs. Apache APISIX is built on top of the Nginx server and can support high levels of traffic with low latency and high availability. It is open source and released under the Apache 2.0 license."
},
"finish_reason": "stop",
"index": 0
}
]
}

項(xiàng)目代碼示例

本教程分為兩部分。第一部分講解如何設(shè)置 Spring Boot 應(yīng)用程序,并創(chuàng)建一個新的 API 端點(diǎn),該端點(diǎn)能夠通過編程方式處理對 ChatGPT API 的調(diào)用。第二部分則介紹如何利用 APISIX 的安全性、流量控制等功能來管理 Spring Boot API。本教程的完整代碼示例可以在名為 apisix-java-chatgpt-openaiapi 的 GitHub 倉庫中找到。

先決條件

在開始之前,請確保具備以下條件:

第 1 步:設(shè)置 Spring Boot 應(yīng)用程序

首先,需要創(chuàng)建一個新的 Spring Boot 應(yīng)用程序??梢允褂?Spring Initializr 生成一個具有必要依賴項(xiàng)的 Maven 項(xiàng)目。在本教程中,將需要添加 Spring Boot Starter Web 依賴項(xiàng)。為了集成 ChatGPT API,可以使用 OpenAI Java 客戶端庫,這是一個開源的社區(qū)庫,提供了在 Java 中創(chuàng)建和調(diào)用 OpenAI GPT API 的服務(wù)類。當(dāng)然,也可以在 Spring 中編寫自己的實(shí)現(xiàn),以與 OpenAI API 進(jìn)行交互。此外,還可以參考其他編程語言的客戶端庫。

<dependencies>       
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.theokanning.openai-gpt3-java</groupId>
<artifactId>service</artifactId>
<version>0.12.0</version>
</dependency>
</dependencies>

第 2 步:創(chuàng)建 Controller 類

ChatCompletionController.java 類中,可以使用 OpenAI 服務(wù)向 ChatGPT API 發(fā)送請求。

import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class ChatCompletionController {

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

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

@PostMapping("/ai-chat")
public String chat(@RequestBody String prompt) {
OpenAiService service = new OpenAiService(openaiApiKey);
final List<ChatMessage> messages = new ArrayList<>();
final ChatMessage systemMessage = new ChatMessage(
ChatMessageRole.USER.value(), prompt
);
messages.add(systemMessage);

ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
.model(model)
.messages(messages)
.maxTokens(250)
.build();

List<ChatCompletionChoice> choices = service.createChatCompletion(chatCompletionRequest).getChoices();

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

return choices.get(0).getMessage().getContent();
}
}

聊天 API 端點(diǎn)處理 POST 請求,創(chuàng)建聊天請求,并將其發(fā)送到 OpenAI API。然后,返回 API 響應(yīng)中的第一條消息。端點(diǎn)地址為 /ai-chat。

第 3 步:定義應(yīng)用程序?qū)傩?/h3>

application.properties 文件中定義 API 屬性,包括模型和 API 密鑰:

openai.model=gpt-3.5-turbo
openai.api.key=YOUR_OPENAI_API_TOKEN

請將 YOUR_OPENAI_API_TOKEN 替換為實(shí)際的 OpenAI API 密鑰。

第 4 步:運(yùn)行 Spring Boot 應(yīng)用程序

現(xiàn)在,可以運(yùn)行 Application.java 并使用 Postman 或 cURL 命令對其進(jìn)行測試。

運(yùn)行 Application.java 后,使用 Postman 或 cURL 發(fā)送請求來測試應(yīng)用程序。以下是 cURL 請求的示例:

curl -X POST http://localhost:8080/ai-chat \
-H "Content-Type: application/json" \
-d '{"prompt": "What is Apache APISIX?"}'

如上所示,應(yīng)用程序?qū)⒏鶕?jù)提示請求正文生成回答。

第 5 步:創(chuàng)建 Dockerfile

接下來,為了將 Spring Boot 應(yīng)用程序容器化,可以創(chuàng)建一個 Dockerfile,用于構(gòu)建 JAR 文件并執(zhí)行它。以下是一個示例 Dockerfile

# 使用官方 Java 運(yùn)行時作為基礎(chǔ)鏡像
FROM openjdk:17-jdk-alpine

# 將 JAR 文件復(fù)制到容器中
COPY target/openaiapi.jar /app/openaiapi.jar

# 設(shè)置容器啟動命令
ENTRYPOINT ["java", "-jar", "/app/openaiapi.jar"]

然后,在 docker-compose.yml 文件中注冊服務(wù),將應(yīng)用程序與其他 APISIX 容器一起配置:

version: '3'
services:
openaiapi:
build: ./openaiapi
ports:
- "8080:8080"
networks:
- apisix

networks:
apisix:

這將構(gòu)建 Spring Boot 應(yīng)用程序的 Docker 鏡像,并在 8080 端口上暴露它,使其可以與 APISIX 進(jìn)行集成。

第 6 步:設(shè)置 Apache APISIX

要配置 Apache APISIX,只需運(yùn)行以下命令,因?yàn)?docker-compose.yml 文件已定義了所需的服務(wù)。該文件配置了兩個容器,一個用于 APISIX,另一個用于之前創(chuàng)建的 Spring Boot 應(yīng)用。在本示例中,APISIX 以獨(dú)立模式運(yùn)行,其他安裝選項(xiàng)和部署模式也可供選擇。運(yùn)行以下命令啟動服務(wù):

docker compose up

此時,APISIX 將作為一個單獨(dú)的服務(wù)運(yùn)行在 localhost:9080 上,而 Spring Boot 應(yīng)用程序則在 localhost:8080 上運(yùn)行。

第 7 步:使用 APISIX 保護(hù) API

在設(shè)置完 APISIX 后,可以通過以下步驟為 Spring Boot API 添加安全功能,以確保只有授權(quán)的 API 消費(fèi)者能夠訪問該 API。APISIX 提供了多種插件用于 API 保護(hù),例如 jwt-auth 插件,可以要求所有請求必須使用 JWT 令牌。以下是如何在 apisix.yml 文件中配置帶有上游服務(wù)和插件的路由示例:

upstreams:
- id: 1
type: roundrobin
nodes:
"openaiapi:8080": 1

routes:
- uri: /ask-me-anything
upstream_id: 1
plugins:
proxy-rewrite:
uri: /ai-chat
jwt-auth: {}

- uri: /login
plugins:
public-api:
uri: /apisix/plugin/jwt/sign

consumers:
- username: appsmithuser
plugins:
jwt-auth:
key: appsmithuser@gmail.com
secret: my-secret-key

apisix.yml 文件中定義了上游服務(wù)、路由、消費(fèi)者對象及其規(guī)則后,APISIX 將在 Docker 容器啟動后立即加載這些配置文件。APISIX 會定期檢測配置文件是否有更新,并在檢測到變化時自動重新加載配置。

在此配置中,添加了一個上游服務(wù)、兩個路由和一個消費(fèi)者對象。第一個路由配置要求所有請求(自定義 URI 路徑,可根據(jù)需要修改)必須在請求頭中包含有效的 JWT 令牌。APISIX 使用 proxy-rewrite 插件將自定義的 URI 路徑重寫為實(shí)際的 API 路徑,并將請求轉(zhuǎn)發(fā)到運(yùn)行在 localhost:8080 的 Spring Boot 應(yīng)用程序。

如果嘗試訪問 APISIX 路由而未提供有效的 JWT 令牌,請求將被拒絕,返回授權(quán)錯誤:

curl -i http://localhost:9080/ask-me-anything -X POST -d '{"prompt":"What is Apache APISIX?"}'

響應(yīng)示例:

HTTP/1.1 401 Unauthorized
{"message":"Missing JWT token in request"}

在第二個路由配置中,啟用了 public-api 插件,以公開新的端點(diǎn)用于生成新的 JWT 令牌。APISIX 充當(dāng)身份提供者,可以為 API 消費(fèi)者或客戶端應(yīng)用程序生成和驗(yàn)證新令牌。請參閱第 8 步了解如何為 API 使用者生成新令牌:

- uri: /login
plugins:
public-api:
uri: /apisix/plugin/jwt/sign

此外,配置文件中注冊了一個 API 消費(fèi)者,允許用戶使用其 secret 來聲明 JWT 令牌,以訪問 API:

consumers:
- username: appsmithuser
plugins:
jwt-auth:
key: appsmithuser@gmail.com
secret: my-secret-key

第 8 步:領(lǐng)取新的 JWT 令牌

要為現(xiàn)有的 API 使用者獲取新的 JWT 令牌,可以使用以下 cURL 命令。您需要替換 user-key 為實(shí)際的 API 使用者密鑰:

curl -i http://127.0.0.1:9080/login?key=user-key

成功執(zhí)行后,APISIX 將返回一個新的 JWT 令牌。響應(yīng)示例如下:

HTTP/1.1 200 OK
Server: APISIX/3.0.0
Content-Type: application/json

{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJrZXkiOiJ1c2VyLWtleSIsImV4cCI6MTY4NjU5MjE0NH0.4Kn9c2DBYKthyUx824Ah97-z0Eu2Ul9WGO2WB3IfURA"
}

您可以將返回的 JWT 令牌用于后續(xù) API 請求。在請求中,您需要將此令牌放在 Authorization 頭中,以便驗(yàn)證請求的合法性:

curl -i http://localhost:9080/ask-me-anything -X POST -H "Authorization: Bearer YOUR_NEW_JWT_TOKEN" -d '{"prompt":"What is Apache APISIX?"}'

這將確保只有持有有效 JWT 的請求才能訪問受保護(hù)的 API 端點(diǎn)。

第 9 步:使用 JWT 令牌請求 API

最后,可以使用從上一步中獲取的 JWT 令牌向 API 發(fā)送請求。以下是如何使用 cURL 命令進(jìn)行請求的示例:

curl -i http://localhost:9080/ask-me-anything \
-H 'Authorization: Bearer YOUR_JWT_TOKEN' \
-X POST \
-d '{ "prompt": "What is Apache APISIX?" }'

YOUR_JWT_TOKEN 替換為實(shí)際的 JWT 令牌。

此外,也可以使用 Postman 發(fā)送相同的請求。確保在請求頭中添加 Authorization,其值為 JWT 令牌。請求成功后,將從 APISIX 網(wǎng)關(guān)收到 AI 的響應(yīng)。

結(jié)論

本教程介紹了如何利用 OpenAI ChatGPT API 生成對提示的響應(yīng)。首先創(chuàng)建了一個 Spring Boot 應(yīng)用程序,該應(yīng)用程序通過調(diào)用 API 生成響應(yīng)。隨后,通過更新現(xiàn)有的 apisix.yml 文件,可以為集成引入其他功能。此外,還可以查看名為 with-frontend 的分支,并運(yùn)行項(xiàng)目,以查看使用 Appsmith 構(gòu)建的與 APISIX 配合使用的 UI 界面。

原文鏈接:Managing AI-Powered Java App With API Management

上一篇:

使用 Angular 和 Asp.Net WebAPI 將 Crystal Report 轉(zhuǎn)換為 PDF

下一篇:

免費(fèi)試用谷歌云API:輕松調(diào)用云端服務(wù)
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊

多API并行試用

數(shù)據(jù)驅(qū)動選型,提升決策效率

查看全部API→
??

熱門場景實(shí)測,選對API

#AI文本生成大模型API

對比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個渠道
一鍵對比試用API 限時免費(fèi)

#AI深度推理大模型API

對比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費(fèi)