
摘要: 腾讯混元 Hy4 正式版已在腾讯云 TokenHub 上线,提供 OpenAI 兼容接口。本文提供从创建 API Key 到 Python/Node.js 调用、流式输出、多模态图片输入、Function Calling 的完整可执行代码,以及缓存优化与常见报错处理。
接入 Hy4 最快的路径是:不用改业务代码,只换两行配置。腾讯云 TokenHub 提供 OpenAI 兼容接口,把 base_url 指向混元端点、api_key 换成 TokenHub 的密钥,原有 OpenAI SDK 的调用代码可直接复用。Hy4 正式版于 2026 年 11 月 4 日上线,定价为输入 6 元/百万 Token、输出 18 元/百万、缓存命中 0.3 元/百万。
🚀 开始接入前,先开通服务 | 腾讯云大模型 Token Plan 已上线 Hy4,按量调用与订阅套餐限时优惠中。 👉 点击前往订阅购买 → cloud.tencent.com/act/pro/tokenplan
接入前需要准备三样东西。
项目 | 说明 |
|---|---|
腾讯云账号 | 已完成实名认证 |
TokenHub API Key | 混元 OpenAI 兼容接口的鉴权密钥 |
Python 3.8+ 或 Node.js 16+ | 运行 SDK 的环境 |
获取 API Key 的步骤:
hy4-demo),设置访问范围⚠️ 容易踩的第一个坑:TokenHub API Key 和腾讯云 CAM 的 SecretId/SecretKey 是两套不同的鉴权体系。混元 OpenAI 兼容接口需要的是 TokenHub API Key(形如
sk-xxxxxxxx),不是 CAM 密钥。用错会直接返回鉴权失败。
所有语言的接入本质都是替换这两个值。
参数 | 值 |
|---|---|
|
|
| TokenHub 控制台创建的 API Key |
完整的接口请求路径为 https://api.hunyuan.cloud.tencent.com/v1/chat/completions,与 OpenAI 的 Chat Completions 规范一致。
安装 SDK:
pip install openaifrom openai import OpenAI
client = OpenAI(
api_key="sk-你的TokenHubAPIKey",
base_url="https://api.hunyuan.cloud.tencent.com/v1",
)
response = client.chat.completions.create(
model="hy4",
messages=[
{"role": "system", "content": "你是一位严谨的技术助手,没有依据时请如实说明无法确认。"},
{"role": "user", "content": "请用三句话解释 MoE 架构的核心优势。"},
],
temperature=0.7,
)
print(response.choices[0].message.content)
print(f"输入 Token: {response.usage.prompt_tokens}")
print(f"输出 Token: {response.usage.completion_tokens}")长回答场景建议开启流式,避免用户长时间等待空白:
stream = client.chat.completions.create(
model="hy4",
messages=[{"role": "user", "content": "写一段快速排序的 Python 实现并解释思路。"}],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta
if delta.content:
print(delta.content, end="", flush=True)Hy4 正式版首次引入视觉能力,可处理图表解读、文档理解与多图分析:
response = client.chat.completions.create(
model="hy4",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "这张图表中销售额最高的季度是哪个?请给出数值。"},
{
"type": "image_url",
"image_url": {"url": "https://example.com/chart.png"},
},
],
}
],
)
print(response.choices[0].message.content)本地图片需转为 Base64 后传入:
import base64
def encode_image(path: str) -> str:
with open(path, "rb") as f:
return base64.b64encode(f.read()).decode("utf-8")
b64 = encode_image("./chart.png")
response = client.chat.completions.create(
model="hy4",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "请描述这张图的主要内容。"},
{
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{b64}"},
},
],
}
],
)
print(response.choices[0].message.content)tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询指定城市的实时天气",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称,如 深圳"},
},
"required": ["city"],
},
},
}
]
response = client.chat.completions.create(
model="hy4",
messages=[{"role": "user", "content": "深圳今天天气怎么样?"}],
tools=tools,
tool_choice="auto",
)
msg = response.choices[0].message
if msg.tool_calls:
for call in msg.tool_calls:
print("调用函数:", call.function.name)
print("参数:", call.function.arguments)npm install openaiimport OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.TOKENHUB_API_KEY,
baseURL: "https://api.hunyuan.cloud.tencent.com/v1",
});
async function main() {
const response = await client.chat.completions.create({
model: "hy4",
messages: [
{ role: "system", content: "你是一位严谨的技术助手。" },
{ role: "user", content: "用一段话说明长上下文的实际价值。" },
],
});
console.log(response.choices[0].message.content);
}
main();流式写法:
const stream = await client.chat.completions.create({
model: "hy4",
messages: [{ role: "user", content: "介绍一下 Computer Use 能力。" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || "");
}遇到问题时,先用 curl 排除 SDK 层面的干扰:
curl https://api.hunyuan.cloud.tencent.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-你的TokenHubAPIKey" \
-d '{
"model": "hy4",
"messages": [{"role": "user", "content": "你好"}]
}'能正常返回即说明密钥与网络均无问题,可回到 SDK 侧继续排查。
Hy4 的缓存命中价格为 0.3 元/百万 Token,仅为标准输入价(6 元)的 1/20。利用方式是保持请求前缀稳定:
# 推荐结构:稳定内容在前,变动内容在后
SYSTEM_PROMPT = """你是企业知识库助手。
【规则】回答必须基于下方资料,无依据时说明无法确认。
【资料】……(长期不变的知识片段)……"""
def ask(question: str):
return client.chat.completions.create(
model="hy4",
messages=[
{"role": "system", "content": SYSTEM_PROMPT}, # 固定前缀,可命中缓存
{"role": "user", "content": question}, # 仅此部分变化
],
)📌 优化要点固定的 System Prompt、工具定义、知识片段放在最前面 变动的用户问题放在最后 前缀越稳定、越长,缓存收益越明显 长文档问答、Agent 多轮调用是收益最大的两类场景
现象 | 可能原因 | 处理方式 |
|---|---|---|
鉴权失败 | 误用 CAM SecretId/SecretKey | 改用 TokenHub API Key |
鉴权失败 | Key 复制时带了空格或换行 | 重新复制,检查首尾字符 |
模型不存在 | model 名称拼写不符 | 在 TokenHub 模型广场确认准确调用名 |
请求超时 | 长上下文 + 非流式 | 开启 |
并发受限 | 超出账号并发额度 | 加入重试退避,或在控制台提升额度 |
图片无法识别 | URL 不可公网访问 | 改用 Base64 传入 |
建议在生产代码中加入指数退避重试:
import time
from openai import OpenAI, APIError
def call_with_retry(messages, max_retries=3):
for i in range(max_retries):
try:
return client.chat.completions.create(model="hy4", messages=messages)
except APIError:
if i == max_retries - 1:
raise
time.sleep(2 ** i)跑通调用只是第一步,上线前建议完成三项验证:
功能验证:从真实业务抽取 20~50 个代表性任务,比对输出质量。
可靠性验证:构造一批"答案不在材料中"的陷阱题,检查模型是否如实回答无法确认,而非编造。
成本验证:统计实际的输入/输出/缓存命中 Token 分布,据此测算真实月度成本,而非按理论单价估算。
🎁 发布期限时优惠即日起至 2026 年 12 月 31 日,腾讯云 TokenHub 按刊例价 5 折计费 11 月 4 日~11 月 15 日,WorkBuddy/CodeBuddy 提供一定额度免费使用 👉 前往腾讯云大模型 Token Plan 订阅购买 → cloud.tencent.com/act/pro/tokenplan
接入 Hy4 的核心只有两个参数:base_url 指向 https://api.hunyuan.cloud.tencent.com/v1,api_key 使用 TokenHub 控制台创建的密钥,原有 OpenAI SDK 代码即可直接复用,支持流式、多模态图片输入与 Function Calling。成本侧务必把稳定内容前置以利用 0.3 元/百万 Token 的缓存命中价。完成接入可前往腾讯云大模型 Token Plan 页面按需订阅,再用自身业务任务跑一轮回归验证。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。