# 常见问题 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。 LangWatch Settings 页面中的 Project API Key

2. 添加 LangWatch 目的地

1. 打开 [AIHubMix 广播](https://console.aihubmix.com/observability)。 2. 在 **Add destination** 下点击 **LangWatch**。 AIHubMix 广播页面中的 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 中关联会话或用户。 AIHubMix 的 LangWatch 目的地配置表单 ### 测试并保存 1. 点击 **Test**。连接成功后,按钮会显示 **Connected**。 2. 点击 **Add destination** 保存新目的地。 3. 确认目的地开关已开启,状态显示为 **OK**。 后续修改配置时,点击 **Save changes** 保存。 AIHubMix 中状态为 OK 的 LangWatch 目的地

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 和模型信息。 LangWatch Traces 页面中的 AIHubMix 调用记录 启用 Privacy 后,Prompt 等内容列显示为空,但耗时、成本、token 和模型信息仍会保留。 启用 Privacy 后 LangWatch 中为空的内容列 ## 常见问题 ### 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): 打开 Aihubmix 供应商的 API 设置 2. 配置以下三项,客户端会据此为 Claude 自动注入 `cache_control`: * **缓存 Token 阈值**(Cache Token Threshold):内容超过该 Token 数才注入缓存断点(设正数开启,0 或留空关闭); * **缓存系统消息**(Cache System Message):开启后给 `system` 消息打缓存断点(适合缓存固定的长系统提示词); * **缓存最后 N 条消息**(Cache Last N Messages):给最近 N 条消息打缓存断点(适合多轮对话滚动缓存)。 在 API 设置中配置缓存 Token 阈值、缓存系统消息、缓存最后 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 可用后,如仍进入登录流程,可按以下步骤跳过首次引导: Claude Code 首次启动时提示登录或继续配置的终端界面 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**,再点击「添加供应商」。 CC Switch 首页中点击添加供应商入口的界面 2. 在预设列表中选择「AiHubMix」。请确认当前配置的是 Claude Code 侧的 Provider。 CC Switch 供应商预设列表中选择 AiHubMix 的界面 3. 在「API Key」栏中填写你的真实密钥。 CC Switch AiHubMix 配置表单中填写 API Key 的界面 4. 配置完成后,先使用 `claude-sonnet-4-5` 作为模型 ID,点击「添加」保存设置。确认健康检查通过后,可在 Claude Code 中通过 `/models` 或 `/model` 切换其他 Claude 模型。 AIHubMix 模型列表中复制 Claude 模型 ID 的界面 5. 返回首页,在供应商列表中选择「AiHubMix」,点击「启动」即可使用。 CC Switch 首页中选择 AiHubMix 并点击启动的界面 > > Claude Code 终端中使用 status 和 models 命令查看模型配置 > > > 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,安装插件。 VS Code 扩展市场中安装 Claude Code 插件的界面 2. 按下 `Ctrl + Shift + P` (或 `Cmd + Shift + P`),输入 `Settings` 打开设置。 VS Code 命令面板中打开 Settings 设置页的界面 3. 搜索 `Claude Code` ,找到 `Claude Code: Environment Variable` → `Edit in settings.json` 。 VS Code 设置中搜索 Claude Code 环境变量配置项的界面 4. 在 `claudeCode.environmentVariables` 中填入 AIHubMix 相关信息。 VS Code settings.json 中配置 Claude Code 环境变量的示例 ## [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 模型。 Claude Code config 中检查自定义 API Key 的界面 在 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,添加供应商。 CC-Switch 添加供应商界面 2. 在预设列表中选择「AiHubMix」。 在 CC-Switch 预设列表选择 AiHubMix 3. 在「API Key」栏中填写你的密钥并点击「添加」保存设置。 在 CC-Switch 填写 API Key 并保存 4. 返回首页,在供应商列表中选择「AiHubMix」,点击「启用」即可使用。 在 CC-Switch 启用 AiHubMix 供应商 ## 使用 Codex ### 在终端中使用 1. 打开终端,定位到你的项目目录,然后运行 `codex` 命令。 ```bash theme={null} cd /你的项目路径 codex ``` 2. 根据需求,设置权限。 Codex 启动时设置审批权限 3. 根据需求,选择需要使用的模型。 Codex 选择使用的模型 4. 输入自然语言,若正常响应,则配置成功。 Codex 终端输入自然语言并正常响应 ### 在 Codex 桌面端使用 1. 打开 Codex 桌面端,选择工作目录。 2. 在输入框输入任务,若正常响应,则配置成功。 Codex 桌面端输入任务并正常响应 ## 实用命令参考 ### 帮助命令 ```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]` 段): config.toml 中 model_catalog_json 与 aihubmix provider 配置 ### 第 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` 后会列出目录里声明的全部模型,方向键选中、回车确认: Codex /model 选择器显示 AIHubMix 自定义模型列表 选中模型后,`/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): Codex 切换到 glm-5.2 后的会话与底部状态栏 ## 自定义模型常见问题 * **`/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) **示例图如下:** 在 Dify 插件市场安装 Aihubmix 插件 ## 配置 1. 首先点击页面右上角头像 → 选择「Settings」菜单 2. 点击左侧「Model Provider」Tab 3. 在右侧找到 Aihubmix → 展开 Setup,填入你的[API Key](https://console.aihubmix.com/token) 在模型供应商中配置 Aihubmix 与 API Key **目前预置的模型有以下 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 提供的模型。 **示例图如下:** LLM配置 ## Embeddings/Reranker 模型选择 Embeddings/Reranker 模型主要用于知识库问答,你可以在顶部的 Knowledge Tab 快速体验,也可以在工作流节点中选择相应的模型。 **示例图如下:** RAG配置 ## TTS/SST 选择 TTS/SST 模型主要用于语音解析与合成,选择工具时,对应的不是常规的「LLM」,而是「Tools」Tab 里面的「Audio」 类型。 对应关系: 1. TTS 文转音:选择「Text to Speech」 2. SST 音转文:选择「Speech to Text」 **示例图如下:** Audio配置 ## 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` 两个区块分别配置: 在 AIHubMix 创建 Key 面板中配置模型名映射与错误回退 *** ## 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 ``` AIHubMix 后台配置模型名映射与 Fallback 回退列表 ### 5.3 Claude Desktop 模型列表 在 Claude Desktop 的 `Model list` 里配置的是**映射前的别名**——也就是 Claude Desktop 发给 AIHubMix 的模型名,不是真实上游模型名。 Claude Desktop Model list 配置映射前的模型别名 配置完成后,Claude Desktop 的模型下拉框会出现对应模型: 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。 Claude Desktop 中上传图片后由兜底模型返回结果 AIHubMix 日志显示,这次最终实际调用的是 `Google AI Studio/gemini-3.1-flash-image`,也就是 fallback 列表里的第 2 个。第 1 个 `gpt-5.4` 同样不支持该图片输入、对这次请求继续返回可重试错误,于是网关接着往下,落到了支持图片理解的 `gemini-3.1-flash-image`。 AIHubMix 日志显示请求最终路由到支持图片理解的回退模型 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 的请求。 **视频效果:**