跳到主要内容

预定义提示词模板

提示词模板允许管理员定义可复用的请求体,并为客户端提供的值预留占位符。这样既能在不同应用之间统一提示词,又只需让每个请求提供会发生变化的值。

当客户端应调用经过批准的请求结构、而非自行构造完整模型载荷时,提示词模板非常有用。管理员控制固定指令、模型选项和工具,客户端只提供声明过的变量。

本指南介绍如何使用 ai-prompt-template 插件为 OpenAI 创建 Chat Completions 和 Responses API 模板。当下游插件支持相应请求格式时,同一种模板机制也可用于其他 LLM 服务提供方。

前置条件

  • 安装 Docker
  • 安装 cURL 以发送验证请求。
  • 按照快速入门教程在 Docker 或 Kubernetes 中启动 APISIX 实例。
  • 拥有 OpenAI 账户,并能通过 API 访问同时支持 Chat Completions 和 Responses API Web 搜索的模型。

获取 OpenAI API Key

创建 OpenAI API Key,然后导出 API Key 和模型:

export OPENAI_API_KEY="<your-api-key>"
export OPENAI_MODEL="<your-model-name>"

配置 Chat Completions 模板

ai-prompt-template 插件会使用选定的 JSON 模板替换传入的请求体。模板可以使用下游插件支持的任意请求结构。本示例配置包含 messages 数组的 Chat Completions 请求体。

如需在不替换请求体的情况下向现有 Chat Completions 或 Responses API 请求添加固定内容,请使用 ai-prompt-decorator

创建 Chat Completions 模板

创建一个指向 OpenAI API 端点的路由,并配置一个示例提示词模板。该模板接收用户定义的提示词,并按指定的复杂程度作答:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
--data-binary @- <<EOF
{
"id": "ai-prompt-template-route",
"uri": "/anything",
"plugins": {
"ai-proxy": {
"provider": "openai",
"auth": {
"header": {
"Authorization": "Bearer $OPENAI_API_KEY"
}
},
"options": {
"model": "$OPENAI_MODEL"
}
},
"ai-prompt-template": {
"templates": [
{
"name": "QnA with complexity",
"template": {
"model": "$OPENAI_MODEL",
"messages": [
{
"role": "system",
"content": "Answer in {{complexity}}."
},
{
"role": "user",
"content": "Explain {{prompt}}."
}
]
}
}
]
}
}
}
EOF

❶ 为模板命名。请求该路由时,应在请求中包含模板名称。

❷ 指定模型标识符。

❸ 配置提示词,从请求体键 complexity 获取用户定义的回答复杂程度。

❹ 配置提示词,从请求体键 prompt 获取用户定义的问题。

发送请求

现在可以复用该路由,回答不同问题,并支持用户指定不同的复杂程度。

向路由发送 POST 请求,在请求体中提供示例问题和期望的回答复杂程度:

curl "http://127.0.0.1:9080/anything" -X POST \
-H "Content-Type: application/json" \
-d '{
"template_name": "QnA with complexity",
"complexity": "brief",
"prompt": "quick sort"
}'

你应该会收到类似以下的响应:

{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "Quick sort is a highly efficient sorting algorithm that uses a divide-and-conquer approach to arrange elements in a list or array in order. Here’s a brief explanation:\n\n1. **Choose a Pivot**: Select an element from the list as a 'pivot'. Common methods include choosing the first element, the last element, the middle element, or a random element.\n\n2. **Partitioning**: Rearrange the elements in the list such that all elements less than the pivot are moved before it, and all elements greater than the pivot are moved after it. The pivot is now in its final position.\n\n3. **Recursively Apply**: Recursively apply the same process to the sub-lists of elements to the left and right of the pivot.\n\nThe base case of the recursion is lists of size zero or one, which are already sorted.\n\nQuick sort has an average-case time complexity of O(n log n), making it suitable for large datasets. However, its worst-case time complexity is O(n^2), which occurs when the smallest or largest element is always chosen as the pivot. This can be mitigated by using good pivot selection strategies or randomization.",
"role": "assistant"
}
}
],
"created": 1723194057,
"id": "chatcmpl-9uFmTYN4tfwaXZjyOQwcp0t5law4x",
"model": "gpt-4o-2024-05-13",
"object": "chat.completion",
"system_fingerprint": "fp_abc28019ad",
"usage": {
"completion_tokens": 234,
"prompt_tokens": 18,
"total_tokens": 252
}
}

配置 Responses API Web 搜索模板

模板还可以生成使用内置工具的 Responses API 请求。本示例提供一个可复用的 Web 搜索,并将搜索范围限制为 Apache APISIX 官方网站。

路由 URI 可以有自定义前缀,但必须以 /v1/responses 结尾,以便 APISIX 将生成的请求体与 Embeddings 请求区分开来。

创建 Web 搜索模板

使用 Web 搜索模板创建一个单独的路由:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
--data-binary @- <<EOF
{
"id": "ai-prompt-template-responses-route",
"uri": "/template/v1/responses",
"methods": ["POST"],
"plugins": {
"ai-proxy": {
"provider": "openai",
"auth": {
"header": {
"Authorization": "Bearer $OPENAI_API_KEY"
}
}
},
"ai-prompt-template": {
"templates": [
{
"name": "Search APISIX documentation",
"template": {
"model": "$OPENAI_MODEL",
"tools": [
{
"type": "web_search",
"filters": {
"allowed_domains": ["apisix.apache.org"]
}
}
],
"tool_choice": "required",
"input": "Search the official Apache APISIX website for {{topic}} and summarize the result in one sentence."
}
}
]
}
}
}
EOF

❶ 保留 Responses API 检测所需的 /v1/responses 后缀。

❷ 启用 Responses API Web 搜索工具。

❸ 将 Web 搜索结果限制为 Apache APISIX 官方网站。

❹ 要求模型使用已配置的工具。

❺ 使用传入请求中的值创建搜索请求。

发送请求

向路由发送模板名称和变量值:

curl "http://127.0.0.1:9080/template/v1/responses" -X POST \
-H "Content-Type: application/json" \
-d '{
"template_name": "Search APISIX documentation",
"topic": "what APISIX is"
}'

ai-proxy 处理请求之前,ai-prompt-template 会使用解析后的模板替换传入的请求体:

{
"model": "<your-model-name>",
"tools": [
{
"type": "web_search",
"filters": {
"allowed_domains": ["apisix.apache.org"]
}
}
],
"tool_choice": "required",
"input": "Search the official Apache APISIX website for what APISIX is and summarize the result in one sentence."
}

APISIX 会根据生成的请求体和路由 URI,将其识别为 Responses API 请求。你应该收到 HTTP 200 响应。output 数组先包含已完成的 Web 搜索调用,随后包含一条带 URL 引用的消息:

{
"status": "completed",
"output": [
{
"type": "web_search_call",
"status": "completed",
"action": {
"type": "search",
"queries": [
"site:apisix.apache.org what is Apache APISIX"
],
"query": "site:apisix.apache.org what is Apache APISIX"
}
},
{
"type": "message",
"status": "completed",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "Apache APISIX is an open-source, high-performance API and AI gateway for managing traffic at scale through dynamic routing, load balancing, authentication, observability, rate limiting, and over 100 plugins. ([apisix.apache.org](https://apisix.apache.org/?utm_source=openai))",
"annotations": [
{
"type": "url_citation",
"start_index": 208,
"end_index": 275,
"title": "Apache APISIX - Open Source API Gateway & AI Gateway",
"url": "https://apisix.apache.org/?utm_source=openai"
}
]
}
]
}
]
}

下一步

现在,你已了解如何在 APISIX 集成 LLM 服务提供方时预定义提示词模板,使同一路由可以复用不同的用户输入,服务于多种用途。

此外,你还可以集成 APISIX 提供的更多能力,例如限流缓存,以提升系统可用性和用户体验。