OpenAI 为开源模型系列统一定义了 Harmony 响应格式,这是一套标准化的 API 接口规范,便于开发者集成和使用多个模型。
OpenAI 为其开放权重模型系列 gpt-oss 设计的响应格式。试用 gpt-oss|了解更多|Model card
gpt-oss 模型使用 harmony 响应格式进行训练。该格式用于定义对话结构、生成推理输出,以及组织函数调用。如果你不是直接使用 gpt-oss,而是通过 API 或 HuggingFace、Ollama、vLLM 等提供商使用,就无需操心这些内容,因为你的推理解决方案会自动处理格式。如果你正在构建自己的推理解决方案,本指南将带你了解 prompt 格式。该格式旨在模拟 OpenAI Responses API,因此如果你以前用过这个 API,应该会对它感到熟悉。使用 gpt-oss 时必须采用 harmony 格式,否则模型将无法正常工作。
该格式允许模型通过多个不同的 channel 输出思维链、工具调用前言和常规响应。它还支持指定不同的工具 namespace、生成结构化输出,并提供清晰的指令层级。请查看指南,进一步了解该格式本身。
<|start|>system<|message|>You are ChatGPT, a large language model trained by OpenAI.
Knowledge cutoff: 2024-06
Current date: 2025-06-28
Reasoning: high
# Valid channels: analysis, commentary, final. Channel must be included for every message.
Calls to these tools must go to the commentary channel: 'functions'.<|end|>
<|start|>developer<|message|># Instructions
Always respond in riddles
# Tools
## functions
namespace functions {
// Gets the location of the user.
type get_location = () => any;
// Gets the current weather in the provided location.
type get_current_weather = (_: {
// The city and state, e.g. San Francisco, CA
location: string,
format?: "celsius" | "fahrenheit", // default: celsius
}) => any;
} // namespace functions<|end|><|start|>user<|message|>What is the weather like in SF?<|end|><|start|>assistant
在使用采用 harmony 响应格式的模型时,我们推荐使用这个库。
格式一致——渲染与解析共享同一套实现,确保 token 序列无损转换。
速度极快——繁重的处理工作由 Rust 完成。
一流的 Python 支持——可通过 pip 安装,内置类型存根,并与 Rust 测试套件实现 100% 的测试一致性。
查看完整文档。
运行以下命令,从 PyPI 安装该软件包:
pip install openai-harmony
# or if you are using uv
uv pip install openai-harmony
from openai_harmony import (
load_harmony_encoding,
HarmonyEncodingName,
Role,
Message,
Conversation,
DeveloperContent,
SystemContent,
)
enc = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
convo = Conversation.from_messages([
Message.from_role_and_content(
Role.SYSTEM,
SystemContent.new(),
),
Message.from_role_and_content(
Role.DEVELOPER,
DeveloperContent.new().with_instructions("Talk like a pirate!")
),
Message.from_role_and_content(Role.USER, "Arrr, how be you?"),
])
tokens = enc.render_conversation_for_completion(convo, Role.ASSISTANT)
print(tokens)
# Later, after the model responded …
parsed = enc.parse_messages_from_completion_tokens(tokens, role=Role.ASSISTANT)
print(parsed)
查看完整文档。
将依赖项添加到你的 Cargo.toml:
[dependencies]
openai-harmony = { git = "https://github.com/openai/harmony" }
use openai_harmony::chat::{Message, Role, Conversation};
use openai_harmony::{HarmonyEncodingName, load_harmony_encoding};
fn main() -> anyhow::Result<()> {
let enc = load_harmony_encoding(HarmonyEncodingName::HarmonyGptOss)?;
let convo =
Conversation::from_messages([Message::from_role_and_content(Role::User, "Hello there!")]);
let tokens = enc.render_conversation_for_completion(&convo, Role::Assistant, None)?;
println!("{:?}", tokens);
Ok(())
}
为了获得更好的性能,大部分渲染与解析功能都使用 Rust 构建,并通过轻量的 pyo3 binding 暴露给 Python。
┌──────────────────┐ ┌───────────────────────────┐
│ Python code │ │ Rust core (this repo) │
│ (dataclasses, │────► │ • chat / encoding logic │
│ convenience) │ │ • tokeniser (tiktoken) │
└──────────────────┘ FFI └───────────────────────────┘
.
├── src/ # Rust crate
│ ├── chat.rs # High-level data-structures (Role, Message, …)
│ ├── encoding.rs # Rendering & parsing implementation
│ ├── registry.rs # Built-in encodings
│ ├── tests.rs # Canonical Rust test-suite
│ └── py_module.rs # PyO3 bindings ⇒ compiled as openai_harmony.*.so
│
├── python/openai_harmony/ # Pure-Python wrapper around the binding
│ └── __init__.py # Dataclasses + helper API mirroring chat.rs
│
├── tests/ # Python test-suite (1-to-1 port of tests.rs)
├── Cargo.toml # Rust package manifest
├── pyproject.toml # Python build configuration for maturin
└── README.md # You are here 🖖
Rust 工具链(stable)——https://rustup.rs
Python ≥ 3.8,以及 virtualenv/venv
maturin——PyO3 项目的构建工具
git clone https://github.com/openai/harmony.git
cd harmony
# Create & activate a virtualenv
python -m venv .venv
source .venv/bin/activate
# Install maturin and test dependencies
pip install maturin pytest mypy ruff # tailor to your workflow
# Compile the Rust crate *and* install the Python package in editable mode
maturin develop --release
maturin develop 会使用 Cargo 构建 harmony,生成原生扩展(openai_harmony.<abi>.so),并将其放入 virtualenv 中纯 Python wrapper 的旁边——这类似于在纯 Python 项目中运行 pip install -e .。
cargo test # runs src/tests.rs
pytest # executes tests/ (mirrors the Rust suite)
一次运行两者,以确保测试结果保持一致:
pytest && cargo test
mypy harmony # static type analysis
ruff check . # linting
cargo fmt --all # Rust formatter