# 将流量路由到 DeepSeek 模型

[DeepSeek](https://www.deepseek.com/) 通过 OpenAI 兼容 API，以具有竞争力的价格提供高性能语言模型。API7 网关内置专用 DeepSeek 驱动，无需使用通用的 `openai-compatible` 服务提供方。本指南介绍如何使用 [`ai-proxy`](https://docs.apiseven.com/hub/ai-proxy.md) 插件将流量路由到 DeepSeek。

## 前置条件[​](#前置条件 "前置条件的直接链接")

* 安装 [Docker](https://docs.docker.com/get-docker/)。

* 安装 [cURL](https://curl.se/)，用于发送请求并验证服务。

* 拥有一个正在运行的 API7 网关实例。

* [从控制台获取 Token](https://docs.apiseven.com/api7-gateway/reference/obtain-dashboard-token.md)，并将其保存到环境变量：

  ```
  export API_KEY=your-dashboard-token   # 请替换为你的控制台 Token
  ```

* 将 `{gateway_group_id}` 替换为网关组 ID。如果正在按照快速入门操作，请使用 `default`。

* 如果使用 Admin API 示例，请创建或复用一个服务。如果尚无服务，请按照[创建或复用服务](https://docs.apiseven.com/api7-gateway/ai-gateway/get-started.md#create-or-reuse-a-service)操作，然后将其 ID 保存到环境变量：

  ```
  export SERVICE_ID=your-service-id         # 请替换为你的服务 ID
  ```

## 获取 DeepSeek API Key（API 密钥）[​](#获取-deepseek-api-keyapi-密钥 "获取 DeepSeek API Key（API 密钥）的直接链接")

在 [platform.deepseek.com](https://platform.deepseek.com/) 创建账户并生成 API Key，然后将 API Key 保存到环境变量：

```
export DEEPSEEK_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxx   # 请替换为你的 DeepSeek API Key
```

## 为 DeepSeek 配置 AI 代理[​](#为-deepseek-配置-ai-代理 "为 DeepSeek 配置 AI 代理的直接链接")

创建一个启用 [`ai-proxy`](https://docs.apiseven.com/hub/ai-proxy.md) 插件的路由：

* Admin API
* ADC

```
curl -k "https://localhost:7443/apisix/admin/routes/deepseek-route?gateway_group_id={gateway_group_id}" -X PUT \

  -H "X-API-KEY: ${API_KEY}" \

  -H "Content-Type: application/json" \

  --data-binary @- <<EOF

  {

    "name": "deepseek-route",

    "service_id": "$SERVICE_ID",

    "paths": ["/deepseek"],

    "plugins": {

      "ai-proxy": {

        "provider": "deepseek",

        "auth": {

          "header": {

            "Authorization": "Bearer $DEEPSEEK_API_KEY"

          }

        },

        "options": {

          "model": "deepseek-chat"

        }

      }

    }

  }

EOF
```

❶ 将服务提供方设置为 `deepseek`，以使用专用 DeepSeek 驱动。

❷ 在 `Authorization` 请求头中附加 DeepSeek API Key。

❸ 将模型设置为 `deepseek-chat`。其他可用模型包括 `deepseek-reasoner`。

adc.yaml

```
services:

  - name: DeepSeek Service

    routes:

      - uris:

          - /deepseek

        name: deepseek-route

        plugins:

          ai-proxy:

            provider: deepseek

            auth:

              header:

                Authorization: "Bearer ${DEEPSEEK_API_KEY}"

            options:

              model: deepseek-chat

    labels:

      docs-example: deepseek-service
```

❶ 将服务提供方设置为 `deepseek`，以使用专用 DeepSeek 驱动。

❷ 在 `Authorization` 请求头中附加 DeepSeek API Key。

❸ 将模型设置为 `deepseek-chat`。其他可用模型包括 `deepseek-reasoner`。

预览本示例管理的资源变更，确认没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=deepseek-service
```

审查变更后同步配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=deepseek-service
```

## 使用 DeepSeek 进行多模型路由[​](#使用-deepseek-进行多模型路由 "使用 DeepSeek 进行多模型路由的直接链接")

DeepSeek 模型的每 Token 价格明显低于许多替代方案。使用 [`ai-proxy-multi`](https://docs.apiseven.com/hub/ai-proxy-multi.md) 将大部分流量路由到 DeepSeek，同时保留高级服务提供方作为备用：

* Admin API
* ADC

```
curl -k "https://localhost:7443/apisix/admin/routes/deepseek-multi-route?gateway_group_id={gateway_group_id}" -X PUT \

  -H "X-API-KEY: ${API_KEY}" \

  -H "Content-Type: application/json" \

  --data-binary @- <<EOF

  {

    "service_id": "$SERVICE_ID",

    "name": "deepseek-multi-route",

    "paths": ["/deepseek-multi"],

    "plugins": {

      "ai-proxy-multi": {

        "fallback_strategy": ["http_429", "http_5xx"],

        "instances": [

          {

            "name": "deepseek-primary",

            "provider": "deepseek",

            "auth": { "header": { "Authorization": "Bearer $DEEPSEEK_API_KEY" } },

            "options": { "model": "deepseek-chat" },

            "weight": 1,

            "priority": 2

          },

          {

            "name": "openai-fallback",

            "provider": "openai",

            "auth": { "header": { "Authorization": "Bearer $OPENAI_API_KEY" } },

            "options": { "model": "gpt-4o-mini" },

            "weight": 1,

            "priority": 1

          }

        ]

      }

    }

  }

EOF
```

❶ `fallback_strategy` 会在出现 HTTP 429（限流）或 5xx（服务器错误）时启用自动故障转移。

❷ 将 DeepSeek 设置为优先级最高的主实例。

❸ 将 OpenAI 设置为较低优先级的备用实例，仅在 DeepSeek 不可用时才将流量路由到该实例。

adc.yaml

```
services:

  - name: DeepSeek with Fallback

    routes:

      - uris:

          - /deepseek-multi

        name: deepseek-multi-route

        plugins:

          ai-proxy-multi:

            fallback_strategy:

              - http_429

              - http_5xx

            instances:

              - name: deepseek-primary

                provider: deepseek

                auth:

                  header:

                    Authorization: "Bearer ${DEEPSEEK_API_KEY}"

                options:

                  model: deepseek-chat

                weight: 1

                priority: 2

              - name: openai-fallback

                provider: openai

                auth:

                  header:

                    Authorization: "Bearer ${OPENAI_API_KEY}"

                options:

                  model: gpt-4o-mini

                weight: 1

                priority: 1

    labels:

      docs-example: deepseek-with-fallback
```

❶ `fallback_strategy` 会在出现 HTTP 429（限流）或 5xx（服务器错误）时启用自动故障转移。

❷ 将 DeepSeek 设置为优先级最高的主实例。

❸ 将 OpenAI 设置为较低优先级的备用实例，仅在 DeepSeek 不可用时才将流量路由到该实例。

预览本示例管理的资源变更，确认没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=deepseek-with-fallback
```

审查变更后同步配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=deepseek-with-fallback
```

更多路由策略请参阅[多模型路由和故障转移](https://docs.apiseven.com/api7-gateway/ai-gateway/use-cases/multi-llm-routing-and-fallback.md)。

## 验证配置[​](#验证配置 "验证配置的直接链接")

向多模型路由发送以下请求。要测试单模型路由，请将 `/deepseek-multi` 替换为 `/deepseek`。

```
curl "http://127.0.0.1:9080/deepseek-multi" -X POST \

  -H "Content-Type: application/json" \

  -d '{

    "messages": [

      { "role": "user", "content": "What is the Fibonacci sequence?" }

    ]

  }'
```

你应收到类似以下内容的响应：

```
{

  "id": "chatcmpl-abc123",

  "object": "chat.completion",

  "model": "deepseek-chat",

  "choices": [

    {

      "index": 0,

      "message": {

        "role": "assistant",

        "content": "The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1: 0, 1, 1, 2, 3, 5, 8, 13, 21, ..."

      },

      "finish_reason": "stop"

    }

  ],

  "usage": {

    "prompt_tokens": 10,

    "completion_tokens": 48,

    "total_tokens": 58

  }

}
```

要启用流式响应，请在请求体中设置 `"stream": true`。使用 [`proxy-buffering`](https://docs.apiseven.com/hub/proxy-buffering.md) 插件禁用 NGINX `proxy_buffering`，避免服务器发送事件（SSE）被缓冲。

## 后续步骤[​](#后续步骤 "后续步骤的直接链接")

你已经了解如何通过 API7 网关将流量路由到 DeepSeek。有关可用模型的更多信息，请参阅 [DeepSeek API 文档](https://platform.deepseek.com/api-docs)。

* [多模型路由和故障转移](https://docs.apiseven.com/api7-gateway/ai-gateway/use-cases/multi-llm-routing-and-fallback.md) — 将 DeepSeek 与其他服务提供方组合，以优化成本。
* [Token 限流](https://docs.apiseven.com/api7-gateway/ai-gateway/use-cases/token-rate-limiting-and-quota-management.md) — 使用 Token 预算控制支出。
