> ## Documentation Index
> Fetch the complete documentation index at: https://aisa.one/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> - Base URLs: models `https://api.aisa.one/v1` (Gemini GenerateContent: `https://api.aisa.one/v1beta`); data APIs `https://api.aisa.one/apis/v1`. The `servers` of each operation in https://aisa.one/openapi.yaml is authoritative.
> - Auth: `Authorization: Bearer $AISA_API_KEY`. Never print, log, or commit the key.
> - MCP (preferred for agents): `https://mcp.aisa.one/mcp`, signed in with OAuth, so there is no key to paste.
> - Agent Skill: `npx skills add AIsa-team/agent-skills --skill aisa`. Fallback with the AIsa CLI: `aisa skills install aisa`.
> - Spending: docs, https://aisa.one/models, https://aisa.one/api, `/v1/models`, and MCP `search`, `list_categories`, `get_details`, `batch_quote`, and the `account` operation are free. Quote the exact calls before running them (MCP `batch_quote`, CLI `aisa quote --json`). If the quote reports `auto_execute_eligible: true`, run it unless the user set a tighter limit or asked only for a quote. Otherwise, tell the user in one message the planned calls, the quoted price, and a total USD budget for the task, then wait for approval. Direct HTTP calls follow the stricter rule at https://aisa.one/docs/get-started/cli.md#direct-http-fallback. Do not make paid calls to test availability. Full rule: https://aisa.one/llms.txt

# AIsa LLM Router

> 只需一个 AIsa key，即可跨多家 LLM 提供商路由提示词。

[在 GitHub 上查看 →](https://github.com/AIsa-team/agent-skills/tree/main/ai-models/llm-router)

**多款 LLM 的统一网关**。只需单个 API key，即可通过 AIsa 在各类兼容 OpenAI 的模型间路由智能体请求。

## 安装

```bash npx skills theme={null}
npx skills add AIsa-team/agent-skills --skill llm-router
```

```bash AIsa CLI theme={null}
npm install -g @aisa-one/cli
aisa skills install llm-router
```

安装后请启动新的智能体会话以加载该 Skill。

## 智能体能用它做什么？

> [card] 模型匹配
>
> 根据任务类型和约束条件挑选模型。

> [card] 提供商覆盖
>
> 在 GPT、Claude、Gemini、Qwen、DeepSeek、Grok 等多种模型间路由。

> [card] 成本感知路由
>
> 在质量要求允许时选择更经济的模型。

> [card] 回退规划
>
> 在模型不可用时建议备选方案。

## 🔥 你能用它做什么？

### 多模型对话

```
"Chat with GPT-4 for reasoning, switch to Claude for creative writing"
```

### 模型对比

```
"Compare responses from GPT-4, Claude, and Gemini for the same question"
```

### 视觉分析

```
"Analyze this image with GPT-4o - what objects are in it?"
```

### 成本优化

```
"Route simple queries to fast/cheap models, complex queries to GPT-4"
```

### 回退策略

```
"If GPT-4 fails, automatically try Claude, then Gemini"
```

## 为什么选择 LLM Router？

| 特性 | LLM Router | 直连 API |
| - | - | - |
| API key | 1 | 10+ |
| SDK 兼容性 | OpenAI SDK | 多种 SDK |
| 计费 | 统一 | 按提供商分别计费 |
| 模型切换 | 修改字符串 | 重写代码 |
| 回退路由 | 内置 | 自行实现 |
| 成本追踪 | 统一 | 分散 |

## 支持的模型家族

| 家族 | 开发者 | 示例模型 |
| - | - | - |
| GPT | OpenAI | gpt-5.5, gpt-5.4, gpt-5.4-mini, gpt-4o, gpt-4o-mini |
| Claude | Anthropic | claude-opus-4-8, claude-sonnet-4-6, claude-haiku-4-5-20251001 |
| Gemini | Google | gemini-3.8-flash |
| Qwen | Alibaba | qwen3.7-max, qwen-plus-2025-12-01, qwen-flash |
| Deepseek | Deepseek | deepseek-v4-pro, deepseek-v4.1-flash |
| Grok | xAI | grok-4.7, grok-4.5, grok-4.3 |

> **注意**：模型可用性可能会有所变化。请查看 [aisa.one/models](https://aisa.one/models) 获取当前可用模型与价格的完整列表。

## 快速开始

```bash theme={null}
export AISA_API_KEY="your-key"
```

## API 端点

### 兼容 OpenAI 的 Chat Completions

```
POST https://api.aisa.one/v1/chat/completions
```

#### 请求

```bash theme={null}
curl -X POST "https://api.aisa.one/v1/chat/completions" \
  -H "Authorization: Bearer $AISA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.4",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Explain quantum computing in simple terms."}
    ],
    "temperature": 0.7,
    "max_tokens": 1000
  }'
```

#### 参数

| 参数 | 类型 | 必填 | 描述 |
| - | - | - | - |
| `model` | string | 是 | 模型标识符（例如 `gpt-5.4`、`claude-opus-5`） |
| `messages` | array | 是 | 对话消息列表 |
| `temperature` | number | 否 | 随机性（0-2，默认值：1） |
| `max_tokens` | integer | 否 | 最大响应 token 数 |
| `stream` | boolean | 否 | 启用流式传输（默认值：false） |
| `top_p` | number | 否 | 核采样（0-1） |
| `frequency_penalty` | number | 否 | 频率惩罚（-2 到 2） |
| `presence_penalty` | number | 否 | 存在惩罚（-2 到 2） |
| `stop` | string/array | 否 | 停止序列 |

#### 消息格式

```json theme={null}
{
  "role": "user|assistant|system",
  "content": "message text or array for multimodal"
}
```

#### 响应

```json theme={null}
{
  "id": "chatcmpl-xxx",
  "object": "chat.completion",
  "created": 1234567890,
  "model": "gpt-5.4",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Quantum computing uses..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 50,
    "completion_tokens": 200,
    "total_tokens": 250
  }
}
```

### 流式响应

```bash theme={null}
curl -X POST "https://api.aisa.one/v1/chat/completions" \
  -H "Authorization: Bearer $AISA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4-6",
    "messages": [{"role": "user", "content": "Write a poem about AI."}],
    "stream": true
  }'
```

流式传输返回 Server-Sent Events (SSE)：

```
data: {"id":"chatcmpl-xxx","choices":[{"delta":{"content":"In"}}]}
data: {"id":"chatcmpl-xxx","choices":[{"delta":{"content":" circuits"}}]}
...
data: [DONE]
```

### 视觉 / 图像分析

通过传入图像 URL 或 base64 数据来分析图像：

```bash theme={null}
curl -X POST "https://api.aisa.one/v1/chat/completions" \
  -H "Authorization: Bearer $AISA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "user",
        "content": [
          {"type": "text", "text": "What is in this image?"},
          {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}
        ]
      }
    ]
  }'
```

### Function Calling

启用工具/函数以获取结构化输出：

```bash theme={null}
curl -X POST "https://api.aisa.one/v1/chat/completions" \
  -H "Authorization: Bearer $AISA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.4",
    "messages": [{"role": "user", "content": "What is the weather in Tokyo?"}],
    "functions": [
      {
        "name": "get_weather",
        "description": "Get current weather for a location",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {"type": "string", "description": "City name"},
            "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
          },
          "required": ["location"]
        }
      }
    ],
    "function_call": "auto"
  }'
```

### Google Gemini 格式

对于 Gemini 模型，你也可以使用原生格式：

```
POST https://api.aisa.one/v1beta/models/{model}:generateContent
```

```bash theme={null}
curl -X POST "https://api.aisa.one/v1beta/models/gemini-3.8-flash:generateContent" \
  -H "Authorization: Bearer $AISA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [{"text": "Explain machine learning."}]
      }
    ],
    "generationConfig": {
      "temperature": 0.7,
      "maxOutputTokens": 1000
    }
  }'
```

## Python 客户端

### 安装

无需安装——仅使用标准库。

### CLI 用法

```bash theme={null}
# Basic completion
python3 scripts/llm_router_client.py chat --model gpt-5.4 --message "Hello, world!"

# With system prompt
python3 scripts/llm_router_client.py chat --model claude-sonnet-4-6 --system "You are a poet" --message "Write about the moon"

# Streaming
python3 scripts/llm_router_client.py chat --model gpt-4o --message "Tell me a story" --stream

# Multi-turn conversation
python3 scripts/llm_router_client.py chat --model qwen3.7-max --messages '[{"role":"user","content":"Hi"},{"role":"assistant","content":"Hello!"},{"role":"user","content":"How are you?"}]'

# Vision analysis
python3 scripts/llm_router_client.py vision --model gpt-4o --image "https://example.com/image.jpg" --prompt "Describe this image"

# List supported models
python3 scripts/llm_router_client.py models

# Compare models
python3 scripts/llm_router_client.py compare --models "gpt-5.4,claude-sonnet-4-6,gemini-3.8-flash" --message "What is 2+2?"
```

### Python SDK 用法

```python theme={null}
from llm_router_client import LLMRouterClient

client = LLMRouterClient()  # Uses AISA_API_KEY env var

# Simple chat
response = client.chat(
    model="gpt-5.4",
    messages=[{"role": "user", "content": "Hello!"}]
)
print(response["choices"][0]["message"]["content"])

# With options
response = client.chat(
    model="claude-sonnet-4-6",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain relativity."}
    ],
    temperature=0.7,
    max_tokens=500
)

# Streaming
for chunk in client.chat_stream(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Write a story."}]
):
    print(chunk, end="", flush=True)

# Vision
response = client.vision(
    model="gpt-4o",
    image_url="https://example.com/image.jpg",
    prompt="What's in this image?"
)

# Compare models
results = client.compare_models(
    models=["gpt-5.4", "claude-sonnet-4-6", "gemini-3.8-flash"],
    message="Explain quantum computing"
)
for model, result in results.items():
    print(f"{model}: {result['response'][:100]}...")
```

## 使用场景

### 1. 成本优化路由

为简单任务使用更经济的模型：

```python theme={null}
def smart_route(message: str) -> str:
    # Simple queries -> fast/cheap model
    if len(message) < 50:
        model = "gpt-4o-mini"
    # Complex reasoning -> powerful model
    else:
        model = "gpt-5.4"
    
    return client.chat(model=model, messages=[{"role": "user", "content": message}])
```

### 2. 回退策略

失败时自动回退：

```python theme={null}
def chat_with_fallback(message: str) -> str:
    models = ["gpt-5.4", "claude-sonnet-4-6", "gemini-3.8-flash"]
    
    for model in models:
        try:
            return client.chat(model=model, messages=[{"role": "user", "content": message}])
        except Exception:
            continue
    
    raise Exception("All models failed")
```

### 3. 模型 A/B 测试

对比不同模型的输出：

```python theme={null}
results = client.compare_models(
    models=["gpt-5.4", "claude-opus-4-8"],
    message="Analyze this quarterly report..."
)

# Log for analysis
for model, result in results.items():
    log_response(model=model, latency=result["latency"], cost=result["cost"])
```

### 4. 专用模型选择

为每类任务选择最佳模型：

```python theme={null}
MODEL_MAP = {
    "code": "deepseek-v4-pro",
    "creative": "claude-opus-4-8",
    "fast": "gpt-4o-mini",
    "vision": "gpt-4o",
    "chinese": "qwen3.7-max",
    "reasoning": "gpt-5.4"
}

def route_by_task(task_type: str, message: str) -> str:
    model = MODEL_MAP.get(task_type, "gpt-5.4")
    return client.chat(model=model, messages=[{"role": "user", "content": message}])
```

## 错误处理

发生错误时将返回包含 `error` 字段的 JSON：

```json theme={null}
{
  "error": {
    "code": "model_not_found",
    "message": "Model 'xyz' is not available"
  }
}
```

常见错误码：

* `401` - API key 无效或缺失
* `402` - 余额不足
* `404` - 未找到模型
* `429` - 超出速率限制
* `500` - 服务器错误

## 最佳实践

1. **使用流式传输**：长响应采用流式传输以提升用户体验
2. **设置 max\_tokens**：控制成本
3. **实现回退机制**：保障生产可靠性
4. **缓存响应**：应对重复查询
5. **监控用量**：通过响应元数据掌握使用情况
6. **选用合适的模型**：不要在简单任务中使用 GPT-4

## OpenAI SDK 兼容性

只需更改 base URL 和 key：

```python theme={null}
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AISA_API_KEY"],
    base_url="https://api.aisa.one/v1"
)

response = client.chat.completions.create(
    model="gpt-5.4",
    messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
```

## 定价

基于 token 的定价因模型而异。请查看 [aisa.one/models](https://aisa.one/models) 获取当前费率。

每个响应均包含 `usage.cost` 和 `usage.credits_remaining`。

## 完整 API 参考

请参阅 [API 参考](https://aisa.one/docs/zh/api-reference.md) 查看完整的端点文档。

## 开始使用

1. 在 [aisa.one](https://aisa.one) 注册并在控制台中创建 API key。
2. 在你的 Shell 中设置：`export AISA_API_KEY="your-key"`。
3. 使用 [安装](#安装) 中的任一命令安装该 Skill，然后启动新的智能体会话。

## 相关

> [card] [模型目录](https://aisa.one/docs/zh/guides/models.md)
>
> 浏览支持的模型 ID 与模型家族。

> [card] [对比模型](https://aisa.one/models)
>
> 在路由生产流量之前对比模型。

> [card] [AIsa CN-LLM 路由](https://aisa.one/docs/zh/agent-skills/cn-llm.md)
>
> 中文大模型路由。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.