# 常见问题
Source: https://docs.aihubmix.com/cn/FAQs/Faq
高频问题请先查阅此文档
### 访问异常 / 接口无法连接怎么办?
若主域名 `https://aihubmix.com` 访问异常(如无法连接、超时),可将请求地址替换为备用域名 `https://api.inferera.com`,其余参数(API Key、模型、请求体等)保持不变。当模型调用失败且没有返回带tid的报错时,可以尝试在域名结尾添加或删除/v1,如:[https://api.inferera.com/v1](https://api.inferera.com/v1)
***
## 一、模型使用与安全
### AIHubMix是否会存储用户 API 请求内容?
* 默认情况下,AIHubMix 不会存储您通过 API 发送的任何请求内容,也不会记录模型返回的响应内容。AIHubMix 的角色仅为中转通道,用于将您的请求安全地转发至相应的模型提供商,并将对方的响应原样返回给您。
* **唯一的例外情况**:当您主动向我们反馈问题、提交错误报告或请求协助排查故障时,AIHubMix 可能会临时存储与错误相关的技术信息(如报错堆栈、调用元数据、接口状态等),以便我们进行诊断与处理。但这些信息**不会包含您的业务数据、提示词内容或完整的请求/响应载荷**。
***
### 为什么 Claude 或 GPT 等官方产品与 API 返回结果不同?
模型本身是相同的,不同在于网页版进行了额外的工程优化。
* 网页版相当于精装修房,内置搜索、记忆、计算器、系统提示等功能;
* API 调用相当于毛坯房,只提供核心能力,需要开发者自行配置上下文和工具。
***
### 为什么使用 GPT-5 或 o 系列模型时可能被 AIHubMix 封号?
在使用 GPT-5 或 o 系列模型时,如果在提示词中请求模型“展示推理过程”、“显示思维链”或 “reasoning trace” 等内容,系统可能会触发安全策略,导致账号被暂时限制或封禁。
* 官方对 GPT-5 与 o 系列模型的安全策略相对严格,正常使用不会导致封禁;
* 若出现误封或异常提示,可联系客服协助处理;
* 如需查看模型的推理摘要,可通过 Response API 获取结果,而不建议在 Prompt 中直接请求模型输出推理过程,以避免触发安全策略。
***
### 账户被禁用时如何处理?
若账户出现禁用情况,可联系在线客服或发送邮件至 [**feedback@aihubmix.com**](mailto:feedback@aihubmix.com) 申请处理或解封。
账户封禁通常由系统封控机制自动触发,常见原因包括以下两类:
1. **在沉浸式翻译场景中使用了 GPT-5 系列模型** 该系列模型属于推理模型,其设计目标是用于复杂推理与结构化内容生成,并不适合高频、实时的翻译任务。在此类场景下频繁调用,可能触发系统风控策略,从而导致账号被暂时限制或封禁。为确保账号稳定运行,翻译任务请优先选择非推理模型,例如:
* `gpt-4.1-mini`
* `gpt-4o-mini`
2. **使用 Grok 模型时发送了违规内容** 在调用 Grok 模型过程中,如请求内容被系统判定为违反使用规范(例如涉及暴力、血腥、色情等违规信息),将直接触发封禁机制。请确保请求内容符合平台及模型的使用规范,避免发送违法或不当内容。
如遇误封或异常限制情况,可通过客服或邮件渠道提交申诉申请。但需注意,**若账户多次触发封禁记录,可能将无法再次解封**。
如你是开发者,可在请求前使用 AIHUBMIX 的[审查接口](https://docs.aihubmix.com/cn/api/moderation)对输入内容进行合规检查,以降低违规风险。该步骤为可选项,但在内容开放或用户输入不可控的应用场景中,强烈建议使用。
***
### **为什么账户有余额,但仍然无法调用某些模型(如 Claude Opus 系列、GPT-5.4-Pro 系列)?**
平台已启用预扣费机制。当调用成本较高的模型(如 Claude Opus、GPT-5.4-Pro 等)时,系统会在请求发起时根据最大可能的输出 Token 数量预估费用并进行余额校验。如果账户余额 \< `输出 Token 单价 × 最大输出 Token 数量`,请求可能会被拒绝。建议在调用此类模型前确保账户余额充足,并合理设置最大输出参数;若未设置,系统将使用默认值进行预估。不同模型的最大输出参数名称不同:Claude、GPT 系列为 `max_tokens`,Gemini 系列为 `max_output_tokens`。
### 为什么不推荐在翻译类工具中使用 GPT-5 系列模型?
GPT-5 系列属于推理模型,设计目标是执行复杂推理与结构化生成,不适合高频实时任务。
**原因:**
* 调用速度较慢(推理步骤多);
* 消耗更多 Token(系统提示和推理上下文较长);
* 翻译插件可能误触安全策略。
翻译或对话场景推荐使用 GPT-4o mini 或 Gemini 等轻量模型,响应更快更稳定。
***
### 为什么问“你是谁”时,GPT-5 有时会回答“我是 GPT-4”?
这种现象属于语言模型的幻觉,表现为模型对自身基座、来源或能力的描述错误。 在使用 GPT-4、GPT-5、Claude 等大语言模型时,开发者可能会遇到模型自信却不准确地回答自身身份的情况。
**说明:**
* 这种现象并非平台故意修改或替换模型输出,也不是“移花接木”,属于 LLM 的正常行为;
* GPT-5 在训练阶段并未被赋予“GPT-5”这个名称,这个名字是官方在训练完成后定义的;
* 模型本身不知道自己的名称或知识库时间;如果 OpenAI 的网页版本能正确回答是因为网页内置了系统提示词;我们这边是官方的 API 版本非网页版本。
* 通过 API 直接询问模型自身身份时,回答可能随机且不准确,因为模型本身并不具备自我认知。
***
### 调用某些模型(如 Gemini-3-Pro)时经常超时怎么办?
请提高超时设置时长。Gemini-3-Pro 属于大模型,推理过程会有较长的思考时间,尤其在复杂任务下响应时间可能超过 30 秒。因此 30s 的默认设置容易导致超时。
* 如果必须使用 Gemini-3-Pro,请将超时时间适当延长。
* 如果对响应速度要求较高,建议改用 Gemini 2.0 等轻量模型,更适合短时间超时配置。
***
### 为什么只发了一句“你好”,却消耗了很多 Tokens?
部分第三方工具(如 Cline、Claude Code 等)在请求时会自动携带上下文或系统提示,这些隐藏内容也会计入 Token 消耗。
即使用户只输入一句“你好”,后台请求中可能包含大量历史对话或设定文本。
这些附加内容来自工具端,而非 AiHubMix 平台生成。
***
### 为什么我只调用了 GPT-4o,却也看到 4o-mini 的消耗?
在部分第三方工具或场景中,为了实现对话总结、搜索或辅助计算等功能,系统可能会额外调用轻量模型(如 4o-mini)来处理这些任务。因此,在账单或日志中可能会出现多个模型的混合消耗记录。
这种额外消耗来源于工具功能的配置,而非 AiHubMix 自动切换模型。
***
### API 并发请求的频率限制是多少?
AiHubMix 当前对并发请求没有统一限制。若遇到并发问题,请联系客服。
***
### 为什么相同提示词,每次生成结果不同?
大模型在生成文本时使用概率采样机制(如 temperature、top-p 等),每次会从多个可能的词中随机选择。
* 若希望结果更稳定,可降低 temperature 或关闭采样;
* 生成差异也可能受上下文、系统提示或网络环境影响。
***
### 使用 Claude 模型时,为什么回答会提前结束?
针对 Claude 模型,AIHubMix 当前支持两种调用方式:
1. OpenAI Chat 兼容接口
2. Anthropic Claude 原生接口
当通过 OpenAI Chat 兼容接口调用 Claude 模型时,系统默认 max\_tokens=4096。 如果请求中未显式设置更大的 max\_tokens,模型将在达到该上限后自动停止输出。因此,出现“回答未完成即结束”的情况,通常并非模型异常,而是触达了默认输出长度限制。
**如何生成更长文本?**
在 OpenAI Chat 兼容接口下,可手动设置更大的 max\_tokens 参数,例如:
```Python theme={null}
completion = client.chat.completions.create(
model="claude-sonnet-4-6",
max_tokens=6000,
messages=[
{
"role": "assistant",
"content": "总是用中文回复"
},
{
"role": "user",
"content": "What is the meaning of life?, over 6000 words"
}
]
)
```
max\_tokens 不得超过对应模型的最大支持上限,如设置后如仍出现截断情况,可提供模型名称及完整请求参数以便进一步排查。
***
## 二、API 调用与数据
### 有哪些可用的 API 接口?
AIHubMix 提供统一网关,兼容多种主流模型规范:
* **OpenAI 标准端点**:`https://aihubmix.com/v1`(支持 GPT 及兼容模型)
* **Gemini 专属端点**:`https://aihubmix.com/gemini`(适配 Google 原生规范)
* **Claude 自动转发端点**:`https://aihubmix.com`(兼容 Anthropic SDK 调用方式)
***
### API 使用期间会记录哪些数据?
我们仅记录必要的使用数据,包括账户信息、调用记录、使用模型、Token 消耗量及支付信息。
**隐私保障:**
* 不会保存用户输入或模型输出内容;
* 数据仅用于计费与服务优化,不会用于内容分析或向第三方共享;
* AiHubMix 自身不会保留具体请求数据,但若底层云厂商(如模型提供方或托管平台)出于安全或合规要求记录访问日志,该部分数据将受其隐私政策约束。
详情请见[《AIHubMix 隐私政策》](https://aihubmix.com/legal/privacy)。
***
## 三、模型知识与常见现象
### 什么是 AI 幻觉(AI Hallucination)?
AI 幻觉是指大型语言模型生成与事实不符、缺乏依据或完全虚构的信息。
**可能原因:**
* 训练数据偏差或缺失;
* 模型参数过拟合;
* 生成阶段存在随机性。
幻觉是所有大语言模型的共性现象,并非系统故障。
***
## 四、使用与故障排查
### 如何监控 API 使用情况和消耗?
可通过 AiHubMix 控制台查看调用量、Token 消耗量及计费明细。
支持按模型、时间段进行分类统计,便于优化调用策略和成本管理。
***
### 调用失败或报错时该怎么办?
API 返回错误时会附带错误码与说明。
常见原因包括:
* 请求格式错误;
* 模型不可用或超出限额。
可参考[《API 手册》](https://docs.aihubmix.com/cn/api-reference)快速定位问题,或联系客服获取支持。
***
### 如何管理 API Key?
用户可在控制台生成、撤销或更新 API Key。
**安全建议:**
* 不要在公共环境中暴露 API Key;
* 为不同项目使用独立 Key;
* 定期更换以保障账户安全。
***
更新时间:2026-06-01
# 提交反馈
Source: https://docs.aihubmix.com/cn/FAQs/Feedback
遇到问题时,可以通过工单表单向我们提交反馈,附上 Tid 可以帮助我们更快定位问题。
填写表单,通常在 1 个工作日内回复
## 表单填写指南
### Category(问题分类)
请选择最符合的问题类型,这有助于我们将工单分配给正确的团队:
| 分类 | 说明 |
| ---------------------- | ------------------------- |
| **Latency** | 响应速度明显慢于预期 |
| **Incoherence** | 模型回复混乱、重复或答非所问 |
| **Incorrect Response** | 回复包含明显的事实错误或错误信息 |
| **Formatting** | Markdown、代码块、JSON 等格式输出异常 |
| **Billing** | 计费金额异常或 Token 消耗与预期不符 |
| **API Error** | 请求失败、返回错误码或连接异常 |
| **Other** | 其他未涵盖的问题 |
### Subject(主题)
用一句话概括问题,例如:`Claude Sonnet 4.5 在流式输出时返回 500`。上限 200 字符。
### Description(详细描述)
描述越具体,排查越快。建议包含以下信息:
* 使用的模型名称(例如 `claude-sonnet-4-6`、`gpt-4o`)
* 完整的错误信息或异常返回内容
* 复现步骤或最小可复现代码
* 首次出现的时间
### Tid(追踪 ID,可选)
Tid 是每次 API 请求的唯一标识符,提供后我们可以直接在系统中查找对应记录,**强烈建议填写**。
**如何获取 Tid:**
* **API 响应**:从返回结果的 `request id` 字段中获取
* **控制台**:Dashboard → [Log Detail](https://console.aihubmix.com/statistics?tab=detail),找到对应请求即可查看 Tid
Tid 格式示例:`20260519133124...`,通常为时间戳开头的长数字串。
### Reply Email(回复邮箱)
系统会自动填入账户绑定的邮箱。如需将回复发送到其他邮箱,可手动修改。
***
## 其他联系方式
## 如工单渠道无法满足需求,也可以发邮件至 [feedback@aihubmix.com](mailto:feedback@aihubmix.com) 联系我们。
更新时间:2026-06-01
# HTTP 状态码
Source: https://docs.aihubmix.com/cn/FAQs/HTTP-Codes
关键错误代码映射表
* 400 状态码通常是传参错误,请查看接口文档。大部分 400 错误是上游透传的报错。
* 错误响应中的 response ID 已更改为 tid (traceId),用于错误追踪和问题定位。
| 状态码 | 错误标识符 | 错误消息 | 常见原因 |
| :-: | ------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------- |
| 503 | - | Incorrect model ID. Please request to view the model page or you do not have permission to use this model | 没有可用的渠道处理请求 |
| 503 | - | Rate limited by provider – contact support to request higher concurrency or try again later. | 模型遇到官方限速 |
| 429 | - | The xx(xx: model id) model Too many requests; please try again later. | 请求频率超过限制 |
| 403 | insufficient\_user\_quota | Your account balance is insufficient. Please recharge your account to continue using the API. | 用户余额不足,需要充值 |
| 403 | - | Account suspended. | 用户状态被禁用或在黑名单 |
| 403 | - | Forbidden – insufficient permissions. | 用户角色权限不够 |
| 403 | - | Forbidden – key(请求的 key 后六位) allowed only from approved IP ranges. | IP 不在令牌允许的网段内 |
| 403 | - | Forbidden – key(请求的 key 后六位) not authorized to access the requested model. | 令牌不支持请求的模型 |
| 403 | - | Key error;(请求的 key 后六位) | 非管理员用户尝试指定渠道 |
| 403 | - | Forbidden – channel has been disabled. | 渠道状态为禁用 |
| 401 | - | Unauthorized – no access token supplied; please log in and include a valid token. | 未提供 Authorization 头 |
| 401 | - | Unauthorized – access token is invalid or expired. | access token 验证失败 |
| 400 | - | Bad Request – invalid channel ID. | 渠道 ID 格式错误或不存在 |
| 400 | prompt\_missing | prompt is required | 图片生成缺少提示词 |
| 400 | prompt\_too\_long | prompt is too long | 提示词超过长度限制 |
| 400 | text\_too\_long | input is too long | 音频输入文本过长 |
| 400 | size\_not\_supported | size not supported | 图片尺寸不被模型支持 |
| 400 | n\_not\_within\_range | invalid value of n | n 参数值不在有效范围 |
***
更新时间:2026-06-01
# Agent 接入
Source: https://docs.aihubmix.com/cn/agents
AIHubMix 面向 AI Agent 的全部接入入口:agents.md 接入说明、llms.txt 机读索引、每模型 llms.txt 调用指南、Playground Skill、Playground 深链。每项一条可复制命令。
AIHubMix 为 AI Agent(Claude Code、Codex、Cursor、Cline 等编程助手)提供一组机器可读的接入入口。Agent 可以自行完成发现模型、生成调用、验证连通、直至把配置好的 Playground 链接交回给你。本页汇总全部入口,每项一条可复制命令。
## 一句话上手
把下面这句话发给你的 AI Agent:
```text theme={null}
Fetch https://aihubmix.com/agents.md and follow it.
```
`agents.md` 是写给 Agent 直接执行的接入说明:检查 API Key、从实时目录选模型、按协议调用、端到端验证,并包含故障排查表。
## 入口总览
| 入口 | 地址 | 用途 |
| ---------------- | ----------------------------------------------------------- | ------------------------------- |
| Agent 接入说明 | `https://aihubmix.com/agents.md` | Agent 自助完成接入与验证的分步说明 |
| 站点机读索引 | `https://aihubmix.com/llms.txt` | 全站能力与文档的 LLM 可读索引 |
| 文档机读索引 | `https://docs.aihubmix.com/llms.txt` | 文档站全量页面索引,任意文档页地址后加 `.md` 可取纯文本 |
| 每模型调用指南 | `https://aihubmix.com/model/{model_id}/llms.txt` | 单个模型的价格、已核实能力、协议端点与可运行示例 |
| Playground Skill | `https://aihubmix.com/skills/playground` | 试用、调参、对比模型与生成媒体的 Agent 技能文件 |
| 实时模型目录 | `https://aihubmix.com/api/v1/models?type=llm&sort_by=order` | 免鉴权 JSON,含价格与元数据 |
## 每模型 llms.txt
每个模型都有一份机器可读的调用指南,包含价格、已核实的能力清单、支持的协议端点和可运行示例:
```bash theme={null}
curl -s https://aihubmix.com/model/gemini-3.7-flash/llms.txt
```
模型详情页上的 `llms.txt` 标签可直接打开对应文件。尚未完成核实的模型返回一份指引文档,指向实时目录与参数 schema,不包含未经核实的能力声明。
## Playground Skill
把 Playground 的能力(模型试用、参数调试、同题对比、图像与视频生成、深链接力)交给你的 Agent:
```text theme={null}
Run curl -fsSL https://aihubmix.com/skills/playground and follow it.
```
Skill 同时发布在 `/.well-known/skills/aihubmix-playground/SKILL.md`,也可通过 [GitHub 仓库](https://github.com/AIhubmix/skills) 以 `npx skills add AIhubmix/skills` 安装。接入与集成场景请使用 [AIHubMix API Skill](/cn/skills)。
## Playground 深链
Agent 可以生成直达链接,让你在浏览器中接手一个已配置好的 Playground 会话:
* 多模型开局:`https://playground.aihubmix.com/?models=gemini-3.7-flash,claude-opus-4-1`(一条链接开出最多 6 个模型的标签页)
* 配置直达:`https://playground.aihubmix.com/?config=`,JSON 形如 `{"model": "...", "proto": "chat", "params": {...}, "system": "...", "draft": "..."}`,`draft` 预填输入框但不发送
* 规格与价格并排对比:主站对比页 `https://aihubmix.com/compare/{model_a}/{model_b}`,任意两个模型的规格、价格与能力并排展示,Agent 可直接生成链接
链接为一次性参数:页面加载后地址栏参数即被清除,不携带任何密钥。
## 代码生成
npm 包 [`@aihubmix/codegen`](https://www.npmjs.com/package/@aihubmix/codegen) 提供 4 协议、7 语言的程序化代码生成,其构造的请求体与 Playground 实际发出的请求体一致;[`@aihubmix/model-schema`](https://www.npmjs.com/package/@aihubmix/model-schema) 将参数 schema 转换为 codegen 输入。
## 常见问题
### Agent 如何验证接入成功?
`agents.md` 内含端到端验证步骤:发送一条要求精确回复的最小请求,检查响应正文与模型回显。HTTP 200 不等于成功,需要检查响应内容。
### 这些入口需要凭证吗?
读取本页全部机读入口(agents.md、llms.txt、每模型 llms.txt、Skill 文件、模型目录)不需要任何凭证,直接访问即可。只有发起真实模型调用时才需要 AIHubMix API Key:通过环境变量 `AIHUBMIX_API_KEY` 传递,可在 [控制台](https://console.aihubmix.com/token) 创建。请勿把 Key 写入代码、脚本或对话。
### 每模型 llms.txt 覆盖哪些模型?
已核实模型返回完整文档(能力清单来自官方核实数据),其余模型返回指引文档。覆盖范围随核实进度扩大。
### 目前对 MCP 的支持情况如何?
MCP 端点当前提供图像生成服务,能力扩展进行中。当前阶段建议优先使用 Skill 与 agents.md 接入。
***
更新时间:2026-08-20
# Create an AIHubMix image generation
Source: https://docs.aihubmix.com/cn/api-reference/aihubmix-unified-api/create-an-aihubmix-image-generation
/openapi.json post /ai/v1/images/generations
Generates images with the AIHubMix native media protocol. Requests are synchronous by default and become asynchronous when `async` is `true`.
# Create an AIHubMix video task
Source: https://docs.aihubmix.com/cn/api-reference/aihubmix-unified-api/create-an-aihubmix-video-task
/openapi.json post /ai/v1/videos
Creates a video task with the AIHubMix native media protocol. Video generation is always asynchronous.
# Download an AIHubMix image result
Source: https://docs.aihubmix.com/cn/api-reference/aihubmix-unified-api/download-an-aihubmix-image-result
/openapi.json get /ai/v1/images/{id}/content/{result_id}
Downloads one result from a completed image task. Clients normally use the `output[].content_url` returned by the task object.
# Download an AIHubMix video
Source: https://docs.aihubmix.com/cn/api-reference/aihubmix-unified-api/download-an-aihubmix-video
/openapi.json get /ai/v1/videos/{id}/content
Downloads the primary video result from a completed video task.
# Get a model's supported endpoints and request Schemas
Source: https://docs.aihubmix.com/cn/api-reference/aihubmix-unified-api/get-a-models-supported-endpoints-and-request-schemas
/openapi.json get /call/schema/models/{model}/endpoints
Returns all currently discoverable protocol endpoints for a media model. Select an endpoint by `path`; do not depend on array order.
# Get a specific unified task result
Source: https://docs.aihubmix.com/cn/api-reference/aihubmix-unified-api/get-a-specific-unified-task-result
/openapi.json get /ai/v1/tasks/{id}/content/{result_id}
Downloads one result from a task with multiple artifacts.
# Get a unified AIHubMix task
Source: https://docs.aihubmix.com/cn/api-reference/aihubmix-unified-api/get-a-unified-aihubmix-task
/openapi.json get /ai/v1/tasks/{id}
Returns a read-only task snapshot. Poll active media through the image or video detail endpoint instead.
# Get an AIHubMix image task
Source: https://docs.aihubmix.com/cn/api-reference/aihubmix-unified-api/get-an-aihubmix-image-task
/openapi.json get /ai/v1/images/{id}
Returns the latest state of an image task. Poll this endpoint for asynchronous image generation.
# Get an AIHubMix video task
Source: https://docs.aihubmix.com/cn/api-reference/aihubmix-unified-api/get-an-aihubmix-video-task
/openapi.json get /ai/v1/videos/{id}
Returns the latest state of a video task. Poll this endpoint until the task reaches a terminal state.
# Get the primary unified task result
Source: https://docs.aihubmix.com/cn/api-reference/aihubmix-unified-api/get-the-primary-unified-task-result
/openapi.json get /ai/v1/tasks/{id}/content
Downloads a single media artifact or returns an archived LLM response. Multi-result tasks require the result-specific endpoint.
# List AIHubMix image tasks
Source: https://docs.aihubmix.com/cn/api-reference/aihubmix-unified-api/list-aihubmix-image-tasks
/openapi.json get /ai/v1/images
Returns snapshots of image tasks created by the current API key.
# List AIHubMix video tasks
Source: https://docs.aihubmix.com/cn/api-reference/aihubmix-unified-api/list-aihubmix-video-tasks
/openapi.json get /ai/v1/videos
Returns snapshots of video tasks created by the current API key.
# List models with media request Schemas
Source: https://docs.aihubmix.com/cn/api-reference/aihubmix-unified-api/list-models-with-media-request-schemas
/openapi.json get /api/v1/models
Lists image or video models from the public model directory. Use `schema_checked=true` to return models whose request Schema has been reviewed.
# List unified AIHubMix tasks
Source: https://docs.aihubmix.com/cn/api-reference/aihubmix-unified-api/list-unified-aihubmix-tasks
/openapi.json get /ai/v1/tasks
Returns read-only snapshots of image, video, and recoverable LLM tasks created by the current API key.
# Create a Message
Source: https://docs.aihubmix.com/cn/api-reference/anthropic-compatible/create-a-message
/openapi.json post /v1/messages
Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation.
The Messages API can be used for either single queries or stateless multi-turn conversations.
Learn more about the Messages API in our [user guide](https://docs.claude.com/en/docs/initial-setup)
# Generate Content
Source: https://docs.aihubmix.com/cn/api-reference/google-vertex-ai-compatible/generate-content
/openapi.json post /gemini/v1beta/models/{model}:generateContent
Native Gemini protocol entry point. Mirrors the request and response
shapes of `https://generativelanguage.googleapis.com` — clients may
point the google-genai SDK at this gateway directly.
# Create a Chat Completion
Source: https://docs.aihubmix.com/cn/api-reference/openai-compatible/create-a-chat-completion
/openapi.json post /v1/chat/completions
**Starting a new project?** We recommend trying [Responses](https://developers.openai.com/api/docs/api-reference/responses)
to take advantage of the latest OpenAI platform features. Compare
[Chat Completions with Responses](https://developers.openai.com/api/docs/guides/responses-vs-chat-completions?api-mode=responses).
---
Creates a model response for the given chat conversation. Learn more in the
[text generation](https://developers.openai.com/api/docs/guides/text-generation), [vision](https://developers.openai.com/api/docs/guides/vision),
and [audio](https://developers.openai.com/api/docs/guides/audio) guides.
Parameter support can differ depending on the model used to generate the
response, particularly for newer reasoning models. Parameters that are only
supported for reasoning models are noted below. For the current state of
unsupported parameters in reasoning models,
[refer to the reasoning guide](https://developers.openai.com/api/docs/guides/reasoning).
Returns a chat completion object, or a streamed sequence of chat completion
chunk objects if the request is streamed.
# Create a Completion
Source: https://docs.aihubmix.com/cn/api-reference/openai-compatible/create-a-completion
/openapi.json post /v1/completions
Creates a completion for the provided prompt and parameters.
Returns a completion object, or a sequence of completion objects if the request is streamed.
# Create a Model Response
Source: https://docs.aihubmix.com/cn/api-reference/openai-compatible/create-a-model-response
/openapi.json post /v1/responses
Creates a model response. Provide [text](https://developers.openai.com/api/docs/guides/text) or
[image](https://developers.openai.com/api/docs/guides/images) inputs to generate [text](https://developers.openai.com/api/docs/guides/text)
or [JSON](https://developers.openai.com/api/docs/guides/structured-outputs) outputs. Have the model call
your own [custom code](https://developers.openai.com/api/docs/guides/function-calling) or use built-in
[tools](https://developers.openai.com/api/docs/guides/tools) like [web search](https://developers.openai.com/api/docs/guides/tools-web-search)
or [file search](https://developers.openai.com/api/docs/guides/tools-file-search) to use your own data
as input for the model's response.
# Create a Video
Source: https://docs.aihubmix.com/cn/api-reference/openai-compatible/create-a-video
/openapi.json post /v1/videos
Create a new video generation job from a prompt and optional reference assets.
# Create an Embedding
Source: https://docs.aihubmix.com/cn/api-reference/openai-compatible/create-an-embedding
/openapi.json post /v1/embeddings
Creates an embedding vector representing the input text.
# Create Moderation
Source: https://docs.aihubmix.com/cn/api-reference/openai-compatible/create-moderation
/openapi.json post /v1/moderations
Classifies if text and/or image inputs are potentially harmful. Learn
more in the [moderation guide](https://developers.openai.com/api/docs/guides/moderation).
# Create Speech
Source: https://docs.aihubmix.com/cn/api-reference/openai-compatible/create-speech
/openapi.json post /v1/audio/speech
Generates audio from the input text.
Returns the audio file content, or a stream of audio events.
# Create Transcription
Source: https://docs.aihubmix.com/cn/api-reference/openai-compatible/create-transcription
/openapi.json post /v1/audio/transcriptions
Transcribes audio into the input language.
Returns a transcription object in `json`, `diarized_json`, or `verbose_json`
format, or a stream of transcript events.
# Create Translation
Source: https://docs.aihubmix.com/cn/api-reference/openai-compatible/create-translation
/openapi.json post /v1/audio/translations
Translates audio into English.
# Delete a Video
Source: https://docs.aihubmix.com/cn/api-reference/openai-compatible/delete-a-video
/openapi.json delete /v1/videos/{video_id}
Permanently delete a completed or failed video and its stored assets.
# Download Video Content
Source: https://docs.aihubmix.com/cn/api-reference/openai-compatible/download-video-content
/openapi.json get /v1/videos/{video_id}/content
Download the generated video bytes or a derived preview asset.
Streams the rendered video content for the specified video job.
# Generate Images
Source: https://docs.aihubmix.com/cn/api-reference/openai-compatible/generate-images
/openapi.json post /v1/images/generations
Creates an image given a prompt. [Learn more](https://developers.openai.com/api/docs/guides/images).
# Remix a Video
Source: https://docs.aihubmix.com/cn/api-reference/openai-compatible/remix-a-video
/openapi.json post /v1/videos/{video_id}/remix
Create a remix of a completed video using a refreshed prompt.
# Retrieve a Video
Source: https://docs.aihubmix.com/cn/api-reference/openai-compatible/retrieve-a-video
/openapi.json get /v1/videos/{video_id}
Fetch the latest metadata for a generated video.
# 3D 生成接口
Source: https://docs.aihubmix.com/cn/api/3D-Gen
AiHubMix 提供统一的 3D 模型生成 API,支持文生 3D 与图生 3D,异步任务模式,首批支持腾讯混元 3D(hy-3d-3.1),产物支持 obj / glb / stl / usdz / fbx 格式与 PBR 材质
## 快速开始
3D 生成是异步操作,整个流程分为三步:
```text theme={null}
1. 提交任务 → 获得 generation_id
2. 轮询状态 → 等待 status 变为 completed
3. 下载产物 → 通过 output 中的 content_url 直接下载 3D 文件
```
**最简示例**
```shellscript theme={null}
# 第一步:提交 3D 生成任务(文生 3D)
curl -X POST https://aihubmix.com/v1/3d/generations \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "hy-3d-3.1",
"prompt": "一只戴帽子的柴犬"
}'
# 响应示例:
# {
# "id": "eyJtb2RlbCI6Imh5LTNkLTMuMSIsIml...",
# "object": "3d.generation",
# "model": "hy-3d-3.1",
# "status": "queued",
# "output": null,
# "error": null,
# "created_at": 1752728000,
# "completed_at": null,
# "expires_at": 1752814400
# }
# 第二步:轮询查询状态(每 10~15 秒查询一次,直到 status 为 completed)
curl https://aihubmix.com/v1/3d/generations/{generation_id} \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
# 第三步:下载产物(content_url 为临时地址,可直接下载,无需鉴权)
curl "{content_url}" --output model.glb
```
## 接口概览
| 接口 | 方法 | 路径 | 说明 |
| :------- | :--- | :----------------------------------- | :--------- |
| 创建 3D 任务 | POST | `/v1/3d/generations` | 提交 3D 生成任务 |
| 查询状态 | GET | `/v1/3d/generations/{generation_id}` | 查询任务状态与产物 |
Base URL:`https://aihubmix.com`
认证方式:Bearer Token
```shellscript theme={null}
Authorization: Bearer $AIHUBMIX_API_KEY
```
与视频接口不同,3D 接口**没有** `/content` 下载端点和 `DELETE` 删除端点:产物通过查询响应 `output[]` 中的 `content_url` 直接下载。
## 支持的模型
| 厂商 | 模型名称 | 特点 |
| -- | ----------- | ---------------------------------------- |
| 腾讯 | `hy-3d-3.1` | 混元 3D 3.1,支持文生 3D、图生 3D、草图生 3D,可选 PBR 材质 |
**生成类型(`generate_type`)**
| 类型 | 说明 |
| :--------- | :--------------------- |
| `Normal` | 标准生成(默认),几何 + 纹理 |
| `Geometry` | 仅生成几何白模,不含纹理 |
| `Sketch` | 草图生 3D,允许同时传入草图图片与文字描述 |
## API 详细说明
### 请求头
```shellscript theme={null}
Authorization: Bearer $AIHUBMIX_API_KEY
Content-Type: application/json
```
### 创建 3D 生成任务
```shellscript theme={null}
POST /v1/3d/generations
```
#### **请求体**
| 参数 | 类型 | 必填 | 说明 |
| :----------------- | :----- | :- | :---------------------------------------------------------------------------------------------------------------------------------------- |
| `model` | string | 是 | 模型名称:`hy-3d-3.1` |
| `prompt` | string | 条件 | 文本描述,不超过 1024 字符;与 `input_references` 至少传其一 |
| `input_references` | array | 条件 | 参考图数组(图生 3D),当前仅支持 1 张;项内 `image_url` 与 `image_base64` 二选一 |
| `generate_type` | string | 否 | 生成类型:`Normal`(默认)/ `Geometry` / `Sketch`,大小写不敏感 |
| `enable_pbr` | bool | 否 | 是否生成 PBR 材质,默认 `false` |
| `face_count` | int | 否 | 目标面数,范围 `3000` \~ `1500000`;不传由模型默认决定 |
| `format` | string | 否 | 产物格式:`stl` / `usdz` / `fbx`,大小写不敏感;不传时由模型推理厂商默认决定(Normal 通常返回 obj + glb,Geometry 仅 glb);指定格式为**追加**生成(如 `format: "stl"` 返回 glb + stl,非替换) |
| `extra_body` | object | 否 | 其余模型推理厂商原生参数透传(见下方说明) |
**参数校验规则**
* `prompt` 与 `input_references` **互斥**(只能传其一),仅 `generate_type: "Sketch"` 允许两者同传(草图 + 文字描述)。
* `input_references` 每项中 `image_url` 与 `image_base64` 必须**恰好传一个**:
* `image_url` 仅支持 `http(s)` 公网 URL,**不支持 data URL**(请改用 `image_base64`);
* `image_base64` 解码后不超过 **6MB**。
* `hy-3d-3.1` 不支持 `LowPoly` 生成类型。
* 请求体总大小不超过 **10MB**。
**`extra_body` 使用说明**:模型推理厂商原生参数(如 `polygon_type`)可放入 `extra_body` 顶层透传。以下参数**必须使用顶层字段**传入,出现在 `extra_body` 中会返回 400:`model`、`prompt`、`image_url`、`image_base64`、`generate_type`、`enable_pbr`、`face_count`、`result_format`;`multi_view_images`(多视角图)暂不支持。
#### 响应示例
```json theme={null}
{
"id": "eyJtb2RlbCI6Imh5LTNkLTMuMSIsIml...",
"object": "3d.generation",
"model": "hy-3d-3.1",
"status": "queued",
"output": null,
"error": null,
"created_at": 1752728000,
"completed_at": null,
"expires_at": 1752814400
}
```
#### 状态值说明
| 状态 | 说明 |
| :------------ | :---------------------- |
| `queued` | 排队中 |
| `in_progress` | 生成中 |
| `completed` | 生成完成,`output` 中包含产物下载地址 |
| `failed` | 生成失败,`error` 中包含错误信息 |
### 查询任务状态
```shellscript theme={null}
GET /v1/3d/generations/{generation_id}
```
轮询此接口检查任务是否完成。建议每 **10\~15 秒** 查询一次。查询不计费。
#### **响应示例(生成完成)**
```json theme={null}
{
"id": "eyJtb2RlbCI6Imh5LTNkLTMuMSIsIml...",
"object": "3d.generation",
"model": "hy-3d-3.1",
"status": "completed",
"output": [
{
"type": "obj",
"b64_json": null,
"content_url": "https://example-cos.tencentcos.cn/.../model.obj?sign=...",
"preview_url": "https://example-cos.tencentcos.cn/.../preview.png?sign=..."
},
{
"type": "glb",
"b64_json": null,
"content_url": "https://example-cos.tencentcos.cn/.../model.glb?sign=..."
}
],
"error": null,
"created_at": 1752728000,
"completed_at": 1752728180,
"expires_at": 1752814400
}
```
**`output[]` 字段说明**
| 字段 | 说明 |
| :------------ | :----------------------------------------- |
| `type` | 产物文件类型(小写),如 `obj`、`glb`、`stl` |
| `b64_json` | 恒为 `null`(3D 产物不内联返回,统一走 `content_url` 下载) |
| `content_url` | 产物下载地址(临时链接),**请尽快下载转存** |
| `preview_url` | 预览缩略图地址(模型推理厂商提供时返回) |
`content_url` 与 `preview_url` 为**临时链接**,会在一段时间后过期,请在任务完成后尽快下载并转存到自己的存储。任务 ID 自创建起 **24 小时**内可查询(`expires_at` 字段即查询截止时刻),过期后查询将返回错误。临时链接仅支持 GET 请求,HEAD 请求会返回 403。
## 使用示例
```shellscript 文生 3D theme={null}
curl -X POST https://aihubmix.com/v1/3d/generations \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "hy-3d-3.1",
"prompt": "一辆复古蒸汽朋克风格的摩托车,黄铜质感,细节丰富",
"enable_pbr": true
}'
```
```shellscript 图生 3D(URL) theme={null}
curl -X POST https://aihubmix.com/v1/3d/generations \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "hy-3d-3.1",
"input_references": [
{ "image_url": "https://example.com/cat.png" }
]
}'
```
```shellscript 图生 3D(Base64) theme={null}
curl -X POST https://aihubmix.com/v1/3d/generations \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "hy-3d-3.1",
"input_references": [
{ "image_base64": "" }
]
}'
```
```shellscript 草图生 3D(Sketch) theme={null}
curl -X POST https://aihubmix.com/v1/3d/generations \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "hy-3d-3.1",
"generate_type": "Sketch",
"prompt": "科幻风格的飞行器,金属外壳",
"input_references": [
{ "image_url": "https://example.com/sketch.png" }
]
}'
```
```shellscript 指定面数与格式 theme={null}
curl -X POST https://aihubmix.com/v1/3d/generations \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "hy-3d-3.1",
"prompt": "一个中世纪骑士头盔",
"generate_type": "Normal",
"enable_pbr": true,
"face_count": 40000,
"format": "fbx"
}'
```
## 完整调用示例
```python Python theme={null}
import requests
import time
API_KEY = "AIHUBMIX_API_KEY"
BASE_URL = "https://aihubmix.com"
HEADERS = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
# 第一步:创建 3D 生成任务
response = requests.post(
f"{BASE_URL}/v1/3d/generations",
headers=HEADERS,
json={
"model": "hy-3d-3.1",
"prompt": "一只戴帽子的柴犬",
"enable_pbr": True
}
)
result = response.json()
generation_id = result["id"]
print(f"任务已创建,generation_id: {generation_id}")
# 第二步:轮询查询状态
while True:
status_response = requests.get(
f"{BASE_URL}/v1/3d/generations/{generation_id}",
headers=HEADERS
)
status_data = status_response.json()
current_status = status_data["status"]
print(f"当前状态: {current_status}")
if current_status == "completed":
print("3D 生成完成!")
break
elif current_status == "failed":
error = status_data.get("error") or {}
print(f"生成失败: {error.get('message', '未知错误')}")
exit(1)
time.sleep(15) # 每 15 秒查询一次
# 第三步:下载产物(content_url 为临时地址,直接下载)
for item in status_data["output"]:
file_url = item["content_url"]
file_name = f"model.{item['type']}"
file_response = requests.get(file_url)
with open(file_name, "wb") as f:
f.write(file_response.content)
print(f"已保存 {file_name}({len(file_response.content) / 1024 / 1024:.1f} MB)")
```
```javascript Node.js theme={null}
const API_KEY = "your_aihubmix_api_key";
const BASE_URL = "https://aihubmix.com";
async function generate3D() {
// 第一步:创建任务
const createResponse = await fetch(`${BASE_URL}/v1/3d/generations`, {
method: "POST",
headers: {
"Authorization": `Bearer ${API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "hy-3d-3.1",
prompt: "一只戴帽子的柴犬",
enable_pbr: true
})
});
const { id: generationId } = await createResponse.json();
console.log(`任务已创建: ${generationId}`);
// 第二步:轮询状态
let result;
while (true) {
await new Promise(resolve => setTimeout(resolve, 15000));
const statusResponse = await fetch(
`${BASE_URL}/v1/3d/generations/${generationId}`,
{ headers: { "Authorization": `Bearer ${API_KEY}` } }
);
result = await statusResponse.json();
console.log(`当前状态: ${result.status}`);
if (result.status === "completed" || result.status === "failed") break;
}
if (result.status === "failed") {
console.error(`生成失败: ${result.error?.message}`);
return;
}
// 第三步:下载产物
const fs = require("fs");
for (const item of result.output) {
const fileResponse = await fetch(item.content_url);
const buffer = Buffer.from(await fileResponse.arrayBuffer());
fs.writeFileSync(`model.${item.type}`, buffer);
console.log(`已保存 model.${item.type}`);
}
}
generate3D();
```
## 计费说明
* 按**次**计费:价格由 `模型 × generate_type × 是否启用 PBR × 是否指定面数 × 是否指定格式` 的组合决定,具体价格见[模型广场](https://aihubmix.com/models)。
* 计费发生在**任务创建成功**时;查询任务状态与下载产物不计费。
* 未配置价格的参数组合会在创建时直接返回 400,不会产生扣费。
## FAQ
### 3D 生成需要多长时间?
通常需要数分钟,具体取决于模型、生成类型与面数设置。建议以 10\~15 秒的间隔轮询查询接口。
### 产物链接和任务的有效期是多久?
* 任务 ID 自创建起 **24 小时**内可查询,响应中的 `expires_at` 字段即查询截止时刻。
* `content_url` / `preview_url` 为临时链接,会在一段时间后过期,请在任务完成后**尽快下载转存**。
### 可以同时传 `prompt` 和参考图吗?
不可以,两者互斥。唯一例外是 `generate_type: "Sketch"`(草图生 3D),允许同时传入草图图片与文字描述。
### `generate_type` 各类型有什么区别?
| 类型 | 说明 |
| :--------- | :---------------- |
| `Normal` | 标准生成(几何 + 纹理),默认值 |
| `Geometry` | 仅几何白模,无纹理 |
| `Sketch` | 草图生 3D,可同传图片与文字 |
### 任务失败怎么处理?
当 `status` 为 `failed` 时,响应中的 `error` 字段包含错误信息:
```json theme={null}
{
"status": "failed",
"error": {
"message": "...",
"type": "z3d_generation_error"
}
}
```
常见失败原因包括:内容不合规、图片格式不支持、参考图无法访问等。请根据错误信息调整后重试。
***
更新时间:2026-07-17
# AIhubMix 一站式集成
Source: https://docs.aihubmix.com/cn/api/Aihubmix-Integration
了解 AIhubMix 的通用模型调用方式
AIHubMix 以 OpenAI 模型调用接口为标准,聚合了 OpenAI、谷歌 Gemini、Anthropic Claude 等多家主流大模型。通过统一的 API 接口,您可以无缝调用多个不同厂商的700➕模型。只需修改对应的 模型 ID,即可在同一套代码中切换使用 OpenAI、Gemini、Claude 等任意模型,无需学习和适配不同的调用协议。
核心要点:只需要在 client 内部加入转发的 `base_url` 和 AIHubMix 平台的[密钥](https://aihubmix.com/token)。 模型 ID 可以在[模型广场的卡片上](https://aihubmix.com/models)点击「复制按钮」来获取。
## 基础集成:使用 OpenAI 官方库
### Python 示例
```py Python theme={null}
from openai import OpenAI
client = OpenAI(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com/v1"
)
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": "Say this is a test",
}
],
model="gpt-4o-mini", # 替换为任意支持的模型 ID
)
print(chat_completion)
```
OpenAI 官方当前服务状态 [查询](https://status.openai.com/)
## 通用模型转发 API
端点(Endpoint): `POST` /v1/chat/completions
**Body 请求参数:**
```json theme={null}
{
"model": "gpt-4o-mini",
"messages": [
{
"role": "user",
"content": "What is the meaning of life?"
}
]
}
```
### 请求参数
| 名称 | 位置 | 类型 | 必选 | 说明 |
| ------------- | ------ | ------ | -- | ------------------------- |
| Authorization | header | string | 否 | Bearer AIHUBMIX\_API\_KEY |
| Content-Type | header | string | 否 | none |
| body | body | object | 否 | none |
**返回示例:**
```json theme={null}
200 Response
```
```json theme={null}
{
"id": "chatcmpl-AzJqsyf2h02BKjrqHMA1HVUQpiDfL",
"model": "gpt-4o-mini",
"object": "chat.completion",
"created": 1739177682,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "The meaning of life is a philosophical question that has been debated for centuries. Different people and cultures may have different beliefs about the purpose and significance of life. Some believe that the meaning of life is to seek happiness and fulfillment, while others believe in spiritual or religious meanings such as serving a higher power or fulfilling a destiny. Ultimately, the meaning of life may be a deeply personal and individual question that each person must answer for themselves."
},
"finish_reason": "stop"
}
],
"system_fingerprint": "fp_0165350fbb",
"usage": {
"prompt_tokens": 14,
"completion_tokens": 86,
"total_tokens": 100
}
}
```
### 返回结果
| 状态码 | 状态码含义 | 说明 | 数据模型 |
| --- | ----- | ---- | ------ |
| 200 | OK | none | Inline |
***
更新时间:2026-06-01
# Anthropic API 兼容(Beta)
Source: https://docs.aihubmix.com/cn/api/Anthropic-Compatible
## 说明
为了满足开发者对 Anthropic API 生态的使用需求,我们的 API 现支持通过 Anthropic API 调用所有的模型。支持 200+ LLMs,包括 7个免费模型。
## 快速开始
### 安装 Anthropic SDK
```shellscript Python theme={null}
pip install -U anthropic
```
```shellscript Node.js theme={null}
npm install @anthropic-ai/sdk
```
### 调用方法
**端点 :**`https://aihubmix.com/v1/messages`
```shellscript Curl theme={null}
curl https://aihubmix.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: " \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "minimax-m2.1",
"max_tokens": 16000,
"thinking": {
"type": "enabled",
"budget_tokens": 10000
},
"messages": [
{
"role": "user",
"content": "Are there an infinite number of prime numbers such that n mod 4 == 3?"
}
]
}'
```
```python Python theme={null}
from anthropic import Anthropic
client = Anthropic(
api_key="",
base_url="https://aihubmix.com"
)
response = client.messages.create(
model="glm-4.7",
max_tokens=16000,
thinking={
"type": "enabled",
"budget_tokens": 10000
},
messages=[
{
"role": "user",
"content": "Are there an infinite number of prime numbers such that n mod 4 == 3?"
}
]
)
# The response will contain summarized thinking blocks and text blocks
for block in response.content:
if block.type == "thinking":
print(f"\nThinking summary: {block.thinking}")
elif block.type == "text":
print(f"\nResponse: {block.text}")
```
## 兼容性说明
### 支持的参数
在使用 Anthropic API 接入时,我们支持以下输入参数:
| 参数 | 类型 | 是否必需 | 说明 |
| ------------- | --------------------------------- | ---- | ------------------------------------------ |
| `model` | string | 是 | 支持模型请查询[模型列表](https://aihubmix.com/models) |
| `messages` | array of MessageParam | 是 | 输入信息 |
| `max_toknes` | number | 否 | 最大生成 token 数 |
| `stream` | boolean | 否 | 流式响应 |
| `system` | string or array of TextBlockParam | 是 | 系统提示词 |
| `temperature` | number | 否 | 取值范围 (0.0, 1.0],控制输出随机性,建议取值 1 |
| `top_p` | number | 否 | 核采样参数 |
| `thinking` | ThinkingConfigParam | 否 | 推理内容 |
### Messages 字段支持
| 字段类型 | 说明 |
| -------------------- | ------ |
| `type="text"` | 文本消息 |
| `type="tool_use"` | 工具调用 |
| `type="tool_result"` | 工具调用结果 |
| `type="thinking"` | 推理的内容 |
## 使用示例
### 在 Claude Code 中使用 GPT-5.2
虽然您可以通过 AIHubMix 使用任何模型,但为了获得最佳体验,我们建议您使用功能强大的模型,例如 gpt-5.2、glm-4.7 等。
#### 1. 安装配置 Claude Code
Claude Code 安装请参考:[https://docs.aihubmix.com/cn/api/Claude-Code](https://docs.aihubmix.com/cn/api/Claude-Code)
#### 2. 将 Claude Code 连接到AIHubMix
**Claude 配置文件:**`.claude/settings.json`
```bash theme={null}
{
"env": {
"ANTHROPIC_API_KEY": "AIHUBMIX_API_KEY",
"ANTHROPIC_BASE_URL": "https://aihubmix.com",
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "gpt-5.2",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "gpt-5.2",
"ANTHROPIC_DEFAULT_SONNET_MODEL": "gpt-5.2",
"ANTHROPIC_MODEL": "gpt-5.2"
},
"includeCoAuthoredBy": false
}
```
请替换 `AIHUBMIX_API_KEY` 为实际的 AIHUBMIX API 密钥。
Claude Code 原生安装程序无法读取标准 `.env` 文件,因此请勿将这些内容放置在 `.env` 文件中。
#### 3. 开始对话
导航到您的项目目录并启动 Claude Code:
```bash theme={null}
$ cd /path/your-project
> claude
```
连接成功后,您发送的任何提示都将通过 AIHubMix 路由。
#### 4. 验证
您可以通过在 Claude Code 中输入 `/status` 命令来确认您的连接。
```bash theme={null}
> /status
API key: ANTHROPIC_API_KEY
Anthropic base URL: https://aihubmix.com
Model: gpt-5.2
```
***
更新时间:2026-06-01
# 构建 AI 共赢生态
Source: https://docs.aihubmix.com/cn/api/App-code
AIhubmix 推出应用标识码 APP-Code,为开发者们提供全部模型(除 claude 系列模型外)10%优惠!
主要用于优化你的 API 调用成本,**根据你的有效域名生成一行标识码,加入 headers 立即生效。**
* **对于平台**:平台方所有 AIhubmix 调用成本得到降低,用户本身没有优惠。
* **对于开发者或普通用户**:通过你的工具发出的 AIhubmix 调用都享受优惠,即使由你的用户发起。
接入并使用之后,你会在用量的日志明细中看到请求的优惠。
## 1️⃣ 调用方法:
```shell Curl 方式 theme={null}
curl https://aihubmix.com/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-H "APP-Code:***" \
-d '{
"model": "gpt-5.5",
"input": "Hello! Please say Hello back to me."
}'
```
```py Openai sdk 方式 theme={null}
completion = client.chat.completions.create(
extra_headers={
"APP-Code":"***"
},
model="gpt-5.5",
messages=[
{
"role": "user",
"content": "What is the meaning of life?"
}
]
)
```
## 2️⃣ 注意事项
gemini 的 header 稍微特殊,这样加:
```py Python theme={null}
client = genai.Client(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
http_options={
"base_url": "https://api.aihubmix.com/gemini",
"headers": {
"APP-Code": "***"
}
},
)
```
## 3️⃣ 优惠使用条款
使用 APP-Code 享受优惠的同时,请严格遵循以下使用条款,AIHubMix 保留对所有条款的最终解释权。
**开源产品使用规范**
如果您的产品是开源的,只需要在产品功能中体现 AIHubMix 作为 AI 模型供应商之一即可,形式不限。
**闭源产品使用规范**
如果您的产品是闭源的,需要在产品界面、用户协议或相关说明中提及模型服务来源。
示例说明:
* "AIHubMix 提供 AI 模型技术支持"
* "AI 模型服务来自 AIHubMix"
* 在应用的关于页面或帮助文档中注明相关信息
**活动时效说明**
APP-Code 优惠活动限时有效。 具体优惠政策可能根据实际情况调整,请关注官方公告获取最新信息。
更新日期:2026年4月28日
# Broadcast
Source: https://docs.aihubmix.com/cn/api/Broadcast
Broadcast 将 AIHubMix API 请求的 Trace 发送到外部可观测性平台,支持配置 LangWatch 目的地、隐私模式、采样率和 API Key 范围。
Broadcast 可将 AIHubMix API 请求的 Trace 自动发送到已配置的外部可观测性平台。无需在应用代码中添加额外埋点,即可在 LangWatch 中监控、调试和分析 LLM 使用情况。
AIHubMix 当前支持将 LangWatch 配置为 Broadcast 目的地。配置完成后,可以在 LangWatch 中查看模型、token 用量、实际计费成本、耗时、会话和 Trace 信息。
## 准备工作
开始前,请准备:
* 一个可用的 [AIHubMix API Key](https://console.aihubmix.com/token)
* 一个 LangWatch 账号和目标 Project
* AIHubMix 控制台的访问权限
此集成需要目标 Project 下现成的 `Project API Key`,其格式为 `sk-lw-*`。组织或团队范围的密钥,以及 Personal OTLP Endpoint 使用的 `pkey_*`,不适用于此配置。AIHubMix 当前使用 LangWatch 官方云端地址,不支持自托管实例。
1. 获取 LangWatch Project API Key
1. 登录 [LangWatch](https://app.langwatch.ai/),选择用于接收 AIHubMix Trace 的 Project。
2. 打开 **Settings → API Keys**。
3. 找到 **Project API Key**。确认其 Scope 是目标 Project,然后点击复制按钮。
无需创建新的 Secret Key。AIHubMix 使用该 Project 自带的 Project API Key。
2. 添加 LangWatch 目的地
1. 打开 [AIHubMix 广播](https://console.aihubmix.com/observability)。
2. 在 **Add destination** 下点击 **LangWatch**。
3. 填写配置:
| 配置项 | 说明 |
| ------------------------------- | ---------------------------------------------------------- |
| **Name** | 为目的地设置便于识别的名称,例如 `Production tracing`。 |
| **API Key** | 粘贴上一步复制的 LangWatch Project API Key。密钥会加密存储,仅用于投递。 |
| **Privacy** | 开启后不发送 prompt 和 completion 内容,只发送 token 用量、实际计费成本、耗时和模型信息。 |
| **Sampling rate** | 设置转发流量的比例。首次验证建议设为 `100%`。 |
| **Only forward these API keys** | 可选。指定需要转发的 AIHubMix API Key;不选择时转发全部 Key 的调用记录。 |
`x-session-id` 请求头和请求中的 `user` 字段会随记录传递,可用于在 LangWatch 中关联会话或用户。
### 测试并保存
1. 点击 **Test**。连接成功后,按钮会显示 **Connected**。
2. 点击 **Add destination** 保存新目的地。
3. 确认目的地开关已开启,状态显示为 **OK**。
后续修改配置时,点击 **Save changes** 保存。
3. 发送验证请求
确认当前 shell 已设置 `AIHUBMIX_API_KEY` 环境变量,然后发送一次正常模型请求:
```bash cURL theme={null}
curl https://aihubmix.com/v1/chat/completions \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-H "x-session-id: langwatch-tutorial" \
-d '{
"model": "gpt-4o-mini",
"messages": [
{
"role": "user",
"content": "What is the meaning of life?"
}
],
"user": "langwatch-tutorial"
}'
```
记录采用异步投递。请求完成后,Trace 可能需要数秒才会出现在 LangWatch。
4. 在 LangWatch 中验证
1. 打开目标 Project 的 **Traces** 页面。
2. 查找刚才请求使用的模型,或通过 `x-session-id`、`user` 字段定位记录。
3. 确认记录包含耗时、成本、token 和模型信息。
启用 Privacy 后,Prompt 等内容列显示为空,但耗时、成本、token 和模型信息仍会保留。
## 常见问题
### Test 返回 401
确认使用的是目标 Project 下的 **Project API Key**。不要使用 Personal OTLP Endpoint 的 `pkey_*`,也不要使用组织或团队范围密钥。
### 保存成功但没有 Trace
依次检查:
* 目的地开关是否已开启,状态是否为 **OK**
* Sampling rate 是否大于 `0%`
* 如果设置了 **Only forward these API keys**,请求是否使用了已选择的 AIHubMix API Key
* 请求完成后是否等待数秒并刷新 LangWatch Traces 页面
### Privacy 是否影响统计数据
Privacy 只停止发送 prompt 和 completion 内容。token 用量、实际计费成本、耗时和模型信息仍会发送。
***
更新时间:2026-08-25
# Claude Code,模型自由
Source: https://docs.aihubmix.com/cn/api/CC-any
使用 Aihubmix 平台上的任何大模型为 Claude Code 提供强劲动力,彻底告别连接不稳定和额度难买的烦恼。Aihubmix 的转发服务基于官方渠道,合规安全,无需担心账号风险或隐性限制。
1. 由于 Claude Code 的多智能体属性,额度消耗会比较夸张,建议为你的 Key 设置有限额度,防止账单刺客。
2. 使用时请关闭本地的 VPN,否则可能造成 `gpt-5` 延迟
## 快速配置指引
### 1️⃣ 全局安装 npm 包
使用终端运行:
```shell theme={null}
npm install -g @aihubmix/claude-code@latest
```
### 2️⃣ 设置系统环境变量(推荐)
注意 `sk-***` 要换成你在 AiHubMix 生成的[密钥](https://aihubmix.com/token),模型以外的配置项会以系统环境变量优先的顺序处理。
```
export AIHUBMIX_API_KEY="sk-***"
export HOST="127.0.0.1" # Optional
export PORT="3456" # Optional
export LOG="true" # Optional
export API_TIMEOUT_MS="30000" # Optional
```
* 对于 Mac 用户,你可以在`用户名`目录通过快捷键 `⌘ + ⇧ + .` 显示隐藏的 .zshrc 文件,用系统的「文本编辑」APP 打开并添加上述内容。
* 添加配置之后,终端执行 `source ~/.zshrc`,回车,使配置生效
### 3️⃣ 生成配置文件
将下方的 `sk-***` 替换成你的 AiHubMix 密钥,然后使用终端一键运行即可:
```shell theme={null}
mkdir -p ~/.aihubmix-claude-code && cat > ~/.aihubmix-claude-code/config.json <
```shell 启动服务 theme={null}
acc start
```
```shell 停止服务 theme={null}
acc stop
```
```shell 运行 CC theme={null}
acc code
```
```shell 重启服务(修改配置需要用的) theme={null}
acc restart
```
```shell 状态检测 theme={null}
acc status
```
```shell 显示帮助 theme={null}
acc help
```
```shell 查看版本 theme={null}
acc version
```
## 更多资源
* [Claude Code 转发](/cn/api/Claude-Code)
* [Github](https://github.com/inferera/aihubmix/blob/main/packages/claude-code/README.md)
* [npm 包](https://www.npmjs.com/package/@aihubmix/claude-code)
* [官方最佳实践](https://www.anthropic.com/engineering/claude-code-best-practices)
* [官方配置指引](https://docs.anthropic.com/en/docs/claude-code/settings#settings-files)
* [Claude Code: A Highly Agentic Coding Assistant](https://www.deeplearning.ai/short-courses/claude-code-a-highly-agentic-coding-assistant/)
***
更新时间:2026-06-01
# 模型后缀能力说明
Source: https://docs.aihubmix.com/cn/api/Capability-Suffix
通过模型后缀,部分模型的高级能力已预先配置,用户可在统一的 OpenAI / Chat 接口下直接使用。
## 已支持的模型
* [claude-sonnet-4-5-think](https://aihubmix.com/model/claude-sonnet-4-5-think)
* [claude-opus-4-5-think](https://aihubmix.com/model/claude-opus-4-5-think)
* [gpt-5.2-high](https://aihubmix.com/model/gpt-5.2-high)
* [gpt-5.2-low](https://aihubmix.com/model/gpt-5.2-low)
* [gemini-3-pro-preview-search](https://aihubmix.com/model/gemini-3-pro-preview-search)
* [gemini-3-flash-preview-search](https://aihubmix.com/model/gemini-3-flash-preview-search)
## Claude 思考模型
Claude 模型默认不启用思考模式,若需使用其深度推理能力,通常需要通过 Claude 原生接口调用。为方便用户在 OpenAI 兼容接口下直接使用该能力,现提供 claude `-think` 模型,该模型已预先开启思考模式。
### 已支持的模型
* [claude-sonnet-4-5-think](https://aihubmix.com/model/claude-sonnet-4-5-think)
* [claude-opus-4-5-think](https://aihubmix.com/model/claude-opus-4-5-think)
### 说明
1. 思考能力通过模型名称显式选择
2. Claude 思考模型使用平台默认的上下文与 token 配置
* Sonnet 系列默认 `max_tokens = 32k`
* Opus 系列默认 `max_tokens = 64k`
3. 无需额外参数,调用方式与普通模型一致
***
## GPT 思考模型
GPT-5.2 的推理强度仅支持在 `/responses` 接口中进行配置。为兼容统一的 OpenAI `/Chat` 接口,平台提供 `GPT-5.2-*` 系列预配置模型,在模型层固定不同级别的推理强度,用户可直接调用使用。
### 已支持的模型
* [gpt-5.2-high](https://aihubmix.com/model/gpt-5.2-high)
* [gpt-5.2-low](https://aihubmix.com/model/gpt-5.2-low)
### 说明
1. -low/high 表示推理强度
2. 推理强度通过模型名称确定,无需传入额外字段
***
## Google 搜索增强模型
Gemini 模型默认不开启 Google Search,若需开启,需使用 Gemini 原生接口。为方便用户在 OpenAI 兼容接口下直接使用该能力,部分 Gemini 模型已集成 Google 官方搜索能力。通过选择对应的模型名称,即可在生成过程中自动启用搜索,无需额外参数。
### 已支持的模型
* [gemini-3-pro-preview-search](https://aihubmix.com/model/gemini-3-pro-preview-search)
* [gemini-3-flash-preview-search](https://aihubmix.com/model/gemini-3-flash-preview-search)
### 说明
1. 带 `-search` 后缀的模型已集成 Google 官方搜索能力,适用于需要实时信息、外部事实校验、最新数据参考等场景
2. 搜索能力会产生额外费用,该费用将以独立日志形式计入总费用
* 当前版本暂不展示搜索费用的明细日志,后续将补充
3. 仅支持 **OpenAI 兼容格式** 调用
* 不支持 Gemini 原生 SDK
* 如使用 Gemini 官方 SDK,请参考对应版本非思考模型接口调用示例
***
更新时间:2026-06-01
# Claude 提示词缓存
Source: https://docs.aihubmix.com/cn/api/Claude-Cache
提示缓存显著减少了重复任务或包含一致元素的提示的处理时间,有效减低了 Token 成本。
不同 Claude 模型的最小可缓存 Token 门槛不同(512 / 1,024 / 2,048 / 4,096 不等),该门槛由各模型单独设定、并非随版本升级而提高:例如 Claude Opus 4.8 为 1,024、Claude Opus 4.7 为 2,048、Claude Opus 4.6 / 4.5 与 Claude Haiku 4.5 为 4,096。完整分档见下文「缓存限制」。低于门槛的前缀即使显式设置 `cache_control` 也不会被缓存,且不会返回错误。
以下是如何使用 Messages API 实现提示缓存的示例:
```shell Curl theme={null}
curl https://aihubmix.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: AIHUBMIX_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"stream": true,
"model": "claude-opus-4-20250514",
"max_tokens": 20000,
"system": [
{
"type": "text",
"text": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style."
},
{
"type": "text",
"text": "Pride and Prejudice by Jane Austen... [此处放置完整文本内容]",
"cache_control": {"type": "ephemeral"}
}
],
"thinking": {
"type": "enabled",
"budget_tokens": 16000
},
"messages": [
{
"role": "user",
"content": "Analyze the major themes in Pride and Prejudice."
}
]
}'
```
```py Python (Anthropic SDK - 推荐) theme={null}
import os
import anthropic
client = anthropic.Anthropic(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com"
)
# 使用缓存的流式响应
with client.messages.stream(
model="claude-opus-4-20250514",
max_tokens=20000,
system=[
{
"type": "text",
"text": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n"
},
{
"type": "text",
"text": "",
"cache_control": {"type": "ephemeral"}
}
],
thinking={
"type": "enabled",
"budget_tokens": 16000
},
messages=[
{"role": "user", "content": "Analyze the major themes in 'Pride and Prejudice'."}
]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
# 非流式响应
message = client.messages.create(
model="claude-opus-4-20250514",
max_tokens=20000,
system=[
{
"type": "text",
"text": "You are an AI assistant tasked with analyzing literary works."
},
{
"type": "text",
"text": "",
"cache_control": {"type": "ephemeral"}
}
],
messages=[
{"role": "user", "content": "Analyze the major themes in 'Pride and Prejudice'."}
]
)
print(message.content)
```
```py Python (Requests - 备选) theme={null}
import requests
url = "https://aihubmix.com/v1/messages"
headers = {
"content-type": "application/json",
"x-api-key": "sk-***", # 换成你在 AiHubMix 生成的密钥
"anthropic-version": "2023-06-01"
}
data = {
"stream": True,
"model": "claude-opus-4-20250514",
"max_tokens": 20000,
"system": [
{
"type": "text",
"text": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n"
},
{
"type": "text",
"text": "",
"cache_control": {"type": "ephemeral"}
}
],
"thinking": {
"type": "enabled",
"budget_tokens": 16000
},
"messages": [{"role": "user", "content": "Analyze the major themes in 'Pride and Prejudice'."}]
}
response = requests.post(url, headers=headers, json=data, stream=True)
# 检查响应状态
if response.status_code == 200:
# Process the streaming response
for line in response.iter_lines():
if line:
print(line.decode('utf-8'))
else:
print(f"Error: {response.status_code}, {response.text}")
```
**Response:**
```json theme={null}
{"cache_creation_input_tokens":188086,"cache_read_input_tokens":0,"input_tokens":21,"output_tokens":393}
{"cache_creation_input_tokens":0,"cache_read_input_tokens":188086,"input_tokens":21,"output_tokens":393}
```
在这个例子中,《傲慢与偏见》的全文通过 cache\_control 参数进行了缓存。这样就可以在多次 API 调用中重复使用这段长文本,而无需每次都重新处理。只需改变用户消息,就能针对这本书提出各种问题,同时利用缓存内容,从而获得更快的响应速度和更高的效率。
## 提示词缓存的工作原理
当你发送启用了提示词缓存的请求时:
1. 系统会检查是否已经缓存了最近查询中指定缓存断点之前的提示词前缀
2. 如果找到,就使用缓存版本,减少处理时间和成本
3. 否则,系统会处理完整提示词,并在开始响应时缓存前缀部分
这在以下场景特别有用:
* 包含大量示例的提示词
* 大量的上下文或背景信息
* 具有一致指令的重复任务
* 长时间的多轮对话
**缓存默认有效期为 5 分钟**,每次使用缓存内容时都会免费刷新。我们还支持 **1 小时缓存**,适用于需要更长缓存时间的场景。
## 提示词缓存会缓存完整前缀
提示词缓存会引用整个提示词 - 按顺序包括 `tools`、`system` 和 `messages`,直到并包含使用 `cache_control` 标记的内容块。
## 常见错误:写了缓存却"只写不读"
最常见的失效场景是:每轮请求 `cache_creation_input_tokens` 都很大(一直在写缓存),但 `cache_read_input_tokens` 始终为 `0`(从来读不到),等于完全没省到钱。
根因只有一个:**缓存断点(`cache_control`)之前的内容,在两次请求之间发生了变化。** 缓存命中要求断点及其之前的所有内容(按 `tools` → `system` → `messages` 顺序)逐字节完全一致;只要断点前有任何一个字变了,整段前缀缓存全部作废、重新写入。
### ❌ 错误写法:把每轮会变的问题放在断点前面
```json theme={null}
{
"messages": [
{
"role": "user",
"content": [
{ "type": "text", "text": "请总结这份资料的核心观点。" }, // ← 每轮会变,却放在断点前
{ "type": "text", "text": "<大文档>", "cache_control": { "type": "ephemeral" } } // 断点
]
}
]
}
```
下一轮把问题换成"请列出其中的关键风险点。",断点前的内容就变了,后面那段大文档的缓存也跟着读不到。
### ✅ 正确写法:大文档放最前 + 断点 + 问题放最后
```json theme={null}
{
"messages": [
{
"role": "user",
"content": [
{ "type": "text", "text": "<固定不变的大文档/参考资料,≥4096 token>", "cache_control": { "type": "ephemeral" } }, // 断点;前缀恒定
{ "type": "text", "text": "请总结这份资料的核心观点。" } // ← 每轮变化的问题,放在断点之后
]
}
]
}
```
下一轮只替换最后这个问题块(大文档原样不动),即可命中缓存。
### 实测对照(claude-opus-4-6,两次调用间隔数秒)
| 写法 | 第 2 次只改了什么 | `cache_creation` | `cache_read` | 结果 |
| ---- | ----------- | ---------------- | ------------ | -------- |
| ❌ 错误 | 断点**前**的内容 | 19821 | **0** | 整段重写,未命中 |
| ✅ 正确 | 仅断点**后**的问题 | **0** | **19814** | 完整命中 |
要点:
1. 固定不变的大块(参考文档、长上下文)放在 `messages` 用户消息的**最前面**,`cache_control` 打在它末尾,这段内容**一个字都不能动**;
2. 每轮变化的问题/指令放到断点**之后**(同一条 `user` 消息里大文档之后,或后续消息);多轮对话**只往后追加**,不要回头修改历史消息;
3. 开启 `thinking` 时,历史助手轮里的思考块要**原样回传**,否则前缀同样会断(见下文「无法缓存的内容」);
4. 若该块小于最小缓存门槛(不同模型 512–4,096 Token 不等,见下文「缓存限制」),即使显式设置 `cache_control` 也不会被缓存——这是预期行为。
## 缓存定价
提示词缓存采用新的定价结构。下表显示了每个支持模型的百万 Token 价格:
| 模型 | 基础输入 Token | 5 分钟缓存写入 | 1 小时缓存写入 | 缓存命中和刷新 | 输出 Token |
| ----------------- | ---------- | ---------- | -------- | --------- | -------- |
| Claude Opus 4 | 按平台定价 | 1.25x 基础价格 | 2x 基础价格 | 0.1x 基础价格 | 按平台定价 |
| Claude Sonnet 4 | 按平台定价 | 1.25x 基础价格 | 2x 基础价格 | 0.1x 基础价格 | 按平台定价 |
| Claude Sonnet 3.7 | 按平台定价 | 1.25x 基础价格 | 2x 基础价格 | 0.1x 基础价格 | 按平台定价 |
| Claude Sonnet 3.5 | 按平台定价 | 1.25x 基础价格 | 2x 基础价格 | 0.1x 基础价格 | 按平台定价 |
| Claude Haiku 3.5 | 按平台定价 | 1.25x 基础价格 | 2x 基础价格 | 0.1x 基础价格 | 按平台定价 |
| Claude Opus 3 | 按平台定价 | 1.25x 基础价格 | 2x 基础价格 | 0.1x 基础价格 | 按平台定价 |
| Claude Haiku 3 | 按平台定价 | 1.25x 基础价格 | 2x 基础价格 | 0.1x 基础价格 | 按平台定价 |
注意:
* 5 分钟缓存写入 Token 价格为基础输入 Token 价格的 1.25 倍
* 1 小时缓存写入 Token 价格为基础输入 Token 价格的 2 倍
* 缓存读取 Token 价格为基础输入 Token 价格的 0.1 倍
* 常规输入和输出 Token 按平台标准费率计价
## 如何实现提示词缓存
### 支持的模型
Anthropic Claude 全系模型均支持提示词缓存,包括 Claude Opus 4.8 / 4.7 / 4.6 / 4.5、Claude Sonnet 5 / 4.6 / 4.5、Claude Haiku 4.5、Claude Fable 5 等当前模型,以及 Claude Opus 4、Sonnet 4、Sonnet 3.7、Sonnet 3.5、Haiku 3.5、Haiku 3、Opus 3 等早期模型。不同模型的最小可缓存 Token 门槛见下文「缓存限制」。
### 自动缓存(顶层 cache\_control)
在请求体顶层添加一个 `cache_control` 字段即可启用自动缓存:系统自动将缓存断点应用到最后一个可缓存块,并随对话增长自动前移,适合多轮对话滚动缓存。自动断点占用 4 个断点槽位中的 1 个,可与块级显式断点组合使用。Amazon Bedrock 平台不支持自动缓存。
```json theme={null}
{
"model": "claude-sonnet-5",
"max_tokens": 1024,
"cache_control": {"type": "ephemeral"},
"system": "You are an AI assistant tasked with analyzing literary works.",
"messages": [
{"role": "user", "content": "Analyze the major themes in Pride and Prejudice."}
]
}
```
需要精确控制缓存边界时,使用下文的块级显式断点。
### 构建提示词结构
将静态内容 (工具定义、系统指令、上下文、示例) 放在提示词的开头。使用 `cache_control` 参数标记要缓存的可重用内容的结束位置。
缓存前缀按以下顺序创建:`tools`、`system`,然后是 `messages`。
使用 `cache_control` 参数,你可以定义最多 4 个缓存断点,允许分别缓存不同的可重用部分。对于每个断点,系统会自动检查之前位置的缓存命中情况,如果找到就使用最长的匹配前缀。
### 缓存限制
最小可缓存提示词长度按模型区分,该门槛并非随版本升级而提高:
| 最小缓存 Token | 模型 |
| :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 512 | Claude Fable 5、Claude Mythos 5(在 Amazon Bedrock 上为 1,024) |
| 1,024 | Claude Opus 4.8、Claude Sonnet 5、Claude Sonnet 4.6、Claude Sonnet 4.5、Claude Opus 4.1、Claude Opus 4、Claude Sonnet 4、Claude Sonnet 3.7、Claude Sonnet 3.5、Claude Opus 3 |
| 2,048 | Claude Opus 4.7、Claude Haiku 3.5、Claude Haiku 3 |
| 4,096 | Claude Opus 4.6、Claude Opus 4.5、Claude Haiku 4.5 |
即使标记了 `cache_control`,更短的提示词也无法缓存。任何请求缓存少于这个数量的 Token 都会在不使用缓存的情况下处理。要查看提示词是否被缓存,请查看响应使用情况[字段](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching#tracking-cache-performance)。
对于并发请求,注意缓存条目只有在第一个响应开始后才可用。如果需要并行请求的缓存命中,请等待第一个响应后再发送后续请求。
目前支持的缓存生存期:
* **"ephemeral"**:默认 5 分钟生存期
* **1 小时缓存**:在 `cache_control` 中设置 `"ttl": "1h"`,适用于需要更长缓存时间的场景
### 1 小时缓存持续时间
对于需要更长缓存时间的场景,我们提供 1 小时缓存选项。
在 `cache_control` 定义中包含 `ttl` 即可,无需额外请求头:
```shell theme={null}
curl https://aihubmix.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: AIHUBMIX_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-4-20250514",
"system": [
{
"type": "text",
"text": "Long-term instructions...",
"cache_control": {
"type": "ephemeral",
"ttl": "1h"
}
}
],
"messages": [...]
}'
```
```json theme={null}
{
"cache_control": {
"type": "ephemeral",
"ttl": "5m" | "1h"
}
}
```
#### 何时使用 1 小时缓存
1 小时缓存特别适用于:
* **批处理作业**:处理大量具有共同前缀的请求
* **长时间会话**:需要在较长时间内保持上下文的对话
* **大型文档分析**:对同一文档进行多次不同类型的分析
* **代码库问答**:在较长时间内对同一代码库进行多次查询
#### 混合不同的 TTL
你可以在同一个请求中混合使用不同的缓存持续时间:
```json theme={null}
{
"system": [
{
"type": "text",
"text": "Long-term instructions...",
"cache_control": {
"type": "ephemeral",
"ttl": "1h"
}
},
{
"type": "text",
"text": "Short-term context...",
"cache_control": {
"type": "ephemeral",
"ttl": "5m"
}
}
]
}
```
### 可以缓存的内容
请求中的每个块都可以用 cache\_control 指定缓存。这包括:
* 工具:tools 数组中的工具定义
* 系统消息:system 数组中的内容块
* 消息:messages.content 数组中的内容块,包括用户和助手的对话轮次
* 图片和文档:用户对话轮次中 messages.content 数组的内容块
* 工具使用和工具结果:用户和助手对话轮次中 messages.content 数组的内容块
这些元素都可以用 `cache_control` 标记来启用该部分请求的缓存。
### 无法缓存的内容
虽然大多数请求块都可以缓存,但有一些例外:
* **思考块**无法直接使用 `cache_control` 缓存。但是,当思考块出现在之前的助手回合中时,可以与其他内容一起缓存。以这种方式缓存时,从缓存读取时它们确实计为输入 Token。
* **子内容块**(如引用)本身无法直接缓存。相反,缓存顶级块。
* **空文本块**无法缓存。
### 跟踪缓存性能
通过响应中的这些 API 响应字段 (或流式传输时的 message\_start 事件) 监控缓存性能:
* `cache_creation_input_tokens`: 创建新缓存条目时写入缓存的 Token 数
* `cache_read_input_tokens`: 从缓存中检索的 Token 数
* `input_tokens`: 未从缓存读取或用于创建缓存的输入 Token 数
### 有效缓存的最佳实践
要优化提示词缓存性能:
* 缓存稳定的、可重用的内容,如系统指令、背景信息、大型上下文或常用工具定义
* 将缓存内容放在提示词开头以获得最佳性能
* 策略性地使用缓存断点来分隔不同的可缓存前缀部分
* 定期分析缓存命中率并根据需要调整策略
* 对于长期使用的内容,考虑使用 1 小时缓存以获得更好的成本效益
### 针对不同用例的优化
根据你的场景调整提示词缓存策略:
* 对话代理:减少长时间对话的成本和延迟,特别是那些有长指令或上传文档的对话
* 编程助手:通过在提示词中保留相关部分或代码库的摘要版本,改善自动完成和代码库问答
* 大文档处理:在提示词中包含完整的长篇材料 (包括图片),而不增加响应延迟
* 详细指令集:共享广泛的指令、程序和示例列表来微调 Claude 的响应。开发者通常在提示词中包含一两个示例,但使用提示词缓存,你可以通过包含 20+ 个高质量答案的多样化示例获得更好的性能
* 代理工具使用:提升涉及多个工具调用和迭代代码更改的场景性能,每个步骤通常需要新的 API 调用
* 与书籍、论文、文档、播客记录和其他长篇内容对话:通过在提示词中嵌入整个文档,让用户能够提问
### 常见问题解决
* 确保缓存部分在不同调用之间完全相同,并在相同位置标记了 `cache_control`
* 检查调用是否在缓存生存期内(5 分钟或 1 小时)
* 验证 `tool_choice` 和图片使用在调用之间保持一致
* 确认你缓存的 Token 数至少达到最小要求
* 虽然系统会尝试使用缓存断点之前位置的已缓存内容,但你可以使用额外的 `cache_control` 参数来保证查找提示词前面部分的缓存,这对于包含很长内容块列表的查询可能很有用
注意,更改 `tool_choice` 或提示词中任何位置的图片存在/缺失都会使缓存失效,需要创建新的缓存条目。
### 缓存存储和共享
* **组织隔离:** 缓存在组织之间是隔离的。不同组织永远不会共享缓存,即使它们使用相同的提示词。
* **精确匹配:** 缓存命中需要 100% 相同的提示词段,包括标记有 cache control 的块之前及其本身的所有文本和图片。在缓存读取和创建期间必须用 cache\_control 标记相同的块。
* **输出 Token 生成:** 提示词缓存不会影响输出 Token 生成。你收到的响应将与不使用提示词缓存时完全相同。
***
## 在客户端 / 平台中启用 Claude 缓存
很多客户端的界面没有地方直接填 `cache_control`,而是用各自的"语法糖"或开关替你注入。底层规则与上文完全一致——**被缓存的前缀必须每轮逐字不变,会变化的内容放在缓存断点之后**,否则会"只写不读"(见上文「常见错误」)。
### Dify(通过 Aihubmix 插件)
Aihubmix 的 Dify 插件继承了 Anthropic 官方插件的语法糖,两步开启:
1. 用 `…` 包裹要缓存的提示词(固定不变的系统提示词 / 长上下文),插件会在该处自动转换成 `cache_control` 断点;
2. 在模型参数里把「**大消息自动缓存阈值**」设为一个正整数:内容达到该 Token 阈值才会真正写缓存(仍受下文「缓存限制」的最小缓存约束,Opus 4.5/4.6、Haiku 4.5 为 4096 Token),设 0 或留空则关闭。
插件安装与配置见 [Dify 插件](./Dify-plugin)。
### Cherry Studio
Cherry Studio 经 Aihubmix 调用 Claude 默认不开缓存(「缓存 Token 阈值」默认为 `0`),需要在供应商的「API 设置」里打开。
1. 点击 Aihubmix 供应商名称右侧的齿轮,打开「API 设置」(API Settings):
2. 配置以下三项,客户端会据此为 Claude 自动注入 `cache_control`:
* **缓存 Token 阈值**(Cache Token Threshold):内容超过该 Token 数才注入缓存断点(设正数开启,0 或留空关闭);
* **缓存系统消息**(Cache System Message):开启后给 `system` 消息打缓存断点(适合缓存固定的长系统提示词);
* **缓存最后 N 条消息**(Cache Last N Messages):给最近 N 条消息打缓存断点(适合多轮对话滚动缓存)。
接入步骤见 [Cherry Studio](../clients/Cherry-Studio)。
上述阈值只决定客户端"**何时注入断点**",并不改变 Anthropic 的最小缓存要求:实际写入仍需被缓存内容达到最小缓存 Token(Opus 4.5/4.6、Haiku 4.5 为 4096)。若把每轮会变的内容(如轮换的指令)放进被缓存的系统提示词里,同样会"只写不读"。
***
## 常见问题(FAQ)
### 为什么写了缓存(`cache_creation_input_tokens` 很大)却一直读不到(`cache_read_input_tokens` 为 0)?
因为缓存断点(`cache_control`)之前的内容在两次请求之间变了。命中要求断点及其之前的所有内容逐字节一致;一旦把每轮会变的内容放在断点前面,整段前缀缓存就作废、每轮重写。把固定内容放最前、变化内容放断点之后即可,详见上文「常见错误」。
### 缓存最少需要多少 Token?
低于最小缓存长度的前缀即使显式设置 `cache_control` 也不会被缓存;各模型的最小门槛见上文「缓存限制」。
### 缓存有效期多久?能改成 1 小时吗?
默认 5 分钟,每次命中都会免费刷新。需要更久可在 `cache_control` 中设 `"ttl": "1h"`,无需额外请求头。1 小时档缓存写入按基础输入价的 2 倍计费。详见上文「1 小时缓存持续时间」。
### 在 Dify / Cherry Studio 里怎么开缓存?
这些客户端不直接填 `cache_control`:Dify 用 `…` 包裹要缓存的内容并设「大消息自动缓存阈值」;Cherry Studio 在「API 设置」里设「缓存 Token 阈值 / 缓存系统消息 / 缓存最后 N 条消息」。详见上文「在客户端 / 平台中启用 Claude 缓存」。
***
## 不同模型的支持情况
* 是否支持 Prompt Caching 取决于模型本身。
* 如果模型本身支持,并且不需要显式声明相关的参数,则通过 opanai 兼容格式转发可以支持。
* OpenAI 默认支持 Prompt Caching,自动生效(前缀 ≥1024 Token)。GPT-5.6 之前的模型缓存写入不另计费,不活跃 5-10 分钟后自动清除;GPT-5.6 及之后缓存写入按 1.25 倍输入价计费、读取按 0.1 倍计费,缓存至少保留 30 分钟,并支持显式缓存断点。详见 [GPT 提示词缓存](/cn/api/GPT-Cache)。
* Claude 需要原生的 `cache_control: { type: "ephemeral" }` 声明,缓存费率为常规输入的 1.25 倍(5 分钟)或 2 倍(1 小时),缓存 Tokens 读取费用为 0.1 倍,生命周期 5 分钟或 1 小时。[文档](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching#how-to-implement-prompt-caching)
* Deepseek V3 和 R1 原生支持,缓存费率为常规输入的 1 倍,缓存 Tokens 读取费用为 0.1 倍。[文档](https://api-docs.deepseek.com/zh-cn/)
* Gemini 模型支持[隐式缓存](https://ai.google.dev/gemini-api/docs/caching?lang=python):
* **隐式缓存**:默认情况下为所有 Gemini 2.5 模型启用。如果你的请求命中缓存,会自动传递成本节省。此功能自 2025 年 5 月 8 日起生效。上下文缓存的最低输入 Token 数:Gemini 2.5 Flash 为 1,024,Gemini 2.5 Pro 为 2,048。
* 提高隐式缓存命中率的技巧:
* 将大块的常见内容放在提示的开头。
* 尝试在短时间内发送前缀相似的请求。
* 你可以在响应对象的 `usage_metadata` 字段中查看缓存命中的 Token 数量。
* 成本节省是根据预填充缓存命中次数衡量的。只有预填充缓存和 YouTube 视频预处理缓存支持隐式缓存。
***
更新时间:2026-07-10
# Claude Code
Source: https://docs.aihubmix.com/cn/api/Claude-Code
在 Claude Code 中接入 AIHubMix:这款终端 AI 编程助手用单个 API key 即可跨厂商调用模型,享受稳定路由与统一计费。
## 快速开始
本指南将帮助您在几分钟内使用由 AIHubMix 提供的 Claude Code。
### 1. 安装 Claude Code
#### 本地安装
```shellscript macOS theme={null}
curl -fsSL https://claude.ai/install.sh | bash
```
```shellscript Windows theme={null}
irm https://claude.ai/install.ps1 | iex
```
#### 使用 npm 安装
需要 [Node.js 18 或更高版本](https://nodejs.org/en/download/)
```shellscript theme={null}
npm install -g @anthropic-ai/claude-code
```
### 2. 配置 AIHubMix API
要通过兼容 Anthropic API 的方式来接入 AIHubMix 的模型服务,需要配置以下环境变量。
1. 将 `ANTHROPIC_BASE_URL` 设置为 `https://aihubmix.com`
2. 将 `ANTHROPIC_AUTH_TOKEN` 设置为从 [AIHubMix 平台](https://console.aihubmix.com/token) 获取的 API Key
3. 将 `ANTHROPIC_MODEL` 设置为[模型列表](https://aihubmix.com/models)中支持的 Claude 模型,例如 `claude-sonnet-4-5`。
`AIHUBMIX_API_KEY` 只是占位符,请替换成你自己的真实 Key(通常以 `sk-` 开头)。如果原样写入,Claude Code 会把它当成真正的 Key,并返回 `401 invalid key: AIHUBMIX_API_KEY`。
1. 在终端中执行以下命令,查看默认 Shell 类型。
```shellscript theme={null}
echo $SHELL
```
2. 根据 Shell 类型设置环境变量,命令如下:
```shellscript Zsh theme={null}
# 将 替换为你从 AIHubMix 平台获取的真实 Key
echo 'export ANTHROPIC_BASE_URL="https://aihubmix.com"' >> ~/.zshrc
echo 'export ANTHROPIC_AUTH_TOKEN=""' >> ~/.zshrc
echo 'export ANTHROPIC_MODEL="claude-sonnet-4-5"' >> ~/.zshrc
```
```shellscript Bash theme={null}
# 将 替换为你从 AIHubMix 平台获取的真实 Key
echo 'export ANTHROPIC_BASE_URL="https://aihubmix.com"' >> ~/.bash_profile
echo 'export ANTHROPIC_AUTH_TOKEN=""' >> ~/.bash_profile
echo 'export ANTHROPIC_MODEL="claude-sonnet-4-5"' >> ~/.bash_profile
```
3. 在终端中执行下列命令,使环境变量生效。
```shellscript Zsh theme={null}
source ~/.zshrc
```
```shellscript Bash theme={null}
source ~/.bash_profile
```
4. 打开一个新的终端,执行下列命令,查看环境变量是否生效。
```shellscript theme={null}
echo $ANTHROPIC_BASE_URL
test -n "$ANTHROPIC_AUTH_TOKEN" && echo "ANTHROPIC_AUTH_TOKEN is set"
echo $ANTHROPIC_MODEL
```
在 Windows 中,可以通过 CMD 或 PowerShell 将 AIHubMix 的 Base URL 和 [API Key](https://console.aihubmix.com/token) 设置为环境变量。
1. 在 CMD 中运行以下命令,设置环境变量。
```shellscript theme={null}
REM 将 替换为你从 AIHubMix 平台获取的真实 Key
setx ANTHROPIC_AUTH_TOKEN ""
setx ANTHROPIC_BASE_URL "https://aihubmix.com"
setx ANTHROPIC_MODEL "claude-sonnet-4-5"
```
2. 打开一个新的 CMD 窗口,运行以下命令,检查环境变量是否生效。
```shellscript theme={null}
if defined ANTHROPIC_AUTH_TOKEN echo ANTHROPIC_AUTH_TOKEN is set
echo %ANTHROPIC_BASE_URL%
echo %ANTHROPIC_MODEL%
```
1. 在 PowerShell 中运行以下命令,设置环境变量。
```shellscript theme={null}
# 将 替换为你从 AIHubMix 平台获取的真实 Key
[Environment]::SetEnvironmentVariable("ANTHROPIC_AUTH_TOKEN", "", [EnvironmentVariableTarget]::User)
[Environment]::SetEnvironmentVariable("ANTHROPIC_BASE_URL", "https://aihubmix.com", [EnvironmentVariableTarget]::User)
[Environment]::SetEnvironmentVariable("ANTHROPIC_MODEL", "claude-sonnet-4-5", [EnvironmentVariableTarget]::User)
```
2. 打开一个新的 PowerShell 窗口,运行以下命令,检查环境变量是否生效。
```shellscript theme={null}
if ($env:ANTHROPIC_AUTH_TOKEN) { "ANTHROPIC_AUTH_TOKEN is set" }
echo $env:ANTHROPIC_BASE_URL
echo $env:ANTHROPIC_MODEL
```
如果你准备通过 CC Switch 管理 Claude Code,建议不要再额外设置全局 `ANTHROPIC_AUTH_TOKEN`、`ANTHROPIC_BASE_URL`、`ANTHROPIC_MODEL`。系统或用户环境变量可能覆盖 CC Switch 写入的 Provider 配置,导致界面里选择了正确 Provider,但 Claude Code 实际仍使用旧 Key 或旧模型。
### 3. 验证配置是否生效
完成环境变量或 CC Switch 配置后,建议先用一次最小请求确认 Key、模型和 Anthropic 兼容接口都可用,再启动长会话。
```bash macOS/Linux theme={null}
curl https://aihubmix.com/v1/messages \
-H "content-type: application/json" \
-H "anthropic-version: 2023-06-01" \
-H "x-api-key: $ANTHROPIC_AUTH_TOKEN" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 16,
"messages": [{"role": "user", "content": "1+1, output only the answer"}]
}'
```
```powershell Windows theme={null}
curl.exe https://aihubmix.com/v1/messages `
-H "content-type: application/json" `
-H "anthropic-version: 2023-06-01" `
-H "x-api-key: $env:ANTHROPIC_AUTH_TOKEN" `
-d "{\"model\":\"claude-sonnet-4-5\",\"max_tokens\":16,\"messages\":[{\"role\":\"user\",\"content\":\"1+1, output only the answer\"}]}"
```
如果返回 `200` 且内容为 `2`,说明 AIHubMix Key 与 Claude 模型可用。随后可以运行:
```bash theme={null}
claude -p "1+1, output only the answer" --model claude-sonnet-4-5
```
返回 `2` 即表示 Claude Code 端到端配置成功。
### 4. 开始使用
完成配置后,进入你的工作目录,在终端运行 `claude` 命令开始使用 Claude Code。
```bash theme={null}
$ cd /path/your-project
> claude
```
如果启动后看到 `Not logged in · Please run /login`,或进入 Anthropic 登录选项,通常说明 Claude Code 没有读取到可用的 AIHubMix 配置,或首次引导尚未完成。请先确认上一步最小请求可返回 `2`,并检查 `ANTHROPIC_AUTH_TOKEN`、`ANTHROPIC_BASE_URL`、`ANTHROPIC_MODEL` 是否被旧的全局环境变量覆盖。确认 Key 可用后,如仍进入登录流程,可按以下步骤跳过首次引导:
1. 定位用户主目录下的 `.claude.json` 文件,具体路径如下:
* macOS / Linux: `~/.claude.json`
* Windows: `C:\Users\%USERNAME%\.claude.json`
2. 设置`hasCompletedOnboarding` 字段的值为 `true`
```json theme={null}
{
"hasCompletedOnboarding": true
}
```
3. 保存文件,然后在终端中重新运行 `claude` 。
#### (可选)更多配置模型的方式
Claude Code 支持以下模型配置方式,**按优先级从高到低排列**,优先级高的配置会覆盖优先级低的配置。
1. **对话期间:** 执行`/model <模型名称>`命令切换模型。适用于临时切换模型。
```text theme={null}
/model claude-sonnet-4-5
```
2. **启动 Claude Code 时:** 执行`claude --model <模型名称>`指定模型。适用于单次会话。
```text theme={null}
claude --model claude-sonnet-4-5
```
3. **设置环境变量**:可按任务复杂度配置不同级别的模型,Claude Code 会根据任务类型自动选择合适的模型。适用于全局生效。
```shellscript theme={null}
export ANTHROPIC_DEFAULT_OPUS_MODEL="claude-opus-4-5"
export ANTHROPIC_DEFAULT_SONNET_MODEL="claude-sonnet-4-5"
export ANTHROPIC_DEFAULT_HAIKU_MODEL="claude-haiku-4-5"
```
其中:
* `ANTHROPIC_DEFAULT_OPUS_MODEL`:用于复杂推理、架构设计等高难度任务。
* `ANTHROPIC_DEFAULT_SONNET_MODEL`:用于代码编写、功能实现等日常任务。
* `ANTHROPIC_DEFAULT_HAIKU_MODEL`:用于语法检查、文件搜索等简单任务。
4. **在 settings.json 配置文件中永久设置**:在 Claude Code 的用户配置文件(如 `~/.claude/settings.json`,Windows 为 `C:\Users\%USERNAME%\.claude\settings.json`)或项目级配置中写入模型配置信息,可分别进行用户级或项目级的永久配置。
**兜底配置:** 如果前面的 `/model`、启动参数、环境变量或 CC Switch 配置没有生效,或 Claude Code 仍读取旧模型,可直接编辑 `settings.json`。下面示例同时设置 `ANTHROPIC_MODEL` 和顶层 `model`,并保留 Opus、Sonnet、Haiku 三个槽位的模型名称。
```json theme={null}
{
"env": {
"ANTHROPIC_AUTH_TOKEN": "",
"ANTHROPIC_BASE_URL": "https://aihubmix.com",
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "gemini-3.5-flash",
"ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME": "gemini-3.5-flash",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "gemini-3.5-flash",
"ANTHROPIC_DEFAULT_OPUS_MODEL_NAME": "gemini-3.5-flash",
"ANTHROPIC_DEFAULT_SONNET_MODEL": "gemini-3.5-flash",
"ANTHROPIC_DEFAULT_SONNET_MODEL_NAME": "gemini-3.5-flash",
"ANTHROPIC_MODEL": "gpt-5.5"
},
"model": "gpt-5.5"
}
```
将 `` 替换为你自己的真实 Key。保存后需要重新启动 Claude Code,再输入 `/models` 查看当前会话可切换的模型。
## 如何通过 CC Switch 配置?
1. 运行 CC Switch,先在左侧选择 **Claude Code**,再点击「添加供应商」。
2. 在预设列表中选择「AiHubMix」。请确认当前配置的是 Claude Code 侧的 Provider。
3. 在「API Key」栏中填写你的真实密钥。
4. 配置完成后,先使用 `claude-sonnet-4-5` 作为模型 ID,点击「添加」保存设置。确认健康检查通过后,可在 Claude Code 中通过 `/models` 或 `/model` 切换其他 Claude 模型。
5. 返回首页,在供应商列表中选择「AiHubMix」,点击「启动」即可使用。
>
>
>
>
> Tip: 终端打开 Claude Code后,输入 /status 可查询模型ID,输入/models 可选择配置的其他模型
如果 CC Switch 提示「检测到系统环境变量冲突」,请优先处理 `ANTHROPIC_AUTH_TOKEN`、`ANTHROPIC_BASE_URL`、`ANTHROPIC_MODEL`。这些全局变量会覆盖当前 Provider 配置;其中 `ANTHROPIC_AUTH_TOKEN=AIHUBMIX_API_KEY` 这类占位符值会直接导致认证失败。确认不再需要全局变量后,可在 CC Switch 中删除冲突项,或手动删除系统/用户环境变量,然后重启终端。
## 如何通过 VS Code 插件配置?
1. 运行 VS Code,安装插件。
2. 按下 `Ctrl + Shift + P` (或 `Cmd + Shift + P`),输入 `Settings` 打开设置。
3. 搜索 `Claude Code` ,找到 `Claude Code: Environment Variable` → `Edit in settings.json` 。
4. 在 `claudeCode.environmentVariables` 中填入 AIHubMix 相关信息。
## [Wechat-Agent-SDK](https://github.com/AIhubmix/wechat-agent-sdk)
通过简单的接口调用,一键将 Claude Code、Codex、Kimi 等主流 AI 智能体接入微信。支持 ACP 协议,纯本地运行,无需服务器、无需数据库,内置断点续传、自动重连等企业级特性,让您的 AI 助手轻松在微信中智能对话。
> 安装地址:[https://github.com/AIhubmix/wechat-agent-sdk](https://github.com/AIhubmix/wechat-agent-sdk)
## 常见问题
### Q:提示 `401` 认证错误怎么办?
`401` 表示请求没有通过认证,但具体原因要看完整错误消息:
* `No token provided`:没有传入 Key。打开 Claude Code,输入 `/config`,找到 `Use custom API key` 选项,检查 Token 是否已配置。
* `invalid key: AIHUBMIX_API_KEY`:通常表示把示例占位符原样写入了环境变量。请在 AIHubMix 控制台重新复制真实 Key,并更新 `ANTHROPIC_AUTH_TOKEN`。
* `this key is not enabled`:请求已到达 AIHubMix,但当前 Key 尚未启用或没有调用权限。请在 [AIHubMix 控制台](https://console.aihubmix.com/token) 检查该 Key 是否启用、是否过期、是否有额度,并确认它可以调用你选择的 Claude 模型。
在 Windows 上还要检查用户环境变量或系统环境变量中是否保留了旧值:
```powershell theme={null}
[Environment]::GetEnvironmentVariable("ANTHROPIC_AUTH_TOKEN", "User")
[Environment]::GetEnvironmentVariable("ANTHROPIC_BASE_URL", "User")
[Environment]::GetEnvironmentVariable("ANTHROPIC_MODEL", "User")
```
如果你使用 CC Switch 管理配置,建议删除这些全局 `ANTHROPIC_*` 变量,让 CC Switch 当前 Provider 接管配置。
注意:`/v1/models` 可能在无有效 Key 时也能返回模型列表,因此不能用它判断 Key 是否可用。请参考上文「如何验证配置是否生效?」中的最小消息请求;如果返回 `200` 且内容为 `2`,说明 Key 与模型可用,再重启 Claude Code 或通过 CC Switch 重新启动即可。
### Q:提示 `400 Incorrect model ID` 或 `Bad request (400)` 怎么办?
这通常表示请求格式已到达供应商侧,但模型 ID 不正确、模型名称与接口不匹配,或当前 Key 没有调用该模型的权限。请在 [AIHubMix 模型列表](https://aihubmix.com/models) 中重新复制完整模型 ID,确认没有手动拼写、大小写或系列名称错误。
如果你通过 CC Switch 配置,请回到对应 Provider,更新模型 ID 后保存,并重新启动 Claude Code。如果仍然报错,可先换用模型列表中确认可用的 Claude 模型完成健康检查,再切换到目标模型。
### Q:macOS 中安装成功后仍然报错:`zsh: command not found: claude`
这是因为 Claude CLI 已安装,但其可执行目录未加入系统 `PATH`。
1. 确认 Claude 安装路径。Claude Code 官方脚本通常安装在以下目录之一:
* `~/.claude/bin`
* `~/.local/bin`
在终端执行:
```shellscript theme={null}
ls -l ~/.claude/bin
或
ls -l ~/.local/bin | grep claude
```
如果看到 claude 文件,说明安装成功,只是 PATH 未配置。
2. 将安装目录加入 PATH。根据实际安装位置执行对应命令:
#### 情况 A:安装在 `~/.claude/bin`
```shellscript theme={null}
echo 'export PATH="$HOME/.claude/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
```
#### 情况 B:安装在 `~/.local/bin`
```shellscript theme={null}
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
```
3. 验证是否生效。执行:
```text theme={null}
which claude
claude -v
```
若能看到 `claude` 路径及版本号,说明安装成功。
### Q:Claude Code 无法连接 Anthropic 服务
升级到最新版本的 Claude Code 后,若出现无法连接 Anthropic 服务或认证失败的情况,通常是由于认证请求头名称已发生调整所致。新版本要求将请求头由 `ANTHROPIC_API_KEY` 修改为 `ANTHROPIC_AUTH_TOKEN`,API Key 的值无需更换,仅需更新请求头名称并重新加载配置即可。具体操作可参考本文档重新配置。
## 更多资源
* [Github](https://github.com/inferera/aihubmix/blob/main/packages/claude-code/README.md)
* [npm 包](https://www.npmjs.com/package/@aihubmix/claude-code)
* [官方最佳实践](https://www.anthropic.com/engineering/claude-code-best-practices)
* [官方配置指引](https://docs.anthropic.com/en/docs/claude-code/settings#settings-files)
祝您使用愉快!
最新更新日期:2026年6月9日
# Claude 原生接口调用
Source: https://docs.aihubmix.com/cn/api/Claude-Native
## 说明
Claude 系列模型支持通过官方原生接口调用,使用之前确保安装或升级 anthropic 依赖:
```bash theme={null}
pip install -U anthropic
```
## 模型信息
| 模型名称 | Claude Opus 4.7 | Claude Opus 4.6 | Claude Sonnet 4.6 | Claude Sonnet 4.5 | Claude Haiku 4.5 |
| -------- | --------------- | ----------------------------------------------- | ----------------------------------------------- | ----------------- | ---------------- |
| 是否支持扩展思考 | 是 | 是 | 是 | 是 | 是 |
| 上下文窗口大小 | 1M tokens | 200K tokens /
1M tokens (beta)3 | 200K tokens /
1M tokens (beta)3 | 200K | 200K |
| 最大输出长度 | 128K tokens | 128K tokens | 128K tokens | 64K tokens | 64K tokens |
| 训练数据截止时间 | 2026年1月 | 2025年8月 | 2025年8月 | 2025年7月 | 2025年7月 |
## Claude Opus 4.7 新功能
1. **Claude Opus 4.7 官方增加了更高的推理参数** \
`xhigh `**强度级别是介于**`high` 和 `max` 之间的全新 effort 级别,适合编程和 agentic 任务。
2. **Claude Opus 4.7 思考内容官方改为了默认隐藏**\
流式输出中思考过程默认不展示。如需查看思考摘要,需接口中额外传参display:
| **display 值** | **Opus 4.7** | **Opus 4.6** | **效果** |
| :------------ | :----------- | :----------- | :------- |
| "omitted" | **默认** | 非默认 | 思考块内容为空 |
| "summarized" | 需手动设置 | **默认** | 返回思考摘要文字 |
```text theme={null}
"reasoning": {"effort": "xhigh", "display": "summarized"}
```
#### Claude Opus 4.7格式接口说明
**Anthropic 原生接口effort值与官方保持一致,参考如下:**
| **effort值** | **适用模型** | **说明** | **推荐场景** |
| :------------ | :-------------- | :----------------------------- | :-----------------: |
| low | 所有支持模型 | 显著节省 token,适当降低能力 | 简单任务、高并发请求、子 agent |
| medium | 所有支持模型 | 均衡模式,适度节省 token | 一般 agentic 任务 |
| high | 所有支持模型 | 默认值,高能力表现 | 复杂推理、编程、agentic 任务 |
| **xhigh(新增)** | **Opus 4.7 专属** | 扩展能力,介于 high 和 max 之间,长程任务表现优异 | 编程和 agentic 任务的推荐起点 |
| max | Opus 系列 | 最高能力 | 前沿研究问题 |
**AIHubmix Claude 原生接口 Claude Opus 4.7 调用示例 (返回思考摘要)**
```text theme={null}
from openai import OpenAI
client = OpenAI(
base_url="https://aihubmix.com/v1",
api_key="",
)
completion = client.chat.completions.create(
model="claude-opus-4-7",
messages=[
{
"role": "user",
"content": "A snail is at the bottom of a 10-meter well. Each day it climbs 3 meters, but each night it slides back 2 meters. How many days does it take to reach the top?"
}
],
extra_body={
"reasoning": {"effort": "xhigh", "display": "summarized"}
}
)
print(completion.choices[0].message.content)
```
## Claude 4.6 新功能
### 自适应思考(Adaptive Thinking)
Claude 4.6 推荐使用新的自适应思考模式,该模式下,Claude 会根据问题复杂度自动决定是否进行思考及深度思考:
```python theme={null}
thinking={"type": "adaptive"}
```
`thinking: {type: "enabled", budget_tokens: N}` 在 4.6 上已弃用,未来版本将移除。
### 自动上下文压缩(Compaction,Beta)
当对话接近上下文窗口上限时,Claude 4.6 可自动对早期内容进行服务器端摘要压缩。
**优势:**
* 支持超长对话
* 无需客户端自行摘要
* 提高 Agent 连续会话能力
**注意:**
* 自动压缩可能丢失部分细节
* 对强一致性场景建议评估测试
### 弃用与变更
* \*\*移除 \*\*`interleaved-thinking-2025-05-14`**Beta 头:** 在 4.6 中,自适应思考已自动支持交错思考,不需要再添加 `extra_headers` 。如仍添加,该头会被安全忽略。
## Claude 4 新功能
### 新的拒绝停止原因 (Refusal Stop Reason)
Claude 4 模型引入了新的 `refusal` 停止原因,用于处理模型因安全原因拒绝生成的内容:
```json theme={null}
{
"id": "msg_014XEDjypDjFzgKVWdFUXxZP",
"type": "message",
"role": "assistant",
"model": "claude-sonnet-4-20250514",
"content": [{"type": "text", "text": "I would be happy to assist you. You can "}],
"stop_reason": "refusal",
"stop_sequence": null,
"usage": {
"input_tokens": 564,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0,
"output_tokens": 22
}
}
```
在迁移到 Claude 4 时,您应该更新应用程序以处理 `refusal` 停止原因。
### 扩展思考 (Extended Thinking)
启用扩展思考后,Claude 4 模型的 Messages API 会返回 Claude 完整思考过程的摘要。摘要思考提供了扩展思考的全部智能优势,同时防止滥用。
虽然 API 在 Claude 3.7 和 4 模型之间保持一致,但扩展思考的流式响应可能以"块状"传递模式返回,流式事件之间可能存在延迟。
摘要由与您在请求中指定的模型不同的模型处理。思考模型不会看到摘要输出。
### 交错思考 (Interleaved Thinking)
Claude 4 模型支持将工具使用与扩展思考交错,允许更自然的对话,其中工具使用和响应可以与常规消息混合。
交错思考目前处于测试阶段。要启用交错思考,请在 API 请求中添加测试头 `interleaved-thinking-2025-05-14`:
```python theme={null}
extra_headers={
"anthropic-beta": "interleaved-thinking-2025-05-14"
}
```
**端点(Endpoint):** `POST` /v1/messages
## 调用
```shell Curl theme={null}
curl https://aihubmix.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \ # 换成你在 AiHubMix 生成的密钥
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--data \
'{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Hello, world"}
]
}'
```
```py Python 非流式 theme={null}
import anthropic
client = anthropic.Anthropic(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com"
)
message = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude"}
]
)
print(message.content)
```
```py Python 流式 128K theme={null}
import anthropic
client = anthropic.Anthropic(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com"
)
with client.messages.stream(
model="claude-3-7-sonnet-20250219", # claude-opus-4-20250514, claude-sonnet-4-20250514
max_tokens=128000,
messages=[
{"role": "user", "content": "Please generate a 100,000 token article that elaborates on Charlie Munger's 100 mental models (approximately 1,000 tokens for each model), with each section including an introduction to the model, multidimensional thinking, application methods, practical blind spots, and specific examples. Clarity and engagement are key. Use bullet points only when necessary."}
],
extra_headers={
"anthropic-beta": "output-128k-2025-02-19"
}
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
```
```py Python 交错思考 theme={null}
import anthropic
client = anthropic.Anthropic(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com"
)
response = client.messages.create(
model="claude-sonnet-4-20250514", # 或 claude-opus-4-20250514
max_tokens=1024,
messages=[
{"role": "user", "content": "Help me analyze this data and generate a chart"}
],
tools=[
{
"type": "computer_20241022",
"name": "computer"
}
],
extra_headers={
"anthropic-beta": "interleaved-thinking-2025-05-14"
}
)
print(response.content)
```
### Body 请求结构
```json theme={null}
{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": "What is the meaning of life?"
}
]
}
```
### 请求参数
| 名称 | 位置 | 类型 | 必选 | 说明 |
| ------------- | ------ | --------- | -- | ------------------ |
| x-api-key | header | string | 否 | AIHUBMIX\_API\_KEY |
| Content-Type | header | string | 否 | none |
| body | body | object | 否 | none |
| » model | body | string | 是 | none |
| » messages | body | \[object] | 是 | none |
| »» role | body | string | 否 | none |
| »» content | body | string | 是 | none |
| » max\_tokens | body | number | 是 | none |
### 返回示例
```json theme={null}
200 Response
```
```json theme={null}
{
"id": "msg_013Uf6CwwyjSe35n3yVaPbLM",
"type": "message",
"role": "assistant",
"model": "claude-3-5-sonnet-20241022",
"content": [
{
"type": "text",
"text": "That's one of humanity's most enduring and complex philosophical questions! While there's no universal answer, I aim to explore such questions thoughtfully while acknowledging their complexity. I try to focus on having meaningful conversations and helping where I can. What does meaning in life mean to you?"
}
],
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 14,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0,
"output_tokens": 61
}
}
```
### 返回结果
| 状态码 | 状态码含义 | 说明 | 数据模型 |
| --- | ----- | ---- | ------ |
| 200 | OK | none | Inline |
## 迁移到 Claude 4
如果您正在从 Claude 3.7 迁移到 Claude 4 模型,请注意以下变化:
### 更新模型名称
```python theme={null}
# 从 Claude 3.7
model="claude-3-7-sonnet-20250219"
# 迁移到 Claude 4
model="claude-sonnet-4-20250514" # 或 "claude-opus-4-20250514"
```
### 处理新的停止原因
更新您的应用程序以处理新的 `refusal` 停止原因:
```python theme={null}
if response.stop_reason == "refusal":
print("Claude 拒绝生成此内容")
elif response.stop_reason == "end_turn":
print("正常完成")
```
### 移除不支持的功能
* **Token 高效工具使用**:仅在 Claude Sonnet 3.7 中可用,Claude 4 中不再支持
* **扩展输出**:`output-128k-2025-02-19` 测试头仅在 Claude Sonnet 3.7 中可用
如果您正在从 Claude Sonnet 3.7 迁移,建议从请求中移除这些测试头:
```python theme={null}
# 移除这些头部(如果存在)
# "token-efficient-tools-2025-02-19"
# "output-128k-2025-02-19"
```
## 在应用中使用(以 Lobe-Chat 为例)
* 进入设置页面选择模型服务商 Claude
* API key 输入[本站的 Key](https://aihubmix.com/token)
* 接口代理地址,直接输入下方的网址:
```text theme={null}
https://aihubmix.com
```
* 建议打开「使用客户端请求模式」
* 最后在模型列表添加自己要使用的模型(建议从我们网站的设置页面复制粘贴模型名后选择)\
## Claude 文本编辑工具
Claude 可以使用 Anthropic 定义的文本编辑工具来查看和修改文本文件,帮助你调试、修复和改进代码或其他文本文档。这使得 Claude 能够直接与你的文件进行交互,提供实际的操作帮助,而不仅仅是提出建议。
### 使用文本编辑工具前的准备
选择兼容的模型 Anthropic 的文本编辑工具支持以下 Claude 模型:
* **Claude 4 系列模型** (`claude-opus-4-20250514`, `claude-sonnet-4-20250514`): `text_editor_20250429`
* **Claude 3.7 Sonnet** (`claude-3-7-sonnet-20250219`): `text_editor_20250124`
* **Claude 3.5 Sonnet** (`claude-3-5-sonnet-20241022`): `text_editor_20241022`
Claude 4 模型使用了全新的文本编辑工具,与旧版本不兼容。请确保使用正确的工具类型和名称。
### 模型对应的工具配置
| 模型版本 | 工具类型 | 工具名称 | 支持的功能 |
| ---------------------- | ---------------------- | ----------------------------- | -------------------------------------- |
| Claude 4 (Opus/Sonnet) | `text_editor_20250429` | `str_replace_based_edit_tool` | view, str\_replace, create |
| Claude 3.7 Sonnet | `text_editor_20250124` | `str_replace_editor` | view, str\_replace, create, undo\_edit |
| Claude 3.5 Sonnet | `text_editor_20241022` | `str_replace_editor` | view, str\_replace, create, undo\_edit |
**重要变化:** Claude 4 模型不再支持 `undo_edit` 命令,请在代码中移除对此功能的依赖。
### 评估使用场景
以下是使用文本编辑工具的一些典型场景:
* 代码调试:帮助识别和修复代码中的问题,从语法错误到逻辑问题。
* 代码重构:通过有针对性的编辑来改进代码结构、可读性和性能。
* 文档生成:为你的代码库添加文档字符串、注释或 README 文件。
* 测试创建:根据对实现的理解创建单元测试。
### 使用文本编辑工具
通过 Messages API 向 Claude 提供文本编辑工具(命名为 `str_replace_editor`): 需要安装 `anthropic` 包:
```shell theme={null}
pip install anthropic
```
**调用示例:**
```python Python-Claude 4 theme={null}
import anthropic
client = anthropic.Anthropic(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com"
)
response = client.messages.create(
model="claude-sonnet-4-20250514", # 或 claude-opus-4-20250514
max_tokens=1024,
tools=[
{
"type": "text_editor_20250429",
"name": "str_replace_based_edit_tool"
}
],
messages=[
{
"role": "user",
"content": "There's a syntax error in my primes.py file. Can you help me fix it?"
}
]
)
print("Response content:")
for message in response.content:
print(message.text)
```
```py Python-Claude 3.7 theme={null}
import anthropic
client = anthropic.Anthropic(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com"
)
response = client.messages.create(
model="claude-3-7-sonnet-20250219",
max_tokens=1024,
tools=[
{
"type": "text_editor_20250124",
"name": "str_replace_editor"
}
],
messages=[
{
"role": "user",
"content": "There's a syntax error in my primes.py file. Can you help me fix it?"
}
]
)
print("Response content:")
for message in response.content:
print(message.text)
```
```shell Curl-Claude 4 theme={null}
curl -X POST https://aihubmix.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: xxx" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-sonnet-4-20250514",
"max_tokens": 1024,
"tools": [
{
"type": "text_editor_20250429",
"name": "str_replace_based_edit_tool"
}
],
"messages": [
{
"role": "user",
"content": "There'\''s a syntax error in my primes.py file. Can you help me fix it?"
}
]
}'
```
```shell Curl-Claude 3.7 theme={null}
curl -X POST https://aihubmix.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: xxx" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-3-7-sonnet-20250219",
"max_tokens": 1024,
"tools": [
{
"type": "text_editor_20250124",
"name": "str_replace_editor"
}
],
"messages": [
{
"role": "user",
"content": "There'\''s a syntax error in my primes.py file. Can you help me fix it?"
}
]
}'
```
### 迁移到 Claude 4(文本编辑工具)
如果您正在从 Claude 3.7 Sonnet 迁移到 Claude 4 模型,请注意以下变化:
#### 更新工具配置
```py python theme={null}
# Claude 3.7 Sonnet
tools=[
{
"type": "text_editor_20250124",
"name": "str_replace_editor"
}
]
# Claude 4 (Opus/Sonnet)
tools=[
{
"type": "text_editor_20250429",
"name": "str_replace_based_edit_tool"
}
]
```
#### 移除不支持的功能
* **`undo_edit 命令`**:Claude 4 模型不再支持撤销编辑功能
* 请从您的代码中移除任何依赖 `undo_edit` 的逻辑
返回示例:
```json theme={null}
{
"id": "msg_bdrk_012xyNaFCQg4zsVcTk5VkDAe",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "I'd be happy to help you fix the syntax error in your `primes.py` file. First, let me take a look at the file to identify the issue."
},
{
"type": "tool_use",
"text": "",
"id": "toolu_bdrk_01P6jQG6suDSsDjzugqGVHWC",
"name": "str_replace_based_edit_tool",
"input": {
"command": "view",
"path": "/repo/primes.py"
}
}
],
"model": "claude-sonnet-4-20250514",
"stop_reason": "tool_use",
"usage": {
"input_tokens": 1042,
"output_tokens": 115
}
}
```
***
更新时间:2026-06-01
# 获取当前用户可用模型列表
Source: https://docs.aihubmix.com/cn/api/CliEndpoints/available-models
GET /api/user/available_models
返回当前用户允许使用的模型列表
## 请求参数
### 请求头(headers)
请求身份认证。接口使用 AIHubMix Manage Key 进行身份认证。
请求内容类型。此参数必须设置为 application/json。
## 响应参数
模型列表。
模型名称。
模型开发者 ID。
模型顺序。
是否成功。
提示信息(可能为空)。请求失败时返回失败原因。
***
更新时间:2026-06-01
# 创建新 KEY
Source: https://docs.aihubmix.com/cn/api/CliEndpoints/create-key
POST /api/token/
创建一个新的 API KEY
## 请求参数
### 请求头(headers)
请求身份认证。接口使用 AIHubMix Manage Key 进行身份认证。
请求内容类型。此参数必须设置为 application/json。
### 请求体(Request Body)
新 Key 的名称。
过期时间。存储格式为 UNIX 时间戳,-1 表示永不过期。
是否限额。
remain\_quota 为:期望限额\*500000
限制模型。
限制 IP
## 响应参数
用户新建 Key 相关信息(通常包含 id、name 等)。
Key ID。
用户 ID
Key 状态。0 为未启用,1 为启用。
Key 名称。
Key 创建时间,保存格式为 UNIX 时间戳。
Key 获取时间,保存格式为 UNIX 时间戳。
Key 过期时间,-1 表示永不过期。
限额余量,-1 表示无限额。
是否限额。
已使用额度为:used\_quota / 500000
限制当前 Key 使用的模型。
IP 限制。
请求失败的详细信息。请求成功时不会返回此参数。
是否成功
***
更新时间:2026-06-01
# 删除 KEY
Source: https://docs.aihubmix.com/cn/api/CliEndpoints/delete-key
DELETE /api/token/{token_id}
根据 token_id 删除一个 KEY
## 请求参数
### 请求头(headers)
请求身份认证。接口使用 AIHubMix Manage Key 进行身份认证。
请求内容类型。此参数必须设置为 application/json。
### 路径参数(Path)
KEY 的 ID。
## 响应参数
是否成功。
提示信息(可能为空)。请求失败时返回失败原因。
删除结果对象(如接口返回)。可能为空对象 `{}`。
***
更新时间:2026-06-01
# 获取单个 KEY 详情
Source: https://docs.aihubmix.com/cn/api/CliEndpoints/get-key
GET /api/token/{token_id}
根据 token_id 获取 KEY 的详细信息
## 请求参数
### 请求头(headers)
请求身份认证。接口使用 AIHubMix Manage Key 进行身份认证。
请求内容类型。此参数必须设置为 application/json。
### 路径参数(Path)
KEY ID。
## 响应参数
是否成功。
提示信息(可能为空)。请求失败时返回失败原因。
Key 详情对象。请求失败时 data 可能为空对象 `{}`。
Key ID。
用户 ID。
Key 字符串(用于调用/鉴权)。
Key 状态。0 为未启用,1 为启用。
Key 名称。
Key 创建时间(UNIX 时间戳)。
Key 最近获取/访问时间(UNIX 时间戳)。
Key 过期时间(UNIX 时间戳);-1 表示永不过期。
限额余量;-1 表示无限额。
是否无限额。true 表示无限额;false 表示限额。
已使用额度。实际用量换算:used\_quota / 500000。
限制当前 Key 使用的模型(空字符串表示不限制或未设置)。
IP 限制(空字符串表示不限制或未设置)。
***
更新时间:2026-06-01
# 获取当前用户信息与余额
Source: https://docs.aihubmix.com/cn/api/CliEndpoints/get-self
GET /api/user/self
获取当前用户信息与账户余额
用于查询当前登录用户的基本信息与余额额度。
## 请求参数
### 请求头(headers)
请求身份认证。接口使用 AIHubMix Manage Key 进行身份认证。
请求内容类型。此参数必须设置为 application/json。
## 响应参数
用户信息对象,包含基本资料、余额额度与提醒设置。
用户名。
用户展示名。
用户角色标识(数值越大权限越高,如管理员)。
账户状态(1 为正常)。
邮箱。
账户余额,实际金额(美元)为: quota / 500000。
已使用额度,实际金额(美元)为: used\_quota / 500000。
累计请求次数。
账户分组。
邀请码。
是否接受低余额提醒。
余额低于 quota\_remind\_threshold / 500000 时接收邮件提醒。
接收提醒的邮箱地址。
扩展字段(预留,通常为空字符串)。
请求失败的详细信息。请求成功时不会返回此参数。
是否成功
```json 200 theme={null}
{
"data": {
"username": "your_name",
"display_name": "your_name",
"role": 1,
"status": 1,
"email": "you@example.com",
"quota": 29071257,
"used_quota": 286403484,
"request_count": 614422,
"group": "default",
"aff_code": "XXXX",
"notify": true,
"quota_remind_threshold": 10000000,
"notify_email": "you@example.com",
"ext": ""
},
"message": "",
"success": true
}
```
***
更新时间:2026-06-26
# 获取用户 KEY
Source: https://docs.aihubmix.com/cn/api/CliEndpoints/get-user-token
GET /api/user/token
获取当前用户的 KEY 信息(若接口返回 token 字段)
## 请求参数
### 请求头(headers)
请求身份认证。接口使用 AIHubMix Manage Key 进行身份认证。
请求内容类型。此参数必须设置为 application/json。
## 响应参数
是否成功。
提示信息(可能为空)。请求失败时返回失败原因。
当前用户的 KEY 信息对象(字段以实际返回为准)。
用户 Token(如接口返回该字段)。
***
更新时间:2026-06-01
# 获取 KEY 列表
Source: https://docs.aihubmix.com/cn/api/CliEndpoints/list-keys
GET /api/token/
获取所有 KEY 列表,支持 num 参数控制数量
## 请求参数
### 请求头(headers)
请求身份认证。接口使用 AIHubMix Manage Key 进行身份认证。
请求内容类型。此参数必须设置为 application/json。
## 响应参数
用户 Key 相关信息(通常包含 id、name 等)。
Key ID。
用户 ID
Key 状态。0 为未启用,1 为启用。
Key 名称。
Key 创建时间,保存格式为 UNIX 时间戳。
Key 获取时间,保存格式为 UNIX 时间戳。
Key 过期时间,-1 表示永不过期。
限额余量,-1 表示无限额。
是否限额。
已使用额度为:used\_quota / 500000
限制当前 Key 使用的模型。
IP 限制。
请求失败的详细信息。请求成功时不会返回此参数。
是否成功
***
更新时间:2026-06-01
# 搜索 KEY
Source: https://docs.aihubmix.com/cn/api/CliEndpoints/search-keys
GET /api/token/search
通过 keyword 搜索 KEY
## 请求参数
### 请求头(headers)
请求身份认证。接口使用 AIHubMix Manage Key 进行身份认证。
请求内容类型。此参数必须设置为 application/json。
### 查询参数(Query)
搜索关键词(通常匹配 KEY 名称等字段)。
## 响应参数
是否成功。
提示信息(可能为空)。请求失败时返回失败原因。
搜索结果列表。数组中每个元素为一个 KEY 对象。
Key ID。
用户 ID。
Key 字符串(用于调用/鉴权)。
Key 状态。0 为未启用,1 为启用。
Key 名称。
Key 创建时间(UNIX 时间戳)。
Key 最近获取/访问时间(UNIX 时间戳)。
Key 过期时间(UNIX 时间戳);-1 表示永不过期。
限额余量;-1 表示无限额。
是否无限额。true 表示无限额;false 表示限额。
已使用额度。实际用量换算:used\_quota / 500000。
限制当前 Key 使用的模型(空字符串表示不限制或未设置)。
IP 限制(空字符串表示不限制或未设置)。
***
更新时间:2026-06-01
# 更新 KEY
Source: https://docs.aihubmix.com/cn/api/CliEndpoints/update-key
PUT /api/token/
更新现有 KEY 的名称、过期时间、额度、模型/IP 限制与状态等
## 请求参数
### 请求头(headers)
请求身份认证。接口使用 AIHubMix Manage Key 进行身份认证。
请求内容类型。此参数必须设置为 application/json。
### 路径参数(Path)
KEY ID。
### 请求体(Request Body)
新 Key 的名称。
过期时间(UNIX 时间戳),-1 表示永不过期。
是否无限额。true 表示无限额;false 表示启用限额(需配合 remain\_quota)。
限额余量。remain\_quota 为:期望限额 \* 500000(例如期望限额 10,则传 5000000)。 当 unlimited\_quota 为 true 时建议传 -1。
Key 状态。0 为未启用,1 为启用。
限制当前 Key 可使用的模型(为空或不传表示不限制)。
IP 限制(为空或不传表示不限制)。
## 响应参数
是否成功
请求失败的详细信息。请求成功时可能为空或不返回。
更新后的 Key 对象。
***
更新时间:2026-06-01
# Codex CLI 接入 AIHubMix 教程
Source: https://docs.aihubmix.com/cn/api/Codex-CLI
在 Codex CLI 中接入 AIHubMix:用单个 API key 在 /model 列表自由切换 GLM、Claude、Gemini、DeepSeek 等模型。含 config.toml 配置、model_catalog_json 模型目录生成脚本与常见问题排查。
[Codex CLI](https://openai.com/codex/) 是 OpenAI 官方的终端编程工具。接入 AIHubMix 后,你只需一个 API key 就能在终端里调用并自由切换 GLM、Claude、Gemini、DeepSeek 等各家模型,无需绑定单一厂商。本文覆盖两种接入方式:**基础方式**(profile + 固定单模型,最快上手)与**自定义模型方式**(用 `model_catalog_json` 目录文件,在 `/model` 列表里随时切换)。
## 安装
### 官网下载(macOS 版本)
[https://openai.com/zh-Hans-CN/codex/](https://openai.com/zh-Hans-CN/codex/)
### 使用命令行安装
```bash theme={null}
npm install -g @openai/codex
```
## 环境变量配置
### 使用配置文件配置
1. 修改 ` ~/.codex/config.toml` 配置文件,增加如下配置:
```toml theme={null}
profile = "aihubmix"
[model_providers.aihubmix]
name = "aihubmix"
base_url = "https://aihubmix.com/v1"
personality = "pragmatic"
wire_api = "responses"
[profiles.aihubmix]
model = "gpt-5.2"
model_provider = "aihubmix"
model_reasoning_effort = "high"
```
2. 修改 ` ~/.codex/auth.json` 配置文件,修改如下配置:
```json theme={null}
{
"OPENAI_API_KEY": "AIHUBMIX_API_KEY"
}
```
### 通过 cc-switch 配置
1. 运行 CC-Switch,添加供应商。
2. 在预设列表中选择「AiHubMix」。
3. 在「API Key」栏中填写你的密钥并点击「添加」保存设置。
4. 返回首页,在供应商列表中选择「AiHubMix」,点击「启用」即可使用。
## 使用 Codex
### 在终端中使用
1. 打开终端,定位到你的项目目录,然后运行 `codex` 命令。
```bash theme={null}
cd /你的项目路径
codex
```
2. 根据需求,设置权限。
3. 根据需求,选择需要使用的模型。
4. 输入自然语言,若正常响应,则配置成功。
### 在 Codex 桌面端使用
1. 打开 Codex 桌面端,选择工作目录。
2. 在输入框输入任务,若正常响应,则配置成功。
## 实用命令参考
### 帮助命令
```bash theme={null}
codex -h
```
### 完整命令选项
```bash theme={null}
Usage
$ codex [options]
Options
-h, --help 显示帮助信息并退出
-m, --model 指定使用的模型 (默认: codex-mini-latest)
-i, --image 包含图像输入的文件路径
-v, --view 查看之前保存的会话记录
-q, --quiet 非交互模式,仅打印助手的最终输出
-a, --approval-mode 覆盖审批策略: 'suggest', 'auto-edit', 或 'full-auto'
--auto-edit 自动批准文件编辑;仍会提示确认命令
--full-auto 自动批准沙箱环境中的编辑和命令
--no-project-doc 不自动包含仓库中的 'codex.md' 文件
--project-doc 包含指定的 Markdown 文件作为上下文
--full-stdout 不截断命令输出的 stdout/stderr
危险选项
--dangerously-auto-approve-everything
跳过所有确认提示并直接执行命令(无沙箱保护)
仅用于临时本地测试环境
实验性选项
-f, --full-context 以"完整上下文"模式启动,将整个仓库加载到上下文中
并在一次操作中应用批量编辑
仅兼容 --model 参数
示例
$ codex "编写并运行一个打印 ASCII 艺术的 Python 程序"
$ codex -q "修复构建问题"
```
## 在 Codex 中使用自定义模型
Codex 默认只在 `/model` 列表里展示 OpenAI 官方模型。如果你想直接从列表中选择 AIHubMix 上的任意模型(GLM、Claude、Gemini、DeepSeek、Kimi、Qwen……),可以用官方支持的「自定义模型」机制:通过一个本地 JSON 文件(`model_catalog_json`)声明可选模型,再用 `[model_providers.aihubmix]` 把请求指向 AIHubMix。
> 官方说明:[Advanced Configuration · OSS mode / local providers](https://developers.openai.com/codex/config-advanced)
### 两种接入方式
本页前面「环境变量配置」讲的是**基础方式**,本节讲的是**自定义模型方式**,区别如下,按需选择:
| | 基础方式(profile + 单模型) | 自定义模型方式(本节) |
| ---- | ------------------------------------- | -------------------------------- |
| 配置内容 | 在 `config.toml` 里写死一个 `model = "xxx"` | 额外维护一个 `model_catalog_json` 目录文件 |
| 切换模型 | 改配置文件后重启 | 直接在 `/model` 列表里点选,随时切 |
| 适合场景 | 长期固定用某一个模型 | 想在多个模型间频繁对比 / 切换 |
| 复杂度 | 低 | 中 |
整体流程只有 4 步:**生成目录文件 → 改 `config.toml` → 设环境变量 → 重启选模型**。
### 第 1 步:生成模型目录文件
目录文件是一个 `{ "models": [ ... ] }` 结构,数组里每个元素描述一个可在 `/model` 里选择的模型。下面先用**一个固定模型**讲清字段,再给**批量生成前 30 名**的脚本。
#### 1.1 先理解格式:固定一个模型
下面是一份**已验证可被 Codex 解析**的最小完整目录(只含 `glm-5.2` 一个模型)。直接存成 `~/.codex/model-catalogs/custom-models.json` 就能用;想要更多模型,就往 `models` 数组里继续追加同样结构的条目。
```json theme={null}
{
"models": [
{
"slug": "glm-5.2",
"display_name": "GLM 5.2",
"description": "GLM 5.2 (via AIHubMix)",
"context_window": 1000000,
"max_context_window": 1000000,
"supported_reasoning_levels": [
{ "effort": "low", "description": "Fast responses" },
{ "effort": "medium", "description": "Balanced" },
{ "effort": "high", "description": "Deeper reasoning" }
],
"shell_type": "shell_command",
"visibility": "list",
"supported_in_api": true,
"priority": 0,
"availability_nux": null,
"upgrade": null,
"base_instructions": "You are Codex, a coding agent.",
"supports_reasoning_summaries": true,
"support_verbosity": false,
"default_verbosity": null,
"apply_patch_tool_type": null,
"truncation_policy": { "mode": "tokens", "limit": 10000 },
"supports_parallel_tool_calls": true,
"experimental_supported_tools": []
}
]
}
```
字段说明(你通常会改的几个):
| 字段 | 作用 | 来自接口 |
| --------------------------------------- | ----------------------------------------- | ---------------- |
| `slug` | 模型 ID,Codex 用它发起请求,必须与接口返回的 `model_id` 一致 | `model_id` |
| `display_name` | `/model` 列表里显示的名字 | `model_name` |
| `context_window` / `max_context_window` | 上下文窗口。**不写会回退到很小的保守默认值**,建议按接口真实值填 | `context_length` |
| `supported_reasoning_levels` | 推理档位,切换模型后用 `/model` 还能选 effort | — |
| `visibility` | 设为 `list` 才会出现在选择器中 | — |
| `priority` | 列表排序,数字越小越靠前 | — |
**其余字段是必填且值固定的**:`base_instructions`、`availability_nux`、`upgrade`、`supports_reasoning_summaries`、`support_verbosity`、`default_verbosity`、`apply_patch_tool_type`、`truncation_policy`、`supports_parallel_tool_calls`、`experimental_supported_tools`。新版 Codex(已在 `codex-cli 0.130.0` 上验证)严格解析,**少任何一个,整份目录都会被丢弃**并回退到内置目录,报错形如 `missing field base_instructions`,表现就是「`/model` 里一个自定义模型都看不到」。所以上面这份示例不能再删字段。
关于 `base_instructions`:它是该模型的**系统提示词**。示例里用一句话占位,模型能正常跑;想要最接近原生 Codex 的编码表现,把它换成 `codex debug models --bundled` 里任一内置模型的完整 `base_instructions`(下一节的批量脚本就是这么做的)。
官方目录用 **snake\_case** 字段(`display_name`、`supported_in_api`、`visibility`)。两类错误都会让整份目录被丢弃、`/model` 里看不到模型:缺必填字段会报 `missing field ...`;用了 `displayName`、`hidden` 这类 camelCase 旧格式或不认识的取值会报 `unknown variant ...`。以本文这套字段为准即可避开。
#### 1.2 批量生成前 30 名
手写多个条目容易漏字段。要把 [AIHubMix 模型列表接口](https://aihubmix.com/api/v1/models?type=llm) 的前 30 个 LLM 一次性写进目录,用下面的脚本——它**以一个内置模型为模板克隆**,必填字段(含正确的 `base_instructions`)天生齐全,跨 Codex 版本都不缺。需要 `curl`、`python3` 和已安装的 `codex` CLI:
```bash theme={null}
mkdir -p ~/.codex/model-catalogs
# 1) 取一个内置模型当模板:它自带 base_instructions 等全部必填字段
codex debug models --bundled > /tmp/_tpl.json
# 2) 拉 AIHubMix 模型列表
curl -s "https://aihubmix.com/api/v1/models?type=llm" > /tmp/_aihubmix.json
# 3) 克隆模板逐个生成条目,只覆盖每个模型独有的字段
python3 - <<'PY' > ~/.codex/model-catalogs/custom-models.json
import json, sys
tpl = json.load(open("/tmp/_tpl.json"))["models"][0] # 任意内置模型当模板
api = json.load(open("/tmp/_aihubmix.json"))["data"]
# 跳过图像生成模型(types 含 image_generation),再取前 30
api = [m for m in api if "image_generation" not in (m.get("types") or "")][:30]
out = []
for i, m in enumerate(api):
e = dict(tpl) # 克隆模板的全部字段
ctx = m.get("context_length") or 200000
e["slug"] = m["model_id"] # 必须与接口 model_id 一致
e["display_name"] = m.get("model_name") or m["model_id"]
e["description"] = (m.get("model_name") or m["model_id"]) + " (via AIHubMix)"
e["context_window"] = ctx
e["max_context_window"] = ctx
e["visibility"] = "list"
e["supported_in_api"] = True
e["priority"] = i
e["availability_nux"] = None
e["upgrade"] = None
out.append(e)
json.dump({"models": out}, sys.stdout, ensure_ascii=False, indent=2)
PY
```
脚本只覆盖每个模型独有的字段(`slug`、`display_name`、`description`、`context_window` 等),其余必填字段全部从内置模板克隆而来——这正是 1.1 里那套字段,只是 `base_instructions` 用的是完整官方提示词。
> 生成的文件较大(每个条目都含完整 `base_instructions`,约 1~2 MB),属正常现象。运行后用 `codex debug models` 验证能否被正确解析(见第 5 步)。
> 脚本里那行 `image_generation` 过滤是有意保留的:`type=llm` 的返回中有极少数模型同时带 `image_generation` 标签(如 `gpt-image-2`),不适合对话,脚本会自动跳过后再取前 30。
### 第 2 步:修改 `config.toml`
编辑 `~/.codex/config.toml`,在**根级别**加上 `model_catalog_json`,并定义 `aihubmix` provider:
```toml theme={null}
# ⚠️ model_catalog_json 必须写在根级别,不能放进 [model_providers.*] 段里
model_provider = "aihubmix"
model_catalog_json = "~/.codex/model-catalogs/custom-models.json"
[model_providers.aihubmix]
name = "Aihubmix"
base_url = "https://aihubmix.com/v1"
wire_api = "responses"
env_key = "AIHUBMIX_API_KEY"
```
`wire_api = "responses"` 是关键,**漏写或写成 `chat` 都连不上**。Codex 新版只走 OpenAI 的 Responses API(`/v1/responses`),AIHubMix 已原生兼容 Responses API,所以直接指向 `https://aihubmix.com/v1` 即可,无需自建转换代理。
如果想顺便指定**默认模型**和**默认推理档位**(启动时直接用,不用每次手点),可以用这份更完整的配置:
```toml theme={null}
model = "glm-5.2" # 启动默认模型,需在目录文件里存在
model_provider = "aihubmix"
model_catalog_json = "~/.codex/model-catalogs/custom-models.json"
model_reasoning_effort = "high" # 默认推理档位:minimal / low / medium / high
[model_providers.aihubmix]
name = "Aihubmix"
base_url = "https://aihubmix.com/v1"
wire_api = "responses"
env_key = "AIHUBMIX_API_KEY"
```
配好后 `config.toml` 大致如下(红框为本步的关键项:根级别的 `model` / `model_provider` / `model_catalog_json`,以及 `[model_providers.aihubmix]` 段):
### 第 3 步:设置环境变量
把上面 `env_key` 指定的环境变量配好(注意 `=` 两侧不要有空格):
```bash theme={null}
export AIHUBMIX_API_KEY=sk-xxx
```
建议写进 `~/.zshrc` / `~/.bashrc` 持久化。在 [AIHubMix 控制台](https://aihubmix.com/token) 获取 Key。
### 第 4 步:重启并选择模型
重启 Codex App / TUI 让目录文件生效,然后:
```bash theme={null}
codex
# 在交互界面里输入 /model,即可看到上一步声明的 30 个模型并切换
```
输入 `/model` 后会列出目录里声明的全部模型,方向键选中、回车确认:
选中模型后,`/model` 还会让你选推理档位(effort),按需求选 `low` / `medium` / `high` 即可。
### 第 5 步:验证是否生效
1. 进入 Codex 后输入 `/model`,确认能看到目录里声明的模型,并切到其中一个(如 `glm-5.2`)。
2. 随便提一个问题验证链路打通。注意:**不要靠「你是哪个模型」来判断**——`base_instructions` 里写着「You are Codex... based on GPT-5」,所有模型都会照此自称 GPT-5,问了也分辨不出真实模型。要确认实际调用的模型,登录 [AIHubMix 控制台](https://aihubmix.com/token)「日志」页看那条请求记录的 `model_id`,这才是真相。
切换成功后顶部会提示 `Model changed to ...`,底部状态栏也会显示当前模型与上下文窗口(下图切到了 `glm-5.2`,窗口 258K):
## 自定义模型常见问题
* **`/model` 里看不到自定义模型?** 按先后顺序排查:
1. **先跑 `codex debug models`**。若报 `missing field ...`(最常见,缺必填字段)或 `unknown variant ...`(字段名/取值不对),说明整份目录解析失败被丢弃——用第 1 步「克隆内置模板」脚本重新生成即可。
2. 确认 `model_catalog_json` 写在 `config.toml` **根级别**,不在 `[model_providers.*]` 段里;
3. 确认 JSON 用的是 snake\_case 官方字段、`visibility` 为 `list`;
4. 如果 `codex debug models` 已经能看到全部模型,但\*\*桌面端(Desktop App)\*\*里只剩一两个、当前模型显示为「自定义」——这是桌面端的已知 bug:它会在本地目录之上再套一层官方 slug 白名单过滤,把非官方模型从选择器里删掉(见 GitHub Issue [#19694](https://github.com/openai/codex/issues/19694)、[#15138](https://github.com/openai/codex/issues/15138))。此时模型其实仍按 `config.toml` 里的 `model = "..."` 正常调用(去 AIHubMix 日志可证实),只是名字显示不出来。**要正确显示就用终端 `codex` CLI / TUI**;桌面端只能直接在 `config.toml` 里写死 `model = "你要的模型"`,等官方修复。
* **目录是「替换」不是「合并」。** `model_catalog_json` 会**替换**整个模型列表,而不是追加(实测:目录里只放 2 个模型,`codex debug models` 就只剩这 2 个,内置的 `gpt-5.x` 全部消失)。如果你两类都想要,就把它们一并写进自定义目录。
* **请求报协议错误 / 连不上。** 多半是 provider 的 `base_url` 或 `wire_api` 没配对。AIHubMix 必须 `wire_api = "responses"` + `base_url = "https://aihubmix.com/v1"`。若你接的是只支持 Chat Completions 的第三方,则需要本地转换代理,AIHubMix 用户无需此步。
* **频繁 “Reconnecting” 重连。** 部分网络/代理环境下 WebSocket(WSS)不通,可在 provider 段加 `supports_websockets = false` 强制走 HTTP。
* **解析报 `missing field ...`(如 `missing field base_instructions`)。** 条目缺了必填字段。新版 Codex 严格解析,`base_instructions`、`availability_nux`、`upgrade`、`supports_reasoning_summaries`、`support_verbosity`、`default_verbosity`、`apply_patch_tool_type`、`truncation_policy`、`supports_parallel_tool_calls`、`experimental_supported_tools` 等都必须存在。用第 1 步「克隆内置模板」脚本可一次性补齐。
* **解析报 `unknown variant`。** 目录 JSON 里有 Codex 不认识的字段名或取值(常见于 `displayName`/`hidden` 等 camelCase 旧格式)。改用本文的 snake\_case 字段集即可。
## 相关文档
* [模型智能路由](/cn/api/llm-router):把模型名填 `auto`,由网关按请求自动选最优模型。
* [模型列表 API](/cn/api/Models-API):查询 AIHubMix 上全部可用模型与其 `model_id`。
* [应用标识码 App-Code](/cn/api/App-code):接入后多数模型享 10% 优惠。
* [AIHubMix CLI](/cn/api/aihubmix-cli):在终端查询余额、管理 API Key、查看可用模型。
## 参考文章
* 官方文档:[Advanced Configuration](https://developers.openai.com/codex/config-advanced) | [Configuration Reference](https://developers.openai.com/codex/config-reference)
* 官方内置目录格式参考:[codex-rs/models-manager/models.json](https://github.com/openai/codex/blob/main/codex-rs/models-manager/models.json)
* 社区指南:[Codex config.toml:6 行接入任意自定义 provider](https://www.morphllm.com/codex-provider-configuration)
***
更新时间:2026-06-25
# 零数据存储说明
Source: https://docs.aihubmix.com/cn/api/Data-Pravicy
## 数据存储原则
AIHubMix 不会主动存储您的提示(Prompt)或模型响应内容。
## AIHubMix 会存储哪些数据?
为保障服务质量与系统稳定性,AIHubMix 会存储每次请求的必要元数据(例如 Token 数量、延迟等)。这些信息仅用于支持我们的报告和模型排名,以及您的[用量情况](https://console.aihubmix.com/statistics)。
此元数据不包含您的提示内容或模型响应文本,仅限于与请求本身相关的技术信息。
OpenAI 与 Grok 官方在检测到可能违反其使用政策的内容时,会采取账号限制或封禁措施,并向 AIHubMix 发送合规通知。
AIHubMix 不主动存储提示或响应内容。仅在发生账号封禁且收到官方合规通知时,平台才会被动接收并留存相关请求信息(包括请求时间、提示内容、模型响应及违规说明等)。
## 日志与数据处理
AIHubMix 平台对接的每一家 AI 供应商均拥有独立的数据处理策略,包括日志记录机制和数据保留期限。
### 供应商数据政策
基于合规要求,不同服务提供商会制定并执行各自的数据保留政策。
平台已对主要供应商的数据保留政策进行汇总说明,如需了解完整条款,请通过对应供应商的官方链接进行查阅。
| 供应商 | 是否存储用户数据 | 存储数据范围 | 数据保留 | 是否用于训练 |
| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------- | :------------------ | :--------- | :------ |
| [AI21](https://www.ai21.com/terms-of-service/) | 是 | Prompt / Completion | 提示信息保留时间未知 | 不会用于训练 |
| [Alibaba Cloud Int.](https://terms.alicdn.com/legal-agreement/terms/common_platform_service/20230728213935489/20230728213935489.html?spm=a2c4g.11186623.0.0.5c52f1e5ZqHnxl) | 是 | Prompt / Completion | 提示信息保留时间未知 | 不会用于训练 |
| [Anthropic](https://privacy.claude.com/en/collections/10663361-commercial-customers) | 是 | Prompt / Completion | 保留 30 天 | 不会用于训练 |
| [AWS](https://aws.amazon.com/cn/bedrock/security-compliance/) | ZDR | 无 | 零数据保留 | 不会用于训练 |
| [Azure](https://www.microsoft.com/en-sg/trust-center/privacy) | ZDR | 无 | 零数据保留 | 不会用于训练 |
| [Baichuan](https://platform.baichuan-ai.com/article/privacy-agreement) | 是 | Prompt / Completion | 提示信息保留时间未知 | 不会用于训练 |
| [Baidu (Qianfan)](https://cloud.baidu.com/doc/Agreements/s/Plr0fi68q) | 是 | Prompt / Completion | 提示信息保留时间未知 | 不会用于训练 |
| [ByteDance](https://www.volcengine.com/docs/6256/64902) | ZDR | 无 | 零数据保留 | 不会用于训练 |
| [Cerebras](https://www.cerebras.ai/policies) | ZDR | 无 | 零数据保留 | 不会用于训练 |
| [Chutes](https://chutes.ai/privacy) | 是 | Prompt / Completion | 提示信息保留时间未知 | 可能会用于训练 |
| [Cohere](https://cohere.com/terms-of-use) | 是 | Prompt / Completion | 保留 30 天 | 不会用于训练 |
| [Deepinfra](https://deepinfra.com/docs/data) | ZDR | 无 | 零数据保留 | 不会用于训练 |
| [DeepSeek](https://cdn.deepseek.com/policies/en-US/deepseek-privacy-policy.html) | 是 | Prompt / Completion | 提示信息保留时间未知 | 可能会用于训练 |
| [Google AI Studio](https://ai.google.dev/gemini-api/docs/logs-policy?hl=zh-cn) | 是 | Prompt / Completion | 保留 55 天 | 不会用于训练 |
| [Google Vertex](https://cloud.google.com/privacy) | ZDR | 无 | 零数据保留 | 不会用于训练 |
| [Groq](https://groq.com/privacy-policy) | ZDR | 无 | 零数据保留 | 不会用于训练 |
| [Hunyuan (Tencent)](https://rule.tencent.com/rule/ae038a2d-314d-4320-8cf0-d0193af32ae5) | 是 | Prompt / Completion | 提示信息保留时间未知 | 不会用于训练 |
| [Ideogram](https://ideogram.ai/legal/privacy) | 是 | Prompt / Image | 提示信息保留时间未知 | 可能会用于训练 |
| [InclusionAI](https://render.alipay.com/p/c/180021120000001606/index.html?agreementId=AG01001548) | 是 | Prompt / Completion | 提示信息保留时间未知 | 不会用于训练 |
| [Jina AI](https://jina.ai/legal/) | 是 | Prompt | 提示信息保留时间未知 | 可能会用于训练 |
| [Meituan (LongCat)](https://www.longcatai.net/privacy) | 是 | Prompt / Completion | 提示信息保留时间未知 | 不会用于训练 |
| [MiniMax](https://platform.minimax.io/protocol/privacy-policy) | 是 | Prompt / Completion | 提示信息保留时间未知 | 可能会用于训练 |
| [Mistral](https://mistral.ai/terms/#terms-of-use) | 是 | Prompt / Completion | 保留 30 天 | 不会用于训练 |
| [Moonshot AI](https://platform.moonshot.cn/docs/agreement/userprivacy) | ZDR | 无 | 零数据保留 | 不会用于训练 |
| [Nvidia](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf) | 是 | Prompt / Completion | 提示信息保留时间未知 | 可能会用于训练 |
| [OpenAI](https://developers.openai.com/api/docs/guides/your-data) | 是 | Prompt / Completion | 提示信息保留时间未知 | 不会用于训练 |
| [Perplexity](https://www.perplexity.ai/hub/legal/perplexity-api-terms-of-service) | ZDR | 无 | 零数据保留 | 不会用于训练 |
| [SiliconFlow](https://docs.siliconflow.com/en/legals/privacy-policy) | ZDR | 无 | 零数据保留 | 不会用于训练 |
| [Sophnet](https://github.com/axdlee/sophnet/blob/main/PRIVACY.md) | ZDR | 无 | 零数据保留 | 不会用于训练 |
| [StepFun](https://platform.stepfun.com/legal/privacy-policy.html) | 是 | Prompt / Completion | 提示信息保留时间未知 | 不会用于训练 |
| [xAI](https://x.ai/legal/terms-of-service-enterprise/) | 是 | Prompt / Completion | 保留 30 天 | 不会用于训练 |
| [Xiaomi](https://www.mi.com/global/about/privacy/) | 是 | Prompt / Completion | 保留 30 天 | 不会用于训练 |
| [Z.ai](http://Z.ai) | ZDR | 无 | 零数据保留 | 不会用于训练 |
***
更新时间:2026-06-01
# Dify 插件
Source: https://docs.aihubmix.com/cn/api/Dify-plugin
在 Dify 中通过 Aihubmix 插件接入 Claude、GPT、Gemini 等模型,涵盖对话、向量、重排与语音,并支持为 Claude 开启提示词缓存。
## 一键安装 Aihubmix 插件
直接点击下方链接,在 Dify Marketplace 页面点击「Install」按钮即可完成安装:
👉 [前往 Dify 插件市场](https://marketplace.dify.ai/plugins/langgenius/aihubmix?language=en-US\&theme=system)
**示例图如下:**
## 配置
1. 首先点击页面右上角头像 → 选择「Settings」菜单
2. 点击左侧「Model Provider」Tab
3. 在右侧找到 Aihubmix → 展开 Setup,填入你的[API Key](https://console.aihubmix.com/token)
**目前预置的模型有以下 5 大类:**
* LLM:大语言模型
* TEXT EMBEDDING:向量嵌入模型
* RERANK:重排序模型
* SPEECH2TEXT:语音转文本模型
* TTS:文本转语音模型
**如何新增更多自定义模型?**
点击「+ Add model」,在弹出面板的 Model Name 选项里:
* 填入模型广场中的任何[模型 ID](https://aihubmix.com/models),比如 `gpt-4o-2024-11-20`。
* 填入你的 API Key 后,点击「Save」即可。
需要注意的是,由于 Dify 插件的设计特殊性,目前暂不支持绘图模型,因此像是 `gpt-image-1` 这种绘图模型无法加入。
## LLM 选择
在工作流 (Workflow) 节点中,选择「LLM」,即可选择插件中已经配置好的,由 Aihubmix 提供的模型。
**示例图如下:**
## Embeddings/Reranker 模型选择
Embeddings/Reranker 模型主要用于知识库问答,你可以在顶部的 Knowledge Tab 快速体验,也可以在工作流节点中选择相应的模型。
**示例图如下:**
## TTS/SST 选择
TTS/SST 模型主要用于语音解析与合成,选择工具时,对应的不是常规的「LLM」,而是「Tools」Tab 里面的「Audio」 类型。 对应关系:
1. TTS 文转音:选择「Text to Speech」
2. SST 音转文:选择「Speech to Text」
**示例图如下:**
## Claude 提示词缓存
在 Dify 中通过本插件为 Claude 模型开启提示词缓存:用 `…` 包裹要缓存的提示词,并把模型参数里的「大消息自动缓存阈值」设为正整数。完整用法与命中要点见 [Claude 提示词缓存](./Claude-Cache)。
***
更新时间:2026-06-01
# 向量嵌入
Source: https://docs.aihubmix.com/cn/api/EBD
AIHubMix 提供兼容 OpenAI 标准的高效向量嵌入方案
## 调用指引
AIHubMix 的嵌入模型能够高效地将文本或文档内容转化为可检索的向量数据,广泛应用于 RAG 问答系统和智能客服。无论文本还是文档,均可一键生成嵌入,显著提升语义处理表现。
```py 通用 Embedding theme={null}
from openai import OpenAI
import os
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # 换成你在后台生成的 Key "sk-***"
base_url="https://aihubmix.com/v1"
)
response = client.embeddings.create(
input="Your text string goes here",
model="gemini-embedding-001"
)
print(response.data[0].embedding)
```
```py 文档读取并嵌入 theme={null}
from openai import OpenAI
import os
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # 换成你在后台生成的 Key "sk-***"
base_url="https://aihubmix.com/v1"
)
# Read file
def read_whimery_file():
try:
with open('yourpath/file.md', 'r', encoding='utf-8') as file:
return file.read()
except Exception as e:
print(f"Error reading file: {e}")
return None
# Read the content and create embeddings
content = read_whimery_file()
if content:
response = client.embeddings.create(
input=content,
model="gemini-embedding-001"
)
print("File content successfully processed into embeddings")
print(f"Embedding dimensions: {len(response.data[0].embedding)}")
print("First 10 embedding values:", response.data[0].embedding)
else:
print("Failed to read file content")
```
## 可用模型
* gemini-embedding-001
* gemini-embedding-exp-03-07
* text-embedding-3-large
* text-embedding-3-small
* text-embedding-ada-002
* jina-embeddings-v4
* jina-embeddings-v3
* jina-embeddings-v2-base-code
* text-embedding-v4
* Qwen/Qwen3-Embedding-0.6B
* doubao-embedding-large-text-240915
* doubao-embedding-text-240715
***
更新时间:2026-06-01
# FIM 补全
Source: https://docs.aihubmix.com/cn/api/FIM
### 1. 使用场景
在 FIM (Fill In the Middle) 补全任务中,用户输入希望保留的前缀和后缀内容,模型根据这些提示生成中间缺失的部分。这种补全方式常见于代码自动补全、文本中段生成等应用场景。
### 2. 使用方式
在 chat/completions 接口中使用,只需要将 `model id` 设置为[模型广场](https://aihubmix.com/models)上的模型 id 即可,在模块卡片的右上角复制。
```json theme={null}
{
"model": "model id",
"messages": "prompt",
"params": "params",
"extra_body": {"prefix":"前缀内容", "suffix":"可选的后缀内容"}
}
```
在 completions 接口中使用
```json theme={null}
{
"model": "model info",
"prompt": "前缀内容",
"suffix": "后缀内容"
}
```
### 3. 使用示例
#### 3.1 基于 OpenAI 的 chat.completions 接口使用FIM补全:
```py Python theme={null}
from openai import OpenAI
client = OpenAI(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com/v1"
)
messages = [
{"role": "user", "content": "Please write a sum function code"},
]
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
extra_body={
"prefix": f"""
def sum_numbers(numbers):
# 如果列表为空,返回 0
if not numbers:
return 0
""",
"suffix": f"""
# 测试
numbers = [1, 2, 3, 4, 5]
result = sum_numbers(numbers)
print("Sum of numbers:", result)
"""
},
stream=True,
max_tokens=4096
)
for chunk in response:
if chunk.choices and len(chunk.choices) > 0 and chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end='')
```
#### 3.2 基于 OpenAI 的 completions 接口使用 FIM 补全:
```py Python theme={null}
client = OpenAI(
api_key="Aihubmix APIKEY",
base_url="https://aihubmix.com/v1"
)
response = client.completions.create(
model="deepseek-ai/DeepSeek-V2.5",
prompt=f"""
def quick_sort(arr):
# 基本情况,如果数组长度小于等于 1,则返回数组
if len(arr) <= 1:
return arr
else:
""",
suffix=f"""
# 测试 quick_sort 函数
arr = [3, 6, 8, 10, 1, 2, 1]
sorted_arr = quick_sort(arr)
print("Sorted array:", sorted_arr)
""",
stream=True,
max_tokens=4096
)
for chunk in response:
print(chunk.choices[0].text, end='')
```
***
更新时间:2026-06-01
# GPT 提示词缓存
Source: https://docs.aihubmix.com/cn/api/GPT-Cache
GPT 提示缓存(Prompt Caching)用法与计费:GPT-5.6 系列 gpt-5.6-sol / gpt-5.6-terra / gpt-5.6-luna 缓存写入按 1.25 倍输入价、读取按 0.1 倍计费,支持 prompt_cache_key 与显式缓存断点,含接口示例与命中排查。
GPT 系列模型(gpt-4o 及之后)的提示缓存(Prompt Caching)自动生效:请求前缀达到 1,024 Token、且与近期请求逐字一致时,命中部分按缓存读取价计费,同时降低首 Token 延迟。GPT-5.6 系列(`gpt-5.6-sol` / `gpt-5.6-terra` / `gpt-5.6-luna`)对缓存机制做了升级:缓存写入开始独立计费(1.25 倍输入价)、缓存读取为 0.1 倍输入价、缓存至少保留 30 分钟,并新增 `prompt_cache_key` 可靠匹配与显式缓存断点参数。
两代模型的缓存行为速览:
| | GPT-5.6 之前 | GPT-5.6 及之后 |
| :----------------- | :------------------------------- | :-------------------------------------------- |
| 缓存方式 | 自动 | 自动 + 显式断点 |
| 最小缓存长度 | 1,024 Token | 1,024 Token |
| 缓存写入计费 | 不另计费 | 1.25x 基础输入价 |
| 缓存读取计费 | 按对应模型的缓存读取价 | 0.1x 基础输入价 |
| 缓存保留时间 | 不活跃 5–10 分钟后清除,最长 1 小时 | 至少保留 30 分钟 |
| `prompt_cache_key` | 可选,用于提高命中率 | 官方要求设置,以启用更可靠的缓存匹配 |
| 24 小时扩展保留 | 部分模型支持(`prompt_cache_retention`) | 由 `prompt_cache_options.ttl` 取代,当前仅支持 `"30m"` |
## 快速开始
提示缓存无需额外配置:用相同的长前缀连续请求两次,第二次响应的 `usage.prompt_tokens_details.cached_tokens` 大于 0 即为命中。GPT-5.6 系列建议同时设置 `prompt_cache_key`:
```shell Curl theme={null}
curl https://aihubmix.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-d '{
"model": "gpt-5.6-sol",
"prompt_cache_key": "my-app-report-assistant-v1",
"messages": [
{
"role": "system",
"content": "You are a meticulous assistant for analyzing quarterly financial reports... [此处放置固定不变的长指令或参考资料,≥1024 Token]"
},
{
"role": "user",
"content": "Summarize the key figures in one sentence."
}
]
}'
```
```py Python (OpenAI SDK) theme={null}
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AIHUBMIX_API_KEY"], # 密钥从环境变量读取
base_url="https://aihubmix.com/v1",
)
long_context = "You are a meticulous assistant for analyzing quarterly financial reports... [固定不变的长指令或参考资料,≥1024 Token]"
# 相同前缀连续请求两次,第二次命中缓存
for i in range(2):
completion = client.chat.completions.create(
model="gpt-5.6-sol",
prompt_cache_key="my-app-report-assistant-v1",
messages=[
{"role": "system", "content": long_context},
{"role": "user", "content": "Summarize the key figures in one sentence."},
],
)
print(completion.usage.prompt_tokens_details)
```
两次调用的实测 usage(2026-07-10,`gpt-5.6-sol`):
```json theme={null}
// 第 1 次调用:无命中
"prompt_tokens_details": {"audio_tokens": 0, "cached_tokens": 0}
// 第 2 次调用:前缀命中缓存
"prompt_tokens_details": {"audio_tokens": 0, "cached_tokens": 2816}
```
## 缓存计费
GPT-5.6 系列的缓存计费规则:
| 计费项 | 费率 |
| :--------- | :---------- |
| 常规输入 Token | 按平台定价 |
| 缓存写入 Token | 1.25x 基础输入价 |
| 缓存读取 Token | 0.1x 基础输入价 |
| 输出 Token | 按平台定价 |
OpenAI 官方对该规则的表述(出自 [GPT-5.6 发布公告](https://openai.com/index/gpt-5-6/)):"For GPT‑5.6 and later models, cache writes are billed at 1.25x the model's uncached input rate, while cache reads continue to receive the 90% cached-input discount."。[官方提示缓存指南](https://developers.openai.com/api/docs/guides/prompt-caching)中该计费规则的适用范围表述为 "GPT-5.6 models and later model families"(GPT-5.6 及之后的模型家族)。各模型的官方标价见 [OpenAI Pricing](https://developers.openai.com/api/docs/pricing),AIHubMix 实际价格以[模型广场](https://aihubmix.com/models)为准。
由官方计价规则可以直接算出盈亏:写入一段前缀比不缓存多付 0.25 倍输入价,此后每命中一次省 0.9 倍输入价。前缀只要被复用 1 次即净节省;复用次数越多节省越多。前缀完全不会复用的一次性请求会多付写入费,可以用 explicit 模式关闭缓存(见下文「GPT-5.6 缓存参数」)。
GPT-5.6 之前的模型缓存写入不另计费,缓存读取按对应模型的缓存读取价计费,各模型价格以[模型广场](https://aihubmix.com/models)为准。
GPT-5.6 系列区分长短上下文档位:单次请求输入超过 272K Token 时,整个请求按长上下文档计费(输入 2 倍、输出 1.5 倍)。缓存写入 1.25x、读取 0.1x 的计价比例在长上下文档下同样成立,基数为长上下文档的输入价。
## 缓存如何自动生效
发送请求时,系统会检查请求前缀(按 messages、tools 等序列化后的顺序)是否与近期请求的前缀逐字一致:
1. 前缀达到 1,024 Token 且找到一致的缓存前缀时,命中部分按缓存读取价计费,并降低首 Token 延迟;
2. 未找到时按常规输入处理,并把前缀写入缓存(GPT-5.6 及之后按 1.25x 计写入费);
3. 命中要求前缀逐字节一致,前缀中任何一处变化都会使该位置之后的缓存全部失效。
以下场景收益最明显:
* 固定的长系统指令或大量 few-shot 示例
* RAG 场景中重复引用的长参考资料
* 携带大量工具定义(tools)的 Agent 工作流
* 只往后追加消息的长多轮对话
缓存保留时间:GPT-5.6 之前的模型在不活跃 5–10 分钟后清除、最长 1 小时;GPT-5.6 及之后至少保留 30 分钟,实际可能保留更久。缓存不跨组织共享,且缓存对输出内容没有影响。
## GPT-5.6 缓存参数
GPT-5.6 系列新增了三个缓存相关参数(Chat Completions 与 Responses API 通用):
| 参数 | 类型 / 位置 | 取值 | 默认 |
| :------------------------ | :----------- | :----------------------------------------------------- | :------------------------------ |
| `prompt_cache_key` | string,请求体顶层 | 自定义稳定标识,建议按业务或租户划分;单个 key 的总流量建议控制在约 15 次/分钟内 | 无 |
| `prompt_cache_options` | object,请求体顶层 | `mode`: `"implicit"` / `"explicit"`;`ttl`: 仅支持 `"30m"` | `mode: "implicit"`、`ttl: "30m"` |
| `prompt_cache_breakpoint` | object,内容块内 | `{"mode": "explicit"}`,标记缓存前缀的结束位置 | 不设置断点 |
GPT-5.6 之前的模型不支持这三个参数中的 `prompt_cache_options` 与 `prompt_cache_breakpoint`,请求会被拒绝;旧模型的 24 小时扩展保留参数 `prompt_cache_retention`(`"24h"` / `"in_memory"`)在 GPT-5.6 及之后由 `prompt_cache_options.ttl` 取代。
三种缓存控制方式的关系:
1. **默认(implicit 模式)**:不传任何缓存参数也会自动写缓存——系统在最新一条消息的位置自动设置断点。GPT-5.6 及之后,自动发生的缓存写入同样按 1.25x 计费。
2. **implicit 模式 + 显式断点**:在自动断点之外,可在内容块上设置 `prompt_cache_breakpoint`,把缓存边界固定在稳定内容的末尾;断点之后的内容变化不会破坏断点之前的前缀缓存。
3. **explicit 模式**:`prompt_cache_options.mode` 设为 `"explicit"` 后只使用手动断点;完全不设置断点时该请求不使用缓存、也不产生缓存写入费。[官方原文](https://developers.openai.com/api/docs/guides/prompt-caching):"If the conversation contains no explicit breakpoints, the request does not use prompt caching or incur cache-write charges."
用 explicit 模式关闭一次性长请求的缓存写入费:
```json theme={null}
{
"model": "gpt-5.6-sol",
"prompt_cache_options": {"mode": "explicit"},
"messages": [
{"role": "user", "content": "[不会复用的一次性长内容]"}
]
}
```
显式断点的官方规范用法(断点设置在固定长内容块的末尾):
```json theme={null}
{
"model": "gpt-5.6-sol",
"prompt_cache_key": "my-app-report-assistant-v1",
"messages": [
{
"role": "system",
"content": [
{
"type": "text",
"text": "[固定不变的长指令或参考资料,≥1024 Token]",
"prompt_cache_breakpoint": {"mode": "explicit"}
}
]
},
{"role": "user", "content": "Summarize the key figures in one sentence."}
]
}
```
硬约束(官方口径):
* 每个请求最多创建 4 个新的缓存写入;implicit 模式下自动断点占用其中 1 个;
* 断点之前的前缀仍需达到 1,024 Token 才会被缓存;
* 读取时在最近 50 个断点中取最长匹配前缀;
* 断点设置在不支持的内容块上会返回 `400 invalid_request_error`。Chat Completions 支持 `text` / `image_url` / `input_audio` / `file` / `refusal` 块,Responses API 支持 `input_text` / `input_image` / `input_file` 块。
AIHubMix 对 `prompt_cache_breakpoint` 内容块断点及 Responses API 缓存命中的支持正在完善中。现阶段推荐通过 Chat Completions 使用自动缓存并设置 `prompt_cache_key`(本页快速开始示例,已验证可命中);`prompt_cache_options` 的 explicit 模式可正常用于关闭缓存写入。本页将随支持进度更新。
## 为什么缓存没有命中
命中要求断点位置之前的所有内容逐字节一致。第二次请求 `cached_tokens` 仍为 0 时,按以下清单排查:
* **前缀不足 1,024 Token**:低于最小缓存长度的请求按常规输入处理;
* **前缀中混入了变化内容**:时间戳、会话 ID、用户变量等应放到固定内容之后,前缀中任何一处变化都会使之后的缓存失效;
* **tools 定义或顺序变化**:工具列表参与前缀计算,定义与排列顺序都必须完全一致;
* **图片 detail 参数不一致**:`detail` 影响图片 Token 化结果,需保持相同;
* **结构化输出 schema 变化**:`response_format` 的 JSON Schema 作为系统消息前缀参与缓存,schema 变化即前缀变化;
* **`reasoning_effort` 变化**:官方将其列为缓存命中率降低的常见原因之一("Changes to reasoning effort");
* **超过缓存保留期**:GPT-5.6 之前不活跃 5–10 分钟后清除,GPT-5.6 及之后至少保留 30 分钟;
* **未设置 `prompt_cache_key`(GPT-5.6)**:不设置时仍可能自动命中,但不使用更可靠的匹配机制。
## 最佳实践
* 固定内容(系统指令、示例、参考资料、工具定义)放在请求最前面,每轮变化的内容放在最后;
* 为共享同一前缀的流量设置同一个稳定的 `prompt_cache_key`,单个 key 的总流量控制在约 15 次/分钟内,超出时按业务拆分更多 key;
* 多轮对话只向后追加消息,避免修改历史消息;
* 保持相同前缀的请求有持续流量,减少缓存被清除;
* 前缀不会复用的一次性长请求,用 explicit 模式避免缓存写入费(GPT-5.6 及之后);
* 通过 `usage.prompt_tokens_details.cached_tokens` 持续监控命中情况。
## 常见问题
### GPT 的提示缓存需要手动开启吗?
无需手动开启:前缀达到 1,024 Token 即自动缓存。GPT-5.6 及之后建议同时设置 `prompt_cache_key` 以获得更可靠的缓存匹配。
### GPT-5.6 的缓存写入费如何计算?如何避免不必要的写入费?
缓存写入按基础输入价的 1.25 倍计费,读取按 0.1 倍计费;前缀被复用 1 次即净节省。前缀不会复用的一次性长请求,把 `prompt_cache_options.mode` 设为 `"explicit"` 且不设置断点,该请求即不使用缓存、不产生写入费。
### 缓存能保留多久?
GPT-5.6 及之后至少保留 30 分钟(`ttl` 当前仅支持 `"30m"`,实际可能保留更久);GPT-5.6 之前的模型在不活跃 5–10 分钟后清除、最长 1 小时,部分旧模型支持 `prompt_cache_retention: "24h"` 扩展保留。
### GPT-5.6 的显式断点和 Claude 的 cache\_control 有什么区别?
两者都用于把缓存边界固定在稳定内容末尾。主要区别:GPT-5.6 无需任何参数即自动缓存、断点为可选精细控制,Claude 需在请求中启用缓存(顶层 `cache_control` 自动断点或内容块级显式断点);GPT-5.6 缓存至少保留 30 分钟,Claude 默认 5 分钟、可选 1 小时;两者的缓存读取都按 0.1 倍输入价计费。Claude 的用法见 [Claude 提示词缓存](/cn/api/Claude-Cache)。
### 缓存会影响输出内容吗?
没有影响。官方口径:提示缓存只影响输入侧的处理与计费,模型生成输出的方式与不使用缓存时完全相同。
## 官方参考
本页机制、计价比例与参数口径均来自以下 OpenAI 官方来源:
* [GPT-5.6 发布公告](https://openai.com/index/gpt-5-6/):缓存写入 1.25x / 读取 90% 折扣的计费规则
* [提示缓存指南](https://developers.openai.com/api/docs/guides/prompt-caching):机制、参数、usage 字段与限制
* [OpenAI Pricing](https://developers.openai.com/api/docs/pricing):各模型官方标价
* [GPT-5.6 模型文档](https://platform.openai.com/docs/models/gpt-5.6-sol):上下文窗口、长上下文计费阈值
AIHubMix 各模型实际价格以[模型广场](https://aihubmix.com/models)为准。
***
更新时间:2026-07-10
# GPT Image
Source: https://docs.aihubmix.com/cn/api/GPT-Image-1
使用 gpt-image-2 生成或编辑图片。
## gpt-image-2 接口说明
`gpt-image-2` 支持文生图和图片编辑。同一模型同时提供 AIHubMix 统一生成端点与
OpenAI 兼容端点:
| 场景 | 方法 | 路径 | Content-Type |
| ----------- | ---- | --------------------------- | --------------------- |
| 统一协议生成 | POST | `/ai/v1/images/generations` | `application/json` |
| OpenAI 兼容生成 | POST | `/v1/images/generations` | `application/json` |
| OpenAI 兼容编辑 | POST | `/v1/images/edits` | `multipart/form-data` |
新接入统一协议时,参阅 [AIHubMix 图片生成接口](/cn/api/aihubmix-image-generation)。
本页示例使用 OpenAI 兼容端点,适合已有 OpenAI SDK 集成。
本页的生成、编辑、图片解码和非法参数流程已使用 `gpt-image-2` 实际验证。
模型能力可能调整,接入前请查询 [模型 Schema 接口](/cn/api/async-tasks#model-schema),
按 `path` 选择端点并读取该项的 `request.schema`,不要依赖 `endpoints` 数组位置。
## 准备工作
安装或升级 OpenAI Python SDK,并通过环境变量提供 API Key:
```bash theme={null}
pip install -U openai
export AIHUBMIX_API_KEY="你的 API Key"
```
客户端配置:
```python theme={null}
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AIHUBMIX_API_KEY"],
base_url="https://aihubmix.com/v1",
)
```
## 生成图片
下面的示例生成一张低质量、`1024x1024` 的 PNG 图片,并将返回的 Base64 数据保存到
当前目录。
```python theme={null}
import base64
import os
from pathlib import Path
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AIHUBMIX_API_KEY"],
base_url="https://aihubmix.com/v1",
)
result = client.images.generate(
model="gpt-image-2",
prompt="A simple green triangle centered on a plain white background",
n=1,
size="1024x1024",
quality="low",
output_format="png",
)
image_bytes = base64.b64decode(result.data[0].b64_json)
Path("gpt-image-2.png").write_bytes(image_bytes)
print(result.usage)
```
等价的 HTTP 请求为:
```bash theme={null}
curl https://aihubmix.com/v1/images/generations \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2",
"prompt": "A simple green triangle centered on a plain white background",
"n": 1,
"size": "1024x1024",
"quality": "low",
"output_format": "png"
}'
```
## 编辑图片
编辑接口接收 `multipart/form-data`。将待编辑图片放在当前目录并命名为 `input.png`:
```python theme={null}
import base64
import os
from pathlib import Path
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AIHUBMIX_API_KEY"],
base_url="https://aihubmix.com/v1",
)
with Path("input.png").open("rb") as source_image:
result = client.images.edit(
model="gpt-image-2",
image=source_image,
prompt="Change the red circle to a blue square, keeping the white background",
n=1,
size="1024x1024",
quality="low",
output_format="png",
)
image_bytes = base64.b64decode(result.data[0].b64_json)
Path("gpt-image-2-edited.png").write_bytes(image_bytes)
print(result.usage)
```
等价的 HTTP 请求为:
```bash theme={null}
curl https://aihubmix.com/v1/images/edits \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-F "model=gpt-image-2" \
-F "image=@input.png;type=image/png" \
-F "prompt=Change the red circle to a blue square, keeping the white background" \
-F "n=1" \
-F "size=1024x1024" \
-F "quality=low" \
-F "output_format=png"
```
## 已确认参数
| 字段 | 生成 | 编辑 | 说明 |
| --------------- | -- | -- | ----------------------- |
| `model` | 必填 | 必填 | 使用 `gpt-image-2` |
| `prompt` | 必填 | 必填 | 非空图片描述或编辑指令 |
| `image` | - | 必填 | 待编辑图片 |
| `mask` | - | 可选 | 指定编辑区域的蒙版 |
| `n` | 可选 | 可选 | `1` 至 `10`,默认 `1` |
| `size` | 可选 | 可选 | `{width}x{height}` 格式 |
| `quality` | 可选 | 可选 | `low`、`medium` 或 `high` |
| `output_format` | 可选 | 可选 | `png` 或 `jpeg` |
不要将其他 GPT Image 版本的参数直接套用到 `gpt-image-2`。字段、枚举和取值范围
以模型对应端点的 `request.schema` 为准。
## 返回示例
兼容生成与编辑接口均返回 OpenAI 图片响应。`data[].b64_json` 是图片的 Base64 内容,
`usage` 给出本次请求的输入和输出 Token 用量。
```json theme={null}
{
"created": 1787719630,
"background": "opaque",
"data": [
{
"b64_json": ""
}
],
"output_format": "png",
"quality": "low",
"size": "1024x1024",
"usage": {
"input_tokens": 16,
"input_tokens_details": {
"image_tokens": 0,
"text_tokens": 16
},
"output_tokens": 196,
"output_tokens_details": {
"image_tokens": 196,
"text_tokens": 0
},
"total_tokens": 212
}
}
```
## 错误响应
参数不符合模型支持范围时,接口返回结构化 `4xx` 错误。例如传入不支持的
`quality: "ultra"` 会返回 HTTP `400`:
```json theme={null}
{
"error": {
"message": "Invalid value: 'ultra'. Supported values are: 'low', 'medium', 'high', and 'auto'.",
"type": "invalid_request_error",
"param": "quality",
"code": "invalid_value"
}
}
```
收到错误后应先检查 `error.param` 和 `error.code`,再对照当前模型对应路径的
`request.schema` 修正请求。
# Gemini 指南
Source: https://docs.aihubmix.com/cn/api/Gemini-Guides
Gemini 漫游指南:关于本站的 Gemini 调用细节,在此汇总。
## Gemini 调用方式
对于 Gemini 系列,我们提供原生调用和 Openai 兼容这 2 种调用方式。\
使用前运行 `pip install google-genai` 或 `pip install -U google-genai`,安装(更新)原生依赖。
1️⃣ 对于原生调用,我们的 Gemini 调用支持 AI Studio 和 VertexAI 自动路由。转发方法主要是在内部传入 AIHubMix 密钥和请求链接。需要注意的是,这个链接和常规的 `base_url` 写法不同,请参考示例:
```py theme={null}
client = genai.Client(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"},
)
```
2️⃣ 对于 Openai 兼容格式,则维持通用的 `v1` 端点:
```py theme={null}
client = OpenAI(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com/v1",
)
```
3️⃣ 对于 2.5 系列,如果你需要显示推理过程,可以使用以下 2 种方式:
1. 原生调用:传入 `include_thoughts=True`
2. OpenAI 兼容方式:传入 `reasoning_effort`
相关的详细调用可以参考下文的代码示例。
## **Gemini 3 Pro** Image Preview 说明
Gemini 3 Pro Image Preview(Nano Banana Pro 预览版)专为专业素材资源制作和复杂指令而设计。该模型具有以下特点:
* 使用Google 搜索实时获取世界知识
* 默认“思考”过程(在生成之前优化构图)
* 能够生成分辨率高达 **4K** 的图像
- 流式模式只返回推理过程,生成的图片不会在流式输出中出现。
- 如需获取图片数据,请使用非流式请求。
**Python 调用参考如下:**
```python 文生图 theme={null}
import os
from google import genai
from google.genai import types
API_KEY = ""
client = genai.Client(
api_key=API_KEY,
http_options={"base_url": "https://aihubmix.com/gemini"},
)
prompt = (
"Da Vinci style anatomical sketch of a dissected Monarch butterfly. "
"Detailed drawings of the head, wings, and legs on textured parchment with notes in English."
)
# 可选参数
aspect_ratio = "1:1" # 支持: "1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"
resolution = "4K" # 默认1K,支持: "1K", "2K", "4K",注意:必须是大写“K”
response = client.models.generate_content(
model="gemini-3-pro-image-preview",
contents=prompt,
config=types.GenerateContentConfig(
response_modalities=['TEXT', 'IMAGE'],
image_config=types.ImageConfig(
aspect_ratio=aspect_ratio,
image_size=resolution,
),
),
)
# 保存图片 & 输出文本
for part in response.parts:
if part.text:
print(part.text)
elif image := part.as_image():
image.save("butterfly.png")
print("Image saved: butterfly.png")
```
```python 图生图 theme={null}
from google import genai
from PIL import Image
API_KEY = ""
client = genai.Client(
api_key=API_KEY,
http_options={"base_url": "https://aihubmix.com/gemini"}
)
prompt = (
"Create a picture of my cat eating a nano-banana "
"in a fancy restaurant under the Gemini constellation."
)
image = Image.open("cat_image.jpg")
response = client.models.generate_content(
model="gemini-2.5-flash-image",
contents=[prompt, image],
)
# 保存图片 & 输出文本
for part in response.parts:
if part.text is not None:
print(part.text)
elif part.inline_data is not None:
image = part.as_image()
image.save("generated_image.png")
```
```python 多图参考 theme={null}
from google import genai
from google.genai import types
from PIL import Image
API_KEY = ""
prompt = "An office group photo of these people, they are making funny faces."
aspect_ratio = "5:4"
resolution = "2K"
client = genai.Client(
api_key=API_KEY,
http_options={"base_url": "https://aihubmix.com/gemini"}
)
response = client.models.generate_content(
model="gemini-3-pro-image-preview",
contents=[
prompt,
Image.open('person1.png'),
Image.open('person2.png'),
Image.open('person3.png'),
Image.open('person4.png'),
Image.open('person5.png'),
],
config=types.GenerateContentConfig(
response_modalities=['TEXT', 'IMAGE'],
image_config=types.ImageConfig(
aspect_ratio=aspect_ratio,
image_size=resolution,
),
)
)
# 保存图片 & 输出文本
for part in response.parts:
if part.text is not None:
print(part.text)
elif image := part.as_image():
image.save("office.png")
```
```python Google Search theme={null}
from google import genai
from google.genai import types
API_KEY = ""
prompt = (
"Visualize the current weather forecast for the next 5 days in Shanghai "
"as a clean, modern weather chart. Add a visual on what I should wear each day."
) # 将上海近五日天气以天气图表形式呈现出来
aspect_ratio = "16:9"
client = genai.Client(
api_key=API_KEY,
http_options={"base_url": "https://aihubmix.com/gemini"}
)
response = client.models.generate_content(
model="gemini-3-pro-image-preview",
contents=prompt,
config=types.GenerateContentConfig(
response_modalities=['TEXT', 'IMAGE'],
image_config=types.ImageConfig(
aspect_ratio=aspect_ratio,
),
tools=[{"google_search": {}}]
)
)
# 保存图片 & 输出文本
for part in response.parts:
if part.text is not None:
print(part.text)
elif image := part.as_image():
image.save("weather.png")
```
## Gemini 2.5 系列的「推理」说明
1. 2.5 系列都是推理模型。
2. 2.5 flash 是混合模型,类似 claude sonnet 3.7,可以通过用 `thinking_budget` 控制推理预算来达到最佳效果。
3. 2.5 pro 是纯粹的推理模型,因此不能关闭 thinking、也不显式传递推理预算。
4. 温度值支持范围 0 \<= `temprature` \<= 2
**Python 调用参考如下:**
```py 普通非流式 theme={null}
from google import genai
from google.genai import types
def generate():
client = genai.Client(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"},
)
model = "gemini-2.0-flash"
contents = [
types.Content(
role="user",
parts=[
types.Part.from_text(text="""For the average stock investor, if analyzing financial reports works, why is luck still needed?"""),
],
),
]
print(client.models.generate_content(
model=model,
contents=contents,
))
if __name__ == "__main__":
generate()
```
```py 2.0 系列-流式 theme={null}
from google import genai
from google.genai import types
def generate():
client = genai.Client(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"},
)
model = "gemini-2.0-flash"
contents = [
types.Content(
role="user",
parts=[
types.Part.from_text(text="""For the average stock investor, if analyzing financial reports works, why is luck still needed?"""),
],
),
]
generate_content_config = types.GenerateContentConfig(
response_mime_type="text/plain",
)
for chunk in client.models.generate_content_stream(
model=model,
contents=contents,
config=generate_content_config,
):
print(chunk.text, end="")
if __name__ == "__main__":
generate()
```
```py 2.5 Flash-流式 theme={null}
from google import genai
from google.genai import types
def generate():
client = genai.Client(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"},
)
model = "gemini-2.5-flash-preview-04-17" #gemini-2.5-pro-preview-03-25、gemini-2.5-flash-preview-04-17
contents = [
types.Content(
role="user",
parts=[
types.Part.from_text(text="""For the average stock investor, if analyzing financial reports works, why is luck still needed?"""),
],
),
]
generate_content_config = types.GenerateContentConfig(
thinking_config = types.ThinkingConfig(
thinking_budget=2048, #范围 0-16384。默认 1024,最佳边际效果 16000
),
response_mime_type="text/plain",
)
for chunk in client.models.generate_content_stream(
model=model,
contents=contents,
config=generate_content_config,
):
print(chunk.text, end="")
if __name__ == "__main__":
generate()
```
```py 2.5 Pro-流式 theme={null}
from google import genai
from google.genai import types
def generate():
client = genai.Client(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"},
)
model = "gemini-2.5-pro-preview-03-25"
contents = [
types.Content(
role="user",
parts=[
types.Part.from_text(text="""How do I know I'm not just wasting my time?"""),
],
),
]
generate_content_config = types.GenerateContentConfig(
response_mime_type="text/plain",
)
for chunk in client.models.generate_content_stream(
model=model,
contents=contents,
config=generate_content_config,
):
print(chunk.text, end="")
if __name__ == "__main__":
generate()
```
```py 显示推理内容 theme={null}
from google import genai
from google.genai import types
def generate():
client = genai.Client(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"},
)
model = "gemini-2.5-pro-preview-05-06"
contents = [
types.Content(
role="user",
parts=[
types.Part.from_text(text="""How is the Rule of 72 in finance derived?"""),
],
),
]
generate_content_config = types.GenerateContentConfig(
response_mime_type="text/plain",
thinking_config=types.ThinkingConfig(
include_thoughts=True # 🧠 启用思考过程输出
),
)
# 用于存储最后一个 chunk 的 usage_metadata
final_usage_metadata = None
for chunk in client.models.generate_content_stream(
model=model,
contents=contents,
config=generate_content_config,
):
# 检查是否有内容部分
if chunk.candidates and len(chunk.candidates) > 0:
for part in chunk.candidates[0].content.parts:
if part.text:
if part.thought:
# 思考过程内容
print(part.text, end="")
else:
# 最终答案内容
print(part.text, end="")
# 保存最新的 usage_metadata,只有最后一个 chunk 会包含完整信息
if chunk.usage_metadata:
final_usage_metadata = chunk.usage_metadata
# 在所有 chunk 处理完后,打印完整的 token 使用情况
if final_usage_metadata:
print(f"\n\n📊 Token 使用情况:")
print(f"思考 tokens: {getattr(final_usage_metadata, 'thoughts_token_count', '不可用')}")
print(f"输出 tokens: {getattr(final_usage_metadata, 'candidates_token_count', '不可用')}")
print(f"总计: {final_usage_metadata}")
if __name__ == "__main__":
generate()
```
## Gemini 2.5 Flash 支持
Openai 兼容方式调用参考如下:
```py Python 用于快速任务时,关闭思考 theme={null}
from openai import OpenAI
client = OpenAI(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com/v1",
)
completion = client.chat.completions.create(
model="gemini-2.5-flash-preview-04-17-nothink",
messages=[
{
"role": "user",
"content": "Explain the Occam's Razor concept and provide everyday examples of it"
}
]
)
print(completion.choices[0].message.content)
```
```py Python 控制预算 theme={null}
from openai import OpenAI
client = OpenAI(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com/v1",
)
completion = client.chat.completions.create(
model="gemini-2.5-flash-preview-04-17",
reasoning_effort="low", # 可选 "low", "medium" 和 "high", 分别对应 1024, 8192 和 16384 推理预算
messages=[
{
"role": "user",
"content": "Explain the Occam's Razor concept and provide everyday examples of it"
}
]
)
print(completion.choices[0].message.content)
```
```shell Curl-基础调用 theme={null}
curl -X POST https://aihubmix.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d '{
"model": "gemini-2.5-flash-preview-04-17-nothink",
"messages": [
{
"role": "user",
"content": "Explain the Occam'\''s Razor concept and provide an everyday example of it."
}
]
}'
```
```shell Curl-Thinking 显示 theme={null}
curl https://aihubmix.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d '{
"model": "gemini-2.5-pro-preview-05-06",
"messages": [
{
"role": "user",
"content": "Explain the Occam'\''s Razor concept and provide an everyday example of it."
}
],
"reasoning_effort": "low"
}'
```
1. 用于复杂任务时,只需要将模型 id 设置为默认开启思考的 `gemini-2.5-flash-preview-04-17` 即可。
2. Gemini 2.5 Flash 通过 `budget`(思考预算)来控制思考的深度,范围 0-16K,目前转发采用的是默认预算 1024,最佳边际效果为 16K。
## 多媒体文件
* 对于 **20MB** 以下的多媒体文件(图片、音频、视频),用 `inline_data` 上传。
* 当多媒体文件大于 20M 时,需要用 Files API。
### 20M 以下文件
你可以增加 `EDIARESOLUTION_MEDIUM` 参数来约束图片的精度,从而大幅节省输入的费用以及减少大图报错的可能性。
**支持的媒体分辨率参数值:**
| 参数名 | 备注 |
| ------------------------------ | ------------------------------------------------ |
| MEDIA\_RESOLUTION\_UNSPECIFIED | 媒体分辨率未指定 |
| MEDIA\_RESOLUTION\_LOW | 媒体分辨率设为 low (64 tokens). |
| MEDIA\_RESOLUTION\_MEDIUM | 媒体分辨率设为 medium (256 tokens). |
| MEDIA\_RESOLUTION\_HIGH | 媒体分辨率设为 high (zoomed reframing with 256 tokens). |
**调用参考:**
```py 图片 theme={null}
from google import genai
from google.genai import types
# 读取文件为二进制数据
file_path = "yourpath/file.jpeg"
with open(file_path, "rb") as f:
file_bytes = f.read()
client = genai.Client(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"}
)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=types.Content(
parts=[
types.Part(
inline_data=types.Blob(
data=file_bytes,
mime_type="image/jpeg"
)
),
types.Part(
text="Describe the image."
)
]
),
config=types.GenerateContentConfig(
system_instruction="You are a helpful assistant that can describe images.",
max_output_tokens=768,
temperature=0.1,
thinking_config=types.ThinkingConfig(
thinking_budget=0, include_thoughts=False
),
media_resolution=types.MediaResolution.MEDIA_RESOLUTION_MEDIUM # 256 tokens
)
)
print(response.text)
print(response.usage_metadata) # 输出 token 花费细节
```
```py 音频 theme={null}
from google import genai
from google.genai import types
# 读取文件为二进制数据
file_path = "yourpath/file.m4a"
with open(file_path, "rb") as f:
file_bytes = f.read()
client = genai.Client(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"}
)
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=types.Content(
parts=[
types.Part(
inline_data=types.Blob(
data=file_bytes,
mime_type="audio/m4a"
)
),
types.Part(
text="Transcribe the audio to text."
)
]
)
)
print(response.text)
```
```py 视频 theme={null}
from google import genai
from google.genai import types
# 读取文件为二进制数据
file_path = "yourpath/file.mp4"
with open(file_path, "rb") as f:
file_bytes = f.read()
client = genai.Client(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"}
)
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=types.Content(
parts=[
types.Part(
inline_data=types.Blob(
data=file_bytes,
mime_type="video/mp4"
)
),
types.Part(
text="Summarize this video. Then create a quiz with an answer key based on the information in this video."
)
]
)
)
print(response.text)
```
```py Youtube 链接 theme={null}
from google import genai
from google.genai import types
client = genai.Client(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"}
)
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=types.Content(
parts=[
types.Part(
file_data=types.FileData(
file_uri="https://www.youtube.com/watch?v=OoU7PwNyYUw"
)
),
types.Part(
text="Please summarize the video in 3 sentences."
)
]
)
)
print(response.text)
```
### Files API
Gemini 可以同时处理各种类型的输入数据,包括文本、图片和音频。当总请求大小(包括文件、文本提示、系统指令等)超过 **20 MB** 时,请务必使用 Files API。
* 不支持列出已上传的文件
* 文件会在 48 小时后自动删除,也可以手动删除已上传的文件
**调用参考**
```python 上传文件 theme={null}
from google import genai
client = genai.Client(
api_key="sk-****",
http_options={"base_url": "https://aihubmix.com/gemini"},
)
myfile = client.files.upload(file="path/to/sample.mp3")
response = client.models.generate_content(
model="gemini-2.5-flash", contents=["Describe this audio clip", myfile]
)
print(response.text)
```
```python 获取文件的元数据 theme={null}
from google import genai
client = genai.Client(
api_key="sk-****",
http_options={"base_url": "https://aihubmix.com/gemini"},
)
myfile = client.files.upload(file='path/to/sample.mp3')
file_name = myfile.name
myfile = client.files.get(name=file_name)
print(myfile)
```
```python 删除已上传的文件 theme={null}
from google import genai
client = genai.Client()
myfile = client.files.upload(file='path/to/sample.mp3')
client.files.delete(name=myfile.name)
```
## Code Execution
自动代码解析器用例参考:
```py Python theme={null}
from google import genai
from google.genai import types
# 读取文件为二进制数据
file_path = "yourpath/file.csv"
with open(file_path, "rb") as f:
file_bytes = f.read()
client = genai.Client(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"}
)
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=types.Content(
parts=[
types.Part(
inline_data=types.Blob(
data=file_bytes,
mime_type="text/csv"
)
),
types.Part(
text="Please analyze this CSV and summarize the key statistics. Use code execution if needed."
)
]
),
config=types.GenerateContentConfig(
tools=[types.Tool(
code_execution=types.ToolCodeExecution
)]
)
)
for part in response.candidates[0].content.parts:
if part.text is not None:
print(part.text)
if getattr(part, "executable_code", None) is not None:
print("Generated code:\n", part.executable_code.code)
if getattr(part, "code_execution_result", None) is not None:
print("Execution result:\n", part.code_execution_result.output)
```
## Interactions API
Interactions 是 Gemini 新一代推理接口,返回结构化的 `Interaction` 对象,支持文本生成、原生图像生成(Nano Banana)及多步推理。**同步模式**(`interactions.create()`)与**异步模式**(Background Interactions:`create(background: true)` + `get` / `cancel` / `delete`)均已支持。
SDK 版本要求:`@google/genai` **>= 2.0.0**(JS/TS)或 `google-genai` **>= 2.0.0**(Python)。低版本 SDK 调用 Interactions 会被 Google 后端拒绝(`legacy Interactions schema no longer supported`)。
### 文本生成
调用 `interactions.create()` 发起推理,返回的 `Interaction` 对象提供 `output_text` 便捷属性。
```js JavaScript theme={null}
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
apiKey: "sk-***", // 替换为你在 AIHubMix 生成的 API Key
httpOptions: { baseUrl: "https://aihubmix.com/gemini" },
});
const interaction = await ai.interactions.create({
model: "gemini-3.5-flash",
input: "Explain quantum computing in one sentence",
});
console.log(interaction.output_text);
console.log(interaction.usage);
// { total_tokens, total_input_tokens, total_output_tokens, ... }
```
```py Python theme={null}
from google import genai
client = genai.Client(
api_key="sk-***", # 替换为你在 AIHubMix 生成的 API Key
http_options={"base_url": "https://aihubmix.com/gemini"},
)
interaction = client.interactions.create(
model="gemini-3.5-flash",
input="Explain quantum computing in one sentence",
)
print(interaction.output_text)
```
### 原生图像生成
通过 `response_format` 配置输出模态为图像,返回的 `Interaction` 对象提供 `output_image` 便捷属性。
* 推荐模型 `gemini-3.1-flash-image`(Nano Banana 2,通用生图模型)。
* `response_modalities` 值必须为**小写** `['text', 'image']`;大写为 `generateContent` API 的写法,在 Interactions API 中会返回 `400`。
* 勿传 `delivery: 'inline'`(`400 Image delivery mode is not supported`),结果默认即以 inline 方式返回。
```js JavaScript theme={null}
import { GoogleGenAI } from "@google/genai";
import fs from "node:fs";
const ai = new GoogleGenAI({
apiKey: "sk-***", // 替换为你在 AIHubMix 生成的 API Key
httpOptions: { baseUrl: "https://aihubmix.com/gemini" },
});
const interaction = await ai.interactions.create({
model: "gemini-3.1-flash-image",
input: "A translucent banana-shaped glass lamp on a white desk, soft studio lighting.",
response_modalities: ["text", "image"],
response_format: { type: "image", aspect_ratio: "1:1", image_size: "1K" },
});
// output_image 便捷属性(取最后一张生成图像)
if (interaction.output_image?.data) {
fs.writeFileSync("output.png", Buffer.from(interaction.output_image.data, "base64"));
}
```
```py Python theme={null}
import base64
from google import genai
client = genai.Client(
api_key="sk-***", # 替换为你在 AIHubMix 生成的 API Key
http_options={"base_url": "https://aihubmix.com/gemini"},
)
interaction = client.interactions.create(
model="gemini-3.1-flash-image",
input="A translucent banana-shaped glass lamp on a white desk, soft studio lighting.",
response_format={
"type": "image",
"aspect_ratio": "1:1",
"image_size": "1K",
},
)
if interaction.output_image:
with open("output.png", "wb") as f:
f.write(base64.b64decode(interaction.output_image.data))
```
### 流式输出
传入 `stream: true` 启用 SSE 流式传输。增量文本通过 `event.delta.text` 获取。
```js JavaScript theme={null}
const stream = await ai.interactions.create({
model: "gemini-3.5-flash",
input: "Write a haiku about the moon",
stream: true,
});
for await (const event of stream) {
if (event.event_type === "step.delta" && event.delta?.type === "text") {
process.stdout.write(event.delta.text);
}
if (event.event_type === "interaction.completed") {
console.log("\nUsage:", JSON.stringify(event.interaction?.usage));
}
}
```
### 异步模式(Background Interactions)
传入 `background: true` 发起后台推理。请求立即返回 `Interaction` 对象,`status` 为 `in_progress`,`id` 为该任务的句柄,模型在后台继续推理。用 `interactions.get(id)` 轮询获取结果,建议间隔 3 到 5 秒。适用于耗时较长的推理,无需保持长连接。
任务结果尚未就绪时,`get()` 会返回 `400` 或 `403`。这表示结果还没生成完,应继续轮询,不要当作失败终止。只有返回 `200` 时 `status` 才是终态(`completed` / `failed` / `cancelled`)。
```js JavaScript theme={null}
const task = await ai.interactions.create({
model: "gemini-3.5-flash",
input: "Explain the water cycle in three sentences.",
background: true,
});
console.log(task.id, task.status); // iact1_xxx in_progress
let result;
for (let i = 0; i < 60; i++) {
await new Promise((r) => setTimeout(r, 3000));
try {
const current = await ai.interactions.get(task.id);
if (["completed", "failed", "cancelled"].includes(current.status)) {
result = current;
break;
}
} catch (err) {
continue; // 结果未就绪,继续轮询
}
}
console.log(result.output_text);
await ai.interactions.delete(task.id); // 已取回终态结果,可安全删除
```
* `id` 以 `iact1_` 开头,请原样保存,后续 `get` / `cancel` / `delete` 都用它,不要截断或改写。
* 任务运行中时,模型推理厂商不受理 `cancel` 请求,返回 `403`;`delete` 在任务到达终态前返回 `409`,需先用 `get()` 取回终态结果再删除。
* `background` 与 `stream` 不能同时使用;图像模型(如 `gemini-3.1-flash-image`)不支持异步模式。
> 完整的 SDK 接入指南(含 Embeddings、显式缓存 CRUD、能力矩阵等)请参考 [Gemini 原生 SDK 接入](/cn/api/Gemini-SDK)。
## 上下文缓存
Gemini 在原生 API 下默认启用了**隐式上下文缓存**,无需开发者手动操作。每一次 `generate_content` 请求,系统会自动为输入内容建立缓存。当后续请求与此前内容完全一致时,将直接命中缓存,返回上一次的推理结果,大幅提升响应速度并有机会节省 token 消耗。
* **缓存自动生效,无需手动配置。**
* 缓存仅在内容、模型、参数完全一致时生效;任何字段不同都会视为新请求,不命中缓存。
* 缓存有效期(TTL)由开发者设定,也可以不设置。如果未指定,默认为 1 小时。无最小或最大时长限制,费用取决于缓存 token 数与缓存时间。
* 虽然 Google 官方对 TTL 不设上下限,但由于我们作为转发平台,**仅支持有限的 TTL 配置范围,不保证永久有效**。
### 注意事项
* **无成本节省保证**:缓存 token 的计费为输入原价的 25%,理论上输入部分可最多节省 75% 成本,[**但 Google 官方并未承诺必然节省**](https://ai.google.dev/gemini-api/docs/caching?lang=python),实际账单还需结合缓存命中率、token 类型与存储时长共同评估。
* **缓存命中条件**:建议将重复的上下文放在请求前部,将易变内容(如用户输入)置于后部,以提高缓存命中率。
* **缓存命中反馈**:如果响应结果命中缓存,在 `response.usage_metadata` 中会包含 `cache_tokens_details` 字段,并有 `cached_content_token_count`,开发者可以据此判断本次请求是否命中缓存。\
示例响应字段(命中缓存时):
```
cache_tokens_details=[ModalityTokenCount(modality=, token_count=2003)]
cached_content_token_count=2003
```
**代码示例:**
```python theme={null}
from google import genai
client = genai.Client(
http_options={"base_url": "https://aihubmix.com/gemini"},
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
)
prompt = """
Call me Ishmael. Some years ago—never mind how long precisely—having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off—then, I account it high time to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship. There is nothing surprising in this. If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me. There now is your insular city of the Manhattoes, belted round by wharves as Indian isles by coral reefs—commerce surrounds it with her surf. Right and left, the streets take you waterward.
"""
def generate_content_sync():
response = client.models.generate_content(
model="gemini-2.5-flash-preview-05-20",
contents=prompt + "How many sentences are in this passage? ",
)
print(response.usage_metadata) # 命中缓存时会显示 cache_tokens_details 和 cached_content_token_count 字段
return response
generate_content_sync()
```
> 命中缓存时,`response.usage_metadata` 会包含如下结构:
>
> ```
> cache_tokens_details=[ModalityTokenCount(modality=, token_count=2003)]
> cached_content_token_count=2003
> ```
**核心结论**:隐式缓存支持自动命中与命中反馈。开发者可以通过 usage\_metadata 判断命中情况。成本节省非保证,实际效果因请求结构和使用场景而异。
## Function calling
使用 openai 兼容方式调用 Gemini 的 function calling 功能时,需要在请求体内部传入`tool_choice="auto"`,否则会报错。
```py Python theme={null}
from openai import OpenAI
# Define the function declaration for the model
schedule_meeting_function = {
"name": "schedule_meeting",
"description": "Schedules a meeting with specified attendees at a given time and date.",
"parameters": {
"type": "object",
"properties": {
"attendees": {
"type": "array",
"items": {"type": "string"},
"description": "List of people attending the meeting.",
},
"date": {
"type": "string",
"description": "Date of the meeting (e.g., '2024-07-29')",
},
"time": {
"type": "string",
"description": "Time of the meeting (e.g., '15:00')",
},
"topic": {
"type": "string",
"description": "The subject or topic of the meeting.",
},
},
"required": ["attendees", "date", "time", "topic"],
},
}
# Configure the client
client = OpenAI(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com/v1",
)
# Send request with function declarations using OpenAI compatible format
response = client.chat.completions.create(
model="gemini-2.0-flash",
messages=[
{"role": "user", "content": "Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about the Q3 planning."}
],
tools=[{"type": "function", "function": schedule_meeting_function}],
tool_choice="auto" ## 📍 此处追加了 Aihubmix 兼容,更稳定的请求方式
)
# Check for a function call
if response.choices[0].message.tool_calls:
tool_call = response.choices[0].message.tool_calls[0]
function_call = tool_call.function
print(f"Function to call: {function_call.name}")
print(f"Arguments: {function_call.arguments}")
print(response.usage)
# In a real app, you would call your function here:
# result = schedule_meeting(**json.loads(function_call.arguments))
else:
print("No function call found in the response.")
print(response.choices[0].message.content)
```
**输出结果示例:**
```bash theme={null}
Function to call: schedule_meeting
Arguments: {"attendees":["Bob","Alice"],"date":"2025-03-14","time":"10:00","topic":"Q3 planning"}
CompletionUsage(completion_tokens=28, prompt_tokens=111, total_tokens=139, completion_tokens_details=None, prompt_tokens_details=None)
```
## Tokens 用量追踪
1. Gemini 原生采用 `usage_metadata` 来[追踪使用的 token](https://ai.google.dev/gemini-api/docs/tokens?lang=python),其中的字段对应如下:
* prompt\_token\_count: 输入 token 数
* candidates\_token\_count: 输出 token 数
* thoughts\_token\_count: 推理使用的 token 数,性质上也是输出 token
* total\_token\_count: 总 token 使用量(输入+输出)
2. 对于 OpenAI 兼容格式,则采用 `.usage` 来追踪,字段对应如下:
* usage.completion\_tokens: 输入 token 数
* usage.prompt\_tokens: 输出 token 数(包含推理使用的 token 数)
* usage.total\_tokens:总 token 使用量
**使用方法如下:**
```py Gemini 原生 theme={null}
from google import genai
from google.genai import types
import time
def generate():
client = genai.Client(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"},
)
model = "gemini-2.5-pro-preview-03-25"
contents = [
types.Content(
role="user",
parts=[
types.Part.from_text(text="""How is the Rule of 72 in finance derived?"""),
],
),
]
generate_content_config = types.GenerateContentConfig(
response_mime_type="text/plain",
)
final_usage_metadata = None
for chunk in client.models.generate_content_stream(
model=model,
contents=contents,
config=generate_content_config,
):
print(chunk.text, end="")
if chunk.usage_metadata:
final_usage_metadata = chunk.usage_metadata
# 在所有 chunk 处理完后,打印完整的 token 使用情况
if final_usage_metadata:
print(f"\nUsage: {final_usage_metadata}")
if __name__ == "__main__":
generate()
```
```py OpenAI 兼容 theme={null}
from openai import OpenAI
client = OpenAI(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com/v1",
)
completion = client.chat.completions.create(
model="gemini-2.5-flash-preview-04-17",
reasoning_effort="low", #"low", "medium", and "high", which behind the scenes we map to 1K, 8K, and 24K thinking token budgets. If you want to disable thinking, you can set the reasoning effort to "none".
messages=[
{
"role": "user",
"content": "How is the Rule of 72 in finance derived?"
}
],
stream=True
)
#print(completion.choices[0].message.content)
for chunk in completion:
print(chunk.choices[0].delta)
# 只在最后一个 chunk(包含完整 usage 数据)时打印 usage 信息
if chunk.usage and chunk.usage.completion_tokens > 0:
print(f"输出 tokens: {chunk.usage.completion_tokens}")
print(f"输入 tokens: {chunk.usage.prompt_tokens}")
print(f"总 tokens: {chunk.usage.total_tokens}")
```
***
更新时间:2026-08-14
# Gemini 原生 SDK 接入
Source: https://docs.aihubmix.com/cn/api/Gemini-SDK
通过 @google/genai SDK 接入 AIHubMix,调用 Interactions、Embeddings、Context Caching 等 Gemini API 全部原生能力
## 概述
Google 提供 `@google/genai`(JavaScript / TypeScript)和 `google-genai`(Python)两套官方 SDK,覆盖 Gemini API 的全部端点。将 `baseUrl` 指向 AIHubMix 网关并替换为平台 API Key,即可通过原生 SDK 调用 Interactions、Embeddings、Context Caching 等 OpenAI 兼容层未覆盖的能力,无需改动任何业务代码。
## 快速开始
### 安装
```bash JavaScript / TypeScript theme={null}
npm install @google/genai
# 要求 >= 2.0.0;推荐安装 latest
```
```bash Python theme={null}
pip install -U google-genai
# 要求 >= 2.0.0
```
Interactions API 要求 `@google/genai` **>= 2.0.0** 或 `google-genai` **>= 2.0.0**。低版本 SDK 的请求会被 Google 后端拒绝(`legacy Interactions schema no longer supported`)。
### 初始化客户端
```js JavaScript theme={null}
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
apiKey: "sk-***", // 替换为你在 AIHubMix 生成的 API Key
httpOptions: {
baseUrl: "https://aihubmix.com/gemini",
},
});
```
```python Python theme={null}
from google import genai
client = genai.Client(
api_key="sk-***", # 替换为你在 AIHubMix 生成的 API Key
http_options={"base_url": "https://aihubmix.com/gemini"},
)
```
`baseUrl` 固定为 `https://aihubmix.com/gemini`,与 OpenAI 兼容端点 `https://aihubmix.com/v1` 不同。
***
## Interactions API
Interactions 是 Gemini 新一代推理接口,返回结构化的 `Interaction` 对象,支持文本生成、原生图像生成(Nano Banana)及多步推理。**同步模式**(`interactions.create()`)与**异步模式**(Background Interactions:`create(background: true)` + `get` / `cancel` / `delete`)均已支持。
### 文本生成
调用 `interactions.create()` 发起推理,返回的 `Interaction` 对象提供 `output_text` 便捷属性,直接获取模型最后一段文本输出。
```js JavaScript theme={null}
const interaction = await ai.interactions.create({
model: "gemini-3.5-flash",
input: "Explain quantum computing in one sentence",
});
console.log(interaction.output_text);
console.log(interaction.usage);
// { total_tokens, total_input_tokens, total_output_tokens, ... }
```
```python Python theme={null}
interaction = client.interactions.create(
model="gemini-3.5-flash",
input="Explain quantum computing in one sentence",
)
print(interaction.output_text)
```
### 原生图像生成
通过 `response_format` 配置输出模态为图像。返回的 `Interaction` 对象提供 `output_image` 便捷属性,其 `data` 字段为 Base64 编码的图像数据。
* 推荐模型 `gemini-3.1-flash-image`(Nano Banana 2,通用生图模型)。
* `response_modalities` 值必须为**小写** `['text', 'image']`;大写为 `generateContent` API 的写法,在 Interactions API 中会返回 `400`。
* 勿传 `delivery: 'inline'`(`400 Image delivery mode is not supported`),Interactions API 默认即以 inline 方式返回图像数据。
**`response_format` 参数:**
| 字段 | 说明 | 可选值 |
| -------------- | ----- | ----------------------------------------- |
| `type` | 输出类型 | `"image"` |
| `aspect_ratio` | 宽高比 | `"1:1"` `"3:4"` `"4:3"` `"9:16"` `"16:9"` |
| `image_size` | 输出分辨率 | `"1K"` `"2K"` `"4K"` |
| `mime_type` | 图像格式 | `"image/png"` `"image/jpeg"` |
```js JavaScript theme={null}
import fs from "node:fs";
const interaction = await ai.interactions.create({
model: "gemini-3.1-flash-image",
input: "A translucent banana-shaped glass lamp on a white desk, soft studio lighting.",
response_modalities: ["text", "image"],
response_format: { type: "image", aspect_ratio: "1:1", image_size: "1K" },
});
// 方式 1:output_image 便捷属性(取最后一张生成图像)
if (interaction.output_image?.data) {
fs.writeFileSync("output.png", Buffer.from(interaction.output_image.data, "base64"));
}
// 方式 2:遍历 steps,适用于多步骤混合输出
for (const step of interaction.steps ?? []) {
for (const block of step.content ?? []) {
if (block.type === "image" && block.data) {
fs.writeFileSync("output.png", Buffer.from(block.data, "base64"));
}
}
}
```
```python Python theme={null}
import base64
interaction = client.interactions.create(
model="gemini-3.1-flash-image",
input="A translucent banana-shaped glass lamp on a white desk, soft studio lighting.",
response_format={
"type": "image",
"aspect_ratio": "1:1",
"image_size": "1K",
},
)
# output_image 便捷属性
if interaction.output_image:
with open("output.png", "wb") as f:
f.write(base64.b64decode(interaction.output_image.data))
```
### 流式输出
传入 `stream: true` 启用 Server-Sent Events(SSE)流式传输。事件按以下顺序到达:
```
interaction.created → status_update → step.start → step.delta → step.stop → interaction.completed
```
增量文本通过 `event.delta.text` 获取,事件类型字段为 `event_type`。
```js JavaScript theme={null}
const stream = await ai.interactions.create({
model: "gemini-3.5-flash",
input: "Write a haiku about the moon",
stream: true,
});
for await (const event of stream) {
if (event.event_type === "step.delta" && event.delta?.type === "text") {
process.stdout.write(event.delta.text);
}
if (event.event_type === "interaction.completed") {
console.log("\nUsage:", JSON.stringify(event.interaction?.usage));
}
}
```
### 异步模式(Background Interactions)
传入 `background: true` 发起后台推理。请求立即返回 `Interaction` 对象,`status` 为 `in_progress`,`id` 为该任务的句柄,模型在后台继续推理。用 `interactions.get(id)` 轮询获取结果,建议间隔 3 到 5 秒。适用于耗时较长的推理,无需保持长连接。
任务结果尚未就绪时,`get()` 会返回 `400` 或 `403`。这表示结果还没生成完,应继续轮询,不要当作失败终止。只有返回 `200` 时 `status` 才是终态(`completed` / `failed` / `cancelled`)。
```js JavaScript theme={null}
const task = await ai.interactions.create({
model: "gemini-3.5-flash",
input: "Explain the water cycle in three sentences.",
background: true,
});
console.log(task.id, task.status); // iact1_xxx in_progress
let result;
for (let i = 0; i < 60; i++) {
await new Promise((r) => setTimeout(r, 3000));
try {
const current = await ai.interactions.get(task.id);
if (["completed", "failed", "cancelled"].includes(current.status)) {
result = current;
break;
}
} catch (err) {
continue; // 结果未就绪,继续轮询
}
}
console.log(result.output_text);
console.log(result.usage);
```
```python Python theme={null}
import time
from google.genai import errors
task = client.interactions.create(
model="gemini-3.5-flash",
input="Explain the water cycle in three sentences.",
background=True,
)
print(task.id, task.status) # iact1_xxx in_progress
result = None
for _ in range(60):
time.sleep(3)
try:
current = client.interactions.get(task.id)
except errors.APIError:
continue # 结果未就绪,继续轮询
if current.status in ("completed", "failed", "cancelled"):
result = current
break
print(result.output_text)
print(result.usage)
```
`id` 以 `iact1_` 开头,请原样保存,后续 `get` / `cancel` / `delete` 都用它,不要截断或改写。
#### 取消与删除
| 方法 | 行为 |
| ------------------------- | ------------------------------------------------------------------- |
| `interactions.cancel(id)` | 任务运行中时,模型推理厂商不受理取消请求,返回 `403`;任务到达终态后调用返回 `status: cancelled` |
| `interactions.delete(id)` | 删除任务记录。任务到达终态前调用返回 `409`,需先用 `get()` 取回终态结果再删除。删除后 `get()` 返回 `404` |
```js JavaScript theme={null}
await ai.interactions.delete(task.id); // 已取回终态结果,可安全删除
```
* `background` 与 `stream` 不能同时使用。两者同传时 `stream` 不生效,返回普通 JSON 响应,SDK 会因取不到流对象而报错。
* 图像模型(如 `gemini-3.1-flash-image`)不支持异步模式,传入 `background: true` 返回 `400 Model 'xxx' does not support background interactions`。图像生成请用同步模式。
***
## Embeddings
通过 `embedContent` 端点获取文本或多模态内容的向量表示(embedding)。
如需 OpenAI 兼容的 `/v1/embeddings` 端点,请参阅 [向量嵌入](/cn/api/EBD)。
### embedContent
```js JavaScript theme={null}
const response = await ai.models.embedContent({
model: "gemini-embedding-2-preview",
contents: "What is the meaning of life?",
config: {
outputDimensionality: 768, // 可选:指定输出维度(128–3072),默认 3072
},
});
console.log("dimensions:", response.embeddings[0].values.length); // 768
```
```python Python theme={null}
from google.genai import types
result = client.models.embed_content(
model="gemini-embedding-2-preview",
contents="What is the meaning of life?",
config=types.EmbedContentConfig(
output_dimensionality=768, # 可选:指定输出维度(128–3072),默认 3072
),
)
print(f"dimensions: {len(result.embeddings[0].values)}") # 768
```
### 批量获取 Embeddings
向 `embedContent` 的 `contents` 参数传入 `Content` 数组,即可一次调用获取多条文本的 embedding:
```js JavaScript theme={null}
const response = await ai.models.embedContent({
model: "gemini-embedding-2-preview",
contents: [
{ parts: [{ text: "First paragraph of text" }] },
{ parts: [{ text: "Second paragraph of text" }] },
],
});
console.log("count:", response.embeddings.length); // 2
for (const emb of response.embeddings) {
console.log("dimensions:", emb.values.length);
}
```
### 可用模型与参数
| 模型 | 输入 Token 上限 | 默认输出维度 | 输入模态 | 说明 |
| ---------------------------- | ----------- | ------------- | --------------- | ----------------------------------- |
| `gemini-embedding-2-preview` | 8,192 | 3,072(推荐 768) | 文本、图像、视频、音频、PDF | 最新多模态嵌入模型,支持 `outputDimensionality` |
| `gemini-embedding-001` | 2,048 | 3,072 | 仅文本 | 上一代文本嵌入模型,支持 `taskType` |
`gemini-embedding-001` 支持通过 `config.taskType` 指定嵌入用途,优化特定下游任务的向量质量:
| `taskType` | 用途 |
| --------------------- | ---------- |
| `SEMANTIC_SIMILARITY` | 语义相似度计算 |
| `RETRIEVAL_DOCUMENT` | 文档索引(被检索侧) |
| `RETRIEVAL_QUERY` | 搜索查询(检索侧) |
| `CLASSIFICATION` | 文本分类 |
| `CLUSTERING` | 文本聚类 |
`gemini-embedding-2-preview` 不支持 `taskType` 参数,改为在 prompt 中通过前缀指定任务类型(如 `search_query: ...` 或 `search_document: ...`)。
***
## Context Caching(显式缓存)
显式缓存(Explicit Caching)允许开发者手动创建、查询、引用和删除 `CachedContent` 对象,适用于需要在多次请求间复用同一段长上下文的场景。与[隐式缓存](/cn/api/Gemini-Guides#上下文缓存)不同,显式缓存由应用侧主动管理生命周期。
显式缓存仅适用于 `generateContent` API。Interactions API 仅支持隐式缓存。
未配置存储定价的模型会被网关拦截缓存创建请求(`context caching is not available for model`),以防止存储费用漏收。主流模型(gemini-2.5-flash、gemini-2.5-pro 等)均已配置。
### 创建 CachedContent
通过 `caches.create()` 创建缓存。`ttl`(Time-To-Live)控制缓存有效期,到期后自动清除。
```js JavaScript theme={null}
const longDocument = "需要反复引用的长文本内容...".repeat(500);
const cache = await ai.caches.create({
model: "gemini-3.5-flash",
config: {
contents: longDocument,
ttl: "300s",
},
});
console.log("CachedContent name:", cache.name);
// 格式:cachedContents/xxx
```
```python Python theme={null}
long_document = "需要反复引用的长文本内容..." * 500
cache = client.caches.create(
model="gemini-3.5-flash",
config={
"contents": long_document,
"ttl": "300s",
},
)
print(f"CachedContent name: {cache.name}")
```
### 在 generateContent 中引用缓存
将 `cache.name` 传入 `cachedContent`(JS)或 `cached_content`(Python)参数,即可在推理时命中缓存。命中的 token 数会体现在 `usageMetadata.cachedContentTokenCount` 中。
```js JavaScript theme={null}
const response = await ai.models.generateContent({
model: "gemini-3.5-flash",
contents: "Please summarize the core points of the above document",
config: { cachedContent: cache.name },
});
console.log(response.text);
console.log("cached tokens:", response.usageMetadata?.cachedContentTokenCount);
```
```python Python theme={null}
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="Please summarize the core points of the above document",
config={"cached_content": cache.name},
)
print(response.text)
print(f"cached tokens: {response.usage_metadata.cached_content_token_count}")
```
### 查询与删除
```js JavaScript theme={null}
// 查询 CachedContent 元数据
const info = await ai.caches.get({ name: cache.name });
console.log("model:", info.model, "expireTime:", info.expireTime);
// 删除缓存
await ai.caches.delete({ name: cache.name });
```
```python Python theme={null}
# 查询 CachedContent 元数据
info = client.caches.get(name=cache.name)
print(f"model: {info.model} expire_time: {info.expire_time}")
# 删除缓存
client.caches.delete(name=cache.name)
```
***
## 已支持能力矩阵
| 能力 | 状态 | 说明 |
| ---------------------------------------- | -- | -------------------------------------------------- |
| `generateContent` | ✅ | 非流式 + 流式 |
| `systemInstruction` / `generationConfig` | ✅ | temperature、maxOutputTokens 等 |
| Structured Output(`responseSchema`) | ✅ | JSON mode |
| Function Calling | ✅ | `functionDeclarations` 工具声明 |
| `thinkingConfig` | ✅ | 思维链输出 |
| 多模态输入 | ✅ | 图像 / 音频 / 视频 / PDF via `inlineData` + Files API |
| Google Search Grounding | ✅ | 搜索增强 |
| `countTokens` | ✅ | Token 计数 |
| Imagen(`generateImages`) | ✅ | Imagen 3 图像生成 |
| Veo(`generateVideos`) | ✅ | 视频生成 |
| TTS | ✅ | 语音合成输出 |
| Files API | ✅ | 大文件上传与引用 |
| Interactions API | ✅ | 新一代推理接口(文本 + Nano Banana 生图) |
| Background Interactions | ✅ | 异步模式:`background` 创建 + `get` / `cancel` / `delete` |
| Embeddings(`embedContent`) | ✅ | 原生向量嵌入 |
| Context Caching CRUD | ✅ | 显式缓存管理 |
| Live API(WebSocket) | ❌ | 暂未支持 |
***
## 常见问题
SDK 版本过低。`@google/genai` 须 >= 2.0.0,`google-genai` 须 >= 2.0.0。执行 `npm install @google/genai@latest` 或 `pip install -U google-genai` 升级至最新版本。
部分早期模型名称(如 `gemini-2.5-flash-image-preview`)在 Interactions API 上已下线。请使用当前可用的模型标识符,如 `gemini-3.1-flash-image`(Nano Banana 2)。`generateContent` API 不受影响。
Interactions API 的 `response_modalities` 值必须为小写(`"text"`、`"image"`)。大写 `"TEXT"` / `"IMAGE"` 是 `generateContent` API 的写法,在 Interactions API 中不被接受。
任务结果尚未就绪。异步任务在生成完成前,`interactions.get()` 会返回 `400` 或 `403`,继续按 3 到 5 秒间隔轮询即可,不要当作失败终止。返回 `200` 时读取 `status` 判断终态。
任务还没到达终态。先用 `interactions.get()` 轮询取回终态结果,再调用 `interactions.delete()`。
不可用。SDK 的 `vertexai: true` 模式要求 GCP OAuth + project / location 参数,与 `apiKey` 互斥(SDK 抛出 `Project/location and API key are mutually exclusive`)。通过 AIHubMix 接入时使用 Gemini Developer API 形态即可,后端自动路由。
网关对未配置存储定价的模型会拦截 `caches.create()` 请求,以防止存储费用漏收。主流模型(gemini-2.5-flash、gemini-2.5-pro 等)均已配置;如遇此错误,请确认该模型是否支持显式缓存。
***
更新时间:2026-08-14
# Ideogram AI 绘图支持
Source: https://docs.aihubmix.com/cn/api/IdeogramAI
## Ideogram V3 接口
Ideogram V3 模型提供了高级的图像生成和处理能力。V3 接口与之前版本在参数和使用方式上有所不同,本节将详细介绍 V3 的各个接口及使用示例。
### V3 Generate
`POST` [https://aihubmix.com/ideogram/v1/ideogram-v3/generate](https://aihubmix.com/ideogram/v1/ideogram-v3/generate)
根据给定提示词生成图像。V3 模型提供了更高质量的图像生成能力,支持更丰富的风格和参数控制。
用于生成图像的提示词
渲染速度选项,可选 `TURBO`, `DEFAULT`, `QUALITY`
单次出图数量,范围 1-8\
增加图片几乎不会增加生图耗时
用于图像生成的宽高比,支持超多规格\
可选 \['1x3', '3x1', '1x2', '2x1', '9x16', '16x9', '10x16', '16x10', '2x3', '3x2', '3x4', '4x3', '4x5', '5x4', '1x1']\
和 V3 以下不同的模型使用的 `ASPECT_10_16` 类型的规范不同。
提示词增强选项。可用参数:`AUTO`, `ON`, `OFF`
生成图像的风格类型,可选 `AUTO`, `GENERAL`, `REALISTIC`, `DESIGN`\
注意相对 V2 版本,类型更聚焦
描述不想在图像中出现的内容
随机种子,范围:0-2147483647\
单次生成多张图时不要使用 seed,否则会生成相同图像
风格参考图片,可用于风格引导
### 调用示例
```shell Curl 文生图 theme={null}
curl -X POST https://aihubmix.com/ideogram/v1/ideogram-v3/generate \
-H "Api-Key: sk-***" \
-H "Content-Type: multipart/form-data" \
-F prompt="Delicate 3D cover design with various combat machines flying from an portal. The machines have different shapes, sizes, and colors. The portal is emitting swirling energy. The background contains a futuristic city with tall buildings. The text \"One Gateway, Infinite Models\" is placed in the center with neon lights, expansive view, cinematic lighting, vivid color, bright tone. clean text, cyber punk, smooth render" \
-F rendering_speed="QUALITY" \
-F num_images="2" \
-F aspect_ratio="2x1"
```
```py Python 文生图 theme={null}
import requests
import os
# 准备请求数据 - 使用字典而不是JSON
data = {
"prompt": "Delicate 3D cover design with various combat machines flying from an portal. The machines have different shapes, sizes, and colors. The portal is emitting swirling energy. The background contains a futuristic city with tall buildings. The text \"One Gateway, Infinite Models\" is placed in the center with neon lights, expansive view, cinematic lighting, vivid color, bright tone. clean text, cyber punk, smooth render",
"rendering_speed": "QUALITY",
"num_images": "2",
"aspect_ratio": "2x1",
"magic_prompt": "AUTO",
"style_type": "AUTO",
"negative_prompt": "blurry, watermark"
}
# Content-Type 为 multipart/form-data
files = {}
for key, value in data.items():
files[key] = (None, str(value)) # 将每个数据字段作为表单字段发送
response = requests.post(
"https://aihubmix.com/ideogram/v1/ideogram-v3/generate",
headers={
"Api-Key": "sk-***" # 换成你在 AiHubMix 生成的密钥
},
files=files
)
print(response.json())
# save output image to file
response_json = response.json()
if response.ok and 'data' in response_json and len(response_json['data']) > 0:
image_data = response_json['data'][0]['url'] # 正确获取图片 URL
image_response = requests.get(image_data)
if image_response.ok:
with open('output.png', 'wb') as f:
f.write(image_response.content)
print("图片已保存到 output.png")
else:
print(f"获取图片失败:{image_response.status_code}")
else:
print("API 请求失败或返回数据中没有图片")
```
```py Python 参考图+文生图 theme={null}
import requests
import os
data = {
"prompt": "Delicate 3D cover design with various combat machines flying from an portal. The machines have different shapes, sizes, and colors. The portal is emitting swirling energy. The background contains a futuristic city with tall buildings. The text \"One Gateway, Infinite Models\" is placed in the center with neon lights, expansive view, cinematic lighting, vivid color, bright tone. clean text, cyber punk, smooth render",
"rendering_speed": "QUALITY",
"num_images": 2,
# "seed": "998", # 多张图时不要使用 seed
"aspect_ratio": "2x1",
"magic_prompt": "AUTO",
"style_type": "AUTO",
"negative_prompt": "blurry, watermark",
}
# initialize files parameter
files = None
# 样式参考图路径
style_reference_path = "yourpath/reference-image.jpeg"
use_reference_image = True
if use_reference_image and os.path.exists(style_reference_path):
# 如果使用参考图片且文件存在,则设置 files 参数
files = [
("style_reference_images", open(style_reference_path, "rb")),
# 如果需要添加多个样式参考图片,可以按如下方式添加:
# ("style_reference_images", open("第二张参考图片路径", "rb")),
]
elif use_reference_image:
print(f"警告:样式参考图片未找到:{style_reference_path}")
response = requests.post(
"https://aihubmix.com/ideogram/v1/ideogram-v3/generate",
headers={
"Api-Key": "sk-***" # 换成你在 AiHubMix 生成的密钥
},
data=data,
files=files
)
print(response.json())
# save output image to file
response_json = response.json()
if response.ok and 'data' in response_json and len(response_json['data']) > 0:
image_data = response_json['data'][0]['url'] # 正确获取图片 URL
image_response = requests.get(image_data)
if image_response.ok:
with open('output.png', 'wb') as f:
f.write(image_response.content)
print("图片已保存到 output.png")
else:
print(f"获取图片失败:{image_response.status_code}")
else:
print("API 请求失败或返回数据中没有图片")
```
### V3 Remix
`POST` [https://aihubmix.com/ideogram/v1/ideogram-v3/remix](https://aihubmix.com/ideogram/v1/ideogram-v3/remix)
在参考图的基础上,根据提示词重新生成图像。V3 的 Remix 功能对原始图像的风格和内容有更好的保留能力。
用于重绘图像的提示词
原始图像文件
原图的影响权重,范围 1-100,数值越大,结果越像原图。
渲染速度选项,可选 `TURBO`, `DEFAULT`, `QUALITY`
单次出图数量,范围 1-8
输出图像的宽高比,可选 \['1x3', '3x1', '1x2', '2x1', '9x16', '16x9', '10x16', '16x10', '2x3', '3x2', '3x4', '4x3', '4x5', '5x4', '1x1']
风格参考图片,可用于风格引导
随机种子,范围:0-2147483647
提示词增强选项,可用参数:`AUTO`, `ON`, `OFF`
生成图像的风格类型,可选 `AUTO`, `GENERAL`, `REALISTIC`, `DESIGN`
描述不想在图像中出现的内容
### 调用示例
```py Python 融图 theme={null}
import requests
import os
data = {
"prompt": "bird playing with a cat in the snow, pixel art style",
"image_weight": "60",
"rendering_speed": "QUALITY",
"num_images": 1,
"seed": 1,
"aspect_ratio": "16x9",
"magic_prompt": "AUTO",
"style_type": "AUTO",
"negative_prompt": "blurry, bad anatomy, watermark",
}
# 原图 - 必填
source_image_path = "yourpath/image.jpeg"
if not os.path.exists(source_image_path):
raise FileNotFoundError(f"源图片未找到:{source_image_path}")
# initialize files parameter
files = None
# 样式参考图路径
style_reference_path = "yourpath/reference-image.png"
use_reference_image = True
# 准备文件上传
with open(source_image_path, "rb") as image_file:
if use_reference_image and os.path.exists(style_reference_path):
# 如果使用参考图片且文件存在,则设置 files 参数
files = {
"image": image_file,
"style_reference_images": open(style_reference_path, "rb"),
}
else:
if use_reference_image:
print(f"警告:样式参考图片未找到:{style_reference_path}")
files = {
"image": image_file,
}
response = requests.post(
"https://aihubmix.com/ideogram/v1/ideogram-v3/remix",
headers={
"Api-Key": "sk-***" # 换成你在 AiHubMix 生成的密钥
},
data=data,
files=files
)
print(response.json())
# save output image to file
response_json = response.json()
if response.ok and 'data' in response_json and len(response_json['data']) > 0:
image_data = response_json['data'][0]['url'] # 正确获取图片 URL
image_response = requests.get(image_data)
if image_response.ok:
with open('output.png', 'wb') as f:
f.write(image_response.content)
print("图片已保存到 output.png")
else:
print(f"获取图片失败:{image_response.status_code}")
else:
print("API 请求失败或返回数据中没有图片")
print(f"错误详情:{response_json}")
```
### V3 Edit
`POST` [https://aihubmix.com/ideogram/v1/ideogram-v3/edit](https://aihubmix.com/ideogram/v1/ideogram-v3/edit)
V3 的局部编辑功能允许用户通过提供原始图像和蒙版,精确地编辑图像的特定区域,同时保持其他区域不变。
用于编辑图像的提示词
原始图像文件
遮罩图片,黑色区域表示需要编辑的部分,白色区域表示保持不变
渲染速度选项,可选 `TURBO`, `DEFAULT`, `QUALITY`
单次出图数量,范围 1-8
输出图像的宽高比
随机种子,范围:0-2147483647
提示词增强选项,可用参数:`AUTO`, `ON`, `OFF`
生成图像的风格类型,可选 `AUTO`, `GENERAL`, `REALISTIC`, `DESIGN`
描述不想在图像中出现的内容
### 调用示例
```py Python 局部编辑 theme={null}
import requests
import os
# 原图 - 必填
source_image_path = "yourpath/image.jpeg"
# mask - 必填
mask_image_path = "yourpath/mask.jpg"
if not os.path.exists(source_image_path):
raise FileNotFoundError(f"源图片未找到:{source_image_path}")
with open(source_image_path, "rb") as image_file, open(mask_image_path, "rb") as mask_file:
response = requests.post(
"https://aihubmix.com/ideogram/v1/ideogram-v3/edit",
headers={
"Api-Key": "sk-***" # 换成你在 AiHubMix 生成的密钥
},
data={
"prompt": "remove text",
"rendering_speed": "DEFAULT",
"num_images": 1,
"seed": 1,
"aspect_ratio": "16x9",
"magic_prompt": "AUTO",
"style_type": "AUTO",
"negative_prompt": "blurry, bad anatomy, watermark",
},
files={
"image": image_file,
"mask": mask_file,
}
)
print(response.json())
# save output image to file
response_json = response.json()
if response.ok and 'data' in response_json and len(response_json['data']) > 0:
image_data = response_json['data'][0]['url'] # 正确获取图片 URL
image_response = requests.get(image_data)
if image_response.ok:
with open('output.png', 'wb') as f:
f.write(image_response.content)
print("图片已保存到 output.png")
else:
print(f"获取图片失败:{image_response.status_code}")
else:
print("API 请求失败或返回数据中没有图片")
print(f"错误详情:{response_json}")
```
### V3 Replace Background
`POST` [https://aihubmix.com/ideogram/v1/ideogram-v3/replace-background](https://aihubmix.com/ideogram/v1/ideogram-v3/replace-background)
V3 的背景替换功能可以智能地识别图像的前景和背景,并根据提示词替换背景,同时保持前景对象不变。
用于替换背景的提示词
原始图像文件
渲染速度选项,可选 `TURBO`, `DEFAULT`, `QUALITY`
单次出图数量,范围 1-8
风格参考图片,可用于风格引导
随机种子,范围:0-2147483647
提示词增强选项,可用参数:`AUTO`, `ON`, `OFF`
生成图像的风格类型,可选 `AUTO`, `GENERAL`, `REALISTIC`, `DESIGN`
### 调用示例
```py Python 背景替换 theme={null}
import requests
import os
data = {
"prompt": "bird playing with a cat in the snow, pixel art style",
"rendering_speed": "QUALITY",
"num_images": 1,
"seed": 1,
# no "aspect_ratio"
"magic_prompt": "AUTO",
"style_type": "AUTO",
# no "negative_prompt"
}
# 原图 - 必填
source_image_path = "yourpath/image.png"
if not os.path.exists(source_image_path):
raise FileNotFoundError(f"源图片未找到:{source_image_path}")
# initialize files parameter
files = None
# 样式参考图路径
style_reference_path = "yourpath/reference-image.png"
use_reference_image = True
# 准备文件上传
with open(source_image_path, "rb") as image_file:
if use_reference_image and os.path.exists(style_reference_path):
# 如果使用参考图片且文件存在,则设置 files 参数
files = {
"image": image_file,
"style_reference_images": open(style_reference_path, "rb"),
}
else:
if use_reference_image:
print(f"警告:样式参考图片未找到:{style_reference_path}")
files = {
"image": image_file,
}
response = requests.post(
"https://aihubmix.com/ideogram/v1/ideogram-v3/replace-background",
headers={
"Api-Key": "sk-***" # 换成你在 AiHubMix 生成的密钥
},
data=data,
files=files
)
print(response.json())
# save output image to file
response_json = response.json()
if response.ok and 'data' in response_json and len(response_json['data']) > 0:
image_data = response_json['data'][0]['url'] # 正确获取图片 URL
image_response = requests.get(image_data)
if image_response.ok:
with open('output.png', 'wb') as f:
f.write(image_response.content)
print("图片已保存到 output.png")
else:
print(f"获取图片失败:{image_response.status_code}")
else:
print("API 请求失败或返回数据中没有图片")
print(f"错误详情:{response_json}")
```
更多可选参数可参考 [Ideogram AI 官方指南](https://developer.ideogram.ai/api-reference/api-reference/generate-v3)
### 💰 V3 计价
| Ideogram 模型 | Generate | Remix | Edit | Reframe | Replace BG |
| ----------- | --------- | --------- | --------- | --------- | ---------- |
| 3.0 Turbo | US \$0.03 | US \$0.03 | US \$0.06 | US \$0.06 | US \$0.06 |
| 3.0 Default | US \$0.06 | US \$0.06 | US \$0.06 | US \$0.06 | US \$0.06 |
| 3.0 Quality | US \$0.09 | US \$0.09 | US \$0.09 | US \$0.09 | US \$0.09 |
***
## V2-V1 接口说明
Ideogram AI V2-V1 绘图接口,文字绘制能力强劲,支持生图(generate)、混合(remix)、局部编辑(edit)、放大(upscale)和描述(describe)等。
* **混合:** 在参考图的基础上,根据提示词进行重绘,生成新的图片。
* **编辑:** 在参考图的基础上,根据提示词和蒙版进行局部编辑,生成新的图片。
* **放大:** 将低分辨率的图片放大至高分辨率,会重绘细节(相似度和细节比例可控制)。
* **描述:** 提示词反推,用于描述图片
**支持的风格:**
* AUTO:默认的自动选定
* GENERAL:通用
* REALISTIC:写实
* DESIGN:设计
* RENDER\_3D:3D
* ANIME:动漫
- 注意风格参数 `style_type` 仅适用于 V\_2 及更高版本的模型。
- V3 支持即将上线
1. 支持通过 AiHubMix 官方接口调用或 [Cherry Studio APP](https://cherry-ai.com/) 使用,注意目前需要打开代理才能生图。
2. Cherry Studio 暂时只开放了 Ideogram 绘图(generate)接口。
### Generate
`POST` [https://aihubmix.com/ideogram/generate\\](https://api.aihubmix.com/ideogram/generate\\) 根据给定提示词和可选参数同步生成图像。图像链接的有效期有限;如果你想保留图像,必须下载保存。
**Request Parameters**
生成图像的请求对象
用于生图的提示词
用于图像生成的宽高比,决定了图像的分辨率。不能与分辨率参数同时使用。
可用比例:
* ASPECT\_1\_1
* ASPECT\_3\_1
* ASPECT\_1\_3
* ASPECT\_3\_2
* ASPECT\_2\_3
* ASPECT\_4\_3
* ASPECT\_3\_4
* ASPECT\_16\_9
* ASPECT\_9\_16
* SPECT\_16\_10
* ASPECT\_10\_16
用于生成或编辑图像的模型。/generate 和 /remix 支持所有模型类型,但 /edit 仅支持 V\_2 和 V\_2\_TURBO。
可用模型版本:
* V\_1
* V\_1\_TURBO
* V\_2
* V\_2\_TURBO
* V\_2A
* V\_2A\_TURBO
提示词增强选项。可用参数:AUTO, ON, OFF
随机种子,范围:0-2147483647
生成图像时使用的风格类型;此参数仅适用于 V\_2 及更高版本的模型,不应在 V\_1 版本中指定。
可用风格:
* AUTO
* GENERAL
* REALISTIC
* DESIGN
* RENDER\_3D
* ANIME
描述不想在图像中出现的内容。仅适用于模型版本 V\_1、V\_1\_TURBO、V\_2 和 V\_2\_TURBO。提示词中的描述优先级高于负面提示词中的描述。
单次出图数量,范围 1-8
用于图像生成的分辨率(仅适用于模型版本 2.0,不能与 aspect\_ratio 同时使用),以宽 x 高表示。如果未指定,则默认使用 aspect\_ratio。
### 调用示例
```py Python theme={null}
import requests
import os
url = "https://aihubmix.com/ideogram/generate"
payload = { "image_request": {
"prompt": "3D cartoon, An adorable white owl baby with tilted head, shiny amber eyes with highlight, fluffy body, standing on a trunk with moss and lots of glowing mushrooms, Close up, cinematic lighting, low angle, deep sense of depth. The background is a magical spring landscape, cute and esthetic, huge title design \"Always curious\"", #string 可选
"negative_prompt": "blurry, bad anatomy, watermark",
"aspect_ratio": "ASPECT_3_2", # 可选 include ASPECT_1_1(Default), ASPECT_3_2, ASPECT_2_3, ASPECT_4_3, ASPECT_3_4, ASPECT_16_9, ASPECT_9_16, SPECT_16_10, ASPECT_10_16
"model": "V_2",
"num_images": 2, #integer 可选 >=1 <=8 Defaults to 1
"magic_prompt_option": "AUTO", # string 可选 AUTO, ON, OFF
#"seed": "2" #integer 可选 >=0 <=2147483647
"style_type": "RENDER_3D" # string 可选 AUTO/GENERAL/REALISTIC/DESIGN/RENDER_3D/ANIME, 仅适用于 V_2 及以上版本
} }
headers = {
"Api-Key": os.getenv("AIHUBMIX_API_KEY"),
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.json())
```
```js Javascript theme={null}
const url = 'https://aihubmix.com/ideogram/describe';
const form = new FormData();
form.append('image_file', '');
const options = {method: 'POST', headers: {'Api-Key': ''}};
options.body = form;
try {
const response = await fetch(url, options);
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
```
```shell Curl theme={null}
curl -X POST https://aihubmix.com/ideogram/generate \
-H "Api-Key: " \
-H "Content-Type: application/json" \
-d '{
"image_request": {
"prompt": "A serene tropical beach scene. Dominating the foreground are tall palm trees with lush green leaves, standing tall against a backdrop of a sandy beach. The beach leads to the azure waters of the sea, which gently kisses the shoreline. In the distance, there is an island or landmass with a silhouette of what appears to be a lighthouse or tower. The sky above is painted with fluffy white clouds, some of which are tinged with hues of pink and orange, suggesting either a sunrise or sunset.",
"aspect_ratio": "ASPECT_10_16",
"model": "V_2",
"magic_prompt_option": "AUTO"
}
}'
```
### Response
Image(s) generated successfully.
```json theme={null}
{
"created": "2000-01-23T04:56:07Z",
"data": [
{
"prompt": "A serene tropical beach scene. Dominating the foreground are tall palm trees with lush green leaves, standing tall against a backdrop of a sandy beach. The beach leads to the azure waters of the sea, which gently kisses the shoreline. In the distance, there's an island or landmass with a silhouette of what appears to be a lighthouse or tower. The sky above is painted with fluffy white clouds, some of which are tinged with hues of pink and orange, suggesting either a sunrise or sunset.",
"resolution": "1024x1024",
"is_image_safe": true,
"seed": 12345,
"url": "https://ideogram.ai/api/images/direct/8YEpFzHuS-S6xXEGmCsf7g",
"style_type": "REALISTIC"
}
]
}
```
### 错误代码
* `400` : Post Generate Image Request Bad Request Error
* `401` : Post Generate Image Request Unauthorized Error
* `422` : Post Generate Image Request Unprocessable Entity Error
* `429` : Post Generate Image Request Too Many Requests Error
### Edit
`POST` [https://aihubmix.com/ideogram/edit](https://api.aihubmix.com/ideogram/edit)
使用提供的蒙版同步编辑指定图像。蒙版标示出应被编辑的图像部分,而提示词和所选风格类型可进一步引导编辑方向。支持的图像格式包括 JPEG、PNG 和 WebP。图像链接的有效期有限;如果你想保留图像,必须下载保存。
**Request Parameters**
原始图像文件,支持 JPEG、PNG 和 WebP 格式
遮罩图片,必须符合以下要求:
* 仅包含黑色和白色像素,支持 RGB、RGBA 或灰度图像格式
* 与原图尺寸完全一致
* 黑色区域表示需要修改的部分,白色区域表示需要保持不变的部分
* 不能是纯白色
* 建议修改区域(黑色部分)面积至少占据图片的 10% 以上
用于局部编辑的提示词
用于生成或编辑图像的模型。/generate 和 /remix 支持所有模型类型,但 /edit 仅支持 V\_2 和 V\_2\_TURBO。
可用模型版本:
* V\_2
* V\_2\_TURBO
提示词增强选项。可用参数:AUTO, ON, OFF
单次出图数量,范围 1-8
随机种子,范围:0-2147483647
生成图像时使用的风格类型;此参数仅适用于 V\_2 及更高版本的模型。
可用风格:
* AUTO
* GENERAL
* REALISTIC
* DESIGN
* RENDER\_3D
* ANIME
### 调用示例
```py Python theme={null}
import requests
import os
url = "https://aihubmix.com/ideogram/eidt"
files = {
"image_file": open('', 'rb'), # 必须
"mask": "open('', 'rb')" # 必须
}
payload = {
"prompt": "\"prompt\"", # 必须
"model": "V_2", # 必须,only supported for V_2 and V_2_TURBO.
"magic_prompt_option": ,
"num_images":1, # integer 可选 >=1 <=8 Defaults to 1
"seed": , # integer 可选 >=0 <=2147483647
"style_type":
16}
headers = {"Api-Key": os.getenv("AIHUBMIX_API_KEY")}
response = requests.post(url, data=payload, files=files, headers=headers)
print(response.json()
# close file
files["image_file"].close()
files["mask"].close()
```
```js Javascript theme={null}
const url = 'https://aihubmix.com/ideogram/edit';
const form = new FormData();
form.append('image_file', '');
form.append('mask', '');
form.append('prompt', '"prompt"');
form.append('model', '"V_1"');
form.append('magic_prompt_option', '');
form.append('num_images', '');
form.append('seed', '');
form.append('style_type', '');
const options = {method: 'POST', headers: {'Api-Key': ''}};
options.body = form;
try {
const response = await fetch(url, options);
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
```
```shell Curl theme={null}
curl -X POST https://aihubmix.com/ideogram/edit \
-H "Api-Key: " \
-H "Content-Type: multipart/form-data" \
-F image_file=@ \
-F mask=@ \
-F prompt="prompt" \
-F model="V_1"
```
### Response
Image edits generated successfully.
```json theme={null}
{
"created": "2000-01-23T04:56:07Z",
"data": [
{
"prompt": "A serene tropical beach scene. Dominating the foreground are tall palm trees with lush green leaves, standing tall against a backdrop of a sandy beach. The beach leads to the azure waters of the sea, which gently kisses the shoreline. In the distance, there's an island or landmass with a silhouette of what appears to be a lighthouse or tower. The sky above is painted with fluffy white clouds, some of which are tinged with hues of pink and orange, suggesting either a sunrise or sunset.",
"resolution": "1024x1024",
"is_image_safe": true,
"seed": 12345,
"url": "https://ideogram.ai/api/images/direct/8YEpFzHuS-S6xXEGmCsf7g",
"style_type": "REALISTIC"
}
]
}
```
### 错误代码
* `400` : Post Edit Image Request Bad Request Error
* `401` : Post Edit Image Request Unauthorized Error
* `422` : Post Edit Image Request Unprocessable Entity Error
* `429` : Post Edit Image Request Too Many Requests Error
### Remix
`POST` [https://aihubmix.com/ideogram/remix](https://api.aihubmix.com/ideogram/remix)
根据给定提示词和可选参数来融合提供的图像。输入图像会在重混前裁剪至所选宽高比。支持的图像格式包括 JPEG、PNG 和 WebP。图像链接的有效期有限;如果你想保留图像,必须下载保存。
**Request Parameters**
使用提供的图像和提示词生成新图像的请求,提供的图像会被裁剪以匹配所选的输出宽高比。
用于生成图像的提示词
用于图像生成的宽高比,决定了图像的分辨率。不能与分辨率参数同时使用。
可用比例:
* ASPECT\_1\_1
* ASPECT\_3\_1
* ASPECT\_1\_3
* ASPECT\_3\_2
* ASPECT\_2\_3
* ASPECT\_4\_3
* ASPECT\_3\_4
* ASPECT\_16\_9
* ASPECT\_9\_16
* SPECT\_16\_10
* ASPECT\_10\_16
参考图权重,范围:1-100
用于生成或编辑图像的模型。/generate 和 /remix 支持所有模型类型,但 /edit 仅支持 V\_2 和 V\_2\_TURBO。
描述不想在图像中出现的内容。仅适用于模型版本 V\_1、V\_1\_TURBO、V\_2 和 V\_2\_TURBO。提示词中的描述优先级高于负面提示词中的描述。
提示词增强选项。可用参数:AUTO, ON, OFF
单次出图数量,范围:1-8
用于图像生成的分辨率(仅适用于模型版本 2.0,不能与 aspect\_ratio 同时使用),以宽 x 高表示。如果未指定,则默认使用 aspect\_ratio。
随机种子,范围:0-2147483647
生成图像的风格类型;仅适用于 V\_2 及以上版本的模型,不应在 V\_1 版本中指定。
可用风格:
* AUTO
* GENERAL
* REALISTIC
* DESIGN
* RENDER\_3D
* ANIME
原始图像文件,支持 JPEG、PNG 和 WebP 格式
### 调用示例
```py Python theme={null}
import requests
import os
url = "https://aihubmix.com/ideogram/remix"
files = { "image_file": open('', 'rb') }
payload = {"image_request": '''{
"prompt": "watercolor",
"aspect_ratio": "ASPECT_10_16",
"image_weight": 50,
"magic_prompt_option": "ON",
"model": "V_2"
}'''}
headers = {"Api-Key": os.getenv("AIHUBMIX_API_KEY")}
response = requests.post(url, data=payload, files=files, headers=headers)
print(response.json())
```
```js Javascript theme={null}
const url = 'https://aihubmix.com/ideogram/remix';
const form = new FormData();
form.append('image_request', '{
"prompt": "A serene tropical beach scene. Dominating the foreground are tall palm trees with lush green leaves, standing tall against a backdrop of a sandy beach. The beach leads to the azure waters of the sea, which gently kisses the shoreline. In the distance, there is an island or landmass with a silhouette of what appears to be a lighthouse or tower. The sky above is painted with fluffy white clouds, some of which are tinged with hues of pink and orange, suggesting either a sunrise or sunset.",
"aspect_ratio": "ASPECT_10_16",
"image_weight": 50,
"magic_prompt_option": "ON",
"model": "V_2"
}');
form.append('image_file', '');
const options = {method: 'POST', headers: {'Api-Key': ''}};
options.body = form;
try {
const response = await fetch(url, options);
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
```
```shell Curl theme={null}
curl -X POST https://aihubmix.com/ideogram/remix \
-H "Api-Key: " \
-H "Content-Type: multipart/form-data" \
-F image_request='{
"prompt": "A serene tropical beach scene. Dominating the foreground are tall palm trees with lush green leaves, standing tall against a backdrop of a sandy beach. The beach leads to the azure waters of the sea, which gently kisses the shoreline. In the distance, there is an island or landmass with a silhouette of what appears to be a lighthouse or tower. The sky above is painted with fluffy white clouds, some of which are tinged with hues of pink and orange, suggesting either a sunrise or sunset.",
"aspect_ratio": "ASPECT_10_16",
"image_weight": 50,
"magic_prompt_option": "ON",
"model": "V_2"
}' \
-F image_file=@
```
### Response
Image(s) generated successfully.
```json theme={null}
{
"created": "2000-01-23T04:56:07Z",
"data": [
{
"prompt": "A serene tropical beach scene. Dominating the foreground are tall palm trees with lush green leaves, standing tall against a backdrop of a sandy beach. The beach leads to the azure waters of the sea, which gently kisses the shoreline. In the distance, there's an island or landmass with a silhouette of what appears to be a lighthouse or tower. The sky above is painted with fluffy white clouds, some of which are tinged with hues of pink and orange, suggesting either a sunrise or sunset.",
"resolution": "1024x1024",
"is_image_safe": true,
"seed": 12345,
"url": "https://ideogram.ai/api/images/direct/8YEpFzHuS-S6xXEGmCsf7g",
"style_type": "REALISTIC"
}
]
}
```
### 错误代码
* `400` : Post Remix Image Request Bad Request Error
* `401` : Post Remix Image Request Unauthorized Error
* `422` : Post Remix Image Request Unprocessable Entity Error
* `429` : Post Remix Image Request Too Many Requests Error
### Upscale
`POST` [https://aihubmix.com/ideogram/upscale](https://api.aihubmix.com/ideogram/upscale)
使用可选提示词同步放大提供的图像(超分)。支持的图像格式包括 JPEG、PNG 和 WebP。图像链接的有效期有限;如果你想保留图像,必须下载保存。
**Request Parameters**
请求对象,用于使用可选提示词放大提供的图像
可选的提示词,用于引导放大过程
相似度,范围:1-100
细节,范围:1-100
提示词增强选项。可用参数:AUTO, ON, OFF
生成数量,范围:1-8
随机种子,范围:0-2147483647
原始图像文件,支持 JPEG、PNG 和 WebP 格式
### 调用示例
```py Python theme={null}
import requests
import os
url = "https://aihubmix.com/ideogram/upscale"
files = { "image_file": open('', 'rb') }
payload = { "image_request": "{}" }
headers = {"Api-Key": os.getenv("AIHUBMIX_API_KEY")}
response = requests.post(url, data=payload, files=files, headers=headers)
print(response.json())
```
```js Javascript theme={null}
const url = 'https://aihubmix.com/ideogram/upscale';
const form = new FormData();
form.append('image_request', '{}');
form.append('image_file', '');
const options = {method: 'POST', headers: {'Api-Key': ''}};
options.body = form;
try {
const response = await fetch(url, options);
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
```
```shell Curl theme={null}
curl -X POST https://aihubmix.com/ideogram/upscale \
-H "Api-Key: " \
-H "Content-Type: multipart/form-data" \
-F image_request='{}' \
-F image_file=@
```
### Response
Image(s) generated successfully.
```json theme={null}
{
"created": "2000-01-23T04:56:07Z",
"data": [
{
"prompt": "A serene tropical beach scene. Dominating the foreground are tall palm trees with lush green leaves, standing tall against a backdrop of a sandy beach. The beach leads to the azure waters of the sea, which gently kisses the shoreline. In the distance, there's an island or landmass with a silhouette of what appears to be a lighthouse or tower. The sky above is painted with fluffy white clouds, some of which are tinged with hues of pink and orange, suggesting either a sunrise or sunset.",
"resolution": "1024x1024",
"is_image_safe": true,
"seed": 12345,
"url": "https://ideogram.ai/api/images/direct/8YEpFzHuS-S6xXEGmCsf7g",
"style_type": "REALISTIC"
}
]
}
```
### 错误代码
* `400` : Post Upscale Image Request Bad Request Error
* `401` : Post Upscale Image Request Unauthorized Error
* `422` : Post Upscale Image Request Unprocessable Entity Error
* `429` : Post Upscale Image Request Too Many Requests Error
### Describe
`POST` [https://aihubmix.com/ideogram/describe](https://api.aihubmix.com/ideogram/describe)
对上传的图像进行描述分析。支持的图像格式包括 JPEG、PNG 和 WebP。
**Request Parameters**
需要描述的图像文件,支持 JPEG、PNG 和 WebP 格式
### 调用示例
```py Python theme={null}
import requests
import os
url = "https://aihubmix.com/ideogram/describe"
files = { "image_file": open('', 'rb') }
headers = {"Api-Key": os.getenv("AIHUBMIX_API_KEY")}
response = requests.post(url, files=files, headers=headers)
print(response.json())
# close file
files["image_file"].close()
```
```js Javascript theme={null}
const url = 'https://aihubmix.com/ideogram/describe';
const form = new FormData();
form.append('image_file', '');
const options = {method: 'POST', headers: {'Api-Key': ''}};
options.body = form;
try {
const response = await fetch(url, options);
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
```
```shell Curl theme={null}
curl -X POST https://aihubmix.com/ideogram/describe \
-H "Api-Key: " \
-H "Content-Type: multipart/form-data" \
-F image_file=@
```
### Response
Description(s) created successfully.
```json theme={null}
{
"descriptions": [
{
"text": "A meticulously illustrated cat with striped patterns, sitting upright. The cat's eyes are a captivating shade of yellow, and it appears to be gazing intently at something. The background consists of abstract, swirling patterns in shades of black, white, and beige, creating an almost fluid or wavy appearance. The cat is positioned in the foreground, with the background elements fading into the distance, giving a sense of depth to the image."
},
{
"text": "A meticulously illustrated cat with striped patterns, sitting upright. The cat's eyes are a captivating shade of yellow, and it appears to be gazing intently at something. The background consists of abstract, swirling patterns in shades of black, white, and beige, creating an almost fluid or wavy appearance. The cat is positioned in the foreground, with the background elements fading into the distance, giving a sense of depth to the image."
}
]
}
```
### 错误代码
* `400` : Post Describe Request Bad Request Error
* `422` : Post Describe Request Unprocessable Entity Error
* `429` : Post Describe Request Too Many Requests Error
***
### 💰 V2 & V1 计价
#### 图像生成
| 型号 | 功能 | 每张图片费用 |
| --------- | -------------------------- | ---------- |
| 2a | 文字生图,或文字 + 参考图生图 | US \$0.04 |
| 2a Turbo | 文字生图,或文字 + 参考图生图(更快速但质量略低) | US \$0.025 |
| 2.0 | 文字生图,或文字 + 参考图生图 | US \$0.08 |
| 2.0 Turbo | 文字生图,或文字 + 参考图生图(更快速但质量略低) | US \$0.05 |
| 1.0 | 文字生图,或文字 + 参考图生图 | US \$0.06 |
| 1.0 Turbo | 文字生图,或文字 + 参考图生图(更快速但质量略低) | US \$0.02 |
#### 图像编辑
| 型号 | 功能 | 每张图片费用 |
| -------------- | --------------------------------- | --------- |
| 2.0 Edit | 通过文字提示、参考图片和二进制蒙版重新生成图像 | US \$0.08 |
| 2.0 Turbo Edit | 通过文字提示、参考图片和二进制蒙版重新生成图像(更快速但质量略低) | US \$0.05 |
#### 图像增强
| 型号 | 功能 | 每张图片费用 |
| ------- | ------------------------- | --------- |
| Upscale | 将参考图片分辨率提升至 2 倍,并可能增强图片效果 | US \$0.06 |
## 更多详情可见[官方文档](https://developer.ideogram.ai/api-reference/api-reference/generate)
更新时间:2026-06-01
# 图片生成 OpenAI 兼容(遗留)
Source: https://docs.aihubmix.com/cn/api/Image-Gen
为了方便开发者调用不同的图像生成模型,AIHubMix 提供了统一的图片生成接口
新接入建议使用 [图片生成](/cn/api/aihubmix-image-generation),通过
`/ai/v1/images/generations` 调用统一的图片生成、任务查询、Webhook 和错误协议。
本页现有的 OpenAI 兼容、zimage 与厂商适配接口继续可用。
调用前请通过[模型 Schema 接口](/cn/api/async-tasks#model-schema)查询模型支持的端点,
按返回的 `path` 选择协议并读取该项的 `request.schema`,不要依赖 `endpoints` 数组位置。
## 可用模型列表
Nano Banana 系列请参考:[https://docs.aihubmix.com/cn/api/Gemini-Guides](https://docs.aihubmix.com/cn/api/Gemini-Guides)
### OpenAI 模型
* [gpt-image-2](https://aihubmix.com/model/gpt-image-2) —— 已支持通过 OpenAI 兼容接口调用图片编辑,模型 ID 需要写完整为 `gpt-image-2`,不能简写为 `image2`。
* [gpt-image-2-free](https://aihubmix.com/model/gpt-image-2-free)
* [gpt-image-1.5](https://aihubmix.com/model/gpt-image-1.5)
* [gpt-image-1](https://aihubmix.com/model/gpt-image-1) —— 多模态语言模型,它接受文本和图像输入,并生成图像输出。
* [gpt-image-1-mini](https://aihubmix.com/model/gpt-image-1-mini) —— gpt-image-1 的经济型版本。
* [dall-e-3](https://aihubmix.com/model/dall-e-3) —— 能够根据自然语言描述创建逼真的图像和艺术作品,支持根据提示创建指定尺寸的新图像。
* [dall-e-2](https://aihubmix.com/model/dall-e-2)
### Google Gemini 模型
* [gemini-3.1-flash-lite-image](https://aihubmix.com/model/gemini-3.1-flash-lite-image)
* [gemini-3.1-flash-image](https://aihubmix.com/model/gemini-3.1-flash-image)
* [gemini-3-pro-image](https://aihubmix.com/model/gemini-3-pro-image)
* [gemini-3.1-flash-image-preview](https://aihubmix.com/model/gemini-3.1-flash-image-preview)
* [gemini-3.1-flash-image-preview-free](https://aihubmix.com/model/gemini-3.1-flash-image-preview-free)
* [gemini-3-pro-image-preview](https://aihubmix.com/model/gemini-3-pro-image-preview)
* [gemini-2.5-flash-image](https://aihubmix.com/model/gemini-2.5-flash-image)
* [gemini-2.5-flash-image-preview](https://aihubmix.com/model/gemini-2.5-flash-image-preview)
### Imagen 模型
* [imagen-4.0](https://aihubmix.com/model/imagen-4.0)
* [imagen-4.0-ultra](https://aihubmix.com/model/imagen-4.0-ultra)
* [imagen-4.0-ultra-generate-001](https://aihubmix.com/model/imagen-4.0-ultra-generate-001)
* [imagen-4.0-generate-001](https://aihubmix.com/model/imagen-4.0-generate-001)
* [imagen-4.0-fast-generate-001](https://aihubmix.com/model/imagen-4.0-fast-generate-001)
### 阿里云模型
#### Wan(万相)系列
* [wan2.7-image-pro](https://aihubmix.com/model/wan2.7-image-pro) —— 万相 2.7 专业版,支持思考模式与最高 4K 分辨率
* [wan2.7-image](https://aihubmix.com/model/wan2.7-image) —— 万相 2.7 标准版,最高支持 2K 分辨率
* [wan2.6-t2i](https://aihubmix.com/model/wan2.6-t2i) —— 万相 2.6 文生图
#### Qwen-Image(千问图像)系列
* [qwen-image-3.0](https://aihubmix.com/model/qwen-image-3.0)
* [qwen-image-3.0-pro](https://aihubmix.com/model/qwen-image-3.0-pro)
* [qwen-image](https://aihubmix.com/model/qwen-image) —— 图像生成基础模型,在复杂文本渲染和精确图像编辑方面取得了显著进展
* [qwen-image-edit](https://aihubmix.com/model/qwen-image-edit) —— 图像编辑模型,单图编辑和多图融合
* [qwen-image-2.0-pro](https://aihubmix.com/model/qwen-image-2.0-pro) —— 2.0 专业版,文字渲染和语义理解更强,同时支持图片编辑
* [qwen-image-2.0](https://aihubmix.com/model/qwen-image-2.0) —— 2.0 加速版,兼顾质量和速度,同时支持图片编辑
* [qwen-image-max](https://aihubmix.com/model/qwen-image-max) —— Max 版,擅长工业设计和几何推理
### GLM 模型
* [glm-image](https://aihubmix.com/model/glm-image) —— 智谱 AI 发布的图像生成模型,支持高清(hd)和标准(standard)两种质量模式。
### Doubao 模型
* [doubao-seedream-5.0-pro](https://aihubmix.com/model/doubao-seedream-5.0-pro)
* [doubao-seedream-5.0-lite](https://aihubmix.com/model/doubao-seedream-5.0-lite) —— 字节跳动发布的最新图像创作模型,该模型首次搭载联网检索功能,能融合实时网络信息,提升生图时效性。
* [doubao-seedream-4-5](https://aihubmix.com/model/doubao-seedream-4-5) —— 字节跳动推出的图像多模态模型,整合了文生图、图生图、组图输出等能力。
* [doubao-seedream-4-0](https://aihubmix.com/model/doubao-seedream-4-0) —— 字节跳动SOTA级多模态图像创作模型,支持多图融合创作、图像编辑、组图生成等多样玩法。
### Microsoft 模型
* [mai-image-2.5-pro](https://aihubmix.com/model/mai-image-2.5-pro)
* [mai-image-2.5](https://aihubmix.com/model/mai-image-2.5)
* [mai-image-2.5-flash](https://aihubmix.com/model/mai-image-2.5-flash)
### Ideogram 模型
* [V3](https://aihubmix.com/model/V3) —— Ideogram AI 生图模型,能够快速生成图片。
* [V\_2](https://aihubmix.com/model/V_2)
* [V\_2\_TURBO](https://aihubmix.com/model/V_2_TURBO)
* [V\_2A](https://aihubmix.com/model/V_2A)
* [V\_2A\_TURBO](https://aihubmix.com/model/V_2A_TURBO)
* [V\_1](https://aihubmix.com/model/V_1)
* [V\_1\_TURBO](https://aihubmix.com/model/V_1_TURBO)
* [DESCRIBE](https://aihubmix.com/model/DESCRIBE)
* [UPSCALE](https://aihubmix.com/model/UPSCALE)
### Stable Diffusion 模型
* [Stable-Diffusion-3-5-Large](https://aihubmix.com/model/Stable-Diffusion-3-5-Large)
### Baidu 模型
* [ernie-image-turbo](https://aihubmix.com/model/ernie-image-turbo)
* [musesteamer-air-image](https://aihubmix.com/model/musesteamer-air-image)
### Flux 模型
* [flux-2-flex](https://aihubmix.com/model/flux-2-flex)
* [flux-2-pro](https://aihubmix.com/model/flux-2-pro)
* [FLUX-1.1-pro](https://aihubmix.com/model/FLUX-1.1-pro)
### Agnes 模型
* [agnes-image-2.1-flash](https://aihubmix.com/model/agnes-image-2.1-flash)
## API 接口
### zimage 接口
```shellscript theme={null}
POST https://aihubmix.com/v1/models//predictions
```
\ 为\<供应商/模型id>,如\,\。
### openai 兼容接口
**文生图**
```shellscript theme={null}
POST https://aihubmix.com/v1/images/generations
```
**图片编辑**
```shellscript theme={null}
POST https://aihubmix.com/v1/images/edits
```
### 请求头
```shellscript theme={null}
Authorization: Bearer $AIHUBMIX_API_KEY
Content-Type: application/json
```
### 请求参数
#### 通用参数
| 参数 | 类型 | 必填 | 说明 |
| ------- | ------- | -- | --------------------------------------------------------------------------------------------------------------------------------------- |
| prompt | string | 是 | 提示词 |
| size | string | 否 | 图像尺寸,支持`1K`(Doubao-4-5系列不支持)、`2K`、`4K`、`auto` (默认)。Qwen系列支持参数:`512*1024`、`768*512`、 `768*1024`、 `1024*576`、 `576*1024`、 `1024*1024`(默认) |
| image | string | 否 | 参考图片路径 |
| n | integer | 否 | 生成图像数量,支持1-10,默认为 1。Imagen 模型该参数不生效 |
| quality | string | 否 | 渲染质量,支持 `low` 、`medium` 和`high`,质量越高,耗时越长 |
#### OpenAI 模型参数
| 参数 | 类型 | 必填 | 说明 |
| --------------- | ------ | -- | ----------------------------------------------------- |
| input\_fidelity | string | 否 | 保真度,支`high`和 `low`(默认) |
| moderation | string | 否 | 内容审核严格程度,支持 `auto` (默认,标准过滤)和 `low`(过滤限制较少),图生图模式下不支持 |
| output\_format | string | 否 | 输出图片格式,支持 `png` 、 `jpeg` (默认) 、`webp` |
#### Imagen 模型参数
| 参数 | 类型 | 必填 | 说明 |
| ----------- | ------- | -- | ------------ |
| sampleCount | integer | 否 | 生成图像数量,默认为 4 |
#### FLUX-1.1-pro 模型参数
| 参数 | 类型 | 默认值 | 必填 | 说明 |
| ------------------ | ------- | --------- | -- | ------------------------ |
| prompt | string | - | 是 | 图像的文本描述 |
| size | string | 1024x1024 | 否 | 图像尺寸(像素) |
| prompt\_upsampling | boolean | false | 否 | 是否对提示词进行增强优化以获得更好的效果 |
| seed | integer | null | 否 | 随机数种子,用于结果复现,可填任意整数 |
| safety\_tolerance | integer | 2 | 否 | 内容审核级别,范围 0(最严格)到 6(最宽松) |
| output\_format | string | jpeg | 否 | 输出图片格式,支持 `jpeg` 和 `png` |
`prompt_upsampling`、`safety_tolerance`、`seed` 需放在请求体的 `extra_body` 字段内传递。
#### 阿里云模型参数
阿里云模型支持两种调用方式:OpenAI 兼容接口和 zimage 原生接口。
**OpenAI 兼容接口 — 标准参数**
| 参数 | 类型 | 必填 | 默认值 | 说明 |
| ---------------- | ------- | -- | --------- | ----------------------- |
| model | string | 是 | - | 模型名称 |
| prompt | string | 是 | - | 图像描述提示词,最长 800 字符 |
| n | integer | 否 | 1 | 生成图片数量,取值范围因模型而异 |
| size | string | 否 | 1024x1024 | 图片尺寸,格式 `宽x高` |
| response\_format | string | 否 | url | 返回格式:`url` 或 `b64_json` |
**OpenAI 兼容接口 — 扩展参数(与 `model`、`prompt` 同级传递)**
| 参数 | 类型 | 默认值 | 支持模型 | 说明 |
| ---------------- | ------- | ----- | -------------------- | ----------------------------------------------- |
| thinking\_mode | boolean | true | wan2.7 系列 | 思考模式,提升生成质量,增加耗时约 10-30s |
| negative\_prompt | string | - | qwen-image 系列、wan2.6 | 反向提示词,最长 500 字符。wan2.7 系列请在 prompt 中使用「不要出现 XX」 |
| prompt\_extend | boolean | true | qwen-image 系列、wan2.6 | 提示词智能改写,wan2.7 系列不支持 |
| seed | integer | 随机 | 全部 | 随机种子,范围 `0`-`2147483647` |
| watermark | boolean | false | 全部 | 是否添加水印 |
**zimage 原生接口参数(位于 `input` 对象内)**
| 参数 | 类型 | 必填 | 说明 |
| ---------------- | --------- | -- | ------------------------------------ |
| prompt | string | 是 | 图像描述或编辑指令,最长 800 字符 |
| images | string\[] | 否 | 图片 URL 或 base64 数组(1-3 张),有值时为图片编辑模式 |
| n | integer | 否 | 生成图片数量,取值范围因模型而异 |
| size | string | 否 | 输出分辨率,格式为 `宽*高` 或缩写 `1K`/`2K`/`4K` |
| seed | integer | 否 | 随机种子,范围 `0`-`2147483647` |
| negative\_prompt | string | 否 | 反向提示词,最长 500 字符,wan2.7 系列不支持 |
| prompt\_extend | boolean | 否 | 提示词智能改写,默认 `true`,wan2.7 系列不支持 |
| thinking\_mode | boolean | 否 | 思考模式,仅 wan2.7 系列,默认 `true` |
| watermark | boolean | 否 | 是否添加水印,默认 `false` |
| color\_palette | array | 否 | 自定义颜色主题,含 3-10 个颜色对象,仅 wan2.7 系列支持 |
**各模型 `n` 和 `size` 取值范围**
| 模型 | n 范围 | size 范围 | 默认 size |
| ----------------------------------- | ------------ | ----------------------------------------------------------------- | --------- |
| wan2.7-image-pro | 1(组图模式 1-12) | `1K`/`2K`/`4K`;自定义每边 768-4096px,宽高比 1:8\~8:1 | 2K |
| wan2.7-image | 1(组图模式 1-12) | `1K`/`2K`;自定义每边 768-2048px,宽高比 1:8\~8:1 | 2K |
| wan2.6-t2i | 1-4 | 自定义每边 1280-1440px,宽高比 1:4\~4:1 | 1280x1280 |
| qwen-image-2.0-pro / qwen-image-2.0 | 1-6 | 自定义每边 512-2048px,总像素 ≤ 2048×2048 | 2048x2048 |
| qwen-image-max | 1-6 | 5 种固定规格:`1664x928`、`1472x1104`、`1328x1328`、`1104x1472`、`928x1664` | 1664x928 |
| qwen-image-edit | 固定 1 | 不可指定,由模型自动决定 | - |
#### GLM 模型参数
| 参数 | 类型 | 必填 | 说明 |
| ------- | ------ | -- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| quality | string | 否 | 渲染质量,支持 `hd`(默认,细节更丰富,约 20 秒)和 `standard`(生成更快,约 5-10 秒) |
| size | string | 否 | 图像尺寸,默认 `1280x1280`。推荐值:`1280x1280`、`1568x1056`、`1056x1568`、`1472x1088`、`1088x1472`、`1728x960`、`960x1728`。自定义尺寸要求:宽高均在 1024px–2048px 之间,必须能被 32 整除,且总像素不超过 2²² px |
#### Doubao 模型参数
| 参数 | 类型 | 必填 | 说明 | |
| -------------------------------------- | ------- | -- | ----------------------------------------------------------------------------------------- | - |
| sequential\_image\_generation | string | 否 | 控制是否关闭组图功能 | |
| sequential\_image\_generation\_options | object | 否 | 组图功能配置,仅当 `sequential_image_generation` 为 `auto` 时生效。目前支`max_images`,取值范围\[1, 15],默认值为 15 | |
| watermark | boolean | 否 | 是否在生成的图片中添加水印,支持 `true` (默认)和 `false` | |
| seed | integer | 否 | 随机数种子,取值范围为 \[-1, 2147483647],默认值为 -1 | |
| response\_format | string | 否 | 生成图像的返回格式,支`url`(链接在图片生成后24小时内有效,请及时下载图片)`base64_json` | |
实际可生成的图片数量,除受到 `max_images` 影响外,还受到输入的参考图数量影响。输入的参考图数量+最终生成的图片数量 ≤ 15 张。
## 使用示例
### OpenAI
```shellscript 文生图 theme={null}
curl https://aihubmix.com/v1/models/openai/gpt-image-1.5/predictions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d '{
"input": {
"prompt": "A deer drinking in the lake, Sakura petals falling, green and clean water, japanese temple, dappled sunlight, cinematic lighting, expansive view, peace",
"size": "1024x1024",
"n": 1,
"quality": "high",
"moderation": "low",
"background": "auto"
}
}'
```
```shellscript 图生图 theme={null}
curl https://aihubmix.com/v1/images/edits \
-H "Authorization: Bearer YOUR_API_KEY" \
-F "model=gpt-image-1.5" \
-F "prompt=Replace the background with a blue sky and white clouds" \
-F "image=@test.png" \
-F "size=1024x1024"
```
#### gpt-image-2
这是 OpenAI 图片编辑模型,调用时请填写完整模型名 `gpt-image-2`,不能简写为 `image2`。该接口返回 `b64_json` 时,可按下面示例保存为 `edited.png`。
```powershell PowerShell theme={null}
curl.exe -sS -X POST "https://aihubmix.com/v1/images/edits" `
-H "Authorization: Bearer YOUR_API_KEY" `
-F "model=gpt-image-2" `
-F "prompt=Replace the background with a blue sky and white clouds" `
-F "image=@test.png" `
-F "size=1024x1024" `
-D headers.txt `
-o response.json `
-w "HTTP_CODE:%{http_code}`nTOTAL:%{time_total}`n"
$b64 = (Get-Content .\response.json -Raw | ConvertFrom-Json).data[0].b64_json
[IO.File]::WriteAllBytes(".\edited.png", [Convert]::FromBase64String($b64))
```
```typescript TypeScript theme={null}
import { readFile, writeFile } from "node:fs/promises";
const apiKey = process.env.AIHUBMIX_API_KEY;
if (!apiKey) {
throw new Error("Set AIHUBMIX_API_KEY first.");
}
const form = new FormData();
form.append("model", "gpt-image-2");
form.append("prompt", "Replace the background with a blue sky and white clouds");
form.append("image", new Blob([await readFile("test.png")], { type: "image/png" }), "test.png");
form.append("size", "1024x1024");
const response = await fetch("https://aihubmix.com/v1/images/edits", {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
},
body: form,
});
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`);
}
const result = (await response.json()) as {
data: Array<{ b64_json: string }>;
};
await writeFile("edited.png", Buffer.from(result.data[0].b64_json, "base64"));
```
### Google Imagen
```shell Curl theme={null}
curl https://aihubmix.com/v1/models/google/imagen-4.0-fast-generate-001/predictions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d '{
"input": {
"prompt": "A deer drinking in the lake, Sakura petals falling, green and clean water, japanese temple, dappled sunlight, cinematic lighting, expansive view, peace",
"numberOfImages": 1
}
}'
```
### 阿里云模型
* 支持两种调用方式:OpenAI 兼容接口(`/v1/images/generations` 和 `/v1/images/edits`)和 zimage 原生接口(`/v1/models/bailian/:model/predictions`)
* 返回的图片 URL 有效期 24 小时,请及时下载保存
```shellscript OpenAI兼容-文生图 theme={null}
curl https://aihubmix.com/v1/images/generations \
-H "Authorization: Bearer sk-***" \
-H "Content-Type: application/json" \
-d '{
"model": "wan2.7-image-pro",
"prompt": "A serene lakeside cabin at sunset, watercolor style",
"n": 1,
"size": "1024x1024",
"thinking_mode": true,
"seed": 42
}'
```
```shellscript zimage-文生图 theme={null}
curl https://aihubmix.com/v1/models/bailian/wan2.7-image-pro/predictions \
-H "Authorization: Bearer sk-***" \
-H "Content-Type: application/json" \
-d '{
"input": {
"prompt": "A serene lakeside cabin at sunset, watercolor style",
"n": 1,
"size": "2K",
"thinking_mode": true,
"seed": 42
}
}'
```
### GLM
```shellscript glm-image theme={null}
curl https://aihubmix.com/v1/models/openai/glm-image/predictions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d '{
"input": {
"prompt": "A deer drinking in the lake, Sakura petals falling, green and clean water, japanese temple, dappled sunlight, cinematic lighting, expansive view, peace",
"size": "1024x1024",
"quality": "hd"
}
}'
```
### Doubao
```shellscript 文生图 theme={null}
curl https://aihubmix.com/v1/models/doubao/doubao-seedream-4-0/predictions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d '{
"input": {
"prompt": "Interstellar, black hole, a vintage train bursting out of a black hole, vying for visual impact, cinematic blockbuster, apocalyptic feel, dynamic, contrasting colors, oc rendering, ray tracing, motion blur, depth of field, surrealism, deep blue, the scene is shaped by delicate rich color layers creating the subject and scene, realistic texture, the lighting effects of a dark background create an atmosphere, combining artistic fantasy, exaggerated wide-angle perspective, glare, reflection, extreme light and shadow, strong gravity, devouring",
"size": "2K",
"sequential_image_generation": "disabled",
"stream": false,
"response_format": "url",
"watermark": true
}
}'
```
```shellscript 图生图 theme={null}
curl https://aihubmix.com/v1/models/doubao/doubao-seedream-4-5/predictions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d '{
"input": {
"model": "doubao-seedream-4-5",
"prompt": "Keep the model's pose and the flowing shape of the liquid clothing unchanged. Change the clothing material from silver metal to completely transparent clear water (or glass). Through the liquid flow, the model's skin details can be seen. The light and shadow change from reflection to refraction.",
"image": "https://ark-project.tos-cn-beijing.volces.com/doc_image/seedream4_5_imageToimage.png",
"size": "2K",
"watermark": false
}
}'
```
```shellscript 多图融合 theme={null}
curl https://aihubmix.com/v1/models/doubao/doubao-seedream-4-5/predictions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d '{
"input": {
"model": "doubao-seedream-4-5",
"prompt": "Change the clothing in image 1 to the clothing in image 2",
"image": ["https://ark-project.tos-cn-beijing.volces.com/doc_image/seedream4_imagesToimage_1.png", "https://ark-project.tos-cn-beijing.volces.com/doc_image/seedream4_5_imagesToimage_2.png"],
"sequential_image_generation": "disabled",
"size": "2K",
"watermark": false
}
}'
```
```shellscript 多参考图生组图 theme={null}
curl https://aihubmix.com/v1/models/doubao/doubao-seedream-4-5/predictions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d '{
"input": {
"model": "doubao-seedream-4-5",
"prompt": "Generate 3 images of a girl and a cow toy happily riding a roller coaster in an amusement park, covering morning, noon, and evening",
"image": ["https://ark-project.tos-cn-beijing.volces.com/doc_image/seedream4_imagesToimages_1.png", "https://ark-project.tos-cn-beijing.volces.com/doc_image/seedream4_imagesToimages_2.png"],
"sequential_image_generation": "auto",
"sequential_image_generation_options": {
"max_images": 3
},
"size": "2K",
"watermark": false
}
}'
```
### Flux
* `flux-2-flex` 和 `flux-2-pro` 为异步端口,需要分 2 步请求。该系列速度极快,几乎秒出。
* Azure 渠道的`FLUX-1.1-pro` 等 BFL 模型均为同步绘图,而非异步。
#### **FLUX 一步绘图**
```shellscript FLUX-1.1-pro theme={null}
curl https://aihubmix.com/v1/models/bfl/FLUX-1.1-pro/predictions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d '{
"input": {
"prompt": "A serene deer drinking from a crystal-clear lake, sakura petals gently falling, traditional Japanese temple in the background, warm dappled sunlight, cinematic lighting, ultra-wide composition, peaceful atmosphere, highly detailed",
"size": "1024x1024",
"output_format": "jpeg",
"extra_body": {
"prompt_upsampling": true,
"safety_tolerance": 6,
"seed": 1
}
}
}'
```
### Ideogram V3
```shell Curl theme={null}
curl https://aihubmix.com/v1/models/ideogram/V3/predictions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d '{
"input": {
"prompt": "A deer drinking in the lake, Sakura petals falling, green and clean water, japanese temple, dappled sunlight, cinematic lighting, expansive view, peace, in the style of Pixar 3D",
"rendering_speed": "QUALITY",
"aspect_ratio": "2x1"
}
}'
```
## 错误响应与兼容错误码
本节适用于本页的 Legacy `/v1/images/*` 接口。新版 `/ai/v1/images/*` 使用独立的
[图片错误合同](/cn/api/aihubmix-image-generation#error-codes)。两套接口的响应结构和
错误码需要分别处理。
Legacy 图片接口的一般错误响应如下。`param` 是可选字段,`tid` 通常附加在 `message`
末尾,不单独返回:
```json theme={null}
{
"error": {
"message": "prompt is required (tid: req_01K0ABCDEF)",
"type": "Aihubmix_api_error",
"param": "",
"code": "prompt_missing"
}
}
```
请求返回 HTTP `5xx` 时,请提交反馈并附上 `message` 中的 `tid`。
| HTTP | `code` | `message` | 说明 |
| ---- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
| 400 | `protocol_not_supported` | `This model does not support the legacy protocol. Use POST /ai/v1/images/generations. See https://docs.aihubmix.com/cn/api/async-tasks` | 所选模型不支持 Legacy 图片创建协议 |
| 400 | `invalid_image_request` | 动态的脱敏请求解析错误 | JSON 或 multipart 图片请求无法解析 |
| 400 | `prompt_missing` | `prompt is required` | generations 或 edits 请求缺少非空 prompt |
| 400 | `size_not_supported` | `size not supported for this image model` | 所选模型不支持请求中的 `size` |
| 400 | `prompt_too_long` | `prompt is too long` | prompt 超过模型限制 |
| 400 | `n_not_within_range` | `invalid value of n` | `n` 超出模型允许范围 |
| 403 | `insufficient_user_quota` | `Your account balance is insufficient. Please recharge your account to continue using the API.` | 账户余额或 API Key 可用额度不足 |
除上表中的稳定兼容错误码外,Legacy 图片接口还可能返回其他动态 `code` 和经过脱敏的
`message`,来源包括模型推理厂商和兼容链路。这些动态 code 属于开放集合,客户端不要把
表外 code 作为稳定枚举。`message` 中的 `tid` 是请求追踪 ID。
***
更新时间:2026-09-01
# Jina AI 集成
Source: https://docs.aihubmix.com/cn/api/Jina-AI
## 说明
我们集成了 Jina AI 的五个核心接口,助你轻松构建功能强大的智能体。这些接口主要适用于以下场景:
* **向量嵌入 (Embeddings)**:适用于多模态 RAG 问答场景,例如智能客服、智能招聘和知识库问答。
* **重排序 (Rerank)**:通过优化 Embedding 候选结果,依据话题相关性进行重排序,显著提升大型语言模型的回答质量。
* **深度搜索 (DeepSearch)**:进行深度搜索与推理,直至找到最优答案,特别适用于课题研究和产品解决方案制定等复杂任务。
* **网页搜索 (Search)**:输入查询词,返回搜索结果页 (SERP) 的干净正文,直接可喂给 LLM 做联网问答 / RAG。
* **网页读取 (Reader)**:输入任意网址,返回该网页转换后的干净 markdown 正文,适合抓取网页内容喂给 LLM。
我们在 Jina AI 接口的基础上进行了增强,以便支持未来的功能扩展,因此在使用方式上会与官方原生调用略有不同。
## 快速指引
除了更换 `API_KEY` 为 [AIHUBMIX\_API\_KEY](https://aihubmix.com/token) 和模型端点链接,其他参数和用法和 [Jina AI 官方](https://jina.ai/)完全一致。
**端点替换:**
* **向量嵌入 (Embeddings)**:`https://jina.ai/embeddings` -> `https://aihubmix.com/v1/embeddings`
* **重排序 (Rerank)**:`https://api.jina.ai/v1/rerank` -> `https://aihubmix.com/v1/rerank`
* **深度搜索 (DeepSearch)**:`https://deepsearch.jina.ai/v1/chat/completions` -> `https://aihubmix.com/v1/chat/completions`
* **网页搜索 (Search)**:`https://s.jina.ai/?q=` -> `https://aihubmix.com/v1/jina/search?q=`
* **网页读取 (Reader)**:`https://r.jina.ai/` -> `https://aihubmix.com/v1/jina/reader/`
如遇当前 API 主地址不可用,可将此处域名替换为备用地址 `https://api.inferera.com`,路径保持不变。
## 一、向量嵌入 (Embeddings)
Jina AI 的 Embedding 支持普通文本和多模态图文,对于多语言任务的处理表现出众。
### 请求参数
模型名称,可用的嵌入模型列表如下:
* `jina-clip-v2`:多模态、多语言、1024 维、8K 上下文窗口、865M 参数
* `jina-embeddings-v3`:文本模型、多语言、1024 维、8K 上下文窗口、570M 参数
* `jina-colbert-v2`:多语言 ColBERT 模型,8K token 上下文,560M 参数,用于嵌入和重排序
* `jina-embeddings-v2-base-code`:针对代码和文档搜索优化的模型,768 维,8K 上下文窗口,137M 参数
输入文本或图片,根据不同模型支持不同的输入格式。对于文本,直接提供字符串数组;对于多模态模型,可以提供包含 text 或 image 字段的对象数组
返回的数据类型,可选值:
* `float`:默认,返回浮点数数组。最常见且易于使用的格式,返回为浮点数列表
* `binary_int8`:返回为 int8 打包的二进制格式。更高效的存储、搜索和传输方式
* `binary_uint8`:返回为 uint8 打包的二进制格式。更高效的存储、搜索和传输方式
* `base64`:返回 base64 编码的字符串。更高效的传输方式
计算维度,可选值:
* 1024
* 768
### 1. 多模态用法
```shell Curl theme={null}
curl https://aihubmix.com/v1/embeddings \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d @- < response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
```
### 2. 纯文本用法
只需要提供文本字符串数组,不需要提供 `image` 字段。
```shell Curl theme={null}
curl https://aihubmix.com/v1/rerank \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d @- < {
let responseData = '';
res.on('data', chunk => {
responseData += chunk;
});
res.on('end', () => {
console.log(responseData);
});
});
req.write(data);
req.end();
```
## 二、重排序 (Rerank)
重排序器的目标是提高搜索相关性和 RAG 准确性。它通过对初始搜索结果的深度分析,考虑查询与文档内容之间的细微交互,从而重新排列搜索结果,将最相关的结果放在顶部。
### 请求参数
模型名称,可用模型列表如下:
* `jina-reranker-m0`:多模态多语言文档重排序器,10K 上下文,2.4B 参数,用于视觉文档排序
搜索查询文本,用于与候选文档进行比较
要返回的最相关文档数量。默认返回所有文档
候选文档数组,将根据与查询的相关性进行重新排序
文档最大分块长度,仅适用于 Cohere,不适用于 Jina。默认值为 4096。\
超过该长度的长文档将自动被截断为指定的 token 数量。
### 1. 多模态用法
```shell Curl theme={null}
curl https://aihubmix.com/v1/rerank \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d @- < response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
```
### 响应说明
```json theme={null}
{
"model": "jina-reranker-m0",
"results": [
{
"index": 1,
"relevance_score": 0.8814517277012487
},
{
"index": 3,
"relevance_score": 0.7756727858283531
},
{
"index": 7,
"relevance_score": 0.6128658982982312
}
],
"usage": {
"total_tokens": 2894
}
}
```
成功的响应包含以下字段:
* `model`: 使用的模型名称
* `results`: 重排序结果数组,按相关性得分降序排列,每个元素包含:
* `index`: 原始文档数组中的索引位置
* `relevance_score`: 相关性分数,介于 0-1 之间,越高表示与查询越相关
* `total_tokens`: 此请求处理的总 Token 数
### 2. 文本用法
文本重排序包含多语言任务和普通任务,和 embedding 用法类似,传入数组。
```shell Curl theme={null}
curl https://aihubmix.com/v1/rerank \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d @- < {
let responseData = '';
res.on('data', chunk => {
responseData += chunk;
});
res.on('end', () => {
console.log(responseData);
});
});
req.write(JSON.stringify(requestData));
req.end();
```
## 三、深度搜索 (DeepSearch)
DeepSearch 结合了搜索、阅读和推理能力,直到找到最佳答案。它完全兼容 OpenAI 的 Chat API 格式,只需将 `api.openai.com` 替换为 `aihubmix.com` 即可开始使用。\
流式调用 (stream) 会返回思考过程。
### 请求参数
模型名称,可用模型列表:
* `jina-deepsearch-v1`:默认模型,搜索、阅读和推理直到找到最佳答案
是否启用流式响应。强烈建议保持此选项开启,DeepSearch 请求可能需要较长时间完成,禁用流式可能导致 '524 超时' 错误
用户与助手之间的对话消息列表。支持多种类型(模态)的消息,如文本 (.txt, .pdf)、图像 (.png, .webp, .jpeg) 等。文件大小最大支持 10MB
### 多模态消息格式
DeepSearch 支持多种类型的消息格式,可以包含纯文本(message)、文件(file)和图像(image)。以下是不同格式的示例:
#### 1. 纯文本消息
```json theme={null}
{
"role": "user",
"content": "hi"
}
```
#### 2. 带有文件附件的消息
```json theme={null}
{
"role": "user",
"content": [
{
"type": "text",
"text": "what's in this file?"
},
{
"type": "file",
"data": "data:application/pdf;base64,JVBERi0xLjQKJfbk...", // PDF 文件的 base64 编码
"mimeType": "application/pdf"
}
]
}
```
#### 3. 带有图像的消息
```json theme={null}
{
"role": "user",
"content": [
{
"type": "text",
"text": "what's in the image?"
},
{
"type": "image",
"image": "data:image/webp;base64,UklGRoDOAAB...", // 图像的 base64 编码
"mimeType": "image/webp"
}
]
}
```
所有文件和图像必须以数据 URI 格式(data URI)提前编码,最大支持 10MB。
### 调用示例
请注意 **Jina AI 官网的 Python 流式调用会没有响应**,参考我们的示例即可。
```shell Curl theme={null}
curl https://aihubmix.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d @- < 0:
delta = json_data['choices'][0].get('delta', {})
content_to_print = delta.get('content') or delta.get('reasoning_content') # Check both fields
if content_to_print:
print(content_to_print, end='', flush=True)
except json.JSONDecodeError:
# Ignore lines that are not valid JSON after "data: "
# print(f"\nCould not decode JSON from line: {decoded_line}")
pass # Optionally log or handle non-JSON data lines if needed
# Handle lines that don't start with "data: " if necessary
# else:
# print(f"Received non-data line: {decoded_line}")
print() # Add a newline at the end
elif response.status_code == 401:
print(f"Error: {response.status_code} - Unauthorized. Please check your API key.")
try:
print(response.json())
except json.JSONDecodeError:
print(response.text)
else:
print(f"Error: {response.status_code}")
try:
print(response.json()) # Print error details if available
except json.JSONDecodeError:
print(response.text) # Print raw text if not JSON
```
```ts TypeScript theme={null}
const https = require('https');
const data = JSON.stringify({
model: "jina-deepsearch-v1",
messages: [
{
role: "user",
content: "Hi!"
},
{
role: "assistant",
content: "Hi, how can I help you?"
},
{
role: "user",
content: "what's the latest blog post from jina ai?"
}
],
stream: true
});
const options = {
hostname: 'aihubmix.com',
path: '/v1/chat/completions',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length,
'Authorization': 'Bearer sk-***' // 替换为你的 AiHubMix 密钥
}
};
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
});
});
req.on('error', error => {
console.error(error);
});
req.write(data);
req.end();
```
### 响应说明
DeepSearch 的响应默认是开启流式的,包括推理步骤和最终答案。最后一个块包含最终答案、访问的 URL 和 token 使用情况。关闭流式则不输出 thinking 内容。\
注意这个对象和 Jina AI 有所差异。
```json theme={null}
{
"id": "1745506101379",
"object": "chat.completion.chunk",
"created": 1745506101,
"model": "jina-deepsearch-v1",
"choices": [
{
"index": 0,
"delta": {
"role": "assistant",
"reasoning_content": ""
}
}
],
"system_fingerprint": "fp_1745506101379"
}
// 流式推理内容
{
"id": "1745506101379",
"object": "chat.completion.chunk",
"created": 1745506101,
"model": "jina-deepsearch-v1",
"choices": [
{
"index": 0,
"delta": {
"reasoning_content": "推理内容片段"
}
}
],
"system_fingerprint": "fp_1745506101379"
}
// 推理结束
{
"id": "1745506101379",
"object": "chat.completion.chunk",
"created": 1745506101,
"model": "jina-deepsearch-v1",
"choices": [
{
"index": 0,
"delta": {
"reasoning_content": "\n\n"
},
"finish_reason": "thinking_end"
}
],
"system_fingerprint": "fp_1745506101379"
}
// 最终响应内容(包含注释和URL引用)
{
"id": "1745506101379",
"object": "chat.completion.chunk",
"created": 1745506101,
"model": "jina-deepsearch-v1",
"choices": [
{
"index": 0,
"delta": {
"content": "响应内容",
"type": "text",
"annotations": [
{
"type": "url_citation",
"url_citation": {
"url": "https://example.com",
"title": "页面标题",
"start_index": 0,
"end_index": 0
}
}
]
},
"finish_reason": "stop"
}
],
"system_fingerprint": "fp_1745506101379",
"usage": {
"prompt_tokens": 673423,
"completion_tokens": 109286,
"total_tokens": 583555
}
}
data: [DONE]
```
**Python 返回示例:**
```py Python theme={null}
I need to check the Jina AI blog for their most recent post, which requires up-to-date information. I need to find the latest blog post from Jina AI. I will use a search engine to find the Jina AI blog and then identify the most recent post. Let me search for latest blog post from Jina AI to gather more information. Okay, I've created some queries to find the latest Jina AI blog post. First, a general search for the Jina AI blog updated in the past week. Then, some focused queries on specific Jina AI products like DeepSearch and neural search, checking for updates in the last month. Also, I included queries about embedding models and API updates, again looking at the past month. And I added a query about Elasticsearch integration from the past year. Finally, I've added a query to find any criticisms or limitations of Jina AI, to get a balanced perspective. Let me search for Jina AI Elasticsearch integration, Jina AI criticism limitations, Jina AI deepsearch updates, Jina AI neural search, Jina AI embedding models to gather more information. To accurately answer the user's question about the latest blog post from Jina AI, I need to visit the provided URLs and extract the publication dates and titles of the blog posts. This will allow me to identify the most recent one. I'll start with the most relevant URLs based on the weights assigned during the search action. Let me read https://jina.ai/news/a-practical-guide-to-implementing-deepsearch-deepresearch, https://jina.ai/news/auto-gpt-unmasked-hype-hard-truths-production-pitfalls, https://jinaai.cn/news/a-practical-guide-to-implementing-deepsearch-deepresearch, https://businesswire.com/news/home/20250220781575/en/Elasticsearch-Open-Inference-API-now-Supports-Jina-AI-Embeddings-and-Rerank-Model, https://gurufocus.com/news/2709507/elastic-nv-estc-enhances-elasticsearch-with-jina-ai-integration to gather more information. Content of https://jina.ai/news/a-practical-guide-to-implementing-deepsearch-deepresearch is too long, let me cherry-pick the relevant parts. Content of https://jinaai.cn/news/a-practical-guide-to-implementing-deepsearch-deepresearch is too long, let me cherry-pick the relevant parts. Content of https://jina.ai/news/auto-gpt-unmasked-hype-hard-truths-production-pitfalls is too long, let me cherry-pick the relevant parts. I have found several blog posts and news articles related to Jina AI. I will summarize the most recent information available to answer the user's question. But wait, let me evaluate the answer first. The answer provides a summary of recent blog posts from Jina AI, covering different aspects of their activities. This constitutes a definitive response as it directly addresses the question with specific information. The answer discusses recent blog posts and news from Jina AI. Tech news has a max age of 7 days, and since the blog posts are only a few days old, the answer is still fresh. I am sorry, but the answer is too generic. While it mentions a few blog posts, it doesn't identify the absolute latest one. A perfect answer should pinpoint the most recent blog post with its exact title and, if possible, a direct link. The current answer provides a summary of several recent posts, which isn't precise enough for what I'm looking for. I messed up by summarizing multiple blog posts instead of pinpointing the single latest one. I needed to focus on finding the most recent date and title. I should prioritize identifying the latest date associated with a blog post and then provide its title and a direct link if available. Okay, I need to find the absolute latest blog post from Jina AI. The previous answer was too generic. I need to be laser-focused on identifying the most recent post. I'll revisit the Jina AI news page and look for specific dates and titles. I'll prioritize URLs that are likely to contain blog posts or news announcements directly from Jina AI. Let me read https://jina.ai/news, https://jina.ai/deepsearch, https://zilliz.com/blog/training-text-embeddings-with-jina-ai, https://github.com/jina-ai/node-DeepResearch, https://x.com/jinaai_?lang=en to gather more information. Content of https://zilliz.com/blog/training-text-embeddings-with-jina-ai is too long, let me cherry-pick the relevant parts. Content of https://jina.ai/deepsearch is too long, let me cherry-pick the relevant parts. I have reviewed my knowledge and can confidently answer the user's question about the latest blog post from Jina AI. I will provide the title and a direct link. But wait, let me evaluate the answer first. The answer provides a clear and direct response to the question, including the title, publication date, and a link to the latest blog post from Jina AI. There are no uncertainty markers or hedging. The blog post was published on April 16, 2025, which is 8 days ago from today (April 24, 2025). Since the blog post falls under 'Tech News,' the maximum age should be 7 days. Therefore, the answer is outdated. Okay, I jumped the gun and didn't double-check the date of the blog post against the current date. My bad for not ensuring it was within the acceptable timeframe! Next time, I'll make absolutely sure to verify the publication date and confirm it's fresh enough before confidently declaring it the latest blog post. Gotta keep those dates in check! I need to find the very latest blog post from Jina AI. The previous attempt failed because it wasn't recent enough. I need to revisit the Jina AI news page to check for any even more recent posts. I'll focus on extracting the title and URL of the most recent entry. Let me read https://jina.ai/news?tag=tech-blog, https://news.ycombinator.com/item?id=38020109, https://github.com/sthagen/jina-ai-jina, https://parsers.vc/news/250222-the-new-frontier-of-ai--elasticsearch-and, https://jina.ai/embeddings to gather more information. Content of https://jina.ai/embeddings is too long, let me cherry-pick the relevant parts. Content of https://news.ycombinator.com/item?id=38020109 is too long, let me cherry-pick the relevant parts. I have gathered information from various sources about Jina AI's blog posts. I will now synthesize this information to provide the most recent blog post title and a direct link, if available. But wait, let me evaluate the answer first. The answer makes a direct statement about the latest blog post from Jina AI, providing the title, publication date, and a link to the post. There are no hedges or qualifications, so it is definitive. Let me finalize the answer. Let Let me cross-reference the information from the web to verify the answer.
The relentless pursuit of better search demands we confront a harsh reality: size matters, and not always in a good way. Jina AI's latest blog post, "On the Size Bias of Text Embeddings and Its Impact in Search," published on April 16, 2025, tackles this head-on. It's not just another piece of content; it's a critical examination of how the length of text inputs can skew similarity metrics, leading search systems to favor verbose, often irrelevant documents over concise, precise matches.
Why should you care? Because in the age of information overload, relevance is king. We're drowning in data, and search engines are our life rafts. But if those rafts are steered by algorithms that are easily fooled by sheer volume, we're all going down with the ship.
The post likely delves into the mechanics of text embeddings, those numerical representations of text that allow machines to understand and compare semantic meaning. The core issue, as Jina AI points out, is that these embeddings can be influenced by the length of the input text, a phenomenon they term "size bias." This means that a longer document, even if only marginally relevant, might appear more similar to a query than a shorter, more focused one.[^1]
To truly grasp the implications, consider the following:
* **What is Size Bias?** Size bias refers to how the length of text inputs affects similarity, regardless of semantic relevance. It explains why search systems sometimes return long, barely-relevant documents instead of shorter, more precise matches to your query.[^2]
* **Who is impacted?** Anyone relying on semantic search, from researchers sifting through academic papers to businesses trying to surface the most pertinent information for their customers, is vulnerable to the distortions caused by size bias.
* **Where does this problem manifest?** This issue isn't confined to a specific search engine or platform. It's a systemic challenge inherent in the way many text embedding models are designed and implemented.
* **When did this become a pressing concern?** As context windows grow, and models are ingesting larger and larger documents, the problem of size bias becomes amplified.
* **Why does this happen?** The reasons are complex, but it boils down to the mathematical properties of high-dimensional spaces and the way similarity is calculated. Longer vectors simply have more "surface area" to overlap with a query vector, even if the semantic alignment is weak.
* **How can we fix it?** Jina AI's blog post likely explores potential mitigation strategies. These might include normalization techniques, architectural modifications to embedding models, or novel similarity metrics that are less susceptible to length-related distortions.
Jina AI's work here isn't just academic; it's a practical intervention. By identifying and analyzing size bias, they're paving the way for more accurate and reliable search technologies. This has real-world implications, influencing everything from information retrieval to content recommendation and beyond.
The latest blog post can be found here: https://jina.ai/news
Ultimately, Jina AI's willingness to confront the inconvenient truths about text embeddings is a testament to their commitment to advancing the field. It's a reminder that progress isn't just about building bigger and more complex models; it's about understanding the nuances and limitations of those models and striving for solutions that prioritize accuracy and relevance above all else. And that's a size-independent truth worth embracing.
[^1]: Size bias refers to how the length of text inputs affects similarity regardless of semantic relevance It explains why search systems sometimes return long barely relevant documents instead of shorter more precise matches to your query [Newsroom - Jina AI](https://jina.ai/news)
[^2]: Size bias refers to how the length of text inputs affects similarity regardless of semantic relevance It explains why search systems sometimes return long barely relevant documents instead of shorter more precise matches to your query [Newsroom - Jina AI](https://jina.ai/news?tag=tech-blog)
Stream finished.
```
## 四、网页搜索 (Search)
基于 Jina AI 的 `s.jina.ai`,传入查询词即可返回搜索结果页 (SERP) 的干净正文,可直接用于 LLM 的联网问答与 RAG。接口同时支持 `GET` 与 `POST`。
**响应格式(默认 markdown)**:默认返回拼接好的 **markdown** 结果列表,直接可喂给 LLM;需要结构化数据(各结果的 `title` / `url` / `content` 与 `usage` 用量)时,在请求头加 `Accept: application/json` 即返回 JSON。
### 请求参数
查询词。在代码中调用时需先做 URL 编码
返回结果的条数上限;实际返回条数以可用结果数量为准
国家 / 地区代码,如 `US`
界面语言,如 `en`
限定在指定站点内搜索,可重复传入,如 `site=jina.ai&site=github.com`
结果正文格式,可选 `markdown` / `html` / `text`
图片保留策略,传 `none` 可移除图片以节省 token
跳过缓存,抓取最新结果
此外,搜索会对每条命中结果调用 Reader 提取正文,因此「五、网页读取 (Reader)」中用于控制正文格式的各类 `X-*` 请求头,同样适用于搜索结果。
### 调用示例
查询词与参数可作为 URL 查询参数使用 `GET`(推荐,最简洁),也可放入 JSON 请求体使用 `POST`;两者打的是同一端点、返回相同结果。下方示例默认加了 `Accept: application/json` 返回 JSON;**去掉该头即返回干净的 markdown 结果列表**(见首个 `Curl-markdown` 示例)。
```shell Curl-markdown theme={null}
# 不带 Accept 头 → 直接返回拼好的 markdown 结果列表
curl "https://aihubmix.com/v1/jina/search?q=AIHubMix&num=5&gl=US&hl=en" \
-H "Authorization: Bearer sk-***"
```
```shell Curl-GET theme={null}
curl "https://aihubmix.com/v1/jina/search?q=AIHubMix&num=5&gl=US&hl=en" \
-H "Authorization: Bearer sk-***" \
-H "Accept: application/json"
```
```shell Curl-POST theme={null}
curl -X POST "https://aihubmix.com/v1/jina/search" \
-H "Authorization: Bearer sk-***" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
"q": "AIHubMix",
"num": 5,
"gl": "US",
"hl": "en"
}'
```
```py Python theme={null}
import requests
url = 'https://aihubmix.com/v1/jina/search'
headers = {
'Authorization': 'Bearer sk-***', # 替换为你的 AiHubMix 密钥
'Accept': 'application/json'
}
params = {'q': 'AIHubMix', 'num': 5, 'gl': 'US', 'hl': 'en'}
response = requests.get(url, headers=headers, params=params)
print(response.json())
```
```ts TypeScript theme={null}
const url = 'https://aihubmix.com/v1/jina/search?q=AIHubMix&num=5&gl=US&hl=en';
fetch(url, {
method: 'GET',
headers: {
'Authorization': 'Bearer sk-***', // 替换为你的 AiHubMix 密钥
'Accept': 'application/json'
}
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
```
### 响应说明
**默认(不带 `Accept`)返回拼好的 markdown 列表**,每条依次给出标题、来源链接、摘要(若有)与正文:
```text theme={null}
[1] Title: AIHubMix - One Interface, Router All LLMs
[1] URL Source: https://aihubmix.com/?lang=en
[1] Description: Access every major LLM through a single, unified interface. Connect to ChatGPT, Claude, Gemini, DeepSeek and more.
[1] Content:
If requests to http://aihubmix.com fail, you can try using a VPN, or switch to the alternative baseURL: https://api.inferera.com …
[2] Title: AI Models & Pricing - AIHubMix
[2] URL Source: https://aihubmix.com/models?lang=en
[2] Content:
…
```
**带 `Accept: application/json` 返回结构化 JSON**:
```json theme={null}
{
"code": 200,
"status": 200,
"data": [
{
"title": "AIHubMix - One Interface, Router All LLMs",
"url": "https://aihubmix.com/?lang=en",
"content": "If requests to http://aihubmix.com fail, you can try using a VPN, or switch to the alternative …",
"usage": { "tokens": 4244 }
},
{
"title": "AI Models & Pricing - AIHubMix",
"url": "https://aihubmix.com/models?lang=en",
"content": "…",
"usage": { "tokens": 4303 }
}
]
}
```
* `data`:搜索结果数组(条数由 `num` 控制,上例返回 5 条,此处仅示前 2 条;`content` 为完整正文,示例中已截断),每条含 `title`、`url`、`content`、`usage.tokens`。
* **计费**:按各条结果的 `usage.tokens` 之和计费;Jina 官方对每次搜索按最低 **10000 token** 起收,因此最终按二者中的较大值计费,即 `max(10000, token 之和)`。
## 五、网页读取 (Reader)
基于 Jina AI 的 `r.jina.ai`,传入任意网址即可返回该网页转换后的干净 markdown 正文,便于抓取网页内容供 LLM 使用。除网页外,还支持**图片**(由视觉模型生成描述)与**本地文件**(PDF、Word / Excel / PPT、HTML、图片)的解析。
**响应格式(默认 markdown)**:默认直接返回**干净的 markdown 正文**,可直接喂给 LLM;需要带 `usage` 用量与 `title` / `url` 等字段的结构化 **JSON**(正文在 `data.content`)时,在请求头加 `Accept: application/json`。
### 请求参数
要读取的网页地址,直接拼接在端点路径末尾,如 `/v1/jina/reader/https://jina.ai`
上传的本地文件,支持 PDF、Word / Excel / PPT、HTML、图片,通过 `POST` 以 `multipart/form-data` 放在 `file` 字段
上传 HTML 文件时必填,作为解析页面内相对链接的参考地址;上传 PDF 时无需
返回格式,可选 `markdown` / `html` / `text` / `screenshot` / `pageshot`
图片保留策略,可选 `all` / `none`(移除图片以节省 token)/ `alt`
链接保留策略,可选 `all` / `none` / `text`
为无 `alt` 的图片自动生成描述文字
在正文末尾汇总全部链接
在正文末尾汇总全部图片
抓取引擎,可选 `browser` / `direct` / `cf-browser-rendering`
CSS 选择器,仅提取匹配的页面区域
CSS 选择器,移除匹配的元素(如 `header, footer, nav`)
抓取超时时间(秒),最大 180
跳过缓存,抓取最新
markdown 标题样式,可选 `atx`(`#`)/ `setext`(下划线)
markdown 项目符号,可选 `-` / `+` / `*`
markdown 水平线样式,如 `***`
markdown 链接样式,可选 `inlined` / `referenced` / `discarded`
以上仅为常用项。Jina 支持的**全部** `X-*` 请求头(包括整个 `X-Md-*` 系列)以及 `POST` 请求体字段(如注入脚本 `injectPageScript`)均由网关**原样转发**,完整列表与取值请以 [Jina 官方文档](https://r.jina.ai/docs) 为准。
### 多模态输入格式
Reader 支持三种输入。**网页与图片**直接把地址拼接在端点路径末尾(`GET`);**本地文件**通过 `POST` 以 `multipart/form-data` 上传。
#### 1. 网页 URL
```text theme={null}
GET /v1/jina/reader/https://example.com
```
#### 2. 图片 URL(返回视觉描述)
图片地址同样拼在路径末尾。Reader 用视觉模型为图片生成**描述**(caption,非逐字 OCR)放入 `content`。
```text theme={null}
GET /v1/jina/reader/https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png
```
#### 3. 上传本地文件(PDF / Word·Excel·PPT / HTML / 图片)
```text theme={null}
POST /v1/jina/reader
Content-Type: multipart/form-data
file=@./doc.pdf # 文件放在 file 字段
url=https://example.com/... # 仅上传 HTML 时需要,作为解析相对链接的参考地址
```
### 调用示例
默认直接返回 markdown 正文;带 `Accept: application/json` 返回结构化 JSON。可选参数以 `X-*` 请求头传入,**均由网关原样转发**给 Jina(完整参数见上方「请求参数」)。
#### 1. 读取网页
```shell 基础(markdown) theme={null}
# 不带 Accept → 直接返回干净 markdown 正文
curl "https://aihubmix.com/v1/jina/reader/https://example.com" \
-H "Authorization: Bearer sk-***"
```
```shell 进阶(多参数) theme={null}
# 组合多个 X-* 头,均由网关原样转发给 Jina:
# 去图省 token · 只提取 #bodyContent 区域 · 末尾汇总链接
curl "https://aihubmix.com/v1/jina/reader/https://en.wikipedia.org/wiki/Large_language_model" \
-H "Authorization: Bearer sk-***" \
-H "Accept: application/json" \
-H "X-Retain-Images: none" \
-H "X-Target-Selector: #bodyContent" \
-H "X-With-Links-Summary: true"
```
```shell JSON theme={null}
curl "https://aihubmix.com/v1/jina/reader/https://example.com" \
-H "Authorization: Bearer sk-***" \
-H "Accept: application/json"
```
```py Python theme={null}
import requests
url = 'https://aihubmix.com/v1/jina/reader/https://example.com'
headers = {
'Authorization': 'Bearer sk-***', # 替换为你的 AiHubMix 密钥
'Accept': 'application/json'
}
response = requests.get(url, headers=headers)
print(response.json())
```
```ts TypeScript theme={null}
const url = 'https://aihubmix.com/v1/jina/reader/https://example.com';
fetch(url, {
method: 'GET',
headers: {
'Authorization': 'Bearer sk-***', // 替换为你的 AiHubMix 密钥
'Accept': 'application/json'
}
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
```
#### 2. 读取图片
```shell Curl theme={null}
curl "https://aihubmix.com/v1/jina/reader/https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" \
-H "Authorization: Bearer sk-***" \
-H "Accept: application/json"
```
#### 3. 上传本地文件
以 `POST` + `multipart/form-data` 上传;上传 **HTML** 时需额外带 `url` 字段作参考地址。计费方式与读取网址一致。
```shell PDF / 图片 / Office theme={null}
curl -X POST "https://aihubmix.com/v1/jina/reader" \
-H "Authorization: Bearer sk-***" \
-H "Accept: application/json" \
-F "file=@./doc.pdf"
```
```shell HTML(需带 url) theme={null}
curl -X POST "https://aihubmix.com/v1/jina/reader" \
-H "Authorization: Bearer sk-***" \
-H "Accept: application/json" \
-F "file=@./local.html" \
-F "url=https://example.com/local.html"
```
### 响应说明
**默认(不带 `Accept`)直接返回 markdown 正文**(即下方 JSON 中 `data.content` 的内容)。例如读取 `https://example.com`:
```text theme={null}
This domain is for use in documentation examples without needing permission. Avoid use in operations.
[Learn more](https://iana.org/domains/example)
```
**带 `Accept: application/json`** 则返回结构化 JSON。三类输入的 JSON 结构一致:`data` 为单个对象,含 `title` / `url` / `content` / `usage.tokens`。以下为三种输入的**真实返回**(`content` 过长时保留开头,其余以 `…` 略去)。
**① 读取网页**(读取 `https://example.com`):
```json theme={null}
{
"code": 200,
"status": 20000,
"data": {
"title": "Example Domain",
"url": "https://example.com/",
"content": "This domain is for use in documentation examples without needing permission. Avoid use in operations.\n\n[Learn more](https://iana.org/domains/example)",
"usage": { "tokens": 29 }
}
}
```
**② 读取图片**(`content` 为视觉模型生成的描述):
```json theme={null}
{
"code": 200,
"status": 20000,
"data": {
"title": "googlelogo_color_272x92dp.png",
"url": "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png",
"content": "The logo for Google, consisting of the word Google in lowercase letters, with its colors being blue, red, yellow, and green, representing the company's innovative approach to information and computing services",
"usage": { "tokens": 38 }
}
}
```
**③ 上传本地文件**(上传一篇 PDF 论文,`content` 较长,仅示开头):
```json theme={null}
{
"code": 200,
"status": 20000,
"data": {
"title": "Unnoticeable Backdoor Attacks on Graph Neural Networks",
"url": "blob:df586d587956e0ca72e50e9e12dc06fc44b7c4b480b8a640a6db7d6f488a7c91",
"content": "# Unnoticeable Backdoor Attacks on Graph Neural Networks\n\n# Enyan Dai ∗\n\nemd5759@psu.edu\n\nThe Pennsylvania State University\n\nState College, USA\n\n## ABSTRACT\n\nGraph Neural Networks (GNNs) have achieved promising results in various tasks such as node classification and graph classification. …",
"usage": { "tokens": 20535 }
}
}
```
* `status`:Jina 上游返回的业务状态码,reader 成功时为 `20000`(与外层 HTTP `200` 一致)。
* **计费**:按 `data.usage.tokens`(实际输出的 token 数)计费,**无起步价**(不同于搜索的「每次 10000 token 起收」);内容极短时按最低计费单位兜底,不会出现 0 扣费。
***
更新时间:2026-07-03
# LLM 联网搜索
Source: https://docs.aihubmix.com/cn/api/LLM-Search
## 1️⃣ 实时联网支持:突破 LLM 时效限制,让输出更准确、更可靠
我们为 OpenAI 和 Gemini 系列大模型接口带来了获取最新网络信息的能力,帮助你:\
✅ **获取最新资讯**:无论是今日热点、最新研究还是实时数据,都能即时获取\
✅ **消除知识盲区**:突破大模型训练数据的时间限制,获取训练后的新信息\
✅ **降低幻觉风险**:基于实时网络搜索的事实回答,大幅减少 AI 已读乱回的可能性\
✅ **提升决策质量**:基于最新事实的分析和建议,让你的决策更有把握
**支持的模型:** 目前支持 OpenAI 和 Gemini 大模型系列,包含两种接入方式:
**1. 原生搜索能力模型:** **Gemini 系列** (Ground with Google search):
* gemini-3.1-pro-preview-search
* gemini-3-flash-preview-search
* gemini-2.5-pro-search
* gemini-2.5-flash-search
**OpenAI 系列** (Search Preview):
* gpt-4o-search-preview
* gpt-4o-mini-search-preview
**2. 参数支持方式:** 增加参数 `web_search_options={}`,可为支持该参数的 gemini、OpenAI 大模型开启联网能力。若返回 `Unknown parameter: 'web_search_options'`,说明当前模型或上游接口不接受该参数,请换用上方原生搜索模型,或使用下文 `:surfing` 后缀方式。Gemini 系列的搜索费率请以控制台和模型详情页展示为准。
### 使用方法
使用前需要运行 `pip install -U openai` 升级 openai 包,并将 AIHubMix API Key 写入环境变量:
```shellscript theme={null}
export AIHUBMIX_API_KEY=""
```
Windows PowerShell:
```powershell theme={null}
setx AIHUBMIX_API_KEY ""
```
**示例:**
```py Python theme={null}
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AIHUBMIX_API_KEY"], # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com/v1"
)
chat_completion = client.chat.completions.create(
model="gemini-3.5-flash",
# 🌐 启用搜索
web_search_options={},
messages=[
{
"role": "user",
"content": "Search for information about the AIhubmix LLM API platform, provide a brief introduction, and include relevant links."
}
]
)
print(chat_completion.choices[0].message.content)
```
```ts Typescript theme={null}
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.AIHUBMIX_API_KEY,
baseURL: 'https://aihubmix.com/v1'
});
async function main() {
const chatCompletion = await client.chat.completions.create({
model: 'gemini-3.5-flash',
// 🌐 启用搜索
web_search_options: {},
messages: [
{
role: 'user',
content: 'Search for information about the AIhubmix LLM API platform, provide a brief introduction, and include relevant links.'
}
]
});
console.log(chatCompletion.choices[0].message.content);
}
main().catch(console.error);
```
```shell Curl theme={null}
curl "https://aihubmix.com/v1/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-d '{
"model": "gemini-3.5-flash",
"web_search_options": {},
"messages": [
{
"role": "user",
"content": "Provide information about Van Gogh on the Google Arts & Culture website, with a brief introduction and relevant links."
}
],
"stream": false
}'
```
## 2️⃣ 智能冲浪:让 AI 自由驰骋互联网
通过在模型 id 后方追加 `:surfing`,让任何大语言模型具备搜索能力。
* 追加后缀即可,不需要复杂的整合
* 这种方式会默认将用户请求转发给 **Tavily 搜索服务**,LLM 根据返回的搜索结果参考作答
* 搜索费用 **0.006 美元/次**
* 目前「日志明细」里未列出每次搜索的费用,费用直接在「额度变动」扣取,后续会列出
模型 id 在[模型广场](https://aihubmix.com/models)中复制即可。
**示例:**
```py Python theme={null}
import requests
import json
import os
try:
response = requests.post(
url="https://aihubmix.com/v1/chat/completions",
headers={
"Authorization": f"Bearer {os.environ.get('AIHUBMIX_API_KEY')}",
"Content-Type": "application/json",
},
json={
"model": "gpt-5.5:surfing", # 模型 id 后面追加 :surfing 即可支持搜索
"messages": [
{
"role": "user",
"content": "搜索 AIHubMix 最近的模型更新,返回中文要点并附来源链接。"
}
],
"stream": False
},
timeout=60
)
result = response.json()
if response.status_code >= 400:
print("请求失败:", response.status_code)
print("API 响应:", json.dumps(result, ensure_ascii=False, indent=2))
except requests.exceptions.RequestException as e:
print(f"请求错误:{e}")
except json.JSONDecodeError as e:
print(f"JSON 解析错误:{e}")
except Exception as e:
print(f"其他错误:{e}")
```
**API 响应示例:**
```json theme={null}
{
"id": "chatcmpl-xxxx",
"model": "gpt-5.5-2026-04-24",
"object": "chat.completion",
"created": 1760000000,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "AIHubMix 是一个聚合多家模型能力的 API 平台,官网为 https://aihubmix.com。"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 220,
"completion_tokens": 240,
"total_tokens": 460,
"prompt_tokens_details": {
"audio_tokens": 0,
"cached_tokens": 0
},
"completion_tokens_details": {
"accepted_prediction_tokens": 0,
"audio_tokens": 0,
"reasoning_tokens": 196,
"rejected_prediction_tokens": 0
}
}
}
```
***
更新时间:2026-06-15
# 模型映射与回退
Source: https://docs.aihubmix.com/cn/api/Model-Mapping-Fallback
在 AIHubMix 控制台为每个 API Key 配置模型名映射与错误时回退:把客户端的模型别名改写为真实上游模型,主模型失败时自动切换到备用模型,按最终响应模型计费,客户端代码零改动。
> 别让上游宕机变成你的宕机。
AIHubMix 提供两个**Key 级别**的能力,在控制台配置一次即可生效,客户端代码无需改动:
* **模型名映射**(Model Mapping)是指在网关层把客户端请求里的模型别名改写为真实上游模型的能力。
* **错误时回退模型**(Fallback)是指当主模型调用失败时,网关按预先配置的优先级顺序自动尝试备用模型,对客户端无感。
这两个能力适用于所有通过 AIHubMix 接入的客户端与平台。无论是上游渠道临时故障、需要在多个模型间做容灾,还是客户端只认特定格式的模型名,过去都要改代码或自建网关才能解决;现在在 AIHubMix 的 Key 配置里就能完成,不必改客户端代码、也不必自建网关。
AIHubMix 支持在 Key 级别配置模型名映射与错误回退,并按最终响应模型计费。两者都在 [AIHubMix Key 管理页](https://console.aihubmix.com/token) 为单个 API Key 配置。
在创建 / 编辑 Key 时,可在面板的 `Model name mapping` 和 `Fallback models on error` 两个区块分别配置:
***
## 1. 模型名映射(Model Mapping)
模型名映射用于处理「客户端看到的模型名」和「AIHubMix 实际调用的模型」不一致的问题。它是**Key 级**(per-key)的别名改写:把请求里的别名改写成你在 Key 里配置的目标模型。
> 目标模型在选定渠道后,平台内部还会做一层渠道级映射到真实上游模型;该层对用户透明、无需配置。你只需要关心「别名 → 目标模型」这一层。
示例:
| 客户端请求模型名(别名) | AIHubMix 目标模型 |
| ------------ | ------------------------ |
| `my-gpt` | `gpt-5.5` |
| `my-fast` | `gemini-3.1-pro-preview` |
| `my-coder` | `deepseek-v4-flash` |
| `my-glm` | `coding-glm-5.2-free` |
> 上表模型名均可在 [AIHubMix 模型页](https://aihubmix.com/models) 查询。
常见用途:
* 客户端限制模型名格式,例如 Claude Desktop 要求模型名符合 Claude 风格(见 [第 5 节](#5-场景一:claude-desktop))。
* 给复杂模型 ID 设置更短、更稳定的别名。
* 客户端配置保持不变,AIHubMix 后台切换真实模型。
* 多个平台共用一套接入命名,但根据 Key 路由到不同模型。
> **逐字符一致**:客户端发送的模型名必须和映射左侧**逐字符一致**。例如 `my-gpt-5.5` 和 `my-gpt-5-5` 是两个不同的字符串,不一致就不会命中映射。
***
## 2. 错误时回退模型(Fallback)
错误时回退模型用于在主模型失败时按顺序尝试备用模型。它不是客户端侧重试,而是 AIHubMix 网关侧在同一个 Key 配置下完成的模型切换;接入方不需要在每次请求里传额外路由参数。
可以把 Fallback 理解成「映射到一个**有序列表**」:主模型失败后,网关自动沿列表往下一个备用模型走。
示例(在同一个 Key 里配置):
| 顺序 | 备用模型 |
| -- | ------------------------ |
| 1 | `gpt-5.4` |
| 2 | `gemini-3.1-pro-preview` |
### 2.1 触发条件(必须全部满足才回退)
只有**以下条件全部成立**时才会发生回退:
1. Key 配置了非空的备用模型列表。
2. 主模型的**所有渠道都被试过、且都以「可重试错误」失败**(渠道耗尽)。
3. **响应尚未开始返回**(首字节 / header 还没发给客户端)。
4. 错误不是 Key / 用户级错误(见下方 [2.2 对照表](#2-2-哪些会回退、哪些不会))。
切到下一个备用模型后,网关会用新模型重新选渠道再试。
### 2.2 哪些会回退、哪些不会
| 情况 | 是否回退 |
| ------------------------------------------------ | :-----------: |
| 主模型全渠道「可重试失败」、响应未开始 | ✅ 回退 |
| 指定了具体渠道(Key 后缀 `sk-xxx-{id}`、`/v1/proxy/{id}/*`) | ❌ |
| 响应已开始返回(流式已出首字节) | ❌ |
| 客户端断开 / 请求超时 | ❌ |
| 你的 AIHubMix Key 额度不足 / 失效 / 过期 / 禁用 | ❌ |
| 账号封禁 / 命中风控关键词 | ❌ |
| 免费主模型触发额度 / 频率限流 | ✅ 回退到备用付费模型 |
| 备用列表里的**免费模型** | ⏭️ 跳过该项,继续下一个 |
| 备用列表里超出 Key 可用范围的模型 | ⏭️ 跳过 |
> 说明:这里「Key 失效」指的是**你自己的 AIHubMix Key**失效,不会回退。若是某个**上游渠道**的 key 坏了,网关会换渠道,渠道耗尽后**仍可**回退——两者不要混淆。
### 2.3 计费口径
**按最终响应模型计费。** 如果最终由回退模型响应,计费、能力和上下文限制都以最终响应的那个模型为准。这个模型也会体现在响应头里(见 [第 4 节](#4-配置与验证))。
### 2.4 免费模型规则(重要)
**免费模型不能作为 fallback 选项**——免费模型只能作主模型,放进备用列表会被**静默跳过**,继续往下一个。所以不要把免费模型写进 fallback 列表。
> **典型用法**:把免费模型设为主模型、付费模型放进备用列表。免费主模型触发额度 / 频率限流时,会自动回退到备用的付费模型——平时省成本用免费额度,限流后无缝切到付费模型保证可用。这是 fallback 最常见的用法之一。
***
## 3. 和 OpenRouter / LiteLLM 的区别
模型映射和回退并不是新概念,OpenRouter、LiteLLM 等都提供类似能力。AIHubMix 的差异在于**配置成本最低**:
| 能力 | OpenRouter | LiteLLM | AIHubMix |
| --------------------------- | :--------------: | :--------------------: | :----------: |
| 配置方式 | 代码里传 `models` 数组 | 自建 `config.yaml` proxy | 控制台按 API Key |
| 客户端代码零改动 | ❌ | ❌ | ✅ |
| 无需自部署 / 自建网关 | ✅ | ❌ | ✅ |
| 保留原生协议(Claude / Gemini SDK) | ❌ | ❌ | ✅ |
| 按最终响应模型计费 | ✅ | — | ✅ |
| 按 API Key 粒度配置 | ❌ | ❌ | ✅ |
一句话:**不用自建网关、不用改一行客户端代码,在 Key 上配一次就生效。**
***
## 4. 配置与验证
### 4.1 配置
1. 在**Key**里配置别名映射:左侧别名要和客户端实际发送的模型名**逐字符一致**。
2. 在**同一 Key**里配置备用模型列表(有序优先级列表)。
3. 备用列表**只放付费 / 可用模型,不放免费模型**(会被跳过)。
4. 备用列表里的模型必须在该 Key 的可用模型范围内(越权模型会被跳过)。
### 4.2 验证(优先看响应头,而不是翻日志)
排查时**不要只看客户端选了哪个模型**,最权威、可自动化的方式是读响应头:
* `X-Aihubmix-Fallback: true`:本次请求发生了回退(最终模型 ≠ 主模型时附加)。
* `X-Aihubmix-Model`:本次实际响应、且据此计费的模型。
curl 验证示例:
```bash theme={null}
curl -i https://aihubmix.com/v1/chat/completions \
-H "Authorization: Bearer sk-你的 Key" \
-H "Content-Type: application/json" \
-d '{"model":"my-gpt","messages":[{"role":"user","content":"hi"}]}' \
| grep -i -E 'x-aihubmix-(model|fallback)'
```
控制台日志可以交叉核对请求模型、映射后主模型和最终响应模型。
***
## 5. 场景一:Claude Desktop
Claude Desktop 通过 `Gateway` 接入 AIHubMix,是模型名映射的典型场景。
本节假设你已经完成 Claude Desktop 的基础接入。完整接入步骤(下载安装、开发者模式、Gateway 配置、auth scheme 等)见 [在 Claude Desktop 中接入 AIHubMix](https://docs.aihubmix.com/cn/api/claude-desktop),本节只讲映射与回退的增量配置。
### 5.1 为什么需要映射
Claude Desktop 以 `Gateway`(Anthropic-compatible)方式接入,客户端会按 Claude 风格约束模型名,因此模型名必须使用 `claude-` 前缀。
于是产生一个矛盾:客户端那侧只能写 `claude-` 风格的名字,但你真正想调用的是 `gpt-5.5`、`gemini-3.1-pro-preview` 这些。**模型名映射正是为此而生**——客户端写别名 `claude-g-p-t-5.5`,AIHubMix 侧映射到真实的 `gpt-5.5`。
> Claude Desktop 走的是 Claude 原生 `/v1/messages` 接口,所以本文示例里**映射和 Fallback 都生效**。
### 5.2 AIHubMix 映射与回退配置
示例配置:
```text theme={null}
claude-g-p-t-5.5 -> gpt-5.5
claude-gemi-3.1 -> gemini-3.1-pro-preview
claude-depsek-v4 -> deepseek-v4-flash
fallback:
1. gpt-5.4
2. gemini-3.1-pro-preview
```
### 5.3 Claude Desktop 模型列表
在 Claude Desktop 的 `Model list` 里配置的是**映射前的别名**——也就是 Claude Desktop 发给 AIHubMix 的模型名,不是真实上游模型名。
配置完成后,Claude Desktop 的模型下拉框会出现对应模型:
命名建议:
* `Model ID` 使用 `claude-` 前缀。
* 不要直接写 `gpt`、`gemini`、`deepseek` 等真实模型系列名,可使用 `g-p-t`、`gemi`、`depsek` 等别名。
* `Model ID` 必须和 AIHubMix 映射左侧**逐字符一致**,否则请求不会命中预期映射,可能继续走错误回退模型。
***
## 6. 场景二:多模态能力兜底
多模态能力兜底用于处理「主模型能回答文本,但不支持当前输入类型」的场景。比如客户端发送了图片或视频,主模型只有文本输入能力,AIHubMix 可以继续尝试回退列表里支持对应模态的模型。
下面是一条实际测试链路。这条 Key 的映射与 fallback 配置如下(见下方截图),重点是 fallback 列表里既有文本模型也有支持图片理解的模型:
```text theme={null}
claude-g-l-m-4.6 -> coding-glm-5.2-free
claude-g-p-t-5.5 -> gpt-5.5
claude-gemi-3.1 -> gemini-3.1-pro-preview
fallback:
1. gpt-5.4
2. gemini-3.1-flash-image
3. veo-3.1-lite-generate-preview
```
在 Claude Desktop 里,选中的模型显示为 `claude-g-l-m-4.6`——一个只支持文本输入的模型。用户上传了一张 AIHubMix 模型列表页面截图,并询问「这个网站是做什么的」。因为请求里包含图片,文本模型无法直接处理该输入,于是触发了 fallback。
AIHubMix 日志显示,这次最终实际调用的是 `Google AI Studio/gemini-3.1-flash-image`,也就是 fallback 列表里的第 2 个。第 1 个 `gpt-5.4` 同样不支持该图片输入、对这次请求继续返回可重试错误,于是网关接着往下,落到了支持图片理解的 `gemini-3.1-flash-image`。
> **触发原因要讲清**:这里兜底是因为**上游对该图片输入返回了可重试错误、且主模型渠道耗尽**——和「主模型限流后回退」是同一套回退机制,只是触发的错误类型不同(前者是输入不被支持,后者是额度 / 频率限流)。
>
> **注意区分理解与生成**:这里说的是**图片 / 视频理解**兜底,不是**图片生成或视频生成**。聊天请求不会自动变成生成接口;要测试画图或视频生成,应走对应的生成接口和模型。模型能力以 AIHubMix 模型页当前标注的 `Input Modalities` 为准。
***
## 7. 场景三:免费模型兜底(省成本 + 保可用)
这是 fallback 最常见的用法之一:把**免费模型设为主模型**、**付费模型放进备用列表**。平时请求都走免费模型、省成本;一旦免费主模型触发额度 / 频率限流,网关自动回退到备用的付费模型,保证服务不中断。
示例 Key 配置:
```text theme={null}
主模型(免费): coding-glm-5.2-free
fallback:
1. gpt-5.4
2. gemini-3.1-pro-preview
```
行为:
* 免费额度还够用时,请求由主模型 `coding-glm-5.2-free` 响应,按免费计费。
* 免费主模型触发限流后,自动回退到 `gpt-5.4`;若 `gpt-5.4` 也不可用,再尝试 `gemini-3.1-pro-preview`。
* 最终由哪个模型响应,就**按那个模型计费**(见 [2.3](#2-3-计费口径))。
> **注意**:免费模型只能作主模型,**不能放进 fallback 列表**(放进去会被跳过,见 [2.4](#2-4-免费模型规则(重要)))。所以「免费兜底」的正确姿势是:免费在主、付费在备,而不是反过来。
验证方式同样是看响应头:发生回退时返回 `X-Aihubmix-Fallback: true`,`X-Aihubmix-Model` 显示最终响应模型(见 [第 4 节](#4-配置与验证))。
***
## 8. 支持的端点
模型映射与错误回退目前支持以下接口类别:
| 接口类别 | Key 别名映射 | 错误回退 Fallback |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------: | :-----------: |
| OpenAI 兼容接口(`/v1/chat/completions`、`/v1/completions`、`/v1/embeddings`、`/v1/images/*`、`/v1/audio/transcriptions`·`/translations`、`/v1/rerank`、`/v1/moderations`、`/v1/edits` 等) | ✅ | ✅ |
| Claude 原生 `/v1/messages` | ✅ | ✅ |
| OpenAI Responses `/v1/responses` | ✅ | ✅ |
| 其他原生透传接口(Gemini 原生、Ideogram、`/v1/videos`、`/v1/audio/speech`(TTS)、Stability、OCR、`/predictions` 等) | ❌ | ❌ |
| 指定渠道透传 `/v1/proxy/{channelid}/*` | ❌ | ❌ |
| 按资源 ID 检索 / 文件类(`GET /v1/responses/{id}`、`/v1/videos/{id}`、files 等,请求体不含 model) | ❌ | ❌ |
要点:
* 模型映射与错误回退支持 **OpenAI 兼容接口、Claude 原生 `/v1/messages`、OpenAI Responses `/v1/responses`** 三类接口。
* 其他原生透传接口(Gemini 原生、Ideogram、视频、TTS、Stability、OCR、predictions 等)、指定渠道透传、以及按资源 ID 检索 / 文件类接口**暂不支持**。
* Claude Desktop 走的是 Claude 原生 `/v1/messages`,所以本文示例里**映射和 Fallback 都生效**。
***
## 9. 常见问题 FAQ
**Q:Claude Desktop 提示 model not found 怎么办?**
A:检查 Claude Desktop 里的 `Model ID` 是否和 AIHubMix 映射左侧**逐字符一致**;不一致就不会命中映射。
**Q:回退会不会影响计费?**
A:按**最终响应模型**计费。最终是哪个模型响应,就按那个模型的价格、能力和上下文限制计算。
**Q:怎么确认这次请求到底走没走回退?**
A:看响应头 `X-Aihubmix-Fallback: true`(发生了回退)和 `X-Aihubmix-Model`(最终响应模型),见 [第 4 节](#4-配置与验证)。
**Q:哪些错误会触发回退,哪些不会?**
A:见 [2.2 的对照表](#2-2-哪些会回退、哪些不会)。简单说:上游可重试失败、渠道耗尽、响应未开始才会回退;指定渠道、响应已开始、客户端断开 / 超时、Key / 用户级错误都不回退。
**Q:免费模型能放进 fallback 列表吗?**
A:不能,会被跳过。免费模型只能作主模型。
**Q:和 OpenRouter / LiteLLM 的 model alias / fallback 有什么区别?**
A:AIHubMix 是**Key 级、平台托管**,在控制台配一次就生效,不用改客户端代码、也不用自建网关。详见 [第 3 节](#3-和-openrouter-/-litellm-的区别)。
***
## 相关资源
* [在 Claude Desktop 中接入 AIHubMix](https://docs.aihubmix.com/cn/api/claude-desktop):开发者模式、Gateway 配置、auth scheme 等完整步骤。
* [AIHubMix 模型页](https://aihubmix.com/models):查询模型名称、价格与 `Input Modalities`。
* [在 LiteLLM 中接入 AIHubMix](https://docs.aihubmix.com/cn/clients/LiteLLM):需要自建网关 + 模型映射 / 回退时的参考。
# 模型管理API
Source: https://docs.aihubmix.com/cn/api/Models-API
GET /api/v1/models
本API文档提供了对模型管理接口的详细说明,包括新版本和旧版本接口的功能、请求示例、参数说明及响应格式。
## 新版本接口
### 获取模型信息平台
**接口地址**:`GET https://aihubmix.com/api/v1/models`
**功能描述**:获取所有可用模型的详细信息。
### 模型对象字段说明
模型信息列表数组
模型唯一标识符
模型功能描述(英文)
模型类型,支持值:`llm`(大语言模型)、`image_generation`(图片生成模型)、`video`(视频生成模型)、`tts`(语音合成模型)、`stt`(语音转文本模型)、`embedding`(嵌入模型)、`rerank`(排序模型)
支持的功能特性,支持值:`thinking`(支持思考推理)、`tools`(支持工具调用)、`function_calling`(支持函数调用)、`web`(支持搜索)、`deepsearch`(支持深度搜索)、`long_context`(长上下文模型)、`structured_outputs`(结构化输出)
支持的输入模态,支持值:`text`(文本)、`image`(图像)、`audio`(音频) 、`video`(视频)、`pdf`
最大输出Token数量
上下文窗口大小(最大输入Token数量)
价格信息对象
输入Token价格(每1K Token,美元)
输出Token价格(每1K Token,美元)
缓存读取价格(每1K Token,美元,可选字段)
缓存写入价格(每1K Token,美元,可选字段)
### 请求示例
```python Python theme={null}
import requests
# 接口地址
url = "https://aihubmix.com/api/v1/models"
response = requests.get(url)
print(response.json())
params = {
"type": "llm",
"modalities": "text",
"model": "gpt-5",
"features": "thinking",
"sort_by": "context_length",
"sort_order": "desc"
}
response = requests.get(url, params=params)
print(response.json())
```
```javascript JavaScript theme={null}
fetch('https://aihubmix.com/api/v1/models')
.then(response => response.json())
.then(data => console.log(data));
const params = new URLSearchParams({
type: 'llm',
modalities: 'text',
model: 'gpt-5',
features: 'thinking',
sort_by: 'context_length',
sort_order: 'desc'
});
fetch(`https://aihubmix.com/api/v1/models?${params}`)
.then(response => response.json())
.then(data => console.log(data));
```
```bash cURL theme={null}
curl -X GET "https://aihubmix.com/api/v1/models"
curl -X GET "https://aihubmix.com/api/v1/models?type=llm&modalities=text&model=gpt-5&features=thinking&sort_by=context_length&sort_order=desc"
```
### 请求参数说明(可用于筛选)
模型类型。支持值:`llm`(大语言模型)、`image_generation`(图片生成模型)、`video`(视频生成模型)、`tts`(语音合成模型)、`stt`(语音转文本模型)、`embedding`(嵌入模型)、`rerank`(排序模型)
输入模态。支持值:`text`(文本)、`image`(图像)、`audio` (音频)、`video`(视频)、`pdf`,支持多模态查询(逗号分隔)
模型名称模糊搜索(支持部分匹配)
模型功能特性。支持值:`thinking`(支持思考推理)、`tools`(支持工具调用)、`function_calling`(支持函数调用)、`web`(支持搜索)、`deepsearch`(支持深度搜索)、`long_context`(长上下文模型)、`structured_outputs`(结构化输出),支持多功能查询(逗号分隔)
排序字段。支持值:\
• `model_ratio`:按性价比排序\
• `context_length`:按上下文长度排序\
• `coding`:编程模型优先排序\
• `order`:按默认顺序排序
排序方向。支持值:\
• `asc`(升序) \
• `desc`(降序)
### 响应成功示例
```json theme={null}
{
"data": [
{
"model_id": "gpt-5",
"desc": "GPT-5 is OpenAI flagship model for coding, reasoning, and agentic tasks across domains.",
"pricing": {
"cache_read": 0.125,
"input": 1.25,
"output": 10
},
"types": "llm",
"features": "thinking,tools,function_calling,structured_outputs",
"input_modalities": "text,image",
"max_output": 128000,
"context_length": 400000
},
{
"model_id": "gpt-5-codex",
"desc": "GPT-5-Codex is a version of GPT-5 optimized for autonomous coding tasks in Codex or similar environments. It is only available in the Responses API, and the underlying model snapshots will be updated regularly. https://docs.aihubmix.com/en/api/Responses-API You can also use it in codex-cll; see https://docs.aihubmix.com/en/api/Codex-CLI for using codex-cll through Aihubmix.",
"pricing": {
"cache_read": 0.125,
"input": 1.25,
"output": 10
},
"types": "llm",
"features": "thinking,tools,function_calling,structured_outputs",
"input_modalities": "text,image",
"max_output": 128000,
"context_length": 400000
},
{
"model_id": "gpt-5-mini",
"desc": "GPT-5 mini is a faster, more cost-efficient version of GPT-5. It's great for well-defined tasks and precise prompts.",
"pricing": {
"cache_read": 0.025,
"input": 0.25,
"output": 2
},
"types": "llm",
"features": "thinking,tools,function_calling,structured_outputs",
"input_modalities": "text,image",
"max_output": 128000,
"context_length": 400000
},
{
"model_id": "gpt-5-nano",
"desc": "GPT-5 Nano is our fastest, cheapest version of GPT-5. It's great for summarization and classification tasks.",
"pricing": {
"cache_read": 0.005,
"input": 0.05,
"output": 0.4
},
"types": "llm",
"features": "thinking,tools,function_calling,structured_outputs",
"input_modalities": "text,image",
"max_output": 128000,
"context_length": 400000
},
{
"model_id": "gpt-5-pro",
"desc": "GPT-5 pro uses more compute to think harder and provide consistently better answers.\n\nGPT-5 pro is available in the Responses API only to enable support for multi-turn model interactions before responding to API requests, and other advanced API features in the future. Since GPT-5 pro is designed to tackle tough problems, some requests may take several minutes to finish. To avoid timeouts, try using background mode. As our most advanced reasoning model, GPT-5 pro defaults to (and only supports) reasoning.effort: high. GPT-5 pro does not support code interpreter.",
"pricing": {
"input": 15,
"output": 120
},
"types": "llm",
"features": "thinking,tools,function_calling,structured_outputs",
"input_modalities": "text,image",
"max_output": 128000,
"context_length": 400000
}
],
"message": "",
"success": true
}
```
### 使用场景示例
```bash 获取所有大语言模型 theme={null}
GET https://aihubmix.com/api/v1/models?type=llm
```
```bash 获取适合编程的模型,按上下文长度排序 theme={null}
GET https://aihubmix.com/api/v1/models?tag=coding&sort_by=context_length&sort_order=desc
```
```bash 搜索特定模型 theme={null}
GET https://aihubmix.com/api/v1/models?model=gpt-5
```
```bash 复合条件查询 theme={null}
GET https://aihubmix.com/api/v1/models?type=llm&modalities=text,image&features=function_calling&sort_by=model_ratio&sort_order=asc
```
```bash 编程模型智能排序 theme={null}
GET https://aihubmix.com/api/v1/models?sort_by=coding
```
> **说明**:在使用编程模型智能排序时,系统会优先展示包含 `coding` 标签的模型,其他模型按默认顺序排列。
### 性能优化
#### 缓存机制
* **缓存策略**:HTTP缓存,缓存时长300秒(5分钟)
* **缓存控制**:`Cache-Control: public, max-age=300, stale-while-revalidate=300`
* **内容验证**:支持ETag内容哈希验证
#### 缓存使用示例
```bash theme={null}
# 使用ETag进行条件请求
curl -H "If-None-Match: \"abc123...\"" \
https://aihubmix.com/api/v1/models
```
> 如果内容未更新,服务器返回 `304 Not Modified` 状态码。
### 错误处理
```json 400 请求参数错误 theme={null}
{
"success": false,
"message": "请求参数格式错误"
}
```
```json 500 服务器内部错误 theme={null}
{
"success": false,
"message": "服务器内部错误,请稍后重试"
}
```
### 重要说明
1. **数据完整性**:此接口返回所有符合条件的模型,不进行分页处理
2. **类型兼容性**:支持新旧类型标识的自动映射
* `t2t` ↔ `llm`
* `t2i` ↔ `image_generation`
* `t2v` ↔ `video`
* `reranking` ↔ `rerank`
3. **筛选逻辑**:多个筛选条件之间为逻辑与(AND)关系
4. **排序规则**:未指定排序方式时,默认按系统预设顺序排列
***
## 旧版本接口
> ⚠️ **注意**:以下为旧版本接口,建议优先使用新版本接口以获得更好的性能和功能体验。
### 获取模型列表
端点(Endpoint): `GET /v1/models`
* 有用户登录获取用户分组下的可用列表,无用户登录获取 default 分组下的可用列表。
* header 中有 Authorization 字段则查询 key 对应的 token 下配置的模型列表。
**返回示例:**
```json theme={null}
{
"data": [
{
"id": "gpt-4o-mini",
"object": "model",
"created": 1626777600,
"owned_by": "OpenAI",
"permission": [
{
"id": "modelperm-LwHkVFn8AcMItP432fKKDIKJ",
"object": "model_permission",
"created": 1626777600,
"allow_create_engine": true,
"allow_sampling": true,
"allow_logprobs": true,
"allow_search_indices": false,
"allow_view": true,
"allow_fine_tuning": false,
"organization": "*",
"group": null,
"is_blocking": false
}
],
"root": "gpt-4o-mini",
"parent": null
}
]
}
```
### 返回结果
| 状态码 | 状态码含义 | 说明 | 数据模型 |
| --- | ----- | ---- | ------ |
| 200 | OK | none | Inline |
### 返回数据结构
状态码 **200**
| 名称 | 类型 | 必选 | 约束 | 中文名 | 说明 |
| -------------------------- | -------------- | ---- | ---- | ----- | ---- |
| » data | \[object] | true | none | | none |
| »» id | string | true | none | 模型 ID | none |
| »» object | string | true | none | model | none |
| »» created | integer | true | none | 创建时间 | none |
| »» owned\_by | string | true | none | 开发者 | none |
| »» permission | \[object]¦null | true | none | | none |
| »»» id | string | true | none | | none |
| »»» object | string | true | none | | none |
| »»» created | integer | true | none | | none |
| »»» allow\_create\_engine | boolean | true | none | | none |
| »»» allow\_sampling | boolean | true | none | | none |
| »»» allow\_logprobs | boolean | true | none | | none |
| »»» allow\_search\_indices | boolean | true | none | | none |
| »»» allow\_view | boolean | true | none | | none |
| »»» allow\_fine\_tuning | boolean | true | none | | none |
| »»» organization | string | true | none | | none |
| »»» group | null | true | none | | none |
| »»» is\_blocking | boolean | true | none | | none |
| »» root | string | true | none | 模型名称 | none |
| »» parent | null | true | none | 父节点 | none |
### 获取模型信息
端点(Endpoint):`GET /v1/models/:model`
### 请求参数
| 名称 | 位置 | 类型 | 必选 | 说明 |
| ----- | ---- | ------ | -- | ----- |
| model | path | string | 是 | 模型 ID |
**返回示例:**
```json theme={null}
200 Response
```
```json theme={null}
{
"id": "string",
"object": "string",
"created": 0,
"owned_by": "string",
"permission": [
{
"id": "string",
"object": "string",
"created": 0,
"allow_create_engine": true,
"allow_sampling": true,
"allow_logprobs": true,
"allow_search_indices": true,
"allow_view": true,
"allow_fine_tuning": true,
"organization": "string",
"group": null,
"is_blocking": true
}
],
"root": "string",
"parent": null
}
```
### 返回结果
| 状态码 | 状态码含义 | 说明 | 数据模型 |
| --- | ----- | ---- | ------ |
| 200 | OK | none | Inline |
### 返回数据结构
状态码 **200**
| 名称 | 类型 | 必选 | 约束 | 中文名 | 说明 |
| ------------------------ | --------- | ----- | ---- | ----- | ---- |
| id | string | true | none | 模型 ID | none |
| object | string | true | none | model | none |
| created | integer | true | none | 创建时间 | none |
| owned\_by | string | true | none | 开发者 | none |
| permission | \[object] | true | none | | none |
| » id | string | false | none | | none |
| » object | string | false | none | | none |
| » created | integer | false | none | | none |
| » allow\_create\_engine | boolean | false | none | | none |
| » allow\_sampling | boolean | false | none | | none |
| » allow\_logprobs | boolean | false | none | | none |
| » allow\_search\_indices | boolean | false | none | | none |
| » allow\_view | boolean | false | none | | none |
| » allow\_fine\_tuning | boolean | false | none | | none |
| » organization | string | false | none | | none |
| » group | null | false | none | | none |
| » is\_blocking | boolean | false | none | | none |
| root | string | true | none | 模型名称 | none |
| parent | null | true | none | 父节点 | none |
***
更新时间:2026-06-01
# Gemini 新「智绘」
Source: https://docs.aihubmix.com/cn/api/Multimodal-Interaction-with-Gemini
Gemini 绘图和视频生成指引
## Imagen 绘图
Imagen 是 Google 推出的先进图像生成 AI 模型系列,能够根据文本提示创建高质量、逼真的图像。本指南将帮助您了解如何使用 Imagen 系列 API 生成图像,包括参数设置、模型选择和代码示例。
可用模型列表:
* `imagen-4.0-generate-001`:最新的正式版
* `imagen-4.0-ultra-generate-001`:更高级的 ultra 正式版
* `imagen-4.0-fast-generate-001`:快速版本
* `imagen-4.0-fast-generate-preview-06-06`:快速版本预览版
* `imagen-3.0-generate-002`:3.0 正式版
1. 目前 Imagen 仅支持英文提示词(prompt),集成时建议增加自动翻译,让用户能够无障碍使用
2. 绘制大量文本的表现不稳定,建议只绘制重点关键词
3. 抢先体验期间,Imagen 系列模型同价,后续可能会按官方正式价格调整。
### 模型参数
Imagen 目前仅支持英文提示词,并提供以下参数:
* **numberOfImages**: 要生成的图像数量,范围从 1 到 4(含)。默认值为 4。另外注意 `imagen-4.0-ultra-generate-001` 单次只能生成 1 张。
* **aspectRatio**: 更改生成图像的宽高比。支持的值有 "1:1"、"3:4"、"4:3"、"9:16" 和 "16:9"。默认值为 "1:1"。
* **personGeneration**: 允许模型生成人物图像。支持以下值:
* "DONT\_ALLOW": 阻止生成人物图像。
* "ALLOW\_ADULT": 生成成人图像,但不生成儿童图像。这是默认值。
### 费率
使用 Imagen API 生成图像的费用如下:
* imagen-4-ultra:\$0.06/张
* imagen-4:\$0.04/张
* imagen-4-fast:\$0.02/张
* imagen-3:\$0.03/张
请注意,每次调用可以生成 1-4 张图像,费用将按实际生成的图像数量计算。
### 调用示例
以下是使用 Imagen 生成图像的 Python 调用示例:
```py Imagen theme={null}
import os
import time
from google import genai
from google.genai import types
from PIL import Image
from io import BytesIO
client = genai.Client(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"},
)
# 目前只支持英文 prompt,绘制大量文本的表现较差
response = client.models.generate_images(
model='imagen-4.0-fast-generate-001',
prompt='A minimalist logo for a LLM router market company on a solid white background. trident in a circle as the main symbol, with ONLY text \'InferEra\' below.',
config=types.GenerateImagesConfig(
number_of_images=1,
aspect_ratio="1:1", # supports "1:1", "9:16", "16:9", "3:4", or "4:3".
)
)
script_dir = os.path.dirname(os.path.abspath(__file__))
output_dir = os.path.join(script_dir, "output")
os.makedirs(output_dir, exist_ok=True)
# 生成时间戳作为文件名前缀,避免文件名冲突
timestamp = int(time.time())
# 保存并显示生成的图片
if response and hasattr(response, 'generated_images') and response.generated_images:
for i, generated_image in enumerate(response.generated_images):
try:
image = Image.open(BytesIO(generated_image.image.image_bytes))
image.show()
file_name = f"imagen3_{timestamp}_{i+1}.png"
file_path = os.path.join(output_dir, file_name)
image.save(file_path)
print(f"图片已保存至:{file_path}")
except Exception as e:
print(f"处理图片 {i+1} 时出错:{e}")
else:
print("错误:未收到有效的图片响应")
print(f"响应类型:{type(response)}")
if response:
print(f"响应属性:{dir(response)}")
if hasattr(response, 'generated_images'):
print(f"generated_images 值:{response.generated_images}")
else:
print("响应为空,请检查 API 密钥和网络连接")
```
### 提示词技巧
创建有效的提示词对于获得理想的图像至关重要:
* 使用详细的描述,包括主题、风格、光照、角度等。
* 指定艺术风格(如电影感、写实主义、动漫风格等)。
* 包含技术细节(如 DSLR、高清、细节丰富等)。
* 避免负面或违禁内容。
* **避免在提示词中包含大量文本**,仅使用重点关键词以获得更稳定的结果。
* 关键词包含 `girl` 时容易触发 TypeError: 'NoneType' object is not iterable 报错,不推荐用于人物绘制
## Gemini 2.5 Flash 图像生成
Gemini 也提供了图像生成能力,作为一种替代方案。与 Imagen 系列相比,Gemini 的图像生成更适合于需要上下文理解和推理的场景,而非追求极致的艺术表现和视觉质量。
* 更高的视觉质量 → 相比早前的 exp 版,图像更锐利、更丰富、更清晰。
* 更准确的文本呈现 → 生成的视觉中,文本更加精准、干净、易读。
* 显著减少过滤拦截 → 得益于更智能、宽松的过滤机制,创作时几乎不再被打断。
**说明:**
* 模型 id:`gemini-2.5-flash-image-preview` ,社交媒体上的别名是`nano-banana`
* 费率(输入→输出):Text: \$0.3→\$2.5/M tokens; Image: \$0.3→\$30/M tokens
* 需要新增参数来体验新特性 `"modalities":["text","image"]`
* 图片以 Base64 编码形式传递与输出
* 输出图片的默认尺寸为 1024\*1024px,折合 1290 Tokens
* python 调用需要最新的 openai sdk 支持,请先运行 `pip install -U openai`
* Aihubmix 平台支持 gemini 原生与 OpenAI 兼容则 2 种请求格式
* 了解更多请访问 [Gemini 官方文档](https://ai.google.dev/gemini-api/docs/image-generation)
`gemini-2.0-flash-preview-image-generation` 已经正式升级为 `gemini-2.5-flash-image-preview`,让你的创作流程更流畅、更精彩。
**输入参考结构:**
```json theme={null}
"modalities": ["text","image"]
{
"model": "gemini-2.5-flash-image-preview",
"messages": [
{
"role": "user",
"content": "生成一幅山水画,并给出一首诗词描述"
}
],
"modalities":["text","image"], //需要添加 image
"temperature": 0.7
}'
```
**输出参考结构:**
```json theme={null}
"choices":
[
{
"index": 0,
"message":
{
"role": "assistant",
"content": "Hello! How can I assist you today?",
"refusal": null,
"multi_mod_content": //📍 新增
[
{
"text": "",
"inlineData":
{
"data":"base64 str",
"mimeType":"png"
}
},
{
"text": "hello",
"inlineData":
{
}
}
],
"annotations":
[]
},
"logprobs": null,
"finish_reason": "stop"
}
],
```
### 图文生成
Iuput:text
Output:text + image
```shell Curl theme={null}
IMG_PATH="/your_path/image.jpg"
if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
B64FLAGS="--input"
else
B64FLAGS="-w0"
fi
IMG_BASE64=$(base64 "$B64FLAGS" "$IMG_PATH" 2>&1)
curl https://aihubmix.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-d '{
"model": "gemini-2.5-flash-image-preview",
"messages": [
{
"role": "user",
"content": [
{
"type":"text",
"text":"describe the image with a concise and engaging paragraph, then fill color as children's crayon style"
},
{
"type": "image_url",
"image_url": {
"url": "data:image/jpeg;base64,'$IMG_BASE64'"
}
}
]
}
],
"modalities": ["text","image"],
"temperature": 0.7
}' \
| grep -o '"data":"[^"]*"' \
| cut -d'"' -f4 \
| base64 --decode > /your_path/imageGen.jpg
```
```py OpenAI Python theme={null}
import os
from openai import OpenAI
from PIL import Image
from io import BytesIO
import base64
client = OpenAI(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com/v1",
)
# Using text-only input
response = client.chat.completions.create(
model="gemini-2.5-flash-image-preview",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "generate an adorable mermaid in the sea, bold outline, chibi cartoon, in the style of Children coloring book, B&W, HD",
}
],
},
],
modalities=["text", "image"],
temperature=0.7,
)
try:
# Print basic response information
print(f"Creation time: {response.created}")
print(f"Token usage: {response.usage.total_tokens}")
# Check if multi_mod_content field exists
if (
hasattr(response.choices[0].message, "multi_mod_content")
and response.choices[0].message.multi_mod_content is not None
):
print("\nResponse content:")
for part in response.choices[0].message.multi_mod_content:
if "text" in part and part["text"] is not None:
print(part["text"])
# Process image content
elif "inline_data" in part and part["inline_data"] is not None:
print("\n🖼️ [Image content received]")
image_data = base64.b64decode(part["inline_data"]["data"])
mime_type = part["inline_data"].get("mime_type", "image/png")
print(f"Image type: {mime_type}")
image = Image.open(BytesIO(image_data))
image.show()
# Save image
output_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "output")
os.makedirs(output_dir, exist_ok=True)
output_path = os.path.join(output_dir, "generated_image.png")
image.save(output_path)
print(f"✅ Image saved to: {output_path}")
else:
print("No valid multimodal response received, check response structure")
except Exception as e:
print(f"Error processing response: {str(e)}")
```
```py Gemini Python theme={null}
import mimetypes
from google import genai
from google.genai import types
import os
def save_binary_file(file_name, data):
f = open(file_name, "wb")
f.write(data)
f.close()
print(f"File saved to to: {file_name}")
def generate():
client = genai.Client(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"},
)
model = "gemini-2.5-flash-image-preview"
contents = [
types.Content(
role="user",
parts=[
types.Part.from_text(text="""generate image: an adorable mermaid in the sea, bold outline, chibi cartoon, in the style of Children coloring book, super cute, B&W, HD"""),
],
),
]
generate_content_config = types.GenerateContentConfig(
response_modalities=[
"IMAGE",
"TEXT",
],
)
file_index = 0
for chunk in client.models.generate_content_stream(
model=model,
contents=contents,
config=generate_content_config,
):
if (
chunk.candidates is None
or chunk.candidates[0].content is None
or chunk.candidates[0].content.parts is None
):
continue
if chunk.candidates[0].content.parts[0].inline_data and chunk.candidates[0].content.parts[0].inline_data.data:
file_name = f"ENTER_FILE_NAME_{file_index}"
file_index += 1
inline_data = chunk.candidates[0].content.parts[0].inline_data
data_buffer = inline_data.data
file_extension = mimetypes.guess_extension(inline_data.mime_type)
save_binary_file(f"{file_name}{file_extension}", data_buffer)
else:
print(chunk.text)
if __name__ == "__main__":
generate()
```
**输出实例:**
### 图片编辑
Iuput:text + image\
Output:text + image
```py Python theme={null}
import os
from openai import OpenAI
from PIL import Image
from io import BytesIO
import base64
client = OpenAI(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com/v1",
)
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
image_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources", "filled.jpg")
if not os.path.exists(image_path):
raise FileNotFoundError(f"image {image_path} not exists")
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
base64_image = encode_image(image_path)
response = client.chat.completions.create(
model="gemini-2.5-flash-image-preview",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "describe the image with a concise and engaging paragraph, then fill color as children's crayon style",
},
{
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{base64_image}"},
},
],
},
],
modalities=["text", "image"],
temperature=0.7,
)
try:
# Print basic response information without base64 data
print(f"Creation time: {response.created}")
print(f"Token usage: {response.usage.total_tokens}")
# Check if multi_mod_content field exists
if (
hasattr(response.choices[0].message, "multi_mod_content")
and response.choices[0].message.multi_mod_content is not None
):
print("\nResponse content:")
for part in response.choices[0].message.multi_mod_content:
if "text" in part and part["text"] is not None:
print(part["text"])
# Process image content
elif "inline_data" in part and part["inline_data"] is not None:
print("\n🖼️ [Image content received]")
image_data = base64.b64decode(part["inline_data"]["data"])
mime_type = part["inline_data"].get("mime_type", "image/png")
print(f"Image type: {mime_type}")
image = Image.open(BytesIO(image_data))
image.show()
# Save image
output_dir = os.path.join(os.path.dirname(image_path), "output")
os.makedirs(output_dir, exist_ok=True)
output_path = os.path.join(output_dir, "edited_image.jpg")
image.save(output_path)
print(f"✅ Image saved to: {output_path}")
else:
print("No valid multimodal response received, check response structure")
except Exception as e:
print(f"Error processing response: {str(e)}")
```
**输出实例:**
## 选择正确的绘图模型
### 选择 Gemini 的情况:
* 需要利用世界知识和推理能力生成上下文相关的图像。
* 需要无缝混合文本和图像。
* 希望在长文本序列中嵌入准确的视觉内容。
* 希望在保持上下文的同时以对话方式编辑图像。
### 选择 Imagen 的情况:
* 图像质量、照片真实感、艺术细节或特定风格(如印象派、动漫)是首要考虑因素。
* 执行专业编辑任务,如产品背景更新或图像放大。
* 注入品牌、风格或生成标志和产品设计。
### 最佳实践
1. **优化提示词**:精心设计提示词,这是获得高质量输出的关键。
2. **实验参数**:尝试不同的宽高比和设置,找到最适合您需求的配置。
3. **批量生成**:生成多张图像以增加获得理想结果的机会。
4. **保存元数据**:将提示词和时间戳与图像一起保存,以便追踪和复制成功的结果。
5. **遵守使用政策**:确保您的使用符合 Google 的内容政策和使用条款。
## Veo 3.0 视频生成
VEO 3.0 是由 Google DeepMind 开发的最新先进视频生成模型。使用 [VEO 3.0](https://aihubmix.com/models?model=veo-3.0-generate-preview),您可以生成具有以下特点的视频:
* 从文本和图像提示中生成的质量提升
* 语音,例如对话和配音
* 音频,例如音乐和声音效果
1. 目前 VEO 3.0 仅支持英文提示词(prompt),集成时建议增加自动翻译
2. 视频通常在几分钟内生成完成,但高峰期可能需要更长时间
3. 目前不支持用图片进行对话生成的视频
### 已知限制
目前 VEO 3.0 的参数固定,无法更改:
* **分辨率**: 720p(横屏)
* **帧率**: 24fps
* **视频长度**: 8秒
### 费率
使用 VEO 3.0 API 的费用是 **\$0.675/秒**(Aihubmix 提供 10% 限时优惠)
### 调用示例
VEO 3.0 目前仅支持 curl 命令调用,采用两步处理方式:
其中:`sk-***` 换成你在 AiHubMix 生成的密钥。
```shell 步骤 1:发起生成请求 theme={null}
curl "https://aihubmix.com/gemini/v1beta/models/veo-3.0-generate-preview:predictLongRunning?key=sk-***" \
-H "Content-Type: application/json" \
-X "POST" \
-d '{
"instances":
[
{
"prompt": "A cat playing with a ball"
}
],
"parameters":
{
"numberOfVideos": 1,
"durationSeconds": 8,
"aspectRatio": "16:9",
"personGeneration": "dont_allow"
}
}'
```
```shell 步骤 2:获取生成结果 theme={null}
# 使用步骤 1 返回的 name 字段中的操作ID
curl "https://aihubmix.com/gemini/v1beta/models/veo-3.0-generate-preview/operations/ff5***?key=sk-***"
```
```py 视频提取脚本 theme={null}
import json
import base64
# 1. 读入响应 JSON 文件
with open('yourpath/response.json', 'r') as f:
data = json.load(f)
# 2. 获取 base64 编码的视频字符串
b64_str = data['response']['videos'][0]['bytesBase64Encoded']
# 3. 解码并写入 mp4 文件
with open('output.mp4', 'wb') as f:
f.write(base64.b64decode(b64_str))
print("视频已保存为 output.mp4")
```
### 返回示例
**步骤 1 返回:**
```json theme={null}
{
"name": "models/veo-3.0-generate-preview/operations/ff5***"
}
```
**步骤 2 返回(生成完成):**
```json theme={null}
{
"name": "projects/ahm-gemini-03/locations/us-central1/publishers/google/models/veo-3.0-generate-preview/operations/ff5***",
"done": true,
"response": {
"@type": "type.googleapis.com/cloud.ai.large_models.vision.GenerateVideoResponse",
"raiMediaFilteredCount": 0,
"videos": [
{
"bytesBase64Encoded": "AAA...2xl",
"mimeType": "video/mp4"
}
]
}
}
```
**步骤 2 返回(仍在处理中):**
```json theme={null}
{
"name": "projects/ahm-gemini-03/locations/us-central1/publishers/google/models/veo-3.0-generate-preview/operations/777***"
}
```
如果收到处理中的返回,请稍等几分钟后重新发送步骤 2 的请求。
**视频效果:**
### 最佳实践
1. **耐心等待**:视频生成通常需要几分钟,高峰期可能更长
2. **检查状态**:如果返回中没有 `done: true`,说明仍在处理中
3. **保存操作 ID**:确保保存步骤 1 返回的操作 ID 用于后续查询
4. **遵守使用政策**:确保您的使用符合 Google 的内容政策和使用条款
更多信息请参考 [Vertex AI 官方文档](https://cloud.google.com/vertex-ai/generative-ai/docs/video/generate-videos)
## Veo 2.0 视频生成
VEO 2.0 是 Google 推出的先进视频生成 AI 模型,能够根据文本提示创建高质量、逼真的短视频。下面的指南将帮助您了解如何使用 VEO 2.0 API 生成视频,包括参数设置、模型选择和代码示例。
1. 目前 VEO 2.0 仅支持英文提示词(prompt),集成时建议增加自动翻译,让用户能够无障碍使用
2. 生成视频需要耗时 2-3 分钟,请耐心等待
### 模型参数
VEO 2.0 提供以下参数:
* **numberOfVideos**: 要生成的视频数量,可选 1 或 2。默认值为 2。
* **aspectRatio**: 生成视频的宽高比。支持的值有 "16:9" 和 "9:16"。
* **durationSeconds**: 视频时长,可选 5 秒或 8 秒。默认值为 8 秒。
* **personGeneration**: 控制是否允许生成含人物的视频。支持以下值:
* "dont\_allow": 阻止生成含人物的视频。
* "allow\_adult": 允许生成含成人的视频,但不生成儿童视频。
### 费率
使用 VEO 2.0 API 的费用是 \$0.35/秒
### 调用示例
以下是使用 VEO 2.0 生成视频的 Python 调用示例:
```py 文生视频 theme={null}
import os
import time
from google import genai
from google.genai import types
client = genai.Client(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"},
)
operation = client.models.generate_videos(
model="veo-2.0-generate-001",
prompt="Panning wide shot of a calico kitten sleeping in the sunshine",
config=types.GenerateVideosConfig(
person_generation="dont_allow", # "dont_allow" 或 "allow_adult"
aspect_ratio="16:9", # "16:9" 或 "9:16"
number_of_videos=1, # 整数,可选 1、2,默认 2
durationSeconds=5, # 整数,可选 5、8,默认 8
),
)
# 耗时 2-3 分钟,视频时长 5-8s
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
for n, generated_video in enumerate(operation.response.generated_videos):
client.files.download(file=generated_video.video)
generated_video.video.save(f"video{n}.mp4") # 保存视频
```
```py 参考图驱动 theme={null}
import os
import time
from google import genai
from google.genai import types
def load_image(path):
with open(path, "rb") as image_file:
return image_file.read()
client = genai.Client(
api_key="sk-***", # 换成你在 AiHubMix 生成的密钥
http_options={"base_url": "https://aihubmix.com/gemini"},
)
operation = client.models.generate_videos(
model="veo-2.0-generate-001",
prompt="The waves in the background keep flowing",
image=types.Image(
mime_type="image/png",
image_bytes=load_image("img/inferbanner.png") # 使用你的图片路径
),
config=types.GenerateVideosConfig(
person_generation="dont_allow",
aspect_ratio="16:9",
numberOfVideos=1,
durationSeconds=5,
),
)
while not operation.done:
time.sleep(20)
operation = client.operations.get(operation)
for n, generated_video in enumerate(operation.response.generated_videos):
client.files.download(file=generated_video.video)
generated_video.video.save(f"video{n}.mp4")
```
### 提示词技巧
创建有效的提示词对于获得理想的视频至关重要:
* 描述清晰的场景、动作和氛围
* 指定拍摄风格(如全景、特写、跟踪镜头等)
* 描述光照条件(如阳光明媚、黄昏、室内灯光等)
* 指明主体对象及其动作(如"猫咪在阳光下睡觉")
* 避免过于复杂的叙事或快速变化的场景
* 避免负面或违禁内容
### 最佳实践
1. **简洁明了的提示词**:使用清晰、具体的描述来指导视频生成。
2. **耐心等待**:视频生成需要 2-3 分钟,请耐心等待完成。
3. **测试不同参数**:尝试不同的宽高比和时长,找到最适合您需求的设置。
4. **保存生成记录**:将提示词与生成的视频一起记录,以便追踪成功的结果。
5. **遵守使用政策**:确保您的使用符合 Google 的内容政策和使用条款。
***
更新时间:2026-06-01
# 阿里通义系列
Source: https://docs.aihubmix.com/cn/api/Qwen
## Qwen 3 系列
Qwen3 系列是阿里推出的新一代开源大模型,能力大幅跃升:在代码理解、数学推理、多语言表达、复杂推断任务上,比肩甚至超越了目前市面上的顶级模型(如 o1、DeepSeek-R1)。**它的核心突破在于引入了「思考模式」与「非思考模式」切换机制,让模型在面对不同难度任务时,自主调节推理深度,实现了速度与精度的双优平衡。** 旗舰版 Qwen3-235B 采用稀疏激活,仅用 22B 参数推理,兼顾成本和卓越能力。全系模型全面开源,涵盖从轻量到超大规模需求。
**1. 基础用法:** 用 OpenAI 兼容格式转发。\
**2. 工具调用:** 常规 Tools 调用支持 OpenAI 兼容格式(适用于 V2.5、V3),而 MCP Tools 依赖 `qwen-agent`,需要先运行指令安装依赖:`pip install -U qwen-agent mcp`。
更多细节可以参考[阿里官方文档](https://huggingface.co/Qwen/Qwen3-235B-A22B)
```py 基础用法 theme={null}
from openai import OpenAI
client = OpenAI(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com/v1",
)
completion = client.chat.completions.create(
model="Qwen/Qwen3-30B-A3B",
messages=[
{
"role": "user",
"content": "Explain the Occam's Razor concept and provide everyday examples of it"
}
],
stream=True
)
# 某些 chunk 对象可能没有 choices 属性或 choices 是一个空列表,处理方法:
for chunk in completion:
if hasattr(chunk.choices, '__len__') and len(chunk.choices) > 0:
if hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
```
```py Tools theme={null}
from openai import OpenAI
client = OpenAI(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com/v1",
)
# 定义工具
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "获取指定位置的当前天气",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市名称,如北京、上海等"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "温度单位"
}
},
"required": ["location"]
}
}
}
]
# 创建聊天完成请求,包含工具定义
completion = client.chat.completions.create(
model="Qwen/Qwen3-30B-A3B", #2.5 和 3 都支持,QwQ 不支持
messages=[
{
"role": "user",
"content": "北京今天的天气怎么样?"
}
],
tools=tools,
tool_choice="auto", # 让模型自行决定是否使用工具
stream=True
)
# 用于收集工具调用信息的字典
tool_calls = {}
# 处理流式响应
for chunk in completion:
if not hasattr(chunk.choices, '__len__') or len(chunk.choices) == 0:
continue
delta = chunk.choices[0].delta
# 处理文本内容
if hasattr(delta, 'content') and delta.content:
print(delta.content, end="")
# 处理工具调用
if hasattr(delta, 'tool_calls') and delta.tool_calls:
for tool_call in delta.tool_calls:
if not hasattr(tool_call, 'index'):
continue
idx = tool_call.index
if idx not in tool_calls:
tool_calls[idx] = {"name": "", "arguments": ""}
if hasattr(tool_call, 'function'):
if hasattr(tool_call.function, 'name') and tool_call.function.name:
tool_calls[idx]["name"] = tool_call.function.name
if hasattr(tool_call.function, 'arguments') and tool_call.function.arguments:
tool_calls[idx]["arguments"] += tool_call.function.arguments
# 完成后,打印收集到的工具调用信息
for idx, info in tool_calls.items():
if info["name"]:
print(f"\n工具调用:{info['name']}")
if info["arguments"]:
print(f"参数:{info['arguments']}")
```
```py MCP Tools theme={null}
from qwen_agent.agents import Assistant
import os
# Define LLM
llm_cfg = {
'model': 'Qwen/Qwen3-30B-A3B',
# Use a custom endpoint compatible with OpenAI API:
'model_server': 'https://aihubmix.com/v1',
'api_key': os.getenv('AIHUBMIX_API_KEY'),
# Other parameters:
# 'generate_cfg': {
# # Add: When the response content is `this is the thoughtthis is the answer;
# # Do not add: When the response has been separated by reasoning_content and content.
# 'thought_in_content': True,
# },
}
# Define Tools
tools = [
{'mcpServers': { # You can specify the MCP configuration file
'time': {
'command': 'uvx',
'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
},
"fetch": {
"command": "uvx",
"args": ["mcp-server-fetch"]
}
}
},
'code_interpreter', # Built-in tools
]
# Define Agent
bot = Assistant(llm=llm_cfg, function_list=tools)
# Streaming generation
messages = [{'role': 'user', 'content': 'https://qwenlm.github.io/blog/ Introduce the latest developments of Qwen'}]
for responses in bot.run(messages=messages):
pass
print(responses)
```
## QvQ、Qwen 2.5 和 QwQ 系列
用 OpenAI 的兼容格式转发即可,区别在于流式调用的提取,需要剔除为空的 `chunk.choices[0].delta.content`,参考如下。
**1. QvQ、Qwen 2.5 VL:** 图片识别\
**2. QwQ:** 文本任务
`Qwen/QVQ-72B-Preview` 是基于 `Qwen2-VL-72B` 构建的开源多模态推理模型,专注于视觉推理和跨模态任务。
```py Qwen 2.5 VL theme={null}
from openai import OpenAI
import base64
import os
client = OpenAI(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com/v1",
)
image_path = "yourpath/file.png"
# 读取并编码图片
def encode_image(image_path):
if not os.path.exists(image_path):
raise FileNotFoundError(f"图片文件不存在:{image_path}")
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
# 获取图片的 base64 编码
base64_image = encode_image(image_path)
# 创建包含文本和图像的消息
completion = client.chat.completions.create(
model="qwen2.5-vl-72b-instruct", #qwen2.5-vl-72b-instruct 或 Qwen/QVQ-72B-Preview
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "请详细描述这张图片,包括图片中的内容、风格和可能的含义。"},
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{base64_image}"
}
}
]
}
],
stream=True
)
for chunk in completion:
# 安全地检查是否有内容
if hasattr(chunk.choices, '__len__') and len(chunk.choices) > 0:
if hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
```
```py QwQ theme={null}
from openai import OpenAI
client = OpenAI(
api_key="sk-***", # 🔑 换成你在 AiHubMix 生成的密钥
base_url="https://aihubmix.com/v1",
)
completion = client.chat.completions.create(
model="Qwen/QwQ-32B",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "支配宇宙的元规则是什么?"}
]
}
],
stream=True
)
for chunk in completion:
if hasattr(chunk.choices, '__len__') and len(chunk.choices) > 0:
if hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
```
***
更新时间:2026-06-01
# 重排序
Source: https://docs.aihubmix.com/cn/api/Rerank
AIHubMix 提供兼容 OpenAI 标准的高效重排序方案
## 调用指引
```py 通用 Rerank theme={null}
import requests
import json
url = "https://aihubmix.com/v1/rerank"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' # 换成你在 AiHubMix 生成的密钥
}
data = {
"model": "jina-reranker-v3",
"query": "Organic skincare products for sensitive skin",
"top_n": 3,
"documents": [
"Organic skincare for sensitive skin with aloe vera and chamomile: Imagine the soothing embrace of nature with our organic skincare range, crafted specifically for sensitive skin. Infused with the calming properties of aloe vera and chamomile, each product provides gentle nourishment and protection. Say goodbye to irritation and hello to a glowing, healthy complexion.",
"New makeup trends focus on bold colors and innovative techniques: Step into the world of cutting-edge beauty with this seasons makeup trends. Bold, vibrant colors and groundbreaking techniques are redefining the art of makeup. From neon eyeliners to holographic highlighters, unleash your creativity and make a statement with every look.",
"Bio-Hautpflege für empfindliche Haut mit Aloe Vera und Kamille: Erleben Sie die wohltuende Wirkung unserer Bio-Hautpflege, speziell für empfindliche Haut entwickelt. Mit den beruhigenden Eigenschaften von Aloe Vera und Kamille pflegen und schützen unsere Produkte Ihre Haut auf natürliche Weise. Verabschieden Sie sich von Hautirritationen und genießen Sie einen strahlenden Teint.",
"Neue Make-up-Trends setzen auf kräftige Farben und innovative Techniken: Tauchen Sie ein in die Welt der modernen Schönheit mit den neuesten Make-up-Trends. Kräftige, lebendige Farben und innovative Techniken setzen neue Maßstäbe. Von auffälligen Eyelinern bis hin zu holografischen Highlightern – lassen Sie Ihrer Kreativität freien Lauf und setzen Sie jedes Mal ein Statement.",
"Cuidado de la piel orgánico para piel sensible con aloe vera y manzanilla: Descubre el poder de la naturaleza con nuestra línea de cuidado de la piel orgánico, diseñada especialmente para pieles sensibles. Enriquecidos con aloe vera y manzanilla, estos productos ofrecen una hidratación y protección suave. Despídete de las irritaciones y saluda a una piel radiante y saludable.",
"Las nuevas tendencias de maquillaje se centran en colores vivos y técnicas innovadoras: Entra en el fascinante mundo del maquillaje con las tendencias más actuales. Colores vivos y técnicas innovadoras están revolucionando el arte del maquillaje. Desde delineadores neón hasta iluminadores holográficos, desata tu creatividad y destaca en cada look.",
"针对敏感肌专门设计的天然有机护肤产品:体验由芦荟和洋甘菊提取物带来的自然呵护。我们的护肤产品特别为敏感肌设计,温和滋润,保护您的肌肤不受刺激。让您的肌肤告别不适,迎来健康光彩。",
"新的化妆趋势注重鲜艳的颜色和创新的技巧:进入化妆艺术的新纪元,本季的化妆趋势以大胆的颜色和创新的技巧为主。无论是霓虹眼线还是全息高光,每一款妆容都能让您脱颖而出,展现独特魅力。",
"敏感肌のために特別に設計された天然有機スキンケア製品: アロエベラとカモミールのやさしい力で、自然の抱擁を感じてください。敏感肌用に特別に設計された私たちのスキンケア製品は、肌に優しく栄養を与え、保護します。肌トラブルにさようなら、輝く健康な肌にこんにちは。",
"新しいメイクのトレンドは鮮やかな色と革新的な技術に焦点を当てています: 今シーズンのメイクアップトレンドは、大胆な色彩と革新的な技術に注目しています。ネオンアイライナーからホログラフィックハイライターまで、クリエイティビティを解き放ち、毎回ユニークなルックを演出しましょう。"
],
"return_documents": False
}
response = requests.post(url, headers=headers, data=json.dumps(data))
print(response.json())
```
```cURL curl theme={null}
curl https://aihubmix.com/v1/rerank \\
-H "Content-Type: application/json" \\
-H "Authorization: Bearer " \\
-d '{
"model": "jina-reranker-v3",
"query": "Organic skincare products for sensitive skin",
"top_n": 3,
"documents": [
"Organic skincare for sensitive skin with aloe vera and chamomile: Imagine the soothing embrace of nature with our organic skincare range, crafted specifically for sensitive skin. Infused with the calming properties of aloe vera and chamomile, each product provides gentle nourishment and protection. Say goodbye to irritation and hello to a glowing, healthy complexion.",
"New makeup trends focus on bold colors and innovative techniques: Step into the world of cutting-edge beauty with this seasons makeup trends. Bold, vibrant colors and groundbreaking techniques are redefining the art of makeup. From neon eyeliners to holographic highlighters, unleash your creativity and make a statement with every look.",
"Bio-Hautpflege für empfindliche Haut mit Aloe Vera und Kamille: Erleben Sie die wohltuende Wirkung unserer Bio-Hautpflege, speziell für empfindliche Haut entwickelt. Mit den beruhigenden Eigenschaften von Aloe Vera und Kamille pflegen und schützen unsere Produkte Ihre Haut auf natürliche Weise. Verabschieden Sie sich von Hautirritationen und genießen Sie einen strahlenden Teint.",
"Neue Make-up-Trends setzen auf kräftige Farben und innovative Techniken: Tauchen Sie ein in die Welt der modernen Schönheit mit den neuesten Make-up-Trends. Kräftige, lebendige Farben und innovative Techniken setzen neue Maßstäbe. Von auffälligen Eyelinern bis hin zu holografischen Highlightern – lassen Sie Ihrer Kreativität freien Lauf und setzen Sie jedes Mal ein Statement.",
"Cuidado de la piel orgánico para piel sensible con aloe vera y manzanilla: Descubre el poder de la naturaleza con nuestra línea de cuidado de la piel orgánico, diseñada especialmente para pieles sensibles. Enriquecidos con aloe vera y manzanilla, estos productos ofrecen una hidratación y protección suave. Despídete de las irritaciones y saluda a una piel radiante y saludable.",
"Las nuevas tendencias de maquillaje se centran en colores vivos y técnicas innovadoras: Entra en el fascinante mundo del maquillaje con las tendencias más actuales. Colores vivos y técnicas innovadoras están revolucionando el arte del maquillaje. Desde delineadores neón hasta iluminadores holográficos, desata tu creatividad y destaca en cada look.",
"针对敏感肌专门设计的天然有机护肤产品:体验由芦荟和洋甘菊提取物带来的自然呵护。我们的护肤产品特别为敏感肌设计,温和滋润,保护您的肌肤不受刺激。让您的肌肤告别不适,迎来健康光彩。",
"新的化妆趋势注重鲜艳的颜色和创新的技巧:进入化妆艺术的新纪元,本季的化妆趋势以大胆的颜色和创新的技巧为主。无论是霓虹眼线还是全息高光,每一款妆容都能让您脱颖而出,展现独特魅力。",
"敏感肌のために特別に設計された天然有機スキンケア製品: アロエベラとカモミールのやさしい力で、自然の抱擁を感じてください。敏感肌用に特別に設計された私たちのスキンケア製品は、肌に優しく栄養を与え、保護します。肌トラブルにさようなら、輝く健康な肌にこんにちは。",
"新しいメイクのトレンドは鮮やかな色と革新的な技術に焦点を当てています: 今シーズンのメイクアップトレンドは、大胆な色彩と革新的な技術に注目しています。ネオンアイライナーからホログラフィックハイライターまで、クリエイティビティを解き放ち、毎回ユニークなルックを演出しましょう。"
],
"return_documents": false
}'
```
## 可用模型
* bce-reranker-base
* gte-rerank-v2
* qwen3-reranker-0.6b
* qwen3-reranker-4b
* qwen3-reranker-8b
* jina-reranker-m0
* jina-colbert-v2
* jina-reranker-v3
***
更新时间:2026-06-01
# Openai Responses API 支持
Source: https://docs.aihubmix.com/cn/api/Responses-API
支持 Openai 的 Responses API 多功能接口,已经上线的功能接口如下:
* Text input:文本输入
* Image input:图文输入
* Streaming:流式调用
* Web search:搜索
* Deep research:深度研究
* Reasoning:推理深度控制,支持 4 档 (minimal / low / medium /high),其中,minimal 仅适用于 gpt-5 系列,completion 端口中参数名为 `reasoning_effort`
* Verbosity:输出篇幅,gpt-5 系列支持 3 档 (low / medium / high),其中,`gpt-5-chat` 仅支持 `medium`,completions 端口需要更新 openai 包来支持此参数
* Functions:函数调用
* image\_generation:绘图工具调用,图片生成部分按 `gpt-image-1` 计价
* Code Interpreter:代码解析器,与 gpt-5 搭配时,不支持 reasoning.effort 'minimal' 档位
* Remote MCP:MCP 调用
* Computer Use:自动操作
## 使用 (Python 调用):
与官方的 OpenAI 调用方式一致,只是替换 `api_key` 和 `base_url` 进行转发。
```py theme={null}
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # 换成你在后台生成的 Key "sk-***"
base_url="https://aihubmix.com/v1"
)
```
1. 对于推理模型,支持通过以下参数来输出推理总结,总结细节的丰富程度为 detailed > auto > None,其中 auto 为最佳平衡。
```py theme={null}
"summary": "auto"
```
2. `gpt-5-chat` 在不传入 reasoning.effort 的情况下,相当于关闭推理,适用于会话场景。
3. 深度研究模型可选:`o3-deep-research` 和 `o4-mini-deep-research`,仅支持 `responses` 端口
4. gpt-5 系列强调稳定推理和一致性输出,不再支持用于控制随机性的 `temprature` 和 `top_p` 参数,如果你需要更多自由度,可以尝试支持 `temprature` 的 `gpt-5-chat-latest`
5. 推理模型(o 系列 / gpt-5 系列)已废弃 `max_tokens`,请[使用 completion](https://platform.openai.com/docs/api-reference/chat/create) 的 `max_completion_tokens` 或 [responses](https://platform.openai.com/docs/api-reference/responses/create) 的 `max_output_tokens` 明确限定输出 token 上限。
```py gpt-5 系列 theme={null}
from openai import OpenAI
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # 换成你在后台生成的 Key "sk-***"
base_url="https://aihubmix.com/v1"
)
response = client.responses.create(
model="gpt-5", # gpt-5, gpt-5-chat-latest, gpt-5-mini, gpt-5-nano
input="Why does tarot reading work, what are the underlying principles, and what transferable methods are there? Output format: Markdown", # GPT-5 默认不使用 Markdown 格式输出,需要明确指定。
reasoning={
"effort": "minimal" # 推理深度 - Controls how many reasoning tokens the model generates before producing a response. value can be "minimal", "low", "medium", "high", default is "medium"
},
text={
"verbosity": "low" # 输出篇幅 - Verbosity determines how many output tokens are generated. value can be "low", "medium", "high", Models before GPT-5 have used medium verbosity by default.
},
stream=True
)
for event in response:
print(event)
```
```py 文本 theme={null}
from openai import OpenAI
import os
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # 换成你在后台生成的 Key "sk-***"
base_url="https://aihubmix.com/v1"
)
response = client.responses.create(
model="gpt-4o-mini", # codex-mini-latest 可用
input="Tell me a three sentence bedtime story about a unicorn."
)
print(response)
```
```py 图文 theme={null}
from openai import OpenAI
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # 换成你在后台生成的 Key "sk-***"
base_url="https://aihubmix.com/v1"
)
response = client.responses.create(
model="gpt-4o-mini", # codex-mini-latest 可用
input=[
{
"role": "user",
"content": [
{ "type": "input_text", "text": "what is in this image?" },
{
"type": "input_image",
"image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
}
]
}
]
)
print(response)
```
```py 流式 theme={null}
from openai import OpenAI
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # 换成你在后台生成的 Key "sk-***"
base_url="https://aihubmix.com/v1"
)
response = client.responses.create(
model="gpt-4o-mini", # codex-mini-latest 可用
instructions="You are a helpful assistant.",
input="Hello!",
stream=True
)
for event in response:
print(event)
```
```py 搜索 theme={null}
from openai import OpenAI
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # 换成你在后台生成的 Key "sk-***"
base_url="https://aihubmix.com/v1"
)
response = client.responses.create(
model="gpt-4o-mini", # codex-mini-latest 不支持搜索📍
tools=[{ "type": "web_search_preview" }],
input="What was a positive news story from today?",
)
print(response)
```
```py Deep Research theme={null}
from openai import OpenAI
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # 换成你在后台生成的 Key "sk-***"
base_url="https://aihubmix.com/v1",
timeout=3600
)
input_text = """
Research the economic impact of semaglutide on global healthcare systems.
Do:
- Include specific figures, trends, statistics, and measurable outcomes.
- Prioritize reliable, up-to-date sources: peer-reviewed research, health
organizations (e.g., WHO, CDC), regulatory agencies, or pharmaceutical
earnings reports.
- Include inline citations and return all source metadata.
Be analytical, avoid generalities, and ensure that each section supports
data-backed reasoning that could inform healthcare policy or financial modeling.
"""
response = client.responses.create(
model="o3-deep-research", # o4-mini-deep-research
input=input_text,
tools=[
{"type": "web_search_preview"},
{"type": "code_interpreter", "container": {"type": "auto"}},
],
)
print(response.output_text)
```
```py 推理 theme={null}
from openai import OpenAI
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # 换成你在后台生成的 Key "sk-***"
base_url="https://aihubmix.com/v1/"
)
response = client.responses.create(
model="o4-mini", # 支持 codex-mini-latest, o4-mini, o3-mini, o3, o1
input="How much wood would a woodchuck chuck?",
reasoning={
"effort": "medium", # 支持 low, medium, high
"summary": "auto" # 推理总结
}
)
print(response)
```
```py 函数调用 theme={null}
from openai import OpenAI
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # 换成你在后台生成的 Key "sk-***"
base_url="https://aihubmix.com/v1"
)
tools = [
{
"type": "function",
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["location", "unit"],
}
}
]
response = client.responses.create(
model="gpt-4o-mini", # codex-mini-latest 可用
tools=tools,
input="What is the weather like in Boston today?",
tool_choice="auto"
)
print(response)
```
```py 图片生成工具 theme={null}
from openai import OpenAI
import base64
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # 换成你在后台生成的 Key "sk-***"
base_url="https://aihubmix.com/v1"
)
response = client.responses.create(
model="gpt-4.1-mini",
input="Generate an image of gray tabby cat hugging an otter with an orange scarf",
tools=[
{
"type": "image_generation",
"background": "opaque",
"quality": "high",
}
],
)
# 保存为图片文件
image_data = [
output.result
for output in response.output
if output.type == "image_generation_call"
]
if image_data:
image_base64 = image_data[0]
with open("cat_and_otter.png", "wb") as f:
f.write(base64.b64decode(image_base64))
```
```py 代码解析器 theme={null}
from openai import OpenAI
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # 换成你在后台生成的 Key "sk-***"
base_url="https://aihubmix.com/v1"
)
instructions = """
You are a personal math tutor. When asked a math question,
write and run code using the python tool to answer the question.
"""
resp = client.responses.create(
model="gpt-4.1",
tools=[
{
"type": "code_interpreter",
"container": {"type": "auto"}
}
],
instructions=instructions,
input="I need to solve the equation 3x + 11 = 14. Can you help me?",
)
print(resp.output)
```
```py Remote MCP theme={null}
from openai import OpenAI
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # 换成你在后台生成的 Key "sk-***"
base_url="https://aihubmix.com/v1"
)
resp = client.responses.create(
model="gpt-4.1",
tools=[{
"type": "mcp",
"server_label": "deepwiki",
"server_url": "https://mcp.deepwiki.com/mcp",
"require_approval": "never",
"allowed_tools": ["ask_question"],
}],
input="What transport protocols does the 2025-03-26 version of the MCP spec (modelcontextprotocol/modelcontextprotocol) support?",
)
print(resp.output_text)
```
**注意:**
1. 最新的 \`codex-mini-latest\` 不支持搜索
2. Computer use 需要配合 Praywright 使用,建议参考[官方仓库](https://github.com/openai/openai-cua-sample-app)
已知细节问题:
* 调用用例复杂
* 截图大量,耗时久,任务成功率低
* 或触发 CAPTCHA 验证或 Cloudflare 真人验证,可能遇到无限循环
***
更新时间:2026-06-01
# 获取自动路由策略对应模型范围
Source: https://docs.aihubmix.com/cn/api/RouterEndpoints/leaderboard
GET /api/router/leaderboard
免登录获取智能路由榜单:5 大类 23 个子维度的模型评分,以及按厂商分组的在池模型池
## 请求参数
此接口为免登录开放接口,无需身份认证,前端页面与第三方可直接调用。已启用 CORS,受全局 API 限流约束。无请求参数。
## 响应参数
响应为原样 JSON 对象(不包含 `success` / `data` 包装),与前端榜单数据结构对齐。
各维度榜单。键为维度名(共 5 大类 23 个子维度,见下表),值为该维度下的模型数组,按分数降序排列。仅包含当前可被正常路由的模型;被手动剔除的模型不会出现。模型无某子维度的专属评分时,会沿维度回退链(如 `text.coding` → `text.overall`)取父维度分数参与该子维度排名。
模型名称。
模型厂商 id(小写)。可用作[获取模型厂商图标](/cn/api/RouterEndpoints/vendors)接口返回对象的键;该接口结果有 5 分钟缓存,新入池厂商可能短暂查不到,键缺失时请自行回退。
归一化分数(0–100,保留 1 位小数)。模型无该子维度专属评分时,为回退父维度分数归一化所得。
输入价格系数。为平台计费系数原始值,非美元单价,仅适合做模型间相对比较;美元单价请通过[模型管理API](/cn/api/Models-API)查询。
输出价格倍率,是相对输入价的倍数而非独立价格。模型的输出价格系数 = `pin` × `pout`,请勿用 `pout` 直接跨模型比较输出价格。
首字延迟(毫秒)。无实测数据时为 `null`。
路由模型池。键为厂商 id,值为该厂商当前在池的模型名数组(按字母序)。
在池模型总数(去重后)。
## 维度列表
| 大类 | 子维度 |
| ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 文本(11) | `text.overall`、`text.coding`、`text.math`、`text.instruction_following`、`text.longer_query`、`text.language.chinese`、`text.language.english`、`text.occupational.software_it`、`text.occupational.mathematical`、`text.occupational.legal`、`text.occupational.medicine` |
| 视觉(6) | `vision.overall`、`vision.ocr`、`vision.diagram`、`vision.homework`、`vision.chinese`、`vision.english` |
| 网页开发(4) | `code_webdev.overall`、`code_webdev.html`、`code_webdev.react`、`code_image_to_webdev.overall` |
| 搜索(1) | `search.overall` |
| 文档(1) | `document.overall` |
以上 23 个子维度是[模型智能路由](/cn/api/llm-router)内置 30+ 路由维度中面向公众展示的子集,不含图像/视频生成类维度。
```json 200 theme={null}
{
"dims": {
"text.coding": [
{ "m": "claude-opus-4-6", "v": "anthropic", "s": 85.4, "pin": 2.5, "pout": 5, "lat": 822 }
]
},
"pool": {
"anthropic": ["claude-opus-4-6"]
},
"poolCount": 37
}
```
***
更新时间:2026-07-13
# 获取模型厂商图标
Source: https://docs.aihubmix.com/cn/api/RouterEndpoints/vendors
GET /api/router/vendors
免登录按模型厂商返回显示名与 icon,供榜单和模型卡片渲染
## 请求参数
此接口为免登录开放接口,无需身份认证,前端页面与第三方可直接调用。已启用 CORS,受全局 API 限流约束。无请求参数。
## 响应参数
响应为原样 JSON 对象:键为厂商 id(对应[获取自动路由策略对应模型范围](/cn/api/RouterEndpoints/leaderboard)条目中的 `v` 字段),值为该厂商的展示信息。仅包含当前模型池内的厂商。
单个厂商的展示信息。
厂商显示名。无匹配的厂商元数据时回退为厂商 id。
厂商 logo 的 URL。可能为空字符串,此时前端应自行回退(如首字母占位块)。
服务端结果缓存 5 分钟:模型池刚更新时,新入池厂商可能延迟最多 5 分钟才出现在本接口结果中,请对缺失的键做回退处理。
```json 200 theme={null}
{
"anthropic": {
"name": "Anthropic",
"icon": "https://.../logo_claude.svg"
},
"deepseek": {
"name": "DeepSeek",
"icon": "https://.../logo_deepseek.svg"
}
}
```
***
更新时间:2026-07-13
# STT 语音转文本
Source: https://docs.aihubmix.com/cn/api/STT
使用 Whisper 模型将音频文件转换为文本,支持转录和翻译功能
## 介绍
语音转文本(STT)API 基于 OpenAI 的 Whisper 模型,可以将音频文件转换为文本。支持多种用途:
* 音频文件转录为文本
* 多语言音频翻译为英文
* 支持多种音频格式输入
* 提供多种输出格式选择
**可用模型列表:**
* **whisper-large-v3** —— 最新的大型 Whisper 模型,支持多语言,中文识别需配合 prompt 和低 temperature 使用
* **whisper-1** —— 初代 Whisper 模型,稳定可靠,支持多语言
* **distil-whisper-large-v3-en** —— 蒸馏模型,处理速度更快,但准确性略低,建议配合低 temperature 值
**性能建议:**
* 对于中文音频,推荐使用 `whisper-large-v3` 模型,配合适当的 prompt 和较低的 temperature 值(如 0.2)以减少幻觉
* 对于英文音频或需要快速处理,可使用 `distil-whisper-large-v3-en` 模型
* 支持的音频格式:mp3, mp4, mpeg, mpga, m4a, wav, webm
* 文件大小限制:最大 25MB
## 模型调用方式
### 语音转录(Transcriptions)
使用 `/v1/audio/transcriptions` 端点,通过 `client.audio.transcriptions.create()` 方法调用,将音频转录为原始语言的文本。
### 语音翻译(Translations)
使用 `/v1/audio/translations` 端点,通过 `client.audio.translations.create()` 方法调用,将音频翻译为英文文本。
### 请求参数
#### 转录参数(Transcriptions)
要转录的音频文件对象,支持格式:mp3, mp4, mpeg, mpga, m4a, wav, webm,最大 25MB
要使用的模型 ID。可选值:`whisper-large-v3`、`whisper-1`、`distil-whisper-large-v3-en`
输入音频的语言,ISO-639-1 格式(如 'en', 'zh')。指定语言可以提高准确性和延迟
可选的文本提示,用于指导模型的风格或继续之前的音频片段。提示应该匹配音频语言
转录输出格式。可选值:`json`(默认)、`text`、`srt`、`verbose_json`、`vtt`
采样温度,介于 0 和 1 之间。较高的值会使输出更随机,较低的值会使其更集中和确定。默认为 0
时间戳粒度。可选值:`word`、`segment`。仅当 response\_format 为 verbose\_json 时可用
#### 翻译参数(Translations)
要翻译的音频文件对象,支持格式同转录
要使用的模型 ID,同转录参数
可选的英文文本提示,用于指导翻译风格
翻译输出格式,同转录参数
采样温度,同转录参数
## 使用方法
```shell Curl 转录 theme={null}
curl https://aihubmix.com/v1/audio/transcriptions \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: multipart/form-data" \
-F file="@/path/to/file/audio.mp3" \
-F model="whisper-large-v3" \
-F response_format="text" \
-F temperature="0.2"
```
```shell Curl 翻译 theme={null}
curl https://aihubmix.com/v1/audio/translations \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: multipart/form-data" \
-F file="@/path/to/file/audio.mp3" \
-F model="whisper-large-v3" \
-F prompt="autocorrect, clean up the stammer, and translate to english" \
-F response_format="text" \
-F temperature="0.2"
```
```py 语音转录 theme={null}
from openai import OpenAI
import os
client = OpenAI(
api_key="sk-***", # 替换为你的 AiHubMix API 密钥
base_url="https://aihubmix.com/v1"
)
# 打开音频文件
audio_file = open("path/to/audio.mp3", "rb")
# 转录音频
transcript = client.audio.transcriptions.create(
model="whisper-large-v3",
file=audio_file,
language="zh", # 指定中文以提高准确性
prompt="Please transcribe the audio accurately, paying attention to punctuation and grammar.",
response_format="text",
temperature=0.2 # 降低随机性以减少幻觉
)
print(transcript)
```
```py 语音翻译 theme={null}
from openai import OpenAI
import os
client = OpenAI(
api_key="sk-***", # 替换为你的 AiHubMix API 密钥
base_url="https://aihubmix.com/v1"
)
# 打开音频文件
audio_file = open("path/to/audio.m4a", "rb")
# 翻译音频为英文
translation = client.audio.translations.create(
model="whisper-large-v3",
file=audio_file,
prompt="autocorrect, clean up the stammer, and translate to english",
response_format="text",
temperature=0.2
)
print(translation)
```
```py 详细输出格式 theme={null}
from openai import OpenAI
import os
client = OpenAI(
api_key="sk-***", # 替换为你的 AiHubMix API 密钥
base_url="https://aihubmix.com/v1"
)
audio_file = open("path/to/audio.wav", "rb")
# 获取详细的转录结果,包含时间戳
transcript = client.audio.transcriptions.create(
model="whisper-large-v3",
file=audio_file,
response_format="verbose_json",
timestamp_granularities=["word"],
temperature=0.2
)
# 输出包含单词级时间戳的结果
print(f"Text: {transcript.text}")
print(f"Language: {transcript.language}")
for word in transcript.words:
print(f"'{word.word}' at {word.start}s - {word.end}s")
```
```py SRT 字幕格式 theme={null}
from openai import OpenAI
import os
client = OpenAI(
api_key="sk-***", # 替换为你的 AiHubMix API 密钥
base_url="https://aihubmix.com/v1"
)
audio_file = open("path/to/video_audio.mp4", "rb")
# 生成 SRT 字幕文件
srt_transcript = client.audio.transcriptions.create(
model="whisper-large-v3",
file=audio_file,
response_format="srt",
language="en",
temperature=0.2
)
# 保存为 .srt 文件
with open("subtitles.srt", "w", encoding="utf-8") as f:
f.write(srt_transcript)
print("SRT 字幕文件已生成")
```
## 响应格式
### JSON 格式(默认)
```json theme={null}
{
"text": "This is the transcribed text content"
}
```
### 详细 JSON 格式(verbose\_json)
```json theme={null}
{
"task": "transcribe",
"language": "chinese",
"duration": 8.470000267028809,
"text": "This is the transcribed text content",
"segments": [
{
"id": 0,
"seek": 0,
"start": 0.0,
"end": 8.470000267028809,
"text": " This is the transcribed text content",
"tokens": [50364, 50365, 50365, 50365],
"temperature": 0.2,
"avg_logprob": -0.9929364013671875,
"compression_ratio": 0.8888888888888888,
"no_speech_prob": 0.0963134765625
}
]
}
```
### 文本格式(text)
```
This is the transcribed text content
```
### SRT 格式
```srt theme={null}
1
00:00:00,000 --> 00:00:08,470
This is the transcribed text content
```
### VTT 格式
```vtt theme={null}
WEBVTT
00:00:00.000 --> 00:00:08.470
This is the transcribed text content
```
## 最佳实践
1. **中文音频处理**:使用 `whisper-large-v3` 模型,设置 `language="zh"`,`temperature=0.2`,并提供合适的中文 prompt
2. **英文音频处理**:可使用 `distil-whisper-large-v3-en` 获得更快的处理速度
3. **噪音处理**:使用 prompt 提示模型忽略背景噪音或清理结巴等问题
4. **长音频处理**:API 自动将长音频分段处理,建议预处理音频质量以获得最佳效果
5. **时间戳需求**:需要精确时间戳时使用 `verbose_json` 格式和 `timestamp_granularities`
6. **字幕制作**:直接使用 `srt` 或 `vtt` 格式输出,无需额外处理
***
更新时间:2026-06-01
# Status
Source: https://docs.aihubmix.com/cn/api/Status
## 页面介绍
AIHubMix Status Page 是用于展示平台系统运行状态的官方页面,旨在提升平台透明度与服务可靠性。通过该页面,您可以实时了解 AIHubMix 各项核心服务的运行情况,以及历史事件记录与处理进展。
访问地址:\
[https://status.aihubmix.com/](https://status.aihubmix.com/)
## 功能说明
### 实时系统状态
Status 页面展示当前各项核心服务组件的运行状态,包括:
* OpenAI Chat 兼容 API 服务可用性
* Gemini 兼容 API 服务可用性
* Claude 兼容 API 服务可用性
* AIHubMix 官网稳定性
* 模型管理 API 服务可用性
当系统运行正常时,将显示为 Operational 状态;若发生异常,将显示对应的 Incident 或 Degraded Performance 信息。
***
### 事件(Incident)说明
当出现服务异常或性能波动时,Status 页面将发布 Incident 公告,包含:
* 事件开始时间
* 影响范围
* 当前状态(Investigating / Identified / Monitoring / Resolved)
* 修复进展更新
* 最终解决时间
所有事件均会保留历史记录,便于您追溯与核查。
***
### 历史记录查询
您可查看历史事件记录,了解:
* 过去服务中断情况
* 处理时长
* 问题类型
* 系统稳定性表现
***
### 订阅更新通知
Status Page 支持订阅更新功能,您可通过邮箱订阅,以便在发生 Incident 时自动接收通知。
通知内容包括:
* 新 Incident 发布提醒
* 状态变更通知
* 事件解决确认
***
## 状态等级说明
| 状态 | 说明 |
| :------------------- | :----------- |
| Operational | 服务运行正常 |
| Degraded Performance | 性能下降,但服务仍可使用 |
| Partial Outage | 部分功能不可用 |
| Major Outage | 核心服务中断 |
| Maintenance | 计划维护中 |
***
更新时间:2026-06-01
# 结构化输出
Source: https://docs.aihubmix.com/cn/api/Structured-Output
通过 JSON Schema 约束模型输出格式(Structured Outputs),支持 OpenAI、Anthropic Claude、Gemini 等模型的 response_format 与 output_config.format,含自动降级与跨协议转换。
## 能力概述
结构化输出(Structured Outputs)让模型的回复严格遵循你定义的 JSON Schema,确保返回值可以直接被程序解析,无需正则或后处理。
与在 prompt 中要求模型"请返回 JSON"不同,结构化输出基于**受约束解码(Constrained Decoding)**:上游将 JSON Schema 编译为语法规则,在推理过程中逐 token 约束生成,模型**不可能**产出违反 Schema 的内容。
典型场景:
* 从非结构化文本中提取实体和字段
* 分类 / 打标签 / 情感分析
* 多步推理中间结果的标准化传递
* Agent 工具调用参数的强类型约束
## 各协议参数对照
三种协议的参数名不同,但底层机制一致:模型输出严格匹配你提供的 JSON Schema。
| 协议 | 参数 | 支持模型 |
| ---------------------------------- | ------------------------------------------ | --------------------------------------- |
| OpenAI Chat `/v1/chat/completions` | `response_format.type: "json_schema"` | Claude 4.5+、GPT-4o / GPT-5 系列、Gemini 系列 |
| Anthropic Messages `/v1/messages` | `output_config.format.type: "json_schema"` | Claude 4.5+(直连 / Vertex / Bedrock) |
| OpenAI Responses `/v1/responses` | `text.format.type: "json_schema"` | 随上游模型能力 |
***
## 快速开始
### OpenAI 协议(推荐)
适用于所有支持结构化输出的模型,跨厂商通用。
```python Python theme={null}
from openai import OpenAI
client = OpenAI(
api_key="",
base_url="https://aihubmix.com/v1",
)
response = client.chat.completions.create(
model="claude-sonnet-5",
messages=[
{"role": "user", "content": "Extract the following: John, 28, San Francisco"}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "person_info",
"strict": True,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"city": {"type": "string"}
},
"required": ["name", "age", "city"],
"additionalProperties": False
}
}
}
)
import json
data = json.loads(response.choices[0].message.content)
print(data)
# {"name": "John", "age": 28, "city": "San Francisco"}
```
```typescript Node.js theme={null}
import OpenAI from "openai";
const client = new OpenAI({
apiKey: "",
baseURL: "https://aihubmix.com/v1",
});
const response = await client.chat.completions.create({
model: "claude-sonnet-5",
messages: [
{ role: "user", content: "Extract the following: John, 28, San Francisco" },
],
response_format: {
type: "json_schema",
json_schema: {
name: "person_info",
strict: true,
schema: {
type: "object",
properties: {
name: { type: "string" },
age: { type: "integer" },
city: { type: "string" },
},
required: ["name", "age", "city"],
additionalProperties: false,
},
},
},
});
const data = JSON.parse(response.choices[0].message.content);
console.log(data);
```
```bash cURL theme={null}
curl https://aihubmix.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer " \
-d '{
"model": "claude-sonnet-5",
"messages": [
{"role": "user", "content": "Extract the following: John, 28, San Francisco"}
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "person_info",
"strict": true,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"city": {"type": "string"}
},
"required": ["name", "age", "city"],
"additionalProperties": false
}
}
}
}'
```
### 使用其他模型(GLM-5.2 示例)
同一套 OpenAI 协议参数适用于所有支持结构化输出的模型,切换 `model` 即可。
```python Python theme={null}
from openai import OpenAI
client = OpenAI(
api_key="",
base_url="https://aihubmix.com/v1",
)
response = client.chat.completions.create(
model="glm-5.2",
messages=[
{"role": "user", "content": "Extract the following: John, 28, San Francisco"}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "person_info",
"strict": True,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"city": {"type": "string"}
},
"required": ["name", "age", "city"],
"additionalProperties": False
}
}
}
)
import json
data = json.loads(response.choices[0].message.content)
print(data)
# {"name": "John", "age": 28, "city": "San Francisco"}
```
### Claude 原生协议
使用 Anthropic SDK 直接调用,参数为 `output_config.format`。
```python Python theme={null}
import anthropic
client = anthropic.Anthropic(
api_key="",
base_url="https://aihubmix.com",
)
response = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "Extract the following: John, 28, San Francisco"}
],
output_config={
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"city": {"type": "string"}
},
"required": ["name", "age", "city"],
"additionalProperties": False
}
}
}
)
import json
data = json.loads(response.content[0].text)
print(data)
```
```bash cURL theme={null}
curl https://aihubmix.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: " \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-sonnet-5",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Extract the following: John, 28, San Francisco"}
],
"output_config": {
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"city": {"type": "string"}
},
"required": ["name", "age", "city"],
"additionalProperties": false
}
}
}
}'
```
***
## Schema 编写要点
### 必需字段
所有 `object` 类型必须显式声明 `additionalProperties: false`,否则部分上游会拒绝请求。
```json theme={null}
{
"type": "object",
"properties": {
"name": { "type": "string" },
"score": { "type": "number" }
},
"required": ["name", "score"],
"additionalProperties": false
}
```
### 嵌套对象
嵌套的 `object` 同样需要 `additionalProperties: false`:
```json theme={null}
{
"type": "object",
"properties": {
"user": {
"type": "object",
"properties": {
"name": { "type": "string" },
"email": { "type": "string" }
},
"required": ["name", "email"],
"additionalProperties": false
}
},
"required": ["user"],
"additionalProperties": false
}
```
### 跨协议 Schema 差异
| 特性 | OpenAI 协议 | Anthropic 协议 |
| -------------------------------- | ------------ | ----------------- |
| `name` 字段 | 必需 | 不支持(网关跨协议调用时自动处理) |
| `strict` 字段 | 可选,推荐 `true` | 不支持 |
| 数值约束 (`minimum`, `maximum` 等) | 支持 | 不支持(网关自动清理,不影响请求) |
| 字符串约束 (`minLength`, `maxLength`) | 支持 | 不支持(网关自动清理) |
使用 OpenAI 协议调用 Claude 模型时,网关会自动转换 Schema 格式并清理不兼容的关键字,无需手动适配。
***
## 自动降级机制
网关默认为所有请求开启结构化输出的自动降级保护。当模型或平台不支持时,网关**不会返回错误**,而是自动剥离 Schema 约束并在响应头中标记降级原因。你的请求仍然会得到正常的模型回复,只是输出不受 Schema 强制约束。
这意味着你可以放心地在客户端统一启用结构化输出,而无需针对每个模型做兼容判断:
* **多模型切换无忧**:同一套代码在 Claude、GPT、Gemini、GLM 之间切换模型时,即使目标模型不支持结构化输出,请求也不会报错
* **兜底透明**:即使实际处理请求的模型版本不支持结构化输出,请求仍然正常完成,仅通过响应头标记降级
* **客户端逻辑简化**:不需要维护一份"哪些模型支持结构化输出"的列表,网关已自动处理;客户端只需检查响应头决定是否需要额外解析
### 响应头
```text theme={null}
X-Structured-Output-Degraded:
```
| reason | 含义 |
| -------------------------------------- | -------------------------------------------- |
| `model_unsupported` | 该模型(或该模型在当前平台上)不支持结构化输出 |
| `json_object_unsupported_on_anthropic` | `json_object` 模式无法转换为 Anthropic 格式 |
| `json_schema_missing_schema` | 指定了 `json_schema` 类型但缺少 `schema` 字段 |
| `schema_keywords_stripped` | Schema 中的部分约束关键字被清理(如 `minimum`、`maxLength`) |
### 检测示例
```python Python theme={null}
import httpx
response = httpx.post(
"https://aihubmix.com/v1/chat/completions",
headers={
"Authorization": "Bearer ",
"Content-Type": "application/json",
},
json={
"model": "claude-sonnet-5",
"messages": [{"role": "user", "content": "Extract: John, age 28"}],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "person",
"strict": True,
"schema": {
"type": "object",
"properties": {"name": {"type": "string"}, "age": {"type": "integer"}},
"required": ["name", "age"],
"additionalProperties": False,
}
}
}
}
)
# 检查是否发生降级
degraded = response.headers.get("X-Structured-Output-Degraded")
if degraded:
print(f"结构化输出已降级:{degraded}")
# 此时模型回复仍然正常,但输出不受 Schema 强制约束
else:
import json
data = json.loads(response.json()["choices"][0]["message"]["content"])
print(data) # {"name": "John", "age": 28}
```
***
## 与 `json_object` 模式的区别
| | `json_schema` (结构化输出) | `json_object` |
| --------- | ------------------------------ | ------------- |
| 输出保证 | 严格匹配指定 Schema | 仅保证是合法 JSON |
| 字段控制 | 字段名、类型、是否必需均受约束 | 无约束 |
| 适用协议 | OpenAI / Anthropic / Responses | 仅 OpenAI 兼容协议 |
| Claude 支持 | 通过 `output_config.format` | 不支持 |
`json_object` 模式不支持转换到 Claude 原生协议。如果你通过 OpenAI 协议向 Claude 发送 `response_format: {"type": "json_object"}`,响应头会标记 `json_object_unsupported_on_anthropic` 降级。建议直接使用 `json_schema` 类型。
***
## 常见问题
**Claude 系列**(通过 Anthropic API 的 `output_config.format`):
* Opus / Sonnet / Haiku 4.5 及以上版本
* Fable / Mythos 5 及以上版本 **OpenAI 系列**(通过 `response_format`):
* GPT-4o 及以上、GPT-5 系列
**Gemini 系列**(通过 `responseSchema`):
* Gemini 2.5 及以上
可通过 [模型列表页](https://aihubmix.com/models) 查看各模型的能力标签。
会。当通过 OpenAI 协议调用 Claude 模型时,网关自动:
1. 将 `response_format` 转换为 `output_config.format`
2. 移除 Anthropic 不支持的 Schema 关键字(`minimum`、`maxLength` 等)
3. 如果有关键字被清理,响应头标记 `schema_keywords_stripped`
反向(Claude 协议调用 OpenAI 模型)同样自动转换。
可以。`output_config` 中的 `format`(结构化输出)和 `reasoning` 中的 `effort`(思考强度)是独立参数,可以同时设置:
```json theme={null}
{
"output_config": {
"format": {
"type": "json_schema",
"schema": { ... }
}
},
"reasoning": {
"effort": "high"
}
}
```
大多数 API 聚合平台在模型不支持结构化输出时会直接返回错误。AIHubMix 采用**优雅降级**策略:自动剥离不兼容的参数,正常返回模型响应,并通过 `X-Structured-Output-Degraded` 响应头告知客户端降级原因。你的应用不会因此中断。
# TTS 文本转语音
Source: https://docs.aihubmix.com/cn/api/TTS
使用 AI 模型将文本转换为自然语音,支持多种语音风格和输出格式
## 介绍
文本转语音(TTS)API 基于先进的生成 AI 模型,可以将输入的文本转换为逼真的语音音频。支持多种用途:
* 为书面博客文章配音
* 生成多种语言的语音音频
* 提供实时音频输出流
## 可用模型列表
### OpenAI 模型
* [gpt-4o-audio-preview](https://aihubmix.com/model/gpt-4o-audio-preview) —— OpenAI 最新的音频生成模型,支持对话式音频生成
* [**gpt-4o-mini-tts**](https://aihubmix.com/model/gpt-4o-mini-tts) —— 智能实时应用的首选模型,支持高级语音控制,可以通过提示词控制多种语音特性:
1. 口音 (Accent)
2. 情感范围 (Emotional range)
3. 语调 (Intonation)
4. 印象/风格 (Impressions)
5. 语速 (Speed of speech)
6. 语调 (Tone)
7. 轻声说话 (Whispering)
* [**tts-1-hd**](https://aihubmix.com/model/tts-1-hd) —— 高清音质的上一代 TTS 模型
* [**tts-1**](https://aihubmix.com/model/tts-1) —— 标准 TTS 模型,平衡质量和速度
### Gemini 模型
* [**gemini-2.5-flash-preview-tts**](https://aihubmix.com/model/gemini-2.5-flash-preview-tts) —— Gemini 快速 TTS 模型,支持单说话人和多说话人音频生成
* [**gemini-2.5-pro-preview-tts**](https://aihubmix.com/model/gemini-2.5-pro-preview-tts) —— Gemini 专业 TTS 模型,支持单说话人和多说话人音频生成
**性能建议:**
1. 为获得最快的响应时间,建议使用 `wav` 或 `pcm` 作为响应格式
2. 对于高质量音频,建议使用 `tts-1-hd`
3. 对于更快的生成速度,使用 `tts-1`
4. 对于智能语音应用,推荐使用 `gpt-4o-mini-tts`
5. 对于需要多说话人对话的场景,推荐使用 Gemini TTS 模型
## API 接口
### 请求地址
```shellscript theme={null}
POST https://aihubmix.com/v1/audio/speech
```
### 请求头
```shellscript theme={null}
Authorization: Bearer $AIHUBMIX_API_KEY
Content-Type: application/json
```
### 请求参数
#### 标准 TTS 参数
标准参数适用于 tts-1, tts-1-hd, gpt-4o-mini-tts, gemini-2.5-flash-preview-tts 以及 gemini-2.5-pro-preview-tts。
| 参数 | 类型 | 必填 | 说明 |
| :--------------- | :----- | :- | :------------------------------------------------------------------------------------------------------------- |
| model | string | 是 | 要使用的模型 ID。可选值:`tts-1`、`tts-1-hd`、`gpt-4o-mini-tts`、`gemini-2.5-flash-preview-tts`、`gemini-2.5-pro-preview-tts` |
| input | string | 是 | 要生成音频的文本,最大长度为 4096 个字符 |
| voice | string | 是 | 用于合成的语音。见下方语音列表 |
| response\_format | string | 否 | 音频输出格式。支持的音频格式包括: `mp3`、 `opus`、 `aac` 、 `flac`、 `wav`、 `pcm`,默认使用 `mp3` 格式。注意:Gemini 模型仅支持 `wav`和 `pcm` 格式。 |
| speed | number | 否 | 生成音频的语速。取值范围 0.25 到 4.0,默认为1.0。注意: `gpt-4o-mini-tts` 和 `Gemini` 模型不支持此参数,但可以通过自然语言描述来控制语速。 |
| instructions | string | 否 | 语音生成指令,可以详细指定语音风格、语调和情感等特性,仅适用于 `gpt-4o-mini-tts` 和 `Gemini` 模型。 |
#### gpt-4o-audio-preview 参数
| 参数 | 类型 | 必填 | 说明 |
| :--------- | :----- | :- | :------------------------------ |
| model | string | 是 | 设置为 `gpt-4o-audio-preview` |
| modalities | array | 是 | 设置为 `["text", "audio"]` 启用音频输出 |
| audio | object | 是 | 音频配置对象,包含 `voice` 和 `format` 字段 |
| messages | array | 是 | 聊天消息数组,与标准聊天格式相同 |
## 语音列表
### OpenAI 语音
支持以下语音选项:
* **alloy** - 中性、平衡
* **ash** - 清晰、专业
* **ballad** - 温暖、叙事性
* **coral** - 友好、平易近人
* **echo** - 清晰、明亮
* **fable** - 富有表现力、戏剧性
* **onyx** - 深沉、权威
* **nova** - 活泼、充满活力
* **sage** - 成熟、知识渊博
* **shimmer** - 柔和、舒缓
* **verse** - 清晰、多才多艺
* **marin** - 自然、友好
* **cedar** - 稳定、可靠
### Gemini 语音
支持以下 30 种语音选项:
| 语音名称 | 风格 | 语音名称 | 风格 | 语音名称 | 风格 |
| :------------ | :----------- | :---------------- | :-------------- | :--------------- | :------------ |
| **Zephyr** | *Bright* | **Puck** | *Upbeat* | **Charon** | *Informative* |
| **Kore** | *Firm* | **Fenrir** | *Excitable* | **Leda** | *Youthful* |
| **Orus** | *Firm* | **Aoede** | *Breezy* | **Callirrhoe** | *Easy-going* |
| **Autonoe** | *Bright* | **Enceladus** | *Breathy* | **Iapetus** | *Clear* |
| **Umbriel** | *Easy-going* | **Algieba** | *Smooth* | **Despina** | *Smooth* |
| **Erinome** | *Clear* | **Algenib** | *Gravelly* | **Rasalgethi** | *Informative* |
| **Laomedeia** | *Upbeat* | **Achernar** | *Soft* | **Alnilam** | *Firm* |
| **Schedar** | *Even* | **Gacrux** | *Mature* | **Pulcherrima** | *Forward* |
| **Achird** | *Friendly* | **Zubenelgenubi** | *Casual* | **Vindemiatrix** | *Gentle* |
| **Sadachbia** | *Lively* | **Sadaltager** | *Knowledgeable* | **Sulafat** | *Warm* |
### 语音映射
当使用 Gemini 模型时,如果传入 OpenAI 语音名称,系统会自动映射到对应的 Gemini 语音:
| OpenAI 语音 | Gemini 语音 | OpenAI 语音 | Gemini 语音 |
| :-------- | :-------- | :-------- | :--------- |
| alloy | Kore | ash | Fenrir |
| ballad | Aoede | coral | Leda |
| echo | Puck | fable | Zephyr |
| onyx | Charon | nova | Orus |
| sage | Algieba | shimmer | Callirrhoe |
| verse | Enceladus | marin | Despina |
| cedar | Iapetus | | |
## 使用示例
### 标准 TTS 模型(OpenAI)
```curl theme={null}
curl https://aihubmix.com/v1/audio/speech \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "tts-1",
"input": "The quick brown fox jumped over the lazy dog.",
"voice": "alloy"
}' \
--output speech.mp3
```
### Gemini TTS 模型(单说话人)
```curl theme={null}
curl https://aihubmix.com/v1/audio/speech \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-2.5-flash-preview-tts",
"input": "Say cheerfully: Have a wonderful day!",
"voice": "Kore",
"response_format": "wav"
}' \
--output speech.wav
```
### Gemini TTS 模型(多说话人 - 通过提示词控制)
```curl theme={null}
curl https://aihubmix.com/v1/audio/speech \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-2.5-flash-preview-tts",
"input": "TTS the following conversation between Joe and Jane:\nJoe: How'\''s it going today Jane?\nJane: Not too bad, how about you?",
"voice": "Kore",
"response_format": "wav",
"instructions": "Joe should sound firm and professional, Jane should sound upbeat and friendly"
}' \
--output conversation.wav
```
### Python 示例(OpenAI SDK)
```python theme={null}
from openai import OpenAI
client = OpenAI(
api_key="your-aihubmix-api-key",
base_url="https://aihubmix.com/v1"
)
response = client.audio.speech.create(
model="tts-1",
voice="alloy",
input="The quick brown fox jumped over the lazy dog."
)
response.stream_to_file("speech.mp3")
```
### Python 示例(Gemini TTS)
```python theme={null}
from openai import OpenAI
client = OpenAI(
api_key="your-aihubmix-api-key",
base_url="https://aihubmix.com/v1"
)
# 单说话人
response = client.audio.speech.create(
model="gemini-2.5-flash-preview-tts",
voice="Kore",
input="Say cheerfully: Have a wonderful day!",
extra_body={
"response_format": "wav"
}
)
response.stream_to_file("speech.wav")
# 多说话人对话
conversation_response = client.audio.speech.create(
model="gemini-2.5-flash-preview-tts",
voice="Kore",
input="""TTS the following conversation between Joe and Jane:
Joe: How's it going today Jane?
Jane: Not too bad, how about you?""",
extra_body={
"response_format": "wav",
"instructions": "Joe should sound firm, Jane should sound upbeat"
}
)
conversation_response.stream_to_file("conversation.wav")
```
## 控制语音风格(Gemini 模型)
Gemini TTS 模型支持通过自然语言提示词来控制语音的风格、语调、口音和语速。您可以在 `input` 或 `instructions` 参数中提供指导。
### 单说话人风格控制
```json theme={null}
{
"model": "gemini-2.5-flash-preview-tts",
"input": "Say in a spooky whisper: By the pricking of my thumbs... Something wicked this way comes",
"voice": "Enceladus",
"response_format": "wav"
}
```
### 多说话人风格控制
```json theme={null}
{
"model": "gemini-2.5-flash-preview-tts",
"input": "Speaker1: So... what's on the agenda today?\nSpeaker2: You're never going to guess!",
"voice": "Kore",
"response_format": "wav",
"instructions": "Make Speaker1 sound tired and bored, and Speaker2 sound excited and happy"
}
```
### 提示词结构建议
为了获得最佳效果,可以使用以下结构化的提示词格式:
```json theme={null}
{
"model": "gemini-2.5-flash-preview-tts",
"input": "Your transcript here",
"voice": "Kore",
"instructions": "# AUDIO PROFILE: Character Name\n## Role Description\n\n## THE SCENE: Scene Name\nDescribe the environment and mood\n\n### DIRECTOR'S NOTES\nStyle: Describe the style\nPacing: Describe the pacing\nAccent: Specify the accent"
}
```
## 支持的语言
TTS 模型自动检测输入语言。支持以下 24 种语言:
| 语言 | BCP-47 代码 | 语言 | BCP-47 代码 |
| :-------- | :------------ | :---------- | :-------- |
| 阿拉伯语(埃及) | ar-EG | 德语(德国) | de-DE |
| 英语(美国) | en-US | 西班牙语(美国) | es-US |
| 法语(法国) | fr-FR | 印地语(印度) | hi-IN |
| 印尼语(印尼) | id-ID | 意大利语(意大利) | it-IT |
| 日语(日本) | ja-JP | 韩语(韩国) | ko-KR |
| 葡萄牙语(巴西) | pt-BR | 俄语(俄罗斯) | ru-RU |
| 荷兰语(荷兰) | nl-NL | 波兰语(波兰) | pl-PL |
| 泰语(泰国) | th-TH | 土耳其语(土耳其) | tr-TR |
| 越南语(越南) | vi-VN | 罗马尼亚语(罗马尼亚) | ro-RO |
| 乌克兰语(乌克兰) | uk-UA | 孟加拉语(孟加拉国) | bn-BD |
| 英语(印度) | en-IN & hi-IN | 马拉地语(印度) | mr-IN |
| 泰米尔语(印度) | ta-IN | 泰卢固语(印度) | te-IN |
## 响应格式
### 音频格式
| 格式 | Content-Type | 说明 | 模型支持 |
| :--- | :----------- | :---------------------------- | :-------- |
| mp3 | audio/mpeg | 默认格式,广泛兼容 | OpenAI 模型 |
| opus | audio/opus | 适合互联网流媒体 | OpenAI 模型 |
| aac | audio/aac | 数字音频压缩 | OpenAI 模型 |
| flac | audio/flac | 无损音频压缩 | OpenAI 模型 |
| wav | audio/wav | 未压缩的 WAV 音频 | 所有模型 |
| pcm | audio/pcm | 原始 PCM 音频(24kHz, 单声道, 16-bit) | 所有模型 |
**注意:** Gemini 模型原生返回 PCM 格式(24kHz, 单声道, 16-bit),系统会自动转换为 WAV 格式。如需其他格式,建议使用 OpenAI 模型。
### 响应体
成功时返回音频流(二进制数据),Content-Type 根据 `response_format` 参数设置。
失败时返回 JSON 错误信息:
```json theme={null}
{
"error": {
"message": "错误描述",
"type": "error_type",
"code": "error_code"
}
}
```
## 计费说明
TTS API 按字符数计费:
* 输入文本的字符数作为计费单位
* 不同模型有不同的价格倍率
* 最大输入长度:4096 字符
## 限制说明
* 最大输入长度:4096 个字符
* Gemini TTS 模型仅支持 `wav` 和 `pcm` 输出格式
* Gemini TTS 模型不支持 `speed` 参数(可通过提示词控制)
* 上下文窗口限制:32k tokens(Gemini 模型)
## 常见问题
### Q: 如何选择合适的模型?
* 需要快速生成 → `tts-1` 或 `gemini-2.5-flash-preview-tts`
* 需要高质量音频 → `tts-1-hd`
* 需要智能语音控制 → `gpt-4o-mini-tts` 或 Gemini TTS 模型
* 需要多说话人对话 → Gemini TTS 模型
### Q: Gemini TTS 和 OpenAI TTS 有什么区别?
* **Gemini TTS**: 支持通过自然语言提示词控制语音风格,支持多说话人,但仅支持 WAV/PCM 格式
* **OpenAI TTS**: 支持多种音频格式,有固定的语音选项,速度可通过参数控制
### Q: 如何实现多说话人对话?
使用 Gemini TTS 模型,在 `input` 中使用对话格式,并在 `instructions` 中为每个说话人指定风格:
```json theme={null}
{
"model": "gemini-2.5-flash-preview-tts",
"input": "Speaker1: Hello!\nSpeaker2: Hi there!",
"instructions": "Speaker1 should sound professional, Speaker2 should sound casual"
}
```
### Q: 支持流式输出吗?
## 目前 TTS API 返回完整的音频文件,不支持流式输出。
更新时间:2026-06-01
# 三方接入技术指南
Source: https://docs.aihubmix.com/cn/api/Third-PartyIntegrationTechnicalGuide
基于 `@aihubmix/ai-sdk-provider`、`dify-plugin-aihubmix` 和 `cherry-studio` 三个项目的核心实现逻辑,本文档为开发者提供快速接入 aihubmix 统一网关的技术指南。
## 1. 核心接入模式
### 1.1 统一鉴权与路由
```typescript theme={null}
// 核心逻辑:替换 API Key、Base URL,添加 APP-Code
const config = {
apiKey: 'your-aihubmix-api-key', // 替换为 aihubmix API Key
baseURL: 'https://aihubmix.com', // 替换为 aihubmix 网关
headers: {
'APP-Code': 'APP Code' // 应用Code可从https://aihubmix.com/appstore获取
}
};
// 模型路由规则
function routeModel(modelName: string) {
if (modelName.startsWith('claude')) {
// Claude 模型:使用 Anthropic SDK
return 'anthropic';
} else if (modelName.startsWith('gemini') && !modelName.endsWith('-nothink') && !modelName.endsWith('-search')) {
// Gemini 模型:使用 Google SDK,端点 https://aihubmix.com/gemini
return 'gemini';
} else {
// 其他模型:使用 OpenAI 兼容接口
return 'openai';
}
}
```
```python theme={null}
# 核心逻辑:替换 API Key、Base URL,添加 APP-Code
credentials = {
"api_key": "your-aihubmix-api-key", # 替换为 aihubmix API Key
"base_url": "https://aihubmix.com", # 替换为 aihubmix 网关
"extra_headers": {
"APP-Code": "APP Code" # 应用Code可从https://aihubmix.com/appstore获取
}
}
# 模型路由规则
def route_model(model_name: str):
if model_name.startswith("claude"):
# Claude 模型:使用 Anthropic SDK
return "anthropic"
elif model_name.startswith("gemini") and not model_name.endswith(("-nothink", "-search")):
# Gemini 模型:使用 Google SDK,端点 https://aihubmix.com/gemini
return "gemini"
else:
# 其他模型:使用 OpenAI 兼容接口
return "openai"
```
### 1.2 特殊处理要点
* **空工具修复**:当 `tools=[]` 且存在 `tool_choice` 时,自动移除 `tool_choice`
* **文件扩展名**:根据 `mediaType` 自动设置正确的文件扩展名
* **缓存控制**:支持 `` 标签实现缓存控制
## 2. 统一接入实现
### 2.1 核心客户端封装
```typescript theme={null}
class AihubmixModelClient {
private config: {
apiKey: string;
baseURL: string;
appCode: string;
};
constructor(apiKey: string) {
this.config = {
apiKey,
baseURL: 'https://aihubmix.com',
appCode: 'APP Code'
};
}
async chatCompletion(model: string, messages: any[], options: any = {}) {
// 根据模型名称自动路由到对应的 SDK
if (model.startsWith('claude')) {
return this.claudeCompletion(model, messages, options);
} else if (model.startsWith('gemini')) {
return this.geminiCompletion(model, messages, options);
} else {
return this.openaiCompletion(model, messages, options);
}
}
private async claudeCompletion(model: string, messages: any[], options: any) {
const { Anthropic } = await import('@anthropic-ai/sdk');
const client = new Anthropic({
apiKey: this.config.apiKey,
baseURL: this.config.baseURL,
defaultHeaders: { 'APP-Code': this.config.appCode }
});
return client.messages.create({ model, messages, ...options });
}
private async geminiCompletion(model: string, messages: any[], options: any) {
const { GoogleGenerativeAI } = await import('@google/generative-ai');
const genAI = new GoogleGenerativeAI(this.config.apiKey, {
baseURL: `${this.config.baseURL}/gemini/v1beta`,
defaultHeaders: { 'APP-Code': this.config.appCode }
});
const genModel = genAI.getGenerativeModel({ model });
return genModel.generateContent(messages);
}
private async openaiCompletion(model: string, messages: any[], options: any) {
const OpenAI = await import('openai');
const client = new OpenAI.default({
apiKey: this.config.apiKey,
baseURL: `${this.config.baseURL}/v1`,
defaultHeaders: { 'APP-Code': this.config.appCode }
});
return client.chat.completions.create({ model, messages, ...options });
}
}
// 使用示例
const client = new AihubmixModelClient('your-aihubmix-api-key');
await client.chatCompletion('gpt-4o-mini', messages);
await client.chatCompletion('claude-3-5-sonnet-20241022', messages);
await client.chatCompletion('gemini-2.5-flash', messages);
```
```python theme={null}
class AihubmixModelClient:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://aihubmix.com"
self.headers = {
"Authorization": f"Bearer {api_key}",
"APP-Code": "APP Code"
}
def chat_completion(self, model: str, messages: list, **kwargs):
"""统一的聊天完成接口"""
if model.startswith("claude"):
return self._claude_completion(model, messages, **kwargs)
elif model.startswith("gemini"):
return self._gemini_completion(model, messages, **kwargs)
else:
return self._openai_completion(model, messages, **kwargs)
def _claude_completion(self, model: str, messages: list, **kwargs):
import anthropic
client = anthropic.Anthropic(
api_key=self.api_key,
base_url=self.base_url,
extra_headers={"APP-Code": "APP Code"}
)
return client.messages.create(model=model, messages=messages, **kwargs)
def _gemini_completion(self, model: str, messages: list, **kwargs):
import google.generativeai as genai
genai.configure(
api_key=self.api_key,
client_options={"api_endpoint": f"{self.base_url}/gemini/v1beta"}
)
genai._client._http_client._session.headers.update({"APP-Code": "APP Code"})
model_instance = genai.GenerativeModel(model)
return model_instance.generate_content(messages)
def _openai_completion(self, model: str, messages: list, **kwargs):
import openai
client = openai.OpenAI(
api_key=self.api_key,
base_url=f"{self.base_url}/v1",
extra_headers={"APP-Code": "APP Code"}
)
return client.chat.completions.create(model=model, messages=messages, **kwargs)
# 使用示例
client = AihubmixModelClient("your-aihubmix-api-key")
await client.chat_completion("gpt-4o-mini", messages)
await client.chat_completion("claude-3-5-sonnet-20241022", messages)
await client.chat_completion("gemini-2.5-flash", messages)
```
### 2.2 特殊处理与工具函数
```typescript theme={null}
// 空工具修复
function fixToolChoice(requestBody: any): any {
if (requestBody.tools?.length === 0 && requestBody.tool_choice) {
delete requestBody.tool_choice;
}
return requestBody;
}
// 文件扩展名映射
function setFileExtension(mediaType: string): string {
const mimeToExt: Record = {
'audio/mpeg': 'mp3', 'audio/wav': 'wav', 'audio/flac': 'flac'
};
return mimeToExt[mediaType] || 'bin';
}
// 缓存控制
function processCacheTags(content: string): { content: string; cacheControl?: any } {
if (content.includes('')) {
return { content: content.replace('', ''), cacheControl: { type: 'ephemeral' } };
}
return { content };
}
```
```python theme={null}
# 空工具修复
def fix_tool_choice(request_body: dict) -> dict:
if request_body.get("tools") == [] and "tool_choice" in request_body:
del request_body["tool_choice"]
return request_body
# 文件扩展名映射
def set_file_extension(media_type: str) -> str:
mime_to_ext = {
'audio/mpeg': 'mp3', 'audio/wav': 'wav', 'audio/flac': 'flac'
}
return mime_to_ext.get(media_type, 'bin')
# 缓存控制
def process_cache_tags(content: str):
if "" in content:
return {
"content": content.replace("", ""),
"cache_control": {"type": "ephemeral"}
}
return {"content": content}
```
## 3. 部署与配置
### 3.1 环境变量
```typescript theme={null}
const config = {
apiKey: process.env.AIHUBMIX_API_KEY || '',
baseURL: process.env.AIHUBMIX_BASE_URL || 'https://aihubmix.com',
appCode: process.env.AIHUBMIX_APP_CODE || 'APP Code'
};
```
```python theme={null}
import os
config = {
"api_key": os.getenv("AIHUBMIX_API_KEY", ""),
"base_url": os.getenv("AIHUBMIX_BASE_URL", "https://aihubmix.com"),
"app_code": os.getenv("AIHUBMIX_APP_CODE", "APP Code")
}
```
### 3.2 错误处理
```typescript theme={null}
class AihubmixError extends Error {
constructor(message: string, public code?: string, public status?: number) {
super(message);
this.name = 'AihubmixError';
}
}
function handleAihubmixErrors(error: any): AihubmixError {
const message = error.message || 'Unknown error';
if (message.toLowerCase().includes('rate limit')) {
return new AihubmixError('Rate limit exceeded', 'RATE_LIMIT', 429);
} else if (message.toLowerCase().includes('unauthorized')) {
return new AihubmixError('Authentication failed', 'AUTH_ERROR', 401);
} else {
return new AihubmixError(message, error.code, error.status);
}
}
```
```python theme={null}
class AihubmixError(Exception):
def __init__(self, message: str, code: str = None, status: int = None):
super().__init__(message)
self.code = code
self.status = status
def handle_aihubmix_errors(e: Exception) -> AihubmixError:
message = str(e).lower()
if "rate limit" in message:
return AihubmixError("Rate limit exceeded", "RATE_LIMIT", 429)
elif "unauthorized" in message:
return AihubmixError("Authentication failed", "AUTH_ERROR", 401)
else:
return AihubmixError(f"Request failed: {e}")
```
## 4. 参考实现与对齐清单
### 4.1 cherry-studio 客户端参考(TypeScript)
下述要点来自 `cherry-studio` 的 `AihubmixAPIClient.ts`,可作为第三方前端/桌面端在 TypeScript 侧接入 aihubmix 的落地范式:
* **统一追加折扣码**:在 Provider 级别合并 `extra_headers` 并设置 `APP-Code`(项目中为 `MLTG2087`)
* **多客户端路由**:
* `claude*` → 使用 Anthropic 客户端
* `gemini*`/`imagen*` 且不以 `-nothink`/`-search` 结尾且不包含 `embedding` → 使用 Gemini 客户端(`apiHost: https://aihubmix.com/gemini`)
* OpenAI 系列(排除 `gpt-oss`)→ 使用 OpenAI 兼容响应客户端
* 其他 → 回退到默认 OpenAI 客户端
* **BaseURL 获取**:从当前已路由的具体客户端导出,保持各家端点差异
### 4.2 dify-plugin-aihubmix 参考(Python)
下述要点来自 `dify-plugin-aihubmix` 的实现,可作为第三方 Python 工具接入 aihubmix 的落地范式:
* **统一追加折扣码**:在 Provider 级别合并 `extra_headers` 并设置 `APP-Code`(项目中为 `Dify2025`)
* **多客户端路由**:
* `claude*` → 使用 Anthropic 客户端
* `gemini*`/`imagen*` 且不以 `-nothink`/`-search` 结尾且不包含 `embedding` → 使用 Gemini 客户端(`apiHost: https://aihubmix.com/gemini`)
* OpenAI 系列(排除 `gpt-oss`)→ 使用 OpenAI 兼容响应客户端
* 其他 → 回退到默认 OpenAI 客户端
* **BaseURL 获取**:从当前已路由的具体客户端导出,保持各家端点差异
### 4.3 对齐清单
* Provider 入口统一合并 `extra_headers` 并注入 `APP-Code`
* Gemini 客户端使用 `https://aihubmix.com/gemini` 作为 `apiHost`
* 路由规则与 `claude*`、`gemini*/imagen*`、OpenAI 系列(排除 `gpt-oss`)一致
* 默认回退到 OpenAI 客户端,保持与 OpenAI 兼容接口行为
* `getBaseURL()` 始终从当前路由客户端导出,避免硬编码
## 5. 迁移检查清单
* 替换 API Key 为 aihubmix API Key
* 替换 Base URL 为 `https://aihubmix.com`
* 添加 `APP-Code` header 享受折扣
* 实现模型路由逻辑(claude/gemini/openai)
* 处理空工具时的 `tool_choice` 修复
* 配置文件上传的 MIME 类型处理
* 测试各种模型调用
* 配置错误处理和重试机制
***
更新时间:2026-06-01
# 视频生成 OpenAI 兼容(遗留)
Source: https://docs.aihubmix.com/cn/api/Video-Gen
AiHubMix 提供统一的视频生成 API,兼容 OpenAI Sora 接口格式,后端支持多家厂商模型
新接入建议使用 [视频生成](/cn/api/aihubmix-video-generation),通过
`/ai/v1/videos` 调用统一的视频创建、任务查询、Webhook 和错误协议。本页现有的
`/v1/videos` 兼容接口及各模型适配说明继续可用。
调用前请通过[模型 Schema 接口](/cn/api/async-tasks#model-schema)查询模型支持的端点,
按返回的 `path` 选择协议并读取该项的 `request.schema`,不要依赖 `endpoints` 数组位置。
## 快速开始
视频生成是异步操作,整个流程分为三步:
```text theme={null}
1. 提交任务 → 获得 video_id
2. 轮询状态 → 等待 status 变为 completed
3. 下载视频 → 获取 MP4 文件
```
**最简示例**
```shellscript theme={null}
# 第一步:提交视频生成任务
curl -X POST https://aihubmix.com/v1/videos \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "wan2.6-t2v",
"prompt": "A cat playing jazz on a piano, warm lighting, cinematic shot",
"seconds": "5",
"size": "1280x720"
}'
# 响应示例:
# {
# "id": "eyJtb2RlbCI6IndhbjI...",
# "object": "video",
# "status": "in_progress",
# "model": "wan2.6-t2v",
# "duration": 5,
# "width": 1280,
# "height": 720,
# ...
# }
# 第二步:轮询查询状态(每 15 秒查询一次,直到 status 为 completed)
curl https://aihubmix.com/v1/videos/{video_id} \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
# 第三步:下载视频
curl https://aihubmix.com/v1/videos/{video_id}/content \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
--output video.mp4
```
## 接口概览
| 接口 | 方法 | 路径 | 说明 |
| :--- | :----- | :------------------------------ | :----------- |
| 创建视频 | POST | `/v1/videos` | 提交视频生成任务 |
| 查询状态 | GET | `/v1/videos/{video_id}` | 查询任务状态与进度 |
| 下载视频 | GET | `/v1/videos/{video_id}/content` | 下载生成的 MP4 视频 |
| 删除任务 | DELETE | `/v1/videos/{video_id}` | 删除视频任务 |
Base URL:`https://aihubmix.com`
认证方式:Bearer Token
```shellscript theme={null}
Authorization: Bearer $AIHUBMIX_API_KEY
```
## 支持的模型
### 当前模型清单
| 厂商 | 模型 ID |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| OpenAI | `sora-2`、`sora-2-pro` |
| Google | `veo-3.1-lite-generate-preview`、`veo-3.0-generate-preview`、`veo-3.1-fast-generate-preview`、`veo-3.1-generate-preview`、`veo-2.0-generate-001` |
| Qwen / Wan 3.0 | `wan3.0-video`、`wan3.0-video-prime` |
| Qwen / Happyhorse 1.1 | `happyhorse-1.1-i2v`、`happyhorse-1.1-r2v`、`happyhorse-1.1-t2v` |
| Qwen / Happyhorse 1.0 | `happyhorse-1.0-i2v`、`happyhorse-1.0-r2v`、`happyhorse-1.0-t2v`、`happyhorse-1.0-video-edit` |
| Qwen / Wan 2.7 | `wan2.7-i2v`、`wan2.7-r2v`、`wan2.7-t2v`、`wan2.7-videoedit` |
| Qwen / Wan 2.6 及更早版本 | `wan2.6-i2v`、`wan2.6-t2v`、`wan2.2-i2v-plus`、`wan2.5-i2v-preview`、`wan2.5-t2v-preview` |
| ByteDance | `doubao-seedance-2-5-260628`、`doubao-seedance-2-0-260128`、`doubao-seedance-2-0-fast-260128`、`doubao-seedance-2-0-mini-260615`、`doubao-seedance-1-5-pro-251215`、`doubao-seedance-1-0-pro-250528`、`doubao-seedance-1-0-pro-fast-251015` |
| MiniMax | `minimax-h3` |
| Kling | `kling-v3-omni`、`kling-video-o1` |
本清单表示模型当前已上线,不代表所有模型共享相同的输入字段。图生视频、参考视频、视频编辑等能力请以[模型 Schema 接口](/cn/api/async-tasks#model-schema)返回的端点和 `request.schema` 为准。
## API 详细说明
### 请求头
```shellscript theme={null}
Authorization: Bearer $AIHUBMIX_API_KEY
Content-Type: application/json
```
### 创建视频生成任务
```shellscript theme={null}
POST /v1/videos
```
#### **请求体**
| 参数 | 类型 | 必填 | 说明 |
| :---------------- | :------------ | :- | :-------------------------------------- |
| `model` | string | 是 | 模型名称,如 `wan2.6-t2v`、`sora-2` |
| `prompt` | string | 是 | 视频描述文本 |
| `seconds` | string | 否 | 视频时长(秒),统一使用字符串类型,如 `"5"`、`"8"`(见各模型详解) |
| `size` | string | 否 | 分辨率,格式 `宽x高`,如 `1920x1080`(各模型支持值不同) |
| `input_reference` | string/object | 否 | 参考图片(图生视频),支持 URL 或 base64 |
> 不同模型的响应格式略有差异,但都包含 `id`(video\_id)和 `status` 字段。以 `status` 判断任务进度即可。
#### 响应示例(**通义万相/Veo**)
```json theme={null}
{
"id": "eyJtb2RlbCI6IndhbjI...",
"object": "video",
"created": 1772460274,
"model": "wan2.6-t2v",
"status": "in_progress",
"prompt": "A cat watching the rain on a windowsill",
"duration": 5,
"width": 1920,
"height": 1080,
"url": null,
"error": null
}
```
**响应示例(Sora)**
```json theme={null}
{
"id": "eyJtb2RlbCI6InNvcmEtMi...",
"object": "video",
"created_at": 1772451930,
"status": "queued",
"model": "sora-2",
"progress": 0,
"prompt": "A cinematic drone shot over mountains",
"seconds": "8",
"size": "1280x720"
}
```
#### 通用状态值说明
| 状态 | 说明 |
| :------------ | :----------- |
| `queued` | 排队中(Sora 特有) |
| `in_progress` | 生成中 |
| `completed` | 生成完成,可以下载 |
| `failed` | 生成失败 |
### 查询视频状态
```shellscript theme={null}
GET /v1/videos/{video_id}
```
轮询此接口检查任务是否完成。建议每 **15 秒** 查询一次。
#### **响应示例(生成完成 - 通义万相)**
```json theme={null}
{
"id": "eyJtb2RlbCI6IndhbjI...",
"object": "video",
"status": "completed",
"model": "wan2.5-t2v-preview",
"duration": 5,
"width": 1920,
"height": 1080,
"url": "https://aihubmix.com/v1/videos/eyJtb2RlbCI6IndhbjI.../content",
"error": null
}
```
#### **响应示例(生成完成 - Sora)**
```json theme={null}
{
"id": "eyJtb2RlbCI6InNvcmEtMi...",
"object": "video",
"created_at": 1772451930,
"status": "completed",
"completed_at": 1772452114,
"expires_at": 1772538330,
"model": "sora-2",
"progress": 100,
"prompt": "A cinematic drone shot over mountains",
"seconds": "8",
"size": "1280x720"
}
```
> 所有模型均通过 `status == "completed"` 判断完成状态,然后调用 `/content` 接口下载。
### 下载视频内容
```shellscript theme={null}
GET /v1/videos/{video_id}/content
```
当状态为 `completed` 后,调用此接口下载 MP4 视频文件。
**响应**: 直接返回视频二进制流`Content-Type: video/mp4`)。
```shellscript theme={null}
curl https://aihubmix.com/v1/videos/{video_id}/content \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
--output my_video.mp4
```
> **注意**:视频下载链接通常有 24 小时有效期,请及时下载保存。
### 删除视频任务
该接口用于删除已创建的视频任务。
```shellscript theme={null}
DELETE /v1/videos/{video_id}
```
## 各模型参数详解
### **OpenAI Sora**
| 参数 | 支持值 |
| ------------ | ------------------------------------------------- |
| 模型 | `sora-2`、`sora-2-pro` |
| 时长 (seconds) | `"4"`(默认)、`"8"`、`"12"` |
| 分辨率 (size) | `720x1280`(默认)、`1280x720`、`1024x1792`、`1792x1024` |
| 图生视频 | 支持,通过 `input_reference` 传入图片 |
> 提示:所有模型的 `seconds` 参数统一使用字符串类型传入(如 `"8"`)。
**示例**
```shellscript Sora theme={null}
curl -X POST https://aihubmix.com/v1/videos \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "sora-2",
"prompt": "A cinematic drone shot soaring over a misty mountain range at sunrise, golden light filtering through the clouds",
"seconds": "8",
"size": "1280x720"
}'
```
```shellscript Sora Pro 竖版视频 theme={null}
curl -X POST https://aihubmix.com/v1/videos \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "sora-2-pro",
"prompt": "A person walking through a neon-lit city street at night, rain reflecting on the pavement, cinematic lighting",
"seconds": "12",
"size": "720x1280"
}'
```
### Google Veo
| 参数 | 支持值 |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 当前模型 | `veo-3.1-lite-generate-preview`、`veo-3.1-generate-preview`、`veo-3.1-fast-generate-preview`、`veo-3.0-generate-preview`、`veo-2.0-generate-001` |
| 本节已核对模型 | `veo-3.1-generate-preview`、`veo-3.1-fast-generate-preview`、`veo-3.0-generate-preview`、`veo-2.0-generate-001` |
| 时长 (seconds) | Veo 3/3.1:`"4"`、`"6"`、`"8"`;Veo 2:`"5"`\~`"8"`(默认 `"8"`) |
| 分辨率 (size) | `720p`(默认)、`1080p`、`4k`(4K 仅 Veo 3+),或像素格式如 `1280x720`、`1920x1080` |
| 宽高比 | 16:9(默认)、9:16 |
| 图生视频(Veo 3.1) | **首帧**:`first_frame`(或兼容字段 `input_reference`);**尾帧**:`last_frame`;**参考图**:`reference_images`(数组,最多 3 张)。图片支持公网 URL、base64 dataURL、`{"mime_type": "...", "data": "..."}` 对象。**时长**:首帧/首尾帧支持 `"4"`/`"6"`/`"8"`;使用参考图时 Google 固定输出 8 秒 |
**示例**
```shellscript Veo 3.1 theme={null}
curl -X POST https://aihubmix.com/v1/videos \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "veo-3.1-generate-preview",
"prompt": "A tranquil Japanese garden, cherry blossom petals slowly drifting down, koi swimming in the pond, with the melodious sound of wind chimes in the background",
"seconds": "8",
"size": "1280x720"
}'
```
```shellscript Veo 3.1 Fast theme={null}
curl -X POST https://aihubmix.com/v1/videos \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "veo-3.1-fast-generate-preview",
"prompt": "Ocean waves crashing on rocky cliffs at sunset, seagulls flying overhead",
"seconds": "8",
"size": "1280x720"
}'
```
```shellscript 首尾帧(图生视频) theme={null}
curl -X POST https://aihubmix.com/v1/videos \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "veo-3.1-generate-preview",
"prompt": "The camera slowly pushes in from a valley at dawn, transitioning naturally into sunset",
"seconds": "8",
"size": "1280x720",
"first_frame": "https://example.com/first.jpg",
"last_frame": "https://example.com/last.jpg"
}'
```
```shellscript 参考图(图生视频,最多 3 张) theme={null}
curl -X POST https://aihubmix.com/v1/videos \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "veo-3.1-generate-preview",
"prompt": "The character from the reference images walks through a forest, cinematic shot",
"seconds": "8",
"size": "1280x720",
"reference_images": [
"https://example.com/ref1.jpg",
"https://example.com/ref2.jpg"
]
}'
```
**图片字段说明**:
* 首帧优先级:`first_frame` > `input_reference`(OpenAI 兼容单帧)。
* `first_frame` / `last_frame` / `reference_images` 每个元素均支持:公网 URL、base64 dataURL(`data:image/png;base64,...`)、或 `{"mime_type":"image/png","data":""}` 对象。
* 也兼容 OpenRouter 风格的 `frame_images`(元素带 `frame_type: first_frame | last_frame`)与 `input_references` 别名。
* 参考图最多 3 张,超出返回 400。
> 提示:Veo 支持原生音频生成,可在 prompt 中描述音效,如"背景传来鸟鸣声"、"钢琴旋律"。
### 通义万相
| 参数 | 支持值 |
| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 当前 Wan 模型 | `wan3.0-video`、`wan3.0-video-prime`、`wan2.7-i2v`、`wan2.7-r2v`、`wan2.7-t2v`、`wan2.7-videoedit`、`wan2.6-t2v`、`wan2.6-i2v`、`wan2.5-t2v-preview`、`wan2.5-i2v-preview`、`wan2.2-i2v-plus` |
| 本节已核对模型 | `wan2.6-t2v`、`wan2.6-i2v`、`wan2.5-t2v-preview`、`wan2.5-i2v-preview`、`wan2.2-i2v-plus` |
| 时长 (seconds) | 因模型而异(见下方说明),默认 `"5"` |
| 分辨率 (size) | 见下方表格,`x` 和 `*` 分隔符均可(如 `1920x1080` 或 `1920*1080`) |
| 图生视频 | 通过 `input_reference` 传入图片 URL 或 base64 |
**各模型支持的时长**
| 模型 | seconds 可选值 | 默认值 |
| :------------------------------------------ | :------------------- | :---- |
| `wan2.6-t2v` / `wan2.6-i2v` | `"2"`\~`"15"`(任意整数值) | `"5"` |
| `wan2.5-t2v-preview` / `wan2.5-i2v-preview` | `"5"` 或 `"10"` | `"5"` |
| `wan2.2-i2v-plus` | `"5"`(固定) | `"5"` |
**支持的分辨率(宽\*高)**
| 清晰度 | 可选分辨率 |
| :---- | :-------------------------------------------------------------------- |
| 480P | `832x480`、`480x832`、`624x624` |
| 720P | `1280x720`(默认)、`720x1280`、`960x960`、`1088x832`(4:3)、`832x1088`(3:4) |
| 1080P | `1920x1080`、`1080x1920`、`1440x1440`、`1632x1248`(4:3)、`1248x1632`(3:4) |
> **注意**:wan2.6 仅支持 720P 和 1080P;wan2.5 支持 480P、720P、1080P;wan2.2 仅支持 480P 和 1080P。
**示例**
```shellscript 文生视频 theme={null}
curl -X POST https://aihubmix.com/v1/videos \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "wan2.6-t2v",
"prompt": "A winding stream flows through an autumn forest, golden fallen leaves drifting on the water surface, sunlight casting dappled light and shadow through the leaves",
"seconds": "5",
"size": "1920x1080"
}'
```
```shellscript 图生视频 theme={null}
curl -X POST https://aihubmix.com/v1/videos \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "wan2.6-i2v",
"prompt": "The character in the frame slowly turns their head and smiles, the camera slowly pushes in",
"seconds": "5",
"size": "1280x720",
"input_reference": "https://example.com/my-image.jpg"
}'
```
> 提示:wan2.5 及以上版本默认生成有声视频(自动配音),中文 prompt 效果更佳。
### 豆包 Seedance
使用真人素材前,请先完成[素材组创建、本人确认和素材入库](/cn/api/doubao-real-person-assets)。已有兼容客户端可直接参考[真人素材兼容协议示例](/cn/api/doubao-real-person-assets#compatible-video)。
| 参数 | 支持值 |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 当前模型 | `doubao-seedance-2-5-260628`、`doubao-seedance-2-0-260128`、`doubao-seedance-2-0-fast-260128`、`doubao-seedance-2-0-mini-260615`、`doubao-seedance-1-5-pro-251215`、`doubao-seedance-1-0-pro-250528`、`doubao-seedance-1-0-pro-fast-251015` |
| 本节已核对模型 | `doubao-seedance-2-0-260128`、`doubao-seedance-2-0-fast-260128` |
| 分辨率 (resolution) | `"480p"`、`"720p"`(默认) |
| 时长 (duration) | 整数,范围 `4`\~`15`,或 `-1`(模型自动决定) |
| 宽高比 (ratio) | `"adaptive"`(默认,自动适配)、`"16:9"`、`"9:16"`、`"1:1"`、`"4:3"`、`"3:4"`、`"21:9"` |
| 有声视频 (generate\_audio) | 默认 `true`;设为 `false` 生成无声视频 |
| 水印 (watermark) | 默认 `false` |
| 多模态参考 | 支持图片、视频、音频 |
**`extra_body.content` 支持的引用类型**
| 类型 | `type` 值 | `role` 值 | 说明 |
| ---- | ----------- | ----------------- | --------- |
| 参考图片 | `image_url` | `reference_image` | 画面/风格参考图片 |
| 参考视频 | `video_url` | `reference_video` | 运镜/构图参考视频 |
| 参考音频 | `audio_url` | `reference_audio` | 背景音乐音频文件 |
**示例**
```shellscript Seedance 2.0 / 2.0 Fast theme={null}
curl -X POST "https://aihubmix.com/v1/videos" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "doubao-seedance-2-0-260128",
"prompt": "Create a first-person fruit tea commercial. Follow the framing of the reference video, use the reference audio as background music, begin with the first reference image, and end with the second reference image. Show an apple being picked, cut, shaken with ice and tea, then present the finished drink to the camera. Use a female voiceover.",
"extra_body": {
"content": [
{
"type": "image_url",
"image_url": {
"url": "https://ark-project.tos-cn-beijing.volces.com/doc_image/r2v_tea_pic1.jpg"
},
"role": "reference_image"
},
{
"type": "image_url",
"image_url": {
"url": "https://ark-project.tos-cn-beijing.volces.com/doc_image/r2v_tea_pic2.jpg"
},
"role": "reference_image"
},
{
"type": "video_url",
"video_url": {
"url": "https://ark-project.tos-cn-beijing.volces.com/doc_video/r2v_tea_video1.mp4"
},
"role": "reference_video"
},
{
"type": "audio_url",
"audio_url": {
"url": "https://ark-project.tos-cn-beijing.volces.com/doc_audio/r2v_tea_audio1.mp3"
},
"role": "reference_audio"
}
],
"ratio": "16:9",
"duration": 11,
"watermark": false
}
}'
```
### 可灵 Kling
| 说明 | 模型 |
| ------------------ | ---------------- |
| 已核对并保留示例 | `kling-v3-omni` |
| 当前上线,参数以 Schema 为准 | `kling-video-o1` |
**`kling-v3-omni` 参数**
| 参数 | 类型 | 说明 |
| ---------------------- | ------ | --------------------------------------------- |
| `model` | string | **必填**,本节示例使用 `kling-v3-omni` |
| `prompt` | string | 文本提示词 |
| `negative_prompt` | string | 负向提示词 |
| `mode` | string | 生成模式:`std`(720P)/ `pro`(1080P)/ `4k`,默认 `std` |
| `duration` / `seconds` | string | 时长(秒),`3`\~`15`,默认 `5` |
| `aspect_ratio` | string | 画幅:`16:9` / `9:16` / `1:1` |
| `sound` | string | `on`/`off`,是否生成原生音频,默认 `off` |
`kling-video-o1` 的能力与请求字段请先查询[模型 Schema 接口](/cn/api/async-tasks#model-schema),不要直接套用本节参数。
**示例**
```shellscript OmniVideo 原生音频 theme={null}
curl https://aihubmix.com/v1/videos \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "kling-v3-omni",
"prompt": "A man smiling and waving hello",
"sound": "on",
"aspect_ratio": "16:9",
"duration": "5"
}'
```
**说明**
* **异步三步**:提交获 `video_id` → 轮询 `GET /v1/videos/{video_id}` 至 `status` 为 `completed` → `GET /v1/videos/{video_id}/content` 下载 MP4。状态值:`in_progress` / `completed` / `failed`。
* 出片通常 1\~3 分钟;结果视频 URL **30 天后清理**,请及时转存。
* **删除任务**:可灵无删除接口,`DELETE /v1/videos/{video_id}` 返回 `501 not_supported`。
* **计费**:按模型、模式、时长和能力扣费;**生成失败不扣费**,查询与下载不计费。
## **完整调用示例**
```python 通义万相 theme={null}
import requests
import time
API_KEY = "AIHUBMIX_API_KEY"
BASE_URL = "https://aihubmix.com"
HEADERS = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
# 第一步:创建视频生成任务
response = requests.post(
f"{BASE_URL}/v1/videos",
headers=HEADERS,
json={
"model": "wan2.6-t2v",
"prompt": "A desert under a starry sky, a meteor streaking across the night sky, the glow of a distant campfire flickering in the breeze",
"seconds": "5",
"size": "1920x1080"
}
)
result = response.json()
video_id = result["id"]
print(f"任务已创建,video_id: {video_id}")
# 第二步:轮询查询状态
while True:
status_response = requests.get(
f"{BASE_URL}/v1/videos/{video_id}",
headers=HEADERS
)
status_data = status_response.json()
current_status = status_data["status"]
print(f"当前状态: {current_status}")
if current_status == "completed":
print("视频生成完成!")
break
elif current_status == "failed":
error_msg = status_data.get("error", {})
if isinstance(error_msg, dict):
error_msg = error_msg.get("message", "未知错误")
print(f"生成失败: {error_msg}")
break
time.sleep(15) # 每 15 秒查询一次
# 第三步:下载视频
video_response = requests.get(
f"{BASE_URL}/v1/videos/{video_id}/content",
headers=HEADERS
)
with open("output.mp4", "wb") as f:
f.write(video_response.content)
print(f"视频已保存为 output.mp4({len(video_response.content) / 1024 / 1024:.1f} MB)")
```
```python Sora theme={null}
import requests
import time
API_KEY = "AIHUBMIX_API_KEY"
BASE_URL = "https://aihubmix.com"
HEADERS = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
# 创建视频生成任务
response = requests.post(
f"{BASE_URL}/v1/videos",
headers=HEADERS,
json={
"model": "sora-2",
"prompt": "A cinematic shot of a futuristic city at sunset, flying cars in the background",
"seconds": "8", # 可选 "4"/"8"/"12"
"size": "1280x720" # 支持 1280x720, 720x1280, 1024x1792, 1792x1024
}
)
result = response.json()
video_id = result["id"]
print(f"任务已创建,video_id: {video_id}")
# Sora 状态轮询(可能出现 queued -> in_progress -> completed)
while True:
status_response = requests.get(
f"{BASE_URL}/v1/videos/{video_id}",
headers=HEADERS
)
status_data = status_response.json()
current_status = status_data["status"]
progress = status_data.get("progress", "")
print(f"状态: {current_status}, 进度: {progress}%")
if current_status == "completed":
print("视频生成完成!")
break
elif current_status == "failed":
print(f"生成失败: {status_data.get('error')}")
break
time.sleep(15)
# 下载视频
video_response = requests.get(
f"{BASE_URL}/v1/videos/{video_id}/content",
headers=HEADERS
)
with open("sora_output.mp4", "wb") as f:
f.write(video_response.content)
print("视频已保存为 sora_output.mp4")
```
```javascript Node.js theme={null}
const API_KEY = "your_aihubmix_api_key";
const BASE_URL = "https://aihubmix.com";
async function generateVideo() {
// 第一步:创建任务(以 Veo 3.1 为例)
const createResponse = await fetch(`${BASE_URL}/v1/videos`, {
method: "POST",
headers: {
"Authorization": `Bearer ${API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "veo-3.1-generate-preview",
prompt: "A desert under a starry sky, with a meteor streaking across the night.",
seconds: "8",
size: "1280x720"
})
});
const { id: videoId } = await createResponse.json();
console.log(`任务已创建: ${videoId}`);
// 第二步:轮询状态
let status = "in_progress";
while (status !== "completed" && status !== "failed") {
await new Promise(resolve => setTimeout(resolve, 15000));
const statusResponse = await fetch(`${BASE_URL}/v1/videos/${videoId}`, {
headers: { "Authorization": `Bearer ${API_KEY}` }
});
const result = await statusResponse.json();
status = result.status;
console.log(`当前状态: ${status}`);
}
if (status === "completed") {
// 第三步:下载视频
const videoResponse = await fetch(`${BASE_URL}/v1/videos/${videoId}/content`, {
headers: { "Authorization": `Bearer ${API_KEY}` }
});
const fs = require("fs");
const buffer = Buffer.from(await videoResponse.arrayBuffer());
fs.writeFileSync("output.mp4", buffer);
console.log("视频已保存为 output.mp4");
}
}
generateVideo();
```
## **FAQ**
### **视频生成需要多长时间?**
视频生成通常需要 1-5 分钟,具体时间取决于模型、分辨率和时长。建议设置 15 秒的轮询间隔。
### `input_reference` **参数怎么用?**
`input_reference` 用于图生视频场景,支持三种传入方式:
```json theme={null}
// 方式一:直接传入图片 URL
"input_reference": "https://example.com/image.jpg"
// 方式二:传入 base64 编码的图片(对象格式)
"input_reference": {
"mime_type": "image/jpeg",
"data": ""
}
// 方式三:传入 data URL
"input_reference": "data:image/jpeg;base64,"
```
### **视频下载链接有效期是多久?**
生成的视频下载链接通常有 **24 小时** 有效期,请及时下载保存。
### **各模型**`seconds` **参数有什么区别?**
| 模型 | 可选值 | 默认值 |
| ---------------------------------------- | --------------------------- | ----- |
| Sora (`sora-2` / `sora-2-pro`) | `"4"`, `"8"`, `"12"` | `"4"` |
| Veo 3/3.1 (`veo-3.1-generate-preview` 等) | `"4"`, `"6"`, `"8"` | `"8"` |
| Veo 2 (`veo-2.0-generate-001`) | `"5"`\~`"8"` | `"8"` |
| 通义万相 `wan2.6` | `"2"`\~`"15"` | `"5"` |
| 通义万相 `wan2.5` | `"5"`, `"10"` | `"5"` |
| 通义万相 `wan2.2` | `"5"`(固定) | `"5"` |
| 豆包 Seedance (`doubao-seedance-2-0-*`) | 整数 `duration4`\~`15` 或 `-1` | `5` |
| 可灵 Kling (`kling-v3-omni`) | `"3"`\~`"15"` | `"5"` |
\> **提示**:所有模型的 `seconds` 参数统一使用字符串类型传入(如 `"8"`),API 会自动处理。
### 不同模型`size` 参数格式有什么区别?
| 模型 | 支持的 size 值 |
| ----------- | -------------------------------------------------------------------------------------- |
| Sora | `1280x720720x12801024x17921792x1024` |
| Veo | 像素格式`1280x720` 等)或分辨率标签`720p1080p4k`) |
| 通义万相 | 像素格式`x` 和 `*` 均可(如 `1920x1080` 或 `1920*1080`) |
| 豆包 Seedance | 宽高比格式(`"adaptive"`、`"16:9"`、`"9:16"` 等) |
| 可灵 Kling | 不使用 `size`,改用 `mode`(`std`/`pro`/`4k` 控制清晰度)+ `aspect_ratio`(`16:9`/`9:16`/`1:1` 控制画幅) |
**###** `seconds` **和** `duration` **有什么区别?**
两者含义相同,均表示视频时长。API 同时支持这两个参数名(Sora 除外,Sora 只接受 `seconds`)。推荐统一使用 `seconds`。
### 如何编写更好的 prompt?
* **描述具体场景**:包含主体、动作、环境、光线、氛围
* **指定镜头语言**:如"特写"、"航拍"、"推镜头"、"慢动作"
* **描述风格**:如"电影感"、"纪录片风格"、"动画风格"
* **中文模型用中文 prompt 效果更好**:通义万相针对中文优化
* **Veo 支持音频描述**:可在 prompt 中描述声音,如"鸟鸣声"、"钢琴旋律"
## 错误响应与兼容错误码
本节适用于本页的 Legacy `/v1/videos/*` 接口。新版 `/ai/v1/videos/*` 使用独立的
[视频错误合同](/cn/api/aihubmix-video-generation#error-codes)。两套接口的响应结构和
错误码需要分别处理。
Legacy 视频接口的一般 HTTP 错误响应如下。普通错误通常不返回 `code` 和 `param`,
`tid` 通常附加在 `message` 末尾:
```json theme={null}
{
"type": "error",
"error": {
"message": " (tid: req_01K0ABCDEF)",
"type": "Aihubmix_api_error"
}
}
```
请求返回 HTTP `5xx` 时,请提交反馈并附上 `message` 中的 `tid`。
| HTTP / 形态 | `code` | `message` | 说明 |
| --------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| HTTP 400 | `protocol_not_supported` | `This model does not support the legacy protocol. Use POST /ai/v1/videos. See https://docs.aihubmix.com/cn/api/async-tasks` | 所选模型不支持 Legacy 视频创建协议 |
| HTTP 202 错误响应 | 无稳定 code | `video is still being generated` | 视频仍在生成,当前不能下载内容 |
| 其他 HTTP 4xx/5xx | 通常省略,不承诺稳定 code | 经过映射和脱敏的动态 `Aihubmix_api_error` message | 创建、查询、删除、下载或 remix 请求失败 |
### HTTP 200 + `status=failed`
查询请求成功时 HTTP 状态仍可能是 200。视频任务为 `failed` 时,`error` 包含模型推理厂商
提供的动态 message,普通任务失败没有稳定 `code`:
```json theme={null}
{
"status": "failed",
"error": {
"message": "Video generation failed due to content policy violation",
"type": "video_generation_error"
}
}
```
message 能够明确指出参数、内容策略或媒体输入问题时,请修改对应输入后重新创建任务;
原因不明确时,视频 ID 是对应的排查标识。
***
更新时间:2026-09-01
# AIHubMix CLI(命令行工具)
Source: https://docs.aihubmix.com/cn/api/aihubmix-cli
AIHubMix CLI 是 AIHubMix 官方命令行工具,单一二进制、零依赖,在终端即可查询账户余额、管理 API Key、查看可用模型,并对脚本与 AI Agent 友好。
**AIHubMix CLI** 是 AIHubMix 官方命令行工具(可执行文件 `aihubmix`)。安装后,你无需打开网页控制台,就能在终端查询账户余额、管理 API Key、查看可用模型。它是单一二进制文件,**无需安装 Python、Node 或 Go**,一条命令即可装好;所有命令都支持 JSON 输出,可直接接入脚本、CI 与 AI Agent(如 Claude Code)。
**它能做什么:**
* **查余额**:实时查询账户余额与已用额度
* **管 Key**:创建、查看、搜索、修改、删除 API Key
* **看模型**:列出当前令牌可用的模型
* **可脚本化**:JSON 输出 + 稳定退出码,天然适配自动化与 AI Agent
**两种凭证别搞混**:CLI 用「系统访问令牌」(Manage Key,格式 `fd***`)登录,在控制台 [console.aihubmix.com/setting](https://console.aihubmix.com/setting) 点「生成系统访问令牌」获取。它用于**管理账户**,和你调用模型用的 API Key(`sk-***`)不是同一个。
在找旧版 Python 脚本(`aihubmix_cli.py`)?请见[通过接口获取账户信息](/cn/api/Cli)。本页是它的新一代替代品,更简单、更快。
## 安装
### 一键安装(推荐)
复制对应系统的命令,粘贴到终端运行,即可下载二进制并自动加入 `PATH`:
```bash macOS / Linux theme={null}
curl -fsSL https://raw.githubusercontent.com/AIhubmix/platfrom-cli/main/install.sh | sh
```
```powershell Windows PowerShell theme={null}
irm https://raw.githubusercontent.com/AIhubmix/platfrom-cli/main/install.ps1 | iex
```
装好后**重开一个终端**,运行 `aihubmix login` 即可开始使用。
也可到 [Releases](https://github.com/AIhubmix/platfrom-cli/releases) 手动下载对应平台的二进制(Windows 为 `aihubmix_windows_amd64.exe`),放入 `PATH` 目录;类 Unix 系统需 `chmod +x`。
需要时,可用环境变量调整安装行为:
| 变量 | 说明 | 默认 |
| ------------------ | ------------------ | ---------------------------------------------------------------------------- |
| `AIHUBMIX_VERSION` | 安装指定版本(如 `v0.2.0`) | `latest` |
| `AIHUBMIX_BIN_DIR` | 自定义安装目录 | Unix:`/usr/local/bin` 或 `~/.local/bin`;Windows:`%LOCALAPPDATA%\aihubmix\bin` |
## 快速开始
登录后即可使用全部命令:
```bash theme={null}
# 1. 登录:自动打开浏览器到令牌生成页,粘贴 Manage Key(输入不回显)
aihubmix login
# 2. 查看当前身份与余额
aihubmix whoami
# 3. 查看完整账户信息
aihubmix me
# 4. 列出你的 API Key
aihubmix keys list
```
## 命令参考
| 命令 | 作用 |
| -------------------------------- | ----------------- |
| `aihubmix login` | 登录(粘贴 Manage Key) |
| `aihubmix logout` | 登出,清除本地凭证 |
| `aihubmix whoami` | 查看当前登录身份与余额 |
| `aihubmix me` | 查看完整账户信息与余额 |
| `aihubmix models list` | 查看当前可用模型 |
| `aihubmix keys list [--num N]` | 列出 API Key |
| `aihubmix keys search <关键字>` | 按关键字搜索 Key |
| `aihubmix keys get ` | 查看指定 Key 详情 |
| `aihubmix keys create [参数]` | 创建新 Key |
| `aihubmix keys update [参数]` | 修改 Key |
| `aihubmix keys delete ` | 删除 Key |
任意命令加 `--help` 可查看完整参数,例如 `aihubmix keys create --help`。
## 常用操作
### 管理 API Key
```bash theme={null}
# 创建一个 $10 限额、仅限指定模型的 Key
aihubmix keys create -n prod-key -q 10 -m "gpt-4o,claude-3.5-sonnet"
# 创建一个不限额度、永不过期的 Key
aihubmix keys create -n ci-key -u
# 重命名 Key(其余设置不变)
aihubmix keys update 123 -n new-name
# 停用某个 Key
aihubmix keys update 123 --status 0
# 删除 Key
aihubmix keys delete 123
```
其中 `-q 10` 表示该 Key 限额 \$10,`-u` 表示不限额度。删除默认会要求确认,CI 场景可加 `--yes` 跳过。
### 在脚本 / AI Agent 中使用
CLI 对自动化非常友好,可被 CI、脚本或 AI Agent(如 Claude Code)直接驱动:
* **免登录**:用环境变量 `AIHUBMIX_TOKEN` 或 `--token` 传入 Manage Key,跳过交互式登录(优先级:`--token` > `AIHUBMIX_TOKEN` > 配置文件)。
* **JSON 输出**:任意命令加 `--json`(`-j`),正常结果走 stdout、错误走 stderr,方便 `jq` 解析。
* **稳定退出码**:脚本可据此判断成败。
```bash theme={null}
# 用环境变量驱动,提取所有 Key 名称
AIHUBMIX_TOKEN=fd*** aihubmix keys list --json | jq '.data[].name'
# 查询余额
AIHUBMIX_TOKEN=fd*** aihubmix whoami --json | jq -r '.balance'
```
退出码含义:
| 退出码 | 含义 |
| --- | -------------------- |
| `0` | 成功 |
| `1` | 通用错误(参数错误、业务失败等) |
| `2` | 鉴权失败(未登录 / Token 无效) |
| `3` | 网络 / 连接错误 |
## 全局参数
以下参数对所有命令生效:
| 参数 | 简写 | 说明 |
| ------------------ | ---- | ------------------------------------- |
| `--token ` | `-t` | 直接传入 Manage Key(CI / 脚本场景) |
| `--json` | `-j` | 以 JSON 格式输出 |
| `--base-url ` | `-b` | 自定义 API 地址(默认 `https://aihubmix.com`) |
| `--no-color` | | 关闭彩色输出 |
| `--config ` | | 指定配置文件路径 |
| `--version` | | 查看版本 |
## 配置文件
登录信息保存在 `~/.aihubmix/config.json`(Windows 为 `%USERPROFILE%\.aihubmix\config.json`),权限被收紧为**仅当前用户可读写**。登录时 Manage Key 不回显、不写入日志。
请勿将 Manage Key 提交到代码仓库或分享给他人。一旦泄露,请到控制台重新生成,旧令牌会立即失效。
## 常见问题
**需要安装 Python / Node / Go 吗?**
不需要。CLI 是单一二进制文件,下载即用。
**Manage Key 和 API Key 有什么区别?**
Manage Key(`fd***`)用于管理账户(查余额、管 Key),由 CLI 使用;API Key(`sk-***`)用于调用模型。两者在控制台不同位置生成,不能混用。
**支持 Windows 吗?**
支持。Windows、macOS、Linux 均提供原生二进制。
**如何在 CI / 脚本中免交互使用?**
通过环境变量 `AIHUBMIX_TOKEN` 传入 Manage Key,再配合 `--json` 与退出码即可,无需运行 `aihubmix login`。
**忘记或泄露了 Manage Key 怎么办?**
到 [console.aihubmix.com/setting](https://console.aihubmix.com/setting) 重新生成,旧令牌即失效。
***
*相关文档:[平台 API · CliEndpoints](/cn/api/CliEndpoints/get-self) · [旧版 Python 脚本](/cn/api/Cli) · [AIHubMix 控制台](https://console.aihubmix.com)*
***
更新时间:2026-06-22
# 图片生成
Source: https://docs.aihubmix.com/cn/api/aihubmix-image-generation
使用 AIHubMix 原生图片协议同步或异步生成图片,并查询任务和下载结果。
AIHubMix 原生图片协议使用 `/ai/v1/images` 系列端点。生成接口默认同步,传入布尔值
`async: true` 后在后台生成,并使用同一套任务状态、Webhook 和错误结构。
使用异步图片、任务查询或 Webhook 前,需要为当前账户开启异步任务功能。未开启时,
异步任务创建请求返回 `403 async_not_enabled`。
## 快速开始
下面使用 `qwen-image-2.0` 异步生成一张图片。
```bash 创建任务 theme={null}
curl -X POST https://aihubmix.com/ai/v1/images/generations \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-image-2.0",
"prompt": "A flower shop with delicate windows, warm sunlight streaming in",
"n": 1,
"size": "1024x1024",
"async": true
}'
```
```json 创建响应 theme={null}
{
"id": "task_01K0ABCDEF",
"object": "image",
"model": "qwen-image-2.0",
"status": "in_progress",
"output": [],
"error": null,
"created_at": 1784707200,
"completed_at": null,
"expires_at": null
}
```
```bash 查询任务 theme={null}
curl https://aihubmix.com/ai/v1/images/{id} \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
```
```bash 下载图片 theme={null}
curl "{content_url}" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
--output result.png
```
任务进入 `completed` 后,逐项读取 `output[].content_url`。该地址对应
`GET /ai/v1/images/{id}/content/{result_id}`,客户端不需要自行拼接 `result_id`。
## 接口概览
| 场景 | 方法 | 路径 | 说明 |
| ------ | ---- | ---------------------------------------- | ---------------------- |
| 生成图片 | POST | `/ai/v1/images/generations` | 默认同步,`async: true` 时异步 |
| 查询图片详情 | GET | `/ai/v1/images/{id}` | 返回任务最新状态 |
| 查询图片列表 | GET | `/ai/v1/images` | 返回当前 API Key 创建的图片任务快照 |
| 下载指定图片 | GET | `/ai/v1/images/{id}/content/{result_id}` | 下载多图任务中的指定结果 |
Base URL:`https://aihubmix.com`
认证方式:
```text theme={null}
Authorization: Bearer $AIHUBMIX_API_KEY
```
## 查询模型 Schema
模型目录可以筛选已经提供请求 Schema 的文生图模型:
```bash theme={null}
curl "https://aihubmix.com/api/v1/models?type=image_generation&schema_checked=true&sort_by=order"
```
取得 `model_id` 后,查询该模型实际支持的端点:
```bash theme={null}
curl "https://aihubmix.com/call/schema/models/qwen-image-2.0/endpoints"
```
同一模型可能同时返回 AIHubMix 原生与兼容端点。应按 `path` 选择原生图片接口,再读取
对应的 `request.schema`:
```bash theme={null}
curl -s "https://aihubmix.com/call/schema/models/qwen-image-2.0/endpoints" \
| jq '.endpoints[] | select(.path == "/ai/v1/images/generations") | .request.schema'
```
不要依赖 `endpoints` 数组位置。完整响应字段和失败情况参阅
[模型 Schema 接口](/cn/api/async-tasks#model-schema)。
## 创建图片
### 同步生成
省略 `async` 或设置为 `false` 时,请求等待生成完成后返回任务对象:
```bash theme={null}
curl -X POST https://aihubmix.com/ai/v1/images/generations \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-image-2.0",
"prompt": "A quiet reading room in the afternoon",
"n": 1,
"size": "1024x1024",
"response_format": "url"
}'
```
同步请求也会保存任务记录。创建响应丢失时,可以通过图片列表找回任务。
### 异步生成
`async` 必须是布尔值 `true`,不能写成字符串。异步请求立即返回任务对象,生成在后台继续。
`webhook_url` 和 `webhook_events_filter` 只能与 `async: true` 一起使用。
### 标准字段
| 字段 | 类型 | 必填 | 说明 |
| ----------------------- | ------------- | -- | -------------------------------------- |
| `model` | string | 是 | 模型 ID |
| `prompt` | string | 是 | 图片描述,不能为空 |
| `n` | integer/null | 否 | 图片数量,最小值 `1`,默认 `1` |
| `size` | string/null | 否 | `{width}x{height}`,例如 `1024x1024` |
| `aspect_ratio` | string/null | 否 | 宽高比,与 `size` 二选一 |
| `seed` | integer/null | 否 | 随机种子 |
| `negative_prompt` | string/null | 否 | 负向提示词 |
| `image` | string/object | 否 | 单张输入图片 |
| `images` | array/null | 否 | 多张输入图片 |
| `mask` | string/object | 否 | 图片编辑蒙版 |
| `output_format` | string/null | 否 | `png`、`jpeg` 或 `webp` |
| `response_format` | string/null | 否 | `url` 或 `b64_json` |
| `async` | boolean | 否 | `true` 时异步执行 |
| `webhook_url` | string | 否 | HTTPS 回调地址,最长 512 字符 |
| `webhook_events_filter` | string\[] | 否 | `completed`、`failed`、`cancelled` 的非空子集 |
| `extra` | object/null | 否 | 模型专属扩展参数 |
标准字段集合不表示所有模型支持全部字段。字段、枚举和取值范围以该模型
`/ai/v1/images/generations` 端点的 `request.schema` 为准。
## 图片任务对象
同步生成完成后,或异步任务进入结束态后,接口返回以下结构:
```json theme={null}
{
"id": "task_01K0ABCDEF",
"object": "image",
"model": "qwen-image-2.0",
"status": "completed",
"output": [
{
"index": 0,
"type": "file",
"b64_json": null,
"content_url": "https://aihubmix.com/ai/v1/images/task_01K0ABCDEF/content/result_01K0XYZ"
}
],
"error": null,
"created_at": 1784707200,
"completed_at": 1784707218,
"expires_at": 1784714418
}
```
| 字段 | 类型 | 说明 |
| -------------- | ------------ | -------------------------------------------- |
| `id` | string | 平台任务 ID |
| `object` | string | 图片任务固定为 `image` |
| `model` | string | 实际使用的模型 ID |
| `status` | string | 当前任务状态 |
| `output` | array | 已生成的图片;尚无结果时为空数组 |
| `error` | object/null | 失败信息,可含 `code`、`message` 和 `upstream_detail` |
| `created_at` | integer | 创建时间,Unix 秒 |
| `completed_at` | integer/null | 进入结束态的时间,Unix 秒 |
| `expires_at` | integer/null | 结果过期时间,Unix 秒;任务完成前可能为空 |
`output` 项包含顺序 `index`、固定值 `type: "file"`、可选的 `b64_json` 和
`content_url`。多图请求会按 `index` 返回多个结果。
### 状态说明
| 状态 | 是否结束 | 说明 |
| ------------- | ---- | ---------------- |
| `pending` | 否 | 已接收,等待执行 |
| `in_progress` | 否 | 正在生成 |
| `completed` | 是 | 已完成,可读取 `output` |
| `failed` | 是 | 已失败,原因见 `error` |
| `cancelled` | 是 | 已取消 |
客户端可以每 15 秒查询一次,直到状态变为 `completed`、`failed` 或 `cancelled`。
15 秒是客户端轮询建议,不是服务端协议限制。
## 查询图片任务
### 查询详情
```bash theme={null}
curl https://aihubmix.com/ai/v1/images/{task_id} \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
```
图片详情接口会返回任务最新状态。异步图片轮询必须使用该接口,不要使用统一任务详情代替。
### 查询列表
创建响应丢失时,可以通过图片列表找回任务 ID:
```bash theme={null}
curl "https://aihubmix.com/ai/v1/images?limit=20&order=desc" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
```
| 参数 | 类型 | 默认值 | 说明 |
| ------- | ------- | ------ | ------------------------ |
| `after` | string | - | 分页游标,使用上一页的 `next_after` |
| `limit` | integer | `20` | 每页数量,最大 `100` |
| `order` | string | `desc` | `asc` 为升序,其他值按 `desc` 处理 |
```json theme={null}
{
"object": "list",
"data": [
{
"id": "task_01K0ABCDEF",
"object": "image",
"model": "qwen-image-2.0",
"status": "in_progress",
"output": [],
"error": null,
"created_at": 1784707200,
"completed_at": null,
"expires_at": null
}
],
"has_more": true,
"next_after": "task_01K0ABCDEF"
}
```
列表返回查询时的任务快照,不会主动刷新活动任务状态。
## 统一任务接口
`/ai/v1/tasks` 提供图片、视频和 LLM 任务的统一只读视图。可以只查询图片任务:
```bash theme={null}
curl "https://aihubmix.com/ai/v1/tasks?object=image&status=completed&limit=20&order=desc" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
```
统一任务列表支持 `object`、`status`、`model`、`after`、`limit` 和 `order`。统一任务详情:
```bash theme={null}
curl https://aihubmix.com/ai/v1/tasks/{task_id} \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
```
统一任务中的图片结果会额外提供 `result_id` 和 `content_type`:
```json theme={null}
{
"index": 0,
"result_id": "result_01K0XYZ",
"type": "file",
"content_type": "image/png",
"content_url": "https://aihubmix.com/ai/v1/tasks/task_01K0ABCDEF/content/result_01K0XYZ"
}
```
多结果统一任务通过 `/ai/v1/tasks/{id}/content/{result_id}` 下载。未指定结果 ID 时返回
`400 result_id_required`。
媒体详情接口可能在查询时更新活动任务状态,统一任务接口只返回当前快照。因此轮询使用
`/ai/v1/images/{id}`;统一筛选和读取结果元数据时使用 `/ai/v1/tasks`。
任务及内容按创建任务时的 Bearer Token 隔离。
## 下载图片结果
任务进入 `completed` 后,优先直接使用媒体任务对象返回的结果字段:
* `output[].b64_json` 非空:直接进行 Base64 解码。
* `output[].content_url` 非空:携带创建任务时的 Bearer Token 请求该地址。
```bash theme={null}
curl "{content_url}" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
--output result.png
```
图片媒体下载路径是 `/ai/v1/images/{id}/content/{result_id}`。媒体任务对象不单独公开
`result_id`,客户端不需要自行解析或拼接,逐项使用 `output[].content_url` 即可。
结果可能过期,也可能存在下载次数限制。过期返回 `410 artifact_expired`;超过下载
次数限制返回 `429 too_many_downloads`。客户端应在任务完成后及时保存结果。
## Webhook
Webhook 仅用于 `async: true` 的图片请求:
```bash theme={null}
curl -X POST https://aihubmix.com/ai/v1/images/generations \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-image-2.0",
"prompt": "A quiet reading room in the afternoon",
"n": 1,
"size": "1024x1024",
"async": true,
"webhook_url": "https://example.com/webhooks/aihubmix",
"webhook_events_filter": ["completed", "failed"]
}'
```
`webhook_url` 最长 512 字符,不能指向本机、私网或其他受限地址。省略事件过滤器时,
平台推送 `completed`、`failed` 和 `cancelled`;显式传入时,数组不能为空、不能重复,
并且必须与 `webhook_url` 一起使用。
### 回调请求
```json theme={null}
{
"event_id": "evt_01K0ABCDEF",
"event_type": "completed",
"created_at": "2026-08-12T12:00:00Z",
"data": {
"task_id": "task_01K0ABCDEF",
"status": "completed",
"model": "qwen-image-2.0",
"results": [
{
"url": "https://aihubmix.com/ai/v1/tasks/task_01K0ABCDEF/content/result_01K0XYZ"
}
]
}
}
```
`event_id` 用于去重;`data.error` 在失败时可能出现;`data.results` 只在结果已存档时出现,
下载仍需 Bearer Token。
### 重试与去重
平台采用至少一次投递,同一事件可能重复送达:
* HTTP `2xx` 表示接收成功。
* HTTP `5xx`、网络错误或超时会触发重试。
* HTTP `3xx` 和 `4xx` 不会重试。
* 最多投递 6 次,重试间隔依次为 1、4、16、64、256 秒。
接收端应保存 `event_id`,重复收到相同事件时直接返回 `2xx`。任务级 Webhook 本身不
携带独立签名密钥;需要签名验证时,请配置账户级 Webhook,并保留详情查询作为结果确认方式。
## 错误响应与错误码
本节只列 `/ai/v1/images/*` 及其图片 Task 适用的稳定公共错误码。客户端需要同时检查
HTTP 状态码和任务对象的 `status`。
```json theme={null}
{
"error": {
"message": "Task not found.",
"type": "invalid_request_error",
"code": "task_not_found",
"tid": "req_01K0ABCDEF"
}
}
```
请求返回 HTTP `5xx` 时,请提交反馈并附上 `error.tid`。
### HTTP 非 2xx 错误
`invalid_request` 和 `schema_violation` 行展示的是兜底 message。服务能够定位具体字段或
参数约束时会返回动态 message;客户端应以 `code` 判断错误类型,不要依赖 message 固定匹配。
| HTTP | `code` | `message` | 说明 |
| ---- | -------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| 400 | `invalid_request` | `Invalid request. Check the request body and parameters.`(兜底模板;实际可能返回动态 message) | 公共请求体或字段类型不正确;此 code 的 message 不是固定值,能够定位字段时会返回更具体的动态 message |
| 400 | `model_not_found` | `The requested model is not available. Check the model name and your account access.` | 模型不存在、不可用,或当前账户无权访问 |
| 400 | `schema_violation` | `Invalid request: one or more parameters are invalid.`(兜底模板;实际可能返回动态 message) | 请求不符合当前图片模型的参数 Schema;此 code 的 message 不是固定值,能够定位字段或约束时会返回字段级动态 message |
| 400 | `capability_not_supported` | `The requested parameters are not supported for this model.` | 当前图片模型不支持请求中的字段、数量或参数上限 |
| 400 | `media_form_unsupported` | 动态媒体提示,见下文 | 输入图片的格式、数据、URL 或内容无法处理 |
| 400 | `result_id_required` | `This task has multiple results. Specify result_id.` | 图片任务包含多个结果,下载时未指定 `result_id` |
| 400 | `upstream_rejected` | `Upstream service rejected the request.` | 模型推理厂商拒绝了图片生成请求 |
| 401 | `authentication_failed` | `Authentication failed: invalid or missing API key.` | API Key 缺失或无效 |
| 402 | `insufficient_quota` | `Insufficient quota.` | AIHubMix 账户可用额度不足 |
| 403 | `permission_denied` | `You do not have permission to access this resource.` | 当前账户、API Key 或访问来源无权使用该资源 |
| 403 | `async_not_enabled` | `Asynchronous tasks are not enabled. Please go to /async-tasks to activate.` | 当前账户未开通异步图片任务功能;控制台地址会按请求站点生成 |
| 404 | `task_not_found` | `Task not found.` | 图片任务不存在、分页游标无效,或当前账户无权查看 |
| 404 | `result_not_found` | `Result not found.` | 图片结果不存在、尚未就绪、结果 ID 不匹配,或当前账户无权下载 |
| 410 | `artifact_expired` | `The result has expired.` | 图片结果已超过保留期 |
| 413 | `request_too_large` | `Request body is too large. Reduce the request size and try again.` | 整体请求体超过 32 MiB |
| 413 | `image_too_large` | `Image is too large. Reduce the image size and try again.` | 解码后的单张输入图片超过模型处理上限 |
| 422 | `image_not_generated` | `The expected image was not generated.` | 模型推理厂商完成请求,但没有返回可交付图片 |
| 429 | `rate_limited` | `Too many requests. Please slow down and retry.` | AIHubMix 对当前账户或 API Key 限流 |
| 429 | `upstream_rate_limited` | `Upstream service is rate limiting. Please retry later.` | 模型推理厂商返回限流错误 |
| 429 | `too_many_downloads` | `Download limit exceeded for this result.` | 单个图片结果达到下载次数上限 |
| 500 | `internal_error` | `Internal error. Please retry.` | 服务发生调用方无法修复的内部错误 |
| 502 | `upstream_unreachable` | `Upstream service is temporarily unavailable. Please retry.` | 无法连接模型推理厂商,或无法完整读取其响应 |
| 502 | `upstream_bad_response` | `Upstream service returned an invalid response.` | 模型推理厂商返回了平台无法处理的响应 |
| 502 | `upstream_error` | `Upstream service is temporarily unavailable. Please retry.` | 模型推理厂商返回服务错误 |
| 503 | `model_unavailable` | `The requested model is temporarily unavailable.` | 所选图片模型暂时不可用 |
| 503 | `service_unavailable` | `Service is temporarily unavailable. Please retry.` | 查询、下载或结果服务暂时不可用 |
| 504 | `sync_timeout` | `Generation timed out. Please retry.` | 同步图片生成没有在等待时间内完成 |
`media_form_unsupported` 会根据已确认的图片输入原因返回具体 message。例如模型只允许
PNG、JPEG、WebP、HEIC 和 HEIF 时,GIF 输入返回:
```text theme={null}
Unsupported image format: GIF. Supported formats for this model: PNG, JPEG, WebP, HEIC, and HEIF.
```
其他稳定模板包括无效图片数据、图片 URL 无法访问和图片内容无法解码。完整模板见
[异步任务错误码](/cn/api/async-tasks#error-codes)。
### HTTP 200 + Task `status=failed`
异步图片请求创建成功后,后台仍可能把任务置为 `failed`。此时查询接口返回 HTTP 200,
客户端需要读取任务对象中的 `error`:
| Task `code` | `message` | 说明 |
| ------------------------- | --------------------------------------------------------------------------------- | -------------------------- |
| `media_form_unsupported` | 动态媒体提示 | 图片格式、数据、URL 或内容无法处理 |
| `image_too_large` | `Image is too large. Reduce the image size and try again.` | 输入图片超过处理上限 |
| `image_not_generated` | `The expected image was not generated.` | 模型推理厂商没有返回可交付图片 |
| `upstream_rejected` | `Upstream service rejected the request.` | 模型推理厂商拒绝创建请求 |
| `upstream_rate_limited` | `Upstream service is rate limiting. Please retry later.` | 模型推理厂商返回限流错误 |
| `upstream_unreachable` | `Upstream service is temporarily unavailable. Please retry.` | 创建任务时无法连接模型推理厂商,或无法完整读取其响应 |
| `upstream_bad_response` | `Upstream service returned an invalid response.` | 模型推理厂商响应无法处理 |
| `upstream_error` | `Upstream service is temporarily unavailable. Please retry.` | 模型推理厂商创建或执行任务失败 |
| `upstream_empty_output` | `The upstream service completed without producing a usable result. Please retry.` | 模型推理厂商完成任务,但没有产生可交付图片 |
| `output_policy_violation` | `Generated content was rejected by the content policy.` | 生成图片未通过内容安全策略 |
| `sync_timeout` | `Generation timed out. Please retry.` | 等待图片生成结果超时 |
| `internal_error` | `Internal error. Please retry.` | 图片任务处理发生内部错误 |
HTTP 非 2xx 响应中的 `error.tid` 是请求追踪 ID。Task `status=failed` 当前不单独返回
`tid`,任务 ID 是对应的排查标识。
## 完整示例
以下示例完成异步创建、轮询和多图片保存。
```python Python theme={null}
import base64
import os
import time
import requests
base_url = "https://aihubmix.com"
headers = {
"Authorization": f"Bearer {os.environ['AIHUBMIX_API_KEY']}",
"Content-Type": "application/json",
}
response = requests.post(
f"{base_url}/ai/v1/images/generations",
headers=headers,
json={
"model": "qwen-image-2.0",
"prompt": "A flower shop with delicate windows, warm sunlight streaming in",
"n": 1,
"size": "1024x1024",
"async": True,
},
timeout=60,
)
response.raise_for_status()
task = response.json()
while task["status"] not in {"completed", "failed", "cancelled"}:
time.sleep(15)
response = requests.get(
f"{base_url}/ai/v1/images/{task['id']}",
headers=headers,
timeout=30,
)
response.raise_for_status()
task = response.json()
if task["status"] != "completed":
raise RuntimeError(task.get("error") or task["status"])
for output in task["output"]:
filename = f"result-{output['index']}.png"
if output.get("b64_json"):
content = base64.b64decode(output["b64_json"])
else:
result = requests.get(output["content_url"], headers=headers, timeout=120)
result.raise_for_status()
content = result.content
with open(filename, "wb") as file:
file.write(content)
```
```typescript TypeScript theme={null}
import { writeFile } from "node:fs/promises";
const baseUrl = "https://aihubmix.com";
const headers = {
Authorization: `Bearer ${process.env.AIHUBMIX_API_KEY}`,
"Content-Type": "application/json",
};
const created = await fetch(`${baseUrl}/ai/v1/images/generations`, {
method: "POST",
headers,
body: JSON.stringify({
model: "qwen-image-2.0",
prompt: "A flower shop with delicate windows, warm sunlight streaming in",
n: 1,
size: "1024x1024",
async: true,
}),
});
if (!created.ok) throw new Error(await created.text());
let task = await created.json();
const finished = new Set(["completed", "failed", "cancelled"]);
while (!finished.has(task.status)) {
await new Promise((resolve) => setTimeout(resolve, 15_000));
const polled = await fetch(`${baseUrl}/ai/v1/images/${task.id}`, { headers });
if (!polled.ok) throw new Error(await polled.text());
task = await polled.json();
}
if (task.status !== "completed") {
throw new Error(JSON.stringify(task.error ?? task.status));
}
for (const output of task.output) {
let content;
if (output.b64_json) {
content = Buffer.from(output.b64_json, "base64");
} else {
const result = await fetch(output.content_url, { headers });
if (!result.ok) throw new Error(await result.text());
content = Buffer.from(await result.arrayBuffer());
}
await writeFile(`result-${output.index}.png`, content);
}
```
## 常见问题
**图片任务应该查询 `/ai/v1/tasks/{id}` 还是图片详情接口?**
轮询使用 `/ai/v1/images/{id}`;统一筛选任务或读取 `result_id`、`content_type` 时使用
`/ai/v1/tasks`。
**创建响应丢失后如何找回任务?**
请求 `GET /ai/v1/images?limit=20&order=desc`,再用返回的任务 ID 查询图片详情。
**Webhook 没收到怎么办?**
确认回调地址可以公开访问并及时返回 `2xx`,然后使用图片详情接口确认最终状态。
更多跨媒体背景参阅 [异步任务](/cn/api/async-tasks)、
[Webhook 说明](/cn/api/async-tasks#webhooks) 和
[完整错误码](/cn/api/async-tasks#error-codes)。
# 视频生成
Source: https://docs.aihubmix.com/cn/api/aihubmix-video-generation
使用 AIHubMix 原生视频协议创建异步任务、查询状态并下载视频。
AIHubMix 原生视频协议使用 `/ai/v1/videos` 系列端点。视频生成固定异步,请求提交后返回
任务 ID,客户端轮询详情或接收 Webhook,完成后下载视频。
使用豆包 Seedance 引用本人已确认的素材时,请先阅读[豆包真人素材使用指南](/cn/api/doubao-real-person-assets)。
使用原生视频任务接口前,需要为当前账户开启异步任务功能。未开启时,任务创建请求返回
`403 async_not_enabled`。
## 快速开始
下面使用 `wan2.6-t2v` 创建一个 5 秒视频。
```bash 创建任务 theme={null}
curl -X POST https://aihubmix.com/ai/v1/videos \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "wan2.6-t2v",
"prompt": "Ocean waves crashing on rocky cliffs at sunset",
"duration": 5,
"size": "1280x720"
}'
```
```json 创建响应 theme={null}
{
"id": "task_01K0ABCDEF",
"object": "video",
"model": "wan2.6-t2v",
"status": "in_progress",
"output": [],
"error": null,
"created_at": 1784707200,
"completed_at": null,
"expires_at": null
}
```
```bash 查询任务 theme={null}
curl https://aihubmix.com/ai/v1/videos/{id} \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
```
```bash 下载视频 theme={null}
curl https://aihubmix.com/ai/v1/videos/{id}/content \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
--output result.mp4
```
## 接口概览
| 场景 | 方法 | 路径 | 说明 |
| ------ | ---- | ---------------------------- | ---------------------- |
| 创建视频 | POST | `/ai/v1/videos` | 提交固定异步的视频生成任务 |
| 查询视频详情 | GET | `/ai/v1/videos/{id}` | 返回任务最新状态 |
| 查询视频列表 | GET | `/ai/v1/videos` | 返回当前 API Key 创建的视频任务快照 |
| 下载视频 | GET | `/ai/v1/videos/{id}/content` | 下载任务的主视频结果 |
Base URL:`https://aihubmix.com`
认证方式:
```text theme={null}
Authorization: Bearer $AIHUBMIX_API_KEY
```
## 查询模型 Schema
模型目录可以筛选已经提供请求 Schema 的文生视频模型:
```bash theme={null}
curl "https://aihubmix.com/api/v1/models?type=video&schema_checked=true&sort_by=order"
```
取得 `model_id` 后,查询该模型实际支持的端点:
```bash theme={null}
curl "https://aihubmix.com/call/schema/models/wan2.6-t2v/endpoints"
```
同一模型可能同时返回 AIHubMix 原生与 OpenAI 兼容端点。应按 `path` 选择原生视频接口,
再读取对应的 `request.schema`:
```bash theme={null}
curl -s "https://aihubmix.com/call/schema/models/wan2.6-t2v/endpoints" \
| jq '.endpoints[] | select(.path == "/ai/v1/videos") | .request.schema'
```
不要依赖 `endpoints` 数组位置。完整响应字段和失败情况参阅
[模型 Schema 接口](/cn/api/async-tasks#model-schema)。
## 创建视频
视频请求始终异步,不支持通过 `Prefer: wait` 改为同步等待。原生协议使用整数
`duration` 表示秒数;不要沿用 `/v1/videos` 兼容协议中的字符串 `seconds`。
### 标准字段
| 字段 | 类型 | 必填 | 说明 |
| ----------------------- | ------------ | -- | ---------------------------------------------------- |
| `model` | string | 是 | 模型 ID |
| `prompt` | string | 是 | 视频描述,不能为空 |
| `duration` | integer/null | 否 | 视频时长,单位为秒 |
| `aspect_ratio` | string/null | 否 | 宽高比,协议默认值为 `16:9` |
| `resolution` | string/null | 否 | `480p`、`720p`、`1080p`、`1K`、`2K` 或 `4K` |
| `size` | string/null | 否 | `{width}x{height}`,可代替 `resolution` 与 `aspect_ratio` |
| `seed` | integer/null | 否 | 随机种子 |
| `input_references` | array/null | 否 | 图片、视频或音频参考素材 |
| `frame_images` | array/null | 否 | 首帧或尾帧图片 |
| `generate_audio` | boolean/null | 否 | 是否生成音轨 |
| `webhook_url` | string | 否 | HTTPS 回调地址,最长 512 字符 |
| `webhook_events_filter` | string\[] | 否 | `completed`、`failed`、`cancelled` 的非空子集 |
| `extra` | object/null | 否 | 模型专属扩展参数 |
参考媒体项示例:
```json theme={null}
{
"type": "image_url",
"url": "https://example.com/reference.png"
}
```
`input_references[].type` 可以是 `image_url`、`video_url` 或 `audio_url`。首尾帧使用
`frame_images`:
```json theme={null}
{
"frame_type": "first_frame",
"image_url": {
"url": "https://example.com/first-frame.png"
}
}
```
标准字段集合不表示所有模型支持全部字段。`duration`、分辨率、参考媒体结构和枚举范围
必须以该模型 `/ai/v1/videos` 端点的 `request.schema` 为准。
## 视频任务对象
创建接口先返回任务对象。任务完成后,详情接口返回以下结构:
```json theme={null}
{
"id": "task_01K0ABCDEF",
"object": "video",
"model": "wan2.6-t2v",
"status": "completed",
"output": [
{
"index": 0,
"type": "file",
"b64_json": null,
"content_url": "https://aihubmix.com/ai/v1/videos/task_01K0ABCDEF/content"
}
],
"error": null,
"created_at": 1784707200,
"completed_at": 1784707320,
"expires_at": 1784714520
}
```
| 字段 | 类型 | 说明 |
| -------------- | ------------ | -------------------------------------------- |
| `id` | string | 平台任务 ID |
| `object` | string | 视频任务固定为 `video` |
| `model` | string | 实际使用的模型 ID |
| `status` | string | 当前任务状态 |
| `output` | array | 已生成的结果;尚无结果时为空数组 |
| `error` | object/null | 失败信息,可含 `code`、`message` 和 `upstream_detail` |
| `created_at` | integer | 创建时间,Unix 秒 |
| `completed_at` | integer/null | 进入结束态的时间,Unix 秒 |
| `expires_at` | integer/null | 结果过期时间,Unix 秒;任务完成前可能为空 |
视频媒体接口的 `output` 项包含 `index`、固定值 `type: "file"`、`content_url`,以及通常
为空的 `b64_json`。视频结果一般通过二进制内容端点下载。
### 状态说明
| 状态 | 是否结束 | 说明 |
| ------------- | ---- | --------------- |
| `pending` | 否 | 已接收,等待执行 |
| `in_progress` | 否 | 正在生成 |
| `completed` | 是 | 已完成,可下载视频 |
| `failed` | 是 | 已失败,原因见 `error` |
| `cancelled` | 是 | 已取消 |
客户端可以每 15 秒查询一次,直到状态变为 `completed`、`failed` 或 `cancelled`。
15 秒是客户端轮询建议,不是服务端协议限制。
## 查询视频任务
### 查询详情
```bash theme={null}
curl https://aihubmix.com/ai/v1/videos/{task_id} \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
```
视频详情接口会返回任务最新状态。轮询必须使用该接口,不要使用统一任务详情代替。
### 查询列表
创建响应丢失时,可以通过视频列表找回任务 ID:
```bash theme={null}
curl "https://aihubmix.com/ai/v1/videos?limit=20&order=desc" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
```
| 参数 | 类型 | 默认值 | 说明 |
| ------- | ------- | ------ | ------------------------ |
| `after` | string | - | 分页游标,使用上一页的 `next_after` |
| `limit` | integer | `20` | 每页数量,最大 `100` |
| `order` | string | `desc` | `asc` 为升序,其他值按 `desc` 处理 |
```json theme={null}
{
"object": "list",
"data": [
{
"id": "task_01K0ABCDEF",
"object": "video",
"model": "wan2.6-t2v",
"status": "in_progress",
"output": [],
"error": null,
"created_at": 1784707200,
"completed_at": null,
"expires_at": null
}
],
"has_more": true,
"next_after": "task_01K0ABCDEF"
}
```
列表返回查询时的任务快照,不会主动更新活动任务状态。
## 统一任务接口
`/ai/v1/tasks` 提供图片、视频和 LLM 任务的统一只读视图。可以只查询视频任务:
```bash theme={null}
curl "https://aihubmix.com/ai/v1/tasks?object=video&status=completed&limit=20&order=desc" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
```
统一任务列表支持 `object`、`status`、`model`、`after`、`limit` 和 `order`。统一任务详情:
```bash theme={null}
curl https://aihubmix.com/ai/v1/tasks/{task_id} \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
```
统一任务中的视频结果会额外提供 `result_id` 和 `content_type`:
```json theme={null}
{
"index": 0,
"result_id": "result_01K0XYZ",
"type": "file",
"content_type": "video/mp4",
"content_url": "https://aihubmix.com/ai/v1/tasks/task_01K0ABCDEF/content"
}
```
单产物可以请求 `/ai/v1/tasks/{id}/content`。若统一任务包含多个结果,则请求
`/ai/v1/tasks/{id}/content/{result_id}`;未指定结果 ID 时返回 `400 result_id_required`。
媒体详情接口可能在查询时更新活动任务状态,统一任务接口只返回当前快照。因此轮询使用
`/ai/v1/videos/{id}`;统一筛选和读取结果元数据时使用 `/ai/v1/tasks`。
任务及内容按创建任务时的 Bearer Token 隔离。
## 下载视频结果
任务进入 `completed` 后,请求视频内容端点:
```bash theme={null}
curl https://aihubmix.com/ai/v1/videos/{task_id}/content \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
--output result.mp4
```
响应为视频二进制,不是 JSON。也可以直接请求任务对象返回的 `output[].content_url`;
两种方式都需要携带创建任务时的 Bearer Token。
结果可能过期,也可能存在下载次数限制。过期返回 `410 artifact_expired`;超过下载
次数限制返回 `429 too_many_downloads`。客户端应在任务完成后及时保存视频。
## Webhook
创建视频任务时可以同时设置任务级 Webhook:
```bash theme={null}
curl -X POST https://aihubmix.com/ai/v1/videos \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "wan2.6-t2v",
"prompt": "A tranquil garden at sunrise",
"duration": 5,
"size": "1280x720",
"webhook_url": "https://example.com/webhooks/aihubmix"
}'
```
`webhook_url` 最长 512 字符,不能指向本机、私网或其他受限地址。`wan2.6-t2v`
当前 Schema 未列出 `webhook_events_filter`,因此本例不传事件过滤器,平台默认推送
`completed`、`failed` 和 `cancelled`。只有模型 Schema 明确包含该字段时才可以设置;
显式传入时,数组不能为空、不能重复,并且必须与 `webhook_url` 一起使用。
### 回调请求
```json theme={null}
{
"event_id": "evt_01K0ABCDEF",
"event_type": "completed",
"created_at": "2026-08-12T12:00:00Z",
"data": {
"task_id": "task_01K0ABCDEF",
"status": "completed",
"model": "wan2.6-t2v",
"results": [
{
"url": "https://aihubmix.com/ai/v1/tasks/task_01K0ABCDEF/content"
}
]
}
}
```
`event_id` 用于去重;`data.error` 在失败时可能出现;`data.results` 只在结果已存档时出现,
下载仍需 Bearer Token。
### 重试与去重
平台采用至少一次投递,同一个事件可能重复送达:
* HTTP `2xx` 表示接收成功。
* HTTP `5xx`、网络错误或超时会触发重试。
* HTTP `3xx` 和 `4xx` 不会重试。
* 最多投递 6 次,重试间隔依次为 1、4、16、64、256 秒。
接收端应保存 `event_id`,重复收到相同事件时直接返回 `2xx`。任务级 Webhook 本身不
携带独立签名密钥;需要签名验证时,请配置账户级 Webhook,并保留详情查询作为结果确认方式。
## 错误响应与错误码
本节只列 `/ai/v1/videos/*` 及其视频 Task 适用的稳定公共错误码。客户端需要同时检查
HTTP 状态码和任务对象的 `status`。
```json theme={null}
{
"error": {
"message": "Task not found.",
"type": "invalid_request_error",
"code": "task_not_found",
"tid": "req_01K0ABCDEF"
}
}
```
请求返回 HTTP `5xx` 时,请提交反馈并附上 `error.tid`。
### HTTP 非 2xx 错误
`invalid_request` 和 `schema_violation` 行展示的是兜底 message。服务能够定位具体字段或
参数约束时会返回动态 message;客户端应以 `code` 判断错误类型,不要依赖 message 固定匹配。
| HTTP | `code` | `message` | 说明 |
| ---- | -------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| 400 | `invalid_request` | `Invalid request. Check the request body and parameters.`(兜底模板;实际可能返回动态 message) | 公共请求体或字段类型不正确;此 code 的 message 不是固定值,能够定位字段时会返回更具体的动态 message |
| 400 | `model_not_found` | `The requested model is not available. Check the model name and your account access.` | 模型不存在、不可用,或当前账户无权访问 |
| 400 | `schema_violation` | `Invalid request: one or more parameters are invalid.`(兜底模板;实际可能返回动态 message) | 请求不符合当前视频模型的参数 Schema;此 code 的 message 不是固定值,能够定位字段或约束时会返回字段级动态 message |
| 400 | `capability_not_supported` | `The requested parameters are not supported for this model.` | 当前视频模型不支持请求中的字段、数量或参数上限 |
| 400 | `media_form_unsupported` | 动态媒体提示,见下文 | 参考图、首帧、尾帧或其他媒体输入的格式、数据、URL 或大小无法处理 |
| 400 | `upstream_rejected` | `Upstream service rejected the request.` | 模型推理厂商拒绝了视频生成请求 |
| 401 | `authentication_failed` | `Authentication failed: invalid or missing API key.` | API Key 缺失或无效 |
| 402 | `insufficient_quota` | `Insufficient quota.` | AIHubMix 账户可用额度不足 |
| 403 | `permission_denied` | `You do not have permission to access this resource.` | 当前账户、API Key 或访问来源无权使用该资源 |
| 403 | `async_not_enabled` | `Asynchronous tasks are not enabled. Please go to /async-tasks to activate.` | 当前账户未开通异步视频任务功能;控制台地址会按请求站点生成 |
| 404 | `task_not_found` | `Task not found.` | 视频任务不存在、分页游标无效,或当前账户无权查看 |
| 404 | `result_not_found` | `Result not found.` | 视频结果不存在、尚未就绪、结果 ID 不匹配,或当前账户无权下载 |
| 410 | `artifact_expired` | `The result has expired.` | 视频结果已超过保留期 |
| 413 | `request_too_large` | `Request body is too large. Reduce the request size and try again.` | 整体请求体超过 32 MiB |
| 429 | `rate_limited` | `Too many requests. Please slow down and retry.` | AIHubMix 对当前账户或 API Key 限流 |
| 429 | `upstream_rate_limited` | `Upstream service is rate limiting. Please retry later.` | 模型推理厂商返回限流错误 |
| 429 | `too_many_downloads` | `Download limit exceeded for this result.` | 单个视频结果达到下载次数上限 |
| 500 | `internal_error` | `Internal error. Please retry.` | 服务发生调用方无法修复的内部错误 |
| 502 | `upstream_unreachable` | `Upstream service is temporarily unavailable. Please retry.` | 无法连接模型推理厂商,或无法完整读取其响应 |
| 502 | `upstream_bad_response` | `Upstream service returned an invalid response.` | 模型推理厂商返回了平台无法处理的响应 |
| 502 | `upstream_error` | `Upstream service is temporarily unavailable. Please retry.` | 模型推理厂商返回服务错误 |
| 503 | `model_unavailable` | `The requested model is temporarily unavailable.` | 所选视频模型暂时不可用 |
| 503 | `service_unavailable` | `Service is temporarily unavailable. Please retry.` | 查询、下载或结果服务暂时不可用 |
`media_form_unsupported` 会根据已确认的媒体输入原因返回具体 message,包括不支持的格式、
无效数据、URL 无法访问、内容无法解码和媒体超过限制。完整模板见
[异步任务错误码](/cn/api/async-tasks#error-codes)。
### HTTP 200 + Task `status=failed`
视频创建请求被接收后,后台仍可能把任务置为 `failed`。此时查询接口返回 HTTP 200,
客户端需要读取任务对象中的 `error`:
| Task `code` | `message` | 说明 |
| ------------------------- | --------------------------------------------------------------------------------- | -------------------------- |
| `media_form_unsupported` | 动态媒体提示 | 参考图、首帧、尾帧或其他媒体输入无法处理 |
| `upstream_rejected` | `Upstream service rejected the request.` | 模型推理厂商拒绝创建请求 |
| `upstream_rate_limited` | `Upstream service is rate limiting. Please retry later.` | 模型推理厂商返回限流错误 |
| `upstream_unreachable` | `Upstream service is temporarily unavailable. Please retry.` | 创建任务时无法连接模型推理厂商,或无法完整读取其响应 |
| `upstream_bad_response` | `Upstream service returned an invalid response.` | 模型推理厂商响应无法处理 |
| `upstream_error` | `Upstream service is temporarily unavailable. Please retry.` | 模型推理厂商创建或执行任务失败 |
| `upstream_empty_output` | `The upstream service completed without producing a usable result. Please retry.` | 模型推理厂商完成任务,但没有产生可交付视频 |
| `output_policy_violation` | `Generated content was rejected by the content policy.` | 生成视频未通过内容安全策略 |
| `internal_error` | `Internal error. Please retry.` | 视频任务处理发生内部错误 |
HTTP 非 2xx 响应中的 `error.tid` 是请求追踪 ID。Task `status=failed` 当前不单独返回
`tid`,任务 ID 是对应的排查标识。
## 完整示例
以下示例完成创建、轮询和 MP4 下载。
```python Python theme={null}
import os
import time
import requests
base_url = "https://aihubmix.com"
headers = {
"Authorization": f"Bearer {os.environ['AIHUBMIX_API_KEY']}",
"Content-Type": "application/json",
}
response = requests.post(
f"{base_url}/ai/v1/videos",
headers=headers,
json={
"model": "wan2.6-t2v",
"prompt": "A cat playing jazz on a piano",
"duration": 5,
"size": "1280x720",
},
timeout=60,
)
response.raise_for_status()
task = response.json()
while task["status"] not in {"completed", "failed", "cancelled"}:
time.sleep(15)
response = requests.get(
f"{base_url}/ai/v1/videos/{task['id']}",
headers=headers,
timeout=30,
)
response.raise_for_status()
task = response.json()
if task["status"] == "completed":
result = requests.get(
f"{base_url}/ai/v1/videos/{task['id']}/content",
headers=headers,
timeout=120,
)
result.raise_for_status()
with open("result.mp4", "wb") as file:
file.write(result.content)
else:
raise RuntimeError(task.get("error") or task["status"])
```
```typescript TypeScript theme={null}
import { writeFile } from "node:fs/promises";
const baseUrl = "https://aihubmix.com";
const headers = {
Authorization: `Bearer ${process.env.AIHUBMIX_API_KEY}`,
"Content-Type": "application/json",
};
const created = await fetch(`${baseUrl}/ai/v1/videos`, {
method: "POST",
headers,
body: JSON.stringify({
model: "wan2.6-t2v",
prompt: "A cat playing jazz on a piano",
duration: 5,
size: "1280x720",
}),
});
if (!created.ok) throw new Error(await created.text());
let task = await created.json();
const finished = new Set(["completed", "failed", "cancelled"]);
while (!finished.has(task.status)) {
await new Promise((resolve) => setTimeout(resolve, 15_000));
const polled = await fetch(`${baseUrl}/ai/v1/videos/${task.id}`, { headers });
if (!polled.ok) throw new Error(await polled.text());
task = await polled.json();
}
if (task.status === "completed") {
const result = await fetch(`${baseUrl}/ai/v1/videos/${task.id}/content`, {
headers,
});
if (!result.ok) throw new Error(await result.text());
await writeFile("result.mp4", Buffer.from(await result.arrayBuffer()));
} else {
throw new Error(JSON.stringify(task.error ?? task.status));
}
```
## 常见问题
**视频任务应该查询 `/ai/v1/tasks/{id}` 还是视频详情接口?**
轮询使用 `/ai/v1/videos/{id}`;统一筛选任务或读取 `result_id`、`content_type` 时使用
`/ai/v1/tasks`。
**为什么 `seconds` 报参数错误?**
`/ai/v1/videos` 标准协议使用整数 `duration`,单位为秒,具体允许值由模型 Schema 决定。
**为什么 `resolution` 在部分模型中报参数错误?**
标准协议包含 `resolution` 和 `size`,具体模型会收窄字段。例如 `wan2.6-t2v` 使用
`size`,不接受 `resolution`。
**创建响应丢失后如何找回任务?**
请求 `GET /ai/v1/videos?limit=20&order=desc`,再用返回的任务 ID 查询视频详情。
**Webhook 没收到怎么办?**
确认回调地址可以公开访问并及时返回 `2xx`,然后使用视频详情接口确认最终状态。
更多跨媒体背景参阅 [异步任务](/cn/api/async-tasks)、
[Webhook 说明](/cn/api/async-tasks#webhooks) 和
[完整错误码](/cn/api/async-tasks#error-codes)。
# 异步任务
Source: https://docs.aihubmix.com/cn/api/async-tasks
AIHubMix 图片、视频与统一任务协议:创建媒体任务、查询状态、下载结果、接收 Webhook,以及恢复中断后的 LLM 响应。
AIHubMix 提供三组任务接口:图片使用 `/ai/v1/images`,视频使用 `/ai/v1/videos`,统一任务记录使用 `/ai/v1/tasks`。
* 图片生成默认同步,传入 `async: true` 后异步执行。
* 视频生成固定异步。
* 图片和视频详情接口用于获取媒体任务的最新状态。
* `/ai/v1/tasks` 提供图片、视频和 LLM 任务的统一只读视图。
豆包 Seedance 视频需要引用真人素材时,先按[豆包真人素材使用指南](/cn/api/doubao-real-person-assets)完成本人确认和素材准备,再创建视频任务。
讲解异步任务的整体机制,并以异步生图为例演示完整调用流程。
使用 `/ai/v1` 媒体任务接口前,请先为当前账户开启异步任务功能。
未开启异步任务功能时,图片和视频任务创建请求返回 `403 async_not_enabled`。
***
## 快速开始
以下示例使用 `wan2.6-t2v` 创建视频。该模型接受 `duration` 和 `size`;不同模型的有效字段可能不同。
```shell curl theme={null}
# 1. 创建视频任务,保存响应中的 id
curl -X POST https://aihubmix.com/ai/v1/videos \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "wan2.6-t2v",
"prompt": "A cat playing jazz on a piano, warm lighting, cinematic shot",
"duration": 5,
"size": "1280x720"
}'
# 2. 每 15 秒查询一次媒体详情
curl https://aihubmix.com/ai/v1/videos/{task_id} \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
# 3. completed 后下载视频
curl https://aihubmix.com/ai/v1/videos/{task_id}/content \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
--output result.mp4
```
```json 创建响应 theme={null}
{
"id": "task_01K0ABCDEF",
"object": "video",
"model": "wan2.6-t2v",
"status": "in_progress",
"output": [],
"error": null,
"created_at": 1784707200,
"completed_at": null,
"expires_at": null
}
```
***
## 三组接口如何选择
| 场景 | 方法 | 路径 | 行为 |
| ------------- | ---- | ------------------------------------------------ | --------------------------- |
| 生成图片 | POST | `/ai/v1/images/generations` | 默认同步,可通过 `async: true` 改为异步 |
| 查询图片详情 | GET | `/ai/v1/images/{id}` | 返回图片任务状态;活动任务可能在查询时更新状态 |
| 查询图片列表 | GET | `/ai/v1/images` | 返回图片任务快照 |
| 下载指定图片 | GET | `/ai/v1/images/{id}/content/{result_id}` | 下载多图任务中的指定结果 |
| 创建视频 | POST | `/ai/v1/videos` | 固定异步 |
| 查询视频详情 | GET | `/ai/v1/videos/{id}` | 返回视频任务状态;活动任务可能在查询时更新状态 |
| 查询视频列表 | GET | `/ai/v1/videos` | 返回视频任务快照 |
| 下载视频 | GET | `/ai/v1/videos/{id}/content` | 下载任务的主视频结果 |
| 获取异步媒体模型列表 | GET | `/api/v1/models?type={type}&schema_checked=true` | 返回已提供请求 Schema 的文生图或文生视频模型 |
| 获取模型请求 Schema | GET | `/call/schema/models/{model}/endpoints` | 返回文生图或文生视频端点及其 JSON Schema |
| 查询统一任务列表 | GET | `/ai/v1/tasks` | 只读查询图片、视频和 LLM 任务 |
| 查询统一任务详情 | GET | `/ai/v1/tasks/{id}` | 返回查询时的只读任务快照 |
| 获取统一任务结果 | GET | `/ai/v1/tasks/{id}/content` | 下载单产物或读取 LLM 存档 |
| 获取指定统一任务结果 | GET | `/ai/v1/tasks/{id}/content/{result_id}` | 下载多产物任务中的指定结果 |
Base URL 为 `https://aihubmix.com`,认证方式为 Bearer Token:
```bash theme={null}
Authorization: Bearer $AIHUBMIX_API_KEY
```
模型列表和模型 Schema 都是公开发现接口,无需 Bearer Token。其余接口均需认证。
`/ai/v1/tasks` 不提供创建接口。图片和视频必须通过对应的媒体生成接口创建;LLM
恢复任务由平台在客户端中断后自动保存。
### 媒体接口和统一任务接口的区别
媒体详情接口与统一任务接口返回相同的任务顶层字段,但 `output` 项和查询行为不同:
| 对比项 | 媒体详情 `/images/{id}`、`/videos/{id}` | 统一任务详情 `/tasks/{id}` |
| -------- | --------------------------------------- | ---------------------------------------------------------------- |
| 任务类型 | 图片或视频 | 图片、视频或 LLM |
| 查询行为 | 活动任务可能在查询时更新状态 | 返回查询时的只读任务快照 |
| 媒体输出字段 | `index`、`type`、`content_url`、`b64_json` | `index`、`result_id`、`type`、`content_type`、`content_url` |
| LLM 输出字段 | 不适用 | `index`、`type=response`、`content_type`、`content_url`、`truncated` |
| 访问范围 | 当前账户创建的对应媒体任务 | 当前 Bearer Token 创建的任务 |
因此,轮询媒体生成状态时应使用图片或视频详情接口;需要统一筛选任务、读取结果元数据或恢复 LLM 响应时使用 `/ai/v1/tasks`。
***
## 如何发现异步媒体模型并获取 Schema
调用流程分为两步。先从公共模型目录取得支持异步接口的文生图或文生视频模型,再用模型的 `model_id` 获取对应端点的请求 Schema。
### 获取支持异步接口的模型列表
模型目录与 Playground 使用同一数据源。`type=image_generation` 返回文生图模型,`type=video` 返回文生视频模型。增加 `schema_checked=true` 后,列表只包含已经提供并核对请求 Schema 的模型。
```bash theme={null}
# 文生图模型
curl "https://aihubmix.com/api/v1/models?type=image_generation&schema_checked=true&sort_by=order"
# 文生视频模型
curl "https://aihubmix.com/api/v1/models?type=video&schema_checked=true&sort_by=order"
```
两个请求使用同一个接口。`type` 当前为单值筛选,获取两类模型时需要分别请求。
响应为 `{success, message, data}`。`data` 中与异步媒体接入相关的字段如下。
| 字段 | 说明 |
| ------------------------- | ------------------------------------------- |
| `data[].model_id` | 模型 ID,用于生成请求和后续 Schema 查询 |
| `data[].model_name` | 模型显示名称 |
| `data[].types` | 逗号分隔的模型类型,可能同时包含 `image_generation` 和 `llm` |
| `data[].input_modalities` | 逗号分隔的输入模态 |
| `data[].schema_checked` | `true` 表示该模型已经提供并核对请求 Schema |
```json theme={null}
{
"success": true,
"message": "",
"data": [
{
"model_id": "qwen-image-2.0",
"model_name": "Qwen Image 2.0",
"types": "image_generation",
"input_modalities": "text,image",
"schema_checked": true
}
]
}
```
### 获取单个模型的请求 Schema
不同模型支持的字段、枚举和数值范围可能不同。提交图片或视频请求前,可以通过同一个公开接口获取指定模型当前可用的端点和请求 JSON Schema。
```bash theme={null}
# 文生图模型
curl "https://aihubmix.com/call/schema/models/qwen-image-2.0/endpoints"
# 文生视频模型
curl "https://aihubmix.com/call/schema/models/wan2.6-t2v/endpoints"
```
响应中的 `modality` 为 `image` 或 `video`。`endpoints` 数组中的每一项描述一个可用调用协议。
| 字段 | 说明 |
| ---------------------------- | -------------------------------------- |
| `default_endpoint` | 当前模型的默认端点标识 |
| `endpoints[].endpoint` | 端点标识 |
| `endpoints[].method` | 请求方法,例如 `POST` |
| `endpoints[].path` | 实际提交路径 |
| `endpoints[].content_types` | 端点接受的内容类型 |
| `endpoints[].lifecycle` | 同步或异步模式、轮询路径和状态值 |
| `endpoints[].request.schema` | 该模型在对应端点下的完整请求 JSON Schema,包括必填字段和取值约束 |
同一个模型可能同时返回 `/ai/v1` 与 OpenAI 兼容 `/v1` 端点。OpenAI 兼容接口可能暂不支持最新模型,请优先使用 `/ai/v1` 端点。异步任务接口应按 `path` 选择 `/ai/v1/images/generations` 或 `/ai/v1/videos`,再读取该项的 `request.schema`。不要依赖 `endpoints` 数组位置。
下面的命令可直接提取两个异步任务端点的请求 Schema。
```bash theme={null}
# 文生图
curl -s "https://aihubmix.com/call/schema/models/qwen-image-2.0/endpoints" \
| jq '.endpoints[] | select(.path == "/ai/v1/images/generations") | .request.schema'
# 文生视频
curl -s "https://aihubmix.com/call/schema/models/wan2.6-t2v/endpoints" \
| jq '.endpoints[] | select(.path == "/ai/v1/videos") | .request.schema'
```
模型不存在或尚未提供可发现端点时,接口返回 `404 model_not_found`。端点数据暂时不可用时返回 `500 endpoints_unavailable`。
***
## 支持的模型和字段
图片和视频协议都定义了跨模型标准字段,但每个模型会基于实际能力收窄字段、枚举和数值范围。调用前应通过[模型 Schema 接口](#model-schema)获取对应模型的当前参数约束。
例如:
* `wan2.6-t2v` 支持 `duration`、`size` 和 `seed`,不接受 `resolution`、`aspect_ratio`、`frame_images`、`input_references` 或 `generate_audio`。
* `qwen-image-2.0` 支持 `n`、`size`、`seed`、`negative_prompt`、`image` 和 `images`,不接受 `aspect_ratio` 或 `mask`。
标准字段集合不代表所有模型支持全部字段。传入当前模型不支持的字段会返回参数错误。
### LLM 中断恢复模型
当前支持以下模型:
* gpt-5.6-sol
* gpt-5.5-pro
* gpt-5.4-pro
* gpt-5.2-pro
* claude-fable-5
* claude-opus-5
支持范围可能调整,请以本页清单为准。使用中断恢复还需要当前账户已开启异步任务功能。任一条件不满足时,原 LLM 请求仍会正常执行,但客户端断开后不会保存恢复任务。
***
## 如何创建图片任务
### 同步图片
省略 `async` 或设置为 `false` 时,接口会等待生成完成并返回任务对象:
```bash theme={null}
curl -X POST https://aihubmix.com/ai/v1/images/generations \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-image-2.0",
"prompt": "A flower shop with delicate windows, warm sunlight streaming in",
"n": 1,
"size": "1024x1024",
"response_format": "url"
}'
```
同步图片任务也会保存任务记录。客户端连接中断或创建响应丢失时,可以通过 `GET /ai/v1/images` 查找对应任务。
### 异步图片
将 `async` 设置为布尔值 `true` 后,接口会立即返回任务对象,生成在后台继续:
```bash theme={null}
curl -X POST https://aihubmix.com/ai/v1/images/generations \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-image-2.0",
"prompt": "A flower shop with delicate windows, warm sunlight streaming in",
"n": 2,
"size": "1024x1024",
"async": true
}'
```
使用 `GET /ai/v1/images/{id}` 查询异步图片任务。完成后,直接请求每个 `output` 项中的 `content_url`;该 URL 已包含对应图片的 `result_id`。
图片请求中的 `async` 必须是布尔值。`webhook_url` 和 `webhook_events_filter`
仅能与 `async: true` 一起使用。
### 图片标准字段
| 字段 | 类型 | 必填 | 说明 |
| ----------------------- | ------------- | -- | ------------------------------------------- |
| `model` | string | 是 | 模型名称 |
| `prompt` | string | 是 | 图片描述,不能为空 |
| `n` | integer/null | 否 | 图片数量,最小值 `1`,默认 `1` |
| `size` | string/null | 否 | `{width}x{height}`,例如 `1024x1024` |
| `aspect_ratio` | string/null | 否 | 宽高比;与 `size` 二选一 |
| `seed` | integer/null | 否 | 随机种子 |
| `negative_prompt` | string/null | 否 | 负向提示词 |
| `image` | string/object | 否 | 单张输入图片,可以是 URL、Data URI、Base64 或 `{url}` 对象 |
| `images` | array/null | 否 | 多张输入图片 |
| `mask` | string/object | 否 | 图片编辑蒙版 |
| `output_format` | string/null | 否 | `png`、`jpeg` 或 `webp`,默认 `png` |
| `response_format` | string/null | 否 | `url` 或 `b64_json`,默认 `url` |
| `async` | boolean | 否 | 设为 `true` 时异步执行 |
| `webhook_url` | string | 否 | HTTPS 回调地址,最长 512 字符 |
| `webhook_events_filter` | string\[] | 否 | `completed`、`failed`、`cancelled` 的非空子集 |
| `extra` | object/null | 否 | 具体模型的扩展参数 |
***
## 如何创建视频任务
视频请求始终异步,不支持通过 `Prefer: wait` 改为同步等待。标准协议使用整数 `duration` 表示秒数:
```bash theme={null}
curl -X POST https://aihubmix.com/ai/v1/videos \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "wan2.6-t2v",
"prompt": "Ocean waves crashing on rocky cliffs at sunset",
"duration": 5,
"size": "1280x720"
}'
```
### 视频标准字段
| 字段 | 类型 | 必填 | 说明 |
| ----------------------- | ------------ | -- | ---------------------------------------------------- |
| `model` | string | 是 | 模型名称 |
| `prompt` | string | 是 | 视频描述,不能为空 |
| `duration` | integer/null | 否 | 视频时长,单位为秒;具体范围由模型决定 |
| `aspect_ratio` | string/null | 否 | 宽高比,协议默认值为 `16:9` |
| `resolution` | string/null | 否 | `480p`、`720p`、`1080p`、`1K`、`2K` 或 `4K` |
| `size` | string/null | 否 | `{width}x{height}`;可代替 `resolution` 与 `aspect_ratio` |
| `seed` | integer/null | 否 | 随机种子 |
| `input_references` | array/null | 否 | 图片、视频或音频参考素材 |
| `frame_images` | array/null | 否 | 首帧或尾帧图片 |
| `generate_audio` | boolean/null | 否 | 是否生成音轨 |
| `webhook_url` | string | 否 | HTTPS 回调地址,最长 512 字符 |
| `webhook_events_filter` | string\[] | 否 | `completed`、`failed`、`cancelled` 的非空子集 |
| `extra` | object/null | 否 | 具体模型的扩展参数 |
`input_references` 项的结构:
```json theme={null}
{
"type": "image_url",
"url": "https://example.com/reference.png"
}
```
`type` 可为 `image_url`、`video_url` 或 `audio_url`。
`frame_images` 项的结构:
```json theme={null}
{
"frame_type": "first_frame",
"image_url": {
"url": "https://example.com/first-frame.png"
}
}
```
`frame_type` 可为 `first_frame` 或 `last_frame`。
***
## 媒体任务对象
图片和视频专属接口返回以下结构:
```json theme={null}
{
"id": "task_01K0ABCDEF",
"object": "video",
"model": "wan2.6-t2v",
"status": "completed",
"output": [
{
"index": 0,
"type": "file",
"b64_json": null,
"content_url": "https://aihubmix.com/ai/v1/videos/task_01K0ABCDEF/content"
}
],
"error": null,
"created_at": 1784707200,
"completed_at": 1784707320,
"expires_at": null
}
```
| 字段 | 类型 | 说明 |
| -------------- | ------------ | -------------------------------------------- |
| `id` | string | 平台任务 ID |
| `object` | string | `image` 或 `video` |
| `model` | string | 模型名称 |
| `status` | string | 当前任务状态 |
| `output` | array | 已生成的结果;尚无结果时为空数组 |
| `error` | object/null | 失败信息,可含 `code`、`message` 和 `upstream_detail` |
| `created_at` | integer | 创建时间,Unix 秒 |
| `completed_at` | integer/null | 最终状态时间,Unix 秒 |
| `expires_at` | null | 媒体专属接口当前返回 `null` |
媒体 `output` 项:
| 字段 | 类型 | 说明 |
| ------------- | ----------- | -------------- |
| `index` | integer | 结果顺序,从 `0` 开始 |
| `type` | string | 当前为 `file` |
| `content_url` | string/null | 结果下载地址 |
| `b64_json` | string/null | Base64 编码的图片结果 |
### 状态说明
| 状态 | 是否结束 | 说明 |
| ------------- | ---- | ----------------- |
| `pending` | 否 | 平台已接收任务,等待执行 |
| `in_progress` | 否 | 任务正在执行 |
| `completed` | 是 | 任务完成,可读取 `output` |
| `failed` | 是 | 任务失败,原因见 `error` |
| `cancelled` | 是 | 任务已取消 |
客户端可以每 15 秒查询一次,直到状态变为 `completed`、`failed` 或 `cancelled`。15 秒是客户端轮询建议,不是服务端协议限制。
***
## 如何查询媒体任务
### 查询媒体详情
```bash theme={null}
# 图片
curl https://aihubmix.com/ai/v1/images/{task_id} \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
# 视频
curl https://aihubmix.com/ai/v1/videos/{task_id} \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
```
媒体详情接口可返回更新后的任务状态,因此媒体轮询应使用对应的图片或视频详情接口。
### 查询媒体列表
创建响应丢失时,可以通过对应媒体列表找回任务 ID:
```bash theme={null}
curl "https://aihubmix.com/ai/v1/videos?limit=20&order=desc" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
```
| 参数 | 类型 | 默认值 | 说明 |
| ------- | ------- | ------ | -------------------------- |
| `after` | string | - | 分页游标,使用上一页的 `next_after` |
| `limit` | integer | `20` | 每页数量,最大 `100` |
| `order` | string | `desc` | 传 `asc` 时升序,其他值按 `desc` 处理 |
```json theme={null}
{
"object": "list",
"data": [
{
"id": "task_01K0ABCDEF",
"object": "video",
"model": "wan2.6-t2v",
"status": "in_progress",
"output": [],
"error": null,
"created_at": 1784707200,
"completed_at": null,
"expires_at": null
}
],
"has_more": true,
"next_after": "task_01K0ABCDEF"
}
```
媒体列表返回查询时的任务快照,不会主动更新任务状态。
***
## 如何使用统一任务接口
统一任务接口支持以下筛选条件:
```bash theme={null}
curl "https://aihubmix.com/ai/v1/tasks?object=video&status=in_progress&limit=20&order=desc" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
```
| 参数 | 类型 | 默认值 | 说明 |
| -------- | ------- | ------ | ---------------------------------------------------------- |
| `object` | string | - | `llm`、`image` 或 `video` |
| `status` | string | - | `pending`、`in_progress`、`completed`、`failed` 或 `cancelled` |
| `model` | string | - | 按模型名称精确筛选 |
| `after` | string | - | 分页游标 |
| `limit` | integer | `20` | 范围 `1` 到 `100` |
| `order` | string | `desc` | `asc` 或 `desc` |
统一任务详情:
```bash theme={null}
curl https://aihubmix.com/ai/v1/tasks/{task_id} \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
```
媒体任务的统一 `output` 项:
```json theme={null}
{
"index": 0,
"result_id": "result_01K0XYZ",
"type": "file",
"content_type": "video/mp4",
"content_url": "https://aihubmix.com/ai/v1/tasks/task_01K0ABCDEF/content"
}
```
单产物直接请求 `/ai/v1/tasks/{id}/content`。多产物任务需要请求 `/ai/v1/tasks/{id}/content/{result_id}`;未指定结果 ID 时返回 `400 result_id_required`。
统一任务列表、详情和内容接口按创建任务时的 Bearer Token 隔离。同一账户下的其他
API Key 不能读取该任务。
***
## 如何下载媒体结果
### 下载图片
图片完成后,逐项请求媒体任务对象中的 `output[].content_url`:
```bash theme={null}
curl "{content_url}" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
--output result.png
```
图片的媒体下载路径为 `/ai/v1/images/{id}/content/{result_id}`。媒体任务对象不单独公开 `result_id`,客户端直接使用 `content_url` 即可。
当 `b64_json` 非空时,可以直接对该字段进行 Base64 解码。
### 下载视频
```bash theme={null}
curl https://aihubmix.com/ai/v1/videos/{task_id}/content \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
--output result.mp4
```
结果可能过期,并且可能存在下载次数限制。过期返回 `410
artifact_expired`,超过下载次数限制返回 `429 too_many_downloads`。
***
## 如何使用 Webhook
异步图片和视频支持任务级 Webhook:
```bash theme={null}
curl -X POST https://aihubmix.com/ai/v1/videos \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "wan2.6-t2v",
"prompt": "A tranquil garden at sunrise",
"duration": 5,
"size": "1280x720",
"webhook_url": "https://example.com/webhooks/aihubmix",
"webhook_events_filter": ["completed", "failed"]
}'
```
`webhook_url` 最长 512 字符,并且不能指向本机、私网或其他受限地址。省略 `webhook_events_filter` 时,平台推送 `completed`、`failed` 和 `cancelled`;显式传入时,数组不能为空、不能重复,并且必须与 `webhook_url` 一起使用。
未在请求中传入 `webhook_url` 时,异步图片和视频会尝试使用账户中配置的默认回调地址。无效的账户默认地址会被忽略,不会阻止任务创建。
### 回调请求
```json theme={null}
{
"event_id": "evt_01K0ABCDEF",
"event_type": "completed",
"created_at": "2026-08-12T12:00:00Z",
"data": {
"task_id": "task_01K0ABCDEF",
"status": "completed",
"model": "wan2.6-t2v",
"results": [
{
"url": "https://aihubmix.com/ai/v1/tasks/task_01K0ABCDEF/content"
}
]
}
}
```
| 字段 | 说明 |
| -------------------- | ---------------------------------- |
| `event_id` | 回调事件 ID,用于去重 |
| `event_type` | `completed`、`failed` 或 `cancelled` |
| `created_at` | RFC 3339 格式的事件时间 |
| `data.task_id` | 平台任务 ID |
| `data.status` | 当前最终状态 |
| `data.model` | 模型名称 |
| `data.results[].url` | 完成时可能返回的结果下载地址 |
| `data.error` | 失败时可能返回的错误信息 |
`results` 仅在结果已存档时出现,下载仍需 Bearer Token。
### 重试与去重
平台采用至少一次投递,同一个事件可能重复送达:
* HTTP `2xx` 表示接收成功。
* HTTP `5xx`、网络错误或超时会触发重试。
* HTTP `3xx` 和 `4xx` 不会重试。
* 最多投递 6 次,重试间隔依次为 1、4、16、64、256 秒。
接收端应保存 `event_id`,重复收到相同事件时直接返回 `2xx`。
任务级 Webhook 本身不携带独立签名密钥。需要签名验证时,请配置账户级 Webhook
订阅,并保留任务详情查询作为结果确认方式。
***
## LLM 中断恢复如何生效
LLM 中断恢复用于取回客户端断开连接后的最终响应。请求方式、流式行为和响应格式保持不变,也不会在请求开始时预先返回任务 ID。
以下条件需要同时满足:
| 条件 | 说明 |
| ----------- | ------------------------------------------------------------------------------------------------------ |
| 账户已开启异步任务功能 | 在 AIHubMix 控制台为当前账户开启 |
| 模型支持中断恢复 | 当前模型在 [LLM 中断恢复模型](#supported-models-llm) 清单中 |
| 接口受支持 | Chat Completions、Anthropic Messages、Responses API 或 Gemini `generateContent` / `streamGenerateContent` |
| 客户端中断 | 客户端取消、网络断开或调用方取消请求 |
平台仅在检测到响应未完整交付且客户端已经断开时创建恢复任务,并保存最终 JSON 或 SSE。正常完成并完整交付给客户端的 LLM 请求不会创建恢复任务。
LLM 响应头包含 `X-Aihubmix-Request-Id`。客户端应尽早保存该值,以便在控制台中定位对应请求。公开任务 API 当前不能按请求 ID 过滤;可以按模型和创建时间查询最近的 LLM 任务:
```bash theme={null}
curl "https://aihubmix.com/ai/v1/tasks?object=llm&model={model}&order=desc&limit=20" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
curl https://aihubmix.com/ai/v1/tasks/{task_id}/content \
-H "Authorization: Bearer $AIHUBMIX_API_KEY"
```
LLM 任务的统一 `output` 项包含 `type=response`、`content_type`、`content_url` 和 `truncated`。`GET /ai/v1/tasks/{id}/content` 返回保存的原始 JSON 或 SSE。
LLM 中断恢复任务当前不发送任务级
Webhook。客户端中断不会停止平台继续处理请求,该次调用仍按原接口规则计费。
***
## 错误响应与错误码
本节适用于 `/ai/v1/images/*`、`/ai/v1/videos/*`,以及 `/ai/v1/tasks/*` 中
`object=image` 或 `object=video` 的媒体任务。客户端需要同时处理 HTTP 非 2xx 响应和
HTTP 200、`status=failed` 的任务终态。
```json theme={null}
{
"error": {
"message": "Task not found.",
"type": "invalid_request_error",
"code": "task_not_found",
"tid": "req_01K0ABCDEF"
}
}
```
请求返回 HTTP `5xx` 时,请提交反馈并附上 `error.tid`。
### HTTP 非 2xx 错误
`invalid_request` 和 `schema_violation` 行展示的是兜底 message。服务能够定位具体字段或
参数约束时会返回动态 message;客户端应以 `code` 判断错误类型,不要依赖 message 固定匹配。
| HTTP | `code` | `message` | 说明 |
| ---- | -------------------------- | ----------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| 400 | `invalid_request` | `Invalid request. Check the request body and parameters.`(兜底模板;实际可能返回动态 message) | 公共请求体、字段类型或列表参数不正确;此 code 的 message 不是固定值,能够定位字段时会返回更具体的动态 message |
| 400 | `model_not_found` | `The requested model is not available. Check the model name and your account access.` | 模型不存在、不可用,或当前账户无权访问 |
| 400 | `schema_violation` | `Invalid request: one or more parameters are invalid.`(兜底模板;实际可能返回动态 message) | 请求不符合当前模型的参数 Schema;此 code 的 message 不是固定值,能够定位字段或约束时会返回字段级动态 message |
| 400 | `capability_not_supported` | `The requested parameters are not supported for this model.` | 当前模型不支持请求中的字段、数量或参数上限 |
| 400 | `media_form_unsupported` | 动态媒体提示,见下文 | 图片、视频、参考图或首尾帧的格式、数据、URL 或大小无法处理 |
| 400 | `result_id_required` | `This task has multiple results. Specify result_id.` | 任务包含多个结果,下载时未指定 `result_id` |
| 400 | `upstream_rejected` | `Upstream service rejected the request.` | 模型推理厂商拒绝了创建请求 |
| 401 | `authentication_failed` | `Authentication failed: invalid or missing API key.` | API Key 缺失或无效 |
| 402 | `insufficient_quota` | `Insufficient quota.` | AIHubMix 账户可用额度不足 |
| 403 | `permission_denied` | `You do not have permission to access this resource.` | 当前账户、API Key 或访问来源无权使用该资源 |
| 403 | `async_not_enabled` | `Asynchronous tasks are not enabled. Please go to /async-tasks to activate.` | 当前账户未开通异步任务功能;控制台地址会按请求站点生成 |
| 404 | `task_not_found` | `Task not found.` | 任务不存在、分页游标无效,或当前账户无权查看 |
| 404 | `result_not_found` | `Result not found.` | 结果不存在、尚未就绪、结果 ID 不匹配,或当前账户无权下载 |
| 410 | `artifact_expired` | `The result has expired.` | 结果已超过保留期 |
| 413 | `request_too_large` | `Request body is too large. Reduce the request size and try again.` | 整体请求体超过 32 MiB |
| 413 | `image_too_large` | `Image is too large. Reduce the image size and try again.` | 图片接口解码后的单张图片超过模型处理上限 |
| 422 | `image_not_generated` | `The expected image was not generated.` | 模型推理厂商完成请求,但没有返回可交付图片 |
| 429 | `rate_limited` | `Too many requests. Please slow down and retry.` | AIHubMix 对当前账户或 API Key 限流 |
| 429 | `upstream_rate_limited` | `Upstream service is rate limiting. Please retry later.` | 模型推理厂商返回限流错误 |
| 429 | `too_many_downloads` | `Download limit exceeded for this result.` | 单个结果达到下载次数上限 |
| 500 | `internal_error` | `Internal error. Please retry.` | 服务发生调用方无法修复的内部错误 |
| 502 | `upstream_unreachable` | `Upstream service is temporarily unavailable. Please retry.` | 无法连接模型推理厂商,或无法完整读取其响应 |
| 502 | `upstream_bad_response` | `Upstream service returned an invalid response.` | 模型推理厂商返回了平台无法处理的响应 |
| 502 | `upstream_error` | `Upstream service is temporarily unavailable. Please retry.` | 模型推理厂商返回服务错误 |
| 503 | `model_unavailable` | `The requested model is temporarily unavailable.` | 所选模型暂时不可用 |
| 503 | `service_unavailable` | `Service is temporarily unavailable. Please retry.` | 查询、下载或结果服务暂时不可用 |
| 504 | `sync_timeout` | `Generation timed out. Please retry.` | 同步生成没有在等待时间内完成 |
`media_form_unsupported` 的 `message` 会根据已确认的原因生成,常见模板如下:
| 场景 | `message` |
| -------------- | ------------------------------------------------------------------------------------------------------------------- |
| 格式不支持 | `Unsupported format: . Supported formats for this model: .` |
| 图片或视频数据无效 | `The data is invalid. Provide a valid .` |
| 媒体类型无法确定时的数据无效 | `The media data is invalid. Provide valid media data.` |
| 媒体 URL 无法访问 | `The URL could not be accessed. Make sure it is publicly accessible and returns a valid .` |
| 媒体无法解码 | `Unable to process the . Check that the data or URL is valid and supported.` |
| 非图片任务的媒体超过限制 | `The is too large. Reduce the size and try again.` |
| 无法安全确定具体原因 | `Unable to process the media. Check that the media data or URL is valid and supported.` |
例如,模型允许 PNG、JPEG、WebP、HEIC 和 HEIF 时,GIF 图片返回:
```text theme={null}
Unsupported image format: GIF. Supported formats for this model: PNG, JPEG, WebP, HEIC, and HEIF.
```
### HTTP 200 + Task `status=failed`
查询请求成功不代表生成成功。任务为 `failed` 时,客户端从任务对象的 `error.code` 和
`error.message` 读取失败原因:
```json theme={null}
{
"id": "task_01K0ABCDEF",
"status": "failed",
"error": {
"code": "media_form_unsupported",
"message": "Unsupported image format: GIF. Supported formats for this model: PNG, JPEG, WebP, HEIC, and HEIF."
}
}
```
| Task `code` | `message` | 说明 |
| ------------------------- | --------------------------------------------------------------------------------- | -------------------------- |
| `media_form_unsupported` | 动态媒体提示,同上 | 异步任务中的媒体格式、数据、URL、解码或大小错误 |
| `image_too_large` | `Image is too large. Reduce the image size and try again.` | 异步图片任务的输入图片超过限制 |
| `image_not_generated` | `The expected image was not generated.` | 模型推理厂商没有返回可交付图片 |
| `upstream_rejected` | `Upstream service rejected the request.` | 模型推理厂商拒绝创建请求 |
| `upstream_rate_limited` | `Upstream service is rate limiting. Please retry later.` | 模型推理厂商返回限流错误 |
| `upstream_unreachable` | `Upstream service is temporarily unavailable. Please retry.` | 创建任务时无法连接模型推理厂商,或无法完整读取其响应 |
| `upstream_bad_response` | `Upstream service returned an invalid response.` | 模型推理厂商响应无法处理 |
| `upstream_error` | `Upstream service is temporarily unavailable. Please retry.` | 模型推理厂商创建或执行任务失败 |
| `upstream_empty_output` | `The upstream service completed without producing a usable result. Please retry.` | 模型推理厂商完成任务,但没有产生可交付结果 |
| `output_policy_violation` | `Generated content was rejected by the content policy.` | 生成内容未通过内容安全策略 |
| `sync_timeout` | `Generation timed out. Please retry.` | 等待生成结果超时 |
| `internal_error` | `Internal error. Please retry.` | 异步任务处理发生内部错误 |
***
## 完整视频示例
```python Python theme={null}
import os
import time
import requests
base_url = "https://aihubmix.com"
headers = {
"Authorization": f"Bearer {os.environ['AIHUBMIX_API_KEY']}",
"Content-Type": "application/json",
}
response = requests.post(
f"{base_url}/ai/v1/videos",
headers=headers,
json={
"model": "wan2.6-t2v",
"prompt": "A cat playing jazz on a piano",
"duration": 5,
"size": "1280x720",
},
timeout=60,
)
response.raise_for_status()
task = response.json()
while task["status"] not in {"completed", "failed", "cancelled"}:
time.sleep(15)
response = requests.get(
f"{base_url}/ai/v1/videos/{task['id']}",
headers=headers,
timeout=30,
)
response.raise_for_status()
task = response.json()
if task["status"] == "completed":
result = requests.get(
f"{base_url}/ai/v1/videos/{task['id']}/content",
headers=headers,
timeout=120,
)
result.raise_for_status()
with open("result.mp4", "wb") as file:
file.write(result.content)
else:
raise RuntimeError(task.get("error") or task["status"])
```
```typescript TypeScript theme={null}
import { writeFile } from "node:fs/promises";
const baseUrl = "https://aihubmix.com";
const headers = {
Authorization: `Bearer ${process.env.AIHUBMIX_API_KEY}`,
"Content-Type": "application/json",
};
const created = await fetch(`${baseUrl}/ai/v1/videos`, {
method: "POST",
headers,
body: JSON.stringify({
model: "wan2.6-t2v",
prompt: "A cat playing jazz on a piano",
duration: 5,
size: "1280x720",
}),
});
if (!created.ok) throw new Error(await created.text());
let task = await created.json();
const finished = new Set(["completed", "failed", "cancelled"]);
while (!finished.has(task.status)) {
await new Promise((resolve) => setTimeout(resolve, 15_000));
const polled = await fetch(`${baseUrl}/ai/v1/videos/${task.id}`, { headers });
if (!polled.ok) throw new Error(await polled.text());
task = await polled.json();
}
if (task.status === "completed") {
const result = await fetch(`${baseUrl}/ai/v1/videos/${task.id}/content`, {
headers,
});
if (!result.ok) throw new Error(await result.text());
await writeFile("result.mp4", Buffer.from(await result.arrayBuffer()));
} else {
throw new Error(JSON.stringify(task.error ?? task.status));
}
```
***
## 常见问题
**媒体任务应该查询 `/ai/v1/tasks/{id}` 还是媒体详情接口?**
轮询生成状态时使用媒体详情接口:图片查询 `/ai/v1/images/{id}`,视频查询 `/ai/v1/videos/{id}`。`/ai/v1/tasks/{id}` 返回只读快照。
**为什么视频请求中的 `seconds` 报参数错误?**
`/ai/v1/videos` 标准协议使用整数 `duration`,单位为秒。具体允许值由对应模型支持的参数决定。
**为什么 `resolution` 在部分视频模型中报参数错误?**
标准视频协议包含 `resolution` 和 `size`,但具体模型会收窄字段。例如 `wan2.6-t2v` 使用 `size`,不接受 `resolution`。
**创建响应丢失后如何找回媒体任务?**
图片请求 `GET /ai/v1/images`,视频请求 `GET /ai/v1/videos`。列表支持 `after`、`limit` 和 `order` 分页参数。
**为什么两种详情接口的 `output` 字段不同?**
媒体详情接口提供直接下载所需的简化字段;统一任务接口额外提供 `result_id` 和 `content_type`,并为 LLM 存档提供 `truncated`。
**Webhook 没收到怎么办?**
确认回调地址可以公开访问并及时返回 `2xx`,然后使用媒体详情接口查询最终状态。
***
更新时间:2026-08-12
# OpenAI 与 Grok 模型请求封号说明
Source: https://docs.aihubmix.com/cn/api/ban-notice
## **封控说明**
* **AIHubmix 不做内容审查**:平台本身不会对内容做任何停留和审查,所有违规判断标准由 OpenAI 官方决定。
* **封控来源**:目前 OpenAI 和 Grok 模型的封控来自模型厂商自身(OpenAI/Grok 团队)。Azure 的高级账户已主动关闭额外的 content filter,因此不存在微软层面的额外拦截。
* **封号风险与规避**:目前会触发封号风险的模型主要是 OpenAI 和 Grok。为规避风险,推荐在请求前使用 AiHubmix 集成的 OpenAI 官方审核接口进行内容预检,详见:[https://docs.aihubmix.com/cn/api/moderation](https://docs.aihubmix.com/cn/api/moderation) 本接口适合做保守的预检——被它判违规的内容强烈不建议提交,这个违规接口的严格程度是比官方会触发封号的违规报错要严格一些。
* **平台立场**:AIHubmix 不希望任何用户被封号。用户频繁触发封号,不仅影响自身使用,还会对 AIHubmix 全平台的账号健康度产生负面影响,甚至可能导致平台级别的风控升级。因此,我们强烈建议用户遵守合规规范,主动做好内容预检,这既是对自己账号的保护,也是对平台整体稳定性的维护。
## **会触发封号的接口返回的报错如下**
当您的提示词触发平台安全机制时,可能会收到以下错误信息:
| English Error Message | 中文翻译 |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------- |
| Invalid prompt: your prompt was flagged as potentially violating our usage policy | 无效提示词:您的提示词被标记为可能违反我们的使用政策 |
| Your request was rejected by the safety system. | 您的请求被安全系统拒绝。 |
| Content violates usage guidelines | 内容违反使用准则 |
| Invalid prompt: we've limited access to this content for safety reasons. This type of information may be used to benefit or to harm people. | 无效提示词:出于安全考虑,我们已限制对此内容的访问。此类信息可能被用于造福或伤害他人。 |
| Your request was rejected as a result of our safety system. | 由于我们的安全系统,您的请求被拒绝。 |
| Your request was rejected as a result of our safety system. The revised prompt may contain text that is not allowed by our safety system. | 由于我们的安全系统,您的请求被拒绝。修改后的提示词可能包含安全系统不允许的文本。 |
| The response was filtered due to the prompt triggering Azure OpenAI's content management policy. Please modify your prompt and retry. | 由于提示词触发了 Azure OpenAI 的内容管理策略,响应被过滤。请修改您的提示词后重试。 |
| The model produced invalid content. Consider modifying your prompt if you are seeing this error persistently | 模型生成了无效内容。如果您持续看到此错误,请考虑修改您的提示词。 |
| System detected potentially unsafe or sensitive content in input or generation. Please avoid using prompts that may generate sensitive content. Thank you for your cooperation | 系统在输入或生成内容中检测到潜在不安全或敏感内容。请避免使用可能生成敏感内容的提示词。感谢您的配合。 |
说明:当您收到此类错误时,表示请求内容已触发安全机制。建议立即停止当前请求模式,检查输入内容,并使用审核接口进行预检。
## 账户被禁用时如何处理?
若账户出现禁用情况,可联系在线客服或发送邮件至 [feedback@aihubmix.com](mailto:feedback@aihubmix.com) 申请处理或解封。
## 更多高频问题请查阅 [https://docs.aihubmix.com/cn/FAQs/Faq](https://docs.aihubmix.com/cn/FAQs/Faq)
更新时间:2026-06-01
# 豆包真人素材使用指南
Source: https://docs.aihubmix.com/cn/api/doubao-real-person-assets
通过本人网页确认创建真人素材,使用 asset:// 引用调用豆包 Seedance 视频生成,并查询、重试和删除素材。
真人素材用于在视频中引用已由本人确认的人物形象。流程为:创建素材组、本人完成网页确认、添加素材、等待素材可用,再提交视频生成任务。
本页以图片素材为例,使用 AIHubMix API 完成素材管理,优先使用新版 `/ai/v1/videos` 生成视频。已有 `/v1/videos` 客户端可参考[兼容协议示例](#compatible-video)。
## 前置条件
* 准备有效的 AIHubMix API Key,通过环境变量 `AIHUBMIX_API_KEY` 读取。
* 使用新版视频接口前,在控制台开启[异步任务](/cn/api/async-tasks),并确认账户有足够额度及目标模型的使用权限。
* 素材中的本人同意相关用途,并亲自完成网页上的确认流程。同一素材组仅添加同一人的素材。
* 准备可供模型推理厂商读取的图片直链,确认链接在素材处理期间持续有效。
* 命令行示例需要 Bash、curl 和 jq。在同一终端按步骤执行,保留返回的素材组、确认会话、素材和视频任务 ID。
BytePlus 官方真人素材指南覆盖 Seedance 2.0 和 Seedance 2.5。本页新版视频主示例使用已完成线上验证的 AIHubMix 模型 ID `doubao-seedance-2-5-260628`;具体版本、参考媒体类型和参数以当前模型 Schema 及账户可用能力为准。验证范围见[本次流程验证](#verified-flow),不要据此推定所有 Seedance 版本均可使用真人素材。
准备终端环境,API Key 应已由你的运行环境注入:
```bash theme={null}
set -euo pipefail
: "${AIHUBMIX_API_KEY:?请先配置 AIHUBMIX_API_KEY 环境变量}"
BASE_URL="https://aihubmix.com"
MODEL="doubao-seedance-2-5-260628"
```
1. 创建素材组
```bash theme={null}
GROUP_JSON=$(curl --fail-with-body -sS --max-time 60 \
-X POST "$BASE_URL/ai/v1/asset-groups" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name":"我的真人素材"}')
printf '%s\n' "$GROUP_JSON" | jq .
GROUP_ID=$(printf '%s' "$GROUP_JSON" | jq -er '.id')
```
请求体只接受 `name`,名称不能为空,最长 100 个字符。创建成功返回 HTTP `201`,初始状态为 `pending_auth`。
素材组公开字段为 `id`、`object`、`name`、`status`、`created_at`、`updated_at`,其中 `object` 固定为 `asset_group`,时间字段为 Unix 秒。后续以 `status=active` 判断素材组已可添加素材。
如果创建响应丢失,先查询列表,避免直接重复创建:
```bash theme={null}
curl --fail-with-body -sS "$BASE_URL/ai/v1/asset-groups?limit=20" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" | jq .
```
列表返回 `data`、`has_more`、`next_after`。下一页传入 `after=上一页的next_after`;`limit` 默认 `20`,最大 `100`。名称不作为幂等标识,请结合 ID 和创建时间识别素材组。
2. 获取本人确认链接
创建确认会话,无需请求体:
```bash theme={null}
SESSION_JSON=$(curl --fail-with-body -sS --max-time 60 \
-X POST "$BASE_URL/ai/v1/asset-groups/$GROUP_ID/verification-sessions" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY")
SESSION_ID=$(printf '%s' "$SESSION_JSON" | jq -er '.id')
printf '%s' "$SESSION_JSON" | jq '{id, status, expires_at, verification_url}'
```
创建成功返回 HTTP `201`。公开字段为 `id`、`object`、`group_id`、`status`、`created_at`、`expires_at`、`completed_at`;`object` 固定为 `verification_session`,时间字段为 Unix 秒,未完成时 `completed_at` 为 `null`。
`verification_url` 仅在成功创建响应中返回,后续查询不会再次返回链接。及时将链接交给素材中的本人,不要放入公开日志、代码仓库或反馈截图。有效期以 `expires_at` 为准,过期后不能继续使用原链接。
本人打开 `verification_url`,核对页面展示的主体与用途,阅读并确认相关条款,按页面提示完成操作。BytePlus 官方指南说明此过程需要登录个人 BytePlus 账户;页面需要相机权限时,由本人操作设备并授权。
官方页面可能包含素材上传等步骤,按实际提示完成。本页接下来的 API 素材创建步骤仍需执行,并取得 AIHubMix 返回的素材 ID;不要把网页显示的其他素材 ID 直接代入 API 示例。
3. 查询确认结果
```bash theme={null}
curl --fail-with-body -sS "$BASE_URL/ai/v1/verification-sessions/$SESSION_ID" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" | jq .
curl --fail-with-body -sS "$BASE_URL/ai/v1/asset-groups/$GROUP_ID" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" | jq .
```
| 会话状态 | 下一步 |
| ---------- | ------------------------- |
| `creating` | 会话仍在创建,稍后查询;持续未完成时联系支持 |
| `pending` | 等待本人完成或结果确认,稍后继续查询 |
| `verified` | 本人确认已完成,继续核对素材组为 `active` |
| `rejected` | 本次未通过,检查网页提示后重新发起 |
| `expired` | 本次已过期,重新发起确认 |
| `failed` | 本次失败,检查错误提示,必要时联系支持 |
客户端可每 10 至 15 秒查询一次,并设置本地等待上限。该间隔为使用建议。网页显示完成或返回空白页面时,仍应通过 API 确认会话为 `verified`、素材组为 `active`,再添加素材。
若重新创建返回 `409 verification_session_active`,先查询已有会话和素材组。有效会话仍存在、素材组已完成确认,或前次结果仍待确认时,都不应反复新建。持续未完成时联系[支持](/cn/FAQs/Feedback)。
网页出现 `internal error` 不代表确认会话已结束。先执行本节的两个 GET 请求,查询会话和素材组;会话仍为 `pending` 时,不要反复创建同组会话。只有会话为 `verified` 且素材组为 `active`,才继续添加素材。仅凭网页错误无法判断原因,持续未完成时保留 ID 联系支持。
4. 通过图片地址创建素材
### 图片准备
提供返回图片文件的绝对 HTTP(S) 地址,优先使用 HTTPS。链接应无需登录或附加请求头即可读取;本地路径、内网地址、Base64 和带账号密码的 URL 不适用于素材创建接口。URL 不应包含 `#` 片段。
根据 [BytePlus 真人素材指南](https://docs.byteplus.com/en/docs/ModelArk/2315856),图片建议为清晰正面照,并符合以下素材入库要求:
| 项目 | 要求 |
| ---- | ------------------------------------ |
| 格式 | JPEG、PNG、WebP、BMP、TIFF、GIF、HEIC、HEIF |
| 单张大小 | 小于 30 MB |
| 宽高比 | 大于 0.4、小于 2.5 |
| 宽和高 | 均大于 300 像素、小于 6000 像素 |
| 人物 | 与该素材组完成确认的人物一致 |
上述为官方素材库要求,视频模型还可能有独立的参考素材限制。上传前同时核对目标模型要求;HTTP 创建成功也不表示素材已通过处理。
### 创建请求
将 `IMAGE_URL` 改为你已获得本人同意使用的图片直链。示例域名仅作占位,不提供真人图片。
```bash theme={null}
IMAGE_URL="https://cdn.example.com/portrait.jpg"
ASSET_KEY="portrait-image-001"
ASSET_BODY=$(jq -n --arg url "$IMAGE_URL" --arg ref "$ASSET_KEY" \
'{url: $url, asset_type: "image", client_reference_id: $ref}')
ASSET_JSON=$(curl --fail-with-body -sS --max-time 60 \
-X POST "$BASE_URL/ai/v1/asset-groups/$GROUP_ID/assets" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: $ASSET_KEY" \
-d "$ASSET_BODY")
printf '%s\n' "$ASSET_JSON" | jq .
ASSET_ID=$(printf '%s' "$ASSET_JSON" | jq -er '.id')
```
| 请求字段 | 必填 | 说明 |
| --------------------- | -- | -------------------------------------- |
| `url` | 是 | 可访问的素材文件地址 |
| `asset_type` | 是 | `image`、`video` 或 `audio`;本例使用 `image` |
| `client_reference_id` | 否 | 业务侧素材标识,最长 128 字节 |
请求体只接受以上三个字段。`Idempotency-Key` 放在请求头,可选,最长 128 字节,不能有首尾空白或控制字符。音视频的文件限制请查阅上述官方指南,并核对目标模型支持的类型与时长。
首次创建通常返回 HTTP `201`;复用已有素材返回 `200`;结果仍待确认、状态为 `reconciling` 时返回 `202`。始终读取对象的 `status`。
素材公开字段为 `id`、`object`、`group_id`、`asset_type`、`status`、`client_reference_id`、`created_at`、`updated_at`、`deleted_at`。`object` 固定为 `asset`;未提供或已删除的 `client_reference_id` 不返回,未删除时 `deleted_at` 为 `null`。时间字段为 Unix 秒,查询不返回原图片地址,请自行保留业务记录。
5. 等待素材可用
```bash theme={null}
curl --fail-with-body -sS "$BASE_URL/ai/v1/assets/$ASSET_ID" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" | jq .
```
| 素材状态 | 含义与处理 |
| ------------- | ----------------------- |
| `creating` | 创建尚未完成,保留 ID 并稍后查询 |
| `processing` | 正在处理,继续查询 |
| `active` | 可作为视频参考素材 |
| `failed` | 素材处理失败,检查图片及人物一致性要求 |
| `reconciling` | 创建或删除结果仍待确认,继续查询,暂不用于视频 |
| `deleting` | 删除处理中,暂不用于视频 |
| `deleted` | 删除已完成,不再用于视频 |
可每 10 至 15 秒查询一次,并设置本地等待上限。停止本地轮询不会取消服务端操作。
创建结果未知且持续没有匹配结果时,素材可能一直保持 `reconciling`,也可能影响素材或素材组删除。保留 ID 和原请求标识,联系支持;不要通过更换标识反复创建,也不要假设等待一段时间就会自动清理。
6. 使用素材生成视频
视频引用使用 AIHubMix 素材创建响应中的完整 `id`,格式为 `asset://`。同一次请求引用的全部素材必须属于同一素材组、归当前账户所有,且均为 `active`。素材组也必须保持可用。
| 素材类型 | 新版 `input_references[].type` | 兼容版嵌套字段 |
| ------- | ---------------------------- | --------------- |
| `image` | `image_url` | `image_url.url` |
| `video` | `video_url` | `video_url.url` |
| `audio` | `audio_url` | `audio_url.url` |
引用类型必须与素材创建时的 `asset_type` 一致。`asset://` 用于视频参考字段,不是供浏览器下载的地址。
### 新版视频协议
先按端点路径核对当前模型 Schema:
```bash theme={null}
curl --fail-with-body -sS "$BASE_URL/call/schema/models/$MODEL/endpoints" \
| jq '.endpoints[] | select(.path == "/ai/v1/videos") | .request.schema'
```
确认模型支持参考图片后提交。以下采用本次线上验证成功的 Seedance 2.5 参数:`duration=4`、`resolution="480p"`、`aspect_ratio="3:4"`、`generate_audio=false`。新版直接使用 `input_references[].url`,其中 `ASSET_ID` 为前面 AIHubMix 返回的素材 ID:
```bash theme={null}
VIDEO_BODY=$(jq -n --arg model "$MODEL" --arg asset "asset://$ASSET_ID" \
'{model: $model,
prompt: "The person in the reference image smiles and waves at the camera.",
duration: 4,
resolution: "480p",
aspect_ratio: "3:4",
generate_audio: false,
input_references: [{type: "image_url", url: $asset}]}')
VIDEO_JSON=$(curl --fail-with-body -sS --max-time 120 \
-X POST "$BASE_URL/ai/v1/videos" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d "$VIDEO_BODY")
printf '%s\n' "$VIDEO_JSON" | jq .
VIDEO_ID=$(printf '%s' "$VIDEO_JSON" | jq -er '.id')
export VIDEO_ID
```
新版使用整数 `duration` 表示请求时长;其他允许值以模型 Schema 为准。`resolution="480p"` 是请求的分辨率档位,不保证输出宽或高固定为 480 像素,实际尺寸以生成文件为准。首尾帧可使用 `frame_images[].image_url.url`,同时设置 `frame_type`,仅在模型支持相应能力时使用。完整参数参阅[视频生成](/cn/api/aihubmix-video-generation)。
### 兼容视频协议
已有客户端使用 `/v1/videos` 时,将引用放在 `content` 或 `extra_body.content`,URL 嵌套在相应媒体对象内。本例选用 `extra_body.content`:
兼容示例保留 `doubao-seedance-2-0-260128`,依据现有兼容接口约定和 BytePlus 官方素材引用说明编写。本次未实测 Seedance 2.0 视频生成及 `/v1/videos` 兼容创建,不能将新版 Seedance 2.5 的验证结果直接用于该示例。
```bash theme={null}
COMPAT_MODEL="doubao-seedance-2-0-260128"
COMPAT_BODY=$(jq -n --arg model "$COMPAT_MODEL" --arg asset "asset://$ASSET_ID" \
'{model: $model,
prompt: "The person in the reference image smiles and waves at the camera.",
extra_body: {content: [{type: "image_url", image_url: {url: $asset}, role: "reference_image"}]}}')
curl --fail-with-body -sS --max-time 120 \
-X POST "$BASE_URL/v1/videos" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d "$COMPAT_BODY" | jq .
```
两种示例择一执行,每次视频创建都是独立请求。不要在兼容请求中混入 `input_references`。同时提供两处 `content` 时,`extra_body.content` 覆盖顶层 `content`,建议只提供一处。
兼容版返回的 `id` 应用于 `GET /v1/videos/{id}` 查询,完成后通过 `GET /v1/videos/{id}/content` 下载。不要把兼容版 ID 交给 `/ai/v1/videos` 查询。详细说明见[兼容视频接口](/cn/api/Video-Gen)。
7. 轮询并下载新版视频
以下 Python 示例仅接续前面的新版创建步骤,读取环境变量中的 `VIDEO_ID`,不重新创建任务。需要安装 `requests`。
```python theme={null}
import os
import time
from pathlib import Path
import requests
base_url = "https://aihubmix.com"
video_id = os.environ["VIDEO_ID"]
headers = {"Authorization": f"Bearer {os.environ['AIHUBMIX_API_KEY']}"}
deadline = time.monotonic() + 1800
while time.monotonic() < deadline:
response = requests.get(
f"{base_url}/ai/v1/videos/{video_id}", headers=headers, timeout=30
)
response.raise_for_status()
task = response.json()
status = task["status"]
if status == "completed":
break
if status in {"failed", "cancelled"}:
raise RuntimeError(f"视频任务未完成:{task.get('error') or status}")
time.sleep(15)
else:
raise TimeoutError(f"本地等待已结束,请稍后继续查询原任务:{video_id}")
temporary = Path("result.mp4.part")
with requests.get(
f"{base_url}/ai/v1/videos/{video_id}/content",
headers=headers,
timeout=120,
stream=True,
) as response:
response.raise_for_status()
with temporary.open("wb") as output:
for chunk in response.iter_content(chunk_size=1024 * 1024):
if chunk:
output.write(chunk)
temporary.replace("result.mp4")
print("视频已保存为 result.mp4")
```
30 分钟为示例的本地等待上限,不代表服务端任务超时。查询 HTTP `200` 不代表生成成功,必须检查 `status`。轮询使用 `/ai/v1/videos/{id}`,统一任务接口 `/ai/v1/tasks/{id}` 提供只读快照。
视频查询和下载使用创建任务时的同一 API Key。完成后及时下载并自行保存;结果有保留期,以 `expires_at` 为准,过期可能返回 `410 artifact_expired`。
### 本次流程验证
2026-09-07 的线上验证使用公网 HTTPS JPEG 直链、本人完成的网页确认,以及上述 Seedance 2.5 参数,观察到以下结果:
| 步骤 | 本次结果 |
| --------- | ---------------------------------------------------------------------------------- |
| 创建素材组 | HTTP `201`,`status=pending_auth` |
| 创建确认会话 | HTTP `201`,`status=pending` |
| 本人完成确认后查询 | 会话 HTTP `200`、`status=verified`,素材组为 `active` |
| 创建并查询图片素材 | 创建 HTTP `201`、`status=processing`,后续查询 HTTP `200`、`status=active` |
| 创建并查询新版视频 | 创建 HTTP `200`、`status=in_progress`,后续查询 HTTP `200`、`status=completed`、`error=null` |
| 下载视频 | HTTP `200`,`Content-Type: video/mp4`,文件通过 ffmpeg 完整解码 |
本次文件为 1,558,358 字节;ffprobe 检测为 H.264、24 fps、560 × 752 像素、4.041667 秒、无音轨。这些数值为该次生成结果,不代表每次请求都会输出相同尺寸、时长或文件大小。
首次打开确认页面曾出现 `internal error`,随后 API 查询仍为 `pending`,页面错误的原因尚未确认。该次测试随后使用独立测试组的新页面,由本人完成操作后确认会话为 `verified`、素材组为 `active`。新组仅是本次测试的处理方式,不作为反复重建素材组的通用建议,也不表示原会话已结束。
本次未实测 Seedance 2.0 视频生成、兼容接口创建、音视频素材、首尾帧、删除及其他异常组合。相关说明保留接口约定和官方资料依据,本次验证不覆盖整篇指南的全部场景。
## 幂等重试
* 素材创建超时或响应丢失时,保留原 `Idempotency-Key`、`client_reference_id`、URL 和 `asset_type`,重发同一请求。两个标识中任一个命中同一账户、同一素材组的已有素材时,会复用该素材。
* 相同标识对应的 URL 或 `asset_type` 发生变化时,返回 `409 asset_idempotency_conflict`。带签名的图片 URL 更新后也属于 URL 变化。
* 未提供任一标识时,不保证跨请求去重。只有确认要创建另一份素材时,才使用新标识。
* 已取得素材 ID 后,优先用 `GET /ai/v1/assets/{id}` 查询。`reconciling` 不等于失败,不应改用新标识再创建。
* 素材删除完成后,原幂等标识不再保留。不要依赖它找回已删除素材,也不要重放旧创建请求。
* 本节幂等约定仅适用于素材创建。素材组、确认会话和视频创建不能套用该约定。新版视频创建响应丢失时,先用 `GET /ai/v1/videos?limit=20&order=desc` 查找原任务,避免重复生成。
## 删除素材和素材组
删除前先确认所有引用该素材的视频均已结束,包括通过兼容接口提交的任务。删除操作不能撤销,已下载的视频文件需自行管理。
删除单个素材:
```bash theme={null}
curl --fail-with-body -sS -X DELETE "$BASE_URL/ai/v1/assets/$ASSET_ID" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" | jq .
```
返回 `202` 表示删除仍在处理,通过 `GET /ai/v1/assets/{id}` 继续查询,直到 `status=deleted`。重复删除返回当前状态;若为 `reconciling`,继续确认结果,持续未完成时联系支持。
删除整个素材组会同时删除组内素材,必须显式传入 `cascade=true`:
```bash theme={null}
curl --fail-with-body -sS -X DELETE \
"$BASE_URL/ai/v1/asset-groups/$GROUP_ID?cascade=true" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" | jq .
```
受理后返回 `202`,通过 `GET /ai/v1/asset-groups/{id}` 查询。`deleting` 表示处理中,`partially_deleted` 表示尚未全部删除,`deleted` 才表示完成。列表默认不展示已删除素材组。
`409 asset_group_in_use` 表示仍有操作或视频任务未结束。等待并查询相关状态后重试。兼容视频任务需要自行确认结束,不要依赖删除请求自动判断所有兼容任务的占用。
## 常见问题
### 已完成网页操作,为什么还不能添加素材?
先查询确认会话和素材组,以 `verified` 和 `active` 为准。网页出现 `internal error` 时也执行相同检查;`pending` 期间不反复创建同组会话。结果尚未确认时稍后再查;持续未完成请提供 ID 联系支持,无需提交确认链接或本人照片。
### 素材可用,为什么生成视频仍然失败?
检查引用是否使用 AIHubMix 返回的素材 ID,所有素材是否属于同一组,媒体类型是否匹配,以及当前模型是否支持相应输入。素材 `active` 表示素材可用,视频任务仍需单独检查完成状态和错误信息。
### 如何处理常见接口错误?
| HTTP | `error.code` | 处理方式 |
| ---- | -------------------------------------------------------------------------- | -------------------------- |
| 400 | `invalid_request` | 检查请求字段、结构和所用视频协议 |
| 400 | `asset_group_invalid` | 检查素材组名称 |
| 400 | `asset_invalid` | 检查 URL、素材类型和请求标识 |
| 400 | `asset_binding_mismatch` | 同一次视频请求只引用同一素材组的素材 |
| 400 | `cascade_confirmation_required` | 确认整组删除意图后传入 `cascade=true` |
| 401 | `authentication_failed` | 检查 API Key 环境变量及认证请求头 |
| 403 | `async_not_enabled` | 开启异步任务后使用新版视频接口 |
| 404 | `asset_group_not_found`、`asset_not_found`、`verification_session_not_found` | 检查资源 ID 和所属账户 |
| 409 | `asset_group_not_verified` | 查询本人确认结果,等待素材组可用 |
| 409 | `verification_session_active` | 查询已有会话或素材组,避免重复发起 |
| 409 | `asset_not_ready` | 查询素材状态,生成视频前等待 `active` |
| 409 | `asset_idempotency_conflict` | 核对标识对应的原 URL 和类型 |
| 409 | `asset_group_in_use` | 等待相关操作、视频任务结束后再删除 |
| 503 | `asset_group_unavailable`、`verification_unavailable`、`asset_unavailable` | 稍后重试;持续不可用时联系支持 |
其他视频错误参阅[异步任务错误码](/cn/api/async-tasks#error-codes)。反馈时提供发生时间、HTTP 状态、`error.code`、返回的 `error.tid`(如有)及相关资源 ID;不要提供 API Key、确认链接或带签名的图片地址。
## 参考资料
* [BytePlus:添加真人素材](https://docs.byteplus.com/en/docs/ModelArk/2315856)
* [BytePlus:使用 Seedance 生成肖像视频](https://docs.byteplus.com/en/docs/ModelArk/2608626)
* [AIHubMix 原生视频生成](/cn/api/aihubmix-video-generation)
* [OpenAI 兼容视频接口](/cn/api/Video-Gen)
* [异步任务](/cn/api/async-tasks)
更新时间:2026-09-07
# 豆包私域虚拟人像素材使用指南
Source: https://docs.aihubmix.com/cn/api/doubao-virtual-portrait-assets
创建无需真人确认的虚拟人像素材组,上传图片并使用 asset:// 引用调用豆包 Seedance 视频生成。
私域虚拟人像素材用于在视频中引用不需要真人确认的虚拟人物形象。本页介绍通过 AIHubMix API 创建虚拟人像素材组、上传图片并生成视频的流程。
本文只介绍私域虚拟人像,不包含公共虚拟人像目录。
## 前置条件
* 准备有效的 AIHubMix API Key,通过环境变量 `AIHUBMIX_API_KEY` 读取。
* 确认账户已开通目标视频模型和虚拟人像素材能力,并有足够额度。
* 准备模型可以访问的公网 HTTPS 图片直链。
* 准备 Bash、curl 和 jq。
虚拟人像不需要创建真人确认 Session,也不能为虚拟人像组创建真人确认 Session。
1. 创建虚拟人像素材组
创建时将 `kind` 设置为 `virtual_portrait`:
```bash theme={null}
BASE_URL="https://aihubmix.com"
GROUP_JSON=$(curl --fail-with-body -sS --max-time 60 \
-X POST "$BASE_URL/ai/v1/asset-groups" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: virtual-portrait-group-" \
-d '{"name":"我的虚拟人像","kind":"virtual_portrait"}')
printf '%s\n' "$GROUP_JSON" | jq '{id,object,kind,status,error}'
GROUP_ID=$(printf '%s' "$GROUP_JSON" | jq -er '.id')
```
创建成功返回 HTTP `201`。虚拟组通常直接返回 `status=active`,授权状态为 `not_required`。只有 `active` 且已绑定模型推理厂商素材组的虚拟组才能添加素材。
2. 上传图片素材
图片必须是公网可访问的 HTTP(S) 直链,不要使用本地路径、内网地址、Base64 或需要登录的链接。
```bash theme={null}
IMAGE_JSON=$(curl --fail-with-body -sS --max-time 60 \
-X POST "$BASE_URL/ai/v1/asset-groups/$GROUP_ID/assets" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: virtual-portrait-image-" \
-d '{"url":"https://example.com/virtual-portrait.jpg","asset_type":"image","client_reference_id":"my-virtual-portrait"}')
printf '%s\n' "$IMAGE_JSON" | jq '{id,object,group_id,asset_type,status,error}'
ASSET_ID=$(printf '%s' "$IMAGE_JSON" | jq -er '.id')
```
上传成功通常返回 `201` 和 `status=processing`,不表示素材已经可用于视频。建议图片小于 30 MB,宽高均在 300 至 6000 像素之间,宽高比大于 0.4 且小于 2.5。
3. 等待素材可用
```bash theme={null}
curl --fail-with-body -sS "$BASE_URL/ai/v1/assets/$ASSET_ID" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" | jq '{id,status,error}'
```
只有 `status=active` 才能用于视频。`creating`、`processing` 继续查询;`failed` 检查图片地址和素材要求;`reconciling` 表示结果待确认,暂不使用。
4. 使用虚拟人像生成视频
使用上传接口返回的完整素材 ID,格式为 `asset://`。不要使用原图片 URL,也不要手工拼接模型推理厂商素材 ID。
```bash theme={null}
VIDEO_JSON=$(curl --fail-with-body -sS --max-time 120 \
-X POST "$BASE_URL/ai/v1/videos" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"doubao-seedance-2-5-260628","prompt":"让虚拟人像自然地向镜头微笑并轻微转头。","input_references":[{"type":"image_url","url":"asset://"}]}' )
printf '%s\n' "$VIDEO_JSON" | jq '{id,object,status,model,error}'
VIDEO_ID=$(printf '%s' "$VIDEO_JSON" | jq -er '.id')
```
同一次请求引用的私域素材必须属于同一素材组、归当前账户所有,并且均为 `active`。虚拟人像组固定使用创建时绑定的渠道、账号、地域和 Project。
通过 `GET /ai/v1/videos/` 查询任务。返回 HTTP `200` 不等于生成成功,必须检查 `status`。只有 `status=completed` 才算生成成功;`in_progress` 继续查询,`failed` 或 `cancelled` 停止并读取 `error`。任务完成后通过 `GET /ai/v1/videos//content` 获取 `video/mp4` 内容。线上验证中,状态查询的 `results` 可能为空,不能仅依赖 `results` 判断是否成功。
建议每 15 秒查询一次,并设置本地等待上限。任务变为 `completed` 后,再请求 `/ai/v1/videos//content` 保存视频文件。示例中的 ``、``、`` 和 `` 都是占位符,必须替换为前一步接口实际返回的值,不能原样复制执行。
## 常见错误
| HTTP | `error.code` | 处理方式 |
| ---- | ------------------------------------------------------------------- | -------------------- |
| 400 | `asset_group_invalid` | 检查素材组名称和 `kind` |
| 400 | `asset_invalid` | 检查图片公网地址、类型和请求字段 |
| 400 | `asset_binding_mismatch` | 同一次请求只引用同一素材组素材 |
| 400 | `channel_pin_conflict` | 指定渠道与素材绑定不一致,修改请求后再试 |
| 404 | `asset_group_not_found`、`asset_not_found` | 检查资源 ID 和当前账户 |
| 409 | `asset_not_ready` | 等待素材状态变为 `active` |
| 503 | `asset_group_unavailable`、`asset_unavailable`、`channel_unavailable` | 稍后重试并检查绑定渠道 |
## 删除和排障
虚拟组处于 `creating` 或 `reconciling` 时,因创建结果仍未知,暂不允许直接删除或自动清理。持续查询不到模型推理厂商素材组时保留本地记录和恢复定位,需要运维核对后处理。
API Key 只通过环境变量传入,不写入脚本、日志或文档。反馈问题时提供发生时间、HTTP 状态、错误码、请求编号和资源 ID,不提供 API Key 或带签名的图片地址。
## 常见问题
### 虚拟人像需要真人确认吗?
不需要。创建素材组时指定 `kind=virtual_portrait`,组授权状态为 `not_required`。
### 为什么图片上传成功后还不能生成视频?
图片通常会先处于 `processing`。必须查询到 `status=active` 后再提交视频任务。
### 视频任务完成后如何获取文件?
查询到 `status=completed` 后,请求 `GET /ai/v1/videos//content` 获取视频文件。
更新时间:2026-09-11
# 模型智能路由
Source: https://docs.aihubmix.com/cn/api/llm-router
AIHubMix 智能路由:把模型名填 auto,网关按请求内容自动选出最优模型,支持成本优先 / 质量优先 / 低延迟策略,按实际命中模型计费,客户端代码零改动。
> 一个 `model=auto`,把"选哪个模型"交给网关。
**智能路由(LLM Router)** 会按请求内容,从**平台数百个模型**中**实时优选**最合适的那一个。你只需把 `model` 填成 `auto`——不用挑模型、不用比价、不用跟踪模型迭代。
按**实际命中的模型**计费,无附加费,客户端代码零改动。命中了哪个模型写在响应头与响应体里(见 [如何确认实际命中的模型](#如何确认实际命中的模型)),完全可追溯。
## 适用场景
* **按请求内容自动分发**:根据prompt,自动分配最合适的模型——尤其适合 agent / 应用里需要多次调用模型、又难以预先为每一步写死选型的场景。
* **成本优化**:让简单任务自动落到更便宜、更快的模型(`auto` 默认成本优先)。
* **质量优化**:确保复杂请求被路由到能力更强的模型(`auto:quality_first`)。
* **低延迟场景**:agent 多轮循环、对话实时交互等对响应速度敏感的场景,优先选响应最快的模型(`auto:latency_critical`)。
* **统一入口、免选型**:不同类型的请求自动分发到各自最优的模型——不必维护"任务 → 模型"映射表,也不必持续跟踪模型迭代、手动比价换模型名。
***
## 快速开始
把 `model` 设为 `auto`,其余请求体和正常调用完全一致。base\_url 使用 `https://aihubmix.com/v1`。
```bash curl theme={null}
curl https://aihubmix.com/v1/chat/completions \
-H "Authorization: Bearer " \
-H "Content-Type: application/json" \
-d '{
"model": "auto",
"messages": [
{ "role": "user", "content": "What is the meaning of life?" }
]
}'
```
```python Python (openai SDK) theme={null}
from openai import OpenAI
client = OpenAI(
api_key="",
base_url="https://aihubmix.com/v1",
)
resp = client.chat.completions.create(
model="auto", # 交给网关自动选模
messages=[
{"role": "user", "content": "What is the meaning of life?"},
],
)
print(resp.choices[0].message.content)
print("实际命中的模型:", resp.model) # 不是 "auto",而是真实模型名
```
```javascript Node.js (openai SDK) theme={null}
import OpenAI from "openai";
const client = new OpenAI({
apiKey: "",
baseURL: "https://aihubmix.com/v1",
});
const resp = await client.chat.completions.create({
model: "auto", // 交给网关自动选模
messages: [
{ role: "user", content: "What is the meaning of life?" },
],
});
console.log(resp.choices[0].message.content);
console.log("实际命中的模型:", resp.model); // 真实模型名
```
智能路由在请求进入上游**之前**完成解析,对流式(`stream: true`)与非流式请求一视同仁,无需额外参数;整个决策**仅增加约 1ms 开销**,对端到端延迟几乎无感。
***
## 如何确认实际命中的模型
**方式一 · AIHubMix 控制台「日志」**:在 [console.aihubmix.com/logs](https://console.aihubmix.com/logs) 里,每条请求都能直接看到实际命中、并据此计费的真实模型名。
**方式二 · 接口响应字段**:
* **响应体的 `model` 字段**回填的是真实命中模型(如 `gpt-5.5`),而不是 `auto`。
* **响应头**
| 响应头 | 含义 | 示例值 |
| ---------------------------------- | ----------------------------------- | ------------------------------------------------------------------ |
| `X-Aihubmix-Router-Resolved-Model` | 实际命中、并据此计费的模型 | `gpt-5.5` |
| `X-Aihubmix-Router-Policy` | 本次使用的策略 | `cost_optimized` |
| `X-Aihubmix-Router-Dimension` | 识别出的任务维度 | `text.overall` |
| `X-Aihubmix-Router-Decision-Id` | 本次决策的唯一 ID | `05dbad09-33c5-42de-…` |
| `X-Aihubmix-Router-Reason` | 决策简要说明(策略 / 维度 / 最高分 / 候选数) | `policy=cost_optimized dim=text.overall top=0.182 survivors=20/33` |
| `X-Aihubmix-Router-Fallback` | **仅当**触发无候选兜底时出现 | `true` |
| `X-Aihubmix-Router-Sticky` | **仅当**复用该会话此前的模型时出现(见[缓存支持](#缓存支持)) | `true` |
读取路由决策(curl 看响应头;SDK 用原始响应对象取 header):
```bash curl theme={null}
curl -i https://aihubmix.com/v1/chat/completions \
-H "Authorization: Bearer " \
-H "Content-Type: application/json" \
-d '{
"model": "auto",
"messages": [
{ "role": "user", "content": "What is the meaning of life?" }
]
}' | grep -i "^x-aihubmix-router"
```
```python Python (openai SDK) theme={null}
# 复用上面创建的 client;with_raw_response 才能拿到响应头
raw = client.chat.completions.with_raw_response.create(
model="auto",
messages=[
{"role": "user", "content": "What is the meaning of life?"},
],
)
print("命中模型:", raw.headers.get("x-aihubmix-router-resolved-model"))
print("策略:", raw.headers.get("x-aihubmix-router-policy"))
print("维度:", raw.headers.get("x-aihubmix-router-dimension"))
completion = raw.parse() # 解析为正常的 completion 对象
print("body.model:", completion.model)
```
```javascript Node.js (openai SDK) theme={null}
// 复用上面创建的 client;.withResponse() 才能拿到原始响应头
const { data: completion, response } = await client.chat.completions
.create({
model: "auto",
messages: [
{ role: "user", content: "What is the meaning of life?" },
],
})
.withResponse();
console.log("命中模型:", response.headers.get("x-aihubmix-router-resolved-model"));
console.log("策略:", response.headers.get("x-aihubmix-router-policy"));
console.log("维度:", response.headers.get("x-aihubmix-router-dimension"));
console.log("body.model:", completion.model);
```
curl 实际输出(命中模型随线上 catalog 变化):
```text theme={null}
x-aihubmix-router-decision-id: 05dbad09-33c5-42de-85b5-559fdb73eb4c
x-aihubmix-router-dimension: text.overall
x-aihubmix-router-policy: cost_optimized
x-aihubmix-router-reason: policy=cost_optimized dim=text.overall top=0.182 survivors=20/33
x-aihubmix-router-resolved-model: xiaomi-mimo-v2.5-pro
```
`reason` :`survivors=20/33` 表示 33 个候选里有 20 个通过硬过滤进入打分,`top=0.182` 是胜出模型在候选池内归一化后的综合得分(能力 / 成本 / 延迟按策略加权)。
示例中的 `Resolved-Model` 取决于线上 catalog 的当前候选与价格,会随平台模型上下线而变化
***
## 路由策略
不带后缀的 `auto` 使用默认策略 `cost_optimized`。你可以用 `auto:<策略>` 显式指定侧重:
| 策略写法 | 侧重 | 适用场景 |
| ------------------------------- | --------------------- | --------------- |
| `auto`(= `auto:cost_optimized`) | **成本优先**:能力达标就选最便宜 | 批量任务、对成本敏感 |
| `auto:balanced` | **均衡**:能力 / 成本 / 延迟兼顾 | 通用,不确定时的稳妥选择 |
| `auto:quality_first` | **质量优先**:优先选能力最强 | 复杂推理、关键输出 |
| `auto:latency_critical` | **低延迟优先**:优先选响应最快 | agent 循环、实时交互对话 |
策略是对模型按 **能力 / 成本 / 延迟** 的不同权重倾向。`auto` 先按你这次请求的内容圈定任务维度,再在该维度下 **平台数百个模型** 的候选池里,按所选策略实时择优——所以同一个策略,面对不同内容会命中不同模型。当前在池模型与各维度评分可通过[获取自动路由策略对应模型范围](/cn/api/RouterEndpoints/leaderboard)接口查询。下方「同一请求、不同策略 → 不同命中」实测表就是这一机制的直观体现;每次到底花落谁家,以响应头 / 控制台日志里的真实模型名为准。
指定策略只需把后缀加到 `model` 上:
```bash curl theme={null}
# 质量优先 + 代码任务
curl -i https://aihubmix.com/v1/chat/completions \
-H "Authorization: Bearer " \
-H "Content-Type: application/json" \
-d '{
"model": "auto:quality_first",
"messages": [
{ "role": "user", "content": "Write a Python function to reverse a linked list." }
]
}' | grep -i "^x-aihubmix-router"
```
```python Python (openai SDK) theme={null}
raw = client.chat.completions.with_raw_response.create(
model="auto:quality_first", # 质量优先
messages=[
{"role": "user", "content": "Write a Python function to reverse a linked list."},
],
)
print(raw.headers.get("x-aihubmix-router-resolved-model"))
print(raw.headers.get("x-aihubmix-router-dimension"))
```
```javascript Node.js (openai SDK) theme={null}
const { response } = await client.chat.completions
.create({
model: "auto:quality_first", // 质量优先
messages: [
{ role: "user", content: "Write a Python function to reverse a linked list." },
],
})
.withResponse();
console.log(response.headers.get("x-aihubmix-router-resolved-model"));
console.log(response.headers.get("x-aihubmix-router-dimension"));
```
**同一请求、不同策略 → 不同命中**(生产环境实测,同一句 `What is the meaning of life?`,都落 `text.overall` 维度):
| 策略 | 命中模型 | top 得分 |
| -------------------------- | ----------------------- | :----: |
| `auto`(= `cost_optimized`) | `xiaomi-mimo-v2.5-pro` | 0.182 |
| `auto:balanced` | `claude-opus-4-6-think` | 0.488 |
| `auto:latency_critical` | `claude-opus-4-6` | 0.646 |
| `auto:quality_first` | `claude-opus-4-6-think` | 0.758 |
> `latency_critical` 选了**非 `-think` 版本**——thinking 变体推理延迟更高,低延迟策略会主动避开它。可见策略权重真实作用于"能力 / 成本 / 延迟"的权衡,而不是只看能力。
> **内容也会改变结果**:把同样的 `auto:quality_first` 用在**代码任务**上(上面示例的请求),维度会从 `text.overall` 变为 `text.coding`、实测命中 `claude-opus-4-6-think`——策略与请求内容共同决定最终模型。
未知的策略后缀(如 `auto:fast`)会**回退到默认策略 `cost_optimized`**,不会报错。
***
## 工作原理
收到 `model=auto` 后,网关分三步把"意图"变成"具体模型":
分析这次请求的输入 / 输出模态(文本、图片、文件)、内容意图(代码、数学、图片理解、视频理解、图表、语言、是否联网搜索等)、以及请求规模(预估输入 / 输出 token),归一为一个**任务维度**。例如:含代码的提问 → `text.coding`;带图片 → `vision`;普通文本 → `text.overall`。
把不满足**硬性约束**的模型直接排除:不支持所需输入 / 输出模态、上下文窗口装不下、被熔断摘除(见[可靠性与容错](#可靠性与容错))、或不在你这把 Key 的可用模型范围内。
对通过过滤的候选,基于**业界权威基准**的模型能力评分、叠加实时价格与性能数据,按所选策略对"能力 / 成本 / 延迟"做三维加权评分,取得分最高的一个。最终模型名会写回请求与响应头。
打分示例(`quality_first` 策略下,同一候选池的 top 3,示例数据基于历史生产决策日志):
| 候选模型 | 能力分 | 相对成本 | 延迟 | 综合得分 |
| ----------------------- | :--: | :--: | :-----: | :-------: |
| `claude-opus-4-6-think` | 1504 | 220 | 1963ms | **0.758** |
| `claude-opus-4-6` | 1498 | 220 | 822ms | 0.721 |
| `claude-fable-5` | 1510 | 484 | 11130ms | 0.600 |
> 注意 `claude-fable-5` 的**能力分最高**(1510),却因成本更高、延迟更大被综合得分压到第三。这正是加权评分的意义:不是"唯能力论",而是按策略在能力 / 成本 / 延迟之间权衡。
`claude-fable-5` 为阶段性发布的预览基线模型(staged preview baseline),现已**退役下线(deprecated)**、不再对外提供服务;此处保留其历史评分,仅用于演示加权打分机制,实际请求不会再命中该模型。
维度识别是自动的——智能路由内置 **30+ 细分任务维度**(代码 / 数学 / 图片 / 图表 / 长文 / 中文 / 联网…),远比"按模型族粗分流"精细。同样填 `auto`,不同内容会路由到不同维度:
| 你的请求 | 识别维度 |
| ------------------------------- | ------------------------- |
| 普通文本提问 | `text.overall` |
| 含代码、要求写 / 调试程序 | `text.coding` |
| 数学证明 / 求解 | `text.math` |
| 很长的提问(约 500+ token) | `text.longer_query` |
| 中文提问 | `text.language.chinese` |
| 图片输入 + "What is in this image?" | `vision.overall` |
| 图片输入 + "OCR…" / "识别文字" | `vision.ocr` |
| 图片输入 + 图表 / 流程图 | `vision.diagram` |
| 开启联网搜索 | `search.overall` |
| 图像生成(`/v1/images/generations`) | `text_to_image.overall` |
| 图像编辑(`/v1/images/edits`,图入图出) | `image_edit.single_image` |
这些维度名来自业界权威评测榜单对模型 **细分能力** 的拆解,`auto` 据此把每类请求送到该细分能力最强的模型。常见领域举例:
* **文本**:`text.coding`=写 / 调代码、`text.math`=数学求解、`text.longer_query`=长文处理、`text.language.chinese`=中文、`text.occupational.legal` / `text.occupational.medicine`=法律 / 医疗等职业场景。
* **视觉**:`vision.ocr`=识别图片中的文字、`vision.diagram`=看懂图表 / 流程图、`vision.overall`=通用看图理解。
维度识别采用保守匹配(高精度、低误判):长尾、模糊的请求会落到更通用的维度(如 `text.overall` / `vision.overall`),而不是被勉强归类,从而避免误路由。
**图片输入也走智能路由**:在 `/v1/chat/completions` 里带图片提问,会按图片任务路由到视觉能力强的模型。生产环境实测:「OCR 识别这张图」→ `vision.ocr`、命中 `qwen3.5-397b-a17b`;通用看图「What is in this image?」→ `vision.overall`、命中 `gpt-5.4-mini`。(这里指图片**理解**;图片**生成**走 `/v1/images/*` 接口,同样支持 `auto`,见 [FAQ](#常见问题-faq)。)
### 缓存支持
同一个会话会优先持续使用同一模型。这样多轮对话的表现更一致,也能持续命中推理厂商的 prompt 缓存,减少长上下文的重复计费并降低响应延迟。
无需额外改造:Claude Code、Codex、OpenCode 等主流 Agent 的会话标识会被自动识别。需要精确控制会话范围时,可在请求中添加:
```text theme={null}
X-Aihubmix-Session-Id: your-session-id
```
模型不会被永久锁定。当当前模型不支持本轮请求、需要更强能力或服务暂时不可用时,系统会自动切换到合适的健康模型;会话空闲约 1 小时后,路由也会重新选择。
你可以通过响应头确认路由结果:
* `X-Aihubmix-Router-Resolved-Model`:本轮实际使用的模型
* `X-Aihubmix-Router-Sticky: true`:复用了该会话此前的模型
* `X-Aihubmix-Router-Reason`:本轮路由原因
***
## 评分榜单与模型池
各维度的模型评分榜单与当前在池模型,可在[智能路由介绍页](https://aihubmix.com/llm-router/auto)交互查看,也可通过免登录开放接口直接获取:[获取自动路由策略对应模型范围](/cn/api/RouterEndpoints/leaderboard)、[获取模型厂商图标](/cn/api/RouterEndpoints/vendors)。榜单展示口径与路由候选一致:仅展示当前可被正常路由的模型,分数为各维度内归一化的 0–100 值,并随模型池持续更新。
***
## 可靠性与容错
智能路由内置**多重容错**,保证 `auto` 路径**永不无故失败**:
网关对每个模型维护一个滑动窗口的失败率统计。当某模型在窗口内失败次数足够多、且失败率超过阈值时,会被临时摘除出候选池,冷却一段时间后自动恢复——避免把后续请求继续送给正在抽风的模型。失败信号来自**上游对该请求返回的错误**;网关自身的"无可用渠道"不计入(那不是模型本身的问题)。
万一硬过滤把所有候选都排除了(例如某种模态组合暂时没有可用模型),网关不会直接报错,而是按输出类型分配一个兜底模型保证有响应,并在响应头加上 `X-Aihubmix-Router-Fallback: true` 让你知晓。
如果你的 Key 限定了可用模型范围,智能路由(含兜底)选出的模型**始终**在该范围内。若范围内确实没有任何模型能服务这次请求,会明确返回 403,而不是静默使用范围外(可能更贵)的模型。
***
## 计费说明
**按实际命中的模型原价计费,智能路由本身不收取任何附加费。**
最终由哪个模型响应,就按那个模型的价格、能力和上下文限制计算——这个模型就是响应头 `X-Aihubmix-Router-Resolved-Model` 和响应体 `model` 字段里的值。换句话说,智能路由不会"偷偷用贵模型":每一次命中都写在响应里,可逐条对账。
***
## 限制
* 智能路由目前面向**对话补全** `/v1/chat/completions` 与**图像生成 / 编辑** `/v1/images/*` 接口(详见 [FAQ:支持哪些接口](#常见问题-faq))。
* `?router=off` 或请求头 `X-Router-Off` 会让 `model=auto` 直接返回 **400**——这是明确拒绝"既要 auto 又要关掉路由"的歧义用法,而不是静默忽略:
```bash theme={null}
curl -i "https://aihubmix.com/v1/chat/completions?router=off" \
-H "Authorization: Bearer " \
-H "Content-Type: application/json" \
-d '{"model":"auto","messages":[{"role":"user","content":"hi"}]}'
# → HTTP/1.1 400 Bad Request
# {"error":{"message":"auto requires router enabled; remove ?router=off / X-Router-Off", ...}}
```
* 候选集合随平台 catalog 动态变化:同一个 `auto` 在不同时间可能命中不同模型(这是设计使然,可通过响应头复盘)。当前候选范围可通过[获取自动路由策略对应模型范围](/cn/api/RouterEndpoints/leaderboard)接口查询。
***
## 和 OpenRouter / LiteLLM 的区别
"自动选模型"并非 AIHubMix 独有,OpenRouter 与 LiteLLM 都提供类似能力。差异主要在**接入成本**与**托管方式**:
| 差异点 | OpenRouter | LiteLLM | AIHubMix |
| ----------------------------------------- | :--------: | :-----: | :------: |
| 按请求内容自动选模 | ✅ | ✅ | ✅ |
| 零配置、开箱即用(无需编写路由规则 / utterances) | ✅ | ❌ | ✅ |
| 平台托管,无需自建 / 自部署 proxy | ✅ | ❌ | ✅ |
| 成本 / 质量 / 延迟多策略,一个参数切换 | ❌ | ❌ | ✅ |
| 命中决策可追溯(响应头含 dimension / policy / reason) | ❌ | ❌ | ✅ |
| 按最终命中模型计费 | ✅ | ❌ | ✅ |
***
## 常见问题 FAQ
**Q:智能路由支持哪些接口?**
A:目前 `model=auto` 支持 **OpenAI 兼容的对话补全接口** `/v1/chat/completions`,以及**图像生成 / 编辑接口**(`/v1/images/generations`、`/v1/images/edits`)。音频、`/v1/embeddings`、`/v1/rerank` 等接口暂不支持 `auto`,请直接指定具体模型。
**Q:智能路由支持图片输入吗?**
A:支持。在 `/v1/chat/completions` 里带图片(`image_url`)提问属于图片**理解**,会按图片任务路由到视觉能力强的模型——例如 `vision.ocr`(识别图片中的文字)、`vision.diagram`(看懂图表 / 流程图)、`vision.overall`(通用看图理解)等。图片**生成**同样支持 `auto`:在 `/v1/images/*` 接口把 `model` 填 `auto`,会按图像生成维度(如 `text_to_image.overall`)选模。
**Q:我怎么知道这次请求到底用了哪个模型?**
A:看响应头 `X-Aihubmix-Router-Resolved-Model`,或响应体的 `model` 字段——回填的都是真实模型名。见 [如何确认实际命中的模型](#如何确认实际命中的模型)。
**Q:智能路由会不会偷偷用贵模型?**
A:不会。默认策略 `cost_optimized` 是成本优先;而且每次命中的模型都写在响应里、按其原价计费,可逐条对账。见[计费说明](#计费说明)。
**Q:怎么控制 / 预估成本?**
A:三个手段叠加——① 默认 `auto`(`cost_optimized`)就是成本优先;② 用 **Key 的可用模型范围**把候选锁定在你接受的价位内,相当于给成本设上界;③ 每次命中按响应头 `Resolved-Model` 的模型原价计费,可逐条对账。需要更强能力时再显式用 `auto:quality_first`。
**Q:`auto` 和「模型映射 / 回退」有什么区别?**
A:[模型映射 / 回退](https://docs.aihubmix.com/cn/api/Model-Mapping-Fallback)是 **Key 级固定别名 + 失败时的有序兜底**(每次都同一个目标);智能路由是**按每次请求内容动态选模**。前者解决"客户端只认某个名字 / 主模型挂了切备用",后者解决"我不在乎是哪个,给我最合适的"。
**Q:能不能限定智能路由只在某几个模型里选?**
A:可以——通过 **Key 的可用模型范围**约束:智能路由只会在该 Key 允许的模型里选,越权模型不会被命中。
**Q:流式请求支持吗?**
A:支持。路由在请求进入上游前完成,对流式 / 非流式一视同仁。
**Q:为什么同一句话两次调用命中了不同模型?**
A:候选集合与价格随平台 catalog 动态变化,这是设计使然。用响应头里的 `Decision-Id` 与 `Resolved-Model` 即可复盘每一次决策;当前候选范围可通过[获取自动路由策略对应模型范围](/cn/api/RouterEndpoints/leaderboard)接口查询。
**Q:怎么让请求稳定命中同一个模型(比如想复用 prompt 缓存)?**
A:智能路由自带会话粘性:同一会话会优先持续使用同一模型,Claude Code、Codex、OpenCode 等主流 Agent 的会话标识会被自动识别,也可用请求头 `X-Aihubmix-Session-Id` 精确控制会话范围(见[缓存支持](#缓存支持))。注意这是"优先复用"而非永久锁定——模型不支持本轮请求、需要更强能力或服务不可用时会自动切换。若要**严格确定**命中同一模型,请**直接指定具体模型名**,或用 **Key 把可用范围限定到单一模型**。
***
## 相关资源
* [模型映射与回退](https://docs.aihubmix.com/cn/api/Model-Mapping-Fallback):Key 级固定别名 + 失败兜底,与智能路由互补。
* [统一推理参数](https://docs.aihubmix.com/cn/api/unified-inference):跨模型一致的请求参数。
* [AIHubMix 模型页](https://aihubmix.com/models):查询模型名称、价格与 `Input Modalities`。
* [获取自动路由策略对应模型范围](https://docs.aihubmix.com/cn/api/RouterEndpoints/leaderboard):免登录查询 30+ 路由维度中公开的 5 大类 23 个子维度评分与在池模型。
# 内容审查接口
Source: https://docs.aihubmix.com/cn/api/moderation
提供与 OpenAI 标准完全兼容的内容审查 API,开发者可以通过此接口,利用多模态审核模型自动识别文本或图片中的有害内容(如仇恨言论、暴力、违禁活动等),确保应用合规性。
## 接口信息
* **Endpoint (API 地址)**: `https://aihubmix.com/v1/moderations`
* **请求方式**: `POST`
* **认证方式**: `Authorization: Bearer `
* **Content-Type**: `application/json`
* 此端点可以使用两种模型:
1. `omni-moderation-latest`:该模型和所有快照均支持更多分类选项和多模态输入
2. `text-moderation-latest`: 仅支持文本输入,且输入分类较少
## 快速入门
### 使用示例
```python 文本输入 theme={null}
import openai
client = openai.OpenAI(
api_key="AIHUBMIX_API_KEY",
base_url="https://aihubmix.com/v1"
)
response = client.moderations.create(
model="text-moderation-latest",
input="The quick brown fox jumps over the lazy dog.",
)
print(response)
```
```python 图片和文字输入 theme={null}
import openai
client = openai.OpenAI(
api_key="AIHUBMIX_API_KEY",
base_url="https://aihubmix.com/v1"
)
response = client.moderations.create(
model="omni-moderation-latest",
input=[
{"type": "text", "text": "图中为一位男性,他双臂用力上举、身体紧绷,头部仰起、张着嘴,表情极度激动或者愤怒。"},
{
"type": "image_url",
"image_url": {
"url": "https://thumbs.dreamstime.com/b/violent-man-furious-straining-arms-looking-up-concept-person-35012557.jpg",
# can also use base64 encoded image URLs
# "url": "data:image/jpeg;base64,abcdefg..."
}
},
],
)
print(response)
```
### 输出示例
以下是一个完整的输出示例,该模型能够正确预测图像中的自残和暴力元素。
```json theme={null}
{
"id": "modr-5175",
"model": "omni-moderation-latest",
"results": [
{
"flagged": true,
"categories": {
"harassment": false,
"harassment_threatening": false,
"hate": false,
"hate_threatening": false,
"illicit": false,
"illicit_violent": false,
"self_harm": true,
"self_harm_instructions": false,
"self_harm_intent": false,
"sexual": false,
"sexual_minors": false,
"violence": true,
"violence_graphic": true
},
"category_applied_input_types": {
"harassment": ["text"],
"harassment_threatening": ["text"],
"hate": ["text"],
"hate_threatening": ["text"],
"illicit": ["text"],
"illicit_violent": ["text"],
"self_harm": ["text", "image"],
"self_harm_instructions": ["text", "image"],
"self_harm_intent": ["text", "image"],
"sexual": ["text", "image"],
"sexual_minors": ["text"],
"violence": ["text", "image"],
"violence_graphic": ["text", "image"]
},
"category_scores": {
"harassment": 0.00507676338091392,
"harassment_threatening": 0.0008967480822931635,
"hate": 8.830458477845481e-05,
"hate_threatening": 1.0720880092159908e-05,
"illicit": 3.740956047302422e-05,
"illicit_violent": 2.868540823874629e-05,
"self_harm": 0.6967791744783793,
"self_harm_instructions": 0.00027978227581033677,
"self_harm_intent": 0.0003781080988395418,
"sexual": 0.0007007652612809208,
"sexual_minors": 2.5071593847983196e-06,
"violence": 0.5236158587905301,
"violence_graphic": 0.4213528687243541
}
}
]
}
```
输出结果在 JSON 响应中包含几个类别,这些类别会告诉你输入中存在哪些(如果有的话)内容类别,以及模型认为它们存在的程度。
| **输出类别** | **描述** |
| :----------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `flagged` | 如果模型将内容判定为可能存在潜在风险或违规,则该值为 `true`;否则为 `false`。 |
| `categories` | 包含一个按类别划分的违规标记字典。对于每一个类别,如果模型认为该类别存在违规行为,则对应的值为`true`,否则为`false` |
| `category_scores` | 包含一个按类别划分的评分字典,用于表示模型判断输入内容违反 OpenAI 相关政策的置信度。取值范围为 `0` 到 `1`,数值越高表示模型对该类别违规判断的置信度越高。 |
| `category_applied_input_types` | 该字段用于说明在每个违规类别中,哪些输入类型被判定为违规。例如:如果模型同时判定图像输入和文本输入在 “violence/graphic(暴力/血腥)” 类别下存在问题,则 `violence/graphic` 对应的值将为 `["image", "text"]`。
⚠️ 该字段仅在 omni 系列模型中提供。 |
## 内容分类
下表描述了审核 API 可以检测到的内容类型,以及每个类别支持的模型和输入类型。
标记为“仅限文本”的类别不支持图像输入。如果您仅向模型发送图像(不包含文本)`omni-moderation-latest`,则对于这些不支持的类别,模型将返回 0 分。
| **类别** | **描述** | **模型** | **输入** |
| :----------------------- | :----------------------------------------------------------------------- | :------ | :----- |
| `harassment` | 表达、煽动或宣扬针对任何目标的骚扰性语言的内容。 | 全部 | 纯文本 |
| `harassment/threatening` | 包含暴力或对任何目标造成严重伤害的骚扰内容。 | 全部 | 纯文本 |
| `hate` | 表达、煽动或宣扬基于种族、性别、民族、宗教、国籍、性取向、残疾状况或种姓的仇恨的内容。针对非受保护群体(例如,国际象棋棋手)的仇恨内容构成骚扰。 | 全部 | 纯文本 |
| `hate/threatening` | 仇恨内容,包括基于种族、性别、民族、宗教、国籍、性取向、残疾状况或种姓而对目标群体实施的暴力或严重伤害。 | 全部 | 纯文本 |
| `illicit` | 提供如何实施非法行为的建议或指导的内容。例如,“如何入店行窃”就属于此类。 | 仅限 Omni | 纯文本 |
| `illicit/violent` | 与该类别标记的内容类型相同`illicit`,但还包括提及暴力或获取武器。 | 仅限 Omni | 纯文本 |
| `self-harm` | 宣扬、鼓励或描绘自残行为(例如自杀、割伤和饮食失调)的内容。 | 全部 | 文字和图片 |
| `self-harm/intent` | 内容中,说话者表达了他们正在或打算进行自残行为,例如自杀、割伤和饮食失调。 | 全部 | 文字和图片 |
| `self-harm/instructions` | 鼓励实施自残行为(如自杀、割伤、饮食失调)的内容,或者提供如何实施此类行为的指导或建议的内容。 | 全部 | 文字和图片 |
| `sexual` | 旨在引起性兴奋的内容,例如对性行为的描述,或宣传性服务的内容(不包括性教育和健康)。 | 全部 | 文字和图片 |
| `sexual/minors` | 包含未满 18 岁人士的性内容。 | 全部 | 纯文本 |
| `violence` | 包含死亡、暴力或身体伤害的内容。 | 全部 | 文字和图片 |
| `violence/graphic` | 包含对死亡、暴力或身体伤害进行详细描述的内容。 | 全部 | 文字和图片 |
***
更新时间:2026-06-01
# 快速使用
Source: https://docs.aihubmix.com/cn/api/responses/Basic-Usage
开始使用 Responses API Beta
Responses API Beta 支持「简单字符串输入」 和 「结构化消息数组」两种方式。
## 简单字符串输入
使用 API 最简单的方法是直接传入一个字符串:
```shellscript theme={null}
curl -X POST https://aihubmix.com/v1/responses \
-H "Authorization: Bearer YOUR_AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5.4",
"input": "What is the meaning of life?",
"max_output_tokens": 5000
}'
```
## 结构化消息输入
如果需要进行更复杂的对话,可以使用消息数组格式:
```shellscript theme={null}
curl -X POST https://aihubmix.com/v1/responses \
-H "Authorization: Bearer YOUR_AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.1-pro-preview",
"input": [
{
"type": "message",
"role": "user",
"content": [
{
"type": "input_text",
"text": "Plan a week-long trip to the US for me."
}
]
}
],
"max_output_tokens": 9000
}'
```
## 响应格式
API 会返回一个结构化响应,包含生成的内容:
```json theme={null}
{
"id": "resp_06785a42ff90c6",
"object": "response",
"created_at": 1773136544,
"status": "completed",
"background": false,
"completed_at": 1773136550,
"content_filters": null,
"error": null,
"frequency_penalty": 0.0,
"incomplete_details": null,
"instructions": null,
"max_output_tokens": 9000,
"max_tool_calls": null,
"model": "gpt-54",
"output": [
{
"id": "rs_06785a42ff90c6d20069afeaa0731c81979150247a7ee80c8a",
"type": "reasoning",
"summary": []
},
{
"id": "msg_06785a42ff90c6d20069afeaa22f3c819781184c050374974d",
"type": "message",
"status": "completed",
"content": [
{
"type": "output_text",
"annotations": [],
"logprobs": [],
"text": "There is no single, universally agreed-upon “answer” to the question “What is the meaning of life?”—it depends on your background, beliefs and the lenses through which you look. Here are a few ways people have approached it:\n\n1. Religious and spiritual perspectives \n • In many theistic traditions, life’s meaning is found in a relationship with the divine—loving and serving God (or gods), living according to sacred teachings, and preparing for an afterlife or spiritual growth. \n • In Eastern spiritualities (Buddhism, Hinduism), life can be about liberating yourself from suffering and ignorance (nirvana or moksha), often through compassion, selflessness and meditation.\n\n2. Philosophical viewpoints \n • Existentialism (Sartre, Camus) argues that life has no inherent meaning—each of us must create our own through our choices, actions and commitments. \n • Nihilism holds that life is ultimately meaningless, but some see this “freedom from pre-existing purpose” as an opportunity to build authentic values for oneself. \n • Aristotelian ethics looks for eudaimonia (“flourishing” or “well-being”) achieved by cultivating virtues—courage, wisdom, justice, friendship—and living in balance.\n\n3. Scientific and naturalistic outlooks \n • From a biological standpoint, life’s “purpose” is to survive and reproduce, passing on genes to the next generation. \n • Many scientists and secular thinkers add that we can create our own meaning by pursuing knowledge, understanding the universe, and using our creativity to improve the human condition.\n\n4. Psychological and humanistic approaches \n • Viktor Frankl (logotherapy) proposed that finding purpose—even in suffering—is crucial to mental health. Meaning can be discovered through work you care about, relationships you value, and the attitude you take toward unavoidable suffering. \n • Positive psychology emphasizes factors like relationships, achievement, personal growth and contribution to something larger than yourself as sources of fulfilment.\n\n5. A personal, evolving journey \n • Ultimately, most agree that “the meaning of life” is something you discover or construct for yourself. It may come from: \n – Deep relationships (family, friends, community) \n – Creative expression (art, music, writing, invention) \n – Service to others (volunteering, activism, caregiving) \n – Pursuit of knowledge (science, philosophy, exploration) \n – Personal growth (learning, overcoming challenges, self-reflection)\n\nHow to explore your own answer: \n• Reflect on your core values and what gives you genuine joy. \n• Notice what activities make you lose track of time or give you a sense of flow. \n• Engage in conversations with people of different beliefs and life experiences. \n• Experiment with new pursuits—volunteering, creative hobbies, study, travel. \n• Be patient: your sense of purpose may shift as you grow, face new challenges or learn more about the world and yourself.\n\nIn the end, the question “What is the meaning of life?” invites you not to find a one-size-fits-all answer, but to embark on a lifelong journey of discovery—to shape, live out and continually refine your own answer."
}
],
"role": "assistant"
}
],
"parallel_tool_calls": true,
"presence_penalty": 0.0,
"previous_response_id": null,
"prompt_cache_key": null,
"prompt_cache_retention": null,
"reasoning": {
"effort": "medium",
"summary": null
},
"safety_identifier": null,
"service_tier": "default",
"store": true,
"temperature": 1.0,
"text": {
"format": {
"type": "text"
},
"verbosity": "medium"
},
"tool_choice": "auto",
"tools": [],
"top_logprobs": 0,
"top_p": 1.0,
"truncation": "disabled",
"usage": {
"input_tokens": 13,
"input_tokens_details": {
"cached_tokens": 0
},
"output_tokens": 935,
"output_tokens_details": {
"reasoning_tokens": 256
},
"total_tokens": 948
},
"user": null,
"metadata": {}
}
```
## 流式响应
可以开启流式输出,实现实时生成内容:
```shellscript theme={null}
curl -X POST https://aihubmix.com/v1/responses \
-H "Authorization: Bearer YOUR_AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5.4",
"input": "What is the meaning of life?",
"max_output_tokens": 5000
"stream": true
}'
```
## 常用参数
| 参数 | 类型 | 描述 |
| :------------------ | :------------- | :--------------------- |
| model | string | 必填。要使用的模型,例如 `gpt-5.4` |
| input | string 或 array | 必填。输入文本或消息数组 |
| stream | boolean | 是否启用流式响应(默认 false) |
| max\_output\_tokens | integer | 最大生成 token 数 |
| temperature | number | 采样温度,参数范围 0~2 |
| top\_p | number | 采样参数,参数范围 0~1 |
***
更新时间:2026-06-01
# 推理
Source: https://docs.aihubmix.com/cn/api/responses/Reasoning
Responses API Beta 支持高级推理能力,允许模型在回答问题时展示其内部推理过程,并且可以通过参数配置推理努力程度。
## 推理配置
可以通过 `reasoning` 参数配置推理行为:
```shellscript theme={null}
curl -X POST https://aihubmix.com/v1/responses \
-H "Authorization: Bearer YOUR_AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "glm-5",
"input": "Plan a week-long trip to the US for me.",
"reasoning": {
"effort": "high"
},
"max_output_tokens": 5000
}'
```
## 推理强度
`effort` 参数用于控制模型投入多少计算资源进行推理,即控制模型推理努力程度。
| 推理等级 | 描述 |
| :------ | :------------ |
| minimal | 最基础推理,计算量最小 |
| low | 轻量推理,适合简单问题 |
| medium | 平衡推理,适合中等复杂问题 |
| high | 深度推理,适合复杂问题 |
## 在对话中使用推理
推理功能也可以用于多轮对话:
```python theme={null}
import requests
url = "https://aihubmix.com/v1/responses"
headers = {
"Authorization": "Bearer YOUR_AIHUBMIX_API_KEY",
"Content-Type": "application/json",
}
data = {
"model": "kimi-k2.5",
"input": [
{
"type": "message",
"role": "user",
"content": [
{
"type": "input_text",
"text": "What is your favorite animal?",
}
],
},
{
"type": "message",
"role": "assistant",
"id": "msg_123",
"status": "completed",
"content": [
{
"type": "output_text",
"text": "I don't have a favorite animal.",
"annotations": []
}
],
},
{
"type": "message",
"role": "user",
"content": [
{
"type": "input_text",
"text": "Why is the sky blue?",
}
],
},
],
"reasoning": {
"effort": "high"
},
"max_output_tokens": 5000,
}
response = requests.post(url, headers=headers, json=data)
print(response.status_code)
print(response.json())
```
## 含有推理信息的响应
当启用推理后,API 返回结果的会包含推理数据:
```json theme={null}
{
"id": "resp_051e00420efb9e150069aff6a18418819591abb7ce5f8487ed",
"object": "response",
"created_at": 1773139617,
"status": "completed",
"background": false,
"completed_at": 1773139621,
"content_filters": [
{
"blocked": false,
"source_type": "completion",
"content_filter_raw": [],
"content_filter_results": {},
"content_filter_offsets": {
"start_offset": 0,
"end_offset": 1147,
"check_offset": 0
}
}
],
"error": null,
"frequency_penalty": 0.0,
"incomplete_details": null,
"instructions": null,
"max_output_tokens": 5000,
"max_tool_calls": null,
"model": "gpt-54",
"output": [
{
"id": "rs_051e00420efb9e150069aff6a32f948195996db3ff98314ef2",
"type": "reasoning",
"summary": []
},
{
"id": "msg_051e00420efb9e150069aff6a33d808195825716a666d8ba8b",
"type": "message",
"status": "completed",
"role": "assistant",
"content": [
{
"type": "output_text",
"annotations": [],
"logprobs": [],
"text": "The sky looks blue because of how sunlight interacts with Earth’s atmosphere.\n\n1. **Sunlight isn’t just “white”**\nSunlight is made of many colors (red, orange, yellow, green, blue, violet), each with different wavelengths.\n\n2. **Air scatters short wavelengths more**\nAs sunlight passes through the atmosphere, it hits gas molecules and tiny particles.\n- Shorter wavelengths (blue, violet) are scattered in all directions much more than longer wavelengths (red, orange).\n- This effect is called **Rayleigh scattering**.\n\n3. **We see more blue than violet**\n- Our eyes are more sensitive to blue than to violet.\n- Some violet light is also absorbed higher in the atmosphere.\nSo the scattered light we perceive is mostly blue.\n\n4. **Why sunsets are red/orange**\nAt sunrise and sunset, sunlight passes through much more atmosphere.\n- Most of the blue light gets scattered out of the direct path.\n- The remaining light reaching your eyes from the Sun is richer in reds and oranges."
}
]
}
],
"parallel_tool_calls": true,
"presence_penalty": 0.0,
"previous_response_id": null,
"prompt_cache_key": null,
"prompt_cache_retention": null,
"reasoning": {
"effort": "high",
"summary": null
},
"safety_identifier": null,
"service_tier": "default",
"store": true,
"temperature": 1.0,
"text": {
"format": {
"type": "text"
},
"verbosity": "medium"
},
"tool_choice": "auto",
"tools": [],
"top_logprobs": 0,
"top_p": 1.0,
"truncation": "disabled",
"usage": {
"input_tokens": 35,
"input_tokens_details": {
"cached_tokens": 0
},
"output_tokens": 267,
"output_tokens_details": {
"reasoning_tokens": 29
},
"total_tokens": 302
},
"user": null,
"metadata": {}
}
```
## 使用建议
1. **选择合适的推理努力程度**:`high`用于复杂问题,`low`用于简单任务。
2. **考虑 token 使用情况**:推理会增加 token 消耗
3. **使用流式处理**:对于较长的推理链,流式处理可提供更好的用户体验。
4. **包含上下文**:为模型提供足够的上下文,使其能够有效推理。
***
更新时间:2026-06-01
# 工具调用
Source: https://docs.aihubmix.com/cn/api/responses/Tool-Calling
使用 Responses API Beta 进行函数调用与工具集成
Responses API Beta 支持完整的工具调用(Tool Calling)能力,允许模型:
* 调用函数(Function Calling)
* 并行执行多个工具
* 处理复杂的多步骤工作流(Multi-step Workflow)
## 基础工具定义
### 请求头
```shellscript theme={null}
curl -X POST https://aihubmix.com/v1/responses \
-H "Authorization: Bearer YOUR_AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
```
### 请求体
```json theme={null}
{
"model": "claude-sonnet-4-6",
"input": [
{
"type": "message",
"role": "user",
"content": [
{
"type": "input_text",
"text": "What is the weather in San Francisco?"
}
]
}
],
"tools": [
{
"type": "function",
"name": "get_weather",
"description": "Get the current weather at a location",
"strict": null,
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"]
}
},
"required": ["location"]
}
}
],
"tool_choice": "auto",
"max_output_tokens": 5000
}
```
## 工具调用策略
`tool_choice` 参数用于控制模型何时以及如何调用工具。
| 参数 | 说明 |
| :--- | :------------ |
| auto | 由模型自动决定是否调用工具 |
| none | 禁止模型调用任何工具 |
## 多工具定义
在复杂任务中,可以定义多个工具,让模型根据用户需求选择合适的工具。
```python theme={null}
import requests
# 天气工具
weather_tool = {
"type": "function",
"name": "get_weather",
"description": "Get current weather information for a city",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "The name of the city"
}
},
"required": ["city"]
}
}
# 计算器工具
calculator_tool = {
"type": "function",
"name": "calculate",
"description": "Perform mathematical calculations",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "The mathematical expression to evaluate"
}
},
"required": ["expression"]
}
}
response = requests.post(
"https://aihubmix.com/v1/responses",
headers={
"Authorization": "Bearer AIHUBMIX_API_KEY",
"Content-Type": "application/json",
},
json={
"model": "glm-5",
"input": [
{
"type": "message",
"role": "user",
"content": [
{
"type": "input_text",
"text": "What is 25 * 4?"
}
]
}
],
"tools": [weather_tool, calculator_tool],
"tool_choice": "auto",
"max_output_tokens": 5000
}
)
print(response.json())
```
## 含有工具调用的响应
```json theme={null}
{
"id": "resp_09b8eb7c272559fc0069affbaab5cc8194a5005746b80f3b57",
"object": "response",
"created_at": 1773140906,
"completed_at": 1773140908,
"status": "completed",
"background": false,
"error": null,
"model": "gpt-54",
"service_tier": "default",
"temperature": 1.0,
"top_p": 1.0,
"frequency_penalty": 0.0,
"presence_penalty": 0.0,
"max_output_tokens": 5000,
"max_tool_calls": null,
"parallel_tool_calls": true,
"tool_choice": "auto",
"truncation": "disabled",
"store": true,
"previous_response_id": null,
"prompt_cache_key": null,
"prompt_cache_retention": null,
"instructions": null,
"safety_identifier": null,
"user": null,
"metadata": {},
"reasoning": {
"effort": "none",
"summary": null
},
"content_filters": [
{
"blocked": false,
"source_type": "completion",
"content_filter_raw": [],
"content_filter_results": {},
"content_filter_offsets": {
"start_offset": 0,
"end_offset": 1289,
"check_offset": 0
}
}
],
"text": {
"format": {
"type": "text"
},
"verbosity": "medium"
},
"output": [
{
"id": "fc_09b8eb7c272559fc0069affbabb0288194b63aa879435c7cd0",
"type": "function_call",
"status": "completed",
"name": "calculate",
"call_id": "call_PFtWscQ3pAyfSaotwujhT0sn",
"arguments": {
"expression": "25*4"
}
}
],
"tools": [
{
"type": "function",
"name": "get_weather",
"description": "Get current weather information for a city",
"strict": true,
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "The name of the city"
}
},
"required": ["city"],
"additionalProperties": false
}
},
{
"type": "function",
"name": "calculate",
"description": "Perform mathematical calculations",
"strict": true,
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "The mathematical expression to evaluate"
}
},
"required": ["expression"],
"additionalProperties": false
}
}
],
"usage": {
"input_tokens": 86,
"output_tokens": 25,
"total_tokens": 111,
"input_tokens_details": {
"cached_tokens": 0
},
"output_tokens_details": {
"reasoning_tokens": 0
}
}
}
```
## 使用建议
1. 清晰的描述:提供详细的功能描述和参数解释。
2. 正确的模式:参数应使用有效的 JSON。
3. 错误处理:处理工具可能无法调用的情况。
4. 并行执行:尽可能设计能够独立运行的工具。
5. 对话流程:在后续请求中包含工具响应以提供背景信息。
***
更新时间:2026-06-01
# 概述
Source: https://docs.aihubmix.com/cn/api/responses/overview
OpenAI-compatible Responses API (Beta)
**Beta API**
该 API 目前处于 测试阶段(Beta),未来可能会有较大更新,在生产环境中使用时需要谨慎。
AIHubMix 的 Responses API(Beta)通过统一接口提供与 OpenAI Responses API 兼容的访问方式,您可以通过该接口调用多个模型,包括 GPT、Claude、GLM、Gemini等。
该接口还提供了增强功能,包括:
* 推理(Reasoning)
* 工具调用(Tool Calling)
## Base URL
```tex theme={null}
https://aihubmix.com/v1/responses
```
## 认证
所有的请求都需要通过 AIHubMix API Key 认证。
```python Python theme={null}
import requests
url = "https://aihubmix.com/v1/responses"
headers = {
"Authorization": "Bearer YOUR_AIHUBMIX_API_KEY",
"Content-Type": "application/json"
}
data = {
"model": "claude-sonnet-4-6",
"input": "Hello, world!"
}
response = requests.post(url, headers=headers, json=data)
print(response.status_code)
print(response.json())
```
```text TypeScript theme={null}
const response = await fetch('https://aihubmix.com/v1/responses', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_AIHUBMIX_API_KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'o4-mini',
input: 'Hello, world!',
}),
});
```
```shellscript cURL theme={null}
curl -X POST https://aihubmix.com/v1/responses \
-H "Authorization: Bearer YOUR_AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "o4-mini",
"input": "Hello, world!"
}'
```
***
更新时间:2026-06-01
# 结构化输出修复
Source: https://docs.aihubmix.com/cn/api/structured-output-repair
为 API Key 开启结构化输出修复:结构化输出请求返回的 JSON 存在截断、尾随逗号、代码块包裹等格式错误时,网关自动修复为可解析的合法 JSON,数值保持原样,支持 Chat Completions、Responses、Claude、Gemini,客户端零改动。
模型在[结构化输出](/cn/api/Structured-Output)场景下返回的 JSON 有时无法通过解析:输出被 `max_tokens` 截断、带有尾随逗号、内容被包在 Markdown 代码块里。应用侧通常要为此编写重试或手工修复逻辑。
**结构化输出修复**(Structured Output Repair)是一个 **Key 级别**的能力,默认关闭。开启后,对声明了结构化 JSON 输出的**非流式**请求,当模型返回的 JSON 存在格式错误时,AIHubMix 网关在返回前自动将其修复为可解析的合法 JSON;客户端代码无需改动。
该开关默认关闭;未开启时所有响应原样返回。开关按 Key 独立配置,开启后立即生效。
创建或编辑 Key,打开「结构化输出修复」(Structured Output Repair)开关。
***
## 1. 生效条件
修复只在以下条件**全部满足**时发生:
1. 请求使用的 Key 已开启「结构化输出修复」。
2. 请求为**非流式**(未设置 `stream: true`)。
3. 请求声明了结构化 JSON 输出(各协议的声明字段见下表)。
4. 模型返回的文本内容无法通过 JSON 解析。
| 协议 | 端点 | 结构化输出声明字段 |
| ---------------- | ----------------------------------------------- | ------------------------------------------------------------------------------ |
| Chat Completions | `/v1/chat/completions` | `response_format.type` 为 `json_object` 或 `json_schema` |
| Responses | `/v1/responses` | `text.format.type` 为 `json_schema` 或 `json_object` |
| Claude Messages | `/v1/messages` | `output_config.format.type` 为 `json_schema` |
| Gemini | `/gemini/v1beta/models/{model}:generateContent` | `generationConfig.responseMimeType` 为 `application/json`,或设置了 `responseSchema` |
内容本身是合法 JSON 时不做任何改动,原样返回。
***
## 2. 可修复的格式错误
**输出截断导致括号 / 引号未闭合**(如 `finish_reason` 为 `length`):
```text 修复前 theme={null}
{"items": [{"name": "Widget", "price": 9.99}, {"name": "Gad
```
```json 修复后 theme={null}
{"items": [{"name": "Widget", "price": 9.99}, {"name": "Gad"}]}
```
**Markdown 代码块包裹**:
````text 修复前 theme={null}
```json
{"status": "ok", "count": 3}
```
````
```json 修复后 theme={null}
{"status": "ok", "count": 3}
```
**尾随逗号**:
```text 修复前 theme={null}
{"a": 1, "b": 2,}
```
```json 修复后 theme={null}
{"a": 1, "b": 2}
```
**单引号**:
```text 修复前 theme={null}
{'name': 'Widget'}
```
```json 修复后 theme={null}
{"name": "Widget"}
```
**键名未加引号**:
```text 修复前 theme={null}
{name: "Widget", price: 9.99}
```
```json 修复后 theme={null}
{"name": "Widget", "price": 9.99}
```
**文本与 JSON 混杂**(JSON 前后带说明文字):
```text 修复前 theme={null}
Here is the JSON you requested: {"name": "Widget", "price": 9.99}
```
```json 修复后 theme={null}
{"name": "Widget", "price": 9.99}
```
修复采取保守策略:
* 修复只补全或规范化 JSON 语法;**数值与字符串内容保持原文,不发生精度损失或改写**。
* 修复产物必须是合法的 JSON 对象或数组,且与原文差异在合理范围内;任一条件不满足时放弃修复、原样返回原始内容。
***
## 3. 如何判断响应被修复过
发生修复时,有两个可编程 / 可查看的信号:
1. **响应头** `X-JSON-Repaired: true`(未发生修复时无此响应头)。
2. **调用日志备注**:[调用记录页](https://console.aihubmix.com/logs) 对应请求的备注列显示 `This request gateway automatically corrected the JSON format issue in the model output.`
Token 用量与计费按模型的原始输出计算,修复不改变计费结果。
***
## 4. 完整示例
以生成商品信息为例,请求使用 `json_schema` 声明结构化输出;开启开关后,即使模型输出存在上述格式错误,拿到的 `content` 也可以直接解析:
```python Python theme={null}
import json
import os
import requests
response = requests.post(
"https://aihubmix.com/v1/chat/completions",
headers={
"Authorization": f"Bearer {os.environ['AIHUBMIX_API_KEY']}",
"Content-Type": "application/json",
},
json={
"model": "gpt-5.2",
"messages": [
{"role": "user", "content": "Generate a product listing for a wireless keyboard."}
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "product",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"price": {"type": "number"},
"description": {"type": "string"},
},
"required": ["name", "price"],
"additionalProperties": False,
},
},
},
},
)
repaired = response.headers.get("X-JSON-Repaired") == "true"
product = json.loads(response.json()["choices"][0]["message"]["content"])
print(product, "repaired:", repaired)
```
```typescript TypeScript theme={null}
const response = await fetch("https://aihubmix.com/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.AIHUBMIX_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gpt-5.2",
messages: [
{ role: "user", content: "Generate a product listing for a wireless keyboard." },
],
response_format: {
type: "json_schema",
json_schema: {
name: "product",
schema: {
type: "object",
properties: {
name: { type: "string" },
price: { type: "number" },
description: { type: "string" },
},
required: ["name", "price"],
additionalProperties: false,
},
},
},
}),
});
const repaired = response.headers.get("X-JSON-Repaired") === "true";
const data = await response.json();
const product = JSON.parse(data.choices[0].message.content);
console.log(product, "repaired:", repaired);
```
```shell curl theme={null}
curl -sD - https://aihubmix.com/v1/chat/completions \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5.2",
"messages": [
{"role": "user", "content": "Generate a product listing for a wireless keyboard."}
],
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "product",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"price": {"type": "number"},
"description": {"type": "string"}
},
"required": ["name", "price"],
"additionalProperties": false
}
}
}
}'
```
想主动观察一次修复,可以把 `max_tokens` 设置为较小的值(如 `80`)让输出被截断:响应的 `finish_reason` 为 `length`,`content` 是修复后的合法 JSON,响应头带有 `X-JSON-Repaired: true`。
***
## 5. 边界与说明
流式请求(`stream: true`)不做修复,按原样转发。需要修复能力时请使用非流式请求。
修复保证内容可以通过 JSON 解析;被截断而缺失的数据无法恢复。建议同时检查 `finish_reason` / `stop_reason`,输出被截断时按需增大 `max_tokens` 后重试。
* **语法修复**:字段名、字段类型是否符合你的 schema 仍需应用侧校验。
* **工具调用参数不在修复范围**:`tool_calls` / `function_call` 的参数 JSON 不做修复;工具参数在执行前应始终由应用侧校验。
* **多文本块输出不做修复**:模型输出包含多个文本块(例如 Gemini 返回多个 `parts`)时按原样返回。
* **推理内容不受影响**:`reasoning_content`、Gemini 的 thought 部分等推理文本不参与修复。
***
## 常见问题
**修复会改变返回内容里的数值或文本吗?**
不会。修复只补全或规范化 JSON 语法(补全闭合括号、去除尾随逗号、引号规范化、剥离代码块标记),数值与字符串内容保持模型输出原文。
**开启开关会影响未声明结构化输出的普通请求吗?**
不会。未声明 `response_format` 等结构化输出字段的请求,以及所有流式请求,响应均原样返回。
**修复会额外计费或改变 token 用量吗?**
不会。Token 用量与计费按模型的原始输出计算,修复过程不产生额外费用。
**修复后的 JSON 一定符合我定义的 schema 吗?**
修复保证内容可以通过 JSON 解析;字段名与字段类型是否符合 schema 取决于模型输出本身,建议应用侧继续保留 schema 校验。
# 统一推理参数
Source: https://docs.aihubmix.com/cn/api/unified-inference
为了简化不同模型供应商(OpenAI, Anthropic, Google, DeepSeek 等)对推理/思考过程的处理逻辑,AIHubMix 现已对接**统一推理参数规范**。开发者可以通过一套标准接口控制模型的思考强度并获取详细的推理链路,控制 claude、Gemini、glm-5、minimax、等模型的思考开关及强度。
# **统一参数定义**
## 开启思考`reasoning`
reasoning可以通过以下方式设置:
### (推荐)使用openai标准定义的reasoning\_effort参数:
```text theme={null}
{
"model": "claude-sonnet-4-5",
"messages": [
{
"role": "system",
"content": "You are an AI assistant"
},
{
"role": "user",
"content": "Hello?"
}
],
"reasoning_effort": "low"
}
```
reasoning\_effort的值包含:
* none(推荐):主动关闭思考(部分强制思考模型可能不生效,如minimax-m2.7等)
* minimal:最小化思考,部分模型的效果是关闭思考
* low(推荐)
* medium(推荐)
* high(推荐)
* xhigh
**对于可设置思考强度的模型**,reasoning\_effort有对应的映射关系:
| **effort值** | **gpt** | **claude** | **gemini** | **doubao** |
| :---------- | :------ | :--------- | :--------- | :--------- |
| minimal | minimal | low | MINIMAL | minimal |
| low | low | low | LOW | low |
| medium | medium | medium | MEDIUM | medium |
| high | high | high | HIGH | high |
| xhigh | xhigh | max | HIGH | high |
**对于只支持设置thinking budget的模型**,reasoning\_effort对应的计算规则为基于MaxOutputTokens,计算thinking budget的比例:
* "xhigh": 0.95,
* "high": 0.8,
* "medium": 0.5,
* "low": 0.2,
* "minimal": 0.1,
**对于只支持是否开启思考的模型/供应商**,例如deepseek、qwen、glm、kimi等,reasoning\_effort的效果只有两种:
* none:关闭思考
* 其他:开启思考
### (次选)使用reasoning参数的effort:
```text theme={null}
{
"model": "claude-sonnet-4-5",
"messages": [
{
"role": "system",
"content": "You are an AI assistant"
},
{
"role": "user",
"content": "Hello?"
}
],
"reasoning": {"effort": "low"}
}
```
### (次选)使用reasoning参数的max\_tokens,精确控制thinking的最大token数:
```text theme={null}
{
"model": "claude-sonnet-4-5",
"messages": [
{
"role": "system",
"content": "You are an AI assistant"
},
{
"role": "user",
"content": "Hello?"
}
],
"reasoning": {"max_tokens":1024}
}
```
## 思考返回
思考结果增加两个字段:
* reasoning\_content:思考内容,格式为字符串。
* reasoning\_details:思考原始信息,供多轮对话使用,保留思考内容提升模型效果,格式为结构体,除type为固定属性外,其他属性会随不同模型变化,但类型均为字符串。
非流式返回示例:
```text theme={null}
{
"id": "chatcmpl-msg_01RSXhFMjbZFadHbeV5wA8Qh",
"model": "claude-sonnet-4-5-20250929",
"object": "chat.completion",
"created": 1771840947,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! How can I help you today?",
"reasoning_content": "The user is just saying \"Hello?\" - this is a simple greeting. I should respond in a friendly and welcoming manner, and let them know I'm here to help.",
"reasoning_details": {
"type": "thinking",
"thinking": "The user is just saying \"Hello?\" - this is a simple greeting. I should respond in a friendly and welcoming manner, and let them know I'm here to help.",
"signature": "Er8CCkYICxgCKkBbWyg5ZeExgqX80Bf5g/2pE/oiuJEhkKhFmMkqcAqeqvKNEIMMqfkY2qm12Vg7dcv+ZMg88VXQ9f8nVK65B9npEgxo8vfdPn1IZBFj0iAaDHnXh4Vk9Czek7MDyCIwOzmEvPUKfM2bg8kwSsxMxgyk6ZZQIUHfPzITEZzge3DH1hrg5DenhuSO8WwEeJpTKqYBnSxK/SP/UEOpiDRJd2gxhAVbxweRQu2qrQTV0E+1kt32KXyuJ2qsOi45gq0LoOX+e9utmXImadFTag+fZ7im1TLOAk5nAQ/yOG72T3SQt/WMFwI+szVmT9M2uc2FVyrpIwM8HyDaH+0mJ457en5SVu32kJdluyIGpcl9LLcqGfJdgV6O3DYsNFzuZYZ5h5VtjhXRXl600PySbNN55wIWzJJY0ECrxxgB"
}
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 44,
"completion_tokens": 56,
"total_tokens": 100,
"claude_cache_tokens_details": {
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0,
"cache_write_5_minutes_input_tokens": 0,
"cache_write_1_hour_input_tokens": 0
}
}
}
```
流式返回示例:
```text theme={null}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"role":"assistant","content":"","reasoning_details":{"type":"thinking"}}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":"","reasoning_content":"The user is greeting","reasoning_details":{"type":"thinking","thinking":"The user is greeting"}}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":"","reasoning_content":" me with","reasoning_details":{"type":"thinking","thinking":" me with"}}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":"","reasoning_content":" \"Hello?\". This is a simple","reasoning_details":{"type":"thinking","thinking":" \"Hello?\". This is a simple"}}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":"","reasoning_content":" greeting,","reasoning_details":{"type":"thinking","thinking":" greeting,"}}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":"","reasoning_content":" so I should respond in a friendly and","reasoning_details":{"type":"thinking","thinking":" so I should respond in a friendly and"}}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":"","reasoning_content":" helpful","reasoning_details":{"type":"thinking","thinking":" helpful"}}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":"","reasoning_content":" manner","reasoning_details":{"type":"thinking","thinking":" manner"}}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":"","reasoning_content":". I'll","reasoning_details":{"type":"thinking","thinking":". I'll"}}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":"","reasoning_content":" gr","reasoning_details":{"type":"thinking","thinking":" gr"}}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":"","reasoning_content":"eet them back and let","reasoning_details":{"type":"thinking","thinking":"eet them back and let"}}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":"","reasoning_content":" them know I'm here","reasoning_details":{"type":"thinking","thinking":" them know I'm here"}}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":"","reasoning_content":" to help.","reasoning_details":{"type":"thinking","thinking":" to help."}}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":"","reasoning_details":{"type":"thinking"}}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":"","reasoning_details":{"type":"thinking","signature":"EtkCCkYICxgCKkA1InJ3Nd008PJgr4w3LT55M0niYdNg6kJdwXDU4PxzLMI9IYVJM4rDAsY+mXgK1TIY2+QRf1vzF98SN9anTQR4EgzXpyX2O9gMMWYaSDQaDDE2Owvd9BJdFiGTwSIwf+JRijgNbVCGLytiEKN6sc/BQ4Y5cKfMBQC7Bupy2w0AS8gCAZORRAjTqPw6JfTtKsABSTlAYhtWpx7QcgqlpYHzRx5Kklf6UElBMNMs/HBCqTDF7pn6gy08RWiJIUCyqyu7diubqeFgqnkNgg5Rw6FRSMW53zNca3o3IgxD7fgTpVM1LgRJ2lWYy5DiPrsN8Lpj6TdYlo2LRYlatlkGuOCvHIved68c9TIuhV31KOc9dvr6Apyv2SsIrzDDzGFyYqgTHh8YVyWzeHG+XPKOih6s4wHZ5DpyNdXdPq5Af6txC00UnbY7axTQ3ElA3oBAT/9/GAE="}}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"role":"assistant","content":""}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":"Hello! How can"}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":" I help you today?"}}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"chat.completion.chunk","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[{"index":0,"delta":{"content":""},"finish_reason":"stop"}],"system_fingerprint":"fp-msg_015ZkNJK6y6mNaNukhgKxoah"}
data: {"id":"chatcmpl-msg_015ZkNJK6y6mNaNukhgKxoah","object":"","created":1771845184,"model":"claude-sonnet-4-5-20250929","choices":[],"usage":{"prompt_tokens":44,"completion_tokens":63,"total_tokens":107,"claude_cache_tokens_details":{"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"cache_write_5_minutes_input_tokens":0,"cache_write_1_hour_input_tokens":0}}}
data: [DONE]
```
## 多轮对话
要在多轮对话中保留思考内容,可将reasoning\_details直接传到下一轮对话中即可,以便于模型在收到tool call结果后进行更复杂的推理;流式返回则只需要将type相同的连续的reasoning\_details中除type外所有参数拼接起来,再把type值加入,传到下一轮对话即可。
### **非流式版本参考示例**
**参考代码**
```text theme={null}
import json
import logging
import http.client
import ssl
from urllib.parse import urlparse
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
BASE_URL = "https://aihubmix.com"
API_KEY = "sk-***"
MODEL = "claude-sonnet-4-6"
EFFORT = "low"
def send_request(path, data):
"""Send HTTP POST request and return JSON response"""
parsed = urlparse(BASE_URL)
host = parsed.netloc
use_https = parsed.scheme == 'https'
if use_https:
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
conn = http.client.HTTPSConnection(host, context=context)
else:
conn = http.client.HTTPConnection(host)
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
json_data = json.dumps(data)
try:
conn.request("POST", path, json_data, headers)
response = conn.getresponse()
response_data = json.loads(response.read().decode('utf-8'))
if response.status != 200:
logger.error(f"HTTP Error: {response.status}")
logger.error(response_data)
raise Exception(f"HTTP {response.status}: {response_data}")
return response_data
finally:
conn.close()
# Define tools once and reuse
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
}
}
}]
# ===== Turn 1 =====
req1 = {
"model": MODEL,
"messages": [
{"role": "user", "content": "What's the weather like in Boston and Beijing? Then recommend what to wear."}
],
"parallel_tool_calls": True,
"reasoning_effort": EFFORT,
"tools": tools
}
logger.debug("[Turn 1] Request:\n%s", json.dumps(req1, indent=2, default=str))
response_data = send_request("/v1/chat/completions", req1)
logger.debug("[Turn 1] Response:\n%s", json.dumps(response_data, indent=2, default=str))
# Extract the assistant message
message = response_data["choices"][0]["message"]
# ===== Turn 2 =====
# Build messages with all tool call responses
messages = [
{"role": "user", "content": "What's the weather like in Boston and Beijing? Then recommend what to wear."},
message
]
# Add tool responses for all tool calls
for tool_call in message.get("tool_calls", []):
messages.append({
"role": "tool",
"tool_call_id": tool_call["id"],
"content": '{"temperature": 45, "condition": "rainy", "humidity": 85}'
})
req2 = {
"model": MODEL,
"messages": messages,
"parallel_tool_calls": True,
"reasoning_effort": EFFORT,
"tools": tools
}
logger.debug("[Turn 2] Request:\n%s", json.dumps(req2, indent=2, default=str))
response_data2 = send_request("/v1/chat/completions", req2)
logger.debug("[Turn 2] Response:\n%s", json.dumps(response_data2, indent=2, default=str))
```
**参考输出**
```text theme={null}
2026-04-12 15:04:10,370 DEBUG [Turn 1] Request:
{
"model": "claude-sonnet-4-6",
"messages": [
{
"role": "user",
"content": "What's the weather like in Boston and Beijing? Then recommend what to wear."
}
],
"parallel_tool_calls": true,
"reasoning_effort": "low",
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string"
}
},
"required": [
"location"
]
}
}
}
]
}
2026-04-12 15:04:13,528 DEBUG [Turn 1] Response:
{
"id": "chatcmpl-msg_01U5aVScUcBHPZRm3KsJZkux",
"model": "claude-sonnet-4-6",
"object": "chat.completion",
"created": 1775977453,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Sure! Let me check the weather in both cities at the same time!",
"reasoning_content": "Let me get weather for both cities simultaneously.",
"reasoning_details": {
"type": "thinking",
"thinking": "Let me get weather for both cities simultaneously.",
"signature": "Eu8BClsIDBgCKkDZd7aZm59FCfvnO9XsFaQfTfhr+CiB/jpZAHHFU2pfSlZneYfF5/mV2FDmm+f19/I4oixVk0CrxTDcD8VpU7ULMhFjbGF1ZGUtc29ubmV0LTQtNjgAEgxj7ktUelYOB0toCBEaDF5tUjSLUbud1CsT/CIw7zwSrL7Ouf5HhoUf/K6px1ENA3/AyDsVoEYldXmhtLQylLTcUtZVi1eV8wcdp+mzKkLrgzTjxq8+JtRcJym/KJYHoa3CPhcAgCd9nJoF3OGcuCnY4sfF2EF0+g0d2WPyWI/k7F4I3y3q0ZGKnNo4JV84YJIYAQ=="
},
"tool_calls": [
{
"id": "toolu_01Uf7t8TeTQBQji8YmFRGxXy",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\":\"Boston\"}"
}
},
{
"id": "toolu_01GMW4HDcCdEEPQi2TAqnLqJ",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\":\"Beijing\"}"
}
}
]
},
"finish_reason": "tool_calls"
}
],
"usage": {
"prompt_tokens": 571,
"completion_tokens": 129,
"total_tokens": 700,
"claude_cache_tokens_details": {
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0,
"cache_write_5_minutes_input_tokens": 0,
"cache_write_1_hour_input_tokens": 0
}
}
}
2026-04-12 15:04:13,528 DEBUG [Turn 2] Request:
{
"model": "claude-sonnet-4-6",
"messages": [
{
"role": "user",
"content": "What's the weather like in Boston and Beijing? Then recommend what to wear."
},
{
"role": "assistant",
"content": "Sure! Let me check the weather in both cities at the same time!",
"reasoning_content": "Let me get weather for both cities simultaneously.",
"reasoning_details": {
"type": "thinking",
"thinking": "Let me get weather for both cities simultaneously.",
"signature": "Eu8BClsIDBgCKkDZd7aZm59FCfvnO9XsFaQfTfhr+CiB/jpZAHHFU2pfSlZneYfF5/mV2FDmm+f19/I4oixVk0CrxTDcD8VpU7ULMhFjbGF1ZGUtc29ubmV0LTQtNjgAEgxj7ktUelYOB0toCBEaDF5tUjSLUbud1CsT/CIw7zwSrL7Ouf5HhoUf/K6px1ENA3/AyDsVoEYldXmhtLQylLTcUtZVi1eV8wcdp+mzKkLrgzTjxq8+JtRcJym/KJYHoa3CPhcAgCd9nJoF3OGcuCnY4sfF2EF0+g0d2WPyWI/k7F4I3y3q0ZGKnNo4JV84YJIYAQ=="
},
"tool_calls": [
{
"id": "toolu_01Uf7t8TeTQBQji8YmFRGxXy",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\":\"Boston\"}"
}
},
{
"id": "toolu_01GMW4HDcCdEEPQi2TAqnLqJ",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\":\"Beijing\"}"
}
}
]
},
{
"role": "tool",
"tool_call_id": "toolu_01Uf7t8TeTQBQji8YmFRGxXy",
"content": "{\"temperature\": 45, \"condition\": \"rainy\", \"humidity\": 85}"
},
{
"role": "tool",
"tool_call_id": "toolu_01GMW4HDcCdEEPQi2TAqnLqJ",
"content": "{\"temperature\": 45, \"condition\": \"rainy\", \"humidity\": 85}"
}
],
"parallel_tool_calls": true,
"reasoning_effort": "low",
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string"
}
},
"required": [
"location"
]
}
}
}
]
}
2026-04-12 15:04:20,866 DEBUG [Turn 2] Response:
{
"id": "chatcmpl-msg_01Pp25hirYgzKuyEKsdQ3dqn",
"model": "claude-sonnet-4-6",
"object": "chat.completion",
"created": 1775977461,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Interestingly, both cities are experiencing very similar weather right now! Here's a summary and outfit recommendations:\n\n---\n\n### \ud83c\udf27\ufe0f Boston & Beijing \u2013 Current Weather\n| | Boston | Beijing |\n|---|---|---|\n| \ud83c\udf21\ufe0f Temperature | 45\u00b0F (~7\u00b0C) | 45\u00b0F (~7\u00b0C) |\n| \ud83c\udf26\ufe0f Condition | Rainy | Rainy |\n| \ud83d\udca7 Humidity | 85% | 85% |\n\n---\n\n### \ud83d\udc57 What to Wear\n\nSince both cities share the same chilly, rainy conditions, here are recommendations for **both**:\n\n1. **Waterproof Jacket or Raincoat** \ud83e\udde5 \u2013 A must with the rain and high humidity. Go for something windproof too if possible.\n2. **Warm Layers** \ud83e\udde3 \u2013 At 45\u00b0F, it's cold enough for a sweater or fleece underneath your jacket.\n3. **Waterproof Boots or Water-Resistant Shoes** \ud83d\udc62 \u2013 Keep your feet dry on wet streets.\n4. **Umbrella** \u2602\ufe0f \u2013 Don't leave home without one!\n5. **Scarf & Gloves** \ud83e\udde4 \u2013 Optional but recommended, especially if you'll be outside for extended periods.\n\nStay warm and dry! \u2614"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 799,
"completion_tokens": 324,
"total_tokens": 1123,
"claude_cache_tokens_details": {
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0,
"cache_write_5_minutes_input_tokens": 0,
"cache_write_1_hour_input_tokens": 0
}
}
}
```
### 流式版本参考示例
**参考代码**
```text theme={null}
import json
import logging
import http.client
import ssl
from urllib.parse import urlparse
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
BASE_URL = "https://aihubmix.com"
API_KEY = "sk-***"
MODEL = "claude-sonnet-4-6"
EFFORT = "low"
def send_stream_request(path, data):
"""Send HTTP POST request with streaming and return accumulated message"""
parsed = urlparse(BASE_URL)
host = parsed.netloc
use_https = parsed.scheme == 'https'
if use_https:
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
conn = http.client.HTTPSConnection(host, context=context)
else:
conn = http.client.HTTPConnection(host)
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
json_data = json.dumps(data)
try:
conn.request("POST", path, json_data, headers)
response = conn.getresponse()
if response.status != 200:
error_data = response.read().decode('utf-8')
logger.error(f"HTTP Error: {response.status}")
logger.error(error_data)
raise Exception(f"HTTP {response.status}: {error_data}")
# Read and process streaming response
accumulated_message = {}
tool_calls_dict = {} # Use dict to merge tool_calls by index
for line in response:
line = line.decode('utf-8').strip()
if not line or line == "data: [DONE]":
continue
if line.startswith("data: "):
try:
chunk_data = json.loads(line[6:]) # Remove "data: " prefix
logger.debug(f"Stream chunk: {json.dumps(chunk_data, indent=2, default=str)}")
# Accumulate message from stream chunks
if "choices" in chunk_data and len(chunk_data["choices"]) > 0:
choice = chunk_data["choices"][0]
if "delta" in choice:
delta = choice["delta"]
# Accumulate content
if "content" in delta:
if "content" not in accumulated_message:
accumulated_message["content"] = ""
accumulated_message["content"] += delta["content"]
# print(delta["content"], end="", flush=True)
# Accumulate role
if "role" in delta:
accumulated_message["role"] = delta["role"]
# Accumulate tool_calls (merge by index)
if "tool_calls" in delta:
for tool_call in delta["tool_calls"]:
index = tool_call.get("index", 0)
if index not in tool_calls_dict:
tool_calls_dict[index] = {}
# Merge tool_call fields
for key, value in tool_call.items():
if key == "index":
continue
if key == "function":
if "function" not in tool_calls_dict[index]:
tool_calls_dict[index]["function"] = {}
# Merge function fields
for func_key, func_value in value.items():
if func_key == "arguments":
if "arguments" not in tool_calls_dict[index]["function"]:
tool_calls_dict[index]["function"]["arguments"] = ""
tool_calls_dict[index]["function"]["arguments"] += func_value
else:
tool_calls_dict[index]["function"][func_key] = func_value
else:
tool_calls_dict[index][key] = value
# Accumulate reasoning_content
if "reasoning_content" in delta:
if "reasoning_content" not in accumulated_message:
accumulated_message["reasoning_content"] = ""
accumulated_message["reasoning_content"] += delta["reasoning_content"]
# Accumulate reasoning_details: type is overwritten, strings concatenated
rd = delta.get("reasoning_details")
if rd and isinstance(rd, dict):
if "reasoning_details" not in accumulated_message:
accumulated_message["reasoning_details"] = {}
for key, value in rd.items():
if key == "type":
accumulated_message["reasoning_details"]["type"] = value
elif isinstance(value, str):
accumulated_message["reasoning_details"][key] = accumulated_message["reasoning_details"].get(key, "") + value
elif value is not None:
accumulated_message["reasoning_details"][key] = value
# Get final message details from response (for non-delta fields like role)
if "message" in choice:
message_data = choice["message"]
for key, value in message_data.items():
if key not in accumulated_message: # Don't overwrite accumulated content
accumulated_message[key] = value
except json.JSONDecodeError:
logger.debug(f"Skipping non-JSON line: {line}")
# Convert tool_calls_dict back to list
if tool_calls_dict:
accumulated_message["tool_calls"] = [
tool_calls_dict[i] for i in sorted(tool_calls_dict)
]
print() # New line after streaming
return accumulated_message
finally:
conn.close()
# Define tools once and reuse
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
}
}
}]
# ===== Turn 1 =====
req1 = {
"model": MODEL,
"messages": [
{"role": "user", "content": "What's the weather like in Boston and Beijing? Then recommend what to wear."}
],
"parallel_tool_calls": True,
"reasoning_effort": EFFORT,
"tools": tools,
"stream": True
}
logger.debug("[Turn 1] Request:\n%s", json.dumps(req1, indent=2, default=str))
print("\n[Turn 1] Streaming response:\n")
message = send_stream_request("/v1/chat/completions", req1)
logger.debug("[Turn 1] Accumulated message:\n%s", json.dumps(message, indent=2, default=str))
# ===== Turn 2 =====
# Build messages with all tool call responses
messages = [
{"role": "user", "content": "What's the weather like in Boston and Beijing? Then recommend what to wear."},
message
]
# Add tool responses for all tool calls
for tool_call in message.get("tool_calls", []):
messages.append({
"role": "tool",
"tool_call_id": tool_call["id"],
"content": '{"temperature": 45, "condition": "rainy", "humidity": 85}'
})
req2 = {
"model": MODEL,
"messages": messages,
"parallel_tool_calls": True,
"reasoning_effort": EFFORT,
"tools": tools,
"stream": True
}
logger.debug("[Turn 2] Request:\n%s", json.dumps(req2, indent=2, default=str))
print("\n[Turn 2] Streaming response:\n")
message2 = send_stream_request("/v1/chat/completions", req2)
logger.debug("[Turn 2] Accumulated message:\n%s", json.dumps(message2, indent=2, default=str))
```
**参考输出**
```text theme={null}
2026-04-12 15:19:39,815 DEBUG [Turn 1] Request:
{
"model": "claude-sonnet-4-6",
"messages": [
{
"role": "user",
"content": "What's the weather like in Boston and Beijing? Then recommend what to wear."
}
],
"parallel_tool_calls": true,
"reasoning_effort": "low",
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string"
}
},
"required": [
"location"
]
}
}
}
],
"stream": true
}
[Turn 1] Streaming response:
2026-04-12 15:19:41,714 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"role": "assistant",
"content": "",
"reasoning_details": {
"type": "thinking"
}
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:41,714 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": "",
"reasoning_content": "Let me get the weather for both cities simultaneously.",
"reasoning_details": {
"type": "thinking",
"thinking": "Let me get the weather for both cities simultaneously."
}
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:41,715 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": "",
"reasoning_details": {
"type": "thinking",
"signature": "EvMBClsIDBgCKkApA3tLqIXac23x4XppC7wlH5lCSu/6iSh/hYWFWKNIlSDW0xTsOargmleRKY9UrTgqCbIDvl+C18yy8cWscQPsMhFjbGF1ZGUtc29ubmV0LTQtNjgAEgxnIIYapULsC2rToUoaDPYn/n0x9r+NtYMUYSIwpgr7lxtZvR8AxXeFAeygW9THqnqMcTwT3lKfBRbR9scj8nc7tpYD0bCJlLWay0kkKkau/0c3WHoLnM7oce2g8K8YrrxKGdPT1olGme7l9Hhj9b93AjwJkG92Toj7JPU1DRU4W1tEULdif7k0d0y6epgiegQe1HJEGAE="
}
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:41,715 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"role": "assistant",
"content": ""
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:41,715 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": "Sure! Let me check the weather in both cities"
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:42,230 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": " at the same time!"
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:42,233 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"role": "assistant",
"tool_calls": [
{
"id": "toolu_01Aeac9GjnyE3cJTmpwKiXeT",
"type": "function",
"function": {
"name": "get_weather",
"arguments": ""
},
"index": 0
}
]
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:42,233 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"tool_calls": [
{
"function": {
"arguments": ""
},
"index": 0
}
]
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:42,859 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"tool_calls": [
{
"function": {
"arguments": "{\"locat"
},
"index": 0
}
]
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:42,860 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"tool_calls": [
{
"function": {
"arguments": "ion\": \"Bos"
},
"index": 0
}
]
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:42,860 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"tool_calls": [
{
"function": {
"arguments": "ton\"}"
},
"index": 0
}
]
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:42,860 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"role": "assistant",
"tool_calls": [
{
"id": "toolu_01ErK5zYygpSoARL39dfHcQ1",
"type": "function",
"function": {
"name": "get_weather",
"arguments": ""
},
"index": 1
}
]
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:42,860 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"tool_calls": [
{
"function": {
"arguments": ""
},
"index": 1
}
]
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:42,861 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"tool_calls": [
{
"function": {
"arguments": "{\""
},
"index": 1
}
]
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:42,861 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"tool_calls": [
{
"function": {
"arguments": "loc"
},
"index": 1
}
]
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:42,861 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"tool_calls": [
{
"function": {
"arguments": "ation\": "
},
"index": 1
}
]
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:42,861 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"tool_calls": [
{
"function": {
"arguments": "\"Be"
},
"index": 1
}
]
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:42,862 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"tool_calls": [
{
"function": {
"arguments": "ijing\"}"
},
"index": 1
}
]
}
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:42,863 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "chat.completion.chunk",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": ""
},
"finish_reason": "tool_calls"
}
],
"system_fingerprint": "fp-msg_019r7FZ1qS2DvsTXKAWLVTwX"
}
2026-04-12 15:19:42,863 DEBUG Stream chunk: {
"id": "chatcmpl-msg_019r7FZ1qS2DvsTXKAWLVTwX",
"object": "",
"created": 1775978381,
"model": "claude-sonnet-4-6",
"choices": [],
"usage": {
"prompt_tokens": 571,
"completion_tokens": 130,
"total_tokens": 701,
"claude_cache_tokens_details": {
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0,
"cache_write_5_minutes_input_tokens": 0,
"cache_write_1_hour_input_tokens": 0
}
}
}
2026-04-12 15:19:42,863 DEBUG [Turn 1] Accumulated message:
{
"content": "Sure! Let me check the weather in both cities at the same time!",
"role": "assistant",
"reasoning_details": {
"type": "thinking",
"thinking": "Let me get the weather for both cities simultaneously.",
"signature": "EvMBClsIDBgCKkApA3tLqIXac23x4XppC7wlH5lCSu/6iSh/hYWFWKNIlSDW0xTsOargmleRKY9UrTgqCbIDvl+C18yy8cWscQPsMhFjbGF1ZGUtc29ubmV0LTQtNjgAEgxnIIYapULsC2rToUoaDPYn/n0x9r+NtYMUYSIwpgr7lxtZvR8AxXeFAeygW9THqnqMcTwT3lKfBRbR9scj8nc7tpYD0bCJlLWay0kkKkau/0c3WHoLnM7oce2g8K8YrrxKGdPT1olGme7l9Hhj9b93AjwJkG92Toj7JPU1DRU4W1tEULdif7k0d0y6epgiegQe1HJEGAE="
},
"reasoning_content": "Let me get the weather for both cities simultaneously.",
"tool_calls": [
{
"id": "toolu_01Aeac9GjnyE3cJTmpwKiXeT",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\": \"Boston\"}"
}
},
{
"id": "toolu_01ErK5zYygpSoARL39dfHcQ1",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\": \"Beijing\"}"
}
}
]
}
2026-04-12 15:19:42,864 DEBUG [Turn 2] Request:
{
"model": "claude-sonnet-4-6",
"messages": [
{
"role": "user",
"content": "What's the weather like in Boston and Beijing? Then recommend what to wear."
},
{
"content": "Sure! Let me check the weather in both cities at the same time!",
"role": "assistant",
"reasoning_details": {
"type": "thinking",
"thinking": "Let me get the weather for both cities simultaneously.",
"signature": "EvMBClsIDBgCKkApA3tLqIXac23x4XppC7wlH5lCSu/6iSh/hYWFWKNIlSDW0xTsOargmleRKY9UrTgqCbIDvl+C18yy8cWscQPsMhFjbGF1ZGUtc29ubmV0LTQtNjgAEgxnIIYapULsC2rToUoaDPYn/n0x9r+NtYMUYSIwpgr7lxtZvR8AxXeFAeygW9THqnqMcTwT3lKfBRbR9scj8nc7tpYD0bCJlLWay0kkKkau/0c3WHoLnM7oce2g8K8YrrxKGdPT1olGme7l9Hhj9b93AjwJkG92Toj7JPU1DRU4W1tEULdif7k0d0y6epgiegQe1HJEGAE="
},
"reasoning_content": "Let me get the weather for both cities simultaneously.",
"tool_calls": [
{
"id": "toolu_01Aeac9GjnyE3cJTmpwKiXeT",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\": \"Boston\"}"
}
},
{
"id": "toolu_01ErK5zYygpSoARL39dfHcQ1",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\": \"Beijing\"}"
}
}
]
},
{
"role": "tool",
"tool_call_id": "toolu_01Aeac9GjnyE3cJTmpwKiXeT",
"content": "{\"temperature\": 45, \"condition\": \"rainy\", \"humidity\": 85}"
},
{
"role": "tool",
"tool_call_id": "toolu_01ErK5zYygpSoARL39dfHcQ1",
"content": "{\"temperature\": 45, \"condition\": \"rainy\", \"humidity\": 85}"
}
],
"parallel_tool_calls": true,
"reasoning_effort": "low",
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string"
}
},
"required": [
"location"
]
}
}
}
],
"stream": true
}
[Turn 2] Streaming response:
2026-04-12 15:19:44,954 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"role": "assistant",
"content": ""
}
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:44,954 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": "Inter"
}
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:45,399 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": "estingly, both cities have the same weather right now! Here's a summary and outfit recommendations:\n\n---\n\n### "
}
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:45,779 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": "\ud83c\udf27\ufe0f Boston & Beijing \u2014 Current Weather\n| | Boston"
}
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:46,264 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": " | Beijing |\n|---|---|---|\n| \ud83c\udf21\ufe0f Temperature | 45\u00b0F | 45\u00b0F |\n| \ud83c\udf26\ufe0f Condition | Rainy"
}
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:46,618 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": " | Rainy |\n| \ud83d\udca7 Humidity | 85% | 85% |\n\n---\n\n### \ud83d\udc57 What to Wear\n\nSince both"
}
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:46,968 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": " cities are experiencing **cool, rainy, and humid**"
}
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:47,668 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": " conditions, here's what we recommend:\n\n1. **Waterproof Jacket or Raincoat** \ud83e\udde5 "
}
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:47,827 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": "\u2014 Essential to stay dry in the rain.\n2. **Warm Mid"
}
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:48,263 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": "-Layer** \ud83e\udde3 \u2014 At 45\u00b0F, a sweater or fleece underneath will"
}
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:48,670 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": " keep you comfortable.\n3. **Waterproof Boots or Shoes** \ud83d\udc62 \u2014 Keep your feet dry on wet"
}
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:49,012 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": " streets.\n4. **Umbrella** \u2602\ufe0f \u2014 A must-have for both cities today!"
}
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:49,439 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": "\n5. **Scarf & Light Gloves** \ud83e\udde4 \u2014 The combination of cold"
}
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:49,991 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": " and humidity can feel extra chilly.\n\nStay warm and dry out"
}
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:50,056 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": " there! \ud83c\udf27\ufe0f"
}
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:50,142 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "chat.completion.chunk",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [
{
"index": 0,
"delta": {
"content": ""
},
"finish_reason": "stop"
}
],
"system_fingerprint": "fp-msg_01FXZYmNPMbnd9EHho9ZEmdY"
}
2026-04-12 15:19:50,170 DEBUG Stream chunk: {
"id": "chatcmpl-msg_01FXZYmNPMbnd9EHho9ZEmdY",
"object": "",
"created": 1775978385,
"model": "claude-sonnet-4-6",
"choices": [],
"usage": {
"prompt_tokens": 800,
"completion_tokens": 302,
"total_tokens": 1102,
"claude_cache_tokens_details": {
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0,
"cache_write_5_minutes_input_tokens": 0,
"cache_write_1_hour_input_tokens": 0
}
}
}
2026-04-12 15:19:50,171 DEBUG [Turn 2] Accumulated message:
{
"content": "Interestingly, both cities have the same weather right now! Here's a summary and outfit recommendations:\n\n---\n\n### \ud83c\udf27\ufe0f Boston & Beijing \u2014 Current Weather\n| | Boston | Beijing |\n|---|---|---|\n| \ud83c\udf21\ufe0f Temperature | 45\u00b0F | 45\u00b0F |\n| \ud83c\udf26\ufe0f Condition | Rainy | Rainy |\n| \ud83d\udca7 Humidity | 85% | 85% |\n\n---\n\n### \ud83d\udc57 What to Wear\n\nSince both cities are experiencing **cool, rainy, and humid** conditions, here's what we recommend:\n\n1. **Waterproof Jacket or Raincoat** \ud83e\udde5 \u2014 Essential to stay dry in the rain.\n2. **Warm Mid-Layer** \ud83e\udde3 \u2014 At 45\u00b0F, a sweater or fleece underneath will keep you comfortable.\n3. **Waterproof Boots or Shoes** \ud83d\udc62 \u2014 Keep your feet dry on wet streets.\n4. **Umbrella** \u2602\ufe0f \u2014 A must-have for both cities today!\n5. **Scarf & Light Gloves** \ud83e\udde4 \u2014 The combination of cold and humidity can feel extra chilly.\n\nStay warm and dry out there! \ud83c\udf27\ufe0f",
"role": "assistant"
}
```
***
更新时间:2026-06-01
# 图像理解
Source: https://docs.aihubmix.com/cn/api/vision
了解如何使用视觉功能来理解图像。
## 能力概述
视觉理解(Vision)能力支持模型同时理解图像与文本,并基于图像内容进行分析、描述、判断与问答。开发者可以在一次请求中向模型传入一张或多张图片,并配合自然语言指令,完成多模态理解任务。典型能力包括:
* 图像内容描述(物体、场景、行为)
* 图像问答(针对图片提出问题)
* 多图对比与综合分析
* 图像 + 文本的联合推理
## 快速开始
```python theme={null}
from openai import OpenAI
client = OpenAI(
api_key="",
base_url="https://aihubmix.com/v1"
)
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "What’s in this image?"
},
{
"type": "image_url",
"image_url": {
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
"detail": "auto"
},
},
],
}
],
max_tokens=300,
)
print(response.choices[0])
```
## 支持的输入形式
图像可以通过两种主要方式提供给模型:传递图像的链接或将基础64编码的图像直接包含在请求中。图像可以在 `user`、`system` 和 `assistant` 消息中提供。目前,不支持在第一个 `system` 消息中使用图像
### 图像 URL 输入(推荐)
通过公网可访问的图片 URL 直接传入,适合线上业务场景。
```json theme={null}
{
"type": "image_url",
"image_url": {
"url": "https://example.com/demo.jpg"
}
}
```
**注意事项:**
* URL 必须可被模型访问
* 图片格式需为 PNG / JPEG / WEBP / 非 GIF
* 单张图片大小不超过 20MB
### Base64 编码图像输入
适用于本地文件或私有图片场景。
**流程说明:**
1. 本地读取图片文件
2. 转换为 base64 字符串
3. 作为 image 内容传入请求
```json theme={null}
{
"type": "image_url",
"image_url": {
"url": "data:image/png;base64,"
}
}
```
## 消息结构示例
图像通常与文本指令一起发送,用于明确模型的理解目标。
```json theme={null}
{
"role": "user",
"content": [
{ "type": "text", "text": "请描述这张图片的主要内容" },
{
"type": "image_url",
"image_url": {
"url": "https://example.com/photo.jpg"
}
}
]
}
```
## 多图像输入
一次请求中可以传入**多张图片**,模型会综合所有图像进行理解。
```json theme={null}
{
"role": "user",
"content": [
{ "type": "text", "text": "比较这两张图片的不同之处" },
{ "type": "image_url", "image_url": { "url": "https://example.com/a.jpg" } },
{ "type": "image_url", "image_url": { "url": "https://example.com/b.jpg" } }
]
}
```
***
## 图像清晰度控制(detail 参数)
可通过 `detail` 参数控制模型处理图像的精细程度:
| 参数值 | 说明 |
| :----- | :------------------- |
| `low` | 低分辨率,速度快、Token 消耗低 |
| `high` | 高分辨率,细节更丰富、Token 消耗高 |
| `auto` | 自动选择(默认) |
```json theme={null}
{
"image_url": {
"url": "https://example.com/photo.jpg",
"detail": "high"
}
}
```
**建议策略:**
* 内容理解 / 场景判断:`auto` 或 `low`
* 需要细节观察(文字、局部):`high`
***
## 计费与 Token 说明
视觉输入会消耗额外 Token,需在成本评估中考虑:
* `low` 模式:每张图像固定消耗 **85 Token**
* `high` 模式:根据图像尺寸切片,Token 随清晰度提升
**建议:**
* 默认使用 `auto`
* 在批量或高并发场景下避免不必要的 `high`
## 使用建议
* 始终明确文本指令,不要只发图片
* 控制图片数量与分辨率,避免不必要成本
* 对关键业务结果做二次校验
* 将视觉理解作为辅助能力,而非唯一判断依据
***
更新时间:2026-06-01
# 产品介绍
Source: https://docs.aihubmix.com/cn/index
AIHubMix 由美国 AIHubMix, LLC 主体运营,是获得微软 Azure、AWS、GCP 、阿里云、百度云等各大模型推理云厂商官方授权的合规模型聚合平台。所有服务全部集群化部署云美国谷歌云上,长期为众多知名应用提供高并发、稳定、可信赖的 AI 模型 API 服务,深受开发者和企业的信任。
AI Agent 请先读取 [`docs.aihubmix.com/llms.txt`](https://docs.aihubmix.com/llms.txt) 与 [`aihubmix.com/agents.md`](https://aihubmix.com/agents.md);全部机读入口见 [Agent 接入](/cn/agents)。
## 概述
* **统一接口,极简迁移**:所有模型统一支持 OpenAI chat 兼容接口,代码零改动即可平滑切换。
* **多接口兼容**:支持 OpenAI、Google Gemini、Anthropic多种兼容格式接口
* **一站式模型能力**:文本、图片/视频生成、向量嵌入、Rerank、TTS、STT、OCR 等主流模型全覆盖,满足多场景需求。
* **灵活计费,按量付费**:无会员、无包月,计费规则完全跟对应厂商对齐一致。
一个接口把所有 AI 模型统一接入你的应用
## 文档结构
### 常用 API 参考
图片生成 API
视频生成 API
### 集成与扩展
通过 OpenAI 兼容接口调用所有的模型
通过 Anthropic API 调用所有的模型
对于 Gemini 模型提供原生调用方式
使用 AI SDK 接入大量模型
### 指南与最佳实践
在三方应用中集成 AIHubMix API
高频问题指南
## 常用功能与场景
* **开发工具:** 在 [Claude Code](https://docs.aihubmix.com/cn/api/Claude-Code)、[OpenCode](https://docs.aihubmix.com/cn/api/Opencode)、[Cline](https://docs.aihubmix.com/cn/clients/Cline)、[Gemini Cli](https://docs.aihubmix.com/cn/api/Gemini-Cli)等开发工具中使用
* **应用软件:** 在 [Lobe-chat](https://docs.aihubmix.com/cn/clients/Lobe-Chat)、[OpenAI Translator](https://docs.aihubmix.com/cn/clients/OpenAI-Translator)、[Cursor](https://docs.aihubmix.com/cn/clients/Cursor)、[Cherry Studio](https://docs.aihubmix.com/cn/clients/Cherry-Studio)、[ChatBox](https://docs.aihubmix.com/cn/clients/ChatBox) 等软件中使用
## 快速导航
* [概述](https://docs.aihubmix.com/cn)- 本页
* [快速入门](https://docs.aihubmix.com/cn/quick-start)- 进行首次 API 调用
* [在 Claude Code 中使用](https://docs.aihubmix.com/cn/api/Claude-Code)
* [在 Codex 中使用](https://docs.aihubmix.com/cn/api/Codex-CLI)
* [在 OpenCode 中使用](https://docs.aihubmix.com/cn/api/Opencode)
* [在 Cline 中使用](https://docs.aihubmix.com/cn/clients/Cline)
* [FAQs](https://docs.aihubmix.com/cn/FAQs/Faq)
* 商务合作:[business@aihubmix.com](mailto:business@aihubmix.com)
* 意见反馈:[feedback@aihubmix.com](mailto:feedback@aihubmix.com)
* [提交反馈](https://docs.aihubmix.com/cn/FAQs/Feedback)
***
更新时间:2026-06-01
# 提示词缓存
Source: https://docs.aihubmix.com/cn/practices/prompt-caching
提示词缓存(Prompt Caching)是一种用于降低模型推理成本的重要机制。通过缓存已经处理过的提示内容,在后续请求中重复利用,从而减少重复计算、降低费用并提升响应效率。
## 原理
当您发送启用了提示缓存的请求时,系统会检查提示前缀是否已从最近的查询中缓存。如果找到,则使用缓存,减少处理时间和成本;否则,处理完整提示并在响应开始后缓存前缀。这对以下场景特别有用:
* 包含大量示例的提示
* 大量上下文或背景信息
* 具有一致指令的重复任务
* 长时间的多轮对话
## 核心机制
不同模型供应商对缓存的支持方式不同:
### 自动缓存
自动缓存无需额外配置,系统自动识别并缓存可复用内容,适用于 OpenAI、DeepSeek 等模型。
#### OpenAI
* 最低提示长度:1024 tokens,前缀逐字一致时自动命中
* GPT-5.6 之前的模型:缓存写入不另计费,缓存读取按对应模型的缓存读取价计费
* GPT-5.6 及之后(官方口径 "GPT-5.6 models and later model families",当前为 gpt-5.6-sol / terra / luna):缓存写入按 1.25x 输入价计费,读取按 0.1x 计费;新增 `prompt_cache_key` 与显式缓存断点参数
* 用法、计费与命中排查见 [GPT 提示词缓存](/cn/api/GPT-Cache)
#### Gemini
* 默认启用隐式上下文缓存,缓存自动生效,无需手动配置。
* 缓存仅在内容、模型、参数完全一致时生效;任何字段不同都会视为新请求,不命中缓存。
* 缓存有效期由开发者设定,也可以不设置。如果未指定,默认为 1 小时。无最小或最大时长限制,费用取决于缓存 token 数与缓存时间。
#### DeepSeek / Grok / Moonshot / Groq
* 价格:写缓存免费或同价,读缓存低于原价
### Claude 模型显式缓存
* 需要通过 `cache_control` 启用:请求体顶层字段自动设置断点(随对话前移),或内容块级断点精细控制缓存位置
* 全部活跃 Claude 模型支持,缓存写入 5 分钟档 1.25x、1 小时档 2x、读取 0.1x,计价比例全系统一
* 适用于 Anthropic Claude 模型
Claude 按模型设定最小可缓存 Token 门槛(512 / 1,024 / 2,048 / 4,096 不等,该门槛并非随版本升级而提高):例如 Claude Opus 4.8 为 1,024、Claude Opus 4.7 为 2,048、Claude Opus 4.6 / 4.5 与 Claude Haiku 4.5 为 4,096、Claude Fable 5 为 512。低于门槛的前缀即使显式设置 `cache_control` 也不会被缓存,且不会返回错误——响应中 `cache_creation_input_tokens` 与 `cache_read_input_tokens` 同时为 0 即为此情况。完整分档与排查见 [Claude 提示词缓存](/cn/api/Claude-Cache)。
#### OpenAI 兼容接口
在 `system`、`user`(含图片)、`tools` 中均可通过 `cache_control` 字段设置缓存断点,以下示例仅展示关键结构:
**System 消息缓存(默认 5 分钟 TTL):**
```json theme={null}
{
"model": "claude-opus-4-5",
"messages": [
{
"role": "system",
"content": [
{"type": "text", "text": "You are an AI assistant"},
{
"type": "text",
"text": "(long context)",
"cache_control": {"type": "ephemeral"}
}
]
},
{
"role": "user",
"content": [{"type": "text", "text": "Hello"}]
}
]
}
```
**User 消息缓存(1 小时 TTL):**
```json theme={null}
{
"model": "claude-opus-4-5",
"messages": [
{
"role": "system",
"content": [{"type": "text", "text": "You are an AI assistant"}]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "(long context)",
"cache_control": {"type": "ephemeral", "ttl": "1h"}
},
{"type": "text", "text": "Hello"}
]
}
]
}
```
**图片消息缓存:**
```json theme={null}
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {"detail": "auto", "url": "data:image/jpeg;base64,/9j/4AAQ..."},
"cache_control": {"type": "ephemeral"}
},
{"type": "text", "text": "What's this?"}
]
}
```
**Tool 定义缓存:**
`cache_control` 放在 tool 对象的顶层(与 `type`、`function` 同级):
```json theme={null}
{
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
},
"cache_control": {"type": "ephemeral", "ttl": "1h"}
}]
}
```
#### Anthropic 兼容接口
```shellscript cURL theme={null}
curl https://aihubmix.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: $AIHUBMIX_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-4-6",
"max_tokens": 1024,
"system": [
{
"type": "text",
"text": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n"
},
{
"type": "text",
"text": "",
"cache_control": {"type": "ephemeral"}
}
],
"messages": [
{
"role": "user",
"content": "Analyze the major themes in Pride and Prejudice."
}
]
}'
# 使用相同的输入再次调用模型,直到缓存检查点
curl https://aihubmix.com/v1/messages # rest of input
```
```python Python theme={null}
import anthropic
client = Anthropic(
api_key="",
base_url="https://aihubmix.com"
)
params = {
"model": "claude-opus-4-6",
"max_tokens": 1024,
"system": [
{
"type": "text",
"text": "You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n",
},
{
"type": "text",
"text": "",
"cache_control": {"type": "ephemeral"},
},
],
"messages": [
{
"role": "user",
"content": "Analyze the major themes in 'Pride and Prejudice'.",
}
],
}
response = client.messages.create(**params)
print(response.usage.model_dump_json())
# 使用相同的输入再次调用模型,直到缓存检查点
response = client.messages.create(**params)
print(response.usage.model_dump_json())
```
#### 缓存时间
* 默认: 5 分钟
* 可选:1 小时("ttl": "1h")
> 需要了解更多信息请查看:[Claude 提示词缓存](https://docs.aihubmix.com/cn/blogs/aihubmix-openai-upgrade-claude#2-%E6%8F%90%E7%A4%BA%E8%AF%8D%E7%BC%93%E5%AD%98%EF%BC%88prompt-caching%EF%BC%89)
## 使用建议
1. **保持前缀稳定**
将固定内容放在 Prompt 前部,推荐结构:
```text theme={null}
[系统设定 / 长文本 / RAG数据]
[用户问题(变化部分)]
```
2. **缓存大文本**
优先缓存一下内容:
* RAG 数据
* 长文本
* CSV / JSON 数据
* 角色设定
3. **控制 TTL**
* 短会话 → 5 分钟
* 长会话 → 1 小时(更省成本)
4. **减少缓存写入**
## 避免频繁变化的内容进入缓存,不要缓存时间戳、用户输入变量、高频变化数据等内容。
更新时间:2026-07-10
# 快速开始
Source: https://docs.aihubmix.com/cn/quick-start
生成 API 密钥并进行首次调用
## 直接调用 AIHubMix API
以下示例均使用主域名 `https://aihubmix.com`。如遇访问异常,可将请求地址替换为备用域名 `https://api.inferera.com`,其余参数保持不变。
其中 `` 替换为 [AIHubMix Key](https://aihubmix.com/token),注意 `key` 的有效期和额度限制。
可使用的 `model` 列表,可查阅 [模型广场](https://aihubmix.com/models) ,复制模型名称替换即可。
```py Python theme={null}
import requests
import json
response = requests.post(
url="https://aihubmix.com/v1/chat/completions",
headers={
"Authorization": "Bearer ",
"Content-Type": "application/json",
},
data=json.dumps({
"model": "gpt-4o-mini", # 替换模型 id
"messages": [
{
"role": "user",
"content": "What is the meaning of life?"
}
]
})
)
```
```typescript Javascript theme={null}
// 请在 https://aihubmix.com 域名下尝试,否则有浏览器跨域问题
fetch('https://aihubmix.com/v1/chat/completions', {
method: 'POST',
headers: {
Authorization: 'Bearer ',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: "gpt-4o-mini", // 替换模型 id
messages: [
{
"role": "user",
"content": "What is the meaning of life?"
}
]
}),
})
```
```Shell Curl theme={null}
curl 'https://aihubmix.com/v1/chat/completions'
-H 'Authorization: Bearer '
-H 'Content-Type: application/json'
-d '{
"model": "gpt-4o-mini",
"messages": [
{
"role": "user",
"content": "What is the meaning of life?"
}
]
}'
```
支持流式调用,只需要增加参数 `stream: true`
## 使用 OpenAI SDK
其中 `` 替换为 [AIhubmix Key](https://aihubmix.com/token),注意 `key` 的有效期和额度限制。 可使用的 `model` 列表,可查阅 [模型广场](https://aihubmix.com/models) ,复制模型名称替换即可。
```py Python theme={null}
from openai import OpenAI
client = OpenAI(
base_url="https://aihubmix.com/v1",
api_key="",
)
completion = client.chat.completions.create(
model="gpt-4o-mini", # 替换模型 id
messages=[
{
"role": "developer",
"content": "总是用中文回复"
},
{
"role": "user",
"content": "What is the meaning of life?"
}
],
temperature=0.8,
max_tokens=1024,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
seed=random.randint(1, 1000000000),
)
print(completion.choices[0].message.content)
```
```js Javascript theme={null}
import OpenAI from 'openai';
const openai = new OpenAI({
baseURL: 'https://aihubmix.com/v1',
apiKey: '',
});
async function main() {
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini", // 替换模型 id
messages: [
{
"role": "user",
"content": "What is the meaning of life?"
}
]
});
console.log(completion.choices[0].message);
}
main();
```
对于支持搜索的模型,可以追加下方参数来支持:
```Python theme={null}
web_search_options={}, # 搜索参数
```
可用模型:`gpt-4o-search-preview`、`gpt-4o-mini-search-preview`。
注意搜索模型暂不支持 `temperature` 等细节参数。
## 通过第三方客户端发起请求
## 参考 [场景示例](/cn/clients/AnythingLLM)
更新时间:2026-06-01
# Skills
Source: https://docs.aihubmix.com/cn/skills
AIHubMix Skill 为 Codex、Claude Code、Cursor、Cline 等 AI Agent 提供实时模型查询、接入配置、调用示例生成与错误排查能力。
**AIHubMix Skill** 是面向 AI 编程助手的一套本地扩展能力。安装后,你可以在 Codex、Claude Code、Cursor、Cline 等支持 Skills 的 Agent 里,用自然语言完成 AIHubMix 接入、模型查询、能力选型、示例生成和错误排查。
该 Skill 不内置固定模型清单,而是在需要时从 AIHubMix 官方接口读取模型、价格、上下文、协议契约等实时信息,让 Agent 避免依赖过期记忆。
## 适用场景
| 场景 | 你可以这样说 | Skill 会做什么 |
| ----------- | ------------------------------ | ------------------------------------- |
| 接入 AIHubMix | “把这个项目接入 AIHubMix” | 识别项目技术栈,选择合适协议,给出最小可运行接入方式 |
| 查询模型 | “查一下 gemini 最新可用模型” | 从 AIHubMix 实时模型接口查询并整理结果 |
| 按能力选型 | “有哪些可用的图片输入模型?” | 按视觉、文生图、视频、TTS、STT、向量、重排等能力筛选候选模型 |
| 生成示例 | “给我一个 Anthropic messages 调用示例” | 生成 OpenAI、Anthropic、Gemini 等协议下的可运行示例 |
| 校验 Key | “帮我确认这个模型能不能用” | 通过真实最小调用校验 API Key 与模型可调用性 |
| 排查错误 | “这个 401 / 400 是什么原因?” | 结合接口、模型、错误体和请求 ID 分析处理方式 |
## 前置条件
* 至少安装一个支持 Skills 的 AI Agent,例如 Codex、Claude Code、Cursor、Cline、Gemini CLI、OpenCode 等。
* 本机可运行 Python 3.8 或更高版本。
* 如需真实调用模型,需要准备 [AIHubMix API Key](https://console.aihubmix.com/token)。
* 如需查询余额、Key 列表或当前账号可调用模型,需要额外安装并登录官方 `aihubmix` CLI。
## 安装
### 方式一:让 Agent 帮你安装
把下面这段话交给当前使用的 AI Agent:
```text theme={null}
请安装 AIHubMix Skill:从 https://github.com/AIhubmix/skills 获取,放入当前工具的 Skills 目录。
Claude Code 可使用 ~/.claude/skills,
Codex 可使用 ~/.codex/skills。
安装后运行 python /scripts/AiHubMixAPI.py --help 验证。
```
### 方式二:手动安装
```bash theme={null}
# Claude Code
cp -r AiHubMixAPI ~/.claude/skills/
# Codex
cp -r AiHubMixAPI ~/.codex/skills/
```
不同 Agent 的 Skills 目录可能不同。如果你的工具使用统一目录,可优先查看该 Agent 的 Skills 文档,或让 Agent 自动判断安装位置。
## 可选:安装 AIHubMix CLI
`AiHubMixAPI` 脚本可以读取公开模型和协议信息;账户余额、Key 管理、当前账号实际可调用模型等数据需要官方 CLI 登录后查询。
```powershell theme={null}
# Windows
irm https://raw.githubusercontent.com/AIhubmix/platfrom-cli/main/install.ps1 | iex
```
```bash theme={null}
# macOS / Linux
curl -fsSL https://raw.githubusercontent.com/AIhubmix/platfrom-cli/main/install.sh | sh
```
安装后执行:
```bash theme={null}
aihubmix login
aihubmix whoami
aihubmix models list
```
## 如何使用
安装完成后,通常不需要记命令。直接在 Agent 里描述任务即可:
```text theme={null}
把这个 Next.js 项目接入 AIHubMix,用一个可调用的文本模型做 smoke test。
查一下 Claude 系列在 AIHubMix 里的最新模型和价格。
我可以用哪些文生图模型?只看我当前账号能调用的。
这个接口返回 401,帮我判断是 Key、Base URL 还是模型权限问题。
```
如果 Agent 没有自动触发,可以显式调用对应 Skill,例如:
```text theme={null}
/AiHubMixAPI 查询 gemini 最新模型
/AiHubMixAPI 排查这个 400 报错
```
## 命令行用法
进入 Skill 目录后,也可以直接调用脚本:
```bash theme={null}
# 查询模型
python scripts/AiHubMixAPI.py list --limit 20
python scripts/AiHubMixAPI.py report gemini
python scripts/AiHubMixAPI.py compare
# 按能力查候选模型
python scripts/AiHubMixAPI.py candidates --capability vision
python scripts/AiHubMixAPI.py candidates --capability image-gen
python scripts/AiHubMixAPI.py candidates --capability rerank
# 只看当前账号可调用的候选模型,需要已登录 aihubmix CLI
python scripts/AiHubMixAPI.py candidates --capability vision --mine
```
中文输出可以追加 `--lang zh`,或设置:
```bash theme={null}
export AIHUBMIX_LANG=zh
```
## 能力速查
| 能力 | 推荐命令 |
| ----------------- | ------------------------------------------------------------------- |
| 查看模型列表 | `list` |
| 查询某个模型或系列 | `get ` / `report ` |
| 对比多个模型 | `compare ...` |
| 按能力选型 | `candidates --capability ` |
| 只看账号可调用模型 | `candidates --capability --mine` |
| 校验 API Key | `doctor --model ` |
| 校验图片输入 | `doctor --model --image` |
| 生成 OpenAI 兼容示例 | `example chat --model ` |
| 生成 Anthropic 兼容示例 | `example messages --model ` |
| 排查错误 | `troubleshoot --status --endpoint --model ` |
## 常见问题
### 安装后 Agent 没有自动调用
不同 Agent 对 Skill 触发的策略不同。可以先直接输入 `/AiHubMixAPI` 显式调用;也可以把需求说得更明确,例如包含“AIHubMix”“模型”“Base URL”“API Key”“报错码”等关键词。
### 公开模型列表里有模型,但我的 Key 调不通
公开模型列表只说明平台存在该模型,不代表当前账号一定有权限或余额可调用。需要使用 `aihubmix models list` 或 `candidates --mine` 查看当前账号实际可调用范围,再用 `doctor --model ` 做真实校验。
### 什么时候需要安装 `aihubmix` CLI
只查公开资料时不需要。需要余额、Key 管理、账号可调用模型、`--mine` 筛选等账户相关能力时,需要安装并登录 CLI。
### 会不会泄露 API Key
Skill 的脚本会对密钥做脱敏处理。仍然建议不要把真实 Key 写入仓库文件、Issue、PR 描述或聊天记录中;本地调试时使用环境变量传入即可。
## 相关资源
* Skill 仓库:[https://github.com/AIhubmix/skills](https://github.com/AIhubmix/skills)
* AIHubMix CLI:[https://github.com/AIhubmix/platfrom-cli](https://github.com/AIhubmix/platfrom-cli)
* AIHubMix 模型广场:[https://aihubmix.com/models](https://aihubmix.com/models)
# AI SDK
Source: https://docs.aihubmix.com/cn/api/AISDK
用 AI SDK 接入 AIHubMix:通过 OpenAI 兼容接口,在 TypeScript / JavaScript 代码中统一调度多家厂商模型。
[官方网址](https://ai-sdk.dev/providers/community-providers/aihubmix)
## 支持的功能
AIHubMix provider 支持以下 AI 功能,让你的产品不再局限于 LLM 驱动:
* **文本生成**:使用各种模型生成文本内容
* **流式文本**:实时文本流式传输
* **图像生成**:从文本提示创建图像
* **向量嵌入**:单个和批量文本嵌入
* **对象生成**:结构化数据生成
* **流式对象**:实时结构化数据流式传输
* **语音合成**:文本转语音
* **转录**:语音转文本
* **工具**:联网搜索和其他工具
## 安装
AIHubMix 在 `@aihubmix/ai-sdk-provider` 模块中可用。通过 [@aihubmix/ai-sdk-provider](https://www.npmjs.com/package/@aihubmix/ai-sdk-provider) 安装:
```shell ai 4.3 theme={null}
npm i @aihubmix/ai-sdk-provider@0.0.1
```
```shell ai 5 beta theme={null}
npm i @aihubmix/ai-sdk-provider
```
## Provider 实例
您可以从 `@aihubmix/ai-sdk-provider` 导入默认的 provider 实例 `aihubmix`:
```ts theme={null}
import { aihubmix } from '@aihubmix/ai-sdk-provider';
```
## 配置
将您的 AIHubMix API 密钥设置为环境变量,确保安全读取:
```bash theme={null}
export AIHUBMIX_API_KEY="your-api-key-here"
```
或直接传递给 provider:
```ts theme={null}
import { createAihubmix } from '@aihubmix/ai-sdk-provider';
const aihubmix = createAihubmix({
apiKey: 'your-api-key-here',
});
```
## 使用
导入必要的函数:
```ts theme={null}
import { createAihubmix } from '@aihubmix/ai-sdk-provider';
import {
generateText,
streamText,
generateImage,
embed,
embedMany,
generateObject,
streamObject,
generateSpeech,
transcribe
} from 'ai';
import { z } from 'zod';
```
各种类型的 AI 生成调用示例:
```ts 生成文本 theme={null}
import { aihubmix } from '@aihubmix/ai-sdk-provider';
import { generateText } from 'ai';
const { text } = await generateText({
model: aihubmix('o4-mini'),
prompt: 'Write a vegetarian lasagna recipe for four people.',
});
```
```ts Claude 模型 theme={null}
import { aihubmix } from '@aihubmix/ai-sdk-provider';
import { generateText } from 'ai';
const { text } = await generateText({
model: aihubmix('claude-3-7-sonnet-20250219'),
prompt: 'Explain quantum computing in simple terms.',
});
```
```ts Gemini 模型 theme={null}
import { aihubmix } from '@aihubmix/ai-sdk-provider';
import { generateText } from 'ai';
const { text } = await generateText({
model: aihubmix('gemini-2.5-flash'),
prompt: 'Create a Python script to sort a list of numbers.',
});
```
```ts 流式文本 theme={null}
import { aihubmix } from '@aihubmix/ai-sdk-provider';
import { streamText } from 'ai';
const result = streamText({
model: aihubmix('gpt-3.5-turbo'),
prompt: 'Write a short story about a robot learning to paint.',
maxOutputTokens: 256,
temperature: 0.3,
maxRetries: 3,
});
let fullText = '';
for await (const textPart of result.textStream) {
fullText += textPart;
process.stdout.write(textPart);
}
console.log('\n使用情况:', await result.usage);
console.log('完成原因:', await result.finishReason);
```
```ts 生成对象 theme={null}
import { aihubmix } from '@aihubmix/ai-sdk-provider';
import { generateObject } from 'ai';
import { z } from 'zod';
const result = await generateObject({
model: aihubmix('gpt-4o-mini'),
schema: z.object({
recipe: z.object({
name: z.string(),
ingredients: z.array(
z.object({
name: z.string(),
amount: z.string(),
}),
),
steps: z.array(z.string()),
}),
}),
prompt: 'Generate a lasagna recipe.',
});
console.log(JSON.stringify(result.object.recipe, null, 2));
console.log('Token使用情况:', result.usage);
console.log('完成原因:', result.finishReason);
```
```ts 流式对象 theme={null}
import { aihubmix } from '@aihubmix/ai-sdk-provider';
import { streamObject } from 'ai';
import { z } from 'zod';
const result = await streamObject({
model: aihubmix('gpt-4o-mini'),
schema: z.object({
recipe: z.object({
name: z.string(),
ingredients: z.array(
z.object({
name: z.string(),
amount: z.string(),
}),
),
steps: z.array(z.string()),
}),
}),
prompt: 'Generate a lasagna recipe.',
});
for await (const objectPart of result.partialObjectStream) {
console.log(objectPart);
}
console.log('Token使用情况:', result.usage);
console.log('最终对象:', result.object);
```
```ts 工具调用 theme={null}
// Aihubmix provider 支持各种工具,包括网络搜索:
import { aihubmix } from '@aihubmix/ai-sdk-provider';
import { generateText } from 'ai';
const { text } = await generateText({
model: aihubmix('gpt-4'),
prompt: 'What are the latest developments in AI?',
tools: {
webSearchPreview: aihubmix.tools.webSearchPreview({
searchContextSize: 'high',
}),
},
});
```
```ts 图像生成 theme={null}
import { aihubmix } from '@aihubmix/ai-sdk-provider';
import { generateImage } from 'ai';
const { image } = await generateImage({
model: aihubmix.image('gpt-image-1'),
prompt: 'A beautiful sunset over the mountains',
});
```
```ts 语音合成 theme={null}
import { aihubmix } from '@aihubmix/ai-sdk-provider';
import { generateSpeech } from 'ai';
const { audio } = await generateSpeech({
model: aihubmix.speech('tts-1'),
text: 'Hello, this is a text-to-speech test.',
});
// 保存音频文件
await saveAudioFile(audio);
console.log('音频生成成功:', audio);
```
```ts 转录 theme={null}
import { aihubmix } from '@aihubmix/ai-sdk-provider';
import { transcribe } from 'ai';
const { text } = await transcribe({
model: aihubmix.transcription('whisper-1'),
audio: audioFile,
});
```
```ts 向量嵌入 theme={null}
import { aihubmix } from '@aihubmix/ai-sdk-provider';
import { embed } from 'ai';
const { embedding } = await embed({
model: aihubmix.embedding('text-embedding-ada-002'),
value: 'What is the meaning of life?',
});
```
```ts 批量嵌入 theme={null}
import { aihubmix } from '@aihubmix/ai-sdk-provider';
import { embedMany } from 'ai';
const { embeddings, usage } = await embedMany({
model: aihubmix.embedding('text-embedding-3-small'),
values: [
'海滩上的晴天',
'城市里的雨天下午',
'山间的雪夜',
],
});
console.log('嵌入向量:', embeddings);
console.log('使用情况:', usage);
```
## 相关资源:
* [AIHubMix provider](https://v5.ai-sdk.dev/providers/community-providers/aihubmix)
* [AI SDK](https://ai-sdk.dev/docs)
***
更新时间:2026-06-01
# 通过接口获取账户信息
Source: https://docs.aihubmix.com/cn/api/Cli
通过 AiHubMix CLI 实用管理脚本在命令行中管理密钥、查看账户和可用模型列表等
AiHubMix CLI 是一个实用管理脚本集合,无需通过网页界面,就可以管理你的 AiHubMix API 密钥、查询账户信息以及使用 AI 服务。它本质上是封装了 API 调用(curl或Python请求)以便于命令行使用。
推荐使用新一代命令行工具 [AIHubMix CLI(命令行工具)](/cn/api/aihubmix-cli):单一二进制、零运行时依赖(无需 Python),提供 `aihubmix keys list` 等资源化命令,并对 `jq` 与 AI Agent 友好。本页保留旧版 Python 脚本用法供参考。
## 准备工作
在开始使用 AiHubMix CLI 前,你需要:
1. 一个 [AIHubMix 账户](https://aihubmix.com)
2. 从 [AIHubMix 设置页面](https://aihubmix.com/setting) 点击「生成系统访问令牌」生成访问令牌 (Access Token);
3. 安装必要的 Python 依赖项:
```bash theme={null}
pip install -U requests openai
```
aihubmix\_cli.py 脚本可以[在此获取](https://github.com/jerlinn/inferHub)
## 功能列表
AIHubMix CLI 提供以下主要功能:
### API 端点一览表
| 端点 | HTTP 方法 | 描述 |
| ---------------------------- | ------- | ------------------------------------- |
| `/api/user/self` | GET | 获取当前用户信息和账户余额 |
| `/api/token/` | GET | 获取所有 Key 列表 |
| `/api/token/` | POST | 创建新的 API Key |
| `/api/token/` | PUT | 更新现有 API Key |
| `/api/token/{token_id}` | GET | 获取特定 Key 的详细信息 |
| `/api/token/{token_id}` | DELETE | 删除特定 Key |
| `/api/token/search` | GET | 搜索 Key (使用 `?keyword=search keyword`) |
| `/api/user/token` | GET | 获取用户 Key |
| `/api/user/available_models` | GET | 获取当前用户可用的模型列表 |
### 获取余额信息
```shell Curl 获取账户余额 theme={null}
# 通过 curl 获取余额,余额为 quota /500000
curl -X GET "https://aihubmix.com/api/user/self" \
-H "Authorization: YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json"
```
```py Python 获取账户余额 theme={null}
import requests
import json
# API 配置
api_url = "https://aihubmix.com"
access_token = "YOUR_ACCESS_TOKEN"
headers = {
"Authorization": access_token,
"Content-Type": "application/json"
}
# 获取账户余额
response = requests.get(f"{api_url}/api/user/self", headers=headers)
if response.status_code == 200:
data = response.json()
if data.get("success", False):
user_data = data.get("data", {})
quota = user_data.get('quota', 0)
usd_balance = quota / 500000 # $1 兑换 500,000 额度
print(f"用户名: {user_data.get('username', '未知')}")
print(f"显示名称: {user_data.get('display_name', '未知')}")
print(f"当前额度: {quota}")
print(f"可用美元: ${usd_balance:.2f}")
else:
print(f"请求失败: {data.get('message', '未知错误')}")
else:
print(f"请求失败,状态码: {response.status_code}")
```
```shell CLI 获取账户余额 theme={null}
python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action get_balance
```
```shell CLI 获取 Key 的可用额度 theme={null}
curl 'https://aihubmix.com/dashboard/billing/remain' \
-H 'authorization: Bearer sk-***' \
```
### Key 管理
#### 创建新 Key
```shell Curl theme={null}
curl -X POST "https://aihubmix.com/api/token/" \
-H "Authorization: YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "新Key名称",
"expired_time": -1,
"remain_quota": 500000,
"unlimited_quota": false,
"subnet": ""
}'
```
```py Python theme={null}
import requests
import json
# API 配置
api_url = "https://aihubmix.com"
access_token = "YOUR_ACCESS_TOKEN"
headers = {
"Authorization": access_token,
"Content-Type": "application/json"
}
# 创建新 Key
payload = {
"name": "新Key名称",
"expired_time": -1, # 永不过期
"remain_quota": 500000,
"unlimited_quota": False,
"subnet": ""
}
response = requests.post(f"{api_url}/api/token/", headers=headers, json=payload)
if response.status_code == 200:
data = response.json()
if data.get("success", False):
token_data = data.get("data", {})
print(f"新Key: {token_data.get('key', '未知')}")
print(f"Key ID: {token_data.get('id', '未知')}")
else:
print(f"创建Key失败: {data.get('message', '未知错误')}")
else:
print(f"请求失败,状态码: {response.status_code}")
```
```shell CLI theme={null}
python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action create_token --name "新Key名称" --expires -1 --quota 500000
```
#### 获取 Key 列表
```shell Curl theme={null}
curl -X GET "https://aihubmix.com/api/token/?num=20" \ #修改num参数可以调整输出的数据数量。
-H "Authorization: YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json"
```
```py Python theme={null}
import requests
import json
# API 配置
api_url = "https://aihubmix.com"
access_token = "YOUR_ACCESS_TOKEN"
headers = {
"Authorization": access_token,
"Content-Type": "application/json"
}
# 获取 Key 列表
response = requests.get(f"{api_url}/api/token/", headers=headers)
if response.status_code == 200:
data = response.json()
if data.get("success", False):
tokens_data = data.get("data", [])
print(f"Key列表 (共 {len(tokens_data)} 个):")
for token in tokens_data:
print(f"Key ID: {token.get('id', '未知')}")
print(f"Key 名称: {token.get('name', '未知')}")
print(f"Key: {token.get('key', '未知')}")
print("---")
else:
print(f"获取Key列表失败: {data.get('message', '未知错误')}")
else:
print(f"请求失败,状态码: {response.status_code}")
```
```shell CLI theme={null}
python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action get_tokens
```
#### 搜索 Key
```shell Curl theme={null}
curl -X GET "https://aihubmix.com/api/token/search?keyword=search keyword" \
-H "Authorization: YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json"
```
```py Python theme={null}
import requests
import json
# API 配置
api_url = "https://aihubmix.com"
access_token = "YOUR_ACCESS_TOKEN"
headers = {
"Authorization": access_token,
"Content-Type": "application/json"
}
# 搜索关键词
query = "search keyword"
# 搜索 Key
response = requests.get(f"{api_url}/api/token/search?keyword={query}", headers=headers)
if response.status_code == 200:
data = response.json()
if data.get("success", False):
tokens_data = data.get("data", [])
print(f"搜索结果 (共 {len(tokens_data)} 个):")
for token in tokens_data:
print(f"Key ID: {token.get('id', '未知')}")
print(f"Key 名称: {token.get('name', '未知')}")
print(f"Key: {token.get('key', '未知')}")
print("---")
else:
print(f"搜索Key失败: {data.get('message', '未知错误')}")
else:
print(f"请求失败,状态码: {response.status_code}")
```
```shell CLI theme={null}
python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action search_tokens --query "search keyword"
```
#### 更新 Key
```shell Curl theme={null}
curl -X PUT "https://aihubmix.com/api/token/" \
-H "Authorization: YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"id": "Key_ID",
"name": "新名称",
"expired_time": 86400,
"remain_quota": 100000,
"status": 1
}'
```
```py Python theme={null}
import requests
import json
# API 配置
api_url = "https://aihubmix.com"
access_token = "YOUR_ACCESS_TOKEN"
headers = {
"Authorization": access_token,
"Content-Type": "application/json"
}
# 更新 Key
key_id = "Key_ID" # 替换为实际的Key ID
payload = {
"id": key_id,
"name": "新名称",
"expired_time": 86400, # 24小时后过期
"remain_quota": 100000,
"status": 1 # 1-启用,0-禁用
}
response = requests.put(f"{api_url}/api/token/", headers=headers, json=payload)
if response.status_code == 200:
data = response.json()
if data.get("success", False):
print(f"Key更新成功")
if "data" in data:
token_data = data.get("data", {})
print(f"名称: {token_data.get('name', '未知')}")
print(f"过期时间: {token_data.get('expired_time', '未知')}")
else:
print(f"更新Key失败: {data.get('message', '未知错误')}")
else:
print(f"请求失败,状态码: {response.status_code}")
```
```shell CLI theme={null}
python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action update_token --id "Key_ID" --name "新名称" --expires 86400 --quota 100000 --status 1
```
#### 删除 Key
```shell Cur theme={null}
curl -X DELETE "https://aihubmix.com/api/token/Key_ID" \
-H "Authorization: YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json"
```
```py Python theme={null}
import requests
import json
# API 配置
api_url = "https://aihubmix.com"
access_token = "YOUR_ACCESS_TOKEN"
headers = {
"Authorization": access_token,
"Content-Type": "application/json"
}
# 删除 Key
key_id = "Key_ID" # 替换为实际的Key ID
response = requests.delete(f"{api_url}/api/token/{key_id}", headers=headers)
if response.status_code == 200:
data = response.json()
if data.get("success", False):
print(f"Key删除成功")
else:
print(f"删除Key失败: {data.get('message', '未知错误')}")
else:
print(f"请求失败,状态码: {response.status_code}")
```
```shell CLI theme={null}
python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action delete_token --id "Key_ID"
```
#### 获取用户 Key
```shell Curl theme={null}
curl -X GET "https://aihubmix.com/api/user/token" \
-H "Authorization: YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json"
```
```py Python theme={null}
import requests
import json
# API 配置
api_url = "https://aihubmix.com"
access_token = "YOUR_ACCESS_TOKEN"
headers = {
"Authorization": access_token,
"Content-Type": "application/json"
}
# 获取用户 Key
response = requests.get(f"{api_url}/api/user/token", headers=headers)
if response.status_code == 200:
data = response.json()
if data.get("success", False):
user_token = data.get("data", {}).get("token")
print(f"用户Key: {user_token}")
else:
print(f"获取用户Key失败: {data.get('message', '未知错误')}")
else:
print(f"请求失败,状态码: {response.status_code}")
```
```shell CLI theme={null}
python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action get_user_token
```
### 模型管理
#### 获取用户可用模型
```shell Curl theme={null}
curl -X GET "https://aihubmix.com/api/user/available_models" \
-H "Authorization: YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json"
```
```py Python theme={null}
import requests
import json
# API 配置
api_url = "https://aihubmix.com"
access_token = "YOUR_ACCESS_TOKEN"
headers = {
"Authorization": access_token,
"Content-Type": "application/json"
}
# 获取用户可用模型
response = requests.get(f"{api_url}/api/user/available_models", headers=headers)
if response.status_code == 200:
data = response.json()
if data.get("success", False):
models_data = data.get("data", [])
print(f"用户可用模型列表 (共 {len(models_data)} 个):")
for i, model in enumerate(models_data, 1):
print(f" {i}. {model}")
else:
print(f"获取用户可用模型失败: {data.get('message', '未知错误')}")
else:
print(f"请求失败,状态码: {response.status_code}")
```
```shell CLI theme={null}
python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action get_available_models
```
## 使用 JSON 格式输出
所有 CLI 命令都支持以 JSON 格式输出结果,方便进行程序化处理:
```bash theme={null}
python aihubmix_cli.py --url "https://aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action get_balance --json
```
## 故障排除
如果遇到问题,可以尝试以下解决方案:
1. **连接问题**:如果主域名连接失败,尝试使用备用域名:
```bash theme={null}
python aihubmix_cli.py --url "https://api.aihubmix.com" --token "YOUR_ACCESS_TOKEN" --action get_balance
```
2. **访问令牌无效**:确保提供的访问令牌是从 AIHubMix 网站获取的有效密钥。访问令牌格式通常是 `fd***` 这样的形式。
3. **权限不足**:某些操作可能需要特定的权限,请确保您的账户有足够的权限。
4. **请求失败**:检查网络连接,或尝试稍后再试。
## 注意事项
* 访问令牌与用于访问 AI 模型的普通 API Key 不同
* 每个用户拥有自己的系统访问令牌,其访问级别由用户角色决定(普通用户、管理员或根用户)
***
更新时间:2026-06-01
# Crush
Source: https://docs.aihubmix.com/cn/api/Crush
[Crush](https://github.com/charmbracelet/crush) 是 [Charmbracelet](https://charm.sh/) 推出的终端 AI 编程工具。该团队此前的代表作包括 Bubble Tea、Glow、Lip Gloss 等业界广受认可的 TUI 项目,因此 Crush 在视觉呈现与交互设计层面具备同类工具中较高的水准。截至当前,该项目在 GitHub 累计获得 24,000 余次 Star。
默认情况下,Crush 要求为每个上游 provider(包括 Anthropic、OpenAI、Google、DeepSeek 等)分别完成 API key 配置。**通过接入 AIHubMix,仅需一次配置即可在 Crush 中调用 800+ 个模型**,涵盖 Claude Opus 4.7、GPT 5.5、Gemini 2.5 Pro、DeepSeek V4 Pro、Qwen Max、Kimi K2 等主流模型。
本文将引导用户在五分钟内完成 Crush 与 AIHubMix 的集成配置。
***
## 快速配置指引:
### 1️⃣ 安装地址
可从[官方仓库](https://github.com/charmbracelet/crush)获取应用
### 2️⃣ 环境变量配置
启动后填入 Aihubmix 然后输入密钥即可使用, 密钥可以在 Aihubmix [「Keys」页面](https://aihubmix.com/token) 生成。
## Crush 工具简介
Crush 是一款基于 TUI 的 agentic AI 编程工具,与 Claude Code、Aider、OpenCode 同属一类产品。其差异化优势主要体现于 Charmbracelet 团队一贯的精致 UI 设计语言,以及对多项高级特性的深度集成。
主要能力如下:
* **多 LLM 支持**:会话进行中可随时切换模型
* **MCP(Model Context Protocol)集成**:兼容 http、stdio、sse 三种 server 协议
* **LSP 上下文感知**:提升代码语义解析的准确性
* **Session 工作区管理**:支持多项目独立隔离
* **文件权限控制与 `.crushignore`**:对 agent 可访问的资源范围实现精细化管控
* **Agent Skills 扩展机制**:遵循开放标准
* **跨平台支持**:涵盖 macOS、Linux、Windows、BSD 等主流操作系统
最新版本为 **v0.67.0**(2026 年 5 月发布),GitHub 累计 24,200 余 Star,由 Charmbracelet 团队持续维护。
***
## Crush 与同类工具的对比
下表展示了 Crush 与 Aider、Claude Code、OpenCode 在关键维度上的差异:
| 维度 | Crush | Aider | Claude Code | OpenCode |
| ---------------------- | ----------------- | ------------- | -------------- | -------- |
| UI 风格 | 精致 TUI | 极简 CLI | 极简 CLI | TUI |
| MCP 支持 | ✅ | ❌ | ✅ | ✅ |
| 会话中动态切换模型 | ✅ | ✅ | ❌ | ✅ |
| 自定义 OpenAI 兼容端点 | ✅ | ✅ | ⚠️ 受限 | ✅ |
| LSP 上下文感知 | ✅ | ⚠️ 部分 | ❌ | ✅ |
| 文件排除机制 | ✅ | ✅ | ⚠️ | ✅ |
| 多 session 工作区 | ✅ | ❌ | ❌ | ⚠️ |
| 配置文件格式 | JSON | YAML / CLI 参数 | 环境变量 | JSON |
| GitHub Star 数(2026.05) | 24.2k | 30k+ | 闭源 | 18k+ |
| 适用场景 | 精致 TUI 与 MCP 深度集成 | 极简主义与高启动速度 | Anthropic 生态用户 | 高度可定制化 |
综合而言,若用户重视终端体验的精致度、MCP 集成的完整性,以及在多家模型之间灵活切换的能力,Crush 是优先推荐的方案。
***
## 准备工作
### 1. 安装 Crush
根据操作系统选择对应的安装命令:
```bash theme={null}
# macOS
brew install charmbracelet/tap/crush
# Linux (Arch)
yay -S crush-bin
# Windows
winget install charmbracelet.crush
# 任意支持 Go 的平台
go install github.com/charmbracelet/crush@latest
# 通过 npm 安装
npm install -g @charmland/crush
```
### 2. 获取 AIHubMix API Key
访问 [aihubmix.com](https://aihubmix.com) 完成账号注册,前往 [aihubmix.com/keys](https://aihubmix.com/keys) 创建 API Key。新注册账户可获得10。
### 3. 确认配置文件位置
Crush 按以下优先级查找配置文件:
1. `./.crush.json`(项目级隐藏配置)
2. `./crush.json`(项目级配置)
3. `~/.config/crush/crush.json`(全局配置)
需要注意的是,**项目级配置将覆盖全局配置中的同名字段**。
***
## 核心配置(crush.json 完整模板)
Crush 提供两种与 AIHubMix 兼容的 provider 类型:
* `"type": "openai-compat"`:适用于 GPT、Gemini、DeepSeek、Qwen、Kimi 等绝大多数模型
* `"type": "anthropic"`:适用于 Claude 系列的原生协议调用(prompt caching 等高级特性需通过原生格式访问)
两种类型可在同一配置文件中并存。
以下提供一份开箱即用的完整 `crush.json` 模板,**仅需将 `YOUR_AIHUBMIX_KEY` 替换为实际 Key 值**:
```json theme={null}
{
"$schema": "https://charm.land/crush.json",
"providers": {
"aihubmix-openai": {
"id": "aihubmix-openai",
"name": "AIHubMix (OpenAI 兼容)",
"base_url": "https://aihubmix.com/v1",
"type": "openai-compat",
"api_key": "YOUR_AIHUBMIX_KEY",
"models": [
{ "id": "claude-opus-4-7", "name": "Claude Opus 4.7" },
{ "id": "claude-sonnet-4-6", "name": "Claude Sonnet 4.6" },
{ "id": "gpt-5.5", "name": "GPT 5.5" },
{ "id": "gpt-5-mini", "name": "GPT 5 Mini" },
{ "id": "gemini-2.5-pro", "name": "Gemini 2.5 Pro" },
{ "id": "deepseek-v4-pro", "name": "DeepSeek V4 Pro" },
{ "id": "deepseek-r1", "name": "DeepSeek R1" },
{ "id": "qwen-max", "name": "Qwen Max" },
{ "id": "kimi-k2", "name": "Kimi K2" }
]
},
"aihubmix-anthropic": {
"id": "aihubmix-anthropic",
"name": "AIHubMix (Anthropic 原生)",
"base_url": "https://aihubmix.com",
"type": "anthropic",
"api_key": "YOUR_AIHUBMIX_KEY",
"models": [
{ "id": "claude-opus-4-7", "name": "Claude Opus 4.7(原生)" },
{ "id": "claude-sonnet-4-6", "name": "Claude Sonnet 4.6(原生)" }
]
}
}
}
```
### 字段说明
| 字段 | 必填 | 说明 |
| ---------- | -- | ------------------------------------------------------------------------------------ |
| `id` | 是 | Crush 内部唯一标识符,可由用户自定义 |
| `name` | 是 | 模型选择器界面中显示的名称 |
| `base_url` | 是 | API 端点地址。OpenAI 兼容协议为 `https://aihubmix.com/v1`,Anthropic 协议为 `https://aihubmix.com` |
| `type` | 是 | 取值为 `openai-compat` 或 `anthropic` |
| `api_key` | 是 | AIHubMix API Key,支持通过 `${ENV_VAR}` 语法引用环境变量 |
| `models` | 是 | 启用的模型 ID 列表,需与 AIHubMix 模型注册表保持一致 |
### 推荐:通过环境变量引用 API Key
为避免 Key 以明文形式存储于配置文件中,建议改用环境变量引用方式:
```json theme={null}
"api_key": "${AIHUBMIX_API_KEY}"
```
随后在 shell 环境中完成设置:
```bash theme={null}
export AIHUBMIX_API_KEY="sk-..."
```
***
## 验证配置结果
进入任意项目目录后,启动 Crush:
```bash theme={null}
crush
```
通过模型选择器快捷键(默认为 `Ctrl+P`)打开模型列表。配置成功的情况下,可在 `AIHubMix (OpenAI 兼容)` 与 `AIHubMix (Anthropic 原生)` 两个分组之下看到先前配置的全部模型。
向模型发送测试消息(例如「你是什么模型?」),以确认响应正常返回。
如需进一步确认请求经由 AIHubMix 转发,可访问 [aihubmix.com/usage](https://aihubmix.com/usage) 查看实时调用记录。
***
## 推荐模型搭配方案
Crush 支持在会话过程中切换模型,因此用户可针对不同任务类型选择最适合的模型,在性能与成本之间取得平衡。下表列出了经过实践验证的推荐方案:
| 任务类型 | 推荐模型 | 模型 ID | 选用理由 |
| ------------------ | ----------------- | ------------------- | ------------------------ |
| 多文件重构、复杂 agent 流程 | Claude Opus 4.7 | `claude-opus-4-7` | 多步推理能力领先 |
| 日常代码编写、内联编辑 | Claude Sonnet 4.6 | `claude-sonnet-4-6` | 代码场景下性价比最优 |
| 中文代码注释、文档生成 | DeepSeek V4 Pro | `deepseek-v4-pro` | 中文语义理解与表达能力出色 |
| 大型 monorepo、长上下文场景 | Gemini 2.5 Pro | `gemini-2.5-pro` | 上下文窗口可达 200 万 token 以上 |
| 代码评审等成本敏感场景 | Qwen Max | `qwen-max` | 调用成本约为 Opus 的十分之一,推理能力充足 |
| 复杂调试、推理密集任务 | DeepSeek R1 | `deepseek-r1` | 链式思维能力突出,价格低廉 |
| 快速补全、规划阶段 | Claude Haiku 4.5 | `claude-haiku-4-5` | Claude 家族中响应速度最快 |
| 原型验证、Demo 测试 | GPT 4.1 Nano | `gpt-4.1-nano-free` | 完全免费 |
> **成本优化建议**:在规划阶段使用 `claude-opus-4-7`,执行阶段切换至 `claude-sonnet-4-6` 或 `qwen-max`,可将整体调用成本降至全程使用 Opus 方案的 20%–40%。
完整模型清单请参见 [AIHubMix 模型库](https://aihubmix.com/models)。
***
## MCP 服务配置
Crush 对 MCP(Model Context Protocol)提供完整支持,使 agent 能够直接调用文件系统、GitHub、数据库、浏览器等外部工具。
在 `crush.json` 中添加 MCP server 配置:
```json theme={null}
{
"providers": { ... },
"mcp": {
"servers": {
"filesystem": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/project"]
},
"github": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
}
}
}
}
}
```
更多 MCP server 配置范例与高级用法,请参阅 [MCP 官方文档](https://modelcontextprotocol.io/)。
***
## 常见问题
**Crush 通过 AIHubMix 能否调用 DeepSeek、Qwen、Kimi 等国产模型?**
可以。通过 `openai-compat` 类型的 provider,所有主流国产模型均与 GPT、Claude 共用同一调用接口,开发者无需额外学习专有协议。
**Crush 与 Aider 应如何选择?**
两者均属于 CLI/TUI 形态的 agentic 工具。Aider 历史更悠久、设计更极简、启动速度更快;Crush 在 UI 精致度、MCP 集成深度、模型切换灵活性方面更具优势。**长时间在终端环境下进行开发并注重交互体验**的用户建议选择 Crush;**追求极致速度与最小化配置**的用户可优先考虑 Aider。
**Crush 是否支持标准 OpenAI SDK 调用格式?**
支持。`"type": "openai-compat"` 遵循标准 OpenAI Chat Completions 协议,AIHubMix 与之完全兼容。
**能否在同一配置中并行使用多个 provider?**
可以。前文 `crush.json` 示例即为 OpenAI 兼容与 Anthropic 原生两种 provider 并存的配置范例,Crush 的模型选择器将全部展示。
**如何在会话过程中切换模型?**
会话进行中按下模型选择器快捷键(默认为 `Ctrl+P`),选择目标模型后,后续消息将自动路由至新模型,且对话上下文得以完整保留。
**如何有效降低使用成本?**
低风险任务建议使用免费模型(`gpt-4.1-nano-free`、`deepseek-v3-free` 等),日常工作可使用 `claude-sonnet-4-6` 或 `qwen-max`,**仅在处理复杂场景时启用 `claude-opus-4-7`**。
**Crush 的配置文件存储于何处?**
按优先级依次为:`./.crush.json` → `./crush.json` → `~/.config/crush/crush.json`。**项目级配置会覆盖全局配置中的同名字段**。
**Crush 是否支持本地模型(Ollama、LM Studio 等)?**
支持。`openai-compat` 类型可对接任意符合 OpenAI 协议的端点,包括 `http://localhost:11434`(Ollama)。本地模型与 AIHubMix 可在同一份配置文件中并行使用。
**免费模型应如何启用?**
将带 `-free` 后缀的模型 ID(如 `gpt-4.1-nano-free`、`deepseek-v3-free`)添加至 `crush.json` 的 `models` 字段即可。完整免费模型清单请参见 [aihubmix.com/models?free=true](https://aihubmix.com/models?free=true)。
**如何限制 Crush 可调用的工具范围?**
Crush 支持通过 `allowed_tools` 与 `disabled_tools` 字段进行精细化权限控制,亦可通过 `--yolo` 参数跳过全部权限确认(请谨慎使用)。详情请参阅 [Crush README](https://github.com/charmbracelet/crush#permissions)。
**报错「model not found」应如何处理?**
请核对 `models` 数组中的 `id` 字段是否与 AIHubMix 模型注册表完全一致(包括大小写与连字符)。新发布的模型可能需要 1 至 2 天才能上线,建议前往 [模型列表页](https://aihubmix.com/models) 进行确认。
**为何选择 AIHubMix 而非 OpenRouter?**
两者均与 Crush 兼容。AIHubMix 的差异化优势主要在于:**对国产前沿模型(DeepSeek、Qwen、Kimi、GLM、Doubao 等)的接入更为完整,提供 26+ 个免费模型,采用按 token 透明计费的模式**。若用户的业务场景不涉及国产模型,OpenRouter 亦是合理选择 —— Crush 与两者均可对接。
***
## 故障排查
| 错误码 | 主要原因 | 解决方案 |
| ----------------------------- | --------------------------- | ----------------------------------------------------------------- |
| `401 Unauthorized` | API Key 错误或包含多余字符 | 重新从 [aihubmix.com/keys](https://aihubmix.com/keys) 复制 Key,确认无前后空格 |
| `404 model not found` | 模型 ID 拼写错误或 AIHubMix 平台尚未上线 | 对照 [模型列表](https://aihubmix.com/models) 进行核对 |
| `402 insufficient balance` | 账户余额不足 | 前往 [aihubmix.com/billing](https://aihubmix.com/billing) 完成充值 |
| `429 rate limit` | 短时间内请求频次超出限额 | 增加指数退避重试逻辑,或升级账户等级 |
| `context window exceeded` | 对话历史超出模型上下文窗口容量 | 中途切换至长上下文模型(如 `gemini-2.5-pro`) |
| 工具调用在 `gpt-4.1-nano-free` 上失败 | 该免费模型不支持 tool use 特性 | 切换至 `claude-sonnet-4-6`、`gpt-5-mini`、`deepseek-v4-pro` 等支持工具调用的模型 |
| 流式输出出现乱码或无响应 | provider type 字段配置错误 | 确认配置为 `"type": "openai-compat"`(而非 `"openai"`) |
***
## 进阶用法
### 按任务类型动态分配模型
Crush 支持会话中动态切换模型这一能力,使得用户可以针对不同任务阶段调用不同模型,从而显著降低整体成本:
* **规划阶段** → `claude-opus-4-7`
* **代码生成** → `claude-sonnet-4-6`
* **Commit 信息撰写、代码评审** → `qwen-max` 或 `gpt-5-mini`
* **复杂调试** → `deepseek-r1`
经实测,典型会话的整体成本可较全程使用 Opus 的方案降低 60% 至 80%。
### 通过 `.crushignore` 精简上下文
在项目根目录创建 `.crushignore` 文件,排除 `node_modules`、大型数据文件、敏感配置、二进制资源等无关内容,可显著降低 token 消耗,同时提升响应速度。
### 通过 LSP 提升上下文准确度
Crush 通过 LSP 获取类型信息、引用关系与定义位置等元数据。**建议项目环境中安装对应语言的 language server**,可显著提升模型对代码语义的理解能力。
### Session 持久化机制
Crush 自动保存会话状态,长任务可通过 `crush --resume ` 命令跨日恢复执行。
### 自定义 MCP server
除官方提供的 filesystem、github 等标准 MCP server 之外,用户可使用 Python 或 Node.js 自行实现 MCP server,将项目专属能力(如部署脚本、内部 API、测试 runner 等)以标准协议暴露给 agent。
***
## 延伸阅读
* **完整模型清单** → [AIHubMix 模型库](https://aihubmix.com/models)
* **其他 CLI agent 集成** → [Claude Code](/cn/api/Claude-Code) / [OpenCode](/cn/api/Opencode)
* **IDE 类工具集成** → [Cursor](/cn/clients/Cursor)
* **免费模型配置** → [AIHubMix 免费模型](https://aihubmix.com/models?free=true)
* **Crush 官方文档** → [github.com/charmbracelet/crush](https://github.com/charmbracelet/crush)
***
## 为什么选择 AIHubMix
* **一份 Key 接入 800+ 模型**:Claude、GPT、Gemini、DeepSeek、Qwen、Kimi 等主流模型统一聚合,免除多账户管理负担
* **26+ 个免费模型**:覆盖原型开发、Demo 测试、prompt 调试等多数研发场景
* **OpenAI SDK 完全兼容**:存量代码仅需修改 `base_url` 即可完成迁移
[\*\*立即注册 AIHubMix → \*\*](https://aihubmix.com/register)
最新更新日期:2026年5月12日
# DeepSeek Harness
Source: https://docs.aihubmix.com/cn/api/DeepSeek-Harness
在 DeepSeek Harness 中接入 AIHubMix:安装 npm 发布版、配置 OpenAI 兼容提供方、添加 auto 或指定模型并验证 Agent 请求。
DeepSeek Harness(命令名 `dsh`)是 DeepSeek 开源的编码 Agent Harness,支持工作区、终端、文件编辑、Skills、计划和 Web UI。它可以通过 OpenAI Chat Completions 兼容接口连接 AIHubMix。
本文基于 2026 年 8 月 14 日的实测,DeepSeek Harness 版本为 `0.1.0-rc.6`。Harness 仍处于开发者预览阶段,后续版本的界面和字段可能变化。
## 快速结论
接入需要以下四项配置:
| 配置项 | 值 |
| ---------------------------- | ------------------------- |
| Provider ID | `aihubmix` |
| Base URL | `https://aihubmix.com/v1` |
| API protocol | `openai-completions` |
| API key environment variable | `AIHUBMIX_API_KEY` |
完成后,Models 页面会显示已配置的 AIHubMix 提供方。
## 需要准备什么?
开始前需要:
* 一个可用的 [AIHubMix API Key](https://console.aihubmix.com/token)
* Node.js `22.19.0` 或更高版本,也可以使用 Node.js 24+
* 能访问 npm Registry 和 `https://aihubmix.com` 的网络环境
检查 Node.js 和 npm:
```bash theme={null}
node --version
npm --version
```
## 如何安装 DeepSeek Harness?
直接安装 npm 发布版,无需克隆源码:
```bash theme={null}
npm install -g @deepseek-ai/dsh
```
确认安装结果:
```bash theme={null}
dsh --version
```
若终端提示 `dsh: command not found`,运行 `npm config get prefix`,并确认该目录下的 `bin` 已加入 `PATH`。
## 如何启动 Web UI?
在准备作为工作区的项目目录中运行:
```bash theme={null}
dsh web --port 3080
```
浏览器打开:
```text theme={null}
http://127.0.0.1:3080
```
首次进入时选择或添加工作区,Harness 才能在该目录中运行 Agent 请求。
## 如何配置 AIHubMix 提供方?
打开 **Settings > Models > Add a custom provider**,填写以下内容:
| 字段 | 推荐值 | 说明 |
| ------------ | ------------------------- | -------------------------------- |
| Provider ID | `aihubmix` | 小写标识;若已占用,可使用 `aihubmix-gateway` |
| Display name | `AIHubMix` | 模型选择器中显示的名称 |
| Base URL | `https://aihubmix.com/v1` | 必须包含 `/v1` |
| API protocol | `openai-completions` | 使用 OpenAI Chat Completions 兼容协议 |
| API key | 你的 AIHubMix API Key | Harness 将其保存为凭据,不会在设置页回显明文 |
Harness 会在 Base URL 后请求 `/chat/completions`,最终请求地址为:
```text theme={null}
https://aihubmix.com/v1/chat/completions
```
Base URL 中不要填写完整的 `/chat/completions` 路径。
## 添加 auto 或其他模型
填写 Base URL 和 API Key 后,点击 **Fetch available models**。Harness 会请求 `GET https://aihubmix.com/v1/models` 并显示当前可用的模型 ID。
首次验证可只添加 `auto`,显示名称填写 `Auto`。`auto` 是 AIHubMix 的自动模型选择入口,适合先验证连接。
需要使用指定模型时,在获取到的列表中勾选对应模型,或点击 **Add model** 手动填写准确的模型 ID。只有已经加入当前 Provider 模型目录的条目会出现在图形界面的模型选择器中。
点击 **Create provider** 保存配置。
## auto 与指定模型对比
| 选择 | 适用情况 |
| ------- | ---------------------------- |
| `auto` | 首次连通性验证,或希望由 AIHubMix 自动选择模型 |
| 指定模型 ID | 需要固定模型能力、版本或可复现结果 |
两种方式使用相同的 Provider、Base URL 和 API Key。切换模型不需要重新创建提供方。
## 使用环境变量保存 API Key
开发机和 CI 环境可让 Harness 配置引用环境变量。编辑 `$HOME/.dsh/settings.yaml`:
```yaml theme={null}
llm-pi-ai:
providers:
aihubmix:
displayName: AIHubMix
apiKeyEnv: AIHUBMIX_API_KEY
api: openai-completions
baseURL: https://aihubmix.com/v1
models:
- id: auto
name: Auto
contextWindow: 1000000
maxTokens: 32768
agent-default-model:
provider: aihubmix
model: auto
```
启动 Harness 前设置密钥:
```bash theme={null}
export AIHUBMIX_API_KEY='sk-***'
dsh web --port 3080
```
密钥来自启动环境时,设置页会显示只读提示,不会展示真实值。
修改环境变量后需要重启 Harness。
## 选择模型并验证对话
关闭设置窗口,点击输入框右下角的模型选择器,然后选择 **Auto** 或已添加的指定模型。
发送一条最小测试消息:
```text theme={null}
Reply with exactly: AIHubMix connection successful
```
收到预期响应后,说明 Harness、OpenAI Chat Completions 兼容接口和 AIHubMix 的连接正常。
## 运行 headless 测试
无需 Web UI 时,可运行:
```bash theme={null}
export AIHUBMIX_API_KEY='sk-***'
dsh --profile headless \
'Reply with exactly DSH_AIHUBMIX_OK and do not use tools.'
```
成功时会输出 `DSH_AIHUBMIX_OK`。
## 常见问题
### 为什么显示 MISSING\_CREDENTIAL?
Harness 没有从启动环境读取到 `AIHUBMIX_API_KEY`。确认变量已经设置,并从同一个终端启动 Harness:
```bash theme={null}
test -n "$AIHUBMIX_API_KEY" && echo configured
```
### 为什么获取模型返回 401?
检查 API Key 是否有效,以及复制时是否包含空格或换行。模型发现请求使用 Bearer 认证。
### 为什么模型选择器只有 Auto?
模型选择器只显示当前 Provider 模型目录中已经注册的模型。进入 **Settings > Models > AIHubMix > Edit**,使用 **Fetch available models** 添加其他模型,或手动添加准确的模型 ID。
### 为什么出现 UNKNOWN\_MODEL?
当前 Provider 的模型目录中没有该模型 ID。模型 ID 区分大小写,应使用模型发现接口返回的准确值。
### 为什么请求连接超时?
检查 DNS、公司网络和本地代理。如果浏览器使用系统代理而终端没有使用,请为启动 `dsh` 的终端配置 `HTTP_PROXY`、`HTTPS_PROXY` 和 `NODE_USE_ENV_PROXY=1`。
## 安全建议
* 不要把 API Key 写入 Git 仓库、教程截图或共享脚本
* 优先使用 Harness 凭据存储或 `AIHUBMIX_API_KEY` 环境变量
* 排错时不要打印完整 API Key
* CI 中使用平台的 Secret 管理功能注入环境变量
***
更新时间:2026-08-14
# Gemini CLI
Source: https://docs.aihubmix.com/cn/api/Gemini-Cli
用 Aihubmix 为 Gemini CLI 提供强劲动力,享受稳定高效的 Gemini 模型服务。
## 快速配置指引:
### 1️⃣ 全局安装 npm 包
终端运行:
```shell theme={null}
npm install -g @google/gemini-cli
```
确保你的 Node.js 版本 >= 18
更多详细说明可以参考:
1. [官方仓库](https://github.com/google-gemini/gemini-cli)
2. [详细配置](https://github.com/google-gemini/gemini-cli/blob/main/docs/cli/configuration.md)
### 2️⃣ 环境变量配置
在系统环境变量中填入 Aihubmix 密钥和转发地址,密钥可以在 Aihubmix [「Keys」页面](https://aihubmix.com/token) 生成。
比如在 \~/.zshrc 中添加:
```shell theme={null}
export GOOGLE_GEMINI_BASE_URL="https://aihubmix.com/gemini"
export GEMINI_API_KEY="sk-***"
```
对于 Mac 用户,你可以在`用户名`目录通过快捷键 `⌘ + ⇧ + .` 显示隐藏的 .zshrc 文件,用系统的「文本编辑」APP 打开并添加上述内容。
### 3️⃣ 使配置生效
添加配置之后,终端执行 `source ~/.zshrc`,回车即可。
### 4️⃣ 终端启动
终端输入
```shell theme={null}
gemini
```
## 初始化配置
### 选择接入方式
启动之后输入 `/auth`,回车,选择 `Gemini API Key (AI Studio)`
```shell theme={null}
○ Login with Google
● Gemini API Key (AI Studio)
○ vertex AI
```
你可以随时用 `/auth` 命令来切换授权方式。
### 启动成功
完成以上初始化即可正常使用。
## 祝你使用愉快!
更新时间:2026-06-01
# Kilo Code
Source: https://docs.aihubmix.com/cn/api/Kilo-Code
## 插件配置
1. 运行 VS Code,安装 Kilo Code。
2. 点击 `Kilo Code` 插件图标,进入配置页面。
3. 设置 API Provider 为 `AIhubmix` 。
4. 填写 API Key,选择需要使用的模型。
5. 保存信息。
## 切换模型
1. 在模型配置页切换。
2. 在模型对话页面切换。
***
更新时间:2026-06-01
# OpenClaw
Source: https://docs.aihubmix.com/cn/api/OpenClaw
吉祥物是一只小龙虾(lobster),名字里的「Claw」来自此。
OpenClaw 的核心交互界面是**用户已经在使用的即时通讯平台**——把 AI 助手以聊天机器人的形态嵌入 WhatsApp、Telegram、Slack、Discord、飞书、钉钉、企业微信、iMessage、LINE 等 20+ IM,作为一个 7×24 小时在线的私人助理存在。
## 安装
安装前请确保 Node>=22
执行安装指令
```bash theme={null}
npm install -g openclaw@latest
```
安装完成后,后续命令可以在任意目录执行,不需要先切换到 OpenClaw 安装目录。如果终端能识别 `openclaw`,直接复制文档中的命令即可。
```powershell theme={null}
openclaw models status
```
如果 Windows 终端提示找不到 `openclaw`,请把命令开头的 `openclaw` 替换成你的本地可执行文件路径:
```powershell theme={null}
& "你的安装路径\OpenClaw\openclaw.cmd" models status
```
`你的安装路径` 是占位符,请替换为你实际安装 OpenClaw 的上级目录。例如 OpenClaw 位于 `D:\Apps\OpenClaw` 时,应写成 `& "D:\Apps\OpenClaw\openclaw.cmd" models status`。
### 终端配置
打开终端,运行以下指令开始配置
```powershell theme={null}
openclaw onboard
```
选择 `Yes`
选择 `QuickStart`
选择 `Skip for now`
选择 `All providers`
根据需求选择默认模型,可以先选择 `Keep current`(如使用「方法二:手动修改配置文件」,下一步会在配置文件中修改)
根据需求关联个人账户,如无相关需求请选择 `Skip for now`
配置技能,选择 `Yes`
选择 `npm`
根据需求配置技能选择
全部选择 `No`
选择 `Skip for now`
选择 `Hatch in UI`
## 配置 AIHubMix
### 方法一:使用插件快速配置(推荐)
插件开源地址:[aihubmix-auth](https://github.com/akakenle/aihubmix-auth)
安装 AIHubMix 认证插件并重启 Gateway:
```powershell theme={null}
openclaw plugins install @akakenle/aihubmix-auth
openclaw gateway restart
```
执行认证指令,按提示输入你的 AIHubMix API Key。下面这条命令对四个 provider 任选其一执行一次即可——插件通过 `providerAuthAliases` 让同一把 key 同时生效到全部 transport:
```powershell theme={null}
openclaw models auth login --provider aihubmix-openai --method api-key --set-default
```
插件会将模型自动归类为以下分组:
* **aihubmix-openai** — `gpt-*` / `o1-*` / `o3-*` / `o4-*`,`https://aihubmix.com/v1`(`openai-completions`)
* **aihubmix-anthropic** — `claude-*`,`https://aihubmix.com`(`anthropic-messages`)
* **aihubmix-google** — `gemini-*`,`https://aihubmix.com/gemini/v1beta`(`google-generative-ai`)
* **aihubmix-other** — 其他模型,`https://aihubmix.com/v1`(`openai-completions`)
简写 id(如 `claude-sonnet-4-5`)会由插件的 `resolveDynamicModel` hook 自动路由到对应 transport,不需要写完整 `provider/model`。
> 不想走交互式登录:先 `export AIHUBMIX_API_KEY=sk-...` 再 install,插件会把 key 作为 inline `apiKey` 写入 provider 配置(交互式登录则由 SDK 存入 auth-profile)。
配置完成后,跳转到[启动](#启动)步骤即可开始使用。
### 方法二:手动修改配置文件
如果不使用插件,或需要为少量模型固定上下文长度、输入类型等元数据,可以打开 `~/.openclaw/openclaw.json` 文件手动增加配置。使用插件时,优先按方法三的命令行方式选择模型:
```json theme={null}
{
"models": {
"mode": "merge",
"providers": {
"aihubmix-openai": {
"baseUrl": "https://aihubmix.com/v1",
"api": "openai-completions",
"models": [
{
"id": "gpt-4o",
"name": "gpt-4o",
"reasoning": false,
"input": ["text"],
"cost": {
"input": 0,
"output": 0,
"cacheRead": 0,
"cacheWrite": 0
},
"contextWindow": 128000,
"maxTokens": 16384
}
]
},
"aihubmix-anthropic": {
"baseUrl": "https://aihubmix.com",
"api": "anthropic-messages",
"models": [
{
"id": "claude-sonnet-4-5",
"name": "claude-sonnet-4-5",
"reasoning": false,
"input": ["text"],
"cost": {
"input": 0,
"output": 0,
"cacheRead": 0,
"cacheWrite": 0
},
"contextWindow": 200000,
"maxTokens": 64000
}
]
},
"aihubmix-google": {
"baseUrl": "https://aihubmix.com/gemini/v1beta",
"api": "google-generative-ai",
"models": []
},
"aihubmix-other": {
"baseUrl": "https://aihubmix.com/v1",
"api": "openai-completions",
"models": []
}
}
},
"agents": {
"defaults": {
"model": {
"primary": "aihubmix-anthropic/claude-sonnet-4-5"
},
"workspace": "your_workspace_path",
"compaction": {
"mode": "safeguard"
},
"maxConcurrent": 4,
"subagents": {
"maxConcurrent": 8
}
}
}
}
```
### 方法三:使用动态模型命令切换默认模型
AIHubMix OpenClaw 插件支持动态模型路由。只要模型在你的 AIHubMix 账号中可用,就可以按 `provider/model-id` 的格式直接调用;模型可用性以 AIHubMix 控制台和 API 实际返回为准。
常用 provider 选择规则如下:
* `aihubmix-openai`:OpenAI 兼容模型,例如 `gpt-*`、`o1-*`、`o3-*`、`o4-*`
* `aihubmix-anthropic`:Claude 模型,例如 `claude-*`
* `aihubmix-google`:Gemini 模型,例如 `gemini-*`
* `aihubmix-other`:其他通过 OpenAI 兼容接口调用的模型,例如 `glm-5.2`
下面以将 `gpt-5.4` 设置为 OpenClaw 默认模型为例:
```powershell theme={null}
openclaw models set aihubmix-openai/gpt-5.4
```
如果 Windows 终端提示找不到 `openclaw`,使用本地路径写法:
```powershell theme={null}
& "你的安装路径\OpenClaw\openclaw.cmd" models set aihubmix-openai/gpt-5.4
```
查看当前默认模型和认证状态:
```powershell theme={null}
openclaw models status
```
真实调用测试:
```powershell theme={null}
openclaw infer model run --local --json --model aihubmix-openai/gpt-5.4 --prompt "只回复 OK"
```
如果需要调用非 OpenAI / Claude / Gemini 分组的模型,可使用 `aihubmix-other`,例如:
```powershell theme={null}
openclaw infer model run --local --json --model aihubmix-other/glm-5.2 --prompt "只回复 OK"
```
查看 OpenClaw 当前已加载的模型目录:
```powershell theme={null}
openclaw infer model list --json
```
## 启动
```powershell theme={null}
openclaw gateway
```
## 测试
在聊天页面输入 `hello`,如收到回复则说明配置成功。
## 常见问题
### 版本升级
```powershell theme={null}
openclaw plugins update @akakenle/aihubmix-auth
openclaw gateway restart
```
### Gateway 进程被占用
```powershell theme={null}
openclaw gateway stop
openclaw gateway
```
## 相关资源
* 官方仓库:[github.com/openclaw/openclaw](https://github.com/openclaw/openclaw)
* 官方文档:[docs.openclaw.ai](http://docs.openclaw.ai)
* 中文指南:[liyupi/openclaw-guide](https://github.com/liyupi/openclaw-guide)
* 阿里云部署:[help.aliyun.com](http://help.aliyun.com)[ 部署 OpenClaw](https://help.aliyun.com/zh/simple-application-server/use-cases/quickly-deploy-and-use-openclaw)
* NVIDIA NemoClaw 集成:[NVIDIA Technical Blog](https://developer.nvidia.com/blog/build-a-secure-always-on-local-ai-agent-with-nvidia-nemoclaw-and-openclaw/)
***
更新时间:2026-07-03
# OpenCode
Source: https://docs.aihubmix.com/cn/api/Opencode
在 OpenCode 中接入 AIHubMix:安装、登录授权、选择模型、手动配置模型与自定义 Base URL 的完整步骤,覆盖 macOS、Linux 与 Windows。
当前已支持 GPT、Claude、DeepSeek、Gemini、Qwen 等主流模型系列。在 OpenCode 使用场景中,推荐以下模型:
* `coding-minimax-m2.1-free`
* `coding-glm-4.7-free`
* `claude-sonnet-4-5`
* `gpt-5`
* `gpt-5-codex`
本文档将介绍如何在不同操作系统中安装、配置并启动 OpenCode,并完成对 AIHubMix API的接入。
***
在开始安装前,请确保系统已满足以下要求:
* **Node.js ≥ 18.0.0**
* 对应系统的包管理工具(可选):
* macOS / Linux:`brew`
* Arch Linux:`paru`
* Windows:`choco`、`winget` 或 `scoop`
***
## 一、安装 OpenCode
可根据所使用的系统与工具选择任意一种安装方式。
### 1. 使用 Node.js 安装
```text theme={null}
# 使用 CURL 脚本快速安装
curl -fsSL https://opencode.ai/install | bash
# 使用 NPM
npm install -g opencode-ai
# 使用 Bun
bun install -g opencode-ai
# 使用 PNPM
pnpm install -g opencode-ai
# 使用 Yarn
yarn global add opencode-ai
```
***
### 2. 使用 Homebrew(macOS / Linux)
```text theme={null}
brew install sst/tap/opencode
```
***
### 3. 使用 Paru(Arch Linux)
```text theme={null}
paru -S opencode-bin
```
***
### 4. Windows 安装
Windows 用户可通过以下方式安装 OpenCode:
```text theme={null}
# Chocolatey
choco install opencode
# WinGet
winget install opencode
# Scoop
scoop bucket add extras
scoop install extras/opencode
# 或使用 NPM(需 Node.js 环境)- 注意:需要管理员权限
npm install -g opencode-ai
```
***
## 二、启动与登录 OpenCode
安装完成后,执行以下步骤完成登录与配置。
### 1. 登录 OpenCode
在终端输入以下命令:
```bash theme={null}
opencode auth login
```
***
### 2. 选择模型供应商
在登录界面中选择 **AIHubMix** 作为模型供应商。
***
### 3. API Key 授权
输入 AiHubMix API Key 并在 OpenCode 登录页面中输入该密钥以完成授权。
***
## 三、模型使用
### 1. 安装验证
可通过以下命令验证 OpenCode 是否安装并配置成功:
```text theme={null}
opencode
```
### 2. 选择模型
输入 `/models`,搜索 `aihubmix`,选择需要的模型。
***
## 四、在 OpenCode 客户端使用
1. 下载 OpenCode 桌面端:[https://opencode.ai/download](https://opencode.ai/download)。
2. 打开 OpenCode,输入 `/model` → `Connect provider` → 搜索 `aihubmix` → 输入 API Key → `Submit`。
3. 在模型选择栏搜索 `aihubmix`,选择需要使用的模型即可使用。
## 五、手动配置更新模型
以添加 **DeepSeek V4 Pro** 为例。
### 第一步:确认模型 ID
在 [AIHubMix](https://aihubmix.com/models) 模型界面找到目标模型,复制 ID。
也可以通过 API 直接查询:
```bash theme={null}
curl https://aihubmix.com/v1/models \
-H "Authorization: Bearer YOUR_API_KEY" \
| python3 -m json.tool | grep "id"
```
### 第二步:打开配置文件
根据你的系统,在终端运行对应命令:
**Mac**
```bash theme={null}
mkdir -p ~/.config/opencode && open -a TextEdit ~/.config/opencode/opencode.json
```
**Linux**
```bash theme={null}
mkdir -p ~/.config/opencode && nano ~/.config/opencode/opencode.json
```
**Windows**(在 PowerShell 中运行)
```powershell theme={null}
New-Item -ItemType Directory -Force "$env:USERPROFILE\.config\opencode"
notepad "$env:USERPROFILE\.config\opencode\opencode.json"
```
文件打开后,你会看到一个空文件或已有的 JSON 内容。
### 第三步:写入配置
**如果是空文件**,直接粘贴以下内容:
```json theme={null}
{
"$schema": "https://opencode.ai/config.json",
"provider": {
"aihubmix": {
"models": {
"deepseek-v4-pro": {
"name": "DeepSeek-V4-Pro",
"contextLength": 131072,
"type": "language"
}
}
}
}
}
```
**如果文件已有内容**,只需在 `"models"` 里追加新模型,每个模型之间用逗号隔开:
```json theme={null}
"models": {
"deepseek-v4-pro": {
"name": "DeepSeek-V4-Pro",
"contextLength": 131072,
"type": "language"
},
"deepseek-v4-flash-think": {
"name": "DeepSeek-V4-Flash-Think",
"contextLength": 131072,
"type": "language"
}
}
```
> **注意**:最后一个模型后面不加逗号,否则文件格式会出错。
保存文件:Mac 按 `Command + S`,Windows 按 `Ctrl + S`。
**字段说明:**
| 字段 | 说明 |
| --------------- | ----------------------- |
| `name` | 模型ID |
| `contextLength` | 上下文长度(token数) |
| `type` | 模型类型,文本对话填 `"language"` |
### 第四步:重启 OpenCode
保存配置文件后,**完全退出 OpenCode 并重新启动**,新模型才会加载。
### 第五步:验证
打开模型选择(默认快捷键 `;`),搜索 `V4` 或 `DeepSeek`,确认 `DeepSeek-V4-Pro` 已出现在列表中。
## 六、自定义 Base URL
默认情况下,OpenCode 会把 AIHubMix 的请求发往 `https://aihubmix.com/v1`。如果你需要让请求走自建网关、企业代理或加速节点,可以在配置文件中通过 `options.baseURL` 覆盖,**无需修改 OpenCode 源码或重新安装**。
### 第一步:打开配置文件
按「五、手动配置更新模型」中的方式打开 `~/.config/opencode/opencode.json`(Windows 为 `%USERPROFILE%\.config\opencode\opencode.json`)。
### 第二步:添加 `options.baseURL`
在 `aihubmix` 这个 provider 下增加 `options.baseURL`。只需写这一个字段,OpenCode 会自动与内置配置深度合并,不必重写整份 provider:
```json theme={null}
{
"$schema": "https://opencode.ai/config.json",
"provider": {
"aihubmix": {
"options": {
"baseURL": "https://api.inferera.com"
}
}
}
}
```
> **注意**:`baseURL` 只需填到域名级(如 `https://api.inferera.com`),`/v1`、`/chat/completions` 等路径会由 SDK 自动拼接。请不要自己再加 `/v1`(如 `https://api.inferera.com/v1`),否则会被拼成 `/v1/v1/` 导致 404。
### 第三步:重启并验证
完全退出 OpenCode 后重新启动。可运行以下命令确认配置已生效:
```bash theme={null}
opencode debug config
```
在输出的 `provider.aihubmix.options.baseURL` 中应能看到你填入的地址;之后任意一次模型请求都会发往该地址。
**字段说明:**
| 字段 | 说明 |
| ----------------- | -------------------------------- |
| `options.baseURL` | 自定义请求地址,优先级高于默认地址;填到域名级即可,路径自动拼接 |
## 七、常见问题与提示
* 若 API Key 无法通过验证,请重新登录 [AIHubMix](https://console.aihubmix.com/token) 并检查密钥有效性。
* 查看帮助文档:`opencode` → `/help`。
* OpenCode 官方文档:[https://opencode.ai/docs/](https://opencode.ai/docs/)。
最新更新日期:2026-07-29
# Qwen Code
Source: https://docs.aihubmix.com/cn/api/Qwen-code
## 快速配置指引:
### 1️⃣ 全局安装 npm 包
确保你的 Node.js 版本 >= 20,然后终端运行:
```shell theme={null}
npm install -g @qwen-code/qwen-code
qwen --version
```
更多详细说明可以参考[官方仓库](https://github.com/QwenLM/qwen-code)
### 2️⃣ 环境变量配置
在系统环境变量中填入 Aihubmix 密钥和转发地址,密钥可以在 Aihubmix [「Keys」页面](https://aihubmix.com/token) 生成。
比如在 \~/.zshrc 中添加:
```shell theme={null}
export OPENAI_API_KEY="your_aihubmix_key"
export OPENAI_BASE_URL="https://aihubmix.com/v1"
export OPENAI_MODEL="your_model"
```
对于 Mac 用户,你可以在`用户名`目录通过快捷键 `⌘ + ⇧ + .` 显示隐藏的 .zshrc 文件,用系统的「文本编辑」APP 打开并添加上述内容。
### 3️⃣ 使配置生效
添加配置之后,终端执行 `source ~/.zshrc`,回车即可。
### 4️⃣ 启动并使用
终端输入
```shell theme={null}
qwen
```
启动之后输入 `/about` 确认配置,回车,可以看到当前的版本信息和选择的大模型:
有网友反馈 Qwen Code 存在一定的卡壳概率,我们推荐为[密钥 ↗](https://aihubmix.com/token)设置**有限额度**来规避不必要的浪费
## 接下来正常使用即可。
更新时间:2026-06-01
# CC Switch 配置指南
Source: https://docs.aihubmix.com/cn/api/cc-switch
CC Switch 是开源跨平台桌面 GUI 工具,统一管理 Claude Code、Codex、Gemini CLI、OpenCode、OpenClaw 的 AIHubMix Provider 配置、API key 切换、MCP 服务器与用量统计,支持 Windows/macOS/Linux 全平台。
> CC Switch 是一款免费的桌面应用,专门用于管理和切换不同 AI 编程工具的接入配置。配合 AIHubMix 使用后,你可以在 Claude Code、Codex、Gemini CLI、OpenCode、OpenClaw 等主流 AI 编程工具之间快速切换,无需反复手动修改配置文件、环境变量或接口设置。对于同时使用多个模型、多个 CLI 工作流的开发者来说,CC Switch 可以明显降低配置成本,让不同工具的接入、切换和日常使用更加统一、高效。
## 一、CC Switch 是什么?
**CC Switch**(项目地址:[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch))是由开发者 **Jason Young(farion1231)** 开发的一款开源跨平台桌面应用,专为 AI 编程 CLI 工具设计的统一管理器。
对于同时使用多个 AI 编程工具的用户特别是开发者而言,以下问题或许并不陌生:
* 每次切换 Provider,都需要手动编辑 `~/.claude/settings.json` 或重新设置环境变量
* 多台设备之间配置无法同步,换一台机器就要从头配置
* WSL 与 Windows 环境各自维护一套配置,管理成本持续叠加
CC Switch 正是为解决上述问题而设计。它是一款轻量的桌面应用,安装后常驻在系统托盘,无论你是开发者还是普通用户,只需点击几下,就能完成 AI 工具和服务商的切换,全程不需要接触任何代码或配置文件。基于 **Tauri 2 + Rust** 构建,安装包体积轻巧,支持 Windows、macOS 与 Linux 全平台,并提供系统托盘常驻入口,让多 Provider 的切换与管理变得高效、直观。
**支持的 5 大 CLI 工具:**
> CLI(Command Line Interface,命令行界面)工具是一类通过文字命令操作的程序,不需要图形界面,常用于开发环境。下表中的工具都属于此类,CC Switch 可以统一管理它们的配置。
| 工具名称 | 开发方 | 简介 |
| ----------- | --------- | ------------------------------------------ |
| Claude Code | Anthropic | 由 Claude 模型驱动的 AI 编程助手,可在终端中直接对话、写代码、改 Bug |
| Codex | OpenAI | OpenAI 推出的代码生成工具,支持多种编程语言的自动补全与生成 |
| Gemini CLI | Google | Google Gemini 模型的命令行版本,适合与 Google 生态集成的开发者 |
| OpenCode | 开源社区 | 开源的 AI 编程命令行工具,支持接入多种 AI 模型 |
| OpenClaw | 开源社区 | 开源的 AI 命令行工具,可灵活切换不同的 AI 服务商(Provider) |
***
## 二、CC Switch 有哪些核心功能?
### 2.1 Provider 管理
CC Switch 内置 **50+ 预设配置**,覆盖主流 AI API 服务商,包括 Anthropic、OpenRouter、AIHubMix、AWS Bedrock 等。你可以:
* 为每个 CLI 工具创建多个 Provider 配置
* 拖拽排序,把最常用的置顶
* 一键切换当前激活的 Provider,无需重启 CLI
* 通过 **Shared Config Snippet** (共享配置)功能,切换服务商时自动保留插件数据与自定义设置——换了 API 不等于一切归零
### 2.2 MCP 服务器统一管理
如果你在多个 CLI 工具中都用到了 MCP(Model Context Protocol)服务器,CC Switch 提供统一的 MCP 管理面板,支持跨应用配置同步,不用在每个工具的配置文件里重复填写。
### 2.3 技能(Skills)安装
CC Switch 支持从 GitHub 仓库或 ZIP 文件安装技能包(Skills),通过 symlink 方式挂载,方便团队共享和版本管理。
### 2.4 用量统计 Dashboard
内置使用量看板,可追踪:
* 每日/每周 API 消费金额
* 请求次数与 Token 用量
* 趋势图可视化
对于同时接入多个 Provider 的用户,这个功能能帮你清楚掌握每个渠道的实际消耗。
### 2.5 云同步
配置数据支持同步到以下云存储:
* Dropbox
* OneDrive
* iCloud(macOS)
* WebDAV 自建服务器
多设备开发者再也不用手动导出导入配置了。
***
## 三、CC Switch 如何安装到 Windows / macOS / Linux?
### 3.1 Windows
**方式一:Winget(推荐)**
```bash theme={null}
winget install --id=farion1231.CC-Switch -e
```
**方式二:手动安装**
前往 [GitHub Releases 页面](https://github.com/farion1231/cc-switch/releases) 下载最新版 `.msi` 安装包或便携版 `.zip`,解压后直接运行。
**系统要求:** Windows 10 及以上
### 3.2 macOS
**方式一:Homebrew(推荐)**
```bash theme={null}
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
**方式二:手动安装**
从 Releases 页面下载已公证的 `.dmg` 文件,挂载后拖入 Applications 文件夹即可。
**系统要求:** macOS 12(Monterey)及以上
### 3.3 Linux
根据你的发行版选择对应包格式:
```bash theme={null}
# Debian / Ubuntu
sudo dpkg -i cc-switch_x.x.x_amd64.deb
# Fedora / RHEL
sudo rpm -i cc-switch-x.x.x.x86_64.rpm
# 通用(AppImage)
chmod +x cc-switch_x.x.x_amd64.AppImage
./cc-switch_x.x.x_amd64.AppImage
# Arch Linux(AUR)
paru -S cc-switch-bin
```
**系统要求:** Ubuntu 22.04+ / Debian 11+ / Fedora 34+
### 3.4 WSL 集成((Windows 用户)
CC Switch 对 WSL(Windows Subsystem for Linux)有专项支持。在 Windows 主机上安装 CC Switch 后,可以直接管理 WSL 内的 Claude Code 等 CLI 工具的配置,无需在 WSL 环境内单独安装。
配置完成后,CC Switch 会通过本地代理桥接 WSL 与 Windows 之间的网络请求,实现统一管理。
***
## 四、Claude Code 如何通过 CC Switch 接入 AIHubMix?
### 为什么选择[ AIHubMix](https://docs.aihubmix.com/en)?
AIHubMix 由美国 AIHubMix, LLC 主体运营,是获得微软 Azure、AWS、GCP 、阿里云、百度云等各大模型推理云厂商官方授权的合规模型聚合平台。我们所有服务全部集群化部署云美国谷歌云上,长期为众多知名应用提供高并发、稳定、可信赖的 AI 模型 API 服务,深受开发者和企业信任。
对于 Claude Code 用户来说,通过 AIHubMix 接入可以有效降低使用成本,同时保持与 OpenRouter 类似的灵活性。
### 4.1 在 CC Switch 中添加 AIHubMix Provider
打开 CC Switch,进入 **Claude Code** 的 Provider 供应商管理页面:
1. 点击右上角「**+ 添加供应商**」
2. 在预设列表中选择「AiHubMix」,点击获取API key 跳转链接
3. 在「API Key」栏中填写你的密钥
4. 配置完成后,复制想要选择的模型ID(以claude-opus-4-7 为例),点击「添加」保存设置。
5. 返回首页,在供应商列表中选择「AiHubMix」,点击「启动」即可使用。
### 4.2 验证连接
在终端中运行 Claude Code,发起一次简单的对话请求,如果响应正常,说明已成功接入 AIHubMix。
终端打开 Claude Code后,输入 /status 可查询模型ID,输入/models 可选择配置的其他模型
## 五、如何在 VSCode 中使用 CC Switch?
Claude Code 有官方 VSCode 扩展,CC Switch 与其完全兼容。配置步骤如下:
### 5.1 安装 Claude Code VSCode 扩展
在 VSCode 扩展市场搜索「**Claude Code**」并安装。
### 5.2 配合 CC Switch 使用
### 5.3 多工作区场景
如果你同时打开了多个 VSCode 工作区,所有窗口共享同一个 CC Switch 配置,切换一次全局生效。
***
## 六、其他 CLI 工具➕AIHubMix 教程
CC Switch 不只是 Claude Code 的管理器,它对另外四个主流 AI 编程 CLI 工具同样有完整支持。
### 6.1 Codex➕AIHubMix
OpenAI Codex CLI 用户可以在 CC Switch 中单独管理 Codex 的 Provider 配置,接入AIHubMix。Codex的完整教程见
[**https://docs.aihubmix.com/cn/api/Codex-CLI**](https://docs.aihubmix.com/cn/api/Codex-CLI)
以接入 deepseek-v4-flash 为例🌰,通过在 CC Switch 中简单配置AIHubMix API key,即可在codex中使用 deepseek-v4-flash 以及其他模型
### 6.2 Gemini➕ AiHubMix
Google Gemini CLI 配置较为分散,CC Switch 将其整合进统一界面,支持多 Google 账号或多个 Gemini API Key 的快速切换,适合需要频繁在不同项目间切换的团队。
### 安装 Gemini CLI
确保 Node.js 版本 ≥ 18,没有则先安装:
```text theme={null}
brew install node
```
然后全局安装 Gemini CLI:
```text theme={null}
npm install -g @google/gemini-cli
```
### 配置步骤
1. 打开 CCSwitch,点击 **添加供应商**
2. 手动添加 **AiHubMix**
3. 填入 **API 密钥**:你的 `sk-` 开头密钥(在 [aihubmix.com/token](https://aihubmix.com/token) 获取)
4. 填入**请求地址**:`https://aihubmix.com/gemini`
### 6.3 OpenCode➕AiHubMix
OpenCode 是一个开源的 AI 编程 CLI,兼容多种 Provider。CC Switch 内置对 OpenCode 的支持,可以直接管理其配置文件,免去手动编辑 TOML/JSON 配置的麻烦。
完整安装教程见 [https://docs.aihubmix.com/cn/api/Opencode](https://docs.aihubmix.com/cn/api/Opencode)
### 配置步骤
1. 打开 CCSwitch,点击 **添加供应商**
2. 选择 **AiHubMix**
3. 填入 **API 密钥**:你的 `sk-` 开头密钥(在 [aihubmix.com/token](https://aihubmix.com/token) 获取)
在终端运行:
```text theme={null}
opencode
```
### 6.4 OpenClaw➕AiHubMix
OpenClaw 是兼容 OpenAI 接口的开源 CLI 工具,适合需要自定义模型路由的高级用户。具体安装教程见 [https://docs.aihubmix.com/cn/api/OpenClaw](https://docs.aihubmix.com/cn/api/OpenClaw)
### CC Switch 与 OpenClaw 的搭配使用方式:
1. 在 CC Switch 中为 OpenClaw 创建独立的 Provider 组
2. 将 AIHubMix、OpenRouter 等聚合平台配置为 OpenClaw 的上游
3. 通过 CC Switch 的热切换功能,在不同的 OpenClaw 上游之间快速跳转
特别适合需要对比不同 API 服务商响应质量的开发者——在 CC Switch 中切换 Provider,OpenClaw 侧无需做任何修改。
***
## 七、CC Switch vs Claude Code Router 对比
市面上另一个常被提到的工具是 **Claude Code Router**,不少用户会问:我该用哪个?
| 对比维度 | CC Switch | Claude Code Router |
| ----------- | ----------------------------------------------- | ------------------ |
| 形态 | 桌面 GUI 应用 | CLI / 配置工具 |
| 支持的 CLI 工具 | 5 个(Claude Code、Codex、Gemini、OpenCode、OpenClaw) | 主要针对 Claude Code |
| Provider 预设 | 50+ | 依赖手动配置 |
| 本地代理 | 内置,支持热切换 + 故障转移 | 需手动配置 |
| MCP 管理 | 统一管理界面 | 不支持 |
| WSL 支持 | 专项支持 | 有限支持 |
| 云同步 | 支持(Dropbox / iCloud / WebDAV) | 不支持 |
| 用量统计 | 内置 Dashboard | 无 |
| 上手难度 | 低(GUI 操作) | 中(需熟悉配置文件) |
| 适合人群 | 多工具用户 / 追求效率者 | 轻量配置需求 / 纯 CLI 爱好者 |
**结论:** 如果你只用 Claude Code 且习惯命令行操作,Claude Code Router 足够用;如果你同时使用多个 AI 编程工具,或者希望有一个可视化的统一管理入口,CC Switch 是更好的选择。
***
## 八、常见问题 FAQ
**Q:CC Switch 本身免费吗?**
A:完全免费,MIT 开源协议,[代码托管在 GitHub](https://github.com/farion1231/cc-switch)。使用过程中产生的 API 费用由你选择的 Provider 决定。
**Q:在 WSL 中如何让 CC Switch 生效?**
A:CC Switch 安装在 Windows 侧,通过本地代理桥接 WSL 内的请求。确保 WSL 的代理设置指向 CC Switch 的本地监听端口即可。具体端口号可在 CC Switch 的代理设置页面查看。
**Q:切换 Provider 后 Claude Code 需要重启吗?**
A:不需要。CC Switch 的热切换功能在激活新 Provider 后立即生效,当前终端会话无需重启。
**Q:配置数据存储在哪里?**
A:本地数据库存储在 `~/.cc-switch/cc-switch.db`,设置文件为 `~/.cc-switch/settings.json`,CC Switch 会自动保留最近 10 个备份版本。
**Q:我可以通过 URL 导入别人的 Provider 配置吗?**
A:可以。CC Switch 支持 Deep Link(`ccswitch://` 协议),团队成员可以通过分享一个链接快速导入统一的 Provider 配置,适合团队统一管理 API 接入。
**Q:CC Switch 支持 AWS Bedrock 吗?**
A:支持,内置 AWS Bedrock 预设,并支持跨区域推断(Cross-Region Inference),适合企业用户通过 Bedrock 接入 Claude 模型。
***
## 结语
CC Switch 把原本分散在各个配置文件里的 AI 编程工具管理工作,整合进了一个轻量的桌面应用。无论你是 Claude Code 的重度用户,还是同时使用 Codex、Gemini CLI 的多工具开发者,它都能让你的工作流更顺畅。
最新版本 **v3.12.0** 已稳定发布,欢迎前往 [github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch) 查看完整文档和 Release Notes。
更新时间:2026年4月28日
# Claude Desktop
Source: https://docs.aihubmix.com/cn/api/claude-desktop
在 Claude Desktop 中接入 AIHubMix:无需 Anthropic 账号登录,全程点击操作即可驱动客户端,通过单个 API key 统一调用 Claude、GPT、Gemini、DeepSeek 等多系列模型,按量计费、灵活可控。
> 适用版本:Claude Desktop 1.3883.0(更新时间:2026 年 4 月 23日)\
> 难度:新手向,无需命令行,全程点击操作,无需 Anthropic 账号登陆
## 简介
\
**Claude Desktop**(企业版称 Claude Cowork)支持接入第三方 LLM 网关,无需 Anthropic 账号订阅,即可驱动客户端。
本指南教你将 AIHubMix 配置为 Claude Desktop 的API 服务商,实现:
* 无需 Anthropic 账号登陆,解决手机号/邮箱难登陆的问题
* 通过 AIHubMix 使用 Claude、GPT、Gemini、DeepSeek 等多系列模型
* 按量计费,灵活可控
***
## 准备工作
在开始之前,请确认以下条件:
* **操作系统:** macOS 13.0 (Ventura) 及以上,或 Windows 10 / 11
* **AIHubMix 账号:** 在 [aihubmix.com](https://aihubmix.com) 注册并充值
***
## 第一步:获取 AIHubMix API Key
1. 访问 [aihubmix.com](https://aihubmix.com) 并登录账号
2. 进入控制台 → **API Keys** 页面
3. 点击 **创建新 Key**,填写名称(如 `claude-desktop`)
4. 复制生成的 Key(格式:`sk-xxxxxxxxxxxxxxxx`)
> **安全提示:** API Key 只显示一次,请立即保存到安全的地方。
***
## 第二步:下载并安装 Claude Desktop
1. 访问官方下载页 [claude.ai/download](https://claude.ai/download)
2. 根据系统下载对应安装包
**macOS:**
* 打开下载的 `.dmg` 文件
* 将 `Claude.app` 拖入 `Applications(应用程序)` 文件夹
* 从启动台或 Applications 打开 Claude
**Windows:**
* 运行下载的 `.msix` 安装包
* 按屏幕提示完成安装
* 从开始菜单打开 Claude
> **注意: 打开后无需登录 Anthropic 账号,直接进行下一步配置。**
***
## 第三步:启用开发者模式
第三方配置需要先开启开发者模式:
1. 打开 Claude Desktop 应用
2. 点击顶部菜单栏 **Help(帮助)**
3. 选择 **Troubleshooting(故障排查)**
4. 点击 **Enable Developer mode(启用开发者模式)**
5. 启用后,顶部菜单栏会出现新的 **Developer(开发者)** 菜单。
6. 点击菜单栏 **Developer(开发者)**,选择 **Configure third-party inference(接入第三方服务)**
7. **在弹出的配置界面中填写以下内容:**
**Connection** — Gateway(Anthropic-compatible)
**Gateway Base URL** — AIHubMix 服务地址
```text theme={null}
https://aihubmix.com
```
**Gateway API Key** — 你的 AIHubMix API Key
```text theme={null}
sk-xxxxxxxxxxxxxxxx
```
8. **点击 Apply locally (本地应用)-Relaunch (重启)**
9. 重启后,进入下图界面,选择 **Continue with Gateway**
***
## 第四步:配置模型并验证
Gateway 模式下,Claude Desktop 会按 Claude 风格约束模型名——**模型名必须以 `claude-` 开头**,所以不能直接填 `gpt`、`gemini`、`deepseek` 等真实模型名,否则下拉框里没有可用模型。解决办法是用**模型名映射**:客户端填 `claude-` 前缀的别名,再在 AIHubMix Key 里把别名映射到真实模型。
**① 在 AIHubMix Key 里配置映射**
进入 [AIHubMix Key 管理页](https://console.aihubmix.com/token),创建 / 编辑 Key,在 `Model name mapping` 区块添加「别名 → 真实模型」:
```text theme={null}
claude-g-p-t-5.5 -> gpt-5.5
claude-gemi-3.1 -> gemini-3.1-pro-preview
claude-depsek-v4 -> deepseek-v4-flash
```
**② 在 Claude Desktop 的 Model list 里填别名**
这里填的是映射前的 `claude-` 别名——也就是 Claude Desktop 发给 AIHubMix 的模型名,不是真实上游模型名:
配置完成后,这些别名就会出现在 Claude Desktop 的模型下拉框里供选择:
命名建议:
* `Model ID` 使用 `claude-` 前缀。
* 不要直接写 `gpt`、`gemini`、`deepseek` 等真实模型系列名,可使用 `g-p-t`、`gemi`、`depsek` 等别名。
* `Model ID` 必须和 AIHubMix 映射左侧**逐字符一致**,否则请求不会命中预期映射。
> 主模型失败时自动切换备用模型、按最终响应模型计费等更多用法,见 [模型映射与回退](https://docs.aihubmix.com/cn/api/Model-Mapping-Fallback)。
> **注意:默认模型为 Claude Opus 4.7,该模型定价较高**,日常使用成本显著。建议改用其他模型;AIHubMix 提供多款高性价比乃至免费的模型,可在 [aihubmix.com](https://aihubmix.com/models) 查看模型详细参数。
配置完成后,重启 Claude Desktop 验证是否生效:
* 左侧导航栏出现 **Cowork** 标签
* 可以正常发送消息并收到 Claude 的回复
* 右下角显示你配置的模型名称
恭喜!你已经可以通过 AIHubMix 使用自己配置的模型了。
***
## 常见问题排查
### 启动时报错 / 无法连接
**检查清单:**
1. 确认 `inferenceProvider` 填写的是 `gateway`(不是 `bedrock` / `vertex`)
2. 检查 Base URL 是否为 `https://aihubmix.com`(无尾部斜杠)
3. 核对 API Key 是否完整复制(`sk-` 开头)
4. 确认 AIHubMix 账号有余额
**查看日志:**
* macOS:打开「控制台(Console.app)」,筛选 `Claude`
* Windows:打开「事件查看器(Event Viewer)」
***
### 模型无法调用 / 报错 model not found
确认填写的模型 ID 在 AIHubMix 中可用。你可以通过 API 查询可用模型列表:
```bash theme={null}
curl https://aihubmix.com/v1/models \
-H "Authorization: Bearer sk-你的API Key"
```
***
### Auth Scheme 应该选哪个?
AIHubMix 使用 `x-api-key` 认证头,选择 `x-api-key` 即可。如果遇到 401 错误,可尝试切换为 `bearer`。
***
## 高级:导出配置文件(可选)
配置完成后,可以导出配置文件方便备份或分发给团队:
**macOS** — 在配置 UI 中点击 **Export** 下载 `.mobileconfig` 文件\
**Windows** — 在配置 UI 中点击 **Export** 下载 `.reg` 注册表文件
## 相关资源
* [AIHubMix 官方文档](https://docs.aihubmix.com)
* [AIHubMix Claude 原生接口说明](https://docs.aihubmix.com/cn/api/Claude-Native.md)
* [Claude Desktop 官方第三方平台配置指南](https://support.anthropic.com/en/articles/claude-cowork-with-third-party-platforms)
* [Claude Desktop 下载页](https://claude.ai/download)
***
*最后更新:2026 年 4 月 23日 | 基于 Anthropic 官方文档 + AIHubMix API 文档整理*
# Hermes Agent
Source: https://docs.aihubmix.com/cn/api/hermes-agent-ai-hubmix
Hermes Agent 是 Nous Research 推出的开源 self-improving AI 智能体,它会自主学习、持续进化,并拥有持久记忆系统。
# 快速开始
## Step 1: 安装 Hermes
打开终端,执行以下命令:
### Linux / macOS / WSL2
```text theme={null}
curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash
```
### Android / Termux
```text theme={null}
curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash
```
> **不支持**原生 Windows 系统,请安装[WSL2](https://learn.microsoft.com/en-us/windows/wsl/install)并从 WSL2 中运行 Hermes Agent。
## Step2:选择供应商
安装成功后,选择 Quick setup -> More providers -> Custom endpoint。
## Step3:配置 AIHubMix 参数
1. 输入 API base URL :`https://aihubmix.com/v1`。
2. 输入 [AIHUBMIX\_API\_KEY](https://console.aihubmix.com/token):sk-\*\*\*。
3. 输入模型编号,选择需要使用的模型。
## Step 4:设置消息平台
按需设置消息平台(使用 Skip 作为参考)-> 是否需要运行(选择 Y)
## Step 5:运行测试
1. 在终端输入 `hermes`,进入 Hermes Agent 交互页面。
2. 在对话框中输入内容,若模型正常响应,则代表安装成功。
# 使用官方插件接入
上面的 Custom endpoint 方式需要每次手动填写 base URL 和模型编号。AIHubMix 提供了官方的 model provider(模型供应商)插件,安装后 AIHubMix 会作为 `aihubmix` 供应商注册进 Hermes,可直接用 `--provider aihubmix` 调用,模型列表由 AIHubMix 的模型目录接口自动填充。插件不改动 Hermes 任何核心文件。
源码与完整说明:[AIhubmix/hermes-provider-aihubmix](https://github.com/AIhubmix/hermes-provider-aihubmix)
## 安装
将插件目录复制到 Hermes 的 model provider 目录:
```bash theme={null}
git clone https://github.com/AIhubmix/hermes-provider-aihubmix.git
mkdir -p ~/.hermes/plugins/model-providers
cp -r hermes-provider-aihubmix/aihubmix ~/.hermes/plugins/model-providers/aihubmix
```
Hermes 会在下次会话首次查询供应商时扫描该目录,无需重启,无需改动配置文件。
也可以通过 pip 安装:
```bash theme={null}
pip install git+https://github.com/AIhubmix/hermes-provider-aihubmix.git
hermes plugins enable aihubmix
```
通过 pip 入口点(entry point,Python 包对外声明的插件注册位)安装的插件默认不加载,需要执行 `hermes plugins enable aihubmix` 写入 `plugins.enabled` 后才生效。
`hermes plugins install AIhubmix/hermes-provider-aihubmix` 对本插件无效。该命令会把插件装到 `~/.hermes/plugins/<仓库名>/`,并提示仓库根目录没有 `plugin.yaml`,而 model provider 仅从 `~/.hermes/plugins/model-providers/` 发现,插件不会注册。插件清单 `aihubmix/plugin.yaml` 中声明了 `kind: model-provider`,但该命令在选择安装目录时不读这个字段。请使用上面两种方式之一。该行为已在 Hermes 0.20.5 上验证。
## 配置密钥
```bash theme={null}
export AIHUBMIX_API_KEY="sk-***"
```
在 [API Key 页面](https://console.aihubmix.com/token)获取。`hermes setup` 会读取该环境变量,`hermes doctor` 会用它探测模型目录接口的连通性。
## 使用
```bash theme={null}
hermes --provider aihubmix --model gpt-5.6-sol
```
也可以在选择 AIHubMix 后用 `/model` 交互式选择模型。
模型列表取自 AIHubMix 的模型目录接口,只列出标注了 `tools` 或 `function_calling` 的条目,两个标记满足其一即可。该接口不可用时,插件回退到通用的 `/v1/models` 列表;再不可用时使用内置的少量兜底模型列表。
设置 `AIHUBMIX_BASE_URL` 可指向代理或自建中转地址。当该值与默认地址不同时,插件改用通用的 `{base_url}/models` 路径获取模型列表。
# 常用指令
代码块
```text theme={null}
hermes model # 选择模型供应商
hermes tools # 配置要启动的工具
hermes gateway setup # 设置消息平台
hermes config set # 设置各个配置参数
hermes setup # 运行完整设置向导,一次性配置所有内容
```
# 常见问题
## `hermes plugins install` 装完为什么用不了?
该命令会把插件装到 `~/.hermes/plugins/<仓库名>/`,而 Hermes 的 model provider 仅从 `~/.hermes/plugins/model-providers/` 发现,插件因此不会注册。插件清单 `aihubmix/plugin.yaml` 中声明了 `kind: model-provider`,但该命令在选择安装目录时不读这个字段,所以安装本身会显示成功。请改用[上文的目录复制方式](#provider-plugin-install),或用 pip 安装后执行 `hermes plugins enable aihubmix`。
## 插件方式与 Custom endpoint 有什么区别?
Custom endpoint 需要手动填写 base URL 和模型编号。插件会把 AIHubMix 注册为具名供应商 `aihubmix`,支持 `--provider aihubmix` 直接调用,模型列表由 AIHubMix 的模型目录接口自动填充,并过滤为支持工具调用的模型。
## `/model` 里模型列表为空或偏少怎么办?
先确认 `AIHUBMIX_API_KEY` 已设置且有效,可用 `hermes doctor` 检查。列表只包含标注了 `tools` 或 `function_calling` 的模型,因此会少于全量模型数。若设置了 `AIHUBMIX_BASE_URL` 且与默认地址不同,插件改用 `{base_url}/models` 获取列表。
***
更新时间:2026-08-25
# Claude Opus 4.7 新参数指南
Source: https://docs.aihubmix.com/cn/blogs/Claude-Opus4.7
Claude Opus 4.7 推理控制实操指南:新增 xhigh 档位、思考内容默认隐藏,附 AIHubMix 原生 API 与 Chat 统一接口的完整调用示例。
> 本文介绍 [Claude Opus 4.7](https://aihubmix.com/model/claude-opus-4-7) 在推理控制上的两项关键变化,并给出 **AIHubmix** 原生 API 与 **Chat** 统一接口两种用法的完整说明。延伸阅读:[Anthropic 官方公告](https://www.anthropic.com/news/claude-opus-4-7) 与 [模型更新日志](https://platform.claude.com/docs/en/about-claude/models/whats-new-claude-4-7)。
## 1. Opus 4.7 新增了哪些推理控制能力?
### ✦ 新增 `xhigh` 推理强度档位
新增的 `xhigh` 档位介于 `high` 与 `max` 之间,专为**编码与 Agent 类任务**设计,在能力与效率之间取得了更好的平衡。
```text theme={null}
low ── medium ── high ── xhigh ★NEW ── max
```
### ✦ 思考内容默认隐藏
在流式响应中,思考过程**默认不再展示**。若需获取推理摘要,请在请求中显式传入 `display` 字段:
| **display 取值** | **Opus 4.7** | **Opus 4.6** | **行为** |
| :------------- | :----------- | :----------- | :------- |
| "omitted" | **默认** | 非默认 | 思考块内容为空 |
| "summarized" | 需手动设置 | **默认** | 返回思考摘要文本 |
```text theme={null}
"reasoning": {
"effort": "xhigh",
"display": "summarized"
}
```
> **图**:Opus 4.7 新增 xhigh 档位 —— Agent 编码性能对比(来源:Anthropic 官方)
***
## 2. Claude 原生 API 参考
### Anthropic 原生 API 的 `effort` 取值与官方规范保持一致:
| **effort 取值** | **支持的模型** | **说明** | **推荐场景** |
| :------------ | :------------- | :---------------------------- | :----------------: |
| low | 所有支持的模型 | 显著节省 token,能力适度折中 | 简单任务、高并发请求、子 Agent |
| medium | 所有支持的模型 | 均衡模式,适度节省 token | 通用 Agent 任务 |
| high | 所有支持的模型 | 默认值;高能力表现 | 复杂推理、编码、Agent 任务 |
| **xhigh(新增)** | **仅 Opus 4.7** | 介于 high 与 max 之间的增强能力;擅长长周期任务 | 编码与 Agent 任务的推荐起点 |
| max | Opus 系列 | 最高能力 | 前沿研究类难题 |
### **AIHubmix Claude 原生 API —— Opus 4.7 示例**
```text theme={null}
from anthropic import Anthropic
client = Anthropic(
api_key="",
base_url="https://aihubmix.com"
)
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=16000,
thinking={"type": "adaptive"},
output_config={"effort": "xhigh"}, # 可选:low / medium / high / xhigh / max
messages=[
{
"role": "user",
"content": "A snail is at the bottom of a 10-meter well. Each day it climbs 3 meters, but each night it slides back 2 meters. How many days does it take to reach the top?"
}
]
)
print(response.content[-1].text)
```
***
## 3. AIHubmix Chat 统一接口对推理强度的支持
AIHubMix Chat 统一接口对齐 OpenAI 规范,通过 `reasoning.effort` 控制推理强度。**不同的 Claude 模型会自动映射到对应的 effort 档位:**
### Claude 模型的 `reasoning_effort`(推理强度控制)
| **effort 取值** | **Opus >=4.7(新增)** | **Opus 4.6 / 4.5** | **Sonnet 4.6** |
| :------------ | :----------------: | :----------------: | :------------: |
| minimal | low | low | low |
| medium | medium | medium | medium |
| high | high | high | high |
| xhigh | xhigh | max | high |
| max | max | max | high |
**说明**:`xhigh` 仅 Opus 4.7 原生支持。其他 Opus 模型会自动回退到 `max`,Sonnet 系列回退到 `high`。
### **Chat 统一接口 —— Opus 4.7 示例**
```text theme={null}
from openai import OpenAI
client = OpenAI(
base_url="https://aihubmix.com/v1",
api_key="",
)
completion = client.chat.completions.create(
model="claude-opus-4-7",
# max_tokens=10000, # 默认 4096;需要更长输出时开启
messages=[
{
"role": "user",
"content": "A snail is at the bottom of a 10-meter well. Each day it climbs 3 meters, but each night it slides back 2 meters. How many days does it take to reach the top?"
}
],
extra_body={
"reasoning": {"effort": "xhigh"}
}
)
print(completion.choices[0].message.content)
```
***
## 4. 如何在 Chat 统一接口中控制思考内容?
在 OpenAI 兼容接口中,`reasoning` 支持 `display` 字段,用于控制是否返回思考摘要。
**Claude Opus 4.7 默认不返回思考内容。设置** `"display": "summarized"` **即可开启。**
| 字段 | 取值 | 说明 |
| :-------- | :------------- | :---------- |
| `display` | *(省略)* | 不返回思考内容(默认) |
| `display` | `"summarized"` | 返回思考摘要 |
### **Opus 4.7 —— 思考摘要示例**
```text theme={null}
from openai import OpenAI
client = OpenAI(
base_url="https://aihubmix.com/v1",
api_key="",
)
completion = client.chat.completions.create(
model="claude-opus-4-7",
messages=[
{
"role": "user",
"content": "A snail is at the bottom of a 10-meter well. Each day it climbs 3 meters, but each night it slides back 2 meters. How many days does it take to reach the top?"
}
],
extra_body={
"reasoning": {"effort": "xhigh", "display": "summarized"}
}
)
print(completion.choices[0].message.content)
```
***
## *更多细节请参阅 [AIHubmix 文档](https://docs.aihubmix.com/cn) 或 [Anthropic 官方文档](https://docs.anthropic.com/)。*
更新时间:2026-06-26
# 2026 年 6 月发布聚焦:近 20 款新模型上线
Source: https://docs.aihubmix.com/cn/blogs/aihubmix-2026-06-recap
2026 年 6 月 AIHubMix 新接入 claude-fable-5【已退役】、glm-5.2、minimax-m3、qwen3.7-plus、kimi-k2.7-code、可灵视频等近 20 款模型,并上线模型智能路由、模型映射与回退、AIHubMix CLI 与备用域名。
本月 AIHubMix 新增近 20 款模型,覆盖对话、代码、视频与图像,并上线多项平台能力。同一把 API Key 可调用的能力进一步扩展。以下是本月重点更新。
## 模型智能路由(LLM Router)
将模型名设为 `auto`,网关即按请求内容从平台数百个模型中自动选择最优模型,支持成本优先、质量优先、低延迟等策略,并按实际命中的模型计费。无需手动比较与切换模型,客户端代码无需改动。详见 [模型智能路由](/cn/api/llm-router)。
## Responses 协议支持任意模型
`/v1/responses` 端点不再限于 GPT 系列,现可调用平台上的任意模型。基于 Responses 协议的工具(如 Codex CLI)因此能通过本地模型目录使用 GLM、Gemini、DeepSeek、Kimi、Qwen 等模型,不再局限于 OpenAI 官方模型。详见 [Codex CLI · 自定义模型](/cn/api/Codex-CLI#custom-models)。
## 模型映射与错误回退(Mapping & Fallback)
在控制台为每个 API Key 配置模型别名映射与失败回退:客户端可自定义模型名,由网关改写为真实上游模型;主模型失败时自动切换至备用模型,并按最终响应的模型计费。可避免单点故障导致线上请求中断,且客户端代码无需改动。详见 [模型映射与回退](/cn/api/Model-Mapping-Fallback)。
## AIHubMix CLI 命令行工具
单一二进制、零依赖,无需安装 Python / Node / Go 即可运行。可在终端直接查询余额、管理 API Key、查看可用模型,并对脚本与 AI Agent(如 Claude Code)友好。详见 [AIHubMix CLI](/cn/api/aihubmix-cli)。
## AIHubMix Skill(AI 编程助手扩展)
为 Codex、Claude Code、Cursor、Cline 等支持 Skills 的 AI Agent 提供本地扩展能力:用自然语言完成 AIHubMix 接入、模型查询、按能力选型、示例生成与错误排查。该 Skill 不内置固定模型清单,而是按需从 AIHubMix 官方接口读取模型、价格、协议契约等实时信息,避免 Agent 依赖过期记忆。详见 [Skills](/cn/skills)。
## 备用域名 api.inferera.com
当主域名 `aihubmix.com` 无法访问或超时时,可将请求地址替换为 `https://api.inferera.com`。端点与能力完全一致,API Key、模型、请求体均无需改动。
## 其他功能更新
* **Gemini 音频输入**:OpenAI 兼容接口(`/v1/chat/completions`)现已支持 `input_audio`,并在 usage 中返回 audio\_tokens。
* **智谱 GLM 5.2 推理强度分档**:原生智谱渠道支持 `reasoning_effort`,可自定义思考深度。
* **Open Design 接入**:AIHubMix 现已成为 [Open Design](/cn/clients/Open-Design) 的内置 BYOK 网关。
* **OpenClaw 接入插件修复**:[aihubmix-auth](https://github.com/akakenle/aihubmix-auth) 已修复,现可稳定使用。
## 稳定性与修复
* 优化计费精度与缓存计量准确性。
* 修复 `/v1/models` 部分模型缺失。
* 修复若干视频生成与渠道测试问题。
## 本月新模型(近 20 款)
**对话 / 通用**
* **claude-fable-5**【已退役】:Claude 最新一代,安全护栏更强(详见 [更新日志 · Fable 5 特性说明](/cn/update/News#06-月-10-日))。
* **minimax-m3**、**qwen3.7-plus**、**glm-5.2**、豆包 **doubao-seed-2-1-pro / doubao-seed-2-1-turbo**。
**代码**
* **kimi-k2.7-code**、**kimi-k2.7-code-highspeed**:Kimi 代码系列,含高速版。
* **coding-glm-5.2** 及免费版 **coding-glm-5.2-free**。
**视频**
* **可灵 Kling**:文生、图生、多图参考、omni 多模态视频生成。
* **happyhorse-1.1**:文生(t2v)、参考生成(r2v)、图生(i2v)三档。
**图像**
* 百度 **musesteamer-air-image** 图像生成。
**其他新增**
* **grok-build-0.1**、**hy3-preview**、免费模型 **step-3.7-flash-free**。
## 价格与公告
* **step-3.7-flash 限时 1 折**:输入 0.022 美元 / 百万 token,输出 0.132 美元 / 百万 token。
* **模型下架与自动路由**:`claude-opus-4-20250514`、`claude-sonnet-4-20250514` 官方 6 月 15 日下架,平台会自动把它们路由到同系列 4-5 版本。
## 常见问题
**本月新增了哪些模型?**
近 20 款,涵盖对话(claude-fable-5【已退役】、minimax-m3、qwen3.7-plus、glm-5.2、doubao-seed-2-1 系列)、代码(kimi-k2.7-code 系列、coding-glm-5.2)、视频(可灵 Kling、happyhorse-1.1)与图像(musesteamer-air-image)。
**模型智能路由如何使用?**
将请求中的模型名设为 `auto`,网关会按请求内容自动选择最优模型,并按实际命中的模型计费,无需改动客户端代码。详见 [模型智能路由](/cn/api/llm-router)。
**主域名无法访问时怎么办?**
可将请求地址替换为备用域名 `https://api.inferera.com`,端点与能力完全一致,API Key、模型、请求体均无需改动。
**step-3.7-flash 的限时优惠价是多少?**
输入 0.022 美元 / 百万 token,输出 0.132 美元 / 百万 token。
查看全部模型请访问 [模型广场](https://aihubmix.com),接入细节详见 [文档中心](https://docs.aihubmix.com)。
***
更新时间:2026-06-30
# GPT-5.6 系列上线:提示缓存计费变化解读
Source: https://docs.aihubmix.com/cn/blogs/aihubmix-gpt-5-6-prompt-caching
2026 年 7 月 GPT-5.6 系列 gpt-5.6-sol / gpt-5.6-terra / gpt-5.6-luna 上线 AIHubMix:105 万上下文、缓存写入 1.25 倍计费、prompt_cache_key 与显式缓存断点,并与 Claude 提示缓存逐项对比。
OpenAI 于 2026 年 7 月 9 日正式发布 GPT-5.6 系列。AIHubMix 已完成三档模型接入:`gpt-5.6-sol`、`gpt-5.6-terra`、`gpt-5.6-luna` 现已可通过 Chat Completions 与 Responses 调用。本次发布同时调整了提示缓存的机制与计费——缓存写入开始独立计费。本文介绍三档模型的定位,并对缓存变化做逐项解读。
## GPT-5.6 三档模型有什么变化
GPT-5.6 调整了命名体系:数字代表模型世代,Sol、Terra、Luna 是可独立演进的能力档位。官方定义为——Sol 是旗舰模型,Terra 是性能与 GPT-5.5 相当的低价档,Luna 是速度最快、价格最低的档位。
| | gpt-5.6-sol | gpt-5.6-terra | gpt-5.6-luna |
| :-------- | :------------ | :------------ | :----------- |
| 官方定位 | 面向复杂专业工作的旗舰模型 | 智能与成本均衡 | 面向成本敏感负载 |
| 上下文窗口 | 1,050,000 | 1,050,000 | 1,050,000 |
| 最大输出 | 128,000 | 128,000 | 128,000 |
| 知识截止 | 2026-02-16 | 2026-02-16 | 2026-02-16 |
| 大致对应旧世代档位 | 无后缀档 | mini 档 | nano 档 |
能力方面的官方口径:Sol 在编码、知识工作、网络安全与科学任务上取得当前最先进结果,官方称其为迄今最佳编码模型,在 Terminal-Bench 2.1 与 DeepSWE 上刷新纪录;Terra 性能与 GPT-5.5 相当且价格减半。系列新增 max 推理档位,Responses API 新增 Programmatic Tool Calling 与 multi-agent(Beta)能力。
## 缓存机制升级解读
GPT-5.6 之前,GPT 系列的提示缓存完全自动:前缀达到 1,024 Token 自动缓存,开发者无法控制缓存什么、保留多久,缓存在不活跃 5–10 分钟后清除。官方将 GPT-5.6 的缓存变化概括为「更可预期的提示缓存」(more predictable prompt caching),具体有三点:
1. **保留时间从「最短 5 分钟」变为「至少 30 分钟」**。`prompt_cache_options.ttl` 当前仅支持 `"30m"`,这是保底时长,实际可能保留更久。
2. **新增显式缓存断点**。在内容块上设置 `prompt_cache_breakpoint` 可以把缓存边界固定在稳定内容的末尾,断点之后的内容变化不会破坏之前的前缀缓存;`prompt_cache_options.mode` 设为 `"explicit"` 时只使用手动断点。
3. **`prompt_cache_key` 从优化项变为官方要求**。GPT-5.6 起需设置该参数以启用更可靠的缓存匹配;官方建议单个 key 的流量控制在约 15 次/分钟内。
## 如何评估缓存写入 1.25 倍计费
GPT-5.6 起,缓存写入按基础输入价的 1.25 倍计费,缓存读取按 0.1 倍计费;此前的模型缓存写入不另计费。官方原文(出自 [GPT-5.6 发布公告](https://openai.com/index/gpt-5-6/)):"For GPT-5.6 and later models, cache writes are billed at 1.25x the model's uncached input rate, while cache reads continue to receive the 90% cached-input discount."
按官方计价规则直接计算盈亏:写入一段前缀比不缓存多付 0.25 倍输入价,此后每命中一次省 0.9 倍输入价——**前缀被复用 1 次即净节省**,复用越多省越多。
* **受益明显的负载**:长系统提示词的 Agent 工作流、重复引用长参考资料的 RAG、携带大量工具定义的应用、只向后追加消息的多轮对话。这类负载前缀复用率高,0.1 倍读取价占主导。
* **需要注意的负载**:前缀不会复用的一次性长请求。自动缓存默认开启,这类请求会产生无法回收的 1.25 倍写入费;把 `prompt_cache_options.mode` 设为 `"explicit"` 且不设置断点,该请求即不使用缓存、不产生写入费。
## 对比:GPT-5.6 与 Claude 的提示缓存
GPT-5.6 的缓存设计与 Claude 的 `cache_control` 在多个维度上趋同,核心差异在默认行为:GPT 无需任何参数即自动缓存;Claude 需在请求中启用缓存——顶层 `cache_control` 字段(自动断点)或内容块级显式断点。
| 维度 | GPT-5.6 系列 | Claude 系列(全部活跃模型) |
| :----- | :------------------------------ | :------------------------------------ |
| 触发方式 | 自动缓存,显式断点可选 | 需启用:顶层 `cache_control` 自动断点,或内容块级显式断点 |
| 断点参数 | `prompt_cache_breakpoint`(内容块级) | `cache_control`(顶层或内容块级) |
| 断点数量上限 | 每请求最多 4 个新写入 | 最多 4 个断点 |
| 缓存保留 | 至少 30 分钟 | 默认 5 分钟(命中即免费刷新),可选 1 小时 |
| 缓存写入计费 | 1.25x 输入价 | 5 分钟档 1.25x,1 小时档 2x |
| 缓存读取计费 | 0.1x 输入价 | 0.1x 输入价 |
| 最小缓存长度 | 1,024 Token | 按模型 512–4,096 Token |
| 命中要求 | 断点前逐字节一致 | 断点前逐字节一致 |
表中 Claude 列为全部活跃 Claude 模型的通用口径:写入 5 分钟档 1.25 倍、1 小时档 2 倍、读取 0.1 倍对全系统一([Anthropic 提示缓存文档](https://platform.claude.com/docs/en/docs/build-with-claude/prompt-caching)),各模型差异只在最小缓存长度;GPT-5.6 列出处为 [OpenAI 提示缓存指南](https://developers.openai.com/api/docs/guides/prompt-caching)。
两家的断点上限、写入计价比例(对应档位)、读取计价比例完全一致;对开发者的实际含义是,同一套「固定内容在前、变化内容在后」的提示词结构策略在两家模型上通用。迁移成本集中在参数语法:GPT 用 `prompt_cache_breakpoint` + `prompt_cache_key`,Claude 用 `cache_control`。
## 两种协议的缓存写法对比
同一个「缓存固定长指令」的场景,两种协议的最小实现如下。示例选用 `gpt-5.6-sol` 与 `claude-opus-4-8`——两者基础输入价相同(\$5/M),缓存写入(1.25 倍)与读取(0.1 倍)换算出的实际单价也完全一致,只有写法不同:
GPT 协议在顶层设置 `prompt_cache_key`(长前缀自动缓存,无需断点标记);Claude 协议在顶层设置 `cache_control` 启用自动缓存,需要精确控制缓存边界时再改用内容块级断点:
```shell GPT-5.6(Chat Completions) theme={null}
curl https://aihubmix.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AIHUBMIX_API_KEY" \
-d '{
"model": "gpt-5.6-sol",
"prompt_cache_key": "my-app-report-v1",
"messages": [
{
"role": "system",
"content": "[固定长指令,≥1024 Token]"
},
{
"role": "user",
"content": "Summarize the key figures."
}
]
}'
```
```shell Claude(Messages) theme={null}
curl https://aihubmix.com/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $AIHUBMIX_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-4-8",
"max_tokens": 1024,
"cache_control": {"type": "ephemeral"},
"system": "[固定长指令,≥1024 Token]",
"messages": [
{
"role": "user",
"content": "Summarize the key figures."
}
]
}'
```
对照两段请求,差异集中在:端点(`/v1/chat/completions` 与 `/v1/messages`)、鉴权头(`Authorization: Bearer` 与 `x-api-key` + `anthropic-version`)、缓存参数(顶层 `prompt_cache_key` 与顶层 `cache_control`)、Claude 需要显式 `max_tokens`。两段请求均经 aihubmix.com 实测(2026-07-10):`gpt-5.6-sol` 第二次调用 `cached_tokens: 2816`;`claude-opus-4-8` 第一次调用 `cache_creation_input_tokens: 3632`、第二次 `cache_read_input_tokens: 3632`。
除请求格式外,机制层面的差异有三处:
1. **启用方式**:GPT 不加任何缓存参数也会自动缓存,`prompt_cache_key` 用于提高命中可靠性;Claude 需要声明——内容块级 `cache_control` 断点,或请求顶层 `cache_control` 自动模式。
2. **usage 字段**:GPT 的缓存读取量在 `prompt_tokens_details.cached_tokens`;Claude 将写入量与读取量分别报告为 `cache_creation_input_tokens` 与 `cache_read_input_tokens`,便于分别核对写入与命中。
3. **生存期控制**:GPT-5.6 的 `ttl` 当前仅支持 `"30m"`;Claude 默认 5 分钟(命中即免费刷新),可选 `"ttl": "1h"`(写入按 2 倍计费)。
### 跨协议互换模型时需要修改什么
AIHubMix 网关支持跨协议调用:OpenAI 兼容接口可以调 Claude 模型(`cache_control` 直接写进 OpenAI 格式的消息内容块,写法见[提示词缓存实践](/cn/practices/prompt-caching));Claude 兼容的 `/v1/messages` 也可以调 GPT-5.6(实测可用)。互换模型时检查三项:
* `model` 换成目标模型 ID;
* 缓存参数换语法:`prompt_cache_key` / 显式断点对应 Claude 的 `cache_control`;
* usage 读数换字段名:`cached_tokens` 对应 Claude 的 `cache_read_input_tokens`。
提示缓存的推荐链路:GPT 模型走 Chat Completions(本文实测命中链路),Claude 模型两种协议均可。
## 对比:GPT-5.6 与旧代 GPT 缓存
| 维度 | GPT-5.6 之前 | GPT-5.6 及之后 |
| :-------- | :------------------------------ | :--------------------------------------- |
| 缓存写入 | 不另计费 | 1.25x 输入价 |
| 缓存保留 | 不活跃 5–10 分钟清除,最长 1 小时 | 至少 30 分钟 |
| 缓存控制 | 无 | 显式断点、explicit 模式、`prompt_cache_key` 可靠匹配 |
| 24 小时扩展保留 | 部分模型支持 `prompt_cache_retention` | 由 `prompt_cache_options.ttl` 取代(当前仅 30m) |
变化的方向一致:旧代缓存免费但不可控、保留时间不确定;GPT-5.6 对写入收费,同时给出保底保留时间和精确的缓存控制手段。按官方计价规则计算,前缀平均被复用 1 次以上时节省即超过新增的写入成本;30 分钟保底保留与可控断点提高了达到这一复用率的确定性。
## 在 AIHubMix 上开始使用
三档模型均已上线,模型 ID 为 `gpt-5.6-sol`、`gpt-5.6-terra`、`gpt-5.6-luna`。缓存无需额外配置,相同长前缀连续请求即可命中:
```py Python theme={null}
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AIHUBMIX_API_KEY"],
base_url="https://aihubmix.com/v1",
)
long_context = "You are a meticulous assistant for analyzing quarterly financial reports... [固定不变的长指令,≥1024 Token]"
for i in range(2):
completion = client.chat.completions.create(
model="gpt-5.6-sol",
prompt_cache_key="my-app-report-assistant-v1",
messages=[
{"role": "system", "content": long_context},
{"role": "user", "content": "Summarize the key figures in one sentence."},
],
)
print(completion.usage.prompt_tokens_details)
```
第二次调用的 `usage.prompt_tokens_details.cached_tokens` 大于 0 即为命中(实测示例:`cached_tokens: 2816`)。参数说明、计费细节与命中排查见 [GPT 提示词缓存](/cn/api/GPT-Cache)文档。
## 常见问题
### GPT-5.6 在 AIHubMix 上可以用哪些接口调用?
Chat Completions(`/v1/chat/completions`)、Responses(`/v1/responses`)与 Claude 兼容的 Messages 接口(`/v1/messages`)均可调用,三档模型已全部上线。提示缓存当前推荐通过 Chat Completions 使用。
### 客户端不做改动,升级到 GPT-5.6 后计费有什么变化?
提示缓存默认自动生效,前缀达到 1,024 Token 的请求会产生按 1.25 倍输入价计费的缓存写入项;前缀被复用时按 0.1 倍读取价计费。前缀复用率高的应用总成本通常下降;完全不复用前缀的一次性长请求可用 explicit 模式关闭缓存。
### 用过 Claude 提示缓存,迁移到 GPT-5.6 需要修改什么?
提示词结构策略不变:固定内容放最前、变化内容放最后。参数从 `cache_control` 换成 `prompt_cache_breakpoint`,并增加 `prompt_cache_key`;保留时间从 5 分钟/1 小时两档变为 30 分钟保底。
### GPT-5.6 三档如何选择?
官方口径:复杂专业工作与编码任务选 Sol;日常工作负载选 Terra(性能与 GPT-5.5 相当、价格减半);成本敏感的大批量场景选 Luna。三档上下文窗口与最大输出相同,可按任务复杂度分层路由。
## 官方参考
本文模型规格、缓存机制与计费规则均来自以下官方来源:
* [GPT-5.6 发布公告](https://openai.com/index/gpt-5-6/)(OpenAI,2026-07-09)
* [OpenAI 提示缓存指南](https://developers.openai.com/api/docs/guides/prompt-caching)
* [OpenAI Pricing](https://developers.openai.com/api/docs/pricing)
* [Anthropic 提示缓存文档](https://platform.claude.com/docs/en/docs/build-with-claude/prompt-caching)
站内配套文档:[GPT 提示词缓存](/cn/api/GPT-Cache) · [Claude 提示词缓存](/cn/api/Claude-Cache) · [提示词缓存实践](/cn/practices/prompt-caching)
***
前往[模型广场](https://aihubmix.com/models)查看 GPT-5.6 系列价格,或在[文档中心](https://docs.aihubmix.com)了解更多接入方式。
***
更新时间:2026-07-10
# OpenAI 兼容接口深度适配 Claude
Source: https://docs.aihubmix.com/cn/blogs/aihubmix-openai-upgrade-claude
AIHubMix 升级 OpenAI 兼容接口,深度适配 Claude:多轮交错思考无需额外传参、提示缓存自动命中,并支持开启 Anthropic beta 功能,让 Claude 在 OpenAI 协议下也能用满原生能力。
我们升级了 OpenAI 兼容接口,针对 Claude 系列模型进行了更深入的适配优化。你可以更精细、更便捷地控制思考(thinking)与缓存(caching)——特别是多轮对话中的交错思考,我们做了更人性化的处理,无需额外传参即可无痛接入。同时支持开启 Anthropic 提供的 beta 功能。
## 1. 模型思考(Extended Thinking)
### 1.1 交错思考的优点
未开启交错思考时,模型在一个 assistant turn 中只在开头进行一次思考,后续收到工具结果后直接生成回复,不再产生新的 thinking block:
```json theme={null}
User → [Thinking] → Tool Call → Tool Result → Response
```
开启交错思考后,模型在每次收到工具结果时都会插入新的 thinking block,形成链式推理:
```json theme={null}
User → [Thinking] → Tool Call → Tool Result → [Thinking] → Response
↑ Interleaved Thinking
```
这使得模型能够:
* **基于工具返回结果进行二次推理**,而非直接拼接输出
* **在多次工具调用之间链式推理**,每一步决策都建立在上一步的分析之上
> 参考:[Anthropic Interleaved Thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#interleaved-thinking)
### 1.2 开启思考
支持四种方式,任选其一:
| 方式 | 示例 | 说明 |
| :--------------------- | :----------------------------------- | :---------------------- |
| `reasoning_effort` | `"reasoning_effort": "low"` | OpenAI 标准参数,直接放在请求体顶层 |
| `reasoning.effort` | `"reasoning": {"effort": "low"}` | 等效于上一种,放在 reasoning 对象中 |
| `reasoning.max_tokens` | `"reasoning": {"max_tokens": 1024}` | 精确控制思考的最大 token 数 |
| 模型名加 `-think` | `"model": "claude-sonnet-4-5-think"` | 最简单的方式,无需额外参数 |
> **优先级**(同时使用多种时):`reasoning_effort` > `reasoning.max_tokens` > `reasoning.effort` > `-think` 后缀
**effort 可选值:** `minimal` / `low` / `medium` / `high` / `xhigh`
### 1.3 思考返回
响应的 message 中会增加两个字段:
* `reasoning_content`:思考内容(字符串),方便直接展示
* `reasoning_details`:思考的完整结构化信息,**多轮对话时需要原样回传,内部结构在不同供应商下可能有差异**
非流式示例(省略无关字段):
```json theme={null}
{
"choices": [{
"message": {
"role": "assistant",
"content": "Hello! How can I help you today?",
"reasoning_content": "The user is just saying hello...",
"reasoning_details": {
"type": "thinking",
"thinking": "The user is just saying hello...",
"signature": "Er8CCkYI..."
}
}
}]
}
```
流式返回时,思考内容会通过 `delta.reasoning_content` 和 `delta.reasoning_details` 逐块下发。完整的流式拼接逻辑见下方完整示例。
### 1.4 多轮对话中保留思考(已内置交错思考,无需额外传参)
要让模型在多轮对话中延续推理能力,只需将上一轮返回的 `reasoning_details` **原样放入**下一轮的 assistant 消息中:
```json theme={null}
messages = [
{"role": "user", "content": "What's the weather like in Boston?"},
{
"role": "assistant",
"content": response.choices[0].message.content,
"tool_calls": response.choices[0].message.tool_calls,
"reasoning_details": response.choices[0].message.reasoning_details,
},
{
"role": "tool",
"tool_call_id": "toolu_xxx",
"content": '{"temperature": 45, "condition": "rainy"}',
}
]
```
AihubMix 检测到请求中包含历史思考信息时,会**自动开启交错思考(Interleaved Thinking)**,让模型在收到工具调用结果后继续深度推理,无需额外传参。
### 1.5 完整示例
以下两个示例演示了完整的多轮 Tool Call + 交错思考流程:用户提问 → 模型思考并调用工具 → 注入工具结果(保留 `reasoning_details`)→ 模型**交错思考**后给出最终回复。
非流式 · 交错思考
```python theme={null}
import os
import json
from openai import OpenAI
client = OpenAI(
base_url="https://aihubmix.com/v1",
api_key=os.environ.get("AIHUBMIX_API_KEY", "sk-***"),
)
# ── Tool definition ───────────────────────────────────────────
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {"location": {"type": "string", "description": "City name"}},
"required": ["location"]
}
}
}]
# ── Mock tool execution ───────────────────────────────────────
WEATHER_DB = {
"boston": {"temperature": "45°F (7°C)", "condition": "rainy", "humidity": "85%", "wind": "15 mph NE"},
"tokyo": {"temperature": "72°F (22°C)", "condition": "sunny", "humidity": "45%", "wind": "5 mph S"},
}
def execute_tool(name: str, args: dict) -> str:
if name == "get_weather":
key = next((k for k in WEATHER_DB if k in args.get("location", "").lower()), None)
return json.dumps(WEATHER_DB.get(key, {"temperature": "65°F", "condition": "clear"}))
return "{}"
# ── Multi-turn conversation loop ─────────────────────────────
messages = [
{"role": "user", "content": "What's the weather like in Boston? Then recommend what to wear."}
]
turn = 0
while True:
turn += 1
print(f"\n── Turn {turn} ──")
response = client.chat.completions.create(
model="claude-sonnet-4-5",
messages=messages,
tools=tools,
extra_body={"reasoning": {"max_tokens": 2000}},
)
msg = response.choices[0].message
# Print thinking process
if msg.reasoning_content:
label = "Interleaved Thinking" if turn > 1 else "Thinking"
print(f"[{label}] {msg.reasoning_content}")
# Print response content
if msg.content:
print(f"[Response] {msg.content}")
# Print tool calls
if msg.tool_calls:
for tc in msg.tool_calls:
print(f"[Tool Call: {tc.function.name}] {tc.function.arguments}")
# Build assistant message, preserve reasoning_details (critical!)
assistant_msg = {"role": "assistant", "content": msg.content}
if msg.tool_calls:
assistant_msg["tool_calls"] = msg.tool_calls
if msg.reasoning_details:
assistant_msg["reasoning_details"] = msg.reasoning_details # pass back unmodified
messages.append(assistant_msg)
# No tool_calls means conversation is done
if not msg.tool_calls:
break
# Execute tools and append results to messages
for tc in msg.tool_calls:
args = json.loads(tc.function.arguments)
result = execute_tool(tc.function.name, args)
print(f"[Tool Result: {tc.function.name}] {result}")
messages.append({"role": "tool", "tool_call_id": tc.id, "content": result})
```
流式 · 交错思考
```python theme={null}
import os
import sys
import json
from openai import OpenAI
client = OpenAI(
base_url="https://aihubmix.com/v1",
api_key=os.environ.get("AIHUBMIX_API_KEY", "sk-***"),
)
# ── Tool definition & mock execution ─────────────────────────
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {"location": {"type": "string", "description": "City name"}},
"required": ["location"]
}
}
}]
WEATHER_DB = {
"boston": {"temperature": "45°F (7°C)", "condition": "rainy", "humidity": "85%", "wind": "15 mph NE"},
"tokyo": {"temperature": "72°F (22°C)", "condition": "sunny", "humidity": "45%", "wind": "5 mph S"},
}
def execute_tool(name: str, args: dict) -> str:
if name == "get_weather":
key = next((k for k in WEATHER_DB if k in args.get("location", "").lower()), None)
return json.dumps(WEATHER_DB.get(key, {"temperature": "65°F", "condition": "clear"}))
return "{}"
# ── Stream response collector ────────────────────────────────
def stream_and_collect(turn: int, **kwargs):
"""Stream response, print thinking/content in real-time, accumulate reasoning_details/tool_calls."""
rd = {} # accumulated reasoning_details
content = "" # accumulated response text
tc_map = {} # accumulated tool_calls (by index)
cur = "none" # current output section: none / thinking / content
stream = client.chat.completions.create(stream=True, **kwargs)
for chunk in stream:
if not chunk.choices:
continue
delta = chunk.choices[0].delta
# ── Handle thinking ──
rd_delta = getattr(delta, "reasoning_details", None)
if rd_delta and isinstance(rd_delta, dict):
for k, v in rd_delta.items():
if k == "type":
rd[k] = v
elif isinstance(v, str):
rd[k] = rd.get(k, "") + v
elif v is not None:
rd[k] = v
# Print thinking chunks in real-time
thinking_chunk = rd_delta.get("thinking", "")
if thinking_chunk:
if cur != "thinking":
cur = "thinking"
label = "Interleaved Thinking" if turn > 1 else "Thinking"
sys.stdout.write(f"\n[{label}] ")
sys.stdout.write(thinking_chunk)
sys.stdout.flush()
# ── Handle content ──
if delta.content:
if cur != "content":
if cur == "thinking":
sys.stdout.write("\n")
cur = "content"
sys.stdout.write("\n[Response] ")
sys.stdout.write(delta.content)
sys.stdout.flush()
content += delta.content
# ── Handle tool_calls ──
for tc in delta.tool_calls or []:
i = tc.index
if i not in tc_map:
tc_map[i] = {"id": "", "type": "function",
"function": {"name": "", "arguments": ""}}
if tc.id:
tc_map[i]["id"] = tc.id
if tc.function:
tc_map[i]["function"]["name"] += tc.function.name or ""
tc_map[i]["function"]["arguments"] += tc.function.arguments or ""
# End current output section
if cur in ("thinking", "content"):
sys.stdout.write("\n")
tool_calls = [tc_map[i] for i in sorted(tc_map)] if tc_map else None
return {
"content": content or None,
"reasoning_details": rd or None,
"tool_calls": tool_calls,
}
# ── Multi-turn conversation loop ─────────────────────────────
messages = [
{"role": "user", "content": "What's the weather like in Boston? Then recommend what to wear."}
]
turn = 0
while True:
turn += 1
print(f"\n── Turn {turn} ──")
result = stream_and_collect(
turn,
model="claude-sonnet-4-5",
messages=messages,
tools=tools,
extra_body={"reasoning": {"max_tokens": 2000}},
)
# Print tool calls
if result["tool_calls"]:
for tc in result["tool_calls"]:
print(f"[Tool Call: {tc['function']['name']}] {tc['function']['arguments']}")
# Build assistant message, preserve reasoning_details (critical!)
assistant_msg = {"role": "assistant", "content": result["content"]}
if result["tool_calls"]:
assistant_msg["tool_calls"] = result["tool_calls"]
if result["reasoning_details"]:
assistant_msg["reasoning_details"] = result["reasoning_details"] # pass back unmodified
messages.append(assistant_msg)
# No tool_calls means conversation is done
if not result["tool_calls"]:
break
# Execute tools and append results to messages
for tc in result["tool_calls"]:
args = json.loads(tc["function"]["arguments"])
tool_result = execute_tool(tc["function"]["name"], args)
print(f"[Tool Result: {tc['function']['name']}] {tool_result}")
messages.append({"role": "tool", "tool_call_id": tc["id"], "content": tool_result})
```
### 1.6 思考强度映射规则
**effort 模式:**
* Opus 4.6 / Sonnet 4.6 及以上:映射为 Anthropic 原生的**自适应思考(Adaptive Thinking)** effort 级别
* 其他模型:按公式计算 `budget_tokens`:
```json theme={null}
budget_tokens = max(min(max_tokens × effort_ratio, 128000), 1024)
```
| effort | effort\_ratio |
| :------ | :------------ |
| xhigh | 0.95 |
| high | 0.80 |
| medium | 0.50 |
| low | 0.20 |
| minimal | 0.10 |
**自适应思考 effort 映射:**
| 传入 effort | Opus 4.6 | Sonnet 4.6 |
| :-------- | :------- | :--------- |
| xhigh | max | high |
| high | high | high |
| medium | medium | medium |
| low | low | low |
| minimal | low | low |
**max\_tokens 模式:** 直接赋值为 Anthropic 的 `budget_tokens`。
`-think` **后缀:** Opus/Sonnet 4.6+ 使用自适应思考(effort=medium);其他模型设 `budget_tokens = min(10240, max_tokens - 1)`,`max_tokens` 默认 4096。
***
## 2. 提示词缓存(Prompt Caching)
你可以在 Chat 接口请求 Claude 模型时使用 Prompt Caching。通过在消息中设置 `cache_control` 断点,让重复使用的大段文本(角色卡片、RAG 数据、书籍章节等)被缓存下来,后续请求直接命中缓存,大幅降低成本。
> Claude 官方文档:[Prompt Caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)
### 2.1 缓存价格
| 操作 | 价格倍率(相对于原始输入价格) |
| :------------- | :-------------- |
| 缓存写入(5 分钟 TTL) | 1.25x |
| 缓存写入(1 小时 TTL) | 2x |
| 缓存读取 | 0.1x |
### 2.2 支持的模型与最小缓存长度
| 模型 | 最小缓存 token 数 |
| :------------------------------------------------------------------------------ | :----------- |
| Claude Opus 4.8 | 1024 |
| Claude Opus 4.7 | 2048 |
| Claude Opus 4.6 / Opus 4.5 | 4096 |
| Claude Sonnet 4.6 / Sonnet 4.5 / Opus 4.1 / Opus 4 / Sonnet 4 / Sonnet 3.7(已弃用) | 1024 |
| Claude Haiku 4.5 | 4096 |
| Claude Haiku 3.5(已弃用)/ Haiku 3 | 2048 |
> **断点数量限制:** 每个请求最多 **4 个** `cache_control` 断点。
### 2.3 缓存 TTL
| TTL | 写法 | 适用场景 |
| :------- | :---------------------------------------------------- | :----------- |
| 5 分钟(默认) | `"cache_control": {"type": "ephemeral"}` | 短会话、常规请求 |
| 1 小时 | `"cache_control": {"type": "ephemeral", "ttl": "1h"}` | 长会话,避免反复缓存写入 |
1 小时 TTL 的写入成本更高,但在长时间会话中可通过减少重复写入来节省总费用。所有 Claude 4.5 及之后版本模型的所有提供商(含 Anthropic、Amazon Bedrock、Google Vertex AI)均支持 1 小时 TTL。
### 2.4 使用方式
在 `system`、`user`(含图片)、`tools` 中均可通过 `cache_control` 字段设置缓存断点。以下示例仅展示关键结构,省略了大段正文内容。
**System 消息缓存(默认 5 分钟 TTL):**
```json theme={null}
{
"model": "claude-opus-4-5",
"messages": [
{
"role": "system",
"content": [
{"type": "text", "text": "You are an AI assistant"},
{
"type": "text",
"text": "(long context)",
"cache_control": {"type": "ephemeral"}
}
]
},
{
"role": "user",
"content": [{"type": "text", "text": "Hello"}]
}
]
}
```
**User 消息缓存(1 小时 TTL):**
```text theme={null}
{
"model": "claude-opus-4-5",
"messages": [
{
"role": "system",
"content": [{"type": "text", "text": "You are an AI assistant"}]
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "(long context)",
"cache_control": {"type": "ephemeral", "ttl": "1h"}
},
{"type": "text", "text": "Hello"}
]
}
]
}
```
**图片消息缓存:**
```text theme={null}
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {"detail": "auto", "url": "data:image/jpeg;base64,/9j/4AAQ..."},
"cache_control": {"type": "ephemeral"}
},
{"type": "text", "text": "What's this?"}
]
}
```
**Tool 定义缓存:**
`cache_control` 放在 tool 对象的顶层(与 `type`、`function` 同级):
```json theme={null}
{
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
},
"cache_control": {"type": "ephemeral", "ttl": "1h"}
}]
}
```
### 2.5 缓存状态查看
响应的 `usage` 中会返回 `claude_cache_tokens_details`,记录缓存的详细信息:
**首次请求(创建缓存):**
```json theme={null}
{
"usage": {
"prompt_tokens": 22,
"completion_tokens": 890,
"total_tokens": 912,
"claude_cache_tokens_details": {
"cache_creation_input_tokens": 6266,
"cache_read_input_tokens": 0,
"cache_write_5_minutes_input_tokens": 6266,
"cache_write_1_hour_input_tokens": 0
}
}
}
```
**后续请求(命中缓存):**
```json theme={null}
{
"usage": {
"prompt_tokens": 22,
"completion_tokens": 810,
"total_tokens": 832,
"prompt_tokens_details": {
"cached_tokens": 6266
},
"claude_cache_tokens_details": {
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 6266,
"cache_write_5_minutes_input_tokens": 0,
"cache_write_1_hour_input_tokens": 0
}
}
}
```
| 字段 | 含义 |
| :------------------------------------ | :---------------------------- |
| `cache_creation_input_tokens` | 本次请求新写入缓存的 token 数 |
| `cache_read_input_tokens` | 本次请求命中缓存读取的 token 数 |
| `cache_write_5_minutes_input_tokens` | 其中写入 5 分钟 TTL 缓存的 token 数 |
| `cache_write_1_hour_input_tokens` | 其中写入 1 小时 TTL 缓存的 token 数 |
| `prompt_tokens_details.cached_tokens` | 命中缓存时,兼容 OpenAI 格式的缓存 token 数 |
***
## 3. 请求头传递 anthropic-beta
你可以通过 HTTP Header `anthropic-beta` 来开启 Claude 模型的 beta 特性,AihubMix 会将该 header 透传给 Anthropic API。
### 用法
在请求头中添加 `anthropic-beta`,值为对应的 beta 功能标识符:
```json theme={null}
curl "https://aihubmix.com/v1/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-***" \
-H "anthropic-beta: context-1m-2025-08-07" \
-d '{
"model": "claude-opus-4-5",
"messages": [
{
"role": "system",
"content": [
{"type": "text", "text": "You are an AI assistant"},
{
"type": "text",
"text": "(long context)",
"cache_control": {"type": "ephemeral"}
}
]
},
{"role": "user", "content": [{"type": "text", "text": "hello"}]}
]
}'
```
> 具体可用的 beta 标识符请参考 [Anthropic API 文档](https://docs.anthropic.com/en/api/beta)。
***
更新时间:2026-06-01
***
更新时间:2026-06-01
# AIHubMix 上的免费 AI 模型
Source: https://docs.aihubmix.com/cn/blogs/free-ai-models
免费 AI 模型:2026 年在 AIHubMix 上零成本构建 AI 应用的终极指南
**免费 AI API 是 2026 年最快交付 AI 功能的方式** —— 但大多数「免费」平台都伴随着信用卡、试用到期或意料之外的用量上限。AIHubMix 走的是另一条路:一个统一、兼容 OpenAI 的网关,提供 **27+ 个真正免费的 LLM 与图像生成模型**(由平台补贴),涵盖 OpenAI 的 GPT-5.5、GPT-Image-2,Google 的 Gemini 3,智谱 GLM-5.1,Kimi,MiniMax 以及小米 MiMo。无需信用卡,无试用到期,一把 API Key 用遍所有主流模型。
## 🚀 最新更新:GPT-5.5 与 GPT-Image-2 现已免费
AIHubMix 致力于为用户争取最大价值。本次更新中,OpenAI 两款最新旗舰模型的免费版 —— **GPT-5.5 与 GPT-Image-2** —— 正式上线。由于 OpenAI 官方 API 并不提供这两款模型的免费访问,AIHubMix **持续投入补贴推理成本**,将顶级模型的使用门槛降到零。
[**GPT-5.5-free**](https://aihubmix.com/model/gpt-5.5-free)
在推理深度、Agent 编排、工具调用、代码生成与数据分析方面全面升级 —— 当前 OpenAI 综合能力最强的可用模型。在 AIHubMix 上免费使用,是不按 token 付费就能将 GPT-5.5 与 Claude Opus 4.6、Gemini 3.1 Pro、GLM-5.1 对比的最快途径。
[**GPT-5.5-free**](https://aihubmix.com/model/gpt-5.5-free) API 调用示例
```python Python theme={null}
import openai
client = openai.OpenAI(
api_key="", # 替换为在 AIHubMix 生成的 Key
base_url="https://aihubmix.com/v1"
)
response = client.chat.completions.create(
model="gpt-5.5-free", # 模型推理深度默认为 medium
messages=[
{"role": "user", "content": "Hello, how are you?"}
],
temperature=0.7 # 默认为 1
)
print(response.choices[0].message.content)
```
```python Responses-API theme={null}
from openai import OpenAI
client = OpenAI(
api_key="",
base_url="https://aihubmix.com/v1"
)
response = client.responses.create(
model="gpt-5.5-free",
input="Hello, how are you?"
)
print(response.output_text)
```
```typescript TypeScript theme={null}
import OpenAI from "openai";
const client = new OpenAI({
apiKey: "",
baseURL: "https://aihubmix.com/v1",
});
const response = await client.chat.completions.create({
model: "gpt-5.5-free",
messages: [{ role: "user", content: "Hello, how are you?" }],
temperature: 0.7,
});
console.log(response.choices[0].message.content);
```
```bash Curl theme={null}
curl https://aihubmix.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer " \
-d '{
"model": "gpt-5.5-free",
"messages": [{"role": "user", "content": "Hello, how are you?"}],
"temperature": 0.7
}'
```
[**GPT-Image-2-free**](https://aihubmix.com/model/gpt-image-2-free)
产品摄影、海报、头像、插画、电商素材、社媒图、直播封面 —— 主流图像生成场景一次调用全覆盖,输出达到商用级品质。这是 OpenAI 首款内置推理能力的图像模型,在拉丁文、中日韩、印地文等多种文字上达到约 99% 的字符级文本渲染准确率。
**API 调用示例**
```python Python_generate theme={null}
import base64
from openai import OpenAI
client = OpenAI(
api_key="", # 替换为在 AIHubMix 生成的 Key
base_url="https://aihubmix.com/v1"
)
response = client.images.generate(
model="gpt-image-2-free",
prompt="A vase of flowers on a table, with intense contrasting colors and thick, expressive brushstrokes. Render the image so it looks painted in Fauvist style.",
n=1, # 生成图片数量,支持 1-10
size="auto", # 图片尺寸:1024x1024, 1024x1536, 1536x1024, 4096x4096, auto(默认)
quality="auto" # 图片质量:high, medium, low, auto(默认)
)
image_bytes = base64.b64decode(response.data[0].b64_json)
with open("output.png", "wb") as f:
f.write(image_bytes)
```
```python Python_edit theme={null}
import base64
from openai import OpenAI
client = OpenAI(
api_key="",
base_url="https://aihubmix.com/v1"
)
# 传入一张或多张参考图,外加一条编辑提示词
response = client.images.edit(
model="gpt-image-2-free",
image=[open("product.png", "rb")], # 用于编辑 / 扩展的参考图
prompt="Change the background to a sunset beach scene, keep the product centered and unchanged.",
n=1,
size="1024x1024",
quality="high"
)
image_bytes = base64.b64decode(response.data[0].b64_json)
with open("edited.png", "wb") as f:
f.write(image_bytes)
```
```bash Curl theme={null}
curl https://aihubmix.com/v1/images/generations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer " \
-d '{
"model": "gpt-image-2-free",
"prompt": "A vase of flowers on a table, with intense contrasting colors and thick, expressive brushstrokes. Render the image so it looks painted in Fauvist style.",
"n": 1,
"size": "auto",
"quality": "auto"
}'
```
```python Python_response theme={null}
import base64
from openai import OpenAI
client = OpenAI(
api_key="",
base_url="https://aihubmix.com/v1"
)
# 通过 Responses API 的 image_generation 工具生成图片
response = client.responses.create(
model="gpt-5.5-free",
input="Generate an image of a vase of flowers on a table, Fauvist style with intense contrasting colors and thick, expressive brushstrokes.",
tools=[{"type": "image_generation"}],
)
for item in response.output:
if item.type == "image_generation_call":
image_bytes = base64.b64decode(item.result)
with open("output.png", "wb") as f:
f.write(image_bytes)
break
```
***
## 为什么要在 2026 年用免费 AI API?
免费 AI 模型 API 带来四项纯付费访问无法比拟的实在好处:
* **模型横向评测** —— 在付费前,用同一组提示词对比 GPT-5.5、Claude Opus 4.6、Gemini 3.1 Pro、GLM-5.1 和 Kimi。
* **零成本原型验证** —— 在探索阶段构建 PoC Agent、聊天机器人和自动化流水线,不必为此刷信用卡。
* **成本感知的生产路由** —— 把低风险流量(批量摘要、日志分析、初稿生成)路由到免费模型,把付费额度留给营收关键路径。
* **爱好者与学生友好** —— 独立开发者、学生和业余项目作者,得以使用原本每月动辄数百美元的前沿模型。
大多数「免费 LLM API」提供商的痛点在于碎片化:Google AI Studio 给你 Gemini,Groq 给你 Llama,OpenRouter 每周给你一套不同的组合,每家都需要独立的账号、API Key 和限流策略。AIHubMix 把 27+ 个免费模型整合到**单一兼容 OpenAI 的端点**之后,并提供自动的供应商故障切换 —— 对任何现有 OpenAI SDK 调用都可直接替换接入。
***
## 完整免费模型清单(27+ 款,2026 年 5 月)
AIHubMix 目前提供 27+ 款免费模型,覆盖 OpenAI、Google、智谱、Kimi、MiniMax、小米等主流厂商 —— 且随着新模型发布,阵容持续扩充。
### 通用对话与推理模型
涵盖 GPT-4o 与 GPT-4.1 家族,外加 Gemini Flash 及国产旗舰 —— 适用于日常问答、内容生成、文档分析与多语言对话。`gpt-4o-free` 支持图文混合输入,`gemini-3-flash-preview-free` 提供超长上下文(1M+ tokens),其余模型在速度与能力之间各有侧重。
| 模型 | 上下文 | 亮点 |
| :------------------------------------------------------------------------------------ | :--- | :---------- |
| [gpt-4o-free](https://aihubmix.com/model/gpt-4o-free) | 128K | 多模态,支持视觉 |
| [gpt-4.1-free](https://aihubmix.com/model/gpt-4.1-free) | 1M | 复杂指令遵循,长文生成 |
| [gpt-4.1-mini-free](https://aihubmix.com/model/gpt-4.1-mini-free) | 1M | 速度与能力均衡 |
| [gpt-4.1-nano-free](https://aihubmix.com/model/gpt-4.1-nano-free) | 1M | 轻量,适合高频任务 |
| [gemini-3-flash-preview-free](https://aihubmix.com/model/gemini-3-flash-preview-free) | 1M+ | 超长上下文,多模态输入 |
| [glm-4.7-flash-free](https://aihubmix.com/model/glm-4.7-flash-free) | 128K | 响应迅速,多语言支持 |
| [mimo-v2-flash-free](https://aihubmix.com/model/mimo-v2-flash-free) | 128K | 低延迟对话 |
| [ling-2.6-flash-free](https://aihubmix.com/model/ling-2.6-flash-free) | 128K | 上下文连贯性强 |
### 免费编码模型(最大类别)
免费层中最深厚的一类 —— 汇集了 Kimi、MiniMax、智谱 GLM 与 Qwen 的专用编码模型系列。如果你在找**免费的 GitHub Copilot 替代品**或**免费的 Cursor 后端**,从这里开始。
| 模型 | 强项 |
| :------------------------------------------------------------------------------ | :-------------------------------- |
| [kimi-for-coding-free](https://aihubmix.com/model/kimi-for-coding-free) | 多文件上下文、重构、调试 |
| [k2.6-code-preview-free](https://aihubmix.com/model/k2.6-code-preview-free) | 算法与系统级代码 |
| [coding-minimax-m2-free](https://aihubmix.com/model/coding-minimax-m2-free) | MiniMax 编码系列 |
| [coding-minimax-m2.1-free](https://aihubmix.com/model/coding-minimax-m2.1-free) | MiniMax 编码系列 |
| [coding-minimax-m2.5-free](https://aihubmix.com/model/coding-minimax-m2.5-free) | MiniMax 编码系列 |
| [coding-minimax-m2.7-free](https://aihubmix.com/model/coding-minimax-m2.7-free) | MiniMax 最新编码版本 |
| [coding-glm-4.6-free](https://aihubmix.com/model/coding-glm-4.6-free) | GLM 编码系列 |
| [coding-glm-4.7-free](https://aihubmix.com/model/coding-glm-4.7-free) | GLM 编码系列 |
| [coding-glm-5-free](https://aihubmix.com/model/coding-glm-5-free) | GLM-5,745B MoE,对标 Claude Opus 4.5 |
| [coding-glm-5-turbo-free](https://aihubmix.com/model/coding-glm-5-turbo-free) | GLM 编码加速版 |
| [coding-glm-5.1-free](https://aihubmix.com/model/coding-glm-5.1-free) | **SWE-bench Pro 第 1 名(58.4%)** |
| [step-3.5-flash-free](https://aihubmix.com/model/step-3.5-flash-free) | 轻量补全,低延迟 |
### 免费图像生成模型
[**GPT-Image-2-free**](https://aihubmix.com/model/gpt-image-2-free)
OpenAI 于 2026 年 4 月发布的新一代图像生成模型,也是其首款内置推理能力的图像模型。生成前会自动规划构图、从网络检索视觉参考并自检输出 —— 品质较 GPT Image 1.5 明显提升。
支持高达 **4096×4096 分辨率**,生成速度约为 GPT Image 1.5 的 2 倍,单条提示词可产出最多 8 张风格一致的图片。文本渲染尤为出色 —— 覆盖拉丁文、中日韩、印地文等文字,字符级准确率约 99%,非常适合海报、营销素材、UI 原型,以及任何需要精确排版的场景。
[**gemini-3.1-flash-image-preview-free**](https://aihubmix.com/model/gemini-3.1-flash-image-preview-free)(Nano Banana 2)
由 Google DeepMind 于 2026 年 2 月发布,将 Pro 级图像品质与 Flash 级速度结合 —— 4–6 秒即可生成一张 4K 图像。与传统图像模型不同,Nano Banana 2 直接集成进标准 Chat Completions API,无需单独的图像端点。只要在对话中描述需求即可生成图片,并可跨轮次继续编辑 —— 例如先生成产品图,再用一句话把背景换成日落场景。它还支持来自网络的实时视觉对齐,能准确渲染特定地标、品牌产品等真实世界对象。
### 免费 Agent 与推理模型
小米 MiMo 系列专为复杂推理、函数调用与工具使用打造 —— 非常适合需要多步规划与链式工具执行的自主 Agent 工作流。
| 模型 | 亮点 |
| :---------------------------------------------------------------------------- | :-------------------------------- |
| [xiaomi-mimo-v2-pro-free](https://aihubmix.com/model/xiaomi-mimo-v2-pro-free) | 高级推理、函数调用,1T+ 参数 |
| [xiaomi-mimo-v2.5-free](https://aihubmix.com/model/xiaomi-mimo-v2.5-free) | 1.02T 参数,42B 激活,1M 上下文,1000+ 工具调用 |
## AIHubMix 五大热门免费模型 🔥
### [coding-glm-5.1-free](https://aihubmix.com/model/coding-glm-5.1-free) —— 最佳免费编码模型
由智谱 AI 于 2026 年 4 月发布,约 754B 参数。**GLM-5.1 成为首个登顶 SWE-bench Pro 的开源模型,得分 58.4%** —— 超越 GPT-5.4(57.7%)、Claude Opus 4.6(57.3%)与 Gemini 3.1 Pro(54.2%)。在覆盖推理、编码、Agent、工具使用与浏览的 12 项基准中,它展现出均衡的能力画像,适合高要求的开发者工作流。通过 AIHubMix,它可零成本直接替换任意 Cursor、Cline、Aider 或 Claude Code 配置。
### [coding-glm-5-free](https://aihubmix.com/model/coding-glm-5-free) —— 开源代码强者
GLM-5.1 的前代:745B 参数 MoE 架构(44B 激活),2026 年 2 月发布。SWE-bench Verified 得分 77.8%,在 Terminal Bench 2.0 等 Agent 编码榜单上达到开源最优,整体编码能力与 Claude Opus 4.5 相当。
### [gpt-4.1-free](https://aihubmix.com/model/gpt-4.1-free) `Hot` —— 最佳免费 1M 上下文模型
> 上下文 1M · 延迟 0.529s · 吞吐 72 TPS · 输入输出免费
OpenAI 于 2025 年 4 月发布的新一代旗舰。在编码与指令遵循上全面超越 GPT-4o —— SWE-bench Verified 54.6%,IFEval 87.4%。1M 超长上下文尤其适合大规模文档分析、代码库理解与复杂 Agent 工作流。免费版托管于 Azure,响应快、稳定性高。
### [xiaomi-mimo-v2-pro-free](https://aihubmix.com/model/xiaomi-mimo-v2-pro-free) `New` —— 最佳免费 Agent 模型
> 上下文 256K · 延迟 1.673s · 吞吐 41 TPS · 输入输出免费
小米的大型推理模型 —— MoE 架构,总参数超 1T,推理时约 42B 激活。在**全球 Intelligence Index 上排名第 8**(中国模型中第 2)。编码能力超过 Claude Sonnet 4.6,整体 Agent 能力接近 Opus 4.6 —— 是复杂代码生成与长链多工具工作流的有力之选。
### [xiaomi-mimo-v2.5-free](https://aihubmix.com/model/xiaomi-mimo-v2.5-free) —— 最强免费开源推理模型
MiMo 系列当前的天花板,Artificial Analysis Intelligence Index 得分 **54**。基于混合注意力 MoE 架构(总 1.02T / 激活 42B),具备 **1M token 上下文窗口**。在通用 Agent 能力、复杂软件工程与长周期任务上较 V2-Pro 全面提升 —— 支持**单次会话 1000+ 工具调用**的 Agent 工作流。
***
## AIHubMix vs OpenRouter:该选哪个免费 AI API?
如果你搜索过「免费 AI API」「OpenRouter 替代品」或「免费 Claude API」,大概率见识过一片碎片化的格局。OpenRouter 是这一类别里被提及最多的名字,但它的免费层和 AIHubMix 的免费层解决的是根本不同的问题 —— 一个优化的是**开源模型的广度**,另一个优化的是**不花钱也能用上前沿闭源模型**。
### OpenRouter 的优势
* **开源模型丰富** —— 若你的工作围绕 DeepSeek、Llama 3.3、Qwen 或社区微调模型,OpenRouter 的清单更广。
* **随机免费模型路由** —— `openrouter/free` 虚拟模型会挑选任意可用的免费开源模型,适合低成本的兜底链路。
* 在独立开源社区有**长期的品牌认知度**。
### AIHubMix 的优势
* **免费访问闭源前沿模型** —— GPT-5.5、GPT-Image-2、Gemini 3,以及通过 GLM-5.1 实现的 Claude 级能力,均可 \$0 使用。OpenRouter 的免费层刻意排除了这些。
* **原生 Claude Code 集成** —— AIHubMix 同时暴露 `/v1/chat/completions`(OpenAI 格式)与 `/v1/messages`(Anthropic 格式,转发 `anthropic-beta` 与 `anthropic-version` 头)。通过 `ANTHROPIC_BASE_URL` 即可接入,无需代理或转换层。
* **同一网关内的图像生成** —— 用与对话相同的 API Key 调用 GPT-Image-2 或 Nano Banana 2。
* **按模型的多供应商故障切换** —— 当某个上游限流或降级时,请求会透明地重新路由,把你的有效上限抬高到单上游网关无法企及的水平。
* **更高的累计免费额度** —— 每日上限分摊在 27+ 款模型上,而非单一的 200 次请求额度。
**何时选 AIHubMix:** 你想免费用上 OpenAI / Anthropic / Google 的旗舰模型、单一兼容 OpenAI 的端点,并在同一网关里做图像生成。
**何时选 OpenRouter:** 你只需要开源模型(Llama、DeepSeek、Qwen、Gemma),且更看重最广的开源清单而非前沿闭源访问。
## 如何获取免费 AI 模型 API Key(3 步)
通过 AIHubMix 访问免费模型的完整流程:
1. 在 [aihubmix.com](https://aihubmix.com) **注册** —— 邮箱或 OAuth,无需信用卡。
2. 在 **API Keys** 页面**创建 API Key**。格式:`sk-...`
3. 从[免费模型清单](https://aihubmix.com/models)**挑选一个模型**,开始调用。
## 使用场景与集成
### 在 Claude Code(Anthropic CLI)中使用免费模型
[Claude Code](https://docs.aihubmix.com/cn/api/Claude-Code) 是 Anthropic 官方的 AI 编码 CLI,如今已是许多开发者工作流的核心。只需一行环境变量,即可让 Claude Code 走 AIHubMix,并将**任意免费编码模型作为后端** —— 无需 Anthropic 计费。
```bash theme={null}
export ANTHROPIC_BASE_URL="https://aihubmix.com"
export ANTHROPIC_AUTH_TOKEN="sk-YOUR_KEY"
claude
```
实用的路由策略:把日常代码生成交给 [kimi-for-coding-free](https://aihubmix.com/model/kimi-for-coding-free) 或 [coding-glm-5.1-free](https://aihubmix.com/model/coding-glm-5.1-free),用 [gpt-4.1-free](https://aihubmix.com/model/gpt-4.1-free) 处理文档与注释,让 [xiaomi-mimo-v2-pro-free](https://aihubmix.com/model/xiaomi-mimo-v2-pro-free) 负责复杂任务的规划与编排。整套开发辅助流水线以零推理成本运行。配置细节见 [Claude Code 集成文档](https://docs.aihubmix.com/cn/api/Claude-Code) —— 同样可直接用于 [Claude Desktop](https://docs.aihubmix.com/cn/api/claude-desktop)。
### 在 Cursor、Cline、Aider 等 AI 编码编辑器中使用免费模型
任何支持自定义 OpenAI 兼容端点的 AI 编码编辑器都能用上 AIHubMix 免费模型。把 `https://aihubmix.com/v1` 配置为 base URL,再挑一个 `*-free` 模型 —— 即可在 IDE 助手中直接替换付费的 GPT-5 或 Claude 用量。
### 在 AI Agent 与自主工作流中使用免费模型
[OpenClaw](https://docs.aihubmix.com/cn/api/OpenClaw) —— 2025 年 11 月发布的开源自主 AI Agent 平台,目前**用户超 320 万**。支持几乎所有主流消息渠道 —— WhatsApp、Telegram、Slack、Discord —— 让 AI Agent 直接在用户已有的工作平台内执行任务。通过 AIHubMix,[xiaomi-mimo-v2-pro-free](https://aihubmix.com/model/xiaomi-mimo-v2-pro-free) 与 [coding-glm-5.1-free](https://aihubmix.com/model/coding-glm-5.1-free) 均可作为后端模型无缝运行,完整支持函数调用、多轮上下文与结构化输出。
[Hermes Agent](https://docs.aihubmix.com/cn/api/hermes-agent-ai-hubmix) —— NousResearch 的 Agent 框架,针对工具使用与结构化 JSON 输出做了深度优化。其 `execute_code` 工具将多步流水线压缩为单次推理调用,大幅减少往返。非常适合需要严格 JSON 输出的自动化流水线 —— AIHubMix 跨供应商的自动限流轮换,确保长时任务在单一供应商触顶时不被中断。
### 在开源客户端中使用免费模型
AIHubMix 是多款热门开源应用官方支持的 API 提供商:
* **桌面聊天客户端** —— [Cherry Studio](https://docs.aihubmix.com/cn/clients/Cherry-Studio) 是最受欢迎的本地 AI 聊天客户端之一,界面简洁、多模型管理便捷。选择 AIHubMix 作为 API 提供商,即可在桌面聊天界面中使用 GPT-4.1、Gemini Flash、GLM-5.1 等免费模型。
* **多模型代理与翻译** —— [LiteLLM](https://docs.aihubmix.com/cn/clients/LiteLLM) 为多个免费模型提供统一的调用管理与负载均衡;[NextAI Translator](https://docs.aihubmix.com/cn/clients/NextAITranslator) 支持用免费模型做高质量多语言翻译。
* **MCP / IDE 集成** —— Claude Desktop、Continue、Open WebUI,以及任何接受 OpenAI 兼容端点的工具。
***
## 限流与免费额度
AIHubMix 上的免费模型按每个模型的限流运行,以**每分钟请求数(RPM)**与**每日 token 上限**表示。具体数值见 [aihubmix.com/models](https://aihubmix.com/models) 上各模型的页面。与单一供应商的免费层相比:
* **比 OpenRouter 更有余量** —— 每个模型背后有多家供应商,某个上游限流时自动切换。
* **比 Google AI Studio 累计上限更高** —— 不是单一模型每天 1500 次请求,AIHubMix 让你把流量分摊到 27+ 款免费模型上。
* **没有意外到期** —— 额度每日重置,没有 30 天试用悬崖。
对于生产流量,推荐的模式是**关键路径用付费额度,辅助负载用免费模型**(批量摘要、日志增强、初稿生成、非营收关键功能)。
## 常见问题
**问:为什么选 AIHubMix 而非 OpenRouter、AIMLAPI 或 Google AI Studio?**
答:AIHubMix 提供统一的兼容 OpenAI 的 API,聚合**全球 500+ 模型,含 27+ 款持续更新的免费模型** —— 且不同于 OpenRouter,其免费层包含 GPT-5.5、GPT-Image-2、Gemini 3 等前沿闭源模型(不只是开源)。付费模型定价更具竞争力。平台由 AIHubMix, LLC(美国)正式运营,并获主流云厂商正式授权 —— 在稳定性与合规性上都值得信赖。
**问:使用 AIHubMix 免费模型需要信用卡吗?**
答:不需要。用邮箱或 OAuth 注册,创建 API Key 即可开始调用。免费模型无需绑定任何支付方式即可立即使用。
**问:AIHubMix 上的免费模型有时间限制或试用到期吗?**
答:没有试用到期。免费模型在各自的每分钟与每日额度内长期可用。限制以 RPM 与每日 token 上限表示 —— 具体见各模型页面。
**问:哪个免费模型的综合编码能力最强?**
答:截至 2026 年 5 月,[coding-glm-5.1-free](https://aihubmix.com/model/coding-glm-5.1-free) 领先 —— 其 58.4% 的 SWE-bench Pro 得分超过 GPT-5.4(57.7%)、Claude Opus 4.6(57.3%)与 Gemini 3.1 Pro(54.2%),是**首个登顶 SWE-bench Pro 榜单的开源模型**。[kimi-for-coding-free](https://aihubmix.com/model/kimi-for-coding-free) 在多文件上下文理解与代码重构上尤为出色。
**问:AIHubMix 免费模型适合用于生产吗?**
答:对于中等量级的生产流量,在精心规划额度的前提下可以。AIHubMix 的自动故障切换会在多家供应商间均衡负载,提升有效可用额度。对于更高流量的生产场景,核心推理用付费额度,辅助工作(批量摘要、日志分析、非关键路径)路由到免费模型,以兼顾成本与稳定性。
**问:能用 OpenAI 的 Python 或 Node.js SDK 调用 AIHubMix 免费模型吗?**
答:可以 —— AIHubMix 完全兼容 OpenAI。把 `base_url` 设为 `https://aihubmix.com/v1`,即可使用任意官方 OpenAI SDK、LangChain 集成、LlamaIndex 流水线或 AI 网关,无需改写代码。
**问:AIHubMix 支持免费的图像生成 API 吗?**
答:支持。免费图像生成包括 **GPT-Image-2**(OpenAI 首款具备推理能力的图像模型,最高 4096×4096)与 **Nano Banana 2**(`gemini-3.1-flash-image-preview-free`,4–6 秒出 4K 图)。二者均通过标准的 chat-completions 或图像端点访问 —— 无单独的计费或额度体系。
***
## 立即开始
准备好在不烧光预算的情况下交付 AI 功能了吗?在 [aihubmix.com](https://aihubmix.com) 注册,领取一把免费 API Key,几分钟内即可开始调用 27+ 款前沿模型。更深入的集成指南、模型性能规格、额度细节与 SDK 示例,见 [AIHubMix 官方文档](https://docs.aihubmix.com/cn)。完整的免费模型清单见 [aihubmix.com/models](https://aihubmix.com/models)。
**相关指南:** [Claude Code 配置](https://docs.aihubmix.com/cn/api/Claude-Code) · [Cherry Studio 集成](https://docs.aihubmix.com/cn/clients/Cherry-Studio) · [LiteLLM 网关](https://docs.aihubmix.com/cn/clients/LiteLLM) · [OpenClaw Agent 平台](https://docs.aihubmix.com/cn/api/OpenClaw) · [Hermes Agent 结构化输出](https://docs.aihubmix.com/cn/api/hermes-agent-ai-hubmix)
***
**参考与来源**
* [Introducing GPT-4.1 | OpenAI](https://openai.com/index/gpt-4-1/)
* [MiMo-V2-Pro | Xiaomi](https://mimo.xiaomi.com/mimo-v2-pro)
* [MiMo-V2.5-Pro | Xiaomi](https://mimo.xiaomi.com/mimo-v2-5-pro/)
* [GLM-5.1 | Hugging Face](https://huggingface.co/zai-org/GLM-5.1)
* [GLM-5.1 Overview | Z.AI Developer Docs](https://docs.z.ai/guides/llm/glm-5.1)
* [GLM-5.1 SWE-bench Pro Results | VentureBeat](https://venturebeat.com/technology/ai-joins-the-8-hour-work-day-as-glm-ships-5-1-open-source-llm-beating-opus-4)
* [GLM Coding Plan | Zhipu AI](https://www.bigmodel.cn/glm-coding)
* [OpenClaw | Official Docs](https://docs.openclaw.ai/)
* [Hermes Agent | Nous Research](https://hermes-agent.nousresearch.com/)
* [Claude Code LLM Gateway Docs | Anthropic](https://code.claude.com/docs/en/llm-gateway)
*最后更新:2026 年 5 月 7 日*
# 全球加速网络:延迟降 75%、可用性 99.99%
Source: https://docs.aihubmix.com/cn/blogs/global-acceleration
AIHubMix 自建全球边缘节点与智能流量调度,响应延迟降低 75%、连接稳定性波动降低 60%、服务可用性达 99.99%,多区域探针每分钟实时健康监测并毫秒级自动切换,让 AI 应用调用更快更稳。
## 我们只做了一件事:让你的 AI 应用,比竞品快一步
为了让每一位用户都能流畅访问 AI 服务,我们前前后后测试了十几家加速服务商。说实话,结果不太让人满意——延迟忽高忽低,稳定性时好时坏。我们不满意的体验,肯定也不能让你们满意。
所以我们做了一个决定:**不用了,自己来。** 自己组节点,自己建监控,自己做调度,自己盯着每一毫秒的延迟。更细粒度的优化,只有自己动手才能做到。
***
## 持续调优,用数据说话
经过不断迭代调度算法、持续监控盯盘、实时动态优化,这是我们交出的成绩单:
### 响应延迟:提速 75%
接口调用从"能感觉到等"变成"几乎没感觉"。对于流式对话场景,首字输出更快,体感提升尤为明显。你的用户不会知道我们做了什么,但他们会觉得——**这个产品,就是比别家快。**
### 连接稳定性:波动降低 60%
以前延迟像过山车,时快时慢,客户体验靠运气。现在每一次请求的延迟都趋于一致,**稳定,才是真正的快。**
### 服务可用性:99.99% 无限接近于100%
不是写在 SLA 里的数字,是我们实际跑出来的数字。全天候在线,节假日不休,凌晨三点和下午三点一样稳。
> 选一个靠谱的 AI 服务商,少一些超时报错,少一些客户投诉,少一些半夜救火。**我们在背后死磕的每一毫秒,都是为了让你省心,让你的客户满意。**
***
## 我们到底做了什么
### 自建全球边缘节点
不依赖单一线路,不绑定任何一家云厂商。我们在全球多个地区精选、实测、部署了一批专属加速节点。每一台机器上线之前,都经过了反复的延迟测试、丢包测试、高峰期压测。不达标的,直接淘汰。只为给你的每一次 API 调用,找到那条最快的路。
### 7×24 实时健康监测
我们自研了一套全链路拨测系统,分布在多个区域的探针每分钟对每个节点发起健康检查。延迟、通过率、稳定性——三个维度,不间断监控。
不是每小时看一次报表,是**每 60 秒扫一遍全网**。任何节点出现异常,我们的系统在你的用户感知到之前就已经知道了。
### 智能流量调度
不是出了问题才切换,不是人工判断再操作。我们的调度系统每分钟都在分析四个时间窗口的拨测数据——1 分钟、5 分钟、15 分钟、1 小时——综合计算每个节点的健康评分,自动把流量调度到当前最优的节点上。
整个过程全自动,零人工干预,切换在毫秒级完成。**你感受不到切换,因为切换发生在问题之前。**
### 全自动运维体系
节点管理、线路优化、配置下发、证书更新、故障恢复——**全部自动化**。
没有人工值守的间隙,没有"等工程师上班再处理"的空窗期,没有"节假日暂停服务"的公告。凌晨三点出了问题,系统自己处理,你第二天醒来什么都不用知道。
***
## 这就是我们的态度
* 一条线路偶尔出现抖动,不是调参数凑合,是直接换节点
* 监控精度到毫秒,每一次优化都有数据支撑,不是"感觉快了",是**精确地快了 75%**
* 每一次 DNS 调度都有完整日志,每一台机器的状态实时可查
**别人在做能用的产品,我们在做让你放心的产品。**
***
*你可能只是感觉"好像最近快了不少"。* *但这背后,是我们对每一个请求、每一毫秒、每一个节点的较真。*
*做 AI 应用已经够难了,网络的事,不应该再让你操心。*
## **AIHubMix — 让你的 AI 应用,比竞品快人一步。**
更新时间:2026-06-01
# Kimi K3 实测调用指南:新参数与三接口支持矩阵
Source: https://docs.aihubmix.com/cn/blogs/kimi-k3-guide
2026 年 7 月 Kimi K3 调用指南:reasoning_effort max 档与思考历史回传、动态工具加载、结构化输出、自动缓存、partial 前缀续写与视觉输入,附 AIHubMix Chat / Responses / Messages 三接口示例。
> 本文介绍 [Kimi K3](https://aihubmix.com/model/kimi-k3) 的新增参数与调用注意事项。K3 在 AIHubMix 可通过 Chat Completions、Responses 与 Claude 兼容的 Messages 接口调用。延伸阅读:[Moonshot 官方平台文档](https://platform.moonshot.ai/docs)。
>
> 各节的「实测」结论与示例返回均来自 2026-07-17 通过 AIHubMix 接口(Chat Completions / Responses / Messages)的实际调用。
## 1. 模型规格速览
| 项 | 值 |
| :---- | :---------------------------------------------- |
| 上下文窗口 | 1M tokens |
| 最大输出 | `max_completion_tokens` 默认 131,072,最大 1,048,576 |
| 输入模态 | 文本、图像(视频输入见 Moonshot 官方文档) |
| 思考模式 | 默认开启,`reasoning_effort` 仅支持 `"max"` |
| 停止序列 | `stop` 最多 5 个,每个不超过 32 字节 |
> **实测**:`stop` 的两个上限均会校验,超出返回 400;Responses 与 Messages 接口分别以 `stop`、`stop_sequences` 执行相同校验。
>
> ❗ **Messages 接口命中停止词时不按 Anthropic 语义返回**:实测 `stop_reason` 为 `"end_turn"`(而非 `"stop_sequence"`)、`stop_sequence` 为 `null`,且停止词之前的可见文本可能为空。依赖这两个字段判断截断原因的客户端需注意。
```text theme={null}
# stop with 6 entries / a 33-byte entry -> HTTP 400
"Invalid request: stop array too long. Expected an array with maximum length 5, but got an array with length 6 instead"
"Invalid request: stop sequence must not be longer than 32, but got 33 instead"
```
> **实测(2026-07-21)**:Responses 接口的 `stop` 此前虽接受参数但不生效,现已修复为实际截断。示例:`input="Count from 1 to 10, one number per line, digits only."`、`stop=["5"]`,输出为 `"1\n2\n3\n4\n"`,未再继续生成到 `5` 及之后的数字;6 个停止词 / 33 字节停止词也已按上限正确返回 400。
## 2. 思考模式:`reasoning_effort` 仅 `max` 档
K3 的思考默认开启,`reasoning_effort` 仅支持 `"max"` 一档。
**多轮对话必须原样回传思考历史**:按 Moonshot 官方说明,K3 采用 preserved thinking 方式训练,多轮对话时需要把上一轮返回的 assistant 消息**原样完整**回传(包含思考内容),思考历史缺失会导致输出质量不稳定。使用会话管理框架或代理层时,请确认思考内容未在回传前被裁剪。
思考内容通过响应里的 `reasoning_content` 字段返回;多轮时把上一轮 assistant 消息(含 `reasoning_content`)原样回传。
```text theme={null}
from openai import OpenAI
client = OpenAI(
base_url="https://aihubmix.com/v1",
api_key="",
)
completion = client.chat.completions.create(
model="kimi-k3",
reasoning_effort="max",
messages=[
{"role": "user", "content": "A snail is at the bottom of a 10-meter well. Each day it climbs 3 meters, but each night it slides back 2 meters. How many days does it take to reach the top?"}
],
)
print(completion.choices[0].message.reasoning_content)
print(completion.choices[0].message.content)
```
```text theme={null}
# Multi-turn: pass the previous assistant message back verbatim
messages = [
{"role": "user", "content": "What is the capital of France?"},
{"role": "assistant", "content": "Paris.", "reasoning_content": ""},
{"role": "user", "content": "And its population?"},
]
```
> **实测**:响应返回 `reasoning_content`;把上一轮 assistant 消息(含 `reasoning_content`)原样回传后,后续轮次正常应答。
思考内容以 `reasoning` 输出项返回;多轮时把上一轮的输出项(`reasoning` + `message`)原样拼回 `input`。
```text theme={null}
from openai import OpenAI
client = OpenAI(
base_url="https://aihubmix.com/v1",
api_key="",
)
response = client.responses.create(
model="kimi-k3",
input="Answer in one word: capital of France",
)
# Observed response.output item types: ["reasoning", "message"]; text: "Paris"
# Multi-turn: input = [first user message] + response.output + [next user message]
# Observed second-turn answer with output items passed back: "Berlin"
```
思考内容以原生 `thinking` 内容块返回;多轮时把上一轮 assistant 的内容块(含 thinking 块)原样回传。
```text theme={null}
from anthropic import Anthropic
client = Anthropic(
api_key="",
base_url="https://aihubmix.com"
)
response = client.messages.create(
model="kimi-k3",
max_tokens=4096,
messages=[
{"role": "user", "content": "Answer in one word: capital of France"}
],
)
# Observed response.content block types: ["thinking", "text"]; text: "Paris"
# Multi-turn: pass response.content back verbatim as the assistant message
```
## 3. 采样参数为固定值
K3 的采样参数为官方固定值:`temperature` 1.0、`top_p` 0.95、`n` 1、`presence_penalty` / `frequency_penalty` 0。官方建议请求中不要传入这些参数。
> **说明**:采样固定值为官方规格,无法从响应信号验证;请按官方建议省略这些参数。
## 4. 工具调用与动态工具加载
`tools` 最多支持 128 个工具;`tool_choice` 支持强制调用与禁用调用。K3 还支持动态工具加载:在对话中途插入一条只带 `tools` 字段(不带 `content`)的 system 消息,注入新工具,无需在请求最外层预先声明全部工具。
`tool_choice` 支持 `auto` / `none` / `required`,`required` 强制模型调用工具。动态工具加载:注入工具的 system 消息不带 `content`,注入的工具对后续轮次生效,每轮请求需要重复携带。
```text theme={null}
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello."},
{"role": "assistant", "content": "Hi, how can I help you?"},
# Inject a new tool mid-conversation: tools field only, no content
{
"role": "system",
"tools": [
{
"type": "function",
"function": {
"name": "get_time",
"description": "Get the current time",
"parameters": {"type": "object", "properties": {}},
},
}
],
},
{"role": "user", "content": "What time is it now?"},
]
```
```text theme={null}
# tool_choice="required" with prompt "Hello" -> the model is forced to call the tool
"finish_reason": "tool_calls",
"tool_calls": [{"function": {"name": "get_weather", "arguments": "{\"city\":\"New York\"}"}}]
```
> **实测**:`tool_choice: "required"` 对无关提问也会强制产生工具调用;`"none"` 抑制工具调用;经无 `content` 的 system 消息中途注入的工具可被正常调用。
工具定义为扁平结构(`name` 在顶层),强制调用同样使用 `tool_choice: "required"`,调用以 `function_call` 输出项返回。动态工具加载与 Chat Completions 同构:在 `input` 数组中插入一条只带 `tools` 字段(不带 `content`)的 system 角色输入项即可注入新工具。
```text theme={null}
response = client.responses.create(
model="kimi-k3",
input="Hello",
tools=[{
"type": "function",
"name": "get_weather",
"description": "Get weather for a city",
"parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
}],
tool_choice="required",
)
# Observed output contains: {"type": "function_call", "name": "get_weather", "arguments": "{\"city\":\"London\"}"}
```
```text theme={null}
# Dynamic tool loading: inject a tool mid-conversation via a system-role input item
input = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello."},
{"role": "assistant", "content": "Hi, how can I help you?"},
{
"role": "system",
"tools": [{
"type": "function",
"name": "get_time",
"description": "Get the current time",
"parameters": {"type": "object", "properties": {}},
}],
},
{"role": "user", "content": "What time is it now?"},
]
# Observed with tool_choice="auto": the model calls the injected tool on its own
# {"type": "function_call", "name": "get_time", "arguments": "{}"}
# Control (same question, tool not injected): the model declines to fabricate a call
```
> **实测(2026-07-21)**:注入工具后,`tool_choice="auto"` 下模型会按需主动调用注入的工具;对照组(不注入该工具、其余条件相同)模型不会编造调用,说明调用确实基于注入的工具定义,而非模型幻觉出的函数名。
工具用 Anthropic 格式(`input_schema`),强制调用为 `tool_choice: {"type": "any"}`,禁用为 `{"type": "none"}`。❗ **Kimi K3 官方的 Messages(Anthropic 兼容)端点不支持动态工具加载**:实测注入消息返回 200,但注入的工具不生效(模型无法调用),请在顶层 `tools` 参数中声明全部工具。
```text theme={null}
response = client.messages.create(
model="kimi-k3",
max_tokens=4096,
tools=[{
"name": "get_weather",
"description": "Get weather for a city",
"input_schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
}],
tool_choice={"type": "any"},
messages=[{"role": "user", "content": "Hello"}],
)
# Observed: stop_reason "tool_use"; content contains a tool_use block calling get_weather
```
## 5. 结构化输出
结构化输出可让模型返回严格符合给定 JSON Schema 的内容。
`response_format` 支持 `json_schema` 与 `strict` 模式。
```text theme={null}
completion = client.chat.completions.create(
model="kimi-k3",
messages=[
{"role": "user", "content": "Paris is the capital of France. Extract the city name."}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "extract",
"strict": True,
"schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
},
)
# Observed response content: {"city":"Paris"}
```
> **实测**:输出为符合 schema 的合法 JSON。
结构化输出通过 `text.format` 声明。
```text theme={null}
response = client.responses.create(
model="kimi-k3",
input="Paris is the capital of France. Extract the city name.",
text={
"format": {
"type": "json_schema",
"name": "extract",
"strict": True,
"schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
}
},
)
# Observed output text: {"city":"Paris"}
```
❗ **Kimi K3 官方的 Messages(Anthropic 兼容)端点不支持结构化输出**:结构化输出字段会被静默忽略——请求返回 HTTP 200 与自由文本,无任何报错或降级提示,下游 JSON 解析会失败。需要结构化输出时请使用 Chat Completions 或 Responses 接口。
## 6. 上下文缓存自动开启
K3 的上下文缓存自动开启,无需传入任何参数。重复的长前缀命中缓存后,命中量在 usage 中报告(字段名随接口而异)。缓存价格见[模型页](https://aihubmix.com/model/kimi-k3)。
```text theme={null}
# usage of the second call with an identical long prefix
"prompt_tokens_details": {"cached_tokens": 1536}
```
> **实测**:相同长前缀的第二次请求在 `usage.prompt_tokens_details.cached_tokens` 中报告命中。
```text theme={null}
# usage of the second Responses call with identical long instructions
"input_tokens_details": {"cached_tokens": 1536}
```
```text theme={null}
# usage of the second Messages call with an identical long system prompt
"cache_read_input_tokens": 1536
```
## 7. `partial` 前缀续写
前缀续写让模型从给定前缀继续生成,适合代码补全和受控格式输出。
在最后一条 assistant 消息中传入 `"partial": true`。
```text theme={null}
messages = [
{"role": "user", "content": "Write a haiku about the sea."},
{"role": "assistant", "content": "Waves fold into foam,", "partial": True},
]
# Prefix: "Waves fold into foam," -> continuation returned by the model
# salt hangs in the air—
# moon pulls the tide home.
```
> **实测**:生成从给定前缀继续,不重复前缀。
把前缀作为 `input` 数组末尾的 assistant 消息传入,无需 `partial` 参数。
```text theme={null}
response = client.responses.create(
model="kimi-k3",
input=[
{"role": "user", "content": "Write a haiku about the sea."},
{"role": "assistant", "content": "Waves fold into foam,"},
],
)
# Observed continuation: "salt hangs in the air— / moon pulls the tide home."
```
以协议原生的 assistant 预填实现同等能力,无需 `partial` 参数——把前缀作为最后一条 assistant 消息传入即可。
```text theme={null}
response = client.messages.create(
model="kimi-k3",
max_tokens=4096,
messages=[
{"role": "user", "content": "Write a haiku about the sea."},
{"role": "assistant", "content": "Waves fold into foam,"},
],
)
# Observed continuation: "salt wind carries the gull's cry— / tide pulls ..."
```
## 8. 视觉输入
图像以 base64 传入,内容块写法随接口而异。
```text theme={null}
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": "What is the dominant color of this image? One word."},
{"type": "image_url", "image_url": {"url": "data:image/png;base64,"}},
],
}
]
# Observed response content: "Red" (input: a 64x64 solid red PNG)
```
> **实测**:base64 图像输入可用,模型正确描述测试图内容。
```text theme={null}
input = [
{
"role": "user",
"content": [
{"type": "input_text", "text": "What is the dominant color of this image? One word."},
{"type": "input_image", "image_url": "data:image/png;base64,"},
],
}
]
# Observed output text: "Red"
```
```text theme={null}
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": "What is the dominant color of this image? One word."},
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": ""}},
],
}
]
# Observed response text: "Red"
```
## 9. 实测参考:长任务单次调用的耗时与用量
K3 思考固定为 max 档,复杂任务的单次请求耗时显著长于常规模型。一次单文件 HTML 游戏生成任务(单条 prompt 附参考图,一次生成,不迭代)的实测数据:单次请求耗时 2,541 秒(约 42 分钟),completion tokens 74,994,其中思考部分 54,486,占 73%,最终一次产出 1,275 行可直接运行的代码,`finish_reason` 为 `stop`。
调用侧建议:
* 客户端超时按分钟级以上设置,长任务优先使用流式返回;
* `max_completion_tokens` 给足余量,本例仅思考即消耗 54,486 tokens。
## 10. 能力 × 接口支持矩阵
下表各格均为通过 AIHubMix 线上接口实际调用验证的结果,格内为对应接口的参数 / 字段写法;除标注日期的两项外,均为 2026-07-17 验证结果。
| 能力 | Chat Completions | Responses | Messages |
| :---------- | :-------------------------------------------- | :--------------------------------------------------- | :----------------------------------------------------------------------------------- |
| 思考内容返回 | ✅ `reasoning_content` 字段 | ✅ `reasoning` 输出项 | ✅ `thinking` 内容块 |
| 思考历史回传 | ✅ assistant 消息原样回传 | ✅ 输出项原样回传 | ✅ 内容块原样回传 |
| 强制 / 禁用工具调用 | ✅ `tool_choice: "required"` / `"none"` | ✅ `tool_choice: "required"` | ✅ `{"type": "any"}` / `{"type": "none"}` |
| 动态工具加载 | ✅ system 消息带 `tools`(无 `content`) | ✅ system 角色输入项带 `tools`(无 `content`),2026-07-21 复测确认 | ❗ 官方 Messages(Anthropic 兼容)端点不支持 |
| 结构化输出 | ✅ `response_format`(json\_schema + strict) | ✅ `text.format`(json\_schema) | ❗ 官方端点不支持,字段被**静默忽略**(200 + 自由文本),请改用 Chat / Responses |
| 自动缓存命中计量 | ✅ `usage.prompt_tokens_details.cached_tokens` | ✅ `usage.input_tokens_details.cached_tokens` | ✅ `usage.cache_read_input_tokens` |
| 前缀续写 | ✅ `"partial": true` | ✅ assistant 预填 | ✅ assistant 预填(协议原生) |
| 视觉输入 | ✅ `image_url`(base64) | ✅ `input_image`(base64) | ✅ `image` 内容块(base64) |
| 停止序列 | ✅ `stop`(上限校验) | ✅ `stop`(上限校验、实际截断生效),2026-07-21 复测由不生效改为已支持 | ❗ `stop_sequences` 上限校验一致,但命中时不返回 `stop_reason: "stop_sequence"` / `stop_sequence` 值 |
## 常见问题
**K3 在 AIHubMix 支持哪些接口?**
Chat Completions(`/v1/chat/completions`)、Responses(`/v1/responses`)与 Claude 兼容的 Messages(`/v1/messages`)。
**可以关闭思考或调低思考强度吗?**
不可以。K3 思考默认开启,`reasoning_effort` 仅支持 `"max"` 一档。
**为什么多轮对话要回传 `reasoning_content`?**
K3 采用 preserved thinking 方式训练,官方要求原样完整回传上一轮 assistant 消息;思考历史缺失会导致输出质量不稳定。
**`stop` 参数有什么限制?**
最多 5 个停止词,每个不超过 32 字节,超出会返回 400 错误。
**Messages 接口支持结构化输出吗?**
❗ 不支持。Kimi K3 官方的 Messages(Anthropic 兼容)端点会静默忽略结构化输出字段(返回 200 与自由文本,无报错)。需要结构化输出请使用 Chat Completions 的 `response_format` 或 Responses 的 `text.format`。
**K3 单次请求为什么耗时较长?**
K3 思考固定为 max 档,复杂任务的思考 token 占比高(实测案例中占 completion tokens 的 73%)。建议按分钟级以上设置客户端超时,并使用流式返回。
***
模型定价与实时状态见 [Kimi K3 模型页](https://aihubmix.com/model/kimi-k3),更多模型见[模型广场](https://aihubmix.com/models)。
更新时间:2026-07-21(第 1、4、10 节:Responses 接口动态工具加载与停止序列均复测更新为已支持)
# AIHubMix 图片生成 MCP
Source: https://docs.aihubmix.com/cn/clients/AHM-mcp
AIHubMix 图片生成 MCP:在支持 MCP 协议的客户端中通过 AIHubMix 调用图片生成模型,统一计费。
## 简介
Aihubmix 使用统一接口的方式整合了市面上主流的图片生成 API,以 MCP 的方式封装设计,让开发者们可以更便利地整合到与 LLM 的交互中,用户使用自然语音输入,即可触发图片生成。
目前整合的模型如下:
* openai/gpt-image-1
* bfl/FLUX.1-Kontext-pro
* google/imagen-4.0-ultra-generate-preview-06-06
* google/imagen-4.0-generate-preview-06-06
* ideogram/V3
gpt-image-1 模型的返回结果为 base64 编码,在 Claude Desktop 中可能会因为太长导致报错。目前建议优先使用 V3 / Flux / Imagen。
## 1️⃣ 安装
根据您使用的工具选择对应的安装方式:
| 工具 | 安装方式 | 适合人群 |
| :------------------------- | :------------------ | :------------------------------ |
| Claude Code(终端命令行) | Claude Code 安装方式 | 开发者,一条命令完成安装,可与代码工作流无缝结合 |
| Claude Desktop(桌面 App) | Claude Desktop 安装方式 | 普通用户,配置后直接在 App 对话即可生成图片,无需编程基础 |
| Cursor / Windsurf 等 AI 编辑器 | IDE 配置文件方式 | 开发者,在项目目录添加配置文件,图片生成能力直接集成到编码环境 |
| Warp AI(终端工具) | Warp AI 安装方式 | 开发者,在终端 AI 对话中直接触发图片生成,无需切换工具 |
下面是一些常用 AI 工具的 MCP 安装方式示例,运行指令之前需要将 `sk-***` 替换为你的 Aihubmix 密钥。
安装之后都需要重启工具才能生效。
### 安装到 Claude Code
**第一步:终端运行安装指令**
```shell theme={null}
claude mcp add --transport http aihubmix-api https://aihubmix.com/mcp/ \
--header "Authorization: Bearer sk-***"
```
**第二步:启动 Claude Code(安装指南见 。。。)**
```text theme={null}
claude
```
在终端输入 `claude` 回车,进入交互界面。
**第三步:输入** `/mcp `**确认**
在 Claude Code 的对话输入框里输入:
```text theme={null}
/mcp
```
回车后会显示当前已连接的 MCP 服务列表,如果看到 `aihubmix-api` 且状态为 ✔ connected,说明安装成功。
> 如果状态是 **failed** 或没有出现,检查两点:
>
> 1. 密钥是否替换了(不能是 `sk-***`)
> 2. 重新运行安装指令后再试
### 安装到 Claude Desktop
Claude Desktop 是 Anthropic 官方出品的**桌面客户端应用**,包含两个入口:**对话界面**(Chat)和 **Code 标签页**,两者的 MCP 配置相互独立。本文档的 Claude Desktop 安装方式适用于对话界面。
官方下载页:[https://code.claude.com/docs/en/desktop](https://code.claude.com/docs/en/desktop)
支持 **macOS** 和 **Windows**,下载安装包后直接安装即可。
**第一步:打开配置文件**
点击 Claude Desktop 右上角头像 → **Settings** → **Developer** → **Edit Config**
打开 `claude_desktop_config.json` 文件。
**第二步:加入以下配置**
将 `sk-***` 替换为你的 Aihubmix 密钥后,添加到 `mcpServers` 对象中:
```text theme={null}
{
"mcpServers": {
"aihubmix-mcp-stdio": {
"command": "npx",
"args": ["-y", "@aihubmix/mcp"],
"env": {
"AIHUBMIX_API_KEY": "sk-***"
}
}
}
}
```
> 如果文件已有其他 MCP 配置,只需把 `aihubmix-mcp-stdio` 这段加进 `mcpServers` 里,注意保持 JSON 格式正确(上一项末尾加逗号)。
**第三步:重启 Claude Desktop**
完全退出后重新打开,在对话界面底部工具栏应出现 🔨 图标,点击可确认 `aihubmix-mcp-stdio` 已连接。
头像 → Settings → Developer → Edit Config → 加入以下配置
```shell theme={null}
"aihubmix-mcp-stdio": {
"command": "npx",
"args": ["-y", "@aihubmix/mcp"],
"env": {
"AIHUBMIX_API_KEY": "sk-***"
}
}
```
### 安装到 Warp AI
**第一步:打开 MCP 配置入口**
点击右上角头像 → **Settings** → **AI** → **Manage MCP Servers** → **Add**
**第二步:加入以下配置**
将 `sk-***` 替换为你的 Aihubmix 密钥:
```text theme={null}
{
"aihubmix-mcp-stdio": {
"command": "npx",
"args": ["-y", "@aihubmix/mcp"],
"env": {
"AIHUBMIX_API_KEY": "sk-***"
},
"working_directory": null
}
}
```
**第三步:保存并重启 Warp**
保存配置后重启 Warp,在 AI 对话中即可使用图片生成功能。
> **前提条件:** 需已安装 Node.js(`node -v` 确认版本 ≥ 18)。Warp 下载:[warp.dev](http://warp.dev)
## 2️⃣ 使用
1. 使用自然语言输入,指定 mcp 和目标,比如:
```shell prompt theme={null}
使用 aihubmix mcp 绘制一只可爱小猫在花园里玩耍,Pixar 3d 卡通风格,3:2,, 自动为我优化 prompt 并执行
```
Claude Desktop 使用示例:
2. 可以指定目标模型,比如 flux-kontext-max、ideogram/V3 等,不需要精确对应,LLM 会自动匹配关键字眼
3. 指定更多参数,比如
```shell prompt theme={null}
影视光、低视角、模型 V3,生成 2 张
```
***
更新时间:2026-06-01
# AnythingLLM
Source: https://docs.aihubmix.com/cn/clients/AnythingLLM
在 AnythingLLM 中接入 AIHubMix:用单个 API Key 为本地私有 RAG 知识库统一接入对话与 Embedding 模型。
**AnythingLLM** 是由 [Mintplex Labs](https://mintplexlabs.com/) 开发的**开源全栈 AI 应用**(MIT 协议),核心定位:**把任何文档变成可以对话的知识库**。
它有三种产品形态:
* **桌面端 AI 客户端**——像 ChatGPT 客户端一样开箱即用,本地存储
* **私有 RAG 系统**——上传 PDF/Word/网页,AI 基于这些文档回答你的问题
* **多用户协作平台**(Docker 自托管)——团队共享知识库 + 权限管理
| 维度 | 详情 |
| :--------- | :---------------------------------------------------------------------------------- |
| **官网** | [anythingllm.com](http://anythingllm.com) |
| **GitHub** | [Mintplex-Labs/anything-llm](https://github.com/Mintplex-Labs/anything-llm)(40k+ ⭐) |
| **协议** | MIT,完全开源 |
| **支持平台** | 桌面端:macOS / Windows / Linux;服务端:Docker |
| **价格** | 桌面版完全免费;Docker 自托管免费;云服务可选付费 |
### 核心能力清单
* **多格式文档导入**:PDF、Word、Excel、CSV、纯文本、Markdown、代码文件、整个网站
* **Workspace 机制**:每个工作区是独立知识库,文档/对话/模型互不污染
* **多模型 LLM 支持**:OpenAI、Anthropic、Google、Azure、AWS Bedrock、Ollama、LM Studio,以及任意 OpenAI 兼容端点( **AIHubMix 入口**)
* **多 Embedder 支持**:OpenAI、Cohere、Voyage、本地模型(如 nomic-embed-text、bge-m3)
* **内置向量数据库**:默认 LanceDB(零配置),也可接 Pinecone、Chroma、Weaviate、Qdrant 等
* **Agent 能力**:在 RAG 之外让模型调用工具——网页抓取、SQL 查询、自定义脚本
* **API 服务**:暴露 OpenAI 兼容接口,可被 n8n、Make、Raycast 等工具反向调用
AnythingLLM 把文档解析、向量化、检索、对话全部在你自己的电脑上完成,**只有"被检索到的少量片段"会发给 LLM 厂商**。这是 RAG 工具区别于聊天客户端的本质——**数据主权 + 文档级精准检索**。
***
## AnythingLLM 在 RAG 工具谱里的位置
| 工具 | 定位 | 适合谁 |
| :------------------------- | :---------------- | :---------------------- |
| **LangChain / LlamaIndex** | RAG 框架(写代码) | 开发者,要从 0 搭流水线 |
| **Dify / FastGPT** | RAG 平台(可视化工作流) | 需要 Agent 编排、多步骤工作流的中小团队 |
| **AnythingLLM** | **开箱即用的 RAG 客户端** | 想直接传文档对话、不想搭建后端的个人或团队 |
| **Ollama + Open WebUI** | 纯本地 LLM 推理界面 | 想完全离线、不接 API 的极客 |
AnythingLLM 的核心卖点:**装好就能用**。下载桌面版,首次启动 5 分钟就能完成"上传 PDF → 提问"的完整流程。它内置了向量库(LanceDB)、文档解析器、Embedder 调用器、Workspace 隔离机制——你只需要选一个 LLM Provider 和一个 Embedder Provider。
## 通用配置方法
先从 [AnythingLLM 官网](https://anythingllm.com/) 下载并安装桌面版。进入应用后,打开左下角头像菜单,在设置页里找到 LLM 配置入口。
打开设置页后,先点击 **LLM Provider** 下拉框,在列表中选择 **Generic OpenAI**,下图对应的就是这一步。这个选项用于接入 OpenAI 兼容接口,AIHubMix 可以直接按这种方式配置。
按下面的方式填写连接信息:
* **Base URL** 填写:
```text theme={null}
https://aihubmix.com/v1
```
如遇当前 API 主地址不可用,可将此处域名替换为备用地址 `https://api.inferera.com`,路径保持不变。
* **API Key** 填写你在 [AIHubMix 控制台](https://aihubmix.com/token) 创建的 Key。
* **Chat Model Name** 填写要使用的模型 ID,例如 `gpt-4o-mini`、`claude-haiku-4-5` 等。模型 ID 建议从 AIHubMix 模型广场复制,避免手动输入出错。
* **Token context window** 和 **Max Tokens** 可以按模型能力调整;如果不确定,先使用默认值,确认能正常对话后再按需要增大。
保存配置后,回到对话页面选择刚配置的模型,发送一条简单消息确认是否能正常回复。
在这个位置也可以快速切换 AIHubMix 支持的其他模型。需要更换模型时,直接从下拉菜单选择已配置的模型即可。
## 非 OpenAI 模型使用方法
模型服务商选择 Generic OpenAI 不变,在 Chat Model Name 一栏手动修改所需模型名称即可。\
在 AIHubMix 模型列表中复制需要使用的模型 ID,填入 Chat Model Name 即可。
### Docker 部署给团队用
桌面版是单机使用,团队需要 [AnythingLLM Docker 镜像](https://hub.docker.com/r/mintplexlabs/anythingllm)。Docker 版本的核心区别:
* 多用户登录,管理员可控权限
* Workspace 可在用户间共享(只读/可写)
* 文档解析、向量化运行在服务端
* LLM 与 Embedder 配置由管理员统一管理——**也就是说,只要管理员配好一个 AIHubMix Key,全团队成员都能用**
```text theme={null}
docker run -d -p 3001:3001 \
-v anythingllm_storage:/app/server/storage \
--name anythingllm \
mintplexlabs/anythingllm
```
访问 `http://localhost:3001`,登录后在系统设置里按上文配置 AIHubMix 即可。
***
## 常见故障排查
**问题:文档上传了,提问时模型说"找不到相关信息"**
90% 的情况是 Embedder 没配置好,或者 chunk size 太大。检查:
1. Embedder 是否真的设置成了向量模型(不是 Chat 模型)
2. 文档是否真的被向量化(在 Workspace 设置里看 "Pinned Documents" 列表)
3. 提问时是否在正确的 Workspace 里(每个 Workspace 文档独立)
**问题:配置完之后,Chat 模型回 401 或 model not found**
按概率排查:
1. `Generic OpenAI` 选对了吗?选成 `OpenAI` 会忽略 Base URL
2. Base URL 是 `https://aihubmix.com/v1`(带 `/v1`),不要漏
3. Chat Model Name 与 AIHubMix 实际支持的模型 ID 一致(去 `aihubmix.com` 复制)
4. AIHubMix 余额是否充足
**问题:回答速度慢,经常卡住**
* 检查模型是不是 `gpt-5` / `o3` / `deepseek-reasoner` 这种推理模型——RAG 场景下确实需要推理时,慢是正常的;只是问"文档里 X 是什么"这种简单检索,换成 `gpt-4o-mini` 或 `claude-haiku-4-5` 立刻就快
* 检查 Token context window 是否设太大,导致每次请求要塞海量上下文
**问题:中文文档检索效果不好**
* 检查 Embedder——`text-embedding-3-small` 对中文已经不错,但本地 `bge-m3` 对中文更优
* 检查 chunk 大小——中文建议 chunk size 设为 300–500 字符,过大会稀释相关性
* 检查文档质量——PDF 表格、扫描件需要先 OCR
**问题:想给团队用,但不想每个人都管 API Key**
使用 Docker 自托管版,管理员配 Key,用户登录即用。
***
## 参考资料
* AnythingLLM 官网:[anythingllm.com](https://anythingllm.com/)
* AnythingLLM 文档:[docs.anythingllm.com](https://docs.anythingllm.com/)
* AIHubMix 模型列表与 Key 管理:[aihubmix.com](https://aihubmix.com/)
* AnythingLLM Docker Hub:[hub.docker.com/r/mintplexlabs/anythingllm](https://hub.docker.com/r/mintplexlabs/anythingllm)
***
更新时间:2026-07-03
# Avante.nvim
Source: https://docs.aihubmix.com/cn/clients/Avante.nvim
在 Avante.nvim 中接入 AIHubMix:在 Neovim 编辑器里用单个 API key 完成 AI 编程,自由切换模型。
## Avante.nvim 是什么
[Avante.nvim](https://github.com/yetone/avante.nvim) 是一款 Neovim 插件,作者 [yetone](https://github.com/yetone):**让 Neovim 用上 Cursor 的 AI 编程体验**。
它不是普通的 Copilot 替代品,而是把 Cursor 里这套 "Composer + Inline Edit + Diff Apply" 工作流完整搬进 Neovim:
* **Ask**(`aa`)——浮窗对话,可引用当前 buffer、选区、整个项目
* **Edit**(`ae`)——选中代码 → 自然语言描述改动 → 看 diff → 一键 apply
* **Suggest**——可选的内联自动补全(类似 Copilot)
* **Agentic Mode**——AI 自主执行 shell / 读写文件 / 跑 Python / 操作 Git
| 维度 | 详情 |
| :-------------- | :------------------------------------------------------------------------------------------------------------- |
| **GitHub** | [yetone/avante.nvim](https://github.com/yetone/avante.nvim)(17.9k ⭐,Apache 2.0) |
| **Neovim 版本要求** | ≥ 0.11.0 |
| **支持 Provider** | Claude / OpenAI / Azure / Gemini / Copilot / Ollama / Bedrock / Moonshot / **AIHubMix(一级支持)** / 任意 OpenAI 兼容端点 |
| **ACP 协议** | 可对接 Claude Code、Codex、Gemini CLI 等外部 Agent |
| **官方文档** | [yetone-avante-nvim.mintlify.app](http://yetone-avante-nvim.mintlify.app) |
***
## Avante vs CodeCompanion vs Copilot:Neovim
| 维度 | **Avante.nvim** | **CodeCompanion.nvim** | **GitHub Copilot** |
| :----------------- | :----------------------- | :--------------------- | :----------------- |
| **核心隐喻** | Cursor 的 Composer | Zed AI 的内联编辑 | 后台自动补全 |
| **交互形态** | 浮窗 + diff + apply | Buffer 流 + slash 命令 | 灰色 ghost text |
| **侵入程度** | 高(多浮窗、多 keybind) | 低(4 个命令搞定) | 极低 |
| **配置复杂度** | 中(需要 Rust 工具链 build) | 低(纯 Lua) | 极低 |
| **后端灵活度** | 全 LLM + ACP 协议 | 全 LLM + GitHub Models | 仅 Copilot 后端 |
| **多步推理任务** | ✅ Agentic Mode | ⚠️ 通过 slash 命令拼 | ❌ |
| **价格(走 AIHubMix)** | 按 token 计费 | 按 token 计费 | \$10/月订阅 |
| **适合谁** | 从 Cursor 迁移过来、要可视 diff 流 | 喜欢 Vim 化、buffer 流的人 | 只想要补全、不要对话 |
## 调用方式
```text theme={null}
opts = {
provider = "openai",
openai = {
endpoint = "https://aihubmix.com/v1",
model = "claude-3-5-sonnet-20240620",
temperature = 0,
max_tokens = 4096,
}
},
```
***
更新时间:2026-06-01
# ChatAll
Source: https://docs.aihubmix.com/cn/clients/ChatAll
ChatALL(齐叨)把同一个问题同时发送给 ChatGPT、Claude、Gemini、文心一言、通义千问、讯飞星火、Kimi、智谱清言等 40+ 大模型,多栏并排对比答案,几秒钟挑出最好的那一个。
完全免费 · 开源 · 数据本地存储 · 隐私安全
[⬇ 下载 Windows](https://github.com/ai-shifu/ChatALL/releases/latest) [⬇ 下载 macOS](https://github.com/ai-shifu/ChatALL/releases/latest) [⬇ 下载 Linux](https://github.com/ai-shifu/ChatALL/releases/latest) [★ GitHub 标星](https://github.com/ai-shifu/ChatALL)
***
使用下方的地址:
```text theme={null}
https://aihubmix.com/v1
```
## 核心功能
## 找到最佳 AI 回答,需要的功能这里全有
**🤖 并发对话 40+ 大模型**\
[ChatGPT](https://chat.openai.com/)(GPT5.5 )、[Claude](https://claude.ai/)(Opus 4.7、Sonnet 4.6)、[Gemini](https://gemini.google.com/)、[Copilot](https://copilot.microsoft.com/)、Llama、Mistral、[Perplexity](https://www.perplexity.ai/)、[文心一言](https://yiyan.baidu.com/)、[通义千问](https://tongyi.aliyun.com/)、[讯飞星火](https://xinghuo.xfyun.cn/)、[Kimi](https://kimi.moonshot.cn/)、[智谱清言](https://chatglm.cn/)、[豆包](https://www.doubao.com/)……一键全部召唤。
**📊 多栏并排对比**\
1 栏、2 栏、3 栏自由切换,高亮好答案,删掉差答案,谁更好一目了然。
**⚡ 快速提问模式**\
不用等慢模型,上一个还在输出就能问下一个,效率拉满。
**🔒 本地优先,隐私安全**\
聊天记录、设置、密码全部存在本地。我们没有服务器,看不到你的数据。
**🔑 自带 Key 或免费网页版**\
API 模式更快、无限速;网页版无需 Key,登录即用。 [→ 查看 API 配置教程](https://github.com/ai-shifu/ChatALL/wiki)
**📝 提示词管理**\
把你最好的 Prompt 保存下来,一键发给所有 AI。
**🎨 10 种语言、暗黑模式、快捷键**\
重度用户专属,`Ctrl + /` 唤起全部快捷键。
## 使用场景
**🔬 AI 研究者** —— 几分钟跑完模型 benchmark,不再用一上午对比。
**💻 应用开发者** —— 同一个 Prompt 跨模型调试,挑性价比最高的那个。
**✍️ 内容创作者** —— 一次拿到 5 个版本的草稿,自由重组。
**🎓 学生 / 研究生** —— 多源交叉验证,不被单一 AI 误导。
**👨💻 程序员** —— ChatGPT vs Claude vs Gemini 谁更会写代码,让它们打一架。
**🌐 跨境工作者** —— AI 翻译 6 个模型同时对比,挑最地道的那一版。
## 常见问题
**Q:ChatALL 收费吗?**\
A:完全免费,基于 [Apache 2.0 协议](https://www.apache.org/licenses/LICENSE-2.0)开源。如果你使用 OpenAI、Anthropic 等付费 API,费用直接付给模型厂商。
**Q:我的聊天记录会上传到服务器吗?**\
A:不会。ChatALL 没有自己的服务器,所有聊天记录、设置、密码都存在你本机。我们看不到你的任何数据。
**Q:ChatALL 支持哪些大模型?**\
A:40+ 模型,完整列表见 [GitHub README](https://github.com/ai-shifu/ChatALL#supported-bots)。
**Q:ChatALL 和 Poe 有什么区别?**\
A:Poe 是 Quora 的付费聚合服务,需要订阅,数据在他们服务器。ChatALL 是开源桌面应用,完全免费,数据全部本地存储,你用自己的 API Key 或账号。
**Q:ChatALL 是开源的吗?**\
A:是。代码托管在 [GitHub](https://github.com/ai-shifu/ChatALL),Apache 2.0 协议,你可以审查、修改、贡献代码。 [→ 提交 Issue / PR](https://github.com/ai-shifu/ChatALL/issues)
--------------------------------------------------------------------------------------------------------------------------------------------------
更新时间:2026-06-01
# Chatbox
Source: https://docs.aihubmix.com/cn/clients/ChatBox
在 Chatbox 中配置 AIHubMix 的 OpenAI 兼容接口,并添加和使用 AIHubMix 模型。
Chatbox 是一款开源桌面 AI 客户端。通过 OpenAI Provider 配置 AIHubMix 后,可以在 Chatbox 中使用 AIHubMix 支持的模型。
下载链接:[Chatbox GitHub Releases](https://github.com/Bin-Huang/chatbox/releases)
## 准备工作
* 安装并打开 Chatbox。本文教程基于 Chatbox `1.21.1`。
* 在 [AIHubMix 控制台](https://aihubmix.com/token) 创建 API Key,格式通常为 `sk-***`。
* 准备要使用的模型 ID,例如 `gpt-5.6-terra`。模型 ID 建议从 AIHubMix 模型列表复制,避免手动输入错误。
## 通过界面配置 AIHubMix
### 1. 打开模型提供商设置
在 Chatbox 左下角点击 **Settings**,进入 **Model Provider**。
在中间栏选择 **OpenAI**。
### 2. 填写 API Key 和 API Host
填写在 AIHubMix 控制台创建的 API Key,并将 **API Host** 设置为完整的 Chat Completions 地址:
```text theme={null}
https://aihubmix.com/v1/chat/completions
```
如果主地址暂时不可用,使用备用地址:
```text theme={null}
https://api.inferera.com/v1/chat/completions
```
填写后可点击 **Check** 检查连通性。
### 3. 添加模型
在 **Model** 区域点击 **New**。已有模型会显示在同一区域,点击右侧齿轮图标可以再次编辑。
在弹窗中填写模型信息:
* **Model ID**:填写 AIHubMix 模型 ID,例如 `gpt-5.6-terra`。
* **Nickname**:填写便于识别的名称,例如 `gpt-5.6-terra-aihubmix`。
* **Model Type**:选择 **Chat**。
* **Capabilities**:按模型能力勾选。模型支持图片输入时勾选 **Vision**,需要工具调用时勾选 **Tool use**,推理模型可勾选 **Reasoning**。
* **Context Window** 和 **Max Output Tokens**:没有特殊要求时可以留空,使用默认值。
点击 **Test Model**,测试成功后点击 **Save**。
### 4. 选择模型并开始对话
回到 Chatbox 主界面,点击输入框右下角的模型名称。在模型选择器中搜索刚才设置的昵称并选中。
发送一条简单消息。能正常收到回复,说明配置已经生效。
## 批量导入模型配置
Chatbox `1.15.1` 及以上版本支持导入 JSON 格式的模型提供方配置。需要一次添加预设模型时,可以复制下面的 OpenAI 兼容配置,再在 Chatbox 的模型提供方配置中导入。
```json theme={null}
{
"id": "aihubmix",
"name": "AIHubMix",
"type": "openai",
"iconUrl": "https://assets.aihubmix.com/docs/favicon.svg",
"urls": {
"website": "https://aihubmix.com/",
"getApiKey": "https://aihubmix.com/token",
"docs": "https://docs.aihubmix.com/",
"models": "https://aihubmix.com/models"
},
"settings": {
"apiHost": "https://aihubmix.com/",
"apiPath": "/v1/chat/completions",
"models": [
{
"modelId": "gpt-5.6-terra",
"nickname": "gpt-5.6-terra-aihubmix",
"type": "chat",
"capabilities": ["vision", "reasoning", "tool_use"],
"contextWindow": 1050000,
"maxOutput": 128000
}
]
}
}
```
导入后仍需在 Chatbox 中填写自己的 API Key。需要添加更多模型时,推荐通过上面的界面配置方式逐个添加,这样可以按模型能力设置 **Vision**、**Reasoning** 和 **Tool use**。
## 常见问题
**API Host 应该填到哪里?**
Chatbox 的 OpenAI Provider 需要填写完整地址 `https://aihubmix.com/v1/chat/completions`,不是只填域名或 `/v1`。
**模型测试失败怎么办?**
检查 API Key 是否完整、API Host 是否为完整的 Chat Completions 地址,以及 Model ID 是否与 AIHubMix 模型列表一致。主地址暂时不可用时,可改用 `https://api.inferera.com/v1/chat/completions`。
**导入配置后没有模型怎么办?**
重新打开模型选择器并搜索模型昵称。若仍未显示,使用“通过界面配置 AIHubMix”的方式添加模型。
更新时间:2026-07-15
# NextChat
Source: https://docs.aihubmix.com/cn/clients/ChatGPT-Next-Web
在 NextChat(ChatGPT Next Web)中接入 AIHubMix:一键部署你的私人 AI 助手,用单个 API key 跨厂商调用模型。
我们以 ChatGPT Next Web 的演示站点为例。
NextChat(原名 ChatGPT-Next-Web,简称 ChatGPT Next Web)是目前最流行的开源 AI 聊天客户端之一,在 GitHub 上拥有 88,000+ 星标、59,700+ Fork。
它的核心定位是:轻量、极速、隐私优先、跨全平台。
一个 NextChat,就是你的私人多模型 AI 工作站。
## 通常使用情况(使用 OpenAI 模型)
* API key 输入[本站的 Key](https://aihubmix.com/token)
* 接口代理地址,直接输入下方的网址:
```text theme={null}
https://aihubmix.com
```
然后即可开始使用。
## 特殊情况(使用其他非 OpenAI 模型)
如果像在 Next Web 客户端使用其他非 OpenAI 模型,那么请按以下步骤。\
首先确保你已经升级到最新版本(v2.13.0)。在这个版本中,增加了自定义模型的方式:
1. **输入自定义模型名**:
* 由于 Next Web 客户端会根据输入的模型名称自动判断模型服务商,而本网站提供的 key 只适用于 OpenAI 接口。
* 所以在输入自定义模型名时,格式应为:“+‘想使用的模型名字’@OpenAI”。
* 例如,若要使用 gemini-pro 模型,自定义模型名输入:“+gemini-pro\@OpenAI”。
* 通过这种方式,可以把模型服务商手动指向 OpenAI。
2. **确认选择**:
* 在选择模型界面,确认手动添加的模型(OpenAI)出现在下方。\
***
更新时间:2026-06-01
# ChatHub
Source: https://docs.aihubmix.com/cn/clients/ChatHub
ChatHub 是一款多模型 AI 聚合平台,致力于解决很多 AI 用户都会遇到的问题:如何判断当前模型给出的答案是否足够好?
通过 ChatHub,你可以一次提问,让 20+ 个主流大模型同时回答,包括 OpenAI 的 GPT-5.5、Anthropic 的 Claude 4.5、Google 的 Gemini 3、Meta 的 Llama 3.3、xAI 的 Grok、DeepSeek 等。多个答案并排展示,可以直观对比、择优而用,有效规避单一模型的幻觉与偏见。
## 安装 ➕ 配置 AIHubMix
1. 通过 Chrome Web Store 安装 ChatHub 插件:[ChatHub - ChatGPT, Gemini, Claude sidebar](https://chromewebstore.google.com/detail/chathub-chatgpt-gemini-cl/iaakpnchhognanibcahlpcplchdfmgma?utm_source=chathub.gg)
2. 打开 ChatHub 后,点击左下角齿轮进入设置页。在设置中找到 **Use your own API key** 区域,开启 **OpenAI**,然后点击 **configure**。
3. 在弹窗中填写 AIHubMix 的连接信息:
* **API Key**:填写你在 [AIHubMix 控制台](https://aihubmix.com/token) 创建的 Key,格式通常为 `sk-***`。
* **API Host**:填写 AIHubMix 地址,默认使用 `https://aihubmix.com`;如遇当前 API 主地址不可用,可改用备用地址 `https://api.inferera.com`,路径保持不变。
```text theme={null}
https://aihubmix.com
```
* **Model**:选择或填写要使用的模型,例如 `gpt-5.5`。确认无误后点击 **Confirm**,再回到设置页点击 **Save changes** 保存。
4. 回到 ChatHub 主页面后,可以在左侧看到已启用的 AIHubMix 配置,并在对话区发送一条简单消息验证效果。
### 用户口碑
> ⭐ 5.0 / 5.0,1,000+ 评价\
> 👥 30 万+ 活跃用户\
> 💬 "选 LLM 的 game changer"——来自真实用户评价
### ChatHub 还能做什么?
除了多模型并排对比,ChatHub 还集成了一系列效率功能:
· AI 图像生成:集成 FLUX.2、Stable Diffusion、Nano Banana\
· 文件分析:上传 PDF、Excel、Word、图片让 AI 解读\
· 联网搜索:实时获取最新信息\
· 代码预览:语法高亮 + 实时运行\
· 提示词库:精选场景化 Prompt 模板\
· 翻译、总结、写作:一键工具栏
全平台覆盖:Web 网页、Chrome 插件、Edge 插件、iOS、Android、Windows、Mac,数据云端同步。
### 常见问题(FAQ)
Q1:ChatHub 收费吗?\
A:基础功能免费,高级订阅可解锁更多并发模型和增强功能。但 API 调用费用是单独的,这部分通过 AIHubMix 充值,按量扣费,不用月度订阅。
Q2:ChatHub 和 ChatALL 哪个好?\
A:ChatHub 是浏览器插件 + 跨平台云同步,适合多设备办公;ChatALL 是桌面应用、本地存储,适合隐私敏感场景。两者都支持选择 AIHubMix。
Q3:配置后没反应怎么办?\
A:检查三件事:① API Key 是否正确(以 `sk-` 开头);② API Host 是否填写为 `https://aihubmix.com`(不要带结尾斜杠);③ AIHubMix 账户余额是否充足。
更新时间:2026年7月3日
# Chatx
Source: https://docs.aihubmix.com/cn/clients/Chatx
## 一、ChatX 是什么
[**ChatX - AI Chat Client**](https://apps.apple.com/app/id6446304087) 是 **6X Studio** 开发的原生 Apple 平台 AI 客户端。它不是某一家模型厂的客户端,而是一个**多供应商聚合器**——把 OpenAI、Anthropic、Google、DeepSeek、Qwen、Perplexity、Groq、Kimi、Azure 等十几家模型源全部整合在一个 App 里。
| 维度 | 详情 |
| :--------------- | :-------------------------------------------------------------------------------------------------------- |
| **开发者** | 6X Studio([6x.studio/chatx](http://6x.studio/chatx)) |
| **支持平台** | iPhone (iOS 15+) · iPad · Mac (macOS 12+) · **Apple Vision Pro** |
| **App Store 评分** | ⭐ 4.6 / 5(482 评分) |
| **价格模式** | 免费下载 + 内购(Pro \$4.99 · 也可按 Word Pack 按量付费) |
| **隐私** | 开发者声明:不收集任何用户数据 |
| **多语言** | 简中、繁中、英、日、韩、法、德 等 17 种 |
| **支持模型** | GPT-4o / GPT-5 · Claude · Gemini · DeepSeek V3/R1 · Qwen · Perplexity · Groq · Kimi · Azure · **自定义 API** |
**与其他 AI 客户端的差异:**
* ✅ **Vision Pro 原生支持**——目前少数几款 visionOS AI 客户端之一
* ✅ **iCloud 同步**——iPhone 上的对话,打开 Mac 就在
* ✅ **Siri 快捷指令 + URL Schemes**——可与 Apple 自动化生态深度集成
* ✅ **锁屏小组件**——iOS 16+ 一键直达
* ✅ **TTS 朗读**——自动识别语种、可调语速
* ✅ **图像生成**(Beta)+ **改写翻译** + **语音输入**
***
## 二、配置 AIHubMix API Key
1. 打开设置,在设置中找到 API Server Config。\
2. 选择 OpenAPI。\
3. 上方 API KEY 一栏从[本站的Key](https://aihubmix.com/token)中生成。
4. 下方 API SERVER 填:
```text theme={null}
https://aihubmix.com
```
## 三 、场景化模型选型:哪个任务用哪个模型?
ChatX 是个全能 AI 客户端,不同任务的最优模型完全不同。
| 使用场景 | 首选 | 备选 | 不推荐 |
| :------------- | :--------------------------------- | :---------------------------- | :----------------- |
| **日常聊天 / 问答** | `gpt-4o-mini` · `claude-haiku-4-5` | `deepseek-chat` | o 系列(过度思考) |
| **写作 / 文案** | `claude-sonnet-4-6` | `gpt-4o` | — |
| **代码 / 调试** | `claude-sonnet-4-6` | `gpt-5` · `deepseek-reasoner` | `gpt-4o-mini` |
| **数学 / 逻辑推理** | `gpt-5` · `o3` | `deepseek-reasoner` | 非推理模型 |
| **翻译(划词级短文本)** | `gpt-4o-mini` · `claude-haiku-4-5` | `qwen-turbo` | ⚠️ o 系列 / GPT-5 系列 |
| **长文档阅读 / 总结** | `gemini-2.5-pro` | `claude-sonnet-4-6` | — |
| **图像识别 / OCR** | `gpt-4o` · `gemini-2.5-flash` | `claude-sonnet-4-6` | 纯文本模型 |
### ⚠️ 翻译场景特别提示
如果你主要拿 ChatX 当**翻译工具**用(Apple 全家桶生态里很多人这么用),**不要选 o 系列(**`o1`**/**`o3`**/**`o4-mini`**)或 GPT-5 系列**。原因有三:
1. 它们是**推理型模型**,输出前会先"想很久",翻译一句话经常 5–30 秒
2. **thinking tokens 也计费**,按量付费的话单次成本能到 GPT-4o 的 5–20 倍
3. 翻译这种确定性任务不需要推理,反而容易**画蛇添足**——把"Hello world"翻译出三段解释
***
## 四、ChatX 进阶玩法(Apple 生态专属)
### 1. iCloud 同步:iPhone 起头,Mac 续写
ChatX 默认开启 iCloud 同步,**对话历史 + Prompt 收藏 + API 配置**都跨设备共享。配一次 AIHubMix,全设备同步生效。
### 2. Siri 快捷指令 / URL Schemes
ChatX 暴露了 URL Scheme 入口,可以从快捷指令直接喂入文本:
```text theme={null}
chatx://chat?text=帮我把这段翻译成英文:{{剪贴板}}
```
把这条做成"对剪贴板内容做 X"的快捷指令,Siri 一句话就能调起。
### 3. 锁屏小组件
iOS 16+ 锁屏小组件 → ChatX 一键开聊。地铁上掏出手机 0.5 秒进入对话。
### 4. Vision Pro 沉浸式 AI
ChatX 是少数原生支持 visionOS 的 AI 客户端,戴着 Vision Pro 工作时可以浮窗常驻——边看资料边对话。
### 5. 多模型 A/B 对比
通过 ChatX 的快速切换菜单,同一句 Prompt 在 `gpt-4o` 和 `claude-sonnet-4-6` 各回一遍,肉眼比对哪个更顺。这种对比在按月订阅的客户端里成本极高,在 AIHubMix 按量付费的模式下随便玩。
***
## 五、常见问题(FAQ)
**Q1:API Base URL 填** `https://aihubmix.com `**还是** `https://aihubmix.com/v1`**?**\
A:ChatX 推荐填 `https://aihubmix.com/v1`(带 `/v1`),与 OpenAI 官方接口路径一致。如果报错可以两种都试。
**Q2:ChatX 自带的 Words Pack 和接 AIHubMix 哪个划算?**\
A:偶尔聊一聊 → Words Pack 省事。日均超过 20 次对话 → 直接 AIHubMix,便宜数倍且模型自由。
**Q3:iCloud 同步会泄露我的 API Key 吗?**\
A:ChatX 的 iCloud 同步走 Apple 私有容器,且开发者声明零数据收集。Key 仅在你的 Apple ID 设备间同步,不经过第三方服务器。
**Q4:能用 Claude 和 Gemini 吗?AIHubMix 不是只代理 OpenAI?**\
A:能。AIHubMix 把所有模型都封装为 OpenAI 兼容格式,你只要在 ChatX 的"模型 ID"字段填 `claude-sonnet-4-6` 或 `gemini-2.5-pro`,请求就会自动路由到对应供应商。
**Q5:Vision Pro 上用起来流畅吗?**\
A:原生 visionOS 应用,启动 \< 1 秒。配合眼动 + 手势输入,长对话体验比 iPad 还好。
**Q6:能在 Mac 上用吗?是 Catalyst 还是原生?**\
A:原生 macOS 应用(非 Catalyst 套壳),支持菜单栏快捷操作和原生快捷键。
***
## 相关链接
* 📱 ChatX App Store:[apps.apple.com/app/id6446304087](https://apps.apple.com/app/id6446304087)
* 🌐 ChatX 开发者主页:[6x.studio/chatx](https://6x.studio/chatx/)
* 🔑 AIHubMix 注册 / 模型列表:[aihubmix.com](https://aihubmix.com/)
* 🐦 ChatX 官方 X(Twitter):[@AppChatX](https://twitter.com/AppChatX)
最新更新日期:2026年5月12日
# Cherry Studio
Source: https://docs.aihubmix.com/cn/clients/Cherry-Studio
在 Cherry Studio 桌面客户端中接入 AIHubMix,调用 Claude、GPT、Gemini 等模型,并为 Claude 开启提示词缓存以降本提速。
Cherry Studio 是一款**多模型桌面 AI 客户端**,支持同时接入多个 AI 服务商(OpenAI、Claude、Gemini、AIHubMix等),在一个界面里统一管理和使用。
项目简介:[https://docs.cherry-ai.com/](https://docs.cherry-ai.com/)
**核心功能:**
* 多模型自由切换,对比不同 AI 的回答
* 支持 MCP 扩展,接入外部工具和服务
* 内置知识库、助手管理、对话历史
* 支持 Markdown 渲染、代码高亮、文件上传
## [**Cherry Studio AI 下载地址**](https://easys.run/cherry-studio/)
## 配置AIHubMix Api Key
1. 应用右上角打开设置-模型服务
2. 在模型供应商界面选择我们的 AIHubMix—点击获取密钥—跳转链接—返回copy Api Key AIHubMix 提供包括 `GPT 5.5`、`Claude Opus 4.6`、`DeepSeek v4 Pro` 等主流大模型在内的 800+ 模型,另外还提供 26+ 免费模型。
3. 模型选择两种方式 : 下拉选择模型
点击 “+” 添加模型,模型 ID 从本网站的设置界面选择想要使用的模型复制粘贴
API 密钥一栏输入[本站的 Key](https://aihubmix.com/token),API 地址一栏不用修改。\
**注:如果检查不通过尝试关闭 vpn**
## 开始使用
## 常见问题
### 模型提示看不到图片
一些新模型可能遇到输入图片后模型看不到的问题。需要在设置页面手动勾选图像选项。
gemini-3-pro-image-preview 模型在流式输出模式下无法返回图片,使用时请关闭流式输出。
### 调用 Claude 模型返回错误 AI\_APICallError
需要检查报错信息中的请求路径是否为`https://aihubmix.com/anthropic/v1/messages`,若是,则在设置中将 Anthropic API Host 修改为`https://aihubmix.com`
## 启用 Claude 提示词缓存
在 Aihubmix 供应商的「API 设置」(供应商名称右侧齿轮)里,配置「缓存 Token 阈值」「缓存系统消息」「缓存最后 N 条消息」即可为 Claude 模型自动注入 `cache_control`。各项含义与命中要点见 [Claude 提示词缓存](../api/Claude-Cache)。
最新更新日期:2026年5月11日
# Cline
Source: https://docs.aihubmix.com/cn/clients/Cline
在 Cline 中接入 AIHubMix:这款 VS Code / JetBrains AI 编码 Agent 用单个 API key 即可跨厂商调用模型。
> Cline 即原来的 **Claude Dev**,是目前 GitHub Star 数最高的开源 AI 编码 Agent 之一。它默认深度适配 Claude 模型,可直接读写多文件、执行终端命令、操控浏览器,是 Cursor / Claude Code 的开源替代方案。
>
> 本文带你从 0 开始,**3 分钟内**完成 Cline 安装并接入 AIhubmix,调用 Claude Opus 4.7 / Sonnet 4.6 与 GPT-5.5 等全部主流模型。
***
## 下载并安装 Cline 插件
### 官方下载渠道一览
| 平台 | 下载地址 | 适用 IDE |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
| VS Code Marketplace | [https://marketplace.visualstudio.com/items?itemName=saoudrizwan.claude-dev](https://marketplace.visualstudio.com/items?itemName=saoudrizwan.claude-dev) | VS Code |
| Open VSX Registry | [https://open-vsx.org/extension/saoudrizwan/claude-dev](https://open-vsx.org/extension/saoudrizwan/claude-dev) | Cursor、Windsurf、VSCodium |
| JetBrains Marketplace | [https://plugins.jetbrains.com/(搜索](https://plugins.jetbrains.com/\(搜索)`Cline`) | IntelliJ、PyCharm、WebStorm、GoLand 等 |
| Cline 官网 | [https://cline.bot/](https://cline.bot/) | 各平台入口聚合 |
| GitHub Releases | [https://github.com/cline/cline/releases](https://github.com/cline/cline/releases) | 手动下载 `.vsix` 离线安装 |
> **认准官方版**:作者(Publisher)显示为 **Cline / saoudrizwan**,插件 ID 为 `saoudrizwan.claude-dev`,这是它从 Claude Dev 时代沿用至今的官方标识。
### 方式 A:在 VS Code 中安装(推荐)
1. 打开 VS Code,左侧活动栏点击 **Extensions** 图标(或按 `Cmd/Ctrl + Shift + X`)。
2. 搜索框中输入 `Cline`。
3. 找到作者为 **Cline** 的插件(ID:`saoudrizwan.claude-dev`),点击 **Install**。
4. 安装完成后,VS Code 左侧活动栏会新增一个 Cline 图标,点击即可打开侧边面板。
### 方式 B:在 Cursor / Windsurf 中安装
Cursor 与 Windsurf 兼容 VS Code 扩展协议,但默认使用 Open VSX 源:
1. 打开内置 Extensions 面板,搜索 `Cline`。
2. 安装作者为 **saoudrizwan** 的版本即可。
3. 如搜索不到,可前往 [Open VSX](https://open-vsx.org/extension/saoudrizwan/claude-dev) 下载 `.vsix` 后手动拖入安装。
### 方式 C:在 JetBrains 全家桶中安装
1. 打开 `Settings / Preferences → Plugins → Marketplace`。
2. 搜索 `Cline`,点击 **Install**。
3. 重启 IDE 后,右侧工具栏可见 Cline 面板。
### 方式 D:离线安装(企业内网场景)
1. 前往 [GitHub Releases](https://github.com/cline/cline/releases) 下载最新版 `.vsix` 文件。
2. VS Code 中按 `Cmd/Ctrl + Shift + P` 打开命令面板。
3. 执行 `Extensions: Install from VSIX...`,选择刚下载的文件即可。
## 配置 AIHubMix Api Key
* 下载插件,进入设置页面。
* API Provider 一栏选择 OpenAl Compatible。
* Base URL 一栏输入:
```text theme={null}
https://aihubmix.com/v1
```
* API Key 一栏从[本站的 Key](https://aihubmix.com/token)中生成。
* 输入模型名后保存设置即可使用。
* **注:模型名称建议从本站设置页面复制粘贴。图片示例为 claude-3-5 模型,gpt-4o 也可以使用。**
## 首次运行测试
回到 Cline 主面板,在输入框中粘贴以下测试 Prompt:
列出当前项目根目录下的所有文件, 然后用一句话总结这是一个什么类型的项目。
如果配置正确,Cline 会:
1. 调用 `list_files` 工具读取目录
2. 在面板中展示文件树
3. 由 Claude 生成项目描述
整个流程无报错,即代表接入成功,可以开始正式使用。
***
## 推荐的初始优化设置
### 1. 开启 Plan / Act 双模式
在面板底部模式切换按钮中:
* **Plan Mode**:复杂任务先让 Claude 出方案,审阅后再执行
* **Act Mode**:简单任务直接执行
养成"先 Plan 后 Act"的习惯,可显著减少返工。
### 2. 配置 `.clinerules`
在项目根目录创建 `.clinerules` 文件,写入项目规约,例如:
所有 API 路由必须用 Zod 校验入参 数据库操作走 Drizzle,禁止裸 SQL 提交前跑 pnpm typecheck && pnpm test 注释只写"为什么",不写"是什么"
Claude 会自动遵守这些规则,无需每次重复提醒。
### 3. 启用 Auto-Approve(可选)
熟悉 Cline 后,可在设置中勾选低风险操作自动审批(如 `Read Files`、`List Directory`),减少弹窗打断,但**写文件与执行命令建议始终保持手动审批**。
***
## 常见问题
### Q1:为什么连接失败,提示 401 / 403?
* 检查 API Key 是否完整复制(包含 `sk-` 前缀)
* 检查 Base URL 末尾是否多了 `/`,正确格式是 `https://aihubmix.com/v1`
* 确认 AIhubmix 账户有余额
### Q2:模型名报错 "model not found"?
请从 [AIhubmix 模型列表](https://aihubmix.com/models) 复制完整 ID,不要手输或简写。
### Q3:为什么 Cline 在我这里调用很慢?
* 优先选 `claude-sonnet-4-6`,响应速度比 Opus 快 2-3 倍
* 大型项目务必在 `.clinerules` 加 ignore 规则,屏蔽 `node_modules`、`dist`
### Q4:可以同时配置多个 Provider 吗?
可以。Cline 支持配置多套 API,在面板顶部一键切换,适合做模型对比测试。
### Q5:Cline 插件 ID 为什么还叫 `claude-dev`?
Cline 前身就是 Claude Dev,作者为保留社区评价与安装基数,沿用了原 Marketplace ID,这也是它"Claude 基因"的官方背书。
***
## MCP (Model Context Protocol) 支持
Cline 支持通过插件安装 MCP Client 服务。
> 支持的 MCP 可以通过 [Cline MCP-marketplace](https://cline.bot/mcp-marketplace) 查询
***
## 按开发阶段的模型选择建议
软件开发的不同阶段对 AI 能力的要求各不相同。选择合适的模型,可以在需求分析、编码、测试与部署的各个阶段提升效率。
### 设计与架构阶段
该阶段更依赖模型的抽象推理、系统设计能力和领域知识,适合选择具备强推理与规划能力的模型。
* `o1`
* `gemini-2.5-pro`
### 开发阶段
该阶段需要模型在代码生成、模式理解、函数补全、调试建议方面表现稳定,适合选择综合代码能力强的模型。
* `gemini-2.5-pro`
* `claude-sonnet-4-5`
* `gpt-5`
* `coding-glm-4.6`(高性价比)
* `qwen3-coder-plus`
### 测试阶段
该阶段更关注边界条件、稳健性、异常流程与用例生成,适合选择擅长代码分析与推理的模型。
* `claude-3-7-sonnet`
* `o3` / `o4-mini`
* `gpt-5`
### 部署与审查阶段
该阶段需要模型具备较大的上下文窗口,以理解完整代码库,从而进行审查、重构建议或部署验证。
* `gemini-2.5-pro`
* `gpt-5`
* `o3` / `o4-mini`
***
接入完成后,推荐尝试以下任务来熟悉 Cline 的能力上限:
* **代码重构**:"把这个项目的鉴权中间件从 JWT 换成 Session"
* **批量改造**:"为所有 API 路由补上 OpenAPI 注释"
* **全栈生成**:"用 Next.js + Drizzle 做一个待办应用,完成后跑通测试"
* **Bug 复现**:"打开 localhost:3000,截图首页,告诉我为什么 Header 错位"
更多技巧、模型选型与企业级最佳实践,可参考我们的 [Cline 完全指南 2026](https://aihubmix.com/blog/cline-guide) 长文版。
***
> **遇到问题?**
>
> * AIhubmix 用户支持:[support@aihubmix.com](mailto:support@aihubmix.com)
> * Cline 官方仓库:\[github.com/cline/cline]\([https://github.com/](https://github.com/)
文档更新日期:2026年5月12日
# CodeBuddy
Source: https://docs.aihubmix.com/cn/clients/CodeBuddy
在 CodeBuddy 中配置 AIHubMix:添加 Custom 模型后使用 AIHubMix 支持的任意模型。
CodeBuddy 可以把 OpenAI 兼容接口作为自定义模型使用。把 AIHubMix 配进去后,就能在 CodeBuddy 里调用 AIHubMix 支持的 GPT、Claude、Gemini、DeepSeek、GLM 等模型。
## 准备工作
* [CodeBuddy](https://www.codebuddy.cn/) 已安装,并且可以正常打开。
* 在 [AIHubMix 控制台](https://aihubmix.com/token) 创建好的 API Key,格式通常是 `sk-***`。
* 要使用的模型 ID,例如 `gpt-5.5`、`gemini-3.5-flash`、`deepseek-chat`。模型 ID 建议直接从 AIHubMix 模型列表复制,避免手动输入错误。
## 前端界面配置 AIHubMix 模型
打开 CodeBuddy,在输入框下方点击当前模型名称,例如 **Default**。
把模型列表拉到底部,点击 **Configure custom models**。
点击 **Add Model**,然后在 **Provider** 下拉框里选择 **Custom**。
接着填写这几项:
* **Endpoint**:通常填 `https://aihubmix.com/v1`。如果主地址暂时不可用,改成备用地址 `https://api.inferera.com/v1`。
* **API Key**:填你在 [AIHubMix 控制台](https://aihubmix.com/token) 创建的 Key。
* **Model Name**:填要用的模型 ID,例如 `gpt-5.5`。
* **Advanced Settings**:按模型能力勾选。需要工具调用就开 **Tool Calling**;模型支持看图就开 **Image Input**;推理模型可以开 **Reasoning**。
填好后点击 **Save**。
保存后回到模型下拉列表,在 **Custom Models** 区域选择刚添加的模型。
## 通过配置文件添加模型
CodeBuddy 会把自定义模型写到本地配置文件里。前端界面配置不方便时,可以编辑这个文件:
```text theme={null}
%USERPROFILE%\.codebuddy\models.json
```
CodeBuddy 支持项目级模型配置,位置是:
```text theme={null}
你的项目目录\.codebuddy\models.json
```
项目级配置优先级更高,适合只在某个项目里使用特定模型。手动写 `models.json` 时,推荐把 `url` 写成完整的 Chat Completions 地址:
```json theme={null}
{
"models": [
{
"id": "gpt-5.5",
"name": "gpt-5.5",
"vendor": "AIHubMix",
"url": "https://aihubmix.com/v1/chat/completions",
"apiKey": "sk-***",
"maxInputTokens": 128000,
"maxOutputTokens": 8192,
"supportsToolCall": true,
"supportsImages": true,
"supportsReasoning": true
}
],
"availableModels": ["gpt-5.5"]
}
```
如果当前 API 主地址不可用,把 `url` 改成备用地址即可:
```json theme={null}
"url": "https://api.inferera.com/v1/chat/completions"
```
这里和前端界面配置稍有区别:前端界面里的 **Endpoint** 填 `https://aihubmix.com/v1` 就可以;直接写 `models.json` 时,按 CodeBuddy 的配置文件格式补到 `/chat/completions` 更稳。改完后重启 CodeBuddy,或重新打开模型下拉列表查看。
如果不想把 Key 明文写进 `models.json`,可以使用环境变量引用:
```json theme={null}
"apiKey": "${AIHUBMIX_API_KEY}"
```
## CodeBuddy CLI
CodeBuddy 的命令行版本叫 **CodeBuddy Code**,安装后在终端执行 `codebuddy` 启动。如果本机还没有安装,可以用 npm 安装:
```shell theme={null}
npm install -g @tencent-ai/codebuddy-code
```
CLI 可以通过环境变量指定 API Key、接口地址和默认模型。AIHubMix 的 Anthropic 兼容接口使用根地址作为 `CODEBUDDY_BASE_URL`:
```powershell theme={null}
$env:CODEBUDDY_API_KEY="sk-***"
$env:CODEBUDDY_BASE_URL="https://aihubmix.com"
$env:CODEBUDDY_MODEL="glm-4.7"
codebuddy
```
示例最后一行的 `codebuddy` 是启动命令。启动后可以直接在终端里输入问题。
需要固定生效时,把这些变量写进 `%USERPROFILE%\.codebuddy\settings.json`:
```json theme={null}
{
"env": {
"CODEBUDDY_API_KEY": "sk-***",
"CODEBUDDY_BASE_URL": "https://aihubmix.com",
"CODEBUDDY_MODEL": "glm-4.7"
}
}
```
CLI 走的是 Anthropic 兼容协议,和上面桌面端自定义模型的 OpenAI 兼容配置不是同一个入口。如果遇到 404,优先检查 `CODEBUDDY_BASE_URL` 是否误写成了 `/v1/chat/completions` 这类 OpenAI 路径。
## 验证效果
选中自定义模型后,发一条简单消息测试一下,比如让 CodeBuddy 简短介绍 AIHubMix。能正常回复,就说明配置已经生效。
如果配置的模型支持图片输入,可以上传图片继续测试多模态能力。
## 常见问题
**保存后模型不可用怎么办?**
先检查 Endpoint 是否带 `/v1`,API Key 是否完整,Model Name 是否和 AIHubMix 模型 ID 一致。如果是手动写 `models.json`,再确认 `url` 是否补到了 `/chat/completions`。
**模型列表里出现两个相似名称正常吗?**
正常。CodeBuddy 可能会把自定义模型显示成 `模型名:模型名` 的形式,只要选中后能正常回复即可。
**CLI 和桌面端用的是同一套配置吗?**
不完全一样。桌面端的自定义模型主要看 `models.json`;CLI 会读取启动前设置的环境变量,或者读取 `settings.json` 里的 `env`。
更新时间:2026-07-10
# Cursor
Source: https://docs.aihubmix.com/cn/clients/Cursor
在 Cursor 中配置 AIHubMix 的 OpenAI 兼容接口,使用 AIHubMix 支持的模型进行代码对话、补全和 Agent 编程。
Cursor 是一款 AI 代码编辑器。本文介绍如何在 Cursor 中配置 AIHubMix,让 Cursor 通过 OpenAI 兼容接口调用 AIHubMix 支持的模型。
下载链接:[Cursor 官网下载](https://cursor.com/downloads)
## 准备工作
* 安装并打开 Cursor。
* 在 [AIHubMix 控制台](https://aihubmix.com/token) 创建 API Key。
* 准备要使用的模型 ID。建议从 [AIHubMix 模型列表](https://aihubmix.com/models) 复制,避免手动输入错误。
## 配置 AIHubMix
### 1. 打开 Models 设置
点击 Cursor 右上角的设置按钮,进入设置页面后选择 **Models**。
### 2. 填写 API Key 和 Base URL
在 **OpenAI API Key** 中填入在 AIHubMix 控制台创建的 API Key。
开启 **Override OpenAI Base URL** 后,填写:
```text theme={null}
https://aihubmix.com/v1
```
主地址暂时不可用时,可以改用备用地址:
```text theme={null}
https://api.inferera.com/v1
```
填写完成后,点击 **Verify** 验证配置。验证通过后,说明 Cursor 已经可以通过 AIHubMix 的 OpenAI 兼容接口发起请求。
### 3. 添加模型
在模型设置区域添加要使用的模型 ID,例如 `gpt-5.6-terra`。模型 ID 需要与 AIHubMix 模型列表中的名称保持一致。
如果要使用 Claude、Gemini、Qwen、Kimi 等模型,也建议直接添加 AIHubMix 支持的模型 ID。不要直接选择 Cursor 内置的官方模型入口,否则 Cursor 可能会走对应平台自己的默认接口,而不是上面配置的 AIHubMix 地址。
## 使用并验证
回到 Cursor 主界面,在聊天或 Agent 面板中选择刚刚添加的模型,发送一条简单请求。能够正常收到回复,即表示配置已经生效。
## 常见问题
**Verify 不通过怎么办?**
检查 API Key 是否完整、Base URL 是否包含 `/v1`,以及当前网络是否可以访问填写的地址。主地址暂时不可用时,可将 **Override OpenAI Base URL** 改为 `https://api.inferera.com/v1` 后再次验证。
**为什么选择模型后没有走 AIHubMix?**
确认选择的是你在模型列表中添加的 AIHubMix 模型 ID,而不是 Cursor 内置的官方模型入口。通过本文方式接入时,Cursor 会把 OpenAI 兼容请求发送到你填写的 Base URL。
***
更新时间:2026-08-04
# Dify
Source: https://docs.aihubmix.com/cn/clients/Dify
在 Dify 中接入 AIHubMix:让这个低代码 AI 应用平台用单个 API key 统一调度多家厂商模型。
Dify 是一个开源的 AI 应用开发平台。它提供了一套可视化的操作界面,不需要写代码,就能搭建出实用的 AI 应用,例如智能客服、文档问答助手、自动化处理流程等。
与直接使用 ChatGPT 相比,Dify 的优势在于:
* 可以自由选择和切换底层 AI 模型(OpenAI、Claude、Gemini 等)
* 可以上传自己的文档,让 AI 基于文档内容回答问题
* 可以通过工作流将多个 AI 步骤串联起来,实现自动化
* 可以将搭建好的应用发布成独立链接或嵌入自己的网站
Dify 有两种使用方式:云端版(直接注册账号使用)和本地版(在自己的电脑或服务器上安装)。两种方式功能基本相同,可根据实际情况选择。
***
## 一、开始使用:注册或安装
### 方式一:使用云端版(推荐新手)
云端版无需安装任何软件,注册即可使用。
**第一步:注册账号**
打开 [https://dify.ai,**点击右上角「Get**](https://dify.ai)\*\* Started」\*\*,使用邮箱注册账号,完成邮箱验证后登录。
**第二步:进入工作台**
登录成功后,会自动进入 Dify 的工作台首页。页面左侧是主导航菜单,后续所有操作都从这里入口。
***
### 方式二:本地部署(Docker 安装)
本地部署适合有一定技术基础的用户,数据完全保留在自己的机器上,适合对数据隐私有要求的场景。
**前提条件**
* 电脑上已安装 Docker 和 Docker Compose
* 如果尚未安装,可前往 [https://www.docker.com](https://www.docker.com) 下载 Docker Desktop,安装完成后 Docker Compose 会一并包含
**第一步:下载 Dify 源码**
打开终端(Mac 用 Terminal,Windows 用 PowerShell),执行以下命令:
```text theme={null}
git clone https://github.com/langgenius/dify.git
```
**第二步:进入 Docker 配置目录**
```text theme={null}
cd dify/docker
```
**第三步:复制环境配置文件**
```text theme={null}
cp .env.example .env
```
**第四步:启动服务**
```text theme={null}
docker compose up -d
```
首次启动会下载所需镜像,时间较长,请耐心等待。
**第五步:访问本地界面**
启动完成后,打开浏览器访问:
```text theme={null}
http://localhost
```
按照页面引导完成管理员账号的初始化设置,即可正常使用。
## 二、接入 AIHubMix LLM大语言模型
Dify 本身不提供 AI 模型,需要用户接入模型供应商的 API。我们AIHubMix作为一个模型聚合平台,提供统一的 API 接口,支持 OpenAI、Claude、Gemini 等700➕模型,只需一个 API Key 即可调用全部模型,适合在 Dify 中统一管理。
### 2.1 通常使用情况(使用OpenAI模型)
第一步:点击页面右上角的用户头像,在下拉菜单中选择「设置」。进入设置页面后,点击左侧菜单中的「模型供应商」。\
第二步:在供应商列表中找到「OpenAI」,点击右侧的「设置」按钮。
第三步:在API Key一栏输入[本站的Key](https://aihubmix.com/token)。
第四步:在API Base一栏输入:
```text theme={null}
https://aihubmix.com
```
### 2.2 使用非OpenAI模型(Claude、Gemini 等)
第一步:进入「设置 → 模型供应商」页面,在列表中找到「OpenAI-API-compatible」,点击右侧的「添加模型」按钮。
第二步:登录 AIhubMix 后台,进入「模型列表」页面,找到想使用的模型,复制其完整名称。在「模型名称」一栏中,粘贴刚才复制的模型名称。
常用模型名称示例:
* `claude-opus-4-7`
* `gemini-2.0-flash`
* `deepseek-chat`
> 模型名称必须与列表中完全一致,包括大小写、数字和连字符,填写错误会导致调用失败。
第三步:在「API Key」一栏中,填入你的 AihubMix API Key。在API Key一栏输入[本站的Key](https://aihubmix.com/token)。
第四步:在「API endpoint URL」一栏中填入
```text theme={null}
https://aihubmix.com/v1
```
## 3.3 接入生图模型
支持多种生图模型,包括但不限于 Nano Banana 2、GPT-Image 2、wan2.7-image 等最新模型。
### 使用步骤
#### 第一步:安装插件
搜索并安装插件:[AIHubMix Image](https://marketplace.dify.ai/plugins/langgenius/aihubmix-image?source=https%253A%252F%252Fcloud.dify.ai\&theme=system)
#### **第二步:** 配置 AIHUBMIX API KEY
在插件配置页面中填入您的 API Key
#### 第三步:添加节点
路径:工作区 → 添加节点 → 工具 → aihubmix-image → 选择具体需要使用的模型
#### **第四步:配置节点参数**
根据业务需求调整参数(如提示词、分辨率、宽高比等)。
#### **第五步:运行工作流**
配置完成后,点击右上角「运行」按钮执行工作流。运行成功后,即可调用 AiHubMix 生图 API 生成图片。
接口返回**URL** 和 **Base64** 两种图片格式。 在实际使用中请根据场景进行格式转换。
## 四、搭建基础对话应用
完成模型配置后,可以创建第一个 AI 对话应用。
**第一步:新建应用**
在 Dify 工作台首页,点击「创建应用」,在弹出的选项中选择「聊天助手」,填写应用名称后点击创建。
**第二步:选择模型**
进入应用编辑页面后,在右侧「模型」下拉菜单中,选择你刚才配置好的模型(例如 GPT 5.4 或 Claude)。
**第三步:设置系统提示词**
在「系统提示词」输入框中,填写对这个 AI 助手的角色定义和行为要求。
例如:
```text theme={null}
你是一位专业的客服助手,负责回答用户关于产品使用的问题。回答时语言简洁,如遇不确定的问题,请如实告知用户。
```
**第四步:调试对话**
在页面右侧的调试窗口中,发送一条测试消息,确认 AI 能够正常响应,并且回答风格符合预期。
**第五步:发布应用**
调试满意后,点击右上角「发布」按钮。发布后可以获得一个独立的访问链接,将链接分享给他人即可直接使用,无需对方了解任何技术背景。
***
## 五、搭建知识库(让 AI 读懂你的文档)
知识库功能允许你上传自己的文档,AI 会基于文档内容来回答问题,而不是仅凭自身训练数据。这种方式通常被称为 RAG(检索增强生成)。
常见使用场景:公司内部知识问答、产品手册查询、合同条款检索等。
**第一步:创建知识库**
在左侧导航中点击「知识库」,然后点击「创建知识库」,填写知识库名称后确认。
**第二步:上传文档**
在知识库页面中,点击「上传文件」,选择你要导入的文档。支持的格式包括 PDF、Word、Markdown、TXT 等常见格式。
上传后,Dify 会自动对文档进行处理和索引,处理时间视文档大小而定,通常在几秒到几分钟之间。
**第三步:在应用中关联知识库**
返回应用编辑页面,在右侧找到「知识库」选项,点击「添加」,选择刚才创建的知识库,保存。
**第四步:测试问答效果**
在调试窗口中,输入一个文档中有明确答案的问题,观察 AI 是否能够准确引用文档内容作答。
> 如果回答不准确,可以尝试调整知识库的分段设置,或者优化系统提示词中对知识库使用方式的说明。
***
## 六、搭建工作流(让 AI 自动完成多步任务)
工作流允许你将多个 AI 处理步骤串联起来,形成一条自动化流水线。整个搭建过程通过拖拽节点完成,无需编写代码。
**工作流与对话应用的区别**
* 对话应用:用户输入一句话,AI 回复一句话,适合交互式问答
* 工作流:用户输入触发后,系统按照预定步骤依次执行,适合批量处理和自动化任务
**示例:搭建一个「输入主题 → 自动生成文章 → 翻译成英文」的工作流**
**第一步:新建工作流**
在首页点击「创建应用」,选择「工作流」,填写名称后进入编辑画布。
**第二步:设置开始节点**
画布上默认已有「开始」节点。点击该节点,添加一个输入变量,命名为 `topic`,类型选择「文本」,用于接收用户输入的主题词。
**第三步:添加文章生成节点**
点击画布空白处,选择「添加节点 → LLM」,添加一个大语言模型节点。
在节点配置中:
* 选择模型(例如 GPT 5.4)
* 在提示词中填写:`请根据以下主题写一篇800字左右的文章:{{topic}}`
其中 `{{topic}}` 会自动替换为用户输入的内容。
**第四步:添加翻译节点**
再添加一个 LLM 节点,连接在文章生成节点之后。
在提示词中填写:`请将以下内容翻译成英文:{{上一节点的输出}}`
**第五步:连接节点**
用鼠标将各节点依次连线:开始 → 文章生成 → 翻译 → 结束。
**第六步:运行测试**
点击右上角「运行」,输入一个主题词(例如「人工智能的发展趋势」),观察工作流是否依次执行并输出最终结果。
***
## 七、搭建 Agent 智能体
Agent 是 Dify 中最灵活的应用类型。与普通对话应用不同,Agent 拥有主动规划和调用工具的能力——它会根据你的目标,自行拆解任务步骤,调用搜索、计算、画图等工具,逐步完成复杂任务。
**第一步:新建 Agent 应用**
在首页点击「创建应用」,选择「Agent」,填写名称后进入编辑页面。
**第二步:选择模型**
在右侧选择一个支持函数调用(Function Calling)的模型,推荐使用 GPT-4o 或 Claude 系列。这类模型对工具调用的理解能力更强,任务完成率更高。
**第三步:编写系统提示词**
系统提示词决定了 Agent 的角色定位和行为边界。示例:
```text theme={null}
你是一位信息研究助手。当用户提出问题时,你需要主动搜索最新资料,整理关键信息,并给出结构清晰的总结报告。
```
**第四步:添加工具**
在「工具」区域点击「添加工具」,从内置工具库中选择需要的工具。常用工具包括:
* **网页搜索**:让 Agent 能够实时检索互联网信息
* **计算器**:处理数学计算任务
* **代码执行**:运行简单的代码逻辑
选择工具后,Agent 会在判断需要时自动决定是否调用,以及如何调用。
**第五步:测试 Agent**
在调试窗口中输入一个需要多步处理的问题,例如:
```text theme={null}
帮我搜索一下2025年全球电动车销量数据,并整理成一段简短的总结。
```
观察 Agent 的执行过程——它会先调用搜索工具获取信息,再对结果进行整理和总结。在调试窗口中可以展开查看每一步的思考过程和工具调用记录。
**第六步:调整与发布**
如果 Agent 的表现不符合预期,可以调整系统提示词或更换模型后再次测试。满意后点击「发布」,即可生成可共享的访问链接。
***
## 常见问题
**模型调用失败,提示认证错误**
检查 API Key 是否填写正确,以及 API Base 地址是否与对应的接入方式匹配(OpenAI 供应商用 `https://aihubmix.com`,兼容模式用 `https://aihubmix.com/v1`)。
**添加非 OpenAI 模型后找不到该模型**
确认模型名称是否与 AIHubMix 模型列表中的名称完全一致,包括大小写和连字符,任何细微差异都会导致模型无法识别。
**知识库问答结果不准确**
可以尝试:将文档拆分成更小的片段后重新上传;在系统提示词中明确要求 AI 优先参考知识库内容;或者检查上传的文档是否为可识别的文本格式(扫描版 PDF 需要先进行 OCR 处理)。
**Agent 没有调用工具,直接给出了回答**
这通常是因为模型判断不需要使用工具,或者系统提示词没有明确引导。可以在提示词中加入类似「遇到需要查询外部信息的问题时,请主动使用搜索工具」的说明。
*最新更新日期:2026年4月30日*
# FeelFish
Source: https://docs.aihubmix.com/cn/clients/FeelFish
在 FeelFish 中接入 AIHubMix:AI 小说写作客户端用单个 API key 接入模型辅助创作。
### 官网
FeelFish 官网:[https://www.feelfish.com](https://www.feelfish.com)
### 配置教程
1. 点击右上角设置图标,进入软件设置弹窗。
2. 切换到“模型配置”标签,滚动到下面找到高级配置,点击添加模型接口。
3. 在弹窗中填写相关信息。FeelFish 已预置 AIHubMix 的 API 地址,您仅需输入一个随机 ID 以及在 AiHubMix 平台生成的密钥,随后点击“保存”完成配置。
4. 回到配置栏顶部,添加可用模型。
5. 添加AIHubMix中的模型至FeelFish。
6. 在创作时选择需要的模型即可使用。
##
更新时间:2026-06-01
# GCMP
Source: https://docs.aihubmix.com/cn/clients/GCMP
GCMP(AI Chat Models)是一个 VS Code 扩展,可以把智谱 AI、MoonshotAI、DeepSeek、阿里云百炼、火山方舟、腾讯云、MiniMax、小米 MiMo 等模型接入 GitHub Copilot Chat,同时也支持 OpenAI / Anthropic 兼容协议。AIHubMix 可以通过自定义 OpenAI 兼容模型接入到 Copilot Chat。
## 安装 GCMP 扩展
1. 在 VS Code 扩展市场搜索 `GCMP`,安装 **AI Chat Models** 扩展。
2. 安装完成后,在 Copilot Chat 的模型选择器底部点击 **Manage Models...**。
## 配置 AIHubMix API Key
3. 在模型管理列表中选择 **Compatible**。
4. 进入 **Manage OpenAI / Anthropic compatible models** 后,选择 **Manage API keys**。
5. 在 **Set AIHubMix** 输入框中填写你的 [AIHubMix API Key](https://console.aihubmix.com/token)。
## 创建 AIHubMix 模型
6. 回到模型配置入口,选择 **Configure models**,然后点击 **Add new model**。
7. 填写模型基础信息:
* **Model ID**:填写要使用的模型 ID,例如 `gpt-5.5`
* **Display Name**:填写模型选择器中展示的名称,例如 `AiHubMix-gpt-5.5`
* **Description**:可选,用于鼠标悬停时展示模型说明
8. 继续填写 API 配置:
* **Provider**:填写 `aihubmix`
* **SDK Mode**:选择 OpenAI 兼容模式
* **Base URL**:默认填写 `https://aihubmix.com/v1`,如主地址不可用,可改用备用地址 `https://api.inferera.com/v1`
* **Chat Endpoint**:保持为空即可
填写完成后点击 **Create**。
## 使用模型
9. 回到 Copilot Chat 模型选择器,选择刚刚创建的 `AiHubMix-gpt-5.5`。
10. 在 Copilot Chat 中发送消息,确认模型可以正常响应。
***
更新时间:2026-07-02
# GPT-Academic
Source: https://docs.aihubmix.com/cn/clients/GPT-Academic
在 GPT-Academic 中接入 AIHubMix:学术优化工具用单个 API key 调用模型,用于论文润色、翻译与解读。
GPT 学术优化 (GPT Academic)是目前 GitHub 上 **Star 数最高的科研类 LLM 工具之一**,专为科研工作者、研究生、博士生、论文作者打造。仓库地址:[https://github.com/binary-husky/gpt\_academic](https://github.com/binary-husky/gpt_academic)
### 核心功能一览
| 功能模块 | 应用场景 |
| :----------------------- | :----------------------------- |
| 📄 **PDF / LaTeX 论文翻译** | 中英文论文一键互译,保留公式与排版 |
| ✍️ **论文润色与改写** | Grammar、学术语气、Native English 润色 |
| 🧠 **论文摘要 / 综述生成** | 一键生成 Abstract、Related Work |
| 💻 **Python / C++ 项目剖析** | 自动解读整个代码仓库,自译解功能 |
| 🔌 **模块化函数插件** | 自定义快捷按钮,扩展专属工作流 |
| ⚡ **并行问询多模型** | 同时对比 GPT-5、Claude、文心一言答案 |
| 🏠 **本地模型支持** | ChatGLM3、LLaMA2、RWKV、MOSS 等 |
### 支持的大语言模型(LLM)
GPT Academic 已接入几乎所有主流模型:
* **OpenAI 系**:GPT-3.5、GPT-4、GPT-4o
* **Anthropic 系**:Claude 2、Claude 3
* **国产模型**:通义千问、讯飞星火、文心一言、ChatGLM3、DeepSeek Coder
* **开源模型**:LLaMA 2、RWKV、MOSS
## GPT 学术优化 + AIHubMix 配置教程(3 步)
> 💡 **前置条件**:
>
> * 已 clone GPT Academic 仓库到本地
> * 已在 [aihubmix.com](http://aihubmix.com) 注册并获取 API Key
> * Python 3.8+ 环境(已 pip install -r requirements.txt)
1. 打开 gpt\_academic/config.py 文件:\
2. 找到 config.py 中的 API\_KEY 变量,将[本站的Key](https://aihubmix.com/token)填入,即可:\
3. 往下滚动,找到 config.py 中的 API\_URL\_REDIRECT 变量,修改为(直接复制下面的代码块进去就行):
```text theme={null}
API_URL_REDIRECT = {"https://api.openai.com/v1/chat/completions": "https://aihubmix.com/v1/chat/completions"}
```
3. 然后就能使用了\\
## 进阶:自定义快捷按钮,打造论文工作流
GPT Academic 最强大的地方在于 **模块化函数插件**。在 [config.py](http://config.py) 中你还可以:
* 自定义高频 Prompt(如「将此段改写为 IEEE 论文风格」)
* 设置默认模型(推荐 GPT-4o 性价比最高)
* 配置代理端口(已通过 AiHubMix,可不设置)
* 启用并行问询,同时对比多个模型答案
GPT 学术优化(GPT Academic)+ AIHubMix 是目前科研工作者 **性价比最高的 AI 论文工作流方案之一**:
* 🚀 **3 步配置**,5 分钟完成
* 💰 **按量付费**
* 🤖 **一 Key 通吃**,GPT-5.5 / Claude / DeepSeek 随意切换
立即开始:
👉 [前往 AiHubMix 注册账号](https://aihubmix.com/)\
👉 [前往 GitHub 下载 GPT Academic](https://github.com/binary-husky/gpt_academic)
**📌 延伸阅读**:
* 《DeepSeek 学术写作测评:论文润色 + 中译英实测(搭配 GPT Academic 食用更佳)》
— \[CSDN 博客]\([https://blog.csdn.net/dinaxuejie/article/details/145374332](https://blog.csdn.net/dinaxuejie/article/details/145374332))
* 《AI 论文写作指南 2026:GPT-5 vs Claude 4 润色 / 降重场景实测对比》
— \[[chatgpt-chinese-guide.com](http://chatgpt-chinese-guide.com)]\([https://www.chatgpt-chinese-guide.com/chatgpt/ai-lunwen-xiezuo-chatgpt-claude-jiangchong-runse-2026.html](https://www.chatgpt-chinese-guide.com/chatgpt/ai-lunwen-xiezuo-chatgpt-claude-jiangchong-runse-2026.html))
最新更新日期:2026年5月13日
# Gptme
Source: https://docs.aihubmix.com/cn/clients/Gptme
在 Gptme 中接入 AIHubMix:开源终端 AI 助手用单个 API key 写代码、跑脚本并自由切换模型。
**gptme** 是开发者 [@ErikBjare](https://github.com/ErikBjare) 开源的 **终端原生 AI Agent**,GitHub 仓库地址:[gptme/gptme](https://github.com/ErikBjare/gptme)。
它是目前最受欢迎的 **ChatGPT Code Interpreter 本地化平替方案**,最大特点是:
> 🚀 **「Agent in Your Terminal」**——只要有终端的地方,就能跑 AI Agent。\
> 笔记本、SSH 远程、tmux 会话、无头服务器、CI/CD 流水线,全部通吃。
#### 核心能力一览
| 能力 | 说明 |
| :-------------------------- | :---------------------------- |
| 💻 **代码执行(shell + python)** | 直接在本地环境跑命令、跑脚本 |
| ✏️ **文件编辑(patch 工具)** | 增量修改文件,告别"全文重写" |
| 🌐 **浏览器操作(Playwright)** | 自动访问网页、抓取信息 |
| 👁️ **视觉能力(Vision)** | 看截图、读图片、识别桌面内容 |
| 🔄 **自我纠错** | 命令输出自动喂回模型,自动迭代 |
| 🤖 **长期自主 Agent** | 参考实现 Bob 已自主运行近一年,自己提 PR、修 CI |
> 📚 PyPI 主页:[pypi.org/project/gptme](https://pypi.org/project/gptme/)\
> 📖 官方文档:[gptme.org](http://gptme.org)
###
#### 🎯 AIHubMix 为什么是 gptme 的完美拍档?
[AIHubMix](https://aihubmix.com/) 提供主流的LLM,专为 gptme 这类「多模型切换」场景设计:
* ✅ **一个 Key 调用全部模型**:GPT-5.5 / Claude Opus 4.7 / DeepSeek V4 Flash / Gemini 3 Pro 全聚合
* ✅ **完全兼容 OpenAI 接口格式**——gptme 只需改一行 `OPENAI_BASE_URL`
* ✅ **接入即生效**,无需重新登录任何模型厂商账户
***
### gptme + AIHubMix 配置教程(3 步搞定)
> 💡 **前置条件**:
>
> * 已安装 Python 3.10+
> * 已通过 pipx / pip 安装 gptme(`pipx install gptme`)
> * 已在 [aihubmix.com](http://aihubmix.com) 注册并拿到 API Key(以 `sk-` 开头)
\
项目部署后进入 \~/.config/gptme/config.toml 文件(位于用户主目录下)进行配置。\
配置文件例子:
```text theme={null}
[env]
OPENAI_API_KEY = "sk-xxx"
MODEL = "local/gpt-4o"
OPENAI_BASE_URL = "https://aihubmix.com/v1"
```
sk-xxx的位置换成输入[本站的Key](https://aihubmix.com/token)
### gptme 常用命令速查
| 命令 | 作用 |
| :----------- | :--------------------- |
| `/help` | 查看所有命令 |
| `/tools` | 查看当前可用工具 |
| `/model` | 切换模型 |
| `/edit` | 编辑上一条消息 |
| `/undo` | 撤销上一步 |
| `/log` | 查看会话日志 |
| `/fork` | 分叉会话 |
| `/summarize` | 总结当前会话 |
| `/tokens` | 查看 token 用量 |
| `/export` | 导出会话 |
| `/commit` | 让 gptme 直接做 git commit |
| `/exit` | 退出 |
***
### 常见问题(FAQ)
#### Q1:报错 `401 Unauthorized`?
检查三点:
1. `OPENAI_API_KEY` 前后是否有空格、引号是否完整
2. AIHubMix 账户是否已充值
3. Key 是否被复制全
#### Q2:MODEL 字段里 `local/gpt-4o` 的 `local/` 是什么意思?
`local/` 是 gptme 内部的 provider 前缀,表示「按本地 BASE\_URL 路由」。**保留** `local/ `**即可**,不要去掉。也可以直接写模型名(如 `gpt-5.5`),gptme 会自动按 OpenAI 格式调用。
#### Q3:和 Cursor / Claude Code / Aider 比,gptme 优势是什么?
| 工具 | 定位 | 适合场景 |
| :---------- | :--------- | :--------------------- |
| **gptme** | 终端原生 Agent | SSH / 服务器 / 自动化脚本 / CI |
| Cursor | IDE 集成 | 桌面写代码 |
| Claude Code | 官方 CLI | Anthropic 生态深度用户 |
| Aider | Git 友好编辑 | 多文件重构 |
gptme 的杀手锏是 **「能在服务器上裸跑」**,远程运维场景无可替代。
#### Q4:在 CI / 服务器上运行安全吗?
gptme 默认每个危险操作都会问你确认。如果在 CI 里全自动跑,可以加 `--no-confirm` 或 `--non-interactive` 参数,配合 Docker 沙盒更安全。
### 推荐工作流:把 gptme 变成你的"贴身工程师"
#### 💼 场景 1:服务器运维
```text theme={null}
ssh user@server
gptme --model deepseek-v4-flash "查一下昨天的 nginx 错误日志,统计 5xx 出现最多的接口"
```
#### 💼 场景 2:本地批量处理
```text theme={null}
gptme "把当前目录下所有 .png 转成 webp,压缩到 80%"
```
#### 💼 场景 3:项目代码审查
```text theme={null}
cd my-project
gptme --model claude-opus-4-7 "审查 src/ 目录下所有 TypeScript 文件,列出潜在的内存泄漏"
```
#### 💼 场景 4:自动化 commit
```text theme={null}
gptme "/commit"
# gptme 会读 git diff、自动生成 commit message、自动执行
```
***
立即开始:
👉 [前往 AiHubMix ](https://aihubmix.com/)\
👉 [前往 GitHub 安装 gptme](https://github.com/ErikBjare/gptme)\
👉 [查看 gptme 官方文档](https://gptme.org/)
最新更新日期:2026年5月13日
# 沉浸式翻译
Source: https://docs.aihubmix.com/cn/clients/Immersive-Translate
在沉浸式翻译中接入 AIHubMix:浏览器翻译扩展用单个 API key 完成高质量双语对照翻译。
【沉浸式翻译】免费的双语对照网页翻译插件,支持PDF翻译(保留排版),视频双语字幕翻译(Youtube, Netflix),EPUB电子书翻译;支持人工智能AI翻译大模型(OpenAI (ChatGPT)、DeepL、Gemini(Bard) 等)
## 前置条件
* 已安装 [沉浸式翻译扩展](https://chromewebstore.google.com/detail/bpoadfkcbjbfhfodiogcnhhhpibjhbnh?utm_source=item-share-cb)(Chrome / Edge / Firefox 任一版本均可)
* 注册 [AIHubMix](https://aihubmix.com/) 账号并完成余额充值
## 在沉浸式翻译中配置自定义服务
提示:翻译软件建议不要使用openai的o系列和gpt-5系列模型。
进入设置界面之后,选择自定义 API Key,在 APIKEY 那一栏输入[本站的Key](https://aihubmix.com/token)\
点开“扩展更多自定义设置”\
自定义 API 接口地址填:
```text theme={null}
https://aihubmix.com/v1/chat/completions
```
***
更新时间:2026-06-01
# LangChain
Source: https://docs.aihubmix.com/cn/clients/LangChain
用 LangChain 接入 AIHubMix:通过 OpenAI 兼容接口在 Python / JS 代码中调用模型,构建 AI 应用与 Agent。
LangChain 是目前应用最广泛的大语言模型应用开发框架之一。本文档介绍如何在 LangChain 项目中接入AIHubMix,涵盖凭据配置、模型切换、检索增强生成(RAG)场景实践与生产环境建议。
## 环境准备
接入 AIHubMix 前,需满足以下条件:
* Python 版本不低于 3.9
* 已安装 LangChain 及其 OpenAI 集成包或者下载:[https://www.langchain.com/](https://www.langchain.com/):
```text theme={null}
pip install langchain langchain-openai openai
```
* 已在 [aihubmix.com](http://aihubmix.com) 完成账号注册,并在控制台创建 API 凭据(以 `sk-` 开头的字符串)
### 最简单的配置方式:直接设置环境变量代码如下
```text theme={null}
API_SECRET_KEY = "sk-pvMtoVO******66249058b93C766F2D70167"
BASE_URL = "https://aihubmix.com/v1"; #aihubmix的base-url
os.environ["OPENAI_API_KEY"] = API_SECRET_KEY
os.environ["OPENAI_BASE_URL"] = BASE_URL
```
注意:openai\_api\_base 的末尾要加上 /v1,
```from langchain.chat_models import ChatOpenAI theme={null}
llm = ChatOpenAI(
openai_api_base="https://aihubmix.com/v1", # 注意,末尾要加 /v1
openai_api_key="sk-3133f******fee269b71d",
)
res = llm.predict("hello")
print(res)
```
示例代码,使用LLM进行预测\
核心其实在于key和url的设置\
方法有:
1. 使用环境变量来设置
2. 使用变量来传入
3. 使用手动设置环境变量
```py Python theme={null}
import os
import requests
import time
import json
import time
from langchain.llms import OpenAI
API_SECRET_KEY = "你在aihubmix的key";
BASE_URL = "https://aihubmix.com/v1"; #aihubmix的base-url
os.environ["OPENAI_API_KEY"] = API_SECRET_KEY
os.environ["OPENAI_API_BASE"] = BASE_URL
def text():
llm = OpenAI(temperature=0.9)
text = "What would be a good company name for a company that makes colorful socks?"
print(llm(text))
if __name__ == '__main__':
text();
```
运行后可以看到返回:
```text theme={null}
Lively Socks.
```
## 检索增强生成(RAG)场景实践
LangChain 在 RAG 应用中通常涉及两类调用:向量化(Embedding)与生成(Chat Completion)。由于向量化调用频次远高于生成调用,但单次成本远低于生成,因此在成本敏感的生产场景中,可通过混搭策略显著降低总体支出。
AIHubMix 的统一入口设计使该策略实现成本极低:
```text theme={null}
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_community.vectorstores import FAISS
from langchain.chains import RetrievalQA
embeddings = OpenAIEmbeddings(
model="text-embedding-3-small",
openai_api_base="https://aihubmix.com/v1",
openai_api_key="sk-xxx",
)
llm = ChatOpenAI(
model="claude-sonnet-4-6",
openai_api_base="https://aihubmix.com/v1",
openai_api_key="sk-xxx",
)
vectorstore = FAISS.from_documents(documents, embeddings)
qa = RetrievalQA.from_chain_type(llm=llm, retriever=vectorstore.as_retriever())
response = qa.invoke("公司年报中第三季度营收数据是多少?")
print(response)
```
上述代码使用 `text-embedding-3-small` 处理向量化、`claude-sonnet-4-6` 处理最终生成。
***
## LangChain 0.1 之后的导入路径变更
自 LangChain 0.1 版本起,官方将 OpenAI 集成拆分至独立包 `langchain-openai`。旧版导入路径虽仍可运行,但已被标记为弃用(deprecated),并在每次导入时输出告警。
```text theme={null}
# 弃用写法
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI
# 推荐写法
from langchain_openai import ChatOpenAI, OpenAI, OpenAIEmbeddings
```
新项目应直接采用新版导入路径;存量项目建议在常规升级窗口内迁移完成。
***
## 生产环境实践建议
将 LangChain 应用部署至生产环境时,以下三项配套实践与 AiHubMix 协同效果良好。
### 成本可观测性
LangChain 提供 `get_openai_callback` 上下文管理器,可实时统计每次调用的 token 用量与费用。结合 AiHubMix 控制台的账单明细,可在代码层与平台层形成双向核对:
```text theme={null}
from langchain_community.callbacks import get_openai_callback
with get_openai_callback() as cb:
response = llm.invoke("hello")
print(f"消耗 tokens: {cb.total_tokens}, 估算费用: ${cb.total_cost}")
```
### 多模型容错
任何单一上游均可能出现短时不可用。LangChain 的 `with_fallbacks` 方法支持声明降级链路,确保关键业务的可用性:
```text theme={null}
primary = ChatOpenAI(model="claude-opus-4-7", openai_api_base="https://aihubmix.com/v1")
fallback = ChatOpenAI(model="gpt-5.5", openai_api_base="https://aihubmix.com/v1")
llm = primary.with_fallbacks([fallback])
```
### 配置外部化
模型选型与端点地址在生产环境中属于高频调整项。建议将其抽离至环境变量或配置中心,避免因调整模型而触发代码发布流程:
```text theme={null}
llm = ChatOpenAI(
model=os.getenv("LLM_MODEL", "claude-sonnet-4-6"),
openai_api_base=os.getenv("LLM_BASE_URL", "https://aihubmix.com/v1"),
)
```
***
## 常见问题
**端点返回 404 Not Found**\
通常由 `OPENAI_BASE_URL` 缺失 `/v1` 后缀引起。请确认配置值为 `https://aihubmix.com/v1`。
**返回 401 Unauthorized**\
请依次确认 API 凭据是否完整复制、AIHubMix 账户余额是否充足、凭据是否已在控制台启用。
**LangGraph 与 LangSmith 是否兼容**\
完全兼容。LangGraph 的节点底层仍调用 `ChatOpenAI`,配置方式一致;LangSmith 作为观测平台,独立于上游模型链路,不受影响。
***
## 参考资源
* AIHubMix 官网:[aihubmix.com](https://aihubmix.com/)
* LangChain 官网:[langchain.com](https://www.langchain.com/)
* LangChain Python 文档:[python.langchain.com](https://python.langchain.com/)
***
更新时间:2026-06-01
# LibreChat
Source: https://docs.aihubmix.com/cn/clients/LibreChat
在 LibreChat 中接入 AIHubMix:通过 OpenAI 兼容接口统一调用多家厂商模型。
LibreChat 是一个开源的多模型对话客户端,支持 OpenAI 兼容接口。接入 AIHubMix 后,可以在 LibreChat 的 **OpenAI** 端点下使用 AIHubMix 支持的 OpenAI、Claude、Gemini、DeepSeek、GLM 等模型。
## 环境准备
接入前请先确认:
* 已部署并启动可用的 LibreChat 实例,推荐使用 v0.7.5 或更高版本。
* 已在 [AIHubMix 控制台](https://aihubmix.com/token) 创建 API Key,格式通常为 `sk-***`。
* 可以修改 LibreChat 部署目录中的 `.env` 文件。`.env` 位于 LibreChat 项目根目录,也就是与 `package.json`、`docker-compose.yml` 同级的位置。
* 配置文件位置通常是 `你的安装路径/LibreChat/.env`;如果该文件不存在,可以把同目录下的 `.env.example` 复制一份并重命名为 `.env`。
* 修改配置后需要重启 LibreChat。
## 配置 `.env`
LibreChat 接入 AIHubMix 的核心就是修改安装目录里的 `.env`:把 OpenAI 端点指向 AIHubMix 网关,并配置 API Key。
需要修改的文件位置是:
```text theme={null}
你的安装路径/LibreChat/.env
```
打开 LibreChat 项目根目录下的 `.env` 文件,找到 OpenAI 相关配置区;如果找不到,也可以直接把下面几行追加到 `.env` 文件末尾。
```env theme={null}
OPENAI_API_KEY=你的_AIHubMix_Key
OPENAI_REVERSE_PROXY=https://aihubmix.com/v1
```
如果不想把 Key 直接写进 `.env`,可以把 `OPENAI_API_KEY` 改成 LibreChat 的用户自填模式:
```env theme={null}
OPENAI_API_KEY=user_provided
OPENAI_REVERSE_PROXY=https://aihubmix.com/v1
```
这里的 `user_provided` 是 LibreChat 的特殊写法,表示不把 Key 写死在服务器配置里,而是在用户界面中由当前登录用户自己填写。两种写法只影响 Key 的保存位置,模型仍然都会出现在 LibreChat 的 **OpenAI** 端点下。
如遇当前 API 主地址不可用,可把 `OPENAI_REVERSE_PROXY` 改为备用地址:
```env theme={null}
OPENAI_REVERSE_PROXY=https://api.inferera.com/v1
```
模型列表默认由 AIHubMix 返回,通常不需要手动写 `OPENAI_MODELS`。如果你只想固定展示部分模型,可以在 `.env` 中补充 `OPENAI_MODELS`,多个模型用英文逗号分隔:
```env theme={null}
OPENAI_MODELS=gpt-4o-mini,gpt-5.5,claude-haiku-4-5,deepseek-chat,gemini-3.5-flash,glm-5.2
```
如果希望展示 AIHubMix 支持的完整模型列表,不要配置 `OPENAI_MODELS`,或保留 `.env` 中 `# OPENAI_MODELS=...` 的注释状态。保存后重启 LibreChat,在模型/端点选择区域选择 **OpenAI**,再选择要使用的模型即可。
## 重启 LibreChat
修改 `.env` 后必须重启服务,否则新配置不会生效:
* 使用本地脚本启动:重新运行你的 LibreChat 启动脚本。
* 使用源码或 npm 启动:进入 LibreChat 项目根目录,也就是 `.env` 所在目录,重新执行你原本的启动命令。
* 使用 Docker 部署:在 `docker-compose.yml` 所在目录执行 `docker compose restart`,或重新启动对应容器。
## 效果说明
配置完成后,模型都会出现在 LibreChat 的 **OpenAI** 端点下,模型列表由 AIHubMix 返回,涵盖 AIHubMix 当前支持的模型。只有在 `.env` 中手动启用了 `OPENAI_MODELS` 时,页面才会只显示你写入的那部分模型。
## 参考资源
* AIHubMix 官网:[aihubmix.com](https://aihubmix.com)
* LibreChat 官网:[librechat.ai](https://www.librechat.ai/)
* LibreChat 本地安装文档:[librechat.ai/zh/docs/local/npm](https://www.librechat.ai/zh/docs/local/npm)
* LibreChat 环境变量示例:[github.com/danny-avila/LibreChat/blob/main/.env.example](https://github.com/danny-avila/LibreChat/blob/main/.env.example)
更新时间:2026-07-03
# LiteLLM
Source: https://docs.aihubmix.com/cn/clients/LiteLLM
用 LiteLLM 接入 AIHubMix:通过统一代理层一行代码切换模型,覆盖流式输出与多轮对话。
## LiteLLM 项目简介
LiteLLM 是一个开源的 **AI 统一网关**,由 [BerriAI](https://github.com/BerriAI/litellm) 开发,目标是用一套标准接口调用市面上几乎所有主流大模型。项目仓库见:[https://github.com/BerriAI/litellm](https://github.com/BerriAI/litellm)
每个 LLM 提供商都有自己的 SDK 和 API 格式,OpenAI、Anthropic、Google 各不相同。一旦需要切换模型或同时使用多个模型,就要维护多套代码。LiteLLM 可以实现——**写一次代码,换一个参数,即可调用任意模型**。
### 两种使用形态
| 形态 | 说明 | 适合场景 |
| :--------------- | :----------------------------- | :-------- |
| **Python SDK** | `pip install litellm`,直接在代码中调用 | 个人开发、快速原型 |
| **Proxy Server** | 独立部署的 AI 网关服务 | 团队共用、企业管控 |
### 核心能力
* **统一 OpenAI 格式**:支持 100+ 个 Provider,包括 OpenAI、Anthropic、Gemini、Bedrock、Azure 等
* **虚拟密钥管理**:统一管控团队 API Key,无需暴露原始密钥
* **成本追踪**:按用户/项目统计 Token 消耗和费用
* **负载均衡**:跨多个模型或部署自动分流,支持故障转移
* **高性能**:1000 RPS 下 P95 延迟约 8ms
## 安装指南
### 环境要求
Python 3.8+
**macOS**
推荐使用 [Homebrew](https://brew.sh/) 安装:
```text theme={null}
brew install python
```
验证:
```text theme={null}
python3 --version
```
**Windows**
前往 [python.org/downloads](https://www.python.org/downloads/) 下载安装包,安装时勾选 **"Add Python to PATH"**。
验证:
```text theme={null}
python --version
```
**Linux(Ubuntu/Debian)**
```text theme={null}
sudo apt update
sudo apt install python3 python3-pip
```
***
#### pip
pip 通常随 Python 一起安装,验证是否可用:
```text theme={null}
pip --version
# 或
pip3 --version
```
如果提示未找到,手动安装:
```text theme={null}
# 通用方式
python3 -m ensurepip --upgrade
# Ubuntu/Debian
sudo apt install python3-pip
# 升级到最新版
pip install --upgrade pip
```
***
### 安装 LiteLLM
环境就绪后,执行:
```text theme={null}
python3 -m pip install litellm
```
验证安装成功,在终端运行:
```text theme={null}
python3 -m pip show litellm
```
这已经包含了调用所有主流 Provider 的能力。
### 按需安装额外依赖
部分 Provider 需要额外的依赖包:
```text theme={null}
# AWS Bedrock
pip install litellm[bedrock]
# Google Vertex AI
pip install litellm[vertex]
# 全部依赖(体积较大,不推荐生产环境)
pip install litellm[all]
```
### 安装 Proxy Server
如果需要部署独立的网关服务,安装带 proxy 的版本:
```text theme={null}
pip install 'litellm[proxy]'
```
### 验证安装
```python theme={null}
import litellm
print(litellm.__version__)
```
### Docker 安装(可选)
如果你更倾向于容器化部署:
```text theme={null}
docker pull ghcr.io/berriai/litellm:main-latest
```
***
> **推荐做法**:个人开发直接 `pip install litellm`,团队部署选 Proxy + Docker。
## 配置 API Key 并调用
### 获取 AiHubMix API Key
前往 [aihubmix.com](http://aihubmix.com) 控制台,创建一个 API Key。
### 设置环境变量
```text theme={null}
export AIHUBMIX_API_KEY="your-aihubmix-key"
```
### 发起第一次调用
```python theme={null}
import os
from litellm import completion
response = completion(
model='openai/gpt-4o-mini',
api_base='https://aihubmix.com/v1',
api_key=os.environ.get('AIHUBMIX_API_KEY'),
messages=[{'role': 'user', 'content': 'What is the meaning of life?'}]
)
print(response.choices[0].message.content)
```
# **基础用法**
## 1. 切换不同模型
AiHubMix 支持主流模型,切换只需改 `model` 参数:
```python theme={null}
import os
from litellm import completion
response = completion(
model='openai/claude-sonnet-4-6', # 换这里
api_base='https://aihubmix.com/v1',
api_key=os.environ.get('AIHUBMIX_API_KEY'),
messages=[{'role': 'user', 'content': 'What is the meaning of life?'}]
)
print(response.choices[0].message.content)
```
***
## 2. 流式输出(Streaming)
加一个 `stream=True`,模型会像打字机一样逐字输出:
```python theme={null}
import os
from litellm import completion
response = completion(
model='openai/claude-sonnet-4-6',
api_base='https://aihubmix.com/v1',
api_key=os.environ.get('AIHUBMIX_API_KEY'),
messages=[{'role': 'user', 'content': 'Explain Python in 100 words'}],
stream=True
)
for chunk in response:
print(chunk.choices[0].delta.content or '', end='', flush=True)
print()
```
***
## 3. 多轮对话
把历史消息拼进 `messages` 列表,模型就能记住上下文:
```python theme={null}
import os
from litellm import completion
messages = [
{'role': 'user', 'content': 'My name is John'},
{'role': 'assistant', 'content': 'Hello, John!'},
{'role': 'user', 'content': 'What is my name?'}
]
response = completion(
model='openai/claude-sonnet-4-6',
api_base='https://aihubmix.com/v1',
api_key=os.environ.get('AIHUBMIX_API_KEY'),
messages=messages
)
print(response.choices[0].message.content)
```
***
## 4. 异步调用
适合需要同时发多个请求的场景,不用等一个完成再发下一个:
```python theme={null}
import os
import asyncio
from litellm import acompletion
async def ask(question):
response = await acompletion(
model='openai/claude-sonnet-4-6',
api_base='https://aihubmix.com/v1',
api_key=os.environ.get('AIHUBMIX_API_KEY'),
messages=[{'role': 'user', 'content': question}]
)
return response.choices[0].message.content
async def main():
questions = ['What color are apples?', 'What color is the sky?', 'What color is grass?']
results = await asyncio.gather(*[ask(q) for q in questions])
for q, r in zip(questions, results):
print(f'Q: {q}')
print(f'A: {r}')
print()
asyncio.run(main())
```
***
## 5. 设置超时与重试
避免请求卡住或因网络抖动失败:
```python theme={null}
import os
from litellm import completion
response = completion(
model='openai/claude-sonnet-4-6',
api_base='https://aihubmix.com/v1',
api_key=os.environ.get('AIHUBMIX_API_KEY'),
messages=[{'role': 'user', 'content': 'What is the meaning of life?'}],
timeout=10, # 超过 10 秒自动报错
num_retries=3 # 失败自动重试 3 次
)
print(response.choices[0].message.content)
```
> `timeout` 单位是秒,`num_retries` 建议设 2~3,太高会拖慢响应。
## 6. 统计 Token 用量和费用
每次调用的返回结果里自带 Token 用量信息:
```python theme={null}
import os
from litellm import completion
response = completion(
model='openai/claude-sonnet-4-6',
api_base='https://aihubmix.com/v1',
api_key=os.environ.get('AIHUBMIX_API_KEY'),
messages=[{'role': 'user', 'content': 'Explain Python in 100 words'}]
)
print(response.choices[0].message.content)
print()
print('Token usage:')
print(f' Input: {response.usage.prompt_tokens}')
print(f' Output: {response.usage.completion_tokens}')
print(f' Total: {response.usage.total_tokens}')
```
***
统计多次调用的累计费用:
```python theme={null}
import os
from litellm import completion, completion_cost
response = completion(
model='openai/claude-sonnet-4-6',
api_base='https://aihubmix.com/v1',
api_key=os.environ.get('AIHUBMIX_API_KEY'),
messages=[{'role': 'user', 'content': 'Explain Python in 100 words'}]
)
cost = completion_cost(completion_response=response)
print(f'Cost: ${cost:.6f}')
```
***
## 7. 负载均衡 / 故障转移
配置多个模型,自动分流或在某个模型失败时切换到备用模型:
```python theme={null}
import os
from litellm import Router
router = Router(
model_list=[
{
'model_name': 'my-model',
'litellm_params': {
'model': 'openai/claude-sonnet-4-6',
'api_base': 'https://aihubmix.com/v1',
'api_key': os.environ.get('AIHUBMIX_API_KEY'),
}
},
{
'model_name': 'my-model',
'litellm_params': {
'model': 'openai/gpt-4o',
'api_base': 'https://aihubmix.com/v1',
'api_key': os.environ.get('AIHUBMIX_API_KEY'),
}
}
]
)
response = router.completion(
model='my-model',
messages=[{'role': 'user', 'content': 'What is the meaning of life?'}]
)
print(response.choices[0].message.content)
```
> 两个模型共用同一个 `model_name`,LiteLLM 会自动轮询;若其中一个报错,自动切换到另一个。
## 8. 部署 Proxy Server
Proxy Server 是一个独立运行的网关服务,团队成员统一通过它访问模型,无需每个人单独配置 API Key。
### 安装
```text theme={null}
python3 -m pip install 'litellm[proxy]'
```
### 创建配置文件
新建 `config.yaml`:
```yaml theme={null}
model_list:
- model_name: gpt-4o
litellm_params:
model: openai/gpt-4o
api_base: https://aihubmix.com/v1
api_key: os.environ/AIHUBMIX_API_KEY
- model_name: claude-sonnet
litellm_params:
model: openai/claude-sonnet-4-6
api_base: https://aihubmix.com/v1
api_key: os.environ/AIHUBMIX_API_KEY
- model_name: gemini-flash
litellm_params:
model: openai/gemini-2.0-flash
api_base: https://aihubmix.com/v1
api_key: os.environ/AIHUBMIX_API_KEY
```
### 启动服务
```text theme={null}
litellm --config config.yaml --port 4000
```
看到以下输出说明启动成功:
```text theme={null}
LiteLLM: Proxy running on http://0.0.0.0:4000
```
### 调用本地服务
服务启动后,把 `api_base` 换成本地地址即可:
```python theme={null}
import os
from litellm import completion
response = completion(
model='gpt-4o',
api_base='http://localhost:4000',
api_key='any-string',
messages=[{'role': 'user', 'content': 'What is the meaning of life?'}]
)
print(response.choices[0].message.content)
```
> `api_key` 此时可以填任意字符串,真实的 AiHubMix Key 由 Proxy 统一管
## 9. 虚拟密钥管理
虚拟密钥让你可以给不同成员或项目分配独立的 Key,统一管控权限和用量,而不暴露真实的 AiHubMix API Key。
### 前置条件
虚拟密钥需要数据库支持,先启动一个 PostgreSQL:
```text theme={null}
docker run -d \
--name litellm-db \
-e POSTGRES_USER=litellm \
-e POSTGRES_PASSWORD=litellm \
-e POSTGRES_DB=litellm \
-p 5432:5432 \
postgres
```
### 更新配置文件
在 `config.yaml` 中加入数据库配置:
```yaml theme={null}
model_list:
- model_name: gpt-4o
litellm_params:
model: openai/gpt-4o
api_base: https://aihubmix.com/v1
api_key: os.environ/AIHUBMIX_API_KEY
- model_name: claude-sonnet
litellm_params:
model: openai/claude-sonnet-4-6
api_base: https://aihubmix.com/v1
api_key: os.environ/AIHUBMIX_API_KEY
general_settings:
master_key: sk-my-master-key
database_url: postgresql://litellm:litellm@localhost:5432/litellm
```
### 重启服务
```text theme={null}
litellm --config config.yaml --port 4000
```
### 创建虚拟密钥
用 `master_key` 创建一个新的虚拟 Key:
```bash theme={null}
curl -X POST http://localhost:4000/key/generate \
-H "Authorization: Bearer sk-my-master-key" \
-H "Content-Type: application/json" \
-d '{
"key_alias": "team-a",
"max_budget": 10,
"models": ["gpt-4o", "claude-sonnet"]
}'
```
返回结果中的 `key` 字段就是虚拟密钥,例如 `sk-xxxxxx`。
### 使用虚拟密钥调用
```python theme={null}
from litellm import completion
response = completion(
model='claude-sonnet',
api_base='http://localhost:4000',
api_key='sk-xxxxxx',
messages=[{'role': 'user', 'content': 'What is the meaning of life?'}]
)
print(response.choices[0].message.content)
```
### 查看用量
```bash theme={null}
curl http://localhost:4000/key/info \
-H "Authorization: Bearer sk-my-master-key" \
-H "Content-Type: application/json" \
-d '{"key": "sk-xxxxxx"}'
```
> 每个虚拟 Key 可以单独设置可用模型、预算上限、过期时间,适合团队多人协作场景。
先设置环境变量:
```text theme={null}
export AIHUBMIX_API_KEY="your-key"
```
## 实战:多模型对比测试
同一个问题同时发给多个模型,对比输出质量、速度和 Token 消耗。
### 设置 API Key
```text theme={null}
export AIHUBMIX_API_KEY="your-key"
```
### 运行对比测试
```text theme={null}
python3 -c "
import os
import time
import asyncio
from litellm import acompletion
MODELS = [
'gpt-5.5',
'claude-opus-4-7',
'deepseek-v4-flash',
'coding-glm-5.1-free',
]
QUESTION = 'If you could give a programmer only one piece of advice, what would it be?'
async def ask_model(model, question):
start = time.time()
try:
response = await acompletion(
model=f'openai/{model}',
api_base='https://aihubmix.com/v1',
api_key=os.environ.get('AIHUBMIX_API_KEY'),
messages=[{'role': 'user', 'content': question}]
)
return {
'model': model,
'answer': response.choices[0].message.content.strip(),
'tokens': response.usage.total_tokens,
'time': round(time.time() - start, 2),
'error': None
}
except Exception as e:
return {
'model': model,
'answer': None,
'tokens': 0,
'time': round(time.time() - start, 2),
'error': str(e)
}
async def main():
print(f'Question: {QUESTION}')
print('=' * 60)
tasks = [ask_model(m, QUESTION) for m in MODELS]
results = await asyncio.gather(*tasks)
for r in results:
print(f'\nModel: {r[\"model\"]}')
print(f'Time: {r[\"time\"]}s | Tokens: {r[\"tokens\"]}')
print('-' * 40)
if r['error']:
print(f'Error: {r[\"error\"]}')
else:
print(r['answer'])
print('\n' + '=' * 60)
print(f'{\"Model\":<30} {\"Time\":>8} {\"Tokens\":>8}')
print('-' * 50)
for r in sorted(results, key=lambda x: x['time']):
status = f'{r[\"time\"]}s' if not r['error'] else 'failed'
print(f'{r[\"model\"]:<30} {status:>8} {r[\"tokens\"]:>8}')
asyncio.run(main())
"
```
***
最新更新日期:2026年4月29日
# LobeChat
Source: https://docs.aihubmix.com/cn/clients/Lobe-Chat
## 通常使用方法
lobe-chat官方网址:[chat-preview.lobehub.com](https://chat-preview.lobehub.com/?utm_source=aihubmix\&utm_medium=website\&utm_campaign=references)
如下图所示点击进入设置\\
* API key 输入[本站的Key](https://aihubmix.com/token)
* 接口代理地址,直接输入下方的网址:
```text theme={null}
https://aihubmix.com/v1
```
(建议打开“使用客户端请求模式”)\
\
最后在模型列表添加自己要使用的模型\\
## 非openai模型使用方法
模型服务商选择 openai 不变,在模型列表手动添加所需模型名称即可。\
打开网站模型广场页面即可复制你想要使用的模型名称
------------------------
更新时间:2026-06-01
# n8n
Source: https://docs.aihubmix.com/cn/clients/N8N
在 n8n 中接入 AIHubMix:让这个工作流自动化平台在节点中用单个 API key 调用模型。
n8n 是一款开源的工作流自动化平台,支持以可视化节点方式编排数据流转、API 调用与 AI 任务。自 2023 年起,n8n 在其节点库中陆续引入 AI Agent、Chat Model、Vector Store 等 LLM 原生组件,使工作流可直接调用大语言模型完成内容生成、分类、信息抽取、多轮决策等任务。本文档介绍如何在 n8n 中以凭据(Credential)形式接入 AIHubMix,并在 Chat Model 节点中调用所需模型。
## 环境准备
在 n8n 中接入 AIHubMix 前,需满足以下条件:
* 已部署可访问的 n8n 实例(n8n Cloud 或自托管版本均可)
* 工作区已启用 AI 节点(默认在 1.19 及以上版本中可用)
* 已在 [aihubmix.com](https://aihubmix.com/) 完成账号注册,并在控制台创建 API 凭据
* 已记录如下两项配置参数:
* **API Key**:以 `sk-` 开头的字符串
* **Base URL**:`https://aihubmix.com/v1`
### 官网
N8N 官网:[http://n8n.io/](http://n8n.io/)
### 配置教程
1. 进入工作区,新增 Chat Model 节点,增加凭据。
2. 填写名称、API Key 以及 Base URL 并保存。
3. 选择新建的凭据,添加需要使用的模型,并关闭 `Use Response API` 。
4. 打开 `Open Chat` 即可在 N8N 中使用 AIHubMix 的模型。
## 模型选择
凭据配置完成后,在节点参数区的 `Model` 字段中可指定具体调用的大模型。
常用模型与适用场景对应关系如下:
* **GPT-5.5**:OpenAI 当前旗舰模型,适用于复杂推理、长链路 Agent 决策、多步骤代码生成等高难度任务。
* **GPT-5.4**:OpenAI 上一代旗舰,与 OpenAI 生态兼容性最广,适合作为存量项目的稳定升级路径。
* **Claude Opus 4.7**:Anthropic 当前旗舰,在长文档理解、复杂指令跟随、合规审查等场景表现优异。
* **Claude Sonnet 4.6**:综合性价比之选,适用于内容生成、客服对话、邮件起草等高频生产任务,建议作为工作流的默认模型。
* **DeepSeek V4 Flash**:响应延迟最短、单位成本最低,适用于分类、抽取、翻译、关键词提取等高并发场景。
在节点的 `Model` 字段中输入对应模型名(例如 `claude-sonnet-4-6`、`deepseek-v4-flash`)即可生效。如该字段提供下拉选项但未包含目标模型,可切换至 `Expression` 模式手动输入模型名。
***
## 典型应用场景
n8n 与 AIHubMix 结合后,可承载多种基于大模型的自动化工作流。以下为生产环境中较为常见的几类用法。
### 邮件自动分类与回复
通过 Email Trigger 节点接收新邮件,将正文传入 OpenAI Chat Model 节点,由 Claude Sonnet 4.6 完成意图分类与回复草稿生成,再经审批节点确认后由 SMTP 节点发出。该工作流将客服团队的初筛工作量减少约 70%。
### 文档批量处理与摘要
由 Google Drive 或 Notion 触发器监听新文档,将内容分块后逐段调用 DeepSeek V4 Flash 完成摘要生成,结果写回知识库。利用 DeepSeek V4 Flash 的低成本特性,可在不增加显著支出的前提下完成大规模文档处理。
### AI Agent 多步任务编排
使用 n8n 的 AI Agent 节点配合 Claude Opus 4.7 作为决策模型,结合 HTTP Request、Database、Code 等工具节点,构建可自主完成"查询、分析、决策、执行"全流程的代理。该模式适用于运维巡检、报表生成、数据治理等需要多步推理的复杂任务。
### 多模态内容生成
将文本输入传入 GPT-5.5 生成文案,再通过 AIHubMix 的图像生成接口生成配图,最终由 n8n 写入内容管理系统。整条链路在同一组凭据下完成,无需维护多套上游配置。
***
## 生产环境实践建议
### 凭据分级管理
建议按环境(开发、预发布、生产)与用途(核心业务、批量任务、实验性工作流)创建多组凭据。AIHubMix 控制台支持创建多个 API Key 并独立设置额度上限,结合 n8n 的凭据隔离能力,可有效控制单一凭据泄漏或超支带来的影响范围。
### 成本可观测
n8n 的 Execution 日志记录了每次节点运行的耗时与状态,但不直接显示 token 用量与费用。建议在工作流中增加一个 Code 节点,从 Chat Model 节点的输出中解析 `usage` 字段并写入数据库或监控系统。AIHubMix 控制台的账单明细可作为对账依据。
### 模型降级链路
对于关键业务工作流,建议构建模型降级机制:主链路使用 Claude Opus 4.7 或 GPT-5.5,当节点报错或超时时由 IF 节点切换至 Claude Sonnet 4.6 或 DeepSeek V4 Flash 重试。该模式可在不影响业务连续性的前提下,最大化保障服务可用性。
### 提示词模板复用
n8n 支持通过 Set 节点或全局变量管理提示词模板。建议将提示词集中维护,避免在多个工作流中复制粘贴。模型升级或迭代提示词时只需修改一处。
***
## 常见问题
**节点调用返回 404 Not Found**\
通常由 Base URL 缺失 `/v1` 后缀引起。确认凭据中的 Base URL 为 `https://aihubmix.com/v1`,并重新保存凭据。
**节点调用返回 401 Unauthorized**\
请依次确认:API Key 是否完整复制(不含前后空格);AIHubMix 账户余额是否充足
**OpenAI Chat Model 节点不支持目标模型名称**\
n8n 的节点下拉列表仅预置部分 OpenAI 官方模型。如需使用 Claude、DeepSeek 等模型,可将 `Model` 字段切换至 `Expression` 模式后手动输入完整模型名。
**自托管 n8n 实例无法访问 AIHubMix**\
请确认 n8n 部署所在服务器的出网策略已允许访问 `aihubmix.com` 域名。对于运行在容器内的 n8n,亦需确认容器网络配置未限制外部 HTTPS 请求。
***
## 参考资源
* AIHubMix :[aihubmix.com](https://aihubmix.com/)
* n8n 官网:[n8n.io](https://n8n.io/)
* n8n 文档:[docs.n8n.io](https://docs.n8n.io/)
最新更新日期:2026年5月13日
# NextAI Translator
Source: https://docs.aihubmix.com/cn/clients/NextAITranslator
在 NextAI Translator(原 OpenAI Translator)中接入 AIHubMix:用单个 API key 调用模型完成划词翻译。
[NextAI Translator](https://github.com/nextai-translator/nextai-translator)(曾用名 **OpenAI Translator**)是一款开源的 AI 翻译工具,支持浏览器插件和桌面客户端,具备划词翻译、截图 OCR、文本润色、摘要生成等功能,支持 55 种以上语言互译。
接入 AIHubMix 后,可使用 Claude、Gemini、DeepSeek 等数百个模型进行翻译, 比传统的 Google Translate 或 DeepL Translator等更加方便快捷。
***
## 安装 NextAI Translator
### 方式一: Chrome 应用商店搜索 **NextAI Translator** :
[→ Chrome Web Store 安装地址](https://chromewebstore.google.com/detail/nextai-translator/...)
### 方式二:桌面客户端
前往 GitHub Releases 页面下载对应系统版本:
[→ 下载桌面客户端](https://github.com/nextai-translator/nextai-translator/releases)
支持 Windows、macOS、Linux。
### 方式三:源码构建
适合希望自定义功能或参与开发的用户,GitHub 仓库见: [nextai-translator/nextai-translator](https://github.com/nextai-translator/nextai-translator)
> **版本提示(2026-04-21):** 当前最新版本为 `v0.6.14`。 如果您使用的是 `v0.4.33` 或 `v0.4.34` 且无法加载模型, 请回退至:[v0.4.32](https://github.com/openai-translator/openai-translator/releases/tag/v0.4.32)
***
## 配置 AiHubMix
### 第一步:获取 API Key
登录 [AiHubMix 控制台](https://aihubmix.com),充值创建并复制一个 API Key。
### 第二步:设置API服务商
打开 NextAI Translator,进入设置页面。
* **默认服务提供商**:选择 `OpenAI (`AIHubMix 提供与 OpenAI 完全兼容的原生接口`)`
* **API 密钥**:填入您的 AIHubMix API Key([aihubmix.com](https://aihubmix.com)获取)
* **API URL**:`https://aihubmix.com`(结尾不要带 `/`) NextAI Translator,进入**设置页面**。
## 模型加载问题排查
### 问题:下拉列表刷不出模型
**方法一:勾选"无模型 API 支持"选项**
在设置页面找到该选项并勾选,然后从 [AiHubMix 模型列表页](https://aihubmix.com/models) 复制模型名称, 手动粘贴到模型输入框中。
**方法二:回退版本**
若为 `v0.4.33` / `v0.4.34` 版本,请下载 [v0.4.32](https://github.com/openai-translator/openai-translator/releases/tag/v0.4.32) 并重新配置。
***
## 使用方法
* **划词翻译**:选中任意网页文字,插件自动弹出翻译结果
* **截图翻译**:点击截图按钮,框选区域即可识别并翻译
* **输入翻译**:点击图标,在输入框中粘贴文字进行翻译
* **文本润色**:切换到润色模式,对英文写作进行语法和表达优化
## 常见问题
**和 DeepL Translator、Google Translate 有什么区别?**
DeepL 和 Google Translate 使用固定翻译引擎,NextAI Translator 通过 AI 大模型翻译, 支持自由切换模型,在专业术语、长句理解上表现更好。
**支持哪些语言?**
支持中文、英文、日文、韩文、法文、德文、西班牙文等 55 种以上语言互译。
**翻译报错 / 无响应怎么办?**
1. 检查 API Key 是否填写正确,无多余空格
2. 确认 API URL 为 `https://aihubmix.com`,结尾无 `/`
3. 检查 AiHubMix 账户余额是否充足
***
## 相关资源
* [NextAI Translator GitHub](https://github.com/nextai-translator/nextai-translator)
* \[AiHubMix 模型列表]\([https://aihubmix.com/models](https://aihubmix.com/models)
***
更新时间:2026-06-01
# Obsidian
Source: https://docs.aihubmix.com/cn/clients/Obsidian
在 Obsidian 中通过 Text Generator 配置 AIHubMix 模型,用于笔记续写、整理与内容生成。
Obsidian 是一款笔记应用。本文介绍如何通过社区插件 Text Generator 接入 AIHubMix。
下载链接:[Obsidian 官网下载](https://obsidian.md/download)
## 准备工作
* 安装并打开 Obsidian。
* 在 [AIHubMix 控制台](https://aihubmix.com/token) 创建 API Key。
## 安装 Text Generator
### 1. 开启社区插件
点击 Obsidian 左下角的设置按钮。
在设置中选择 **Community plugins**,点击 **Turn on community plugins**。
### 2. 安装并启用插件
点击 **Browse**,进入社区插件市场。
搜索 `Text Generator`,点击搜索结果中的 **Text Generator**。
进入插件详情页后安装插件,再点击 **Enable** 启用。
### 3. 打开插件设置
返回 **Community plugins** 页面,在已安装插件列表中找到 **Text Generator**,点击右侧的设置按钮。
## 配置 AIHubMix
在 Text Generator 设置页面填写以下内容:
* **Provider Profile**:选择 `OpenAI Chat`。
* **API Key**:填入在 AIHubMix 控制台创建的 API Key。
* **Base Path**:填 `https://aihubmix.com/v1`。主地址暂时不可用时,使用备用地址 `https://api.inferera.com/v1`。
* **Model**:填写 AIHubMix 支持的模型 ID,可在 [模型列表](https://aihubmix.com/models) 中查询。
## 使用 Text Generator
在笔记中输入并选中需要处理的文本,点击左侧工具栏的 **Generate Text!**。
Text Generator 会将生成结果写入当前笔记。能够正常生成内容,即表示配置成功。
## 常见问题
**左侧工具栏没有 Generate Text! 按钮怎么办?**
返回 **Community plugins** 页面,确认 Text Generator 已安装并启用。
**无法生成内容怎么办?**
检查 API Key、Base Path 和模型 ID 是否填写正确。主地址暂时不可用时,将 **Base Path** 改为 `https://api.inferera.com/v1`。
***
更新时间:2026-07-22
# 懒人客服
Source: https://docs.aihubmix.com/cn/clients/On-CS
在懒人客服中接入 AIHubMix:用单个 API key 调用模型驱动智能客服自动回复。
懒人客服是一款**基于大语言模型的开源智能客服桌面工具**,核心定位是为电商商家与个人卖家提供跨平台自动回复能力。项目仓库 [cs-lazy-tools/ChatGPT-On-CS](https://github.com/cs-lazy-tools/ChatGPT-On-CS) 在 GitHub 上长期处于活跃维护状态。
右上角进入设置页面\
\
在AI配置中选择其它接口接入中。\
API地址设置填:
```text theme={null}
https://aihubmix.com/v1
```
在API Key从[本站的Key](https://aihubmix.com/token)中生成。\\
Sources:
* [GitHub - cs-lazy-tools/ChatGPT-On-CS](https://github.com/cs-lazy-tools/ChatGPT-On-CS)
* [开源免费的多平台客服 - 懒人客服(CSDN)](https://blog.csdn.net/qq_44131750/article/details/139897145)
* [懒人客服 - OpenI](https://ai.openi.cn/sites/LanRenKeFu.html)
* [基于大模型和知识库的 AI 客服工具推荐(CSDN)](https://blog.csdn.net/qq_44131750/article/details/142053976)
***
更新时间:2026-06-01
# Open Design
Source: https://docs.aihubmix.com/cn/clients/Open-Design
用一把 AIHubMix Key 把 Claude Design 开源平替变成本地 AI 设计工作室
[Open Design](https://open-design.ai/)(官网;开源仓库 [`nexu-io/open-design`](https://github.com/nexu-io/open-design))是一款**开源、本地优先的「Claude Design 平替」**。它自己不带模型,而是把你接入的 AI 当作设计引擎,直接产出网页 / 桌面 / 移动端原型、可交互 dashboard、PPT、图片和视频,并能导出为 HTML / PDF / PPTX / MP4——交付的是真实 CSS、真实组件的可运行产物,而不是画布上的像素。Apache-2.0 开源,项目数据都留在你本机。
**AIHubMix 现已是 Open Design 内置支持的 BYOK 网关**:在它的 API(BYOK)模式里选 AIHubMix,一把 Key 就能同时驱动聊天、配图、出片、配音。本文讲的就是怎么把它接进来、怎么用。
Open Design 提供两种执行模式(Settings → Execution mode):
* **Local CLI**——调用本机已装的 CLI agent(Claude Code / Codex 等)当设计引擎,能直接读写项目代码文件。
* **API provider(BYOK,自带密钥)**——不装任何 CLI,直接指向一个 OpenAI / Anthropic 兼容端点。**本文用 AIHubMix 走这条路。**
## 为什么用 AIHubMix 驱动
一把 Key,聊天、配图、出片、配音全打通。Open Design 原生的媒体生成往往要分别对接各家,配图、出视频、配音可能要配上多家厂商的 Key。
[AIHubMix](https://aihubmix.com) 是一个 **OpenAI 接口兼容的聚合网关**,一把 Key 背后同时接通 OpenAI / Anthropic / Google Gemini / DeepSeek 以及主流图像、视频、语音模型。Open Design 会**按模型名选 AIHubMix 对应的原生协议端点**——`claude*` 走 Anthropic、`gemini*` / `imagen*` 走 Gemini、其余走 OpenAI 兼容接口——于是 Claude 的思考链、Gemini 的原生出图都不打折,而你只需要管一把 Key。
### 和常见工具比
下表维度取自 [Open Design 官方 README 的 Comparison 表](https://github.com/nexu-io/open-design#comparison):
| 维度 | Claude Design / Figma / Lovable / v0 等闭源工具 | Open Design + AIHubMix |
| ------------------------------------------ | ------------------------------------------ | -------------------------- |
| 开源 | ❌ | ✅ Apache-2.0 |
| 自托管 / 桌面端 | ❌ | ✅ macOS · Windows · Vercel |
| 跑在你自己的 Agent、自带 Key(BYOK) | ❌ 锁定各自后端 | ✅ 22 个 CLI + BYOK |
| 一把 Key 混用 Claude / GPT / Gemini / DeepSeek | ❌ | ✅ |
| 设计系统 `DESIGN.md` | 专有 / 受限 | ✅ 内置 150 套 |
| 技能 / 插件 | 封闭 | ✅ 100+ 技能 · 261 插件 |
| HyperFrames(HTML→MP4 动效) | ❌ | ✅ |
| 计费 | 订阅(Pro / Team) | BYOK,按各家模型用量 |
对比维度与竞品标注以 Open Design 官方 README 的 Comparison 表为准;竞品按其闭源 / 订阅形态合并为一列,各产品更新较快,以官方最新为准。
## 三步接入
### 前置:拿到 AIHubMix Key
登录 [aihubmix.com](https://aihubmix.com),在控制台 **Keys** 页创建一个 API Key(格式形如 `sk-...`)。新建后请马上复制保存,弹窗关掉就看不到完整明文了。建议预存一点额度——后面图像、视频生成会用到(视频尤其耗额度)。
### 第 1 步:选执行模式与协议
打开 Open Design,点右上角齿轮进入 **Settings(设置)→ Execution mode(执行模式)→ 选 BYOK**,再在 **Gateways** 一行选择 **AIHubMix**。
### 第 2 步:粘贴 Key(地址已固定,无需手填)
在上图同一弹窗的 **API key** 一栏粘贴你的 Key(占位符是 `sk-...`),点 **Test** 即可验证连通(截图里显示 `Connected. Replied in … 'ok'`)。
和其他 provider 不同的是:**AIHubMix 是固定单一入口的网关,地址(`https://aihubmix.com/v1`)已经内置、在表单里对你隐藏**,你不用、也无法手填——少一处可能填错的字段。
### 第 3 步:选模型,挑一个开工
聊天、图像、视频、语音模型都在这个 BYOK 面板里选:**聊天模型**在 **Model** 下拉(Key 验证通过后即可搜索 AIHubMix 实时目录,开箱默认 `gpt-5.5`),**图像 / 视频 / 语音模型**在面板下方对应的选择器。可对着 [Arena 各领域榜](https://arena.ai/) 按用途挑,下面型号都已确认 AIHubMix 可用。
**① 聊天 / 生成网页原型(主力)** · 参考 [Code/WebDev Arena](https://arena.ai/leaderboard/code)(生成网页 UI 的人类投票,最贴 Open Design)、[Agent Arena](https://arena.ai/leaderboard/agent)(工具编排)
| 用途 | 建议模型 |
| --------------- | ---------------------------------------------------- |
| 设计推理 / 网页原型(主力) | `gpt-5.5`、`claude-opus-4-8`、`claude-fable-5` |
| 严格跟指令 / 工具调用稳 | `claude-fable-5`(Steerability 榜首)、`kimi-k2.6`(少幻觉) |
| 速度 / 批量 / 省成本 | `gpt-4o-mini`、`claude-haiku-4-5`、`deepseek-v4-flash` |
> **媒体生成靠工具调用**:聊天里出图 / 出片 / 配音是模型发起的 function call,主力优先选支持 **function calling** 的(`gpt-5.5`、Claude Opus 系最稳),否则会「聊天正常但不出图」。`claude-fable-5` 在 WebDev / Agent 双榜前列,但目录当前标注其官方渠道访问受限,**以实际可用为准**。
**② 图像模型** · 参考 [Text-to-Image Arena](https://arena.ai/leaderboard/text-to-image)
榜单靠前且 AIHubMix 可用:`gpt-image-2`、`gemini-3.1-flash-image`(即 nano-banana-2)、`gemini-3-pro-image`(nano-banana-pro)。
**③ 视频模型** · 参考 [Video Arena](https://arena.ai/leaderboard/text-to-video)
榜单靠前且 AIHubMix 可用:`doubao-seedance-2-0-260128`、`happyhorse-1.0-i2v`(Open Design 默认)、`veo-3.1-generate-preview`、`wan2.7-i2v`。
> 排名与可用型号变动都快:**排名以 [Arena](https://arena.ai/) 最新为准,模型 ID 以 AIHubMix 实时目录为准**(下拉直接搜)。
## 接入 AIHubMix 后能做什么
接入后,AIHubMix 既驱动 Open Design 的主线——用聊天模型生成原型与设计产物,也额外点亮图像、视频、语音三类媒体生成。
### 设计与原型生成(主能力)
这是 Open Design 的主场。你选定的聊天模型负责理解需求,生成**网页 / 桌面 / 移动端原型、可交互 dashboard、PPT / deck**,写设计系统、改稿评审——交付的是真 CSS、真组件的可运行产物。会话里可随时在顶栏切换模型,同一把 Key 无缝切厂商。
**BYOK 模式的能力边界**:API(BYOK)模式下聊天 + 图 / 视频 / 语音生成都齐全,但 AI **不会直接读写、编辑你的项目代码文件**,只产出 artifact。需要让 agent 直接改本地代码时,请切到 **Local CLI** 模式。
### 图像 / 视频 / 语音生成(配套媒体)
除了原型,AIHubMix 还让 Open Design 直接出图、出片、配音。这三类媒体模型都在 **BYOK 面板内**设置,每项已预选一个标着 `Default` 的默认模型(具体型号建议见上文「第 3 步:选模型」)。
#### 图片生成
在聊天里把模式切到 **Image**,直接描述需求即可,比如「Generate an image of the Dragon Boat Festival」,模型会调用内置的 `generate_image` 工具出图,支持多种比例(1:1、16:9、9:16 等)。Gemini / Imagen 系会自动走 Gemini 原生出图接口。
#### 视频生成
视频家族覆盖 **Seedance(豆包)、Wan(通义万相)、Veo(Google)、Sora(OpenAI)** 等(型号建议见上文「第 3 步:选模型」;各家文生 / 图生、时长、比例、配音的具体支持以实时目录与对应官方为准)。
聊天里把模式切到 **Video**、描述一句即可触发 `generate_video`,支持设定时长、比例。图生视频(i2v)模型需要一张参考图——**你不指定时,应用会自动取项目里最新的那张图**(要精确控制就显式指定参考图),衔接「先出图、再出片」非常顺手。视频是异步生成的,应用会自动轮询,完成后直接嵌进对话里。
#### 语音 / 配音
**语音模型**与**音色**在 BYOK 面板里也都已预选默认项(音色默认 `alloy`,另有 `echo` / `fable` / `onyx` / `nova` / `shimmer` 可选),就能在聊天里用 `generate_speech` 把任意文案转成配音——给原型 demo、视频旁白直接配音。
## 常见问题(FAQ)
Local CLI(调用本机已装 agent)能直接改本地代码,但要求你先装好对应 CLI。API(BYOK)模式不装任何 CLI,配一把 AIHubMix Key 就能直接拿到聊天 + 图 / 视频 / 语音全套,上手最快。两种模式可按需切换。
不能。BYOK 模式下 AI 只产出 artifact,不读写 / 编辑项目文件。需要让 agent 直接改本地代码时,请切到 Local CLI 模式。聊天与图 / 视频 / 语音生成不受此限制。
不需要手填。AIHubMix 在 Open Design 里是固定单一入口的网关,地址(`https://aihubmix.com/v1`)已经内置、在表单里对你隐藏。你只填 API Key 即可——地址唯一固定,少一处可能填错的字段。
Key 连接成功后,在 **Model** 下拉里就能搜索 AIHubMix 的实时模型目录(数百个模型)。下拉还预置了几款常用旗舰模型方便快速上手。只要 AIHubMix 支持该模型名就能选用,当前可用型号以实时目录为准。
* **Test 失败、连不上**:检查 API Key 是否填对、AIHubMix 账户是否有余额、本机网络能否访问 `aihubmix.com`。
* **聊天正常但不出图 / 不出片**:多半是当前聊天模型没发起工具调用。换一个**支持 function calling** 的模型(如 `gpt-5.5`、`claude-opus-4-8`),媒体生成才会触发。
* **提示某模型不支持**:以 AIHubMix 实时目录里能搜到的型号为准。
不会。Open Design 会按模型名走 AIHubMix 对应的原生协议端点:`claude*` 走 Anthropic、`gemini*` / `imagen*` 走 Gemini、其余走 OpenAI 兼容接口。原生协议保真,思考链、原生出图等专属能力都能完整发挥。
Open Design 是本地优先应用:API Key 与项目数据都保存在你本机(本地 SQLite,项目文件在 `.od/projects/` 下)。遥测默认关闭、可选开启(opt-in)。请求由本地 daemon 转发到 AIHubMix,AIHubMix 只做模型路由转发。
## 立即开始
1. 去 [aihubmix.com](https://aihubmix.com) 注册,在控制台创建 `sk-` Key 并预存一点额度(图 / 视频生成会用到)
2. 在 Open Design → Settings → Execution mode → API provider(BYOK) 选 **AIHubMix**,粘贴 Key
3. 在 Model 下拉里挑一个模型,让它跑一个落地页 + 主视觉,开始创作
下载 Open Design:[open-design.ai](https://open-design.ai/)。
# Open WebUI
Source: https://docs.aihubmix.com/cn/clients/Open-WebUI
在 Open WebUI 中配置 AIHubMix 的 OpenAI 兼容连接,添加并使用 AIHubMix 模型。
Open WebUI 是可自托管的 AI Web 客户端。管理员配置一次 AIHubMix 的 OpenAI 兼容连接后,实例中的用户即可从模型选择器使用可用模型。
## 准备工作
* 已部署 Open WebUI,并使用管理员账号登录。
* 在 [AIHubMix 控制台](https://aihubmix.com/token) 创建 API Key,格式通常为 `sk-***`。
* 如需限制可用模型,准备对应的模型 ID,例如 `gpt-5.6-terra`;不限制时可让 Open WebUI 自动读取模型列表。
## 配置 AIHubMix 连接
### 1. 打开 Connections
在聊天页点击顶部的模型选择器。没有可用模型时,点击 **Manage Connections**;也可以从管理员设置进入 **Connections**。
在 **Settings** 的 **Connections** 页面,找到 **OpenAI API**。点击右侧的新增按钮创建连接;已有连接时,可点击齿轮图标编辑。
### 2. 填写连接信息
在连接编辑窗口中设置以下内容:
* **URL**:填 `https://aihubmix.com/v1`。主地址暂时不可用时,改为备用地址 `https://api.inferera.com/v1`。
* **Auth**:选择 **Bearer**,填入在 AIHubMix 控制台创建的 API Key。
* **Provider**:保持 **Default**。
* **API Type**:选择 **Chat Completions**。
**Model IDs** 有两种方式:
* 留空:Open WebUI 从 `https://aihubmix.com/v1/models` 自动读取可用模型。
* 手动填写:输入指定模型 ID,例如 `gpt-5.6-terra`,再点击右侧 **+** 添加。适合只向实例用户开放部分模型。
填写完成后,点击窗口右下角 **Save**,再点击设置页右下角的 **Save** 保存连接。
### 3. 选择模型并验证
回到聊天页,打开模型选择器。连接生效后可在 **External** 分类中搜索并选择 AIHubMix 模型。
发送一条简单消息。能正常收到回复,说明连接与模型配置已经生效。
## 常见问题
**为什么模型选择器里没有模型?**
先确认连接窗口和 Connections 设置页都点击了 **Save**。若 Model IDs 留空,检查 Open WebUI 服务是否能访问 `https://aihubmix.com/v1/models`;也可以手动添加一个模型 ID 后重新打开模型选择器。
**URL 要不要补 `/chat/completions`?**
不要。Open WebUI 的 Connections 页面填写 API 根地址 `https://aihubmix.com/v1`,并在 **API Type** 中选择 **Chat Completions**。
**请求失败怎么办?**
检查 API Key 是否完整、URL 是否包含 `/v1`,以及模型 ID 是否正确。主地址暂时不可用时,可将 URL 改为 `https://api.inferera.com/v1`。
更新时间:2026-07-15
# 欧路翻译
Source: https://docs.aihubmix.com/cn/clients/Oulu
在欧路翻译中接入 AIHubMix:用单个 API key 接入模型,增强词典与全文翻译能力。
在主流双语翻译工具中,**欧路翻译(Eudic Translate)** 是少数同时具备「专业词典基因」与「现代 AI 翻译能力」的产品。它脱胎于深耕外语学习赛道十余年的 **欧路词典(Eudic)**,既能像沉浸式翻译那样做整页双语对照,也能直接调用词典数据库返回词形变化、例句、考试词频等深度信息——这一点是纯翻译工具无法提供的。
本文将从产品概述、版本矩阵、核心功能、详细安装与配置、AI 翻译引擎设置以及配置AIHUB等维度,完整介绍欧路翻译的使用方式。
欧路翻译与欧路词典覆盖了几乎所有主流平台:
**桌面端**
* Windows 桌面版(Microsoft Store / 绿色免安装 / 32 位老版本)
* macOS 桌面版
* Linux(AppImage / deb 安装包)
**移动端**
* iOS / iPadOS(App Store)
* Android(Google Play / 各大国内应用市场)
**浏览器扩展**
* Chrome 应用商店
* Microsoft Edge 加载项
* Firefox Add-ons
* 360 极速浏览器
下载入口统一在 [欧路软件官网下载页](https://www.eudic.net/v4/en/app/download)。
***
## 配置AIHubMix
* 左下角点击齿轮进入设置页面,选择“翻译引擎”,“下载更多翻译引擎”。\\
* 添加翻译引擎选择我们AiHubMix.\\
* 在“API Key”中输入[本站的Key](https://aihubmix.com/token)。
* 选择模型后点击认证,通过后确定即可。\\
## 核心功能详解
### 网页划词翻译
鼠标选中网页中的任意单词或句子,即可立即弹出释义气泡,支持:
* 单词:词形变化、音标、考试词频(四六级 / 考研 / 雅思 / 托福)、例句、同义词
* 句子:整句翻译并显示译文与发音
* 划词触发方式可自定义(直接弹出 / 按 Ctrl 触发 / 鼠标悬停)
### 整页双语对照翻译
点击扩展图标 → **翻译整个网页**,即可将当前页面以「原文 + 译文」段落对照的方式呈现。支持的细节配置包括:
* 翻译引擎切换(微软、谷歌、欧路、欧路 GPT、OpenAI GPT 等)
* 译文显示样式(下划线、高亮、对比色块)
* **词汇等级高亮**:可设置「只高亮六级以上单词」「只高亮托福核心词」等,适合英语学习者精读
### PDF 与文档翻译
通过欧路翻译网站,可上传 PDF、Word、PPT、Excel、EPUB 等主流格式文档,输出**保留原版式的双语对照 PDF**,并支持一键下载。这是免费功能,不需要订阅会员即可使用基础额度。
### 视频双语字幕
支持 YouTube、Bilibili、Netflix 等主流视频平台:
* 自动生成双语字幕
* 字幕中的生词可直接点击查询、加入生词本
* 字幕翻译引擎与文本翻译共用同一套配置
### AI 翻译引擎
欧路客户端内置 **欧路 AI 引擎**,底层接入了 DeepSeek 等大模型,用户无需任何配置即可使用。同时支持:
* 选择不同的官方翻译风格(直译 / 信达雅 / 学术 / 商务等)
* **自定义风格 Prompt**:用户可自行编写指令
* **个人术语库**:为专业领域(医学、法律、IT)定制译法
***
## 浏览器扩展安装与配置
### 5.1 安装扩展
1. 打开 [Chrome 应用商店欧路翻译页面](https://chromewebstore.google.com/detail/%E6%AC%A7%E8%B7%AF%E7%BF%BB%E8%AF%91-%E6%B2%89%E6%B5%B8%E7%BD%91%E9%A1%B5%E5%88%92%E8%AF%8D%E7%BF%BB%E8%AF%91%E5%B7%A5%E5%85%B7/djbfechcnkppbknmlhfcaoifgnicolin)
2. 点击 **添加至 Chrome** → 在弹窗中确认 **添加扩展程序**
3. 将扩展固定到工具栏:点击右上角拼图图标 → 找到「欧路翻译」→ 点击图钉图标
> Edge 浏览器可直接安装 Chrome 商店扩展;Firefox 用户请在 Firefox 加载项中搜索「欧路翻译」。
### 登录欧路账号
1. 点击工具栏中的欧路翻译图标
2. 在弹出面板右上角点击 **登录**
3. 使用手机号 / 邮箱 / 微信完成登录
登录后才能启用生词本同步、AI 翻译用量、个性化设置跨设备保存。
### 基础翻译设置
进入扩展设置(扩展图标 → 设置 ⚙):
| 设置项 | 推荐值 | 说明 |
| :------- | :------------------ | :---------- |
| 翻译引擎 | 欧路 GPT / OpenAI GPT | 默认引擎,用于双语对照 |
| 划词翻译 | 开启 | 支持单词与句子两种模式 |
| 鼠标悬停翻译 | 按住 Ctrl 触发 | 避免误触 |
| 网页双语对照样式 | 段落对照 | 适合长文阅读 |
| 词汇等级高亮 | 按需选择 | 学习者建议开启 |
| 自动翻译网页 | 关闭 | 节省额度,按需手动触发 |
### 触发整页翻译
* 方式一:点击工具栏扩展图标 → **翻译整个网页**
* 方式二:右键页面空白处 → **欧路翻译:翻译整个网页**
* 方式三:自定义快捷键(在扩展设置 → 快捷键中设置)
## 使用技巧
* **按需触发自动翻译**:在扩展设置中关闭「打开页面自动翻译」,改用快捷键手动触发,可大幅节约 AI 调用额度
* **划词后再按 Enter 进入深度解释**:AI 引擎会输出包含语法分析、文化背景、相似表达的扩展信息,适合精读
* **PDF 翻译走网页端而非客户端**:网页端的双语版式更精确,可一键下载结果文档
* **视频字幕慢速跟读**:在视频播放页面,字幕区域支持 0.75x / 0.5x 倍速,适合听力训练
* **多终端混用**:浏览器读 → 移动端通勤复习,是最高效的使用闭环
***
## 常见问题排查
| 现象 | 原因 | 解决方案 |
| :---------------------- | :---------------- | :---------------------- |
| 划词后不出现翻译气泡 | 扩展未授权访问当前网站 | 在扩展详情页将「网站访问」改为「在所有网站上」 |
| 整页翻译只翻译了一部分 | 网页采用懒加载,未渲染区域无法翻译 | 滚动至底部后重新触发翻译 |
| AI 翻译返回 401 / 403 | API Key 错误或额度耗尽 | 重新粘贴 Key,检查平台余额 |
| AI 翻译返回 model not found | 模型 ID 错误 | 严格按厂商文档填写,注意大小写 |
| 生词本不同步 | 未登录或不同账号 | 确认所有端使用同一账号登录 |
| PDF 翻译排版错乱 | PDF 为扫描件 | 先 OCR 转可选文本再上传 |
## 最新更新日期;2026年5月13日
更新时间:2026-06-01
# Pot
Source: https://docs.aihubmix.com/cn/clients/Pot-App
在 Pot 中接入 AIHubMix:跨平台划词翻译工具用单个 API key 接入模型,完成多语种翻译。
[**Pot**](https://pot-app.com/) 是一款开源、免费、跨平台的划词翻译与 OCR 工具,**GitHub 17.9k Stars**,基于 **Tauri 1.6** 构建(启动快、内存占用低),GPL-3.0 协议。
| 维度 | 详情 |
| :--------- | :------------------------------------------------------------------------ |
| **官网** | [pot-app.com](http://pot-app.com) |
| **源码** | [github.com/pot-app/pot-desktop](https://github.com/pot-app/pot-desktop) |
| **支持平台** | Windows / macOS / Linux(含 Wayland: KDE / Gnome / Hyprland) |
| **核心能力** | 划词翻译 · 输入翻译 · 截图 OCR · 文本朗读 · 生词本 |
| **翻译引擎** | 20+ 内置(OpenAI / Gemini / DeepL / Google / Bing / 百度 / 腾讯 / 阿里 ...) |
| **OCR 引擎** | 系统原生(Apple Vision / Win Media OCR / Tesseract)+ 云端 + 离线插件(Rapid / Paddle) |
| **扩展性** | 插件系统 + 本地 HTTP API(`127.0.0.1:60828`) |
**Pot 把你需要的翻译能力,全部塞进一个快捷键里。**
## 安装 Pot
根据平台选一种方式即可:
| 平台 | 安装命令 / 方式 |
| :------------------------ | :------------------------------------------------------------ |
| **Windows** | `winget install Pot` 或 [官网下载 .exe](https://pot-app.com/) |
| **macOS** | `brew install --cask pot` 或 [官网下载 .dmg](https://pot-app.com/) |
| **Linux (Debian/Ubuntu)** | `sudo apt install pot` |
| **Linux (Arch)** | `yay -S pot-translation` |
| **Linux (通用)** | Flatpak |
***
## 5 分钟配置:从注册到划词翻译
1. 打开 [Pot 翻译](https://pot-app.com/)后,在服务设置中选择添加内置服务\
2. 点击 OpenAI\
3. 将请求地址设置为
```text theme={null}
https://aihubmix.com
```
4. API key 从[本站的Key](https://aihubmix.com/token)中创建生成。\
5. 划到下方保存\
提示:翻译软件建议不要使用openai的o系列和gpt-5系列模型。
## 模型怎么选:翻译场景的最佳实践
划词翻译是**高频、低延迟、低复杂度**的场景,模型选型的核心是"快",不是"强"。
### ⚠️ 不推荐的:o 系列与 GPT-5 系列
**o 系列**(`o1`、`o3`、`o3-mini`、`o4-mini`)和 **GPT-5 系列** 属于**推理型(reasoning)模型**,输出前会先做一段"内部思考"。这在写代码、解数学题时非常强,但**用于翻译反而是负优化**:
| 痛点 | 说明 |
| :---------- | :---------------------------------------- |
| ⏱️ **慢** | 翻译一句话动辄等 5–30 秒,划词翻译体验崩溃 |
| 💸 **贵** | thinking tokens 也计费,单次成本是 GPT-4o 的 5–20 倍 |
| 🎯 **过度发挥** | 推理模型倾向"解释 + 改写",会把"Hello world"翻译出三段注释 |
| 🔧 **参数受限** | 不支持 `temperature`、流式输出等翻译常用调参 |
### 推荐模型(按使用频率排序)
| 模型 | 适用场景 | 速度 | 成本 |
| :------------------ | :------------ | :-- | :--- |
| `gpt-4o-mini` | 日常划词、高频翻译首选 | ⚡⚡⚡ | 💰 |
| `gpt-4o` | 长句、专业术语、文学翻译 | ⚡⚡ | 💰💰 |
| `claude-haiku-4-5` | 中英互译质量极佳,语感自然 | ⚡⚡⚡ | 💰 |
| `claude-sonnet-4-6` | 学术论文、复杂语境 | ⚡⚡ | 💰💰 |
| `gemini-2.5-flash` | 多语种、长文本 | ⚡⚡⚡ | 💰 |
| `deepseek-chat` | 中文输出极顺,性价比之王 | ⚡⚡⚡ | 💰 |
| `qwen-turbo` | 国内场景、中英术语 | ⚡⚡⚡ | 💰 |
> 一句话:翻译要的是"快、准、稳",**关掉推理,选最便宜最快的 chat 模型即可。**
***
## 进阶技巧
### 1. 自定义 Prompt(提升翻译质量)
Pot 的 ChatGPT 服务支持自定义 System Prompt,建议改为:
```text theme={null}
You are a professional translator. Translate the input text to $to.
Rules:
- Output ONLY the translation, no explanation, no quotes.
- Preserve original formatting, line breaks, and punctuation.
- For technical terms, keep the English original in parentheses.
```
### 2. 多服务并排对照
Pot 支持同时启用多个翻译服务,建议组合:
* **左栏**:`gpt-4o-mini`(速度基准)
* **中栏**:`claude-haiku-4-5`(中文语感)
* **右栏**:DeepL 或 Google(传统 MT 对照)
划一次词,三家结果同屏对比,挑最顺的那个。
### 3. OCR + 翻译联动
截图 OCR 推荐组合:
* **识别**:系统原生 OCR(macOS Vision / Win Media OCR,零延迟)
* **翻译**:AIHubMix 的 `gpt-4o-mini`
技术文档、外文截图、Switch 游戏菜单——全都能秒译。
### 4. 本地 HTTP API(自动化玩家专属)
Pot 默认在 `127.0.0.1:60828` 暴露 HTTP 接口,你可以从任何脚本调起翻译 / OCR:
```text theme={null}
# 划词翻译
curl "http://127.0.0.1:60828/translate?text=Hello"
# 截图 OCR
curl "http://127.0.0.1:60828/ocr_recognize"
```
可以接到 Raycast、Alfred、Keyboard Maestro、AutoHotkey 等工具里,做更深的工作流自动化。
***
## 常见问题(FAQ)
**Q1:填了 Key 报 401 怎么办?**\
A:检查 URL 是否多写了 `/v1`,Pot 只需要根域名 `https://aihubmix.com`。
**Q2:能用 Claude / Gemini 吗?Pot 不是只有 ChatGPT 选项?**\
A:能。AIHubMix 把所有模型都封装为 OpenAI 兼容格式,在 Pot 的"模型"字段直接填 `claude-haiku-4-5`、`gemini-2.5-flash` 即可,无需更换服务类型。
**Q3:流式输出有必要开吗?**\
A:建议开。长句翻译边出边显,体感快 3 倍。
**Q4:手机端能用 Pot 吗?**\
A:Pot 只支持桌面三端。手机用户可用其它 OpenAI 兼容客户端,同样接 AIHubMix。
**Q6:Pot 是用什么技术栈写的?性能怎么样?**\
A:基于 Tauri 1.6(Rust + Web 前端),启动 \< 1 秒,常驻内存约 80MB,比 Electron 类应用轻一个数量级。
***
## 相关链接
* 🌐 Pot 官网:[pot-app.com](https://pot-app.com/)
* 📦 Pot GitHub(17.9k ⭐):[github.com/pot-app/pot-desktop](https://github.com/pot-app/pot-desktop)
* 📖 AIHubMix × Pot 官方专题页:[pot-app.com/ads/aihubmix.html](https://pot-app.com/ads/aihubmix.html)
* 🔑 AIHubMix 模型列表:[aihubmix.com](https://aihubmix.com/)
最新更新日期:2026年5月12日
# RikkaHub
Source: https://docs.aihubmix.com/cn/clients/RikkaHub
在 RikkaHub 中配置 AIHubMix,添加并使用 AIHubMix 模型。
RikkaHub 是一款支持多个 LLM Provider 的 Android 应用。
下载链接:[RikkaHub Releases](https://github.com/rikkahub/rikkahub/releases)
## 准备工作
* 安装并打开 RikkaHub。
* 在 [AIHubMix 控制台](https://aihubmix.com/token) 创建 API Key。
## 配置 AIHubMix
### 1. 打开 Providers
在聊天页点击左上角菜单按钮,打开侧栏后点击底部的设置按钮。在设置页面点击 **Providers**。
### 2. 填写并保存 Provider 信息
在 Provider 列表中点击 **AiHubMix**,填写以下内容:
* **API Key**:填入在 AIHubMix 控制台创建的 API Key。
* **API Base Url**:填 `https://aihubmix.com/v1`。主地址暂时不可用时,使用备用地址 `https://api.inferera.com/v1`。
* **API Path**:保持默认的 `/chat/completions`,无需修改。
* **Enable**:开启。
* **Response API**:保持关闭。
填写完成后,点击页面右下角的 **Save** 保存配置。
## 添加模型
切换到 **Models** 标签页后,可以点击 **Add New Model** 自定义添加模型;也可以点击左侧的模型列表按钮,直接在列表中选择模型。
在模型列表中,可以按名称筛选模型,点击模型右侧的 **+** 添加;需要添加全部模型时,点击 **Select All**。添加完成后,可返回模型管理页面查看和管理已添加的模型。
## 测试连接
模型添加完成后,切换回 **Configuration** 标签页,点击页面底部左侧的连接测试按钮。
在弹出的模型列表中选择一个已添加的模型,然后点击 **Test**。非流式、流式和工具调用均显示通过,说明连接配置正常。
## 选择模型并验证
回到聊天页,打开左下角模型选择器,在 **AiHubMix** 分类中选择已添加的模型。
发送一条消息,能够正常收到回复即表示配置成功。
## 常见问题
**API Base Url 要填完整请求地址吗?**
不需要。**API Base Url** 填到 `/v1`,`/chat/completions` 保持在 **API Path** 的默认值中。
**添加后在模型选择器中找不到模型怎么办?**
确认 Provider 已开启并保存,再检查 **Models** 标签页中是否已添加该模型。必要时返回 Provider 配置页重新测试连接。
**请求失败怎么办?**
检查 API Key、API Base Url 和模型是否正确。主地址暂时不可用时,将 **API Base Url** 更换为 `https://api.inferera.com/v1`。
更新时间:2026-07-17
# ChatGPT 好友 (uTools)
Source: https://docs.aihubmix.com/cn/clients/Utools-ChatGPT
在 uTools「ChatGPT 好友」中接入 AIHubMix:在快捷启动器里用单个 API key 调用模型,全局唤起即用。
API 地址填:
```
https://aihubmix.com
```
在API Key从[本站的Key](https://aihubmix.com/token)中生成。\
\\
***
更新时间:2026-06-01
# WorkBuddy
Source: https://docs.aihubmix.com/cn/clients/WorkBuddy
在 WorkBuddy 中配置 AIHubMix:添加 Custom 模型后使用 AIHubMix 支持的任意模型。
WorkBuddy 可以添加自定义 OpenAI 兼容模型。把 AIHubMix 配进去后,就能在 WorkBuddy 的模型选择器里调用 AIHubMix 支持的 GPT、Claude、Gemini、DeepSeek、GLM 等模型。
## 准备工作
* [WorkBuddy](https://www.codebuddy.cn/work/) 已安装,并且可以正常打开。
* 在 [AIHubMix 控制台](https://aihubmix.com/token) 创建好的 API Key,格式通常是 `sk-***`。
* 要使用的模型 ID,例如 `gpt-5.5`、`gemini-3.5-flash`、`deepseek-chat`。模型 ID 建议直接从 AIHubMix 模型列表复制。
## 前端界面配置 AIHubMix 模型
打开 WorkBuddy,在输入框右下角点击当前模型选择器,例如 **Auto**。
把模型列表拉到底部,点击 **Configure custom models**。
点击 **Add Model**,然后在 **Provider** 下拉框里选择 **Custom**。
接着填写这几项:
* **Endpoint**:通常填 `https://aihubmix.com/v1`。如果主地址暂时不可用,改成备用地址 `https://api.inferera.com/v1`。
* **API Key**:填你在 [AIHubMix 控制台](https://aihubmix.com/token) 创建的 Key。
* **Model Name**:填要用的模型 ID,例如 `gpt-5.5`。
* **Advanced Settings**:按模型能力勾选。需要工具调用就开 **Tool Calling**;模型支持看图就开 **Image Input**;推理模型可以开 **Reasoning**。
填好后点击 **Save**。
保存后回到模型列表,在 **Custom Models** 区域选择刚添加的模型。
## 通过配置文件添加模型
WorkBuddy 的自定义模型会保存到本地 `models.json`。如果不想从前端界面里逐项填写,可以编辑这个文件:
```text theme={null}
%USERPROFILE%\.workbuddy\models.json
```
文件内容是一个模型数组。下面是 AIHubMix 的示例配置:
```json theme={null}
[
{
"id": "gpt-5.5",
"name": "gpt-5.5",
"vendor": "Custom",
"url": "https://aihubmix.com/v1",
"apiKey": "sk-***",
"supportsToolCall": true,
"supportsImages": true,
"supportsReasoning": false,
"useCustomProtocol": false
}
]
```
如果当前 API 主地址不可用,把 `url` 改成备用地址即可:
```json theme={null}
"url": "https://api.inferera.com/v1"
```
字段含义和前端界面里的选项基本一致:`id` / `name` 填模型 ID,`vendor` 使用 `Custom`,`apiKey` 填 AIHubMix Key,`supportsImages` 对应 **Image Input**,`supportsToolCall` 对应 **Tool Calling**。改完后重启 WorkBuddy,或重新打开模型选择器查看。
## 验证效果
选中自定义模型后,发一条简单消息测试一下,比如让 WorkBuddy 简短介绍 AIHubMix。能正常回复,就说明配置已经生效。
如果配置时开启了 **Image Input**,可以再上传一张图片,让 WorkBuddy 根据图片内容回答。这样能顺手确认图片输入能力已经生效。
## 常见问题
**为什么要选择 Custom?**
AIHubMix 提供的是 OpenAI 兼容接口,需要手动填写 Endpoint、API Key 和 Model Name。选择内置供应商时,WorkBuddy 可能会自动使用对方平台自己的接口地址。
**保存后看不到模型怎么办?**
重新打开模型选择器,滑到 **Custom Models** 区域。如果还是没有出现,检查是否点了 **Save**,以及 Model Name 是否为空。手动改配置文件时,检查 `%USERPROFILE%\.workbuddy\models.json` 是否是合法 JSON。
**请求失败怎么办?**
检查 Endpoint 是否带 `/v1`,API Key 是否完整,Model Name 是否和 AIHubMix 模型 ID 一致。若主地址不可用,可将 Endpoint 改为 `https://api.inferera.com/v1`。
更新时间:2026-07-10
# Zotero
Source: https://docs.aihubmix.com/cn/clients/Zotero
在 Zotero 中接入 AIHubMix:文献管理工具通过插件用单个 API key 调用模型,用于文献总结与问答。
本文档基于 zotero-gpt v3.1.4 与 zotero-pdf-translate 最新发布版本,介绍两款插件分别接入 AIHubMix 的完整配置流程。
## 环境准备
在配置任一插件前,需满足以下条件:
* 已安装 Zotero 7 或 Zotero 6(zotero-gpt v3.1.4 同时支持两个主版本,推荐 Zotero 7)
* 已在 [aihubmix.com](http://aihubmix.com) 完成账号注册,并在控制台创建 API 凭据(以 `sk-` 开头)
## zotero-gpt v3.1.4 配置
zotero-gpt 提供基于文献内容的对话式阅读体验,支持选中文本提问、文献摘要生成、AI 标注、AI 大纲生成等高频操作。3.x 版本在保留传统对话能力的基础上,引入了命令标签(Command Tag)体系,使用户可将自定义提示词与 Zotero API 代码片段组合为一键触发的工作单元。
### 插件安装
访问插件项目的 GitHub Releases 页面,下载最新版本的 `.xpi` 文件:
[https://github.com/MuiseDestiny/zotero-gpt/releases](https://github.com/MuiseDestiny/zotero-gpt/releases)
打开 Zotero,进入 `工具` → `附加组件`,将下载完成的 `.xpi` 文件拖入插件管理窗口,按照提示完成安装并重启 Zotero。
下载链接:[https://github.com/MuiseDestiny/zotero-gpt/releases](https://github.com/MuiseDestiny/zotero-gpt/releases)
安装好插件后在编辑中找到设置(老版本在编辑中首选项)。找到GPT的设置界面
按照如图所示配置 Base API,并输入[API key](https://aihubmix.com/token)
或者使用以下命令设置
首选使用「ctrl+/」打开使用窗口\
\
输入
```text theme={null}
/api https://aihubmix.com
```
并回车\
\
输入
```text theme={null}
/secretKey + 密钥 sk-***
```
\
切换模型命令
```text theme={null}
/model gpt-3.5-turbo-0125
```
\
选择自己要用的模型之后就可以使用了。\\
## 翻译插件zotero-pdf-translate 配置
zotero-pdf-translate 提供 PDF 阅读过程中的实时翻译能力,支持划词翻译、整段翻译、双语对照阅读等模式。该插件原生支持多种翻译引擎。
下载链接:[https://github.com/windingwind/zotero-pdf-translate/releases](https://github.com/windingwind/zotero-pdf-translate/releases)
编辑中找到设置(老版本在编辑中首选项)。找到翻译的设置界面\
接口地址填写:
```text theme={null}
https://aihubmix.com/v1/chat/completions
```
不用管状态是否显示可用 填上之后就可以了。\\
## 工作流场景
科研工作者通常将两款插件协同使用,形成完整的 AI 辅助阅读闭环:
在文献初筛阶段,使用 zotero-gpt 对论文摘要进行结构化提炼,快速判断文献相关性。
在精读阶段,对 PDF 中的难点段落使用 zotero-pdf-translate 进行划词翻译,并使用 zotero-gpt 对关键方法论展开追问。
在笔记整理阶段,使用 zotero-gpt 基于选中文本生成结构化笔记或 Markdown 摘要,自动归档至 Zotero 的笔记系统。结合 3.x 版本的命令标签机制,可将常用的提炼、归纳、术语解释提示词固化为一键触发的标签,进一步缩短重复操作的时间成本。
整套工作流在同一 Zotero 主界面中完成,无需切换至外部浏览器或对话工具,也无需复制粘贴文献内容。
***
## 常见问题
**接口返回 404 Not Found**\
zotero-gpt 中 `API URL` 字段应填入 `https://aihubmix.com/v1`。zotero-pdf-translate 中接口地址应填入完整路径 `https://aihubmix.com/v1/chat/completions`。两者填写规则不同,混用是常见的配置错误。
**旧版斜杠命令(/api、/secretKey、/model)失效**\
该组命令为 zotero-gpt 2.x 及更早版本的快速配置方式,在 3.x 版本中已不再作为官方推荐做法记录。如使用 3.x 版本,请通过插件设置面板完成 API URL、API Key 与 Model 字段的填写。
**zotero-pdf-translate 状态栏显示"未知"**\
该状态显示并不代表配置失败,可直接进行实际翻译验证。若翻译可正常返回结果,则配置已生效。
**zotero-gpt 安装路径找不到** `编辑 → 设置`\
3.x 版本的安装入口为 `工具 → 附加组件`。`编辑 → 设置` 在 Zotero 7 中已不承担插件安装职能,部分旧版教程描述的路径不再适用。
***
## 参考资源
* AIHubMix 官网:[aihubmix.com](https://aihubmix.com/)
* Zotero 官网:[zotero.org](https://www.zotero.org/)
* zotero-gpt 插件仓库:[github.com/MuiseDestiny/zotero-gpt](https://github.com/MuiseDestiny/zotero-gpt)
* zotero-gpt Releases 页面:[github.com/MuiseDestiny/zotero-gpt/releases](https://github.com/MuiseDestiny/zotero-gpt/releases)
* zotero-pdf-translate 插件仓库:[github.com/windingwind/zotero-pdf-translate](https://github.com/windingwind/zotero-pdf-translate)
最新更新日期:2026年5月13日
# cc-connect
Source: https://docs.aihubmix.com/cn/clients/ai-agent-tool-cc-connect
cc-connect 通过 AIHubMix 桥接 Claude Code、Codex、Gemini CLI 等 AI Agent,以单个 API key 统一调用主流模型。
Anthropic 官方的 **Claude Code Channels** 于 2026 年 3 月发布,允许开发者通过 Telegram、Discord 或 iMessage 向本地运行的 Claude Code 发送指令。该方案配置简单,但存在明显局限:仅支持三个平台、仅支持 Claude Code 单一 Agent,且不开放源代码。
对于需要接入飞书、钉钉、企业微信、Slack 或同时调度多个 AI Agent 的团队,**cc-connect** 提供了一种更完整的开源替代路径。cc-connect 是一个自托管的 AI Agent 桥接工具,将运行于本地的 AI 编程助手(Claude Code、Codex CLI、Gemini CLI 等 10 余种 Agent)接入 11 个主流即时通讯平台\*\*。\*\*
## cc-connect 与 Claude Code Channels 的对比
| 对比维度 | cc-connect | Claude Code Channels | OpenClaw | claude-code-telegram |
| ---------- | ---------- | -------------------- | ------------- | -------------------- |
| 支持平台数 | **11 个** | 3 个 | 5 个 | 1 个 |
| 支持 Agent 数 | **10+** | 仅 Claude Code | 仅 Claude Code | 仅 Claude Code |
| 开源 / 自托管 | ✅ | ❌ | ✅ | ✅ |
| 无需公网 IP | ✅(大多数平台) | ✅ | ✅ | ✅ |
| Web 管理后台 | ✅ | ❌ | ❌ | ❌ |
| 多项目管理 | ✅ | ❌ | ❌ | ❌ |
| 定时任务 | ✅ | ❌ | ❌ | ❌ |
| 语音 / 图片支持 | ✅ | ❌ | ⚠️ | ⚠️ |
**适用场景:** 若仅需在 Telegram 或 Discord 上与 Claude Code 交互,Claude Code Channels 已能满足需求。若需要接入飞书、钉钉、企业微信、微信等平台,或需要同时管理多个 Agent 和多个项目,cc-connect 是目前开源社区中功能最完整的方案。
## 支持平台一览
cc-connect 目前支持 11 个主流聊天平台,绝大多数采用 WebSocket 或长轮询连接方式,所有通信均为出站连接,**无需在服务器或防火墙上开放入站端口**:
| 平台 | 连接方式 | 需要公网 IP? |
| ------------- | ----------- | ------------ |
| Telegram | 长轮询 | ❌ 不需要 |
| Discord | Gateway | ❌ 不需要 |
| Slack | Socket Mode | ❌ 不需要 |
| 飞书 / Lark | WebSocket | ❌ 不需要 |
| 钉钉 | Stream | ❌ 不需要 |
| 微信个人号(ilink) | HTTP 长轮询 | ❌ 不需要 |
| 微博 | WebSocket | ❌ 不需要 |
| 企业微信 | WebSocket | ❌ 不需要(WS 模式) |
| QQ / QQ 官方机器人 | WebSocket | ❌ 不需要 |
| LINE | Webhook | ✅ 需要 |
这意味着笔记本、家用服务器或企业内网机器,只要能访问互联网,即可运行 cc-connect,无需申请固定公网 IP、无需配置内网穿透。
## 支持的 AI Agent
cc-connect 目前支持以下 AI 编程助手:
| Agent | 提供方 | 状态 |
| ------------------------- | --------- | ----------- |
| Claude Code | Anthropic | ✅ 已支持 |
| Codex CLI | OpenAI | ✅ 已支持 |
| Gemini CLI | Google | ✅ 已支持 |
| Cursor Agent | Cursor | ✅ 已支持 |
| Kimi CLI | Moonshot | ✅ 已支持 |
| OpenCode / iFlow CLI / Pi | — | ✅ 已支持 |
| Devin | Cognition | ✅ 通过 ACP 协议 |
| 任意 ACP 兼容 Agent | — | ✅ 通过 ACP 协议 |
在同一个群聊中,可以同时绑定多个 Agent——例如由 Claude Code 负责代码生成,由 Gemini CLI 进行独立审查,两者的回复均出现在同一个会话线程中。这是 cc-connect 在 **AI Agent 编排**场景下的核心能力。
## 为什么选择我们作为 API 提供商
运行 Claude Code 或其他 Agent,需要对应模型的 API 访问权限。[**AIHubMix**](https://aihubmix.com/?aff=mGTx) 是一站式 AI 模型 API 聚合平台,尤其适合 cc-connect 的多 Agent 使用场景。
### 单一 Key,覆盖 500+ 模型
AIHubMix 聚合了 Claude(Anthropic)、GPT(OpenAI)、Gemini(Google)、DeepSeek、通义千问等 500+ 模型,**一个 API Key 即可驱动全部 Agent**。在多 Agent 场景下,无需分别注册和维护 Anthropic、OpenAI、Google 的独立账号。
### 原生格式兼容,无需修改代码
AIHubMix 同时支持 **OpenAI、Anthropic、Gemini 三种原生 API 格式**:
* Claude Code 通过 Anthropic SDK 格式连接,直接替换端点,无感知切换
* Codex CLI 通过 OpenAI 格式连接,无需任何代码修改
* Gemini CLI 通过 Google 原生格式连接,开箱即用
仅需将各 Agent 的 `base_url` 指向 AIHubMix 端点,并替换 API Key,其余配置保持不变。
### 无限并发,企业级稳定性
AIHubMix 基于谷歌云集群运行,支持**无限并发**。当 cc-connect 同时处理多个用户、多个 Agent、多个项目的请求时,不会因个人账号速率限制导致请求排队或失败。
### 按量计费,支持开票
无月费门槛,按实际消耗计费,平台包含若干免费模型。企业用户可申请开具增值税发票。
**→ [前往注册 AIHubMix](https://aihubmix.com/?aff=mGTx)**,获取 API Key 后,按照以下教程完成 cc-connect 的配置。
***
## 接入教程:将 Claude Code 接入飞书(AIHubMix 版)
以下教程以 **飞书 + Claude Code + AIHubMix** 为例,完整演示从零开始的接入流程。其他平台(Telegram、钉钉、Slack 等)的接入步骤结构相同,仅需替换第三步的平台配置部分。
### 前置条件
* 运行 macOS 或 Linux 的机器(可以是本地笔记本,能访问互联网即可)
* 已安装并完成登录的 [Claude Code](https://code.claude.com) ,可参考 AIHubMix 官方文档
* 已注册 [AIHubMix](https://aihubmix.com/?aff=mGTx) 并获取 API Key
* 飞书账号,以及企业自建应用的创建权限
***
### 第一步:获取 AIHubMix API Key
1. 登录 [aihubmix.com](https://aihubmix.com/?aff=mGTx)
2. 进入 **API Keys** → **创建新 Key**
3. 复制 Key(格式 `sk-xxxxxxxxxxxxxxxx`)
在终端中配置环境变量,使 Claude Code 通过 AIHubMix 端点访问模型:
```bash theme={null}
export ANTHROPIC_BASE_URL=https://aihubmix.com/v1
export ANTHROPIC_API_KEY=sk-your-aihubmix-key
```
> AIHubMix 的 Anthropic 格式端点与 Anthropic 官方端点完全兼容,Claude Code 无需感知差异。Claude Sonnet 4、Claude Opus 4 等所有主流模型均可通过该端点调用。
### 第二步:安装 cc-connect
```bash theme={null}
# npm(推荐)
npm install -g cc-connect
# Homebrew(macOS / Linux)
brew install cc-connect
# 二进制文件(Linux amd64)
curl -L -o cc-connect https://github.com/chenhg5/cc-connect/releases/latest/download/cc-connect-linux-amd64
chmod +x cc-connect && sudo mv cc-connect /usr/local/bin/
```
验证安装:
```bash theme={null}
cc-connect --version
```
### 第三步:在飞书开放平台创建企业自建应用
1. 访问 [open.feishu.cn](https://open.feishu.cn),登录后进入 **开发者后台**
2. 点击 **创建企业自建应用**,填写应用名称和描述
3. 进入应用详情页,点击左侧菜单 **添加应用能力** → 选择 **机器人**
4. 在 **事件订阅** 页面,订阅以下事件:
* `im.message.receive_v1`(接收消息)
5. 在 **权限管理** 页面,申请以下权限:
* `im:message`(读取会话消息)
* `im:message:send_as_bot`(以应用身份发送消息)
6. 发布应用版本并完成审核
完成后,在 **凭证与基础信息** 页面获取以下三项内容:
| 参数 | 位置 |
| -------------------- | ------------------------- |
| `app_id` | 凭证与基础信息 → App ID |
| `app_secret` | 凭证与基础信息 → App Secret |
| `verification_token` | 事件订阅 → Verification Token |
> **关于管理员用户 ID:** 在飞书中发送一条消息给该机器人,然后在事件订阅日志中查看 `sender.open_id` 字段,即为当前用户的 Open ID,用于配置 `admin_from`。
### 第四步:配置 cc-connect
**方式一:Web UI(推荐)**
```bash theme={null}
cc-connect web
```
浏览器访问 `http://localhost:7070`,按照以下顺序操作:
1. 点击 **新建项目**
2. **Agent** 选择 `Claude Code`
3. **工作目录** 填写项目路径(例如 `/Users/you/my-project`)
4. **Provider** 填写 AIHubMix 信息:
* Base URL:`https://aihubmix.com/v1`
* API Key:`sk-your-aihubmix-key`
5. **平台** 选择 `飞书`,填写 App ID、App Secret、Verification Token
6. **admin\_from** 填写管理员的飞书 Open ID
7. 点击 **保存并启动**
**方式二:手动编辑配置文件**
```bash theme={null}
mkdir -p ~/.cc-connect
```
创建 `~/.cc-connect/config.toml`,内容如下:
```toml theme={null}
[[projects]]
name = "my-project"
work_dir = "/Users/you/my-project"
admin_from = "ou_xxxxxxxxxxxxxxxx" # 管理员的飞书 Open ID
[projects.agent]
type = "claude-code"
[projects.agent.provider]
name = "AIHubMix"
base_url = "https://aihubmix.com/v1"
api_key = "sk-your-aihubmix-key"
[[projects.platforms]]
type = "feishu"
app_id = "cli_xxxxxxxxxxxxxxxx"
app_secret = "xxxxxxxxxxxxxxxx"
verification_token = "xxxxxxxxxxxxxxxx"
```
### 第五步:启动 cc-connect
```bash theme={null}
cc-connect
```
控制台输出以下日志,说明服务已正常运行:
```text theme={null}
[INFO] Feishu WebSocket connected
[INFO] Claude Code agent ready — project: my-project
[INFO] cc-connect started successfully
```
***
### 第六步:在飞书中与 Agent 交互
在飞书中向机器人发送消息,或在群聊中 `@机器人`:
示例:
```text theme={null}
请检查最近的代码变更,指出潜在的性能问题并给出优化建议。
```
```text theme={null}
/model 查看当前可用模型(由 AIHubMix 提供)
/mode yolo 自动批准所有工具调用
/dir ~/projects/backend 切换到指定项目目录
/new 版本规划讨论 新建独立会话
```
Claude Code Agent 具备完整的本地文件系统访问权限,处理完成后将回复直接发送至飞书会话。
## 将 Claude Code 接入微信(AIHubMix 版)
### 进阶配置:多 Agent 场景,同一 AIHubMix Key 驱动 Claude 与 Gemini
在同一个 cc-connect 实例中,可以同时运行 Claude Code 和 Gemini CLI,两者共用同一个 AIHubMix Key:
```toml theme={null}
# 项目一:Claude Code 负责代码生成
[[projects]]
name = "claude-project"
work_dir = "/Users/you/project-a"
[projects.agent]
type = "claude-code"
[projects.agent.provider]
base_url = "https://aihubmix.com/v1"
api_key = "sk-your-aihubmix-key"
[[projects.platforms]]
type = "feishu"
app_id = "cli_xxxxxxxxxxxxxxxx"
app_secret = "xxxxxxxxxxxxxxxx"
verification_token = "xxxxxxxxxxxxxxxx"
# 项目二:Gemini CLI 负责独立 Code Review
[[projects]]
name = "gemini-review"
work_dir = "/Users/you/project-a"
[projects.agent]
type = "gemini"
[projects.agent.provider]
base_url = "https://aihubmix.com/v1"
api_key = "sk-your-aihubmix-key" # 同一个 Key
[[projects.platforms]]
type = "feishu"
app_id = "cli_yyyyyyyyyyyyyyyy" # 第二个飞书应用
app_secret = "yyyyyyyyyyyyyyyy"
verification_token = "yyyyyyyyyyyyyyyy"
```
两个机器人均在飞书中可用,分别承担代码生成与审查职责,均通过 AIHubMix 统一计费,无需维护多个 API 账号。
## 核心功能参考
### 斜杠命令
| 命令 | 说明 |
| ---------------------- | ------------------- |
| `/new [名称]` | 创建新会话 |
| `/list` | 列出所有会话 |
| `/switch ` | 切换至指定会话 |
| `/current` | 查看当前会话信息 |
| `/model` | 查看或切换模型 |
| `/mode yolo` | 自动批准所有工具调用 |
| `/mode default` | 每次工具调用前手动确认 |
| `/dir <路径>` | 切换工作目录 |
| `/dir -` | 返回上一个工作目录 |
| `/cron add <表达式> <任务>` | 添加定时任务 |
| `/memory` | 读写 Agent 记忆文件 |
| `/provider list` | 查看已配置的 API Provider |
### 定时任务
cc-connect 支持通过自然语言描述创建 cron 任务,Agent 将在指定时间自动执行并将结果推送至聊天:
```text theme={null}
/cron add 0 9 * * 1 总结本周所有仓库的 commit 记录并列出未关闭的 issue
/cron add 0 22 * * * 检查 package.json 依赖项是否存在新的安全公告
```
### 多模态支持
cc-connect 支持语音消息输入(自动转文字后传递给 Agent)以及文件和图片回传(Agent 生成的图表、PDF、截图可直接作为附件发送至聊天)。
### 企业级用户隔离
通过 `run_as_user` 配置,每个项目可以独立的 Unix 用户身份运行 Agent,在操作系统层面实现文件系统隔离,适用于多人共用同一台服务器的团队场景。
## 常见问题(Q\&A)
**Q: cc-connect 与 Claude Code Channels 是否可以同时使用?**
A: 可以。两者互不冲突,本质上均为向本地 Claude Code 进程传递指令,仅接入渠道不同。
**Q: AIHubMix 是否有地域访问限制?**
A: 无。AIHubMix 基于谷歌云集群运行,全球均可访问。
**Q: cc-connect 是否会将代码内容上传至第三方?**
A: 不会。cc-connect 仅承担消息转发职责,代码内容由本地 AI Agent 处理。AIHubMix 作为模型 API 提供商,提供的是推理接口,不会主动存储用户的项目代码。
**Q: 飞书群聊和私聊均可使用吗?**
A: 均可。飞书平台支持机器人私聊(单聊)和群聊中的 `@提及` 两种交互方式。
**Q: 已有 Anthropic 官方账号,是否仍需要 AIHubMix?**
A: 不强制。若仅使用 Claude Code 单一 Agent,可直接使用 Anthropic 官方账号。若需同时驱动 Claude Code、Gemini CLI 等多个 Agent,或需要更高并发上限,AIHubMix 的统一 Key 方案可显著降低运维成本。
## 总结
cc-connect 是目前开源社区中功能覆盖最完整的 AI Agent 聊天平台桥接工具,支持 11 个平台、10+ Agent、无需公网 IP、内置 Web 管理后台,并提供多项目管理、定时任务、多模态输入及企业级用户隔离能力。
搭配 [**AIHubMix**](https://aihubmix.com/?aff=mGTx) 作为统一 API 提供商,可通过单一 Key 驱动 Claude Code、Codex CLI、Gemini CLI 等全部 Agent,原生格式兼容、无限并发、全球可访问,无需维护多个模型提供商账号。
**快速开始:**
1. [**注册 AIHubMix**](https://aihubmix.com/?aff=mGTx) — 获取统一 API Key
2. [**安装 cc-connect**](https://github.com/chenhg5/cc-connect) — `npm install -g cc-connect`
3. **启动 Web 管理后台** — `cc-connect web`,在浏览器中完成全部配置
4. **在飞书 / 钉钉 / Slack / Telegram 中开始交互** — 随时随地控制本地 AI Agent
## *相关文档:[cc-connect GitHub](https://github.com/chenhg5/cc-connect) · [AIHubMix 文档](https://aihubmix.com/?aff=mGTx) · [Claude Code Channels 官方文档](https://code.claude.com/docs/en/channels)*
更新时间:2026-06-01
# All API Hub x AIHubMix 配置指南
Source: https://docs.aihubmix.com/cn/clients/all-api-hub
本文介绍如何使用第三方开源浏览器扩展 All API Hub 辅助管理 AIHubMix API Key、账户余额、模型价格和模型列表,并支持导出至 Cherry Studio、Claude Code Router、Kilo Code 等 AI 工具。
# All API Hub x AIHubMix 配置指南
AIHubMix 支持通过统一 API 调用 GPT、Claude、Gemini、DeepSeek、Grok 等多种主流 700➕AI 模型。对于经常使用多模型、多客户端或多 API Key 的开发者来说,密钥保存、余额查看和模型价格查询,是日常使用中最常见的管理需求。
本文介绍一款第三方开源浏览器扩展 **All API Hub**,帮助用户辅助管理 AIHubMix API Key、账户余额、模型价格和模型列表,并将密钥配置导出到常用 AI 客户端工具中。
***
## 第三方工具声明
All API Hub 是第三方开源浏览器扩展,并非 AIHubMix 官方产品。
AIHubMix 不参与该扩展的开发、运营、维护或数据存储,也无法对其安全性、稳定性、兼容性或后续更新提供保证。
本文仅介绍 All API Hub 与 AIHubMix 的兼容使用方式,不构成官方推荐、安全承诺或使用背书。使用任何第三方工具前,请用户自行评估风险,并妥善保管 API Key 等敏感信息。
***
## 为什么 AIHubMix 用户可能需要 All API Hub?
随着 AIHubMix 支持的模型数量不断增加,用户在实际使用中可能会频繁处理以下问题:
* API Key 是否已正确保存
* 当前账户余额是否充足
* 不同模型的输入、输出价格是多少
* 某个模型是否适合当前客户端或调用场景
* 如何将 Base URL 与 API Key 快速配置到不同 AI 工具中
如果同时使用 Cherry Studio、Claude Code Router、Kilo Code 等客户端工具,手动复制、保存和维护 API Key 容易增加管理成本。
All API Hub 可以作为辅助工具,帮助用户集中查看和管理:
* AIHubMix 账户余额
* AIHubMix API Key
* AIHubMix 模型列表
* AIHubMix 模型价格
* 常用 AI 客户端导出配置
***
## All API Hub 是什么?
All API Hub 是一款面向 AI API 用户的第三方开源浏览器扩展,主要用于统一管理 API 账号、API Key、账户余额和模型价格信息。
配合 AIHubMix 使用时,All API Hub 可以在创建 API Key 后辅助保存完整密钥,并将 AIHubMix 的 Base URL 与 API Key 导出到常见 AI 客户端中。
***
## All API Hub 的核心功能
### 1. 查看 AIHubMix 账户余额
添加 AIHubMix 账号后,用户可以在 All API Hub 中查看账户余额状态,减少频繁打开控制台确认余额的操作。
### 2. 保存仅显示一次的 AIHubMix API Key
出于安全考虑,AIHubMix API Key 通常只会在创建时完整显示一次。如果用户没有及时保存,后续无法再次查看完整 Key,只能重新创建新的 API Key。
All API Hub 可以在创建密钥后辅助保存完整 API Key,方便后续复制、迁移或导出到其他客户端。
### 3. 查询 AIHubMix 模型价格
All API Hub 支持查看 AIHubMix 模型列表及价格信息,包括:
* 模型名称
* 输入价格
* 输出价格
* 模型搜索
* 可用模型筛选
这对于需要控制调用成本、比较模型价格或选择合适模型的开发者很有帮助。
### 4. 导出到常用 AI 客户端
All API Hub 支持将 AIHubMix API Key 和 Base URL 导出到部分常见 AI 客户端工具,例如:
* Cherry Studio
* CC Switch
* Kilo Code
* CLIProxyAPI
* Claude Code Router
用户可以减少重复配置,提高多客户端使用效率。
***
## 如何安装 All API Hub?
为了获得自动更新和更稳定的使用体验,建议优先通过与你的浏览器匹配的官方扩展商店安装:
* Chrome 浏览器:[Chrome Web Store](https://chromewebstore.google.com/detail/lapnciffpekdengooeolaienkeoilfeo)
* Edge 浏览器:[Microsoft Edge Add-ons](https://microsoftedge.microsoft.com/addons/detail/pcokpjaffghgipcgjhapgdpeddlhblaa)
* Firefox 浏览器:[Firefox Add-ons](https://addons.mozilla.org/firefox/addon/\{bc73541a-133d-4b50-b261-36ea20df0d24})
其他浏览器或设备可参考以下安装方式:
* QQ 浏览器、360 浏览器、猎豹浏览器、Brave、Vivaldi、Opera 等 Chromium 内核浏览器:[QQ / 360 等浏览器安装指南](https://all-api-hub.qixing1217.top/other-browser-install.html)
* Safari Mac 版:[Safari 安装指南](https://all-api-hub.qixing1217.top/safari-install.html)
* Edge 手机版、Firefox Android、Kiwi 等移动端浏览器:[移动端使用指南](https://all-api-hub.qixing1217.top/faq.html#mobile-browser-support)
* 无法使用商店版时,可从 [GitHub Releases](https://github.com/qixing-jk/all-api-hub/releases/latest) 下载 Stable 包手动安装。手动安装版本通常不会像商店版一样自动更新,后续升级需要重新下载并安装。
***
## 如何在 All API Hub 中添加 AIHubMix 账号?
### 第一步:登录 AIHubMix 控制台
打开 AIHubMix 控制台:
[https://console.aihubmix.com](https://console.aihubmix.com)
并确认当前浏览器已登录 AIHubMix 账号。
### 第二步:打开 All API Hub 扩展
点击浏览器右上角的 All API Hub 插件图标,进入扩展界面。
### 第三步:添加账号
点击“添加账号”,填写 AIHubMix 控制台地址。
### 第四步:自动识别账号
点击“自动识别”,All API Hub 会尝试识别当前 AIHubMix 账号类型与相关信息。
### 第五步:确认并保存账号
确认识别结果无误后,保存账号配置。
***
## 如何保存 AIHubMix API Key?
AIHubMix API Key 出于安全原因,仅在创建时完整显示一次。建议用户在创建 API Key 后立即保存,避免后续无法再次查看完整密钥。
推荐流程如下:
1. 在 All API Hub 中添加 AIHubMix 账号
2. 前往 AIHubMix 控制台创建 API Key
3. 在 Key 完整显示时及时保存
4. 将完整 API Key 保存到凭据库
5. 按需导出到 AI 客户端工具
保存后的 API Key 可用于:
* 配置 AI 客户端
* 进行 API 调试
* 在多工具间迁移
* 管理多个 API Key
* 备份常用调用凭据
请注意:API Key 属于敏感信息,请勿公开分享、上传到不可信平台或提交到公开代码仓库。
***
## 如何查询 AIHubMix 模型价格?
在 All API Hub 中,用户可以查看 AIHubMix 的模型列表与价格信息。
可查看内容包括:
* 模型名称
* 模型列表
* 输入价格
* 输出价格
* 模型搜索结果
这可以帮助开发者在不同模型之间进行成本比较,例如在高性能模型、低成本模型、长上下文模型和特定任务模型之间做选择。
***
## 如何导出 AIHubMix API Key 到 AI 客户端?
All API Hub 支持将 AIHubMix 的 API Key 与 Base URL 导出到常见 AI 工具中。
当前支持的工具包括:
* Cherry Studio
* CC Switch
* Kilo Code
* Claude Code Router
* CLIProxyAPI
导出后,用户可以更方便地在不同客户端中调用 AIHubMix API,减少手动复制 Base URL 和 API Key 的重复操作。
***
## All API Hub 与 AI 客户端有什么区别?
All API Hub 主要用于 API 账号、密钥、余额和模型价格管理;AI 客户端则主要用于对话、代码生成、Agent 工作流或实际模型调用。
| 功能 | All API Hub | AI 客户端 |
| ---------- | ----------- | ------ |
| API Key 管理 | 支持 | 通常不支持 |
| 余额查看 | 支持 | 通常不支持 |
| 模型价格查询 | 支持 | 通常不支持 |
| AI 对话 | 不支持 | 支持 |
| Agent 工作流 | 不支持 | 支持 |
| 模型调用 | 不作为主要用途 | 支持 |
建议使用方式:
* 使用 AIHubMix 控制台完成充值、账户管理和官方设置
* 使用 All API Hub 辅助管理 API Key、余额和模型价格
* 使用 Cherry Studio、Claude Code Router、Kilo Code 等客户端进行实际调用
***
## 常见问题 FAQ
### All API Hub 是 AIHubMix 官方产品吗?
不是。
All API Hub 是第三方开源浏览器扩展,与 AIHubMix 完全独立。AIHubMix 不参与其开发、运营、维护或数据管理。
### AIHubMix API Key 为什么只显示一次?
这是出于安全考虑。API Key 属于敏感凭据,完整密钥通常只会在创建时显示一次。
如果未及时保存完整 API Key,后续需要重新创建新的 Key。
### All API Hub 支持查看哪些 AIHubMix 模型?
All API Hub 可辅助查看 AIHubMix 支持的模型信息,例如:
* GPT 系列
* Claude 系列
* Gemini 系列
* DeepSeek 系列
* Grok 系列
具体可用模型请以 AIHubMix 模型列表页面为准:
[https://aihubmix.com/models](https://aihubmix.com/models)
### All API Hub 会上传我的 API Key 吗?
根据 All API Hub 的使用方式,默认数据通常保存在本地浏览器环境中。若用户主动启用 WebDAV 等同步功能,相关数据可能会同步到用户配置的存储服务中。
请在使用前阅读 All API Hub 的开源说明和同步配置文档,并自行评估 API Key 存储风险。
### 可以用 All API Hub 替代 AIHubMix 控制台吗?
不能。
AIHubMix 控制台仍然是账户管理、充值、API Key 创建、官方设置和模型服务管理的主要入口。
All API Hub 仅适合作为第三方辅助管理工具使用。
### 使用第三方工具管理 API Key 安全吗?
任何第三方工具都存在一定风险。建议用户在使用前:
* 查看项目是否开源
* 阅读权限说明
* 确认数据存储方式
* 避免在不可信设备上保存 API Key
* 不要将 API Key 上传到公开仓库或截图分享
***
## 开始使用 AIHubMix + All API Hub
如果你希望更方便地管理 AIHubMix API Key、余额和模型价格,可以按照以下流程尝试:
1. 注册或登录 AIHubMix 账号
2. 在 AIHubMix 控制台创建 API Key
3. 安装 All API Hub 浏览器扩展
4. 添加 AIHubMix 账号
5. 保存完整 API Key
6. 查看余额和模型价格
7. 按需导出到 AI 客户端工具
***
## 相关资源
* AIHubMix 官网:[https://aihubmix.com](https://aihubmix.com)
* AIHubMix API 文档:[https://docs.aihubmix.com](https://docs.aihubmix.com)
* AIHubMix 模型列表:[https://aihubmix.com/models](https://aihubmix.com/models)
* AIHubMix 价格说明:[https://aihubmix.com/pricing](https://aihubmix.com/pricing)
* All API Hub GitHub:[https://github.com/qixing-jk/all-api-hub](https://github.com/qixing-jk/all-api-hub)
* All API Hub 文档:[https://all-api-hub.qixing1217.top](https://all-api-hub.qixing1217.top)
# LobeHub
Source: https://docs.aihubmix.com/cn/clients/lobe-hub
### 从 LobeChat 到 LobeHub
LobeHub 的前身是开源项目 LobeChat,GitHub 仓库 Star 数已经超过 77,000。2026 年项目完成品牌升级,仓库由 lobehub/lobe-chat 迁移至 lobehub/lobehub,定位也从「开源的 ChatGPT 客户端」转向「Agent 协作平台」。官方对它的描述是「一个工作与生活空间,用于发现、构建并与会随着您一起成长的 Agent 队友协作」。在新的产品语境下,Agent 不再是辅助工具,而是 LobeHub 中最小的工作单元。
### 三种使用形态
LobeHub 同时提供三种部署形态,覆盖从个人用户到企业团队的不同场景。
| 形态 | 入口 | 数据存储 | 适用场景 |
| ----------------------------- | ------------------------------------------------------ | ----- | ------------------------ |
| LobeHub Cloud | [lobehub.com](https://lobehub.com) | 官方云端 | 零门槛尝试,订阅积分制 |
| 桌面客户端 | [lobehub.com/downloads](https://lobehub.com/downloads) | 本地 | 离线访问、Mac / Windows 系统级集成 |
| 自部署(Docker / Vercel / Zeabur) | [GitHub 仓库](https://github.com/lobehub/lobehub) | 自有数据库 | 私有化、团队共享、深度定制 |
云端版注册即获得 450,000 compute credits 免费额度,付费订阅分为 Starter、Premium、Ultimate 三档,按积分包额外计费。桌面版与自部署版本身免费,模型调用费用由用户提供的 API Key 承担。
### 2026 版核心能力
LobeHub 2026 版的能力矩阵已远超传统对话客户端,主要构成包括:
* **多模型接入**:原生支持 OpenAI、Anthropic、Google、DeepSeek、月之暗面、智谱、阿里、火山、Ollama 等 40 余家服务商
* **Agent Groups**:支持 Sequential、Parallel、Iterative、Debate 四种多 Agent 协作模式
* **MCP 插件市场**:基于 Model Context Protocol 标准,已收录超过 10,000 个可一键安装的 Skill
* **Personal Memory**:白盒结构化长期记忆,用户可随时查看与编辑
* **Heterogeneous Agent**(v2.1.56 引入):允许将 Claude Code、Codex 等外部 CLI Agent 直接挂载进 LobeHub 工作流
* **知识库 / RAG**:基于 PostgreSQL + pgvector 的向量检索引擎,支持 PDF、Markdown、Word 等格式自动分块与嵌入
这些能力共同决定了一个事实:LobeHub 已经从「替代 ChatGPT 网页」演变为「整合多家模型的统一 Agent 工作台」。正因为如此,模型供给的稳定性和便利性,成为决定其使用体验的关键变量。
***
## 配置 AIHubMix Key
AIHubMix 提供兼容 OpenAI 协议的统一接入端点,单个 Key 可同时调用 GPT-5.5 / GPT-5.4、Claude Opus 4.7 / Sonnet 4.6、Gemini、DeepSeek V4 Flash、Kimi 等主流模型。相较于自建 one-api 或 Cloudflare Workers 反代方案,AIHubMix 省去了服务器运维、模型映射与限流策略的维护成本。
## 前提条件
* 已注册 [AiHubMix](https://aihubmix.com) 账号
* 已获取 API Key([前往控制台获取](https://aihubmix.com/token))
***
## 方式一:网页版
### 第一步:打开模型服务商设置
访问 [app.lobehub.com](https://app.lobehub.com),点击左下角头像,进入 **「设置」→「模型服务商」**,在列表中找到 **AIHubMix** 并点击进入。
### 第二步:填入 API Key
在 **API Key** 输入框中粘贴你的 AIHubMix API Key,点击右侧「校验」按钮确认连接正常, 状态变为绿色即代表配置成功。
### 第三步:开启服务商并选择模型
打开页面顶部的开关,启用 AiHubMix 服务商。 回到对话页面,点击模型选择栏,在 **AIHubMix** 分组下选择你要使用的模型即可开始对话。
***
## 方式二:桌面客户端
### 下载安装
前往 [lobehub.com/downloads](https://lobehub.com/downloads) 下载对应系统版本:
| 系统 | 说明 |
| ------- | ------------------------ |
| macOS | 支持 Apple Silicon 和 Intel |
| Windows | x64 版本 |
> 桌面客户端目前处于公测阶段,功能与网页版保持同步。
### 配置步骤
安装完成后,配置步骤与网页版完全一致:
1. 点击左下角头像 → **「设置」→「模型服务商」**
2. 找到 **AIHubMix**,填入 API Key
3. 开启服务商开关,返回对话页选择模型
***
## 典型使用场景
### 场景一:日常对话与文案写作
推荐模型组合:GPT-5.5(综合)+ Claude Sonnet 4.6(长文)。
在助手市场挑选合适的写作 Agent,例如 Senior Prompt Architect 或品牌内容助手,挂载产品资料、参考文档至知识库,即可批量生成文档、邮件、推文。Claude Sonnet 4.6 在中文长文写作中的性价比明显高于 Opus 4.7,建议作为长文场景的默认模型。
### 场景二:代码与技术任务
推荐模型组合:Claude Opus 4.7(首选)+ GPT-5.5。
LobeHub 的 Agent Builder 允许自定义代码 Agent 的 System Prompt 与 MCP 工具集。挂载 GitHub MCP 插件后,Agent 可以直接读取仓库代码、生成 Pull Request 描述、辅助代码评审。
进阶用法是 Agent Groups 的 Iterative 模式:让 Claude Opus 4.7 生成初版实现,GPT-5.5 进行评审与提出修改建议,再由 Opus 4.7 迭代。由于两个模型都通过 AIHubMix 接入,整个流程可在单个对话窗口内完成,不涉及多端切换。
### 场景三:长文档研究与知识库问答
推荐模型组合:Gemini 2.5 Pro(长上下文)+ Kimi(中文 2M token)+ DeepSeek V4 Flash(性价比高)。
在自部署的数据库版 LobeHub 中,知识库功能基于 pgvector 提供完整 RAG 流程:上传文档 → 自动分块 → 嵌入向量化 → 检索增强生成。通过 AIHubMix 同时配置嵌入模型(如 `text-embedding-3-large`)与对话模型,整套流程在单一 Key 下完成,无需跨服务商管理。
### 场景四:多 Agent 协作
Agent Groups 是 LobeHub 在 2026 版的旗舰能力,提供四种协作模式:
* **Sequential**:研究 Agent → 分析 Agent → 写作 Agent,适用于线性工作流
* **Parallel**:多个 Agent 并行处理独立子任务
* **Iterative**:作者与编辑反复迭代,适用于需要打磨的产出
* **Debate**:多个 Agent 围绕同一议题展开辩论,最终由 Moderator 汇总结论
一个实战示例:组建竞品分析小组,Gemini 2.5 Pro 担任调研员、Claude Opus 4.7 担任批判者、GPT-5.5 担任汇总者。Sequential 模式下三者依次工作,最终产出一份带有对立观点平衡的竞品分析报告。
***
## LobeHub vs Claude Code vs Codex
### 三者定位差异
LobeHub、Claude Code、Codex 在 2026 年常被并列讨论,但产品定位并不相同:
* **LobeHub**:图形界面的多 Agent 协作平台,面向广义工作流
* **Claude Code**:Anthropic 官方命令行工具,面向编码与终端任务
* **Codex**:OpenAI 的代码 Agent,面向编码任务
严格意义上,「LobeHub vs Claude Code」并非同类竞品对比,更接近「平台 vs 工具」的关系。
### 核心维度对比
| 维度 | LobeHub | Claude Code | Codex |
| :-------- | :---------------- | :---------- | :------- |
| 形态 | Web / 桌面 / 自部署 | 命令行 CLI | 命令行 CLI |
| 主用场景 | 通用对话、知识库、Agent 编排 | 仓库内编码、终端任务 | 仓库内编码 |
| 底层模型 | 40+ 服务商任选 | Claude 系列固定 | GPT 系列固定 |
| 多模型协作 | 原生 Agent Groups | 不支持 | 不支持 |
| 知识库 / RAG | 内置(pgvector) | 无 | 无 |
| 插件生态 | MCP(10,000+) | MCP | MCP |
| 学习曲线 | 低 | 中 | 中 |
| 适用人群 | 通用知识工作者 | 工程师 | 工程师 |
### 选 LobeHub
以下场景下 LobeHub 更合适:
* 团队中既有工程师也有非工程师
* 需要在多家模型之间频繁切换(GPT / Claude / Gemini)
* 需要知识库与长期记忆
* 需要多 Agent 编排与对话历史可视化
### 选 Claude Code 或 Codex
以下场景下 CLI 工具更合适:
* 重度编码工作流,需要直接操作仓库与终端
* 习惯命令行界面,希望最小化上下文切换
* 接受锁定单一模型厂商
### 三者结合: Heterogeneous Agent
LobeHub v2.1.56 引入的 Heterogeneous Agent 架构,允许将 Claude Code、Codex 等外部 CLI Agent 接入 LobeHub 工作流,职责划分如下:
* LobeHub 负责对话状态、Memory、Agent 编排
* Claude Code / Codex 负责本地执行(读写文件、运行命令)
* 用户在 LobeHub 的对话窗口内即可驱动 CLI Agent 完成任务
这一架构的实际价值在于消除 GUI 与 CLI 之间的来回切换。当 Claude Code 与 Codex 的底层模型均通过 AIHubMix 调用时,整套配置可在同一个 Key 下统一鉴权与计费,便于在相同任务上对比两者表现。
***
## 常见问题(FAQ)
**Q1:Base URL 末尾要不要加** `/v1`**?**
LobeHub 在请求时会自动拼接路径。Base URL 填写 `https://aihubmix.com/v1` 通常可直接生效;如遇到 404 或空响应,可改为 `https://aihubmix.com` 后重试,并通过「模型列表」中的「测试连接」功能进行验证。
**Q2:模型列表中看不到 Claude Opus 4.7 或新发布的模型怎么办?**
LobeHub 内置模型列表更新存在一定滞后。可通过两种方式手动添加:
* 在「自定义服务商」配置的「模型列表」字段中手动追加模型 ID
* 在 AIHubMix 控制台确认该模型已启用,复制官方模型 ID 后粘贴至 LobeHub
**Q3:响应一直为空或流式中断**
按以下顺序排查:
1. 检查 Base URL 末尾 `/v1` 后缀
2. 检查 Stream 选项是否被禁用
3. 检查本地网络是否阻断 SSE(Server-Sent Events)
4. 在 AIHubMix 控制台查看请求日志,确认请求是否到达
**Q4:502 Bad Gateway**
* 自部署场景:检查 PostgreSQL 与 LobeHub 容器的健康状态,确认 `DATABASE_URL`、NextAuth 域名白名单、S3 CORS 配置正确
* 云端或桌面场景:通常为临时性网络问题,等待数分钟或切换网络后重试
**Q5:接入后能直接使用 Claude Code 与 Codex 吗?**
需满足两个前置条件:
1. LobeHub 版本 ≥ v2.1.56
2. 本地已安装 Claude Code CLI 或 Codex CLI
完成后在 LobeHub 中启用 Heterogeneous Agent,并将 CLI 工具的 `ANTHROPIC_BASE_URL` 与 `OPENAI_BASE_URL` 同样指向 AIHubMix,即可统一鉴权与计费。
***
LobeHub 提供 Agent 工作台,AIHubMix 提供统一的模型供给。两者组合的效果是:一个图形界面、一个 API Key、一套配置,即可访问 GPT-5.5、Claude Opus 4.7、Gemini、DeepSeek V4 Flash 等 2026 年主流模型,并在 Agent Groups、知识库、MCP、Heterogeneous Agent 等能力之上构建个人或团队的 AI 工作流。
对于刚开始接触 LobeHub 的用户,建议起步路径如下:
1. 在 [AiHubMix](https://aihubmix.com)注册并创建测试 Key
2. 使用桌面客户端按「路径 A」完成最小配置,体验完整功能
3. 根据使用频率与团队规模,决定是否升级到自部署数据库版
**相关资源**
* [LobeHub 官网](https://lobehub.com/zh)
* [LobeHub GitHub](https://github.com/lobehub/lobehub)
* [LobeHub 下载页](https://lobehub.com/downloads)
* [LobeHub Pricing](https://lobehub.com/pricing)
* [AIHubMix 官网](https://aihubmix.com/)
最新更新日期:2026年5月13日
# 更新日志
Source: https://docs.aihubmix.com/cn/update/News
AIHubMix 更新日志:实时跟踪平台新接入的 GPT、Claude、Gemini、Qwen、DeepSeek 等模型与功能更新,第一时间掌握最新模型支持、能力升级与平台动态。
## 2026 年
## Qwen 3.8 27B 视觉语言模型上线
### 新增模型
* 新增 [`qwen-3.8-27b`](https://aihubmix.com/model/qwen-3.8-27b):阿里巴巴开源的稠密视觉语言模型,原生支持文本、图像和视频理解。基于 Qwen3.5 架构,提升编码、专业任务、研究任务和长周期复杂工作流能力,支持 131K token 上下文和灵活的认知控制。
## GPT Image 2.5 上线与媒体体验优化
### 新增模型
* 新增 [`gpt-image-2.5-flare`](https://aihubmix.com/model/gpt-image-2.5-flare):OpenAI 图像模型,适合快速完成日常高质量生图,支持文本与图像输入、图像输出,以及 low、medium、high、xhigh、max 和 auto 六种质量设置。
* 新增 [`gpt-image-2.5-sunburst`](https://aihubmix.com/model/gpt-image-2.5-sunburst):OpenAI 图像生成与编辑模型,适合对编辑精度要求较高的工作流,支持文本与图像输入、图像输出,以及 low、medium、high、xhigh、max 和 auto 六种质量设置。
### 图片结算兜底更可靠
* 当上游图片 usage 缺少 `InputTokensDetails` 时,平台会继续使用可用输入用量结算,不再把有效输入误记为 0;消费记录与相关日志保持同一口径。
* 完整 usage 明细仍优先按上游明细结算。
### 公开模型信息更一致
* 模型信息接口现在只返回公开字段,已停用接入不会继续混入公开数据;模型详情和可用参数展示更稳定。
* 性能指标按实测结果回写,减少模型页面与接口展示过期指标的情况。
### 媒体错误提示更清晰
* 图片、视频和异步媒体任务会使用统一的公开错误码、HTTP 状态和可操作提示,区分模型不可用、输入不合法、格式不支持、上游拒绝和结果过期等场景。
* 列表、详情和 webhook 的错误语义更一致;响应不会暴露上游原文、媒体内容或内部配置细节。
### Playground 模型端点筛选更准确
* Playground 现在会按协议版本筛选模型端点,其他协议版本的入口不会混入当前列表。
* 选择模型和端点时更少出现协议不匹配导致的调用失败。
### 旧版 Claude system 兼容性提升
* 旧版 Claude 模型仍使用 `system` 角色的请求,现在可在 Chat 和 Responses 调用中更稳定地转换处理。
* 兼容路径保留现有消息、缓存和 thinking 相关语义,调用方无需为旧模型单独改写请求。
## DeepSeek 多模态试用与临时文件上传
### 新增模型
* 新增 [`deepseek-v4.1-flash`](https://aihubmix.com/model/deepseek-v4.1-flash):DeepSeek 采用新架构的原生多模态内测模型,支持文本与图像输入、文本输出,以及推理、工具调用和结构化输出。当前开放限流试用,仅供测试,不建议用于生产环境。
### Gemini usage 缺失时计费更稳
* Gemini 原生透传请求在客户端中断或上游没有返回 usage 时,会基于已下发内容估算输出用量,避免把预扣值误当作最终实收导致异常超收。
* Web Search 和 cachedContent 场景保留现有计费语义;有真实 usage 时仍优先使用上游返回的用量。
### 模型路由错误更易排查
* 当模型不存在或当前没有可用接入时,错误信息会回显用户原始请求的模型 ID,并引导到模型页复制正确 ID。映射、重定向和 fallback 不会改写这个回显名称,客服和调用方更容易定位失败请求。
### GPT 与 Claude 工具调用兼容性更稳
* 推理模型的 Chat 请求在桥接到 Responses 后,会过滤 `temperature` / `top_p` 等不被目标模型接受的采样参数,减少 gpt-5.6、gpt-6-astra 等模型的 400 错误。
* AWS Bedrock Claude 路径会移除 Bedrock 当前不支持的 advisor 工具声明;其他工具、非 AWS 平台和消息内容保持原样。
### 新增临时文件上传 API
* 新增 `POST /v1/oss/upload`,支持通过 API Key 上传单个 50 MB 以内的图片、PDF、文本、音频或视频文件,并返回 15 分钟有效的读取链接。
* 上传接口不单独计费,适合把多模态文件临时托管后交给模型使用;文件类型校验不等同于病毒扫描或所有模型输入兼容保证。
## 模型标签与 GPT 工具、缓存兼容优化
### 模型标签显示更一致
* 模型广场、模型详情和 `?tag=new` 列表现在统一按上架时间派生 New 标签;New 会在窗口到期后自动消失,旧的 Hot 标签不再展示。近期上线模型不会因为供应商自绑定数据而丢失 New 角标。
### GPT 工具调用兼容性提升
* gpt≥5.5 模型通过 `/v1/chat/completions` 搭配 tools 调用时,会自动走 Responses 兼容路径,减少上游 400 错误;使用 Claude Messages 入口转接这类模型的工具调用也覆盖该兼容口径。
* OpenAI/Azure 直连渠道会过滤不兼容的 reasoning 参数,避免参数方言造成请求失败。
### GPT 缓存写计费档位更准确
* GPT 模型含缓存写入的请求会按原始总输入长度选择计费档位,长上下文首轮请求更贴近官方口径;普通输入、缓存写数量和非 GPT 模型计费逻辑不变。
## GPT-6 Astra 与 MAI 图像模型上线
### 新增模型
* 新增 [`gpt-6-astra`](https://aihubmix.com/model/gpt-6-astra):OpenAI 面向复杂推理、编程、计算机操作、研究和文档创作的模型。支持 105 万 token 上下文、最高 128K 输出、从 low 到 max 的推理强度、异步工具调用,以及回合执行中的指令调整(mid-turn steering)。[上线公告](https://x.com/AiHubMix/status/2096102211524984984)。
* 新增 [`mai-image-2.6`](https://aihubmix.com/model/mai-image-2.6):Microsoft 的图像生成与编辑模型,支持文生图、多种宽高比生成和图像引导编辑。
* 新增 [`mai-image-2.6-flash`](https://aihubmix.com/model/mai-image-2.6-flash):Microsoft MAI-Image-2.6 的低延迟版本,支持多种宽高比的图像生成和图像引导编辑。
## 图片高并发调度与媒体错误优化
### 图片生成请求更稳
* 图片生成、编辑、变体和 `gpt-image-2` 预测请求现在会结合 Azure 返回的限频信息和分布式在途上限调度请求。高并发或上游 429 场景下,平台会更早限流、释放容量并尝试可用渠道,减少图片请求被瞬时流量拖垮的情况。
* 依赖 `by-bill` 图片模型的请求在缺少上游用量字段时会使用统一兜底用量,限流与计费口径更一致;当 Redis 限流组件异常时,图片请求会保守失败并返回错误,避免无限制打到上游。
### 媒体任务错误返回更一致
* `/ai/v1`、`/call/media`、任务查询、列表和 webhook 中的媒体任务失败会使用同一套公开错误码和失败快照。调用方看到的 HTTP 状态、`error.code` 与失败原因更一致,便于重试、展示和客服排查。
* 上游原文、媒体 URL、data URI、Base64 和内部错误细节不会进入用户可见响应;坏 JSON、未知模型、输入超限或上游拒绝等场景会归类到更明确的公开错误。
## 长周期 Agent 与多模态模型扩容
### 新增模型
* 新增 [`muse-spark-1.3`](https://aihubmix.com/model/muse-spark-1.3):Meta 面向长周期 Agent、多智能体与复杂编码工作流的多模态推理模型。支持文本、图像、音频和视频输入、文本输出、100 万 token 上下文与最高 100 万 token 输出,以及推理和工具能力。相比 Muse Spark 1.2,它以更少的不必要轮次和工具调用、更精炼的输出,提高长周期 Agent 与编码任务的执行效率。
* 新增 [`gemini-3.8-flash`](https://aihubmix.com/model/gemini-3.8-flash):Google Flash 系列中智能能力最强的模型,面向长时间运行的软件工程、自主 Agent 与复杂企业工作流。支持文本、图像、音频和视频输入、100 万 token 上下文、最高 65K 输出、推理、联网、工具调用、结构化输出与长上下文。
* 新增 [`gemini-3.8-flash-free`](https://aihubmix.com/model/gemini-3.8-flash-free):Gemini 3.8 Flash 的免费试用版本,保留核心多模态与 Agent 能力。免费资源有限、稳定性不保证,使用时可能出现 429;生产环境如需稳定并发,请使用 gemini-3.8-flash。
## Claude Fable、Qwen 与创作模型更新
### 新增模型
* 新增 [`claude-fable-5-1`](https://aihubmix.com/model/claude-fable-5-1):Anthropic 面向高强度推理、长周期 Agent、多步研究和文档/表格/幻灯片处理的旗舰模型。支持文本与图像输入、100 万 token 上下文,以及思考、工具调用、代码解释器、Computer Use、记忆工具、结构化输出、引用和提示词缓存;缓存读取价格较 Claude Fable 5 降至四分之一。
* 新增 [`mercury-2.5-preview`](https://aihubmix.com/model/mercury-2.5-preview):Inception 的扩散式大语言模型预览版,面向高速度文本生成场景。支持 26 万 token 上下文,官方资料强调可并行生成和优化多个 token,标准 GPU 上生成速度可达 1,107 tokens/s;该模型能力标记尚未完整发布,接入前建议做最小调用验证。
* 新增 [`qwen3.8-max-2026-09-02`](https://aihubmix.com/model/qwen3.8-max-2026-09-02):Qwen3.8 Max 的 2026-09-02 快照版本,面向复杂工程项目、长程自主开发和多工具协作 Agent 场景。AIHubMix 当前记录为文本输入、约 99.1 万 token 上下文;能力标记尚未完整发布,依赖视觉、工具或结构化输出前需以实测为准。
* 新增 [`minimax-h3-max`](https://aihubmix.com/model/minimax-h3-max):MiniMax H3 系列面向广告、品牌、电商、产品设计、UI/UX 和游戏创意工作流的多模态创作模型。AIHubMix 当前记录支持文本与图像输入;H3 系列资料强调视频、音频和参考编辑能力,具体能力标记尚未完整发布,生产接入前建议先验证目标链路。
## 模型退役提示与媒体输入优化
### 模型下线提示更明确
* 调用已下线模型时,API 会返回明确的 `model_retired` 404 错误,而不是笼统的模型不存在提示;如果已配置继任模型,响应头会带上下线和替代模型信息,便于客户端迁移。
* 创建或编辑 Key 时会拒绝已下线模型,智能路由也会避开已下线模型,减少请求落到不可用模型后的失败。
### 媒体输入错误更可操作
* 图片、视频等媒体输入格式不受支持时,错误会稳定返回 `media_form_unsupported`,并说明检测到的媒体类型和当前模型可接受的输入形式。
* 同步、异步和回调场景的媒体错误提示保持一致,并避免把 URL、Base64 或内部原因暴露给用户。
### Google 图片输入上限临时放宽
* AIHubMix 侧对 Google/Gemini 图片输入的网关校验临时放宽到 20 MB,较大的图片请求不会再被平台提前拦截。
* 由于当前链路仍使用 Google inline media 方式,超过 Google 实际可接受范围的输入仍可能被上游拒绝;大文件调用仍需关注返回错误。
## 腾讯混元 Hy4 Preview 上线
### 新增模型
* 新增 [`hy4-preview`](https://aihubmix.com/model/hy4-preview):腾讯混元 Hy4 Preview,采用 770B 总参数、49B 激活参数的 MoE 架构,面向 Agent、Coding 与生产力工作流优化。它强化复杂任务中的理解、规划、工具调用与持续执行,适合编码、复杂软件工程、文档处理、信息分析、办公自动化、网页生成及跨工具协作。支持 100 万 token 上下文、最高 64K 输出、推理、联网、工具/函数调用和结构化输出。
## Qwen 3.8 Flash 与 MCP 图片工具更新
### 新增模型
* 新增 [`qwen3.8-flash`](https://aihubmix.com/model/qwen3.8-flash):阿里云通义千问的旗舰原生视觉语言模型,适合编程、办公、长上下文推理和 Agent 工作流。支持 100 万 token 上下文、最高 128K 输出,以及思考、联网、工具调用和结构化输出。相比 Qwen3.7-Plus,进一步增强编程与办公能力,并提升训练和推理效率。
### MCP 图片工具调用更明确
* MCP 图片生成工具现在要求调用方显式传入模型,避免在未指定模型时被静默使用默认模型。
* `openai/gpt-image-1` 是对外展示和转发使用的标准模型 ID;历史拼写错误仍作为兼容输入保留,旧客户端可继续提交但会被规范化处理。
## Broadcast、远程 MCP 与 Access Key
### 新增模型
* 新增 [`glm-5.3-flash`](https://aihubmix.com/model/glm-5.3-flash):Z.AI 面向 Coding Agent、复杂推理和长周期软件工程任务的高效率多模态模型。支持文本、图像和视频输入、约 100 万 token 上下文、最高 128K 输出,以及思考、工具调用和结构化输出。模型基于现有 GLM 技术栈进一步后训练和优化,更侧重推理效率与响应速度。
### 新增功能
* 新增 [Broadcast](/cn/api/Broadcast):可将 AIHubMix API 请求的 Trace 自动发送到 LangWatch,无需在应用代码中额外埋点。支持隐私模式、采样率和 API Key 过滤,可在 LangWatch 中查看模型、token 用量、实际计费成本、耗时、会话和 Trace 信息。
### MCP 与 Access Key 入口补齐
* 旧版 `/mcp/` 入口可继续按既有鉴权方式使用,并统一到远程 HTTP MCP 能力;旧客户端不需要立即迁移,仍可访问模型、价格、文档检索、余额查询以及聊天、图像和视频工具。
* 控制台将提供只读 Access Key 复制入口,外部 MCP 客户端也可使用 `X-Aihubmix-Access-Key` 请求头;服务端不轮换密钥,不缓存该响应。
### 图片透明背景请求更稳
* `gpt-image-2` 透明背景请求会优先走支持该能力的 OpenAI 原生渠道,减少在不支持透明背景的渠道间连续失败。其他图片请求路径不变。
### Agent 文件更新更及时
* 面向 AI Agent 和外部工具的模型清单与指南更新会更及时。
## 旧版媒体接口迁移提示更新
### 旧版媒体接口迁移提示更明确
* 对已关闭旧协议支持的媒体模型,`/v1/images/generations`、`/v1/images/edits`、`/v1/models/:organization/:model/predictions` 和 `/v1/videos` 会返回 `protocol_not_supported`,并提示迁移到 `/ai/v1` 异步媒体接口和对应文档。
* `model=auto` 仍保持既有自动选模逻辑;如果最终选中的模型不支持旧接口,调用方会收到明确错误,而不是被静默切换到其他模型。Playground 也会隐藏这些模型的旧入口,减少误用。
## Wan 3.0 上线与 GPT-5.6 Sol 降价
### 新增模型
* 新增 [`wan3.0-video`](https://aihubmix.com/model/wan3.0-video):阿里云通义万相预览版 All-in-One 视频模型,整合文生视频、首尾帧图生视频与参考视频工作流,支持最长 30 秒、30 fps 的 480P/720P/1080P 输出,适用于一体化生成与编辑。
* 新增 [`wan3.0-video-prime`](https://aihubmix.com/model/wan3.0-video-prime):能力对齐的高速版,面向一体化视频生成与编辑工作流,提供更快的端到端生成周转。
### GPT-5.6 Sol 价格下调
* [`gpt-5.6-sol`](https://aihubmix.com/model/gpt-5.6-sol) 已同步官方价格下调 20%,当前价格为输入 $4/百万 token、输出 $20/百万 token。现有调用方式不变,复杂推理、编码和长上下文任务的调用成本降低。
### 异步媒体任务开通提示更清楚
* 用户未开通异步任务功能时,媒体创建接口会在 `async_not_enabled` 错误中返回对应站点的控制台开通入口。aihubmix、inferera、shkq 用户会被引导到各自控制台,减少 403 后不知道如何开通的问题。
## DeepSeek 新版本与图片生成恢复优化
### 新增模型
* 新增 [`deepseek-v4-flash-0731-fast`](https://aihubmix.com/model/deepseek-v4-flash-0731-fast):DeepSeek Agent 模型的高速版本,面向编码、工具调用和高并发 Agent 工作负载。它保留 V4 Flash 0731 的能力并提供更快推理;相比 V4 Pro,更侧重低延迟与执行效率。支持 100 万 token 上下文窗口、最高 384K 输出、思考、工具调用和结构化输出。
* 新增 [`deepseek-v4-flash-vision-exp`](https://aihubmix.com/model/deepseek-v4-flash-vision-exp):DeepSeek 实验性多模态视觉理解模型,支持文本和图像输入、文本输出。适合图像描述、截图 OCR、图表分析和视觉 Agent;纯文本 Agent、推理与世界知识能力与 DeepSeek V4 Flash 正式版保持同级。
* 新增 [`ox-alpha`](https://aihubmix.com/model/ox-alpha):由匿名第三方供应商提供的隐身推理模型,真实开发者和所有者尚未披露。AIHubMix 免费提供,支持文本和图像输入、文本输出及 1,048,576 token 上下文窗口,适合编程、长周期软件工程、持续 Agent 工作、复杂推理和图文工作流。
### 图片生成失败恢复更稳
* 图片生成请求遇到临时服务错误时,自动恢复能力更稳定;当错误明确属于当前模型能力限制时,仍会停止重试并返回清晰原因。使用 `gpt-image-2` 等图片模型时,偶发服务差异导致的直接失败会减少。
## Agent 接入与模型广场升级
### 平台公告
* 上线面向 AI Agent 的接入能力:[`agents.md`](https://aihubmix.com/agents.md) 接入说明、站点与每模型 [`llms.txt`](https://aihubmix.com/llms.txt) 机读文档、[Playground Skill](https://aihubmix.com/skills/playground)(固定地址分发)、Playground 深链(`?models=` 多模型开局,一条链接开出最多 6 个模型的标签页;`?config=` 配置直达)。需要并排查看两个模型的规格与价格,可用主站对比页 `https://aihubmix.com/compare/{model_a}/{model_b}`。入口清单见 [Agent 接入](/cn/agents)。
### 图片生成 API 参数与错误更一致
* 图片生成请求对 `resolution`、`imageSize` 等尺寸参数的处理更稳定;当请求参数不符合当前模型能力时,接口会返回更明确的错误说明,便于调用方快速修正。
### 模型广场支持主模型与多版本展示
* GLM 5.2、Coding 版和 Free 版这类同一模型的不同形态可按“主模型 + 版本”归并展示。用户浏览模型广场、对比价格和选择版本时,更容易理解它们之间的关系。
### 异步图片任务处理能力提升
* 异步图片任务可按实时空闲能力并发推进。高峰期排队和处理延迟有望降低,任务状态与结果交付更稳定。
## GPT-5.6 Sol 折扣线路与媒体任务优化
### 新增模型
* 新增 [`gpt-5.6-sol-disc`](https://aihubmix.com/model/gpt-5.6-sol-disc):AIHubMix 为 OpenAI GPT 5.6 Sol 提供的限时折扣线路,当前最高优惠 50%,底层能力与标准 `gpt-5.6-sol` 相同。该前沿推理模型适合复杂编程、专业知识工作、深度研究与长程 Agent,支持文本和图像输入、约 105 万 token 上下文、最高 12.8 万 token 输出,以及思考、工具和结构化输出。
### 媒体生成任务更稳
* 图片、视频等媒体任务的完成时间、结果过期时间和产物归档口径更一致;滚动发布或高并发场景下,任务状态、下载结果和用户侧记录更不容易出现延迟或重复处理。
* 媒体生产服务容量已提升,较大媒体响应的处理上限也更宽,长耗时或大产物任务的可用性更稳。
## 模型信息与 Gemini 媒体兼容优化
### 模型详情和页面展示更完整
* 模型详情现在会展示 `release_date`,模型列表和对比页也能同步读取,官方发布时间与站内上架时间更容易区分。
### Gemini 图片与上传兼容性更稳
* Gemini 图片生成/编辑和 Vertex 多图流程现在对 `imageSize` 与相关图片参数保留得更完整,尺寸和协议信息更不容易丢失。
* Gemini 文件上传会保留原始 `Content-Type`,视频和其他媒体更不容易被误判为错误类型。
### 公开错误提示更可读
* 面向用户的 schema、枚举和能力限制报错现在会优先显示更清楚的文案,排查参数问题更直接。
## GLM-5.3 正式版上线
### 新增模型
* 新增 [`glm-5.3`](https://aihubmix.com/model/glm-5.3):Z.AI 旗舰级纯文本推理模型的正式版 API,面向复杂软件工程、长周期 Agent 任务与漏洞分析,支持 100 万 token 上下文和最高 12.8 万 token 输出。AIHubMix 提供无限并发,当前限时优惠 10%。
## Microsoft MAI Thinking 1 上线
### 新增模型
* 新增 [`mai-thinking-1`](https://aihubmix.com/model/mai-thinking-1):Microsoft MAI 系列推理模型,面向企业级推理、数学、通用智能和高吞吐工作负载。支持 256K 上下文窗口、Chat Completions 与结构化输出,适合需要长上下文推理、稳定响应格式和全天候调用成本控制的业务场景。
## Gemini 3.7 Flash 与 Coding GLM-5.3
### 新增模型
* 新增 [`gemini-3.7-flash`](https://aihubmix.com/model/gemini-3.7-flash):Google 原生多模态推理模型,面向编程、Agent、Web 开发和知识工作。支持文本、图像、音频和视频输入、100 万 tokens 上下文窗口、可调思考级别、工具调用、联网搜索和结构化输出;相比 Gemini 3.6 Flash,在编程、工具使用、多步规划和指令遵循方面进一步提升。
* 新增 [`coding-glm-5.3`](https://aihubmix.com/model/coding-glm-5.3):Z.AI 面向编程与 Agent 工作流的推理模型,适合复杂软件工程、长程 Agent 和漏洞分析。它与 GLM-5.2 使用相同底座,通过扩大后训练规模提升编程、任务执行和 token 效率。当前为限时预览版,仅供测试与评估,服务稳定性不作保证,不建议用于生产环境。
### API 兼容性与任务可靠性
* Gemini 原生 embedding 请求现在能正确保留 Gemini Files API 返回的 `fileUri` 所属模型服务来源。使用 `embedContent` / `batchEmbedContents` 搭配已上传文件时,减少因文件来源不一致导致的 403;批量请求引用多个不同来源文件会明确返回 400。
* OpenRouter 返回模型推理厂商结构化错误时,接口错误会优先展示内层 `message` / `param` / `type`,减少难以解析的长文案;单个模型推理厂商的错误也更不容易影响整个 OpenRouter 服务。
* 媒体异步任务的轮询、终态归档和产物处理更稳。图片、视频生成等长耗时任务在高并发、重启或产物较大时,更不容易重复处理、丢失终态或延迟交付;公开 API 字段、状态词和计费公式保持不变。
## Grok 4.6 与 DeepSeek V4 Pro 更新
### 新增模型
* 新增 [`grok-4.6`](https://aihubmix.com/model/grok-4.6):xAI 旗舰多模态推理模型,面向编程、长程 Agent、知识工作和交互式应用开发。支持图像理解、500K 上下文窗口、工具调用和结构化输出;相比 Grok 4.5,在多步执行、自我验证、编程和视觉项目生成方面进一步提升。
* 新增 [`deepseek-v4-pro-0813`](https://aihubmix.com/model/deepseek-v4-pro-0813):DeepSeek 高性能通用推理与 Agent 模型,适合复杂推理、编程、长文档分析和 Agent 工作流。支持思考与非思考模式、100 万 tokens 上下文窗口、最长 384K 输出、工具调用和 Responses API。
## Agnes 模型扩容与视频、工具兼容优化
### 新增模型
* 新增 [`agnes-2.5-flash`](https://aihubmix.com/model/agnes-2.5-flash)、[`agnes-2.5-pro`](https://aihubmix.com/model/agnes-2.5-pro)、[`agnes-2.5-pro-alpha`](https://aihubmix.com/model/agnes-2.5-pro-alpha) 与 [`agnes-image-2.1-flash`](https://aihubmix.com/model/agnes-image-2.1-flash)。文本与图像类 Agnes 模型现已可通过 AIHubMix 统一入口调用。
### Veo 视频时长返回更准确
* Gemini Veo 任务在创建、轮询和结果读取时会更稳定地保留真实视频时长。使用自定义秒数生成视频的用户,看到的任务时长、下载文件时长和后续计费/展示口径会更一致。
### Azure Responses 工具调用兼容性提升
* 通过 Azure Responses 使用 namespace 工具时,空白或缺失的 description 不再直接导致 Azure 在模型执行前返回 400。原本可在 OpenAI 官方接口通过的工具调用,更容易在 Azure 上保持一致行为。
### 模型与供应商页面数据更完整
* `/call/devs` 现在支持返回厂商官网字段,模型聚合页和供应商页面可在数据补齐后展示 Official site 入口。`/providers/` 厂商页也补齐了边缘缓存策略,页面响应会更稳定。
## Gemini 异步交互与多协议兼容优化
### Gemini interactions 支持异步任务
* Gemini interactions 请求现在可显式使用 `background: true` 走异步任务,并通过返回的任务 ID 查询状态、取消或清理任务。长耗时的多模态/omni 交互更适合接入,不必保持同步连接等待完成。
* 异步任务按真实用量结算,并补齐 token 分列、取消全额释放和长响应保护。用户控制台里的消费记录、余额预扣与最终扣费更一致。
### Claude Messages 桥接 thinking 兼容性提升
* 通过 Messages 协议调用 OpenAI 兼容模型提供方时,模型返回的 thinking/reasoning 内容会被保留,并可在后续多轮中回传。使用 Claude SDK、tools 多轮和 DeepSeek thinking 模式的应用更不容易遇到空响应、400 或思维链上下文丢失。
* 无签名 thinking 块在切换到原生 Claude 服务时会被兼容处理,减少多模型 fallback 或桥接链路中的格式错误。
### Doubao 视频素材提示词兼容性提升
* 调用豆包视频模型时,`prompt` 与 `extra_body.content` 中的参考素材可以一起生效;仅素材内容的请求会保留提示词与素材顺序。
* 创建响应中的尺寸与提示词信息更贴近实际下发内容,并继续忽略暂未支持的原生字段,减少 SDK 额外参数导致的视频生成失败。
## 媒体累计用量与 Azure 模型名修复
### 媒体生成累计用量统计更完整
* 媒体生成任务完成结算后,会同步补记账号累计已用额度。用户在控制台查看累计已用、余额扣减和消费记录时,媒体生成部分会更完整地反映真实用量。
### Azure 点号模型名兼容性提升
* 调用 deployment/model 名中包含点号的 Azure 模型时,模型名在 Chat、Responses 和 Messages 转换链路中保持原样,不再被自动改写;既有 Azure 调用行为保持不变。
## Seedance 2.5 音视频生成上线
### 新增视频生成模型
* 新增 [`doubao-seedance-2-5-260628`](https://aihubmix.com/model/doubao-seedance-2-5-260628):ByteDance Seed 新一代统一多模态音视频生成模型,可一次生成最长 30 秒的音视频同步内容,并支持多轮延展。相比 Seedance 2.0,它在叙事、转场、参考素材支持、真实感和精准编辑方面进一步提升,适合影视制作、广告、教育、仿真和长内容创作。
## Wan 3.0 与 Qwen Image 3.0 上线
### 新增模型
* 新增 [`wan3.0-video`](https://aihubmix.com/model/wan3.0-video):阿里通义实验室推出的一体化视频生成与编辑模型,目前处于公测阶段。它支持最长 30 秒的原生视频生成、生产级角色一致性、逼真的画面与声音,以及统一的参考生成、编辑、复刻和动作驱动工作流,适合广告、电商、影视制作、角色动画、视频编辑和文档转视频。
* 新增 [`qwen-image-3.0`](https://aihubmix.com/model/qwen-image-3.0):阿里云通义千问团队的图像生成与编辑模型,支持文生图、参考图创作和图像编辑。兼顾画质与速度,适合社交媒体、电商、创意设计、日常内容生产以及高频大规模创作。
* 新增 [`qwen-image-3.0-pro`](https://aihubmix.com/model/qwen-image-3.0-pro):阿里云通义千问旗舰级图像生成与编辑模型,面向广告、品牌视觉、UI、演示、产品图和专业设计场景。擅长复杂版式、精准的中英文字渲染、真实材质、参考图编辑,以及细节、构图和商业级视觉品质。
## 多模态 Embedding 与 Seedance 调用优化
### Gemini embedding 支持多模态输入与分模态计费
* `gemini-embedding-2-preview` 现在可以通过 OpenAI 兼容 embeddings 入口和 Gemini 原生入口处理文本、图片、音频、视频和文档输入。使用多模态向量检索、内容理解或知识库构建的用户,可在同一模型上接入更多输入类型。
* Gemini embedding 的费用会优先按模型推理厂商返回的分模态 token 用量计算;图片、音频、视频和文档不再被统一当作文本估算。多模态 embedding 账单更贴近真实用量。
* 单条 embedding 请求可直接使用新一代 Gemini embedding;包含多条输入的批量请求会明确返回能力不支持的提示。
### Seedance 2.0 视频生成调用更稳定
* Seedance 2.0 的图片、音频、视频等引用会按媒体类型更准确地映射,`adaptive`、4K、尺寸等能力约束更清晰。视频生成工作流中因参数映射不准导致的失败会减少。
* 自适应时长请求会先按 15 秒预扣,并在任务完成后按真实时长结算;用户余额预扣和最终账单更一致。
* 媒体生成失败时,接口会返回脱敏后的错误信息,方便用户和客服定位参数、签名链接或模型推理厂商限制问题,同时避免暴露敏感凭证。
## Qwen 3.8 Max 与供应商展示优化
### 新增模型
* 新增 [`qwen3.8-max`](https://aihubmix.com/model/qwen3.8-max):阿里云旗舰原生视觉语言模型,基于 2.4 万亿参数的 Mixture-of-Experts (MoE) 架构,最大上下文窗口达 100 万 tokens。适合复杂多模态理解、高阶推理、软件开发、agent 工作流以及长上下文处理。与 Qwen3.7-Max 价格相近,在推理、编码和 agent 能力上均有明显提升,整体表现对齐当前主流领先模型。
### 模型详情中的供应商可用性更清晰
* 模型详情会优先展示当前更适合调用的供应商,并把仅作备用或暂不可用的供应商放到后面。用户选择模型供应商、客服排查模型可用性时,可以更直观看到哪些供应商当前更适合使用,减少因展示顺序过期带来的误判。
## 小额请求计费与消费日志修复
### 小额账单与消费日志更准确
* by-bill 计费模型的小额请求不再因为取整归零而缺少扣费和消费日志。受影响的请求会按最小有效额度入账,用户账单、余额预扣和消费记录更一致;客服和运营排查小额 embedding 等高频请求时,可以看到更完整的记录。
## DeepSeek、MiniMax 更新与模型优惠
### 新增模型
* 新增 [`deepseek-v4-flash`](https://aihubmix.com/model/deepseek-v4-flash):面向效率优化的 Mixture-of-Experts 模型,总参数 284B,激活参数 13B,上下文窗口 100 万 tokens。为快速推理和高吞吐场景设计,同时保留强劲的推理与编码能力,适合编码助手、聊天系统和 agent 工作流。
### 新增视频生成模型
* 新增 [`minimax-h3`](https://aihubmix.com/model/minimax-h3):MiniMax 的通用多模态视频模型,支持文本、图像、音频和视频输入,可用于文生视频、图生视频、首尾帧生成、参考素材生成和视频编辑。需要搭建视频创作、广告素材、产品演示或多模态内容工作流的用户,可以通过 AIHubMix 统一接口接入。
### GLM-5.2 分时段限时特惠
* `glm-5.2` 调用价格按每日时段打折,时间以 UTC 为准:每日 14:00 至 24:00 享 5 折,每日 00:00 至 14:00 享 7 折。活动限时。
### GPT-5.6 Luna/Terra 价格下调
* `gpt-5.6-luna` 已同步官方降价 80%,当前价格为输入 $0.20、输出 $1.20;`gpt-5.6-terra` 已同步官方降价 20%,当前价格为输入 $2.00、输出 $12.00。对这两个模型有稳定调用量的用户,可重新评估成本敏感和通用任务的模型选择。
## 官方 MCP 服务开放接入
### AIHubMix 官方 MCP Server 上线
* 新增面向 MCP 客户端的官方托管入口 [mcp.aihubmix.com/mcp](https://mcp.aihubmix.com/mcp) 或 [mcp.inferera.com/mcp](https://mcp.inferera.com/mcp)。支持在 Claude Code、Codex、Cursor 等工具中通过同一入口查询模型与价格、检索文档、查看余额,并调用聊天、图像生成和视频生成等工具能力。
* MCP 请求凭证由客户端逐次传入,服务端不保存 API Key;适合希望在 IDE 或 Agent 工具里直接使用 AIHubMix 模型和媒体能力的开发者。
## Jina Reranker V3.5 上线
### 新增模型
* 新增 [`jina-reranker-v3.5`](https://aihubmix.com/model/jina-reranker-v3.5):Jina AI 的 0.6B 多语言 listwise 文档重排模型,可作为 `jina-reranker-v3` 的同接口升级版本。它面向 RAG、搜索和结构化资料排序场景,支持长上下文候选排序,并提升领域鲁棒性、多语言检索、结构化数据排序和推理效率。
## 缓存计费、媒体任务与数据刷新优化
### 缓存计费更准确
* 对显式缓存与隐式缓存请求,平台会更一致地识别缓存读写用量,并按实际返回的缓存类型优先计费。使用 Qwen、Claude 等支持缓存能力的用户,可获得更贴近真实用量的账单明细。
### 媒体生成与任务结果稳定性提升
* 媒体生成首批模型列表收窄到已验证模型,并修复部分图像模型经媒体入口调用时可能 404 的问题。控制台中的 LLM 任务下载也补齐了文本存档场景,历史大结果更容易下载和交付。
### 站点与模型数据刷新更可靠
* 官网、模型数据、博客数据和站点地图的缓存策略已调整为发布后更快生效;模型广场与文档入口在内容更新后更不容易被旧缓存影响。
## 统一异步媒体生成接口上线
### 媒体生成接口上线
* 新增 `/ai/v1/images/generations` 与 `/ai/v1/images/edits` 媒体生成入口,并提供统一的异步任务、结果查询、产物下载和 webhook 回调能力。图像与视频类工作流可以通过同一套任务生命周期接入,便于客户端跟踪长耗时生成结果。
* 生成产物会通过 AIHubMix 统一任务结果返回,并支持受限次数的下载与批量获取。运营和客服可重点关注首批用户的任务状态、下载链接有效性和计费明细反馈。
## Claude Opus 5 上线
### 新增模型
* 新增 [`claude-opus-5`](https://aihubmix.com/model/claude-opus-5):Anthropic 旗舰模型,面向高强度推理、编码和长程 agent 任务。擅长端到端软件开发、代码审查与缺陷发现、图表与文档视觉分析、复杂办公交付以及并行子代理协作,具备 1M 上下文窗口,最大输出 128K。
## MAI 图像与 Qwen TTS 音频能力更新
### 新增模型
* 新增 [`mai-image-2.5-pro`](https://aihubmix.com/model/mai-image-2.5-pro):微软旗舰级图像生成与编辑模型,具备高保真写实效果、精准的图内文字渲染以及强大的图像编辑能力,适合商业设计、产品摄影和专业创意工作流。
* 新增 [`qwen-audio-3.0-tts-flash`](https://aihubmix.com/model/qwen-audio-3.0-tts-flash):通义千问实时语音合成模型,支持更多低资源语言与中文方言,具备丰富的表现力控制,首包延迟低于 200 ms,适合语音助手、实时对话和智能客服。
* 新增 [`qwen-audio-3.0-tts-plus`](https://aihubmix.com/model/qwen-audio-3.0-tts-plus):通义千问高品质语音合成模型,可精细控制情感、语气、角色、语速、音量与合成风格,并在噪声和混响环境下更稳定,适合内容创作、有声书、影视配音、品牌声音设计及高品质语音服务。
### Qwen TTS 音频生成能力
* 两个 Qwen TTS 模型均可通过 `/v1/audio/speech` 调用;非流式请求返回音频结果链接,流式请求返回 SSE 音频生成事件。下表结合 AIHubMix 兼容字段与阿里云官方 Qwen-Audio-TTS 口径整理;`voice` 需按模型分别选择,plus 与 flash 的系统音色不可混用。
| 能力项 | `qwen-audio-3.0-tts-plus` | `qwen-audio-3.0-tts-flash` |
| ---------------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| 输入文本 `input` | 必填,AIHubMix 兼容入口单次不超过 4096 字符;文本内可嵌入 `[excited]`、`[laughing]` 等情感标签。 | 必填,AIHubMix 兼容入口单次不超过 4096 字符;文本内可嵌入 `[excited]`、`[laughing]` 等情感标签。 |
| 音色 `voice` | 系统音色:`longanlingxin`、`longanlufeng`;另有 500+ 基础/克隆音色。 | 系统音色:`longanhuan_v3.6`、`longjielidou_v3.6`、`loongeva_v3.6`、`loongjohn`;另有 500+ 基础/克隆音色。 |
| 输出格式 `response_format` | 默认 `mp3`,也支持 `wav`、`pcm`、`opus`;暂不支持 `aac`/`flac`。 | 默认 `mp3`,也支持 `wav`、`pcm`、`opus`;暂不支持 `aac`/`flac`。 |
| 语速 `speed` | 支持 `0.5` 到 `2.0`,默认 `1.0`。 | 支持 `0.5` 到 `2.0`,默认 `1.0`。 |
| 口播指令 `instructions` | 支持用自然语言控制角色、情绪和口音,例如“用温柔的语气”。 | 支持用自然语言控制角色、情绪和口音,例如“用温柔的语气”。 |
| 流式 `stream_format` | 非流式可不传,返回 URL JSON;流式传 `sse`,返回 SSE 事件。 | 非流式可不传,返回 URL JSON;流式传 `sse`,返回 SSE 事件。 |
### Messages 响应兼容性提升
* 通过 `/v1/messages` 调用桥接模型或 Claude/Bedrock 等模型服务时,响应字段与 Anthropic Messages 生态更一致,减少严格 SDK 或校验器因缺少响应字段而报错的情况。
### AWS Bedrock 流式断连后的用量更完整
* 客户端中途断开 AWS Bedrock 流式请求时,平台会继续收口模型推理厂商结束信号和最终 usage,减少断连场景下请求日志、结算明细和实际模型推理厂商用量不一致的情况。
## Qwen3-Coder 与 Gemini 轻量模型扩容
### 新增模型
* 新增 [`qwen3-coder-480b-a35b-instruct`](https://aihubmix.com/model/qwen3-coder-480b-a35b-instruct):Qwen3-Coder 旗舰代码模型,面向代码生成、软件工程 Agent 和工具调用工作流,适合长上下文代码理解与自动化开发任务。
* 新增 [`gemini-2.5-flash-lite`](https://aihubmix.com/model/gemini-2.5-flash-lite):Google 2.5 系列轻量模型,面向低延迟、低成本的高频文本、多模态和批处理场景。
* 新增 [`Qwen/Qwen3-235B-A22B-Instruct-2507`](https://aihubmix.com/model/Qwen/Qwen3-235B-A22B-Instruct-2507):Qwen3 235B-A22B Instruct 2507 版本,适合通用对话、指令跟随、多语种与长上下文任务。
## Gemini、GLM 扩容与 Qwen 流式修复
### 新增模型
* 新增 [`gemini-3.6-flash`](https://aihubmix.com/model/gemini-3.6-flash):Google 最新 Flash 系列模型,适合复杂工作流、计算机使用、图表推理和长上下文任务。
* 新增 [`gemini-3.5-flash-lite`](https://aihubmix.com/model/gemini-3.5-flash-lite):更轻量、低成本的 3.5 系列模型,适合高吞吐、日常自动化和批量处理场景。
* 新增 [`glm-5.2-fast-preview`](https://aihubmix.com/model/glm-5.2-fast-preview):智谱 GLM-5.2 系列快速预览模型,适合低延迟对话、快速推理和高吞吐应用场景。
### Qwen 3.8 流式请求稳定性提升
* 通过 `/v1/responses` 和 `/v1/messages` 调用 `qwen3.8-max-preview` 的流式请求更稳定;此前可能被误判为 `empty_stream` 或 502 的有效流式响应,现在可正常完成。
## Gemini、Responses 与分时计费优化
### Gemini 图像参数透传
* 通过 OpenAI 兼容的 Chat Completions 调用 Gemini/Vertex 图像输出模型时,现在可在 `extra_body.generationConfig.imageConfig` 中传递 `aspectRatio` 和 `imageSize`。
### Gemini embedding 计费更贴近真实用量
* Gemini embedding 响应提供真实 `usageMetadata` 时,平台会优先按模型推理厂商返回的 token 用量计费;缺失时仍保留原本地估算兜底。
### Responses 动态工具兼容性提升
* `/v1/responses` 请求中的 system/developer 消息现在可携带 message-local function tools,并在桥接到 Chat 模型时保留工具声明。依赖 Kimi K3 等动态工具工作流的客户端,工具调用链路更稳定。
### Responses stop 参数修复
* 通过 `/v1/responses` 调用会桥接到 Chat 的模型时,`stop` 现在会随请求传给模型推理厂商。单个停止词可正常生效,超过模型推理厂商限制的数量或长度会返回与 Chat Completions 一致的边界错误。
### DeepSeek V4 分时段计费支持
* DeepSeek V4 相关模型可按配置支持峰谷分时段计费;预扣与最终结算使用同一请求提交时间口径,跨峰谷边界的流式请求也按提交时刻计价。预扣保护仅作用于配置了分时段计费的模型,避免影响其他普通模型的余额冻结体验。
## Claude 思考兼容与长流式连接优化
### Claude Messages thinking 兼容性修复
* 通过 `/v1/messages` 调用 OpenAI/Azure Chat 桥接模型时,Claude `thinking` 配置现在会转换为模型推理厂商可识别的思考强度,减少带 thinking 请求返回 400 的情况。Opus 4.8 等 Claude 原生思考请求仍保持兼容。
### 长时间流式请求更稳定
* 生产环境网关的最长流式连接时间已从 1 小时放宽到 2 小时。Kimi K3 等长思考、长生成任务更不容易在思考或生成过程中被网关提前切断。
## Qwen 3.8 Max Preview 限时优惠
### 新增模型
* 新增 [qwen3.8-max-preview](https://aihubmix.com/model/qwen3.8-max-preview):
限时福利:Qwen3.8-Max-Preview 调用价格按 1 折计算,相当于用量直接扩大 10 倍,活动限时,先到先用。
Qwen3.8-Max-Preview 是通义千问系列最新一代基座模型,参数量达 2.4T,并仍在持续进化中。相较上一代旗舰 Qwen3.7-Max,它在代码工程(Coding)、专业办公(Cowork)等核心能力上实现显著提升,在全栈开发、数据分析、Office 办公工作流等复杂长程任务中展现出全球领先的综合能力。
## Kimi K3 与混元 3D 生成上线
### 新增模型
* 新增 [`kimi-k3`](https://aihubmix.com/model/kimi-k3):Kimi K3 是 Moonshot AI 发布的开放 3T 级长上下文模型,采用 2.8T 参数、1M 上下文窗口,并原生支持视觉输入,适合长程编码、知识工作、复杂推理和多模态理解场景。调用方式见 [Kimi K3 实测调用指南](/cn/blogs/kimi-k3-guide)(三接口示例与能力支持矩阵)。
* 新增 [`hy-3d-3.1`](https://aihubmix.com/model/hy-3d-3.1):腾讯混元生 3D 专业版模型,支持文生 3D、图生 3D 与多视图输入,面向游戏、电商展示、3D 打印、产品设计等 3D 资产生成场景;3.1 版本在几何精度与纹理细节上进一步提升,并支持八视图多角度输入。
### 3D 生成接口上线
* 新增 `/v1/3d/generations` 异步 3D 生成接口,首期接入腾讯 TokenHub 混元 3D。支持提交生成任务和查询任务结果,便于把 3D 资产生成接入自动化工作流。
### Kimi K3 动态工具兼容
* Kimi K3 请求中的 message-level 动态工具声明会被保留并透传,模型推理厂商不再因为工具声明丢失而返回 400;使用 Kimi 动态加载工具的客户端兼容性更好。
### 请求转换错误更清晰
* Chat Completions 中的 custom tool、Cohere 文本块和 `assistant.content: null` 等请求形态兼容性提升。合法请求更稳定地到达模型推理厂商;畸形或不支持的输入会返回结构化错误,不再被误判为空 200 成功。
### Seedream 图片计费口径更新
* `doubao-seedream-5-0-pro` 的图片生成计费现在支持按输出像素档和输入图片张数计价,文生图、图生图等请求的费用更贴近实际生成规格。
## Gemini 工具与结构化输出兼容优化
### Gemini 工具调用兼容性修复
* 通过 OpenAI 兼容接口调用 Gemini/Vertex 时,工具定义或结构化输出 schema 中包含空字符串枚举值的请求不再因模型推理厂商校验返回 400;工具调用和 JSON Schema 工作流更稳定。
## OpenAI 音频模型与智能路由页面上线
### 新增音频模型
* 新增 [`gpt-audio-1.5`](https://aihubmix.com/model/gpt-audio-1.5):OpenAI 首个正式可用(GA)的音频模型,支持音频输入与音频输出,可通过 Chat Completions REST API 调用,适合语音对话、音频理解与音频生成场景。
* 新增 [`gpt-4o-transcribe-diarize`](https://aihubmix.com/model/gpt-4o-transcribe-diarize):带说话人分离的 ASR 转写模型,可把对话中的音频片段关联到不同说话人;该模型仅在 Transcription API 中可用。
### 智能路由功能介绍页上线
* [智能路由功能介绍页](https://aihubmix.com/llm-router/auto)现已上线,展示公开路由维度评分与在池模型。同时新增两个开放接口:[获取自动路由策略对应模型范围](/cn/api/RouterEndpoints/leaderboard)返回 5 大类 23 个子维度的模型评分、价格系数、首字延迟与在池模型,[获取模型厂商图标](/cn/api/RouterEndpoints/vendors)返回模型厂商的显示名与图标;图像与视频生成维度暂未纳入。使用方式参见[模型智能路由](/cn/api/llm-router)文档。
## API 错误校验与提示词缓存优化
### API 错误提示更一致
* `/v1/responses` 使用未知模型时,现在返回 400,与其他 API 入口保持一致,便于客户端按“无可用服务”场景处理,而不是收到 500。
### 请求参数校验更早返回给客户端
* 请求体转换或参数校验失败时,API 会直接返回相应的 400/错误信息,不再把原始请求继续转给模型推理厂商,减少无效调用和难以理解的失败。
### Claude Code 缓存命中更稳定
* Claude Code 通过 Bedrock 调用 Claude 时,同一会话内的 prompt cache 命中更稳定,有助于减少重复缓存写入费用和首 token 延迟。
### Gemini 多轮/缓存请求粘性更精确
* Gemini 请求现在按响应中实际出现的思考签名或缓存活动决定是否保持同一服务,减少多轮验签或缓存状态不一致;图片生成等无状态任务不会被不必要地固定到同一服务。
## GPT-5.6 系列与提示词缓存更新
### 新增模型
* 新增 `gpt-5.6-sol`、`gpt-5.6-terra`、`gpt-5.6-luna` 三款 GPT-5.6 系列模型(OpenAI 2026-07-09 正式发布)。三档均为 1,050,000 上下文窗口、128K 最大输出、知识截止 2026-02-16,支持文本与图像输入,可通过 Chat Completions、Responses 与 Claude 兼容的 Messages 接口调用。Sol 为旗舰档,面向复杂专业工作,官方称其为当前最佳编码模型;Terra 性能与 GPT-5.5 相当且价格减半;Luna 面向成本敏感场景。
### GPT 提示词缓存文档上线
* 新增 [GPT 提示词缓存](/cn/api/GPT-Cache)文档:GPT-5.6 系列起缓存写入按 1.25 倍输入价计费、缓存读取按 0.1 倍计费、缓存至少保留 30 分钟;覆盖 `prompt_cache_key` 与显式缓存断点参数说明、计费逻辑、接口示例与命中排查。[提示词缓存实践](/cn/practices/prompt-caching)与 [Claude 提示词缓存](/cn/api/Claude-Cache)的 OpenAI 缓存口径同步更新。
### Claude Fable/Mythos 思考模式兼容
* Claude Fable 与 Mythos 系列在请求中使用 `reasoning_effort` 时,现在会按 adaptive thinking 处理,减少这类模型因思考参数不匹配导致的模型推理厂商 400。
### Claude 与 Gemini 的 stop 参数生效更一致
* OpenAI 兼容请求里的 `stop` 现在会映射到 Claude 与 Gemini 原生请求。Claude 不接受的纯空白 stop 会被过滤,OpenAI/Gemini 的数量限制也按各自规则处理,跨协议生成截断更稳定。
### gpt-chat-latest token 上限参数兼容
* `gpt-chat-latest` 以及后续 GPT/ChatGPT latest 别名在需要时会保留 `max_completion_tokens`,减少因误发旧字段 `max_tokens` 导致的 400。
### Key 额度耗尽提示更清晰
* 当 Key 级别使用限额耗尽时,API 现在返回更明确的引导文案,提示去调整并激活 Key 限额,而不是仅返回底层 quota 报错。
### Tool calls 响应结构对齐 OpenAI
* 非流式 chat 响应在只有 `tool_calls`、没有文本内容时,现在会显式返回 `content: null`,提升 OpenAI 风格 SDK 与响应解析器的兼容性。
## 结构化输出修复与 Grok 4.5 上线
### 结构化输出修复:JSON 格式错误自动修复
* 新增 Key 级别的[结构化输出修复](/cn/api/structured-output-repair)能力,默认关闭。开启后,对声明了结构化 JSON 输出的非流式请求,当模型返回的 JSON 存在截断、尾随逗号、代码块包裹等格式错误时,网关在返回前自动修复为可解析的合法 JSON,数值保持原样,客户端无需改动。支持 Chat Completions、Responses、Claude、Gemini 四种协议;发生修复时响应带有 `X-JSON-Repaired: true` 响应头。
### Claude 提示词缓存文档:补齐各模型最小缓存 token 门槛
* 完善 [Claude 提示词缓存](/cn/api/Claude-Cache) 与[提示词缓存实践](/cn/practices/prompt-caching)文档,补齐按模型区分的最小可缓存 token 门槛(512 / 1,024 / 2,048 / 4,096),新增 Claude Opus 4.8、Opus 4.7、Fable 5 等当前模型。该门槛并非随模型版本升级而提高;低于门槛的前缀即使显式设置 `cache_control` 也不会被缓存。
### 用量看板与结算明细口径对齐
* 用量看板的聚合结果现在更接近日志明细结算口径,减少并发聚合丢数,并统一延迟重放时的小时归桶。历史看板数据仍可能存在小幅差异;对账和结算仍以请求日志明细为准。
### 新增模型
* 新增 `grok-4.5`,面向代码、Agent 任务和知识工作,支持可配置推理、工具调用和 500K 上下文,适合代码修复、复杂工程任务、知识问答与 Agent 工作流。
## GPT 工具调用自动桥接 Responses
### gpt-5.5+ 工具调用自动桥接 Responses
* 使用 OpenAI 兼容 `/v1/chat/completions` 调用 gpt-5.5 及以上模型时,带 tools 和 `reasoning_effort` 的请求会自动走 Responses 能力,减少模型推理厂商因参数组合不支持导致的 400。现有客户端无需改成 `/v1/responses` 也能获得更稳的工具调用体验。详见:[Responses API](https://docs.aihubmix.com/cn/api/Responses-API)
## 结构化输出与 Vertex Messages 兼容优化
### 结构化输出跨协议兼容
* OpenAI 兼容的 `response_format` 与 Claude 原生 `output_config.format` 现在可在相关路径中双向适配。调用方在跨 OpenAI/Claude 协议切换时,更容易保留结构化输出约束。详见:[Structured Output](https://docs.aihubmix.com/cn/api/Structured-Output)。
### Vertex AI 的 `/v1/messages` 调用更稳定
* 通过 Vertex AI 调用 Gemini 等非 Claude 模型时,`/v1/messages` 请求会按模型族正确分流,减少误走 Claude 路径导致的 not found 或 404。
## Gemini 原生端点与腾讯混元 Hy3 上线
### Gemini 原生端点补齐
* `@google/genai` SDK 通过 AIHubMix 的 Gemini 入口调用时,现已支持原生 Embeddings、Interactions 和 Context Caching 相关能力。此前这些路径可能返回路由未注册或 404;现在可用于向量生成、交互式推理(含文本与图像生成)和缓存创建/查询/删除等工作流。详见:[Gemini 原生 SDK 接入](/cn/api/Gemini-SDK)
### 长上下文模型计费覆盖扩展
* `hy3-preview`、ERNIE、Grok、Mimo 等长上下文模型现已支持按上下文长度分档计费,费用计算更精确。
### Vertex AI 流式日志指标修复
* Vertex AI 的 Gemini/Claude 流式请求现在会记录更准确的首 token 与延迟数据,日志页和监控排查看到的耗时信息更可信;该变化不影响模型响应内容。
### 新增模型
* 新增 `tencent-hy3` 文本生成模型(腾讯混元 Hy3 正式版)。MoE 架构,295B 总参数 / 21B 激活参数,256K 上下文窗口。支持快慢思维融合推理模式,适合复杂推理、代码生成和 Agent 工作流。Apache 2.0 许可证开源。
## Jina 文件上传与流式响应修复
### Jina Search/Reader 支持 POST 与文件上传
* Jina Search 与 Reader 现在支持 POST 调用;Reader 可通过 multipart 上传 PDF、Word、Excel、PPT、HTML 和图片等本地文件。默认响应更贴近 Jina 原生 markdown;需要 JSON 的客户端可显式发送 `Accept: application/json`。
### Responses 端点的 Azure 类服务调用更稳定
* 修复 `/v1/responses` 经兼容桥接调用 Azure 类非 GPT 服务时可能因 `api-version` 为空而返回 404 的问题,减少此类请求的直接失败。
### 流式回答截断问题修复
* 修复部分 vLLM / Azure Foundry 类模型推理服务在流式输出中可能随机截断的问题,用户更容易收到完整回答、结束信号和用量信息。
### 新增模型:Command A Plus 05-2026
* 新增 `command-a-plus-05-2026` 文本生成模型,适合企业对话、文本生成和 Agent 工作流。
## 搜索、视频与账号能力更新
### Jina 搜索与网页读取接口上线
* 新增 Jina 搜索与 Reader 能力,支持通过 AIHubMix API Key 调用 Jina 搜索结果获取与网页内容读取能力,适合需要外部网页信息检索、资料读取和 Agent 工具调用的场景。详见:[Jina AI](https://docs.aihubmix.com/cn/api/Jina-AI)
### Veo 3.1 图生视频支持首尾帧与参考图
* Veo 3.1 图生视频现支持首帧、尾帧和参考图输入,用户可以更精确地控制视频起止画面、角色参考和风格参考,适用于更复杂的视频创作工作流。详见:[视频生成](https://docs.aihubmix.com/cn/api/Video-Gen)
### Gemini 重试稳定性优化
* 优化 Gemini 请求在重试与 fallback 场景下的兼容性,减少部分重试场景下的 400 错误,提升兜底调用的成功率。详见:[Gemini 使用指南](https://docs.aihubmix.com/cn/api/Gemini-Guides)
### OpenAI 兼容响应字段对齐
* OpenAI 兼容接口在非流式和流式响应中保留 `logprobs`、`refusal`、`finish_reason` 等字段的 `null` 值,减少依赖 OpenAI 标准响应结构的 SDK、Agent 和日志解析工具出现兼容差异。
### Claude Code 接入隐私与兼容性优化
* 优化 Claude Code 通过 AIHubMix 调用 Claude 模型时的请求兼容处理,减少客户端环境信息进入发往模型推理厂商的请求,提升第三方 Agent 客户端接入的隐私保护。
### 登录注册与个人中心能力完善
* 自建账号体系补齐邮箱验证码登录/注册、密码设置、资料修改、第三方账号绑定解绑与账号注销等后端能力,并加强验证码用途隔离与禁用账号拦截;Stripe 充值回调处理也更稳健。
### 新增模型
* **claude-sonnet-5**(对话 / 推理 / Agent 场景)。
* **gemma-4-31b**、**longcat-2.0**(文本生成模型)。
* **gemini-3.1-flash-lite-image**(图像能力模型)。
* **mai-image-2.5**、**mai-image-2.5-flash**(图像生成模型)。
## 图像计费、参数与上传日志优化
### 图像生成计费与参数兼容性优化
* `gpt-image-2` 在 Images 端点的计费口径统一为按 token 结算;GLM 图像生成支持透传 `watermark_enabled`、`quality` 等扩展参数,去水印与质量控制等设置可按模型推理厂商能力生效。详见:[图像生成](https://docs.aihubmix.com/cn/api/Image-Gen)
### Gemini 文件上传日志优化
* Gemini 文件上传接口失败时不再写入用户可见的普通请求日志,减少非推理接口在日志页产生的噪音;内部排障日志仍会保留。
## OpenAI Deep Research 模型上线
### 新增 Deep Research 模型
* 新增 **o4-mini-deep-research** 与 **o3-deep-research**,仅支持通过 `/v1/responses` 接口调用;请求需包含 `web_search_preview` 或 `mcp` tools,适合需要深度资料检索与研究型回答的场景。
## Responses 跨模型支持与 Codex 自定义模型
### Responses 协议支持任意模型
* `/v1/responses` 端点不再限于 GPT 系列,现可调用平台上的任意模型。基于 Responses 协议的工具(如 Codex CLI)因此能通过本地模型目录使用 GLM、Gemini、DeepSeek、Kimi、Qwen 等模型,不再局限于 OpenAI 官方模型。
### Step 3.7 Flash 的 Responses 输出修复
* 修复 `step-3.7-flash` 通过 `/v1/responses` 调用时可能返回空白内容或空响应的问题,推理内容和最终回答现在可正常返回。
### Codex CLI 新增自定义模型支持
* [Codex CLI](https://docs.aihubmix.com/cn/api/Codex-CLI) 文档新增「在 Codex 中使用自定义模型」教程:通过本地模型目录(`model_catalog_json`)声明 AIHubMix 上的任意模型(GLM、Gemini、DeepSeek、Kimi、Qwen 等),即可在 Codex 的 `/model` 列表里自由切换,不再局限于 OpenAI 官方模型。文档含一键生成前 30 名模型目录的脚本与常见踩坑说明。详见:[Codex CLI · 在 Codex 中使用自定义模型](https://docs.aihubmix.com/cn/api/Codex-CLI#custom-models)
## Inferera 备用 API 域名上线
### 新增备用域名支持
* 新增备用域名 `https://api.inferera.com`,端点与能力和主域名 `https://aihubmix.com` 完全一致。当主域名访问异常(如无法连接、超时)时,可将请求地址替换为备用域名,API Key、模型、请求体等参数保持不变。
## 豆包、HappyHorse 与充值体验更新
### 新增模型
* 豆包 **doubao-seed-2-1-pro**、**doubao-seed-2-1-turbo**。
* HappyHorse 视频系列 **happyhorse-1.1-t2v**(文生视频)、**happyhorse-1.1-r2v**(参考生成)、**happyhorse-1.1-i2v**(图生视频)。
### Stripe 结账体验优化
* Stripe 结账页会自动预填账户邮箱,并减少不必要的姓名和账单地址收集,支付宝等支付方式的充值流程更简洁。
### 负余额账户调用限制
* 当账户余额低于 -\$1 时,将无法继续调用免费模型;请充值后再发起调用。
## CLI、智能路由与 Agent Skill 上线
### 新增 AIHubMix CLI(命令行工具)文档
* 新增 [AIHubMix CLI(命令行工具)](https://docs.aihubmix.com/cn/api/aihubmix-cli) 文档:单一二进制、零依赖(无需 Python / Node / Go),在终端即可查询账户余额、管理 API Key、查看可用模型,并对脚本与 AI Agent(如 Claude Code)友好。
### 新增模型智能路由(LLM Router)
* 请求模型名填 `auto`,网关按请求内容从平台数百个模型中自动选出最优模型,支持成本优先 / 质量优先 / 低延迟等策略,按实际命中模型计费,客户端代码零改动。详见:[模型智能路由](https://docs.aihubmix.com/cn/api/llm-router)
### DeepSeek 缓存命中率修复
* 修复 `deepseek-v4-pro`、`deepseek-v4-flash` 两个模型缓存命中率低于预期的问题。
### 新增 AIHubMix Skill(AI 编程助手扩展)
* 为 Codex、Claude Code、Cursor、Cline 等支持 Skills 的 AI Agent 提供本地扩展能力:用自然语言完成 AIHubMix 接入、模型查询、按能力选型、示例生成与错误排查。该 Skill 按需从官方接口读取模型、价格、协议契约等实时信息,避免 Agent 依赖过期记忆。详见:[Skills](https://docs.aihubmix.com/cn/skills)
## 可灵视频生成能力接入
### 新增可灵(Kling)视频模型
* 接入可灵视频生成全能力:文生视频、图生视频、多图参考与 omni 多模态生成,按模型名走原生协议调用。
## OpenClaw 插件修复与 GLM-5.2 上线
### OpenClaw 接入插件问题已修复
* AIHubMix 的 OpenClaw 接入插件 [aihubmix-auth](https://github.com/akakenle/aihubmix-auth) 已修复此前的接入问题,现可稳定使用。安装并填入一把 AIHubMix Key 即可在 OpenClaw 中同时调用 OpenAI / Anthropic / Gemini 等模型。
### 新增模型
* 智谱 **glm-5.2**。
## Open Design 接入与编程模型更新
### 新增 Open Design 接入支持
* AIHubMix 现已是 [Open Design](https://open-design.ai/)(开源、本地优先的 Claude Design 平替)内置支持的 BYOK 网关。在其 API(BYOK)模式里选 AIHubMix、填一把 Key,即可同时驱动聊天 / 图像 / 视频 / 语音生成,并按模型名走各家原生协议。详见:[Open Design 接入教程](https://docs.aihubmix.com/cn/clients/Open-Design)
### 智谱 GLM 5.2 支持推理强度分档
* 原生智谱服务的 `glm-5.2` 支持 `reasoning_effort` 分档调节思考深度,旧版模型按版本自动分流,调用方无需改动。
### 新增模型
* **kimi-k2.7-code-highspeed**(Kimi 代码高速版)。
## Coding GLM-5.2 与免费版上线
### 新增模型
* **coding-glm-5.2** 及免费版 **coding-glm-5.2-free**。
## 模型映射、错误回退与 Kimi Code 上线
### 模型映射与错误回退
* **新增模型映射(Mapping)与错误回退(Fallback):** 在控制台为每个 API Key 配置模型名映射与错误时回退,把客户端的模型别名改写为真实模型名,主模型失败时自动切换到备用模型,按最终响应模型计费,客户端代码零改动。详见:[模型映射与回退](https://docs.aihubmix.com/cn/api/Model-Mapping-Fallback)
### 新增模型
* **kimi-k2.7-code**。
## Step 3.7 Flash 优惠与 Claude 迁移提示
### step-3.7-flash 限时 1 折
* step-3.7-flash 限时 1 折优惠:输入每百万 token 仅 0.022 美元,输出每百万 token 仅 0.132 美元,欢迎体验。
### 模型下架与自动路由
* `claude-opus-4-20250514`、`claude-sonnet-4-20250514` 官方将于 6 月 15 日下架,届时平台会自动将下架模型路由至同系列 4-5 版本。
## Claude Fable 5 上线记录与特性说明
### 新增模型
* **claude-fable-5**【已退役】。
### Claude 新模型 Fable 5 / Mythos 5 的特性说明
* **Fable 5 有更强的安全护栏,部分正常问题也可能被拦:** 会对网络安全、生物 / 化学、模型蒸馏 / 推理提取等方向做额外分类。有些技术研究、漏洞分析、生物医药相关问题,可能被拒绝,或转交到 Opus 4.8 回答。
* **Mythos 5 是受限访问,不是普通开放模型:** Mythos 5 和 Fable 5 能力同源,但少了部分安全分类器;目前只面向 Project Glasswing / 获批客户。一般用户实际用到的是带护栏的 Fable 5。
* **API 成本更高:** Fable 5 价格为每百万输入 token 10 美元、每百万输出 token 50 美元,约为 Opus 4.8 的两倍。
* **隐私:** Fable 5 / Mythos 5 被列为 Covered Models,默认要求至少 30 天数据保留,不支持 Zero Data Retention。
* **API 调用拒绝显示:** Fable 5 拒绝请求时,API 返回的是 HTTP 200,但 `stop_reason` 是 `refusal`。
## Gemini 音频输入与用量计量补齐
### Gemini 兼容接口支持音频输入
* OpenAI 兼容接口(`/v1/chat/completions`)调用 Gemini 时支持 `input_audio` 音频输入(此前会被静默丢弃),并在返回的 usage 中补齐 audio\_tokens 计量。
## Grok、混元与 Step 模型扩容
### 新增模型
* **grok-build-0.1**、**hy3-preview**、免费模型 **step-3.7-flash-free**。
## Qwen 3.7 Plus 上线
### 新增模型
* 通义千问 **qwen3.7-plus**。
## MiniMax M3 与百度图像模型上线
### 新增模型
* MiniMax **minimax-m3**。
* 百度 **musesteamer-air-image**(图像生成)。
## Claude 4.7 系列接入
### 新增模型支持
* **Claude 4.7 系列:** 正式接入最新一代 Claude 4.7 模型,包括 `claude-opus-4-7` 以及具备深度思考能力的 `claude-opus-4-7-think`。该系列在复杂逻辑推理、代码编写及长文本处理能力上实现大幅跃升。详见官方文档:[Claude 4.7 新增参数说明](https://docs.aihubmix.com/cn/blogs/claude-opus4.7)
## 智谱 GLM-5.1 上线
### 模型库扩容
* **智谱 AI 更新:** 新增 `glm-5.1` 模型支持,针对中文语境下的语义理解、创意生成及多轮对话逻辑进行了深度优化。
## Wan 2.7 视频全系列接入
### 多模态视频模型上线
* **Wan 2.7 全系列集成:** 深度接入 Wan 2.7 视频生成大模型,提供全场景创作支持:
* `wan2.7-t2v`:高品质文生视频。
* `wan2.7-i2v`:精准图生视频。
* `wan2.7-r2v`:基于参考视频的风格迁移与生成。
* `wan2.7-videoedit`:智能视频编辑与重绘。
## 多模态、通用与视频模型扩容
### 大规模模型接入
* **多模态与通用模型:** 新增智谱 `glm-5v-turbo`(多模态理解)及阿里通义千问 `qwen3.6-plus`。
* **高性能视频模型:** 接入字节跳动豆包系列 `doubao-seedance-2-0-fast-260128` 等模型,显著提升视频生成响应速度。
## 请求日志性能与服务信息展示升级
### 日志明细页面
* 首 Token 延时:帮助判断请求启动速度(从发起请求到返回第一个 Token 的耗时)
* 吞吐量:用于直观衡量模型输出速度
* E2E:从发送请求到响应结束的整体耗时,用于评估完整请求性能
* 服务商:标识请求实际调用的模型供应商
* 状态:标识请求执行结果(如成功 / 失败),用于快速判断请求是否异常
* tid:唯一请求标识,在遇到问题时可提供给技术支持进行快速排查
## 全球加速网络与健康监测上线
* AIHubMix 全球加速网络正式上线:自建全球边缘节点与智能调度体系,通过持续监控与动态优化,实现响应延迟降低 75%、稳定性提升 60%、可用性达 99.99%,让 AI 应用体验更快更稳。
* 新增 7×24 实时健康监测:多区域探针每分钟全网检测延迟、成功率与稳定性,异常可在用户感知前自动识别并处理,保障服务持续稳定。
* 优化智能流量调度:基于多时间窗口动态计算节点健康评分,毫秒级自动切换最优路径,显著降低波动与超时,提升整体请求成功率。
## Chat 转 Responses 与模型弃用通知
* 新功能: Chat → Responses 兼容调用 本次上线 Chat → Responses 兼容能力,支持通过 chat/completions 接口调用 OpenAI 仅支持 Responses 协议的模型,包括 gpt-5.2-codex、gpt-5.1-codex-max、gpt-5.2-pro 等。 如需要强制 AIHubmix 的 chat 接口让背后路由都走 Responses 协议,请在请求中添加 Header:X-Use-Responses-Enabled: true。当模型同时支持 Chat 与 Responses 双协议时,设置该参数将强制请求使用 Responses 接口。当前 Responses 协议暂不支持音频输入输出,请注意使用场景。
* 模型弃用通知:OpenAI 将于 2026 年 2 月 17 日 下线 chatgpt-4o-latest,我们会在下线后自动将 chatgpt-4o-latest 映射至 gpt-4o-2024-11-20
## 2025 年
## Google Files API 支持上线
* 新功能: Google 接口已支持 [Files API](https://docs.aihubmix.com/cn/api/Gemini-Guides#files-api)
## Qwen、Seedream 与百度绘图模型接入
* 新增 [Qwen系列、豆包seedream4以及百度系列画图模型](/cn/api/Image-Gen)
## AIHubMix 图片生成 MCP 上线
* 推出 [Aihubmix 图片生成 MCP](/cn/clients/AHM-mcp),方便开发者接入图片生成服务
## Claude Code 跨模型调用支持
* 在 Claude Code 中[使用 AiHubMix 平台的任何大模型](/cn/api/CC-any)
## AI SDK 接入支持
* 新增 [AI SDK](/cn/api/AISDK) 支持,一个 KEY 接入海量模型。
## Flux 图像生成接口上线
* 新增 [Flux 接口](/cn/api/Image-Gen) 支持,高质量图片秒出。
## Qwen Code 接入支持
* 新增 [Qwen Code](/cn/api/Qwen-code) 支持,利用 Aihubmix 平台的所有大语言模型来提供支持。
## 文档 llms.txt 模型导航上线
* 新增 [llms.txt](https://docs.aihubmix.com/llms.txt) 支持,一键获取标准化模型导航,让你的 LLM 助手快速读懂全平台模型生态。
## Gemini CLI 与 Responses 工具扩展
* 新增 [Gemini Cli](/cn/api/Gemini-Cli) 转发支持,多种使用方式,由你灵活掌控。
* OpenAI Responses API 接口新增代码解析器和 Remote MCP 调用。
## 通用图像生成接口上线
* 新增 [通用图形接口](/cn/api/Image-Gen),支持多种主流模型,包括 OpenAI、Ideogram、Stability、Google Imagen。
## APP-Code 应用标识与开发者优惠
* 推出 [应用标识码 APP-Code](/cn/api/App-code),为开发者们提供全部模型 10% 优惠;
## HTTP 状态码文档上线
* 新增 [HTTP 状态码](/cn/FAQs/HTTP-Codes) 文档,帮助用户更好地理解错误信息。
## Veo 3.0 视频生成接入
* 新增 Veo3.0 视频生成支持,丰富创作形式。
## Responses 推理总结展示支持
* 支持 openai 的推理总结 (Reasoning summaries) 显示,适用于 responses api。
## Gemini 隐式缓存支持
* 新增 Gemini 隐式缓存功能,支持自动命中与命中反馈。开发者可以通过 usage\_metadata 判断命中情况。成本节省非保证,实际效果因请求结构和使用场景而异。
## Claude 4 工具与缓存能力更新
Claude 4 新功能全面支持
* ⏳ **新的缓存周期**:1 小时级别的缓存Beta 支持
* 🎉 **新的文本编辑工具**:Claude 4 模型支持全新的 text\_editor\_20250429 工具类型和 str\_replace\_based\_edit\_tool 工具名称
* 🚫 **拒绝停止原因**:引入新的 refusal 停止原因,用于处理模型因安全原因拒绝生成的内容
* 🧠 **扩展思考**:Claude 4 模型返回完整思考过程的摘要,提供扩展思考的全部智能优势
* 🔄 **交错思考**:支持工具使用与扩展思考交错,实现更自然的对话体验(Beta)
* ⚠️ **不再支持的功能**:
* Claude 4 文本编辑工具不再支持 undo\_edit 命令
* 移除了 token-efficient-tools-2025-02-19 支持(仅 Claude 3.7 可用)
* 移除了 output-128k-2025-02-19 支持(仅 Claude 3.7 可用)
* 📚 更新了完整的迁移指南和代码示例,帮助用户从 Claude 3.7 平滑迁移到 Claude 4
## Dify 插件集成上线
* 新增对 Dify 插件的支持,实现 Aihubmix 模型在 Dify 中的无缝集成。只需一个密钥,扩展并管理两百多个模型。
## Codex Mini 与 Google 图像、视频更新
* 支持为编程任务而生的 codex-mini-latest,可通过 Responses api 端点或 Codex CLI 调用。
* 支持谷歌 imagen 3.0 绘图和 veo 2.0 视频生成,丰富你的创作形式。
* gemini-2.0-flash-exp 升级为正式预览版 gemini-2.0-flash-preview-image-generation
## Ideogram V3 图像接口上线
新增 [Ideogram AI V3](/cn/api/IdeogramAI) 接口,Ideogram 最先进的图像生成模型。
## 命令行管理脚本上线
新增 [实用管理脚本](/cn/api/Cli),支持命令行管理密钥、查看账户和可用模型列表等。
## GPT Image 1 与 Gemini 原生调用支持
1. 万众期待的 OpenAI 绘图接口 \gpt-image-1\ 正式上线,支持文生图、图生图。
2. 支持 Gemini 原生调用,可以精准控制 Flash 2.5 的推理预算。
## Jina 向量、重排与深度搜索接入
集成了 Jina AI 的三个核心接口,助你轻松构建功能强大的智能体。三个接口分别是:向量嵌入 (Embeddings)、重排序 (Rerank)和深度搜索 (DeepSearch)
## OpenAI Responses API 上线
OpenAI Responses api 端点支持,工具支持更全面。
## Codex CLI 接入支持
新增 OpenAI [CodeX CLI 支持](/cn/api/Codex-CLI)!在命令行中用自然语言编程。
## 跨模型联网搜索 Beta 上线
通过在模型 id 后方追加 :surfing,[让任何模型具备搜索能力 Beta](/cn/api/LLM-Search)
## Claude 提示词缓存支持
支持 Claude prompt caching,高频提示词重复使用可节省高达 76% 成本!
## Ideogram 绘图与编辑接口接入
支持 Ideogram AI 绘图接口,文字绘制能力强劲,支持生图、混合、局部编辑和放大等。
## 新版文档上线
全新文档,带给大家更好的体验
## Claude 文本编辑工具支持
支持 Claude 文本编辑工具 (Claude Text Edit Tool)
## 品牌 Logo 更新
启用全新的三叉戟 Logo
## OpenAI 与 Gemini 原生搜索支持
新增了对 OpenAi 和 Google Gemini 模型的原生搜索功能的支持;未来将完善这个接口扩展支持第三方搜;
## GPT-4o 搜索模型接入
新增模型:gpt-4o-mini-search-preview 和 gpt-4o-search-preview
## o1 与 o3-mini 价格下调
o1 和 o3-mini 价格下降 10%,跟官网一致;
## DeepSeek 价格调整与 Qwen 模型扩容
aihubmix-DeepSeek-R1 由于微软价格上涨 7 倍因此该模型价格上涨 7 倍,推荐使用火山的 DeepSeek-R1,稳定又便宜;新增 qwen-qwq-32b 和 qwen2.5-vl-72b-instruct
## Claude 降价与 GPT-4.5 Preview 上线
Claude 模型全面降价 15%;新增模型 gpt-4.5-preview;注意价格极其昂贵,调用请注意;
## DeepSeek 服务稳定性提升
提升 Deepseek 稳定性;来自字节的最稳定,推荐用这两个:DeepSeek-R1 和 DeepSeek-V3;
## Claude 3.7 Sonnet 上线
增模型 claude-3-7-sonnet-20250219
## 模型服务调整与详情页更新
* gpt-4o 概率性出现返回很慢的情况,次为厂商问题;建议暂时改用 gpt-4o-2024-11-20
* Perplexity api 暂时下线,Perplexity 官方的计费模式较为复杂,成本高于本平台的定价结构,我们调整价格后重新上线;
* 字节官方限时折扣结束恢复原价,DeepSeek-R1 价格已上调
* 新增模型详情页及参数信息
## DeepSeek-V3 折扣结束与价格调整
* 字节官方限时折扣结束恢复原价,DeepSeek-V3 价格已上调;预计字节的 R1 近期也会恢复原价,所以我们也会同步涨价
## 控制台结构优化与模型扩容
* 新增模型:kimi-latest(官方计费根据输入内容长度 8k,32k,128k 分 3 档计费,本站不支持该计费结构,取中 32k 档为计费标准,价格敏感介意勿用)
* 优化了网站页面结构;
* 日志页面并入用量统计页;
* 公告内容移到模型广场页,
* 设置移到头像下面;
* aihubmix-DeepSeek-R1 价格下降 50%
* 新增模型:gemini-2.0-pro-exp-02-05-search,gemini-2.0-flash-exp-search,集成了谷歌官方搜索联网功能
* 新增模型:gemini-2.0-flash、gemini-2.0-pro-exp-02-05、gemini-2.0-flash-lite-preview-02-05 新增模型:o3-mini,o1(注这两个模型后台扣费比官方贵 10% 左右,因为这两个模型帐号帐号有限)
## o1 与 o3-mini 调用参数说明
* o1 模型 openai 官方不支持传入参数 stream
* o3-mini 不支持传入参数 temperature,o3-mini 新增参数 Reasoning effort;可以传入"low, medium, high" 如果不传默认为 medium
## OpenAI 音频能力与多厂商模型扩容
功能:新增 openai 声音模型输入输出的功能支持,api.aihubmix.com 服务器可用,主站服务器稳定 1 周后更新支持。总体后台扣费和官方一致,暂时日志只展示文字部分 token 声音费用暂时无法展示,但不影响使用
新增模型:
* o3-mini,o1;(注这两个模型后台扣费比官方贵 10% 左右,因为这两个模型帐号帐号有限)
* aihubmix-DeepSeek-R1(推荐,比较稳定)
* qwen-max-0125(即 Qwen2.5-Max)、sonar-reasoning
* deepseek-ai/DeepSeek-R1-Zero和deepseek-ai/DeepSeek-R1,deepseek-r1-distill-llama-70b
* aihub-Phi-4
* Doubao-1.5-pro-256k、Doubao-1.5-pro-32k、Doubao-1.5-lite-32k、Doubao-1.5-vision-pro-32k
* sonar、sonar-pro(perplexity ai 最新发布)
* gemini-2.0-flash-thinking-exp-01-21
* deepseek-reasoner(即 DeepSeek-R1)
* MiniMax-Text-01
* codestral-latest(Mistral 推出了新的 code 模型 - Codestral 25.01)
## DeepSeek、豆包与 Gemini 模型扩容
新增模型:
* aihub-Phi-4
* Doubao-1.5-pro-256k、Doubao-1.5-pro-32k、Doubao-1.5-lite-32k、Doubao-1.5-vision-pro-32k
* sonar、sonar-pro(perplexity ai 最新发布)
* gemini-2.0-flash-thinking-exp-01-21
* deepseek-reasoner(即 DeepSeek-R1)
## Perplexity、MiniMax 与 Codestral 接入
* 新增 Perplexity Ai API 模型;仅支持 api.aihubmix.com 预览版服务器调用,如果没问题我们会更新到主服务器 aihubmi.com; api.aihubmix.com 为预览版服务器,后续新功能先更新到这个服务器,通常稳定 1 周我们再更新到主服务器 aihubmix.com 新增模型:
* MiniMax-Text-01
* codestral-latest(Mistral 推出了新的 code 模型 - Codestral 25.01)
## Gemini 联网搜索与 DeepSeek-V3 上线
* 新增 gemini-2.0-flash-exp-search,支持谷歌原生联网搜索功能;官方 gemini 2.0 flash 模型的联网需要额外传入参数才支持联网功能,aihubmix 做了集成,模型名字加上 search 参数即可使用
* 新增模型 deepseek-ai/DeepSeek-V3
## 模型广场上线
* 新增模型广场页面代替原来的模型/价格页面
## 2024 年
## Gemini 思考输出与余额邮件修复
* 修复 gemini-2.0-flash-thinking-exp-1219 模型只输出思考没有答案问题
* 修复余额提醒邮件收不到问题
## 用量统计、充值记录与模型扩容
* 新增用量统计页面,新增充值记录页面
* 新增豆包系列模型:Doubao-lite-128k、Doubao-lite-32k、Doubao-lite-4k、Doubao-pro-128k、Doubao-pro-256k、Doubao-pro-32k、Doubao-pro-4k
* 新增模型:gemini-2.0-flash-thinking-exp-1219
* 新增模型:gemini-2.0-flash-exp、aihubmix-Mistral-Large-2411、aihubmix-Llama-3-3-70B-Instruct、grok-2-1212、grok-2-vision-1212
* 新增模型:gemini-exp-1206、llama-3.3-70b-versatile、learnlm-1.5-pro-experimental
## Gemini、Mistral 与 Llama 模型接入
* 新增模型:gemini-2.0-flash-exp、aihubmix-Mistral-Large-2411、aihubmix-Llama-3-3-70B-Instruct
## 新模型接入与用量统计上线
* 新增模型:gemini-exp-1206、llama-3.3-70b-versatile、learnlm-1.5-pro-experimental
* 新增用量统计页面
## GPT-4o、Grok 与 Qwen 长上下文更新
* 近期新增模型:gpt-4o-2024-11-20,step-2-16k,grok-vision-beta,
* 千问 2.5turbo 百万上下文模型:qwen-turbo-2024-11-01
## Claude 原生 SDK 与 Messages 接口支持
* 兼容 Claude 原生 sdk,v1/messages 接口已支持上线;
* Claude 原生接口的缓存和控制计算机功能还不支持(prompt caching 和 computer use)我们会在接下来的两周内继续完善。
## Claude Haiku 与 Grok Beta 上线
* 新增模型:claude-3-5-haiku-20241022
* 新增马斯克 x.ai 最新模型 grok-beta
## Claude 3.5 Sonnet 新版本接入
* 新增模型:claude-3-5-sonnet-20241022
## OpenAI 提示词缓存功能上线
OpenAI 最新的缓存功能现已上线。此功能目前支持以下模型:
* GPT-4o
* GPT-4o-mini
* o1-preview
* o1-mini 请注意,gpt-4o-2024-05-13 版本不在官方支持范围内。 如果请求命中缓存,您将能够在后台日志中看到相关的缓存 token 数据。 更多详细信息和使用规则,请访问 OpenAI 官方网站:OpenAI 缓存功能详情
## GPT-4o 计费调整与模型扩容
* gpt-4o 模型后台计费下降价格同步官方
* 新增模型:aihubmix-Llama-3-2-90B-Vision,aihubmix-Llama-3-70B-Instruct
* 新增 Cohere 最新模型 aihubmix-command-r-08-2024,aihubmix-command-r-plus-08-2024
## Whisper 模型扩容与音频计费说明
* 新增模型:whisper-large-v3 和 distil-whisper-large-v3-en
* 注意:Whisper 模型实际计费是按照输入的秒数计费的,但是目前页面价格展示有问题未来会修复,后台底层计费没有问题 whisper-1 完全同步 Openai 官方扣费
## o1 系列接入与调用限制说明
* 新增模型 o1-mini 和 o1-preview;
注:最新这两个模型,要求传入参数有变,一些壳软件如果不更新默认传入的参数会报错;
需要注意
经测试,o1 模型不支持以下内容,并报错:
* system 字段:400 报错
* tools 字段:400 报错
* 图片输入:400 报错
* json\_object 输出:500 报错
* structured 输出:400 报错
* logprobs 输出:403 报错
* stream 输出:400 报错
* o1 系列:20 RPM,150,000,000 TPM,很低,随时 429 报错
* 其他:temperature, top\_p and n 被固定为 1;presence\_penalty 和 frequency\_penalty 被固定为 0
## 模型扩容、Claude 调价与并发提升
* 新增模型:mattshumer/Reflection-Llama-3.1-70B;ps:据说 llama3.1-70b 最强微调版本
* claude-3 模型价格上调调整,为了维持 Claude 模型稳定供应,目前调用我们会比直接调用官方贵 10%,后续会逐步下调;
* 增加了 Openai 系列模型的并发能力,理论上基本支持无限并发;
## Phi 模型扩容与调用稳定性优化
* 新增模型:Phi3medium128k、ahm-Phi-3-medium-4k、ahm-Phi-3-small-128k
* 增加了 Llama 相关模型的稳定性
* 进一步优化了 Claude 模型的兼容性
## GPT-4o 与 Gemini 新版本上线
* 新增 Openai 刚刚更新 4o 版本 gpt-4o-2024-08-06,见 [https://platform.openai.com/docs/guides/structured-outputs](https://platform.openai.com/docs/guides/structured-outputs)
* 新增 Google 最新模型:gemini-1.5-pro-exp-0801
## 在线充值、Claude 修复与域名迁移
* 增加了在线直接支付充值
* 修复了 Claude 多轮对话格式报错问题:1、messages: roles must alternate between "user" and "assistant", but found multiple "user" roles in a row;
* 优化了 Claude 模型的使用 function 功能时 index 问题
* [https://orisound.cn](https://orisound.cn) 备用服务器将在 9 月 7 日全面下线;目前在使用这个地址的请抽空改成主服务器 [https://aihubmix.com](https://aihubmix.com) 或者备用服务器 [https://api.aihubmix.com](https://api.aihubmix.com)
## Mistral Large 2 接入与系统优化
* 新增支持 Mistral Large 2,模型名称:Mistral-large-2407 或者 aihubmix-Mistral-large-2407;
* 系统优化
## Llama 3.1 系列上线
* 新增最新 llama-3.1 模型 llama-3.1-405b-instruct,llama-3.1-70b-versatile 和 llama-3.1-8b-instant,欢迎尝试;
## GPT-4o Mini 图像输入计费修复
* 已修复 gpt-4o-mini 模型在价格计算方面的问题。具体情况如下:
文本输入价格:OpenAI 官方的 gpt-4o-mini 模型输入文本的价格仅为 gpt-4o 模型价格的 1/33。
图片输入价格:OpenAI 官方的 gpt-4o-mini 模型输入图片的价格与 gpt-4o 模型价格相等。
* 为了确保价格计算的准确性,我们在计算 gpt-4o-mini 模型输入图片的 token 数时,将其乘以 33 倍,以与官方价格对齐。
* 详情可见 Open AI 官方价格
## GPT-4o Mini 上线
* 新增支持 gpt-4o-mini 模型,后台计费同步官方
## 流式响应支持返回用量
* 支持官方的 api 参数 include\_usage,传入参数可返回 stream 模式下的 usage,详情见 官方文档
## 客户端、工具调用与模型兼容优化
* 新版本 nextweb 增加了支持调用非 Openai 模型 调用本站非 OpenAI 模型
* 增加了阿里千问模型的后台扣费,总统调用我们的成本比调用阿里云官方贵 10% 左右
* 优化 azure openai 返回的输出更好的兼容了 Openai 接口
* 支持 Claude-3 的 tool Calling
* 增加了很多新模型,见设置/可用模型
## 后台界面与模型价格展示升级
* 整体后台界面进行了优化
* 日志每条请求记录增加了展示请求时当时的模型单价
* 增加了模型及价格页面 模型/价格
## Claude 3.5 Sonnet 接入
* 最新 claude-3-5-sonnet-20240620 已支持,调用方法见 调用本站非 open AI 模型教程
## 请求记录下载功能上线
* 后台日志页面现在开始,支持下载使用请求记录
## Azure OpenAI 路由分配调整
* 降低了随机到 azure openai 的概率,现在几乎很小概率会随机到
## Claude 3 系列价格下调
* 下调 Claude-3 相关模型的费用(Claude 3 Haiku、Claude 3 Sonnet、Claude 3 Opus)后台扣费和官方一致;因此当前我们网站额度零售价格,使用我们的 API 的成本相当于官网 86 折;
## GPT-4o 流式 Token 计数优化
* 优化 gpt-4o 的 token 计费,tokenizer 的 cI100k\_base 改为 0200k\_base,之前的 gpt-4 系列用的是 cI100k\_base;结果就是中文、韩文、日文的流式请求的 token 计数会比之前下降;
## Qwen2 开源模型接入
* 新增阿里最新开源模型 Qinwen2
* alibaba/Qwen2-7B-Instruct、alibaba/Qwen2-57B-A14B-Instruct、alibaba/Qwen2-72B-Instruct
## GPT-4o、Gemini 与 Llama 扩容
* 新增模型 gemini-1.5-flash
* 新增模型 gpt-4o
* 新增 llama3(llama3-70b-8192、llama3-8b-8192)gemini-1.5-pro、command-r、command-r-plus、欢迎调用尝试
* Claude-3 模型恢复供应;目前本站正在连接 Claude-3 部署在 aws 和 Google cloud 上的端点。
* 为了维持服务器费用及团队成本,Claude-3 模型和价格后台扣费比官方贵 10%
* 后续调用量增加的话,会逐步下调至 5% 左右,甚至更低,
* 目前并发有待测试和随着调用增加而去申请更高的并发调用。
***
更新时间:2026-06-22