Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# 腾讯混元 Hy3 API 配置
# 复制此文件为 .env 并填入你的 API Key

# TokenHub API Key(获取地址:https://console.cloud.tencent.com/tokenhub/apikey)
HY3_API_KEY=your_api_key_here

# TokenHub Base URL(OpenAI 兼容接口)
HY3_BASE_URL=https://tokenhub.tencentmaas.com/v1

# 模型名称: hy3-preview(推荐,256K上下文)或 hy3
HY3_MODEL=hy3-preview
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@
Thumbs.db
__pycache__/
*.pyc
.env
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
- [vLLM](#vllm)
- [SGLang](#sglang)
- [Finetuning](#finetuning)
- [RL Post-training](#rl-post-training)
- [Quantization](#quantization)
- [License](#license)
- [Contact Us](#contact-us)
Expand Down Expand Up @@ -205,6 +206,10 @@ python3 -m sglang.launch_server \

Hy3 provides a complete model finetuning pipeline. For detailed documentation, please refer to: [Finetuning Guide](./finetune/README.md)

## RL Post-training

Hy3 supports GRPO reinforcement learning training with [verl](https://github.com/volcengine/verl), training on Megatron-LM (model conversion via NVIDIA Megatron-Bridge) with vLLM rollout. For detailed documentation, please refer to: [RL Training Guide](./rl/README.md)

## Quantization

We provide [AngelSlim](https://github.com/tencent/AngelSlim), a more accessible, comprehensive, and efficient toolkit for large model compression. AngelSlim supports a comprehensive suite of compression tools for large-scale multimodal models, including common quantization algorithms, low-bit quantization, and speculative sampling.
Expand Down
5 changes: 5 additions & 0 deletions README_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
- [vLLM](#使用-vllm-推理)
- [SGLang](#使用-sglang-推理)
- [模型微调](#模型微调)
- [强化学习训练](#强化学习训练)
- [量化工具](#量化工具)
- [许可证](#许可证)
- [联系我们](#联系我们)
Expand Down Expand Up @@ -205,6 +206,10 @@ python3 -m sglang.launch_server \

Hy3 提供了完整的模型微调流程,详细的微调文档请参考:[模型微调指南](./finetune/README_CN.md)

## 强化学习训练

Hy3 支持基于 [verl](https://github.com/volcengine/verl) 的 GRPO 强化学习训练,训练侧使用 Megatron-LM(通过 NVIDIA Megatron-Bridge 完成模型转换),rollout 侧使用 vLLM。详细文档请参考:[强化学习训练指南](./rl/README_CN.md)

## 量化工具

我们提供了 [AngelSlim](https://github.com/tencent/AngelSlim)——一套易用、全面、高效的大模型压缩工具包,涵盖常用量化算法、低比特量化和投机采样等能力。
Expand Down
111 changes: 111 additions & 0 deletions api_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
"""
腾讯混元 Hy3 API 调用示例
使用 OpenAI 兼容接口,支持普通对话、深度推理、Function Calling 等模式。
"""
import os
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()

client = OpenAI(
api_key=os.getenv("HY3_API_KEY"),
base_url=os.getenv("HY3_BASE_URL", "https://tokenhub.tencentmaas.com/v1"),
)

MODEL = os.getenv("HY3_MODEL", "hy3-preview")


def chat(prompt: str, reasoning_effort: str = "no_think") -> str:
"""
普通对话 / 深度推理

Args:
prompt: 用户输入
reasoning_effort: "no_think" (直接回复), "low", "high" (深度思维链)
"""
response = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}],
temperature=0.9,
top_p=1.0,
extra_body={"chat_template_kwargs": {"reasoning_effort": reasoning_effort}},
)
return response.choices[0].message.content


def chat_stream(prompt: str, reasoning_effort: str = "no_think"):
"""流式对话(逐字输出)"""
stream = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}],
temperature=0.9,
top_p=1.0,
stream=True,
extra_body={"chat_template_kwargs": {"reasoning_effort": reasoning_effort}},
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()


def chat_with_tools(prompt: str, tools: list[dict]) -> dict:
"""带 Function Calling 的对话"""
messages = [{"role": "user", "content": prompt}]
response = client.chat.completions.create(
model=MODEL,
messages=messages,
tools=tools,
temperature=0.9,
top_p=1.0,
)
return response.choices[0].message


# ─── 使用示例 ─────────────────────────────────────────────

if __name__ == "__main__":
# 1. 普通对话(无推理)
print("=" * 60)
print("【普通对话】")
print("=" * 60)
result = chat("你好!请用一句话介绍你自己。")
print(result)
print()

# 2. 深度推理(复杂任务)
print("=" * 60)
print("【深度推理 - 数学题】")
print("=" * 60)
result = chat(
"设 f(x) = x³ - 6x² + 11x - 6,求 f(x) 在区间 [0, 4] 上的最大值和最小值。",
reasoning_effort="high",
)
print(result)
print()

# 3. Function Calling 示例
print("=" * 60)
print("【Function Calling - 获取天气】")
print("=" * 60)
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称"},
},
"required": ["city"],
},
},
}
]
msg = chat_with_tools("北京今天天气怎么样?", tools)
print(f"tool_calls: {msg.tool_calls}")
print()
print("所有示例运行完成!")
Binary file added assets/rl-training.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 14 additions & 0 deletions issue1/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Hy3 API Quickstart 配置
# 复制此文件为 .env 并填入你的 API Key
#
# 获取 API Key: https://console.cloud.tencent.com/tokenhub/apikey
# 新用户可领取 100 万 Tokens 免费额度(90 天有效)

# TokenHub API Key(必填)
HY3_API_KEY=your_api_key_here

# TokenHub Base URL(OpenAI 兼容接口)
HY3_BASE_URL=https://tokenhub.tencentmaas.com/v1

# 模型名称: hy3-preview(推荐,256K 上下文)或 hy3
HY3_MODEL=hy3-preview
96 changes: 96 additions & 0 deletions issue1/examples/basic_chat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Basic Chat — 单轮与多轮对话

演示 Hy3 API 的基础对话能力,包含单轮问答和多轮上下文对话。多轮对话通过将历史的 assistant 回复加入 `messages` 列表来实现上下文传递。

## 运行

```bash
cd issue1
python examples/basic_chat.py
```

## 请求结构

### 单轮对话

```python
{
"model": "hy3-preview",
"messages": [
{"role": "user", "content": "请用一句话介绍腾讯混元 Hy3 模型。"}
],
"temperature": 0.9,
"top_p": 1.0,
"max_tokens": 128
}
```

### 多轮对话

多轮对话的核心在于保留 `messages` 中的历史对话,让模型能够理解上下文:

```python
{
"model": "hy3-preview",
"messages": [
{"role": "user", "content": "请用一句话介绍腾讯混元 Hy3 模型。"},
{"role": "assistant", "content": "Hy3 是腾讯混元团队研发的..."},
{"role": "user", "content": "那么它在代码生成方面有什么优势?请列出 3 点。"}
],
"temperature": 0.7,
"top_p": 1.0,
"max_tokens": 256
}
```

> **关键设计**:OpenAI Chat Completions API 是无状态的。每次请求都必须携带完整的对话历史,模型不会「记住」之前的任何交互。

## 响应解析

```python
response = client.chat.completions.create(**params)
choice = response.choices[0]

# 关键字段提取
message_id = response.id # 本次请求的唯一 ID
model_name = response.model # 实际使用的模型名
finish_reason = choice.finish_reason # stop / length / content_filter
content = choice.message.content # 模型回复正文
token_usage = response.usage # {prompt_tokens, completion_tokens, total_tokens}
```

### finish_reason 含义

| 值 | 含义 |
|:---|:---|
| `stop` | 正常结束,模型自然完成或命中 stop 序列 |
| `length` | 达到 max_tokens 上限被截断 |
| `content_filter` | 内容被安全过滤 |

## 示例输出

以下为实际调用 TokenHub `hy3-preview` 的输出:

```
=== 单轮对话 ===
模型: hy3-preview
完成原因: stop
回复: 腾讯混元 Hy3 是腾讯自研的 295B 参数混合专家大模型,以 21B 激活参数实现高效推理,在代码、数学、长文本等任务上表现优异。
Token 用量: {'prompt_tokens': 12, 'completion_tokens': 41, 'total_tokens': 53}

=== 多轮对话 ===
模型: hy3-preview
完成原因: stop
回复: Hy3 在代码生成方面具有以下优势:

1. **多语言覆盖**:支持 Python、Java、C++、Go、TypeScript 等主流语言,代码风格规范统一。
2. **上下文理解**:256K 的长上下文窗口使其能理解整个项目结构,生成与现有代码库风格一致的代码。
3. **推理驱动生成**:在复杂算法和架构设计任务中,可通过深度思考模式先分析再编码,减少逻辑错误。
Token 用量: {'prompt_tokens': 65, 'completion_tokens': 116, 'total_tokens': 181}
```

## 关键要点

1. **温度参数**:单轮开放对话推荐 `0.9`,多轮收紧至 `0.7` 以保持回答一致性
2. **Token 计数**:多轮对话的 `prompt_tokens` 随历史增长,需注意上下文预算
3. **历史管理**:生产环境中应实现滑动窗口或摘要机制,避免 messages 过长
100 changes: 100 additions & 0 deletions issue1/examples/basic_chat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""
Hy3 基础对话示例:单轮对话与多轮对话。

使用方式:
cd issue1
python examples/basic_chat.py

前置条件:
1. 复制 .env.example 为 .env 并填入 HY3_API_KEY
2. pip install "openai>=1.0.0" python-dotenv
"""

import os
import sys
from pathlib import Path

# 将 issue1 目录加入路径,以便加载根目录的 .env
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from openai import OpenAI
from dotenv import load_dotenv

load_dotenv(Path(__file__).resolve().parents[1] / ".env")

# ── 配置 ─────────────────────────────────────────────
BASE_URL = os.getenv("HY3_BASE_URL", "https://tokenhub.tencentmaas.com/v1")
API_KEY = os.getenv("HY3_API_KEY", "")
MODEL = os.getenv("HY3_MODEL", "hy3-preview")

client = OpenAI(base_url=BASE_URL, api_key=API_KEY)


def chat(messages: list[dict], **kwargs) -> dict:
"""发送请求并返回解析后的关键字段。"""
params = {
"model": MODEL,
"messages": messages,
"temperature": kwargs.get("temperature", 0.9),
"top_p": kwargs.get("top_p", 1.0),
"max_tokens": kwargs.get("max_tokens", 256),
}
response = client.chat.completions.create(**params)
choice = response.choices[0]
return {
"id": response.id,
"model": response.model,
"finish_reason": choice.finish_reason,
"content": choice.message.content,
"usage": {
"prompt_tokens": response.usage.prompt_tokens if response.usage else 0,
"completion_tokens": response.usage.completion_tokens if response.usage else 0,
"total_tokens": response.usage.total_tokens if response.usage else 0,
},
}


def main():
print("=" * 60)
print("【示例 1】单轮对话")
print("=" * 60)

single_messages = [
{"role": "user", "content": "请用一句话介绍腾讯混元 Hy3 模型。"}
]
print(f"\n请求 messages:\n{single_messages}\n")

result = chat(single_messages, temperature=0.9, max_tokens=128)
print(f"模型: {result['model']}")
print(f"完成原因: {result['finish_reason']}")
print(f"回复: {result['content']}")
print(f"Token 用量: {result['usage']}")

# ── 多轮对话 ─────────────────────────────────────
print("\n" + "=" * 60)
print("【示例 2】多轮对话")
print("=" * 60)

multi_messages = [
{"role": "user", "content": "请用一句话介绍腾讯混元 Hy3 模型。"},
{"role": "assistant", "content": result["content"]},
{
"role": "user",
"content": "那么它在代码生成方面有什么优势?请列出 3 点。",
},
]
print(f"\n请求 messages(含历史上下文):\n{multi_messages[:2]}") # 只展示前两条
print(f"... (共 {len(multi_messages)} 条消息)\n")

result2 = chat(multi_messages, temperature=0.7, max_tokens=256)
print(f"模型: {result2['model']}")
print(f"完成原因: {result2['finish_reason']}")
print(f"回复: {result2['content']}")
print(f"Token 用量: {result2['usage']}")

print("\n✅ basic_chat 示例运行完成!")


if __name__ == "__main__":
main()
Loading