
WordPress REST API 初學者指南
-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 響應:
{
"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
}
]
}
本教程分為兩部分。第一部分講解如何設置 Spring Boot 應用程序,并創建一個新的 API 端點,該端點能夠通過編程方式處理對 ChatGPT API 的調用。第二部分則介紹如何利用 APISIX 的安全性、流量控制等功能來管理 Spring Boot API。本教程的完整代碼示例可以在名為 apisix-java-chatgpt-openaiapi
的 GitHub 倉庫中找到。
在開始之前,請確保具備以下條件:
首先,需要創建一個新的 Spring Boot 應用程序。可以使用 Spring Initializr 生成一個具有必要依賴項的 Maven 項目。在本教程中,將需要添加 Spring Boot Starter Web
依賴項。為了集成 ChatGPT API,可以使用 OpenAI Java 客戶端庫,這是一個開源的社區庫,提供了在 Java 中創建和調用 OpenAI GPT API 的服務類。當然,也可以在 Spring 中編寫自己的實現,以與 OpenAI API 進行交互。此外,還可以參考其他編程語言的客戶端庫。
<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>
在 ChatCompletionController.java
類中,可以使用 OpenAI 服務向 ChatGPT API 發送請求。
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
端點處理 POST 請求,創建聊天請求,并將其發送到 OpenAI API。然后,返回 API 響應中的第一條消息。端點地址為 /ai-chat
。
在 application.properties
文件中定義 API 屬性,包括模型和 API 密鑰:
openai.model=gpt-3.5-turbo
openai.api.key=YOUR_OPENAI_API_TOKEN
請將 YOUR_OPENAI_API_TOKEN
替換為實際的 OpenAI API 密鑰。
現在,可以運行 Application.java
并使用 Postman 或 cURL 命令對其進行測試。
運行 Application.java
后,使用 Postman 或 cURL 發送請求來測試應用程序。以下是 cURL 請求的示例:
curl -X POST http://localhost:8080/ai-chat \
-H "Content-Type: application/json" \
-d '{"prompt": "What is Apache APISIX?"}'
如上所示,應用程序將根據提示請求正文生成回答。
接下來,為了將 Spring Boot 應用程序容器化,可以創建一個 Dockerfile
,用于構建 JAR 文件并執行它。以下是一個示例 Dockerfile
:
# 使用官方 Java 運行時作為基礎鏡像
FROM openjdk:17-jdk-alpine
# 將 JAR 文件復制到容器中
COPY target/openaiapi.jar /app/openaiapi.jar
# 設置容器啟動命令
ENTRYPOINT ["java", "-jar", "/app/openaiapi.jar"]
然后,在 docker-compose.yml
文件中注冊服務,將應用程序與其他 APISIX 容器一起配置:
version: '3'
services:
openaiapi:
build: ./openaiapi
ports:
- "8080:8080"
networks:
- apisix
networks:
apisix:
這將構建 Spring Boot 應用程序的 Docker 鏡像,并在 8080
端口上暴露它,使其可以與 APISIX 進行集成。
要配置 Apache APISIX,只需運行以下命令,因為 docker-compose.yml
文件已定義了所需的服務。該文件配置了兩個容器,一個用于 APISIX,另一個用于之前創建的 Spring Boot 應用。在本示例中,APISIX 以獨立模式運行,其他安裝選項和部署模式也可供選擇。運行以下命令啟動服務:
docker compose up
此時,APISIX 將作為一個單獨的服務運行在 localhost:9080
上,而 Spring Boot 應用程序則在 localhost:8080
上運行。
在設置完 APISIX 后,可以通過以下步驟為 Spring Boot API 添加安全功能,以確保只有授權的 API 消費者能夠訪問該 API。APISIX 提供了多種插件用于 API 保護,例如 jwt-auth
插件,可以要求所有請求必須使用 JWT 令牌。以下是如何在 apisix.yml
文件中配置帶有上游服務和插件的路由示例:
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
文件中定義了上游服務、路由、消費者對象及其規則后,APISIX 將在 Docker 容器啟動后立即加載這些配置文件。APISIX 會定期檢測配置文件是否有更新,并在檢測到變化時自動重新加載配置。
在此配置中,添加了一個上游服務、兩個路由和一個消費者對象。第一個路由配置要求所有請求(自定義 URI 路徑,可根據需要修改)必須在請求頭中包含有效的 JWT 令牌。APISIX 使用 proxy-rewrite
插件將自定義的 URI 路徑重寫為實際的 API 路徑,并將請求轉發到運行在 localhost:8080
的 Spring Boot 應用程序。
如果嘗試訪問 APISIX 路由而未提供有效的 JWT 令牌,請求將被拒絕,返回授權錯誤:
curl -i http://localhost:9080/ask-me-anything -X POST -d '{"prompt":"What is Apache APISIX?"}'
響應示例:
HTTP/1.1 401 Unauthorized
{"message":"Missing JWT token in request"}
在第二個路由配置中,啟用了 public-api
插件,以公開新的端點用于生成新的 JWT 令牌。APISIX 充當身份提供者,可以為 API 消費者或客戶端應用程序生成和驗證新令牌。請參閱第 8 步了解如何為 API 使用者生成新令牌:
- uri: /login
plugins:
public-api:
uri: /apisix/plugin/jwt/sign
此外,配置文件中注冊了一個 API 消費者,允許用戶使用其 secret
來聲明 JWT 令牌,以訪問 API:
consumers:
- username: appsmithuser
plugins:
jwt-auth:
key: appsmithuser@gmail.com
secret: my-secret-key
要為現有的 API 使用者獲取新的 JWT 令牌,可以使用以下 cURL 命令。您需要替換 user-key
為實際的 API 使用者密鑰:
curl -i http://127.0.0.1:9080/login?key=user-key
成功執行后,APISIX 將返回一個新的 JWT 令牌。響應示例如下:
HTTP/1.1 200 OK
Server: APISIX/3.0.0
Content-Type: application/json
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJrZXkiOiJ1c2VyLWtleSIsImV4cCI6MTY4NjU5MjE0NH0.4Kn9c2DBYKthyUx824Ah97-z0Eu2Ul9WGO2WB3IfURA"
}
您可以將返回的 JWT 令牌用于后續 API 請求。在請求中,您需要將此令牌放在 Authorization
頭中,以便驗證請求的合法性:
curl -i http://localhost:9080/ask-me-anything -X POST -H "Authorization: Bearer YOUR_NEW_JWT_TOKEN" -d '{"prompt":"What is Apache APISIX?"}'
這將確保只有持有有效 JWT 的請求才能訪問受保護的 API 端點。
最后,可以使用從上一步中獲取的 JWT 令牌向 API 發送請求。以下是如何使用 cURL 命令進行請求的示例:
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
替換為實際的 JWT 令牌。
此外,也可以使用 Postman 發送相同的請求。確保在請求頭中添加 Authorization
,其值為 JWT 令牌。請求成功后,將從 APISIX 網關收到 AI 的響應。
本教程介紹了如何利用 OpenAI ChatGPT API 生成對提示的響應。首先創建了一個 Spring Boot 應用程序,該應用程序通過調用 API 生成響應。隨后,通過更新現有的 apisix.yml 文件,可以為集成引入其他功能。此外,還可以查看名為 with-frontend 的分支,并運行項目,以查看使用 Appsmith 構建的與 APISIX 配合使用的 UI 界面。
原文鏈接:Managing AI-Powered Java App With API Management