Registry / llm-agents / openai-harmony

openai-harmony

JSON →
library0.0.8pypypi✓ verified 24d ago

OpenAI Harmony is a Python library providing a renderer for OpenAI's 'Harmony' response format, specifically designed for its open-weight model series, gpt-oss. It enables structured conversations, reasoning output, and function calls, mimicking the OpenAI Responses API. The library, with a Rust core and Python bindings, ensures consistent formatting, efficient processing, and first-class Python support, including typed stubs. It is crucial for developers building inference solutions for gpt-oss models, as these models are trained on and require the Harmony format for correct operation.

pip install openai-harmony
INSTALL
IMPORT
SIG · OPENAI-HARMONY
O
openai-harmony
llm-agentspythonv0.0.8
Install
3.4s avg
Import
393ms
Disk
34MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.0.8 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.416s · 35.8MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 3.4s · import 0.370s · 35MB
34MB installed
● package 34MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

load_harmony_encoding
from openai_harmony import load_harmony_encoding
HarmonyEncodingName
from openai_harmony import HarmonyEncodingName
Role
from openai_harmony import Role
Message
from openai_harmony import Message
Conversation
from openai_harmony import Conversation
DeveloperContent
from openai_harmony import DeveloperContent
SystemContent
from openai_harmony import SystemContent

This quickstart demonstrates how to load the Harmony encoding, construct a conversation using various roles, render it into the token format expected by gpt-oss models, and then parse a simulated model's completion back into structured messages.

from openai_harmony import ( load_harmony_encoding, HarmonyEncodingName, Role, Message, Conversation, DeveloperContent, SystemContent, ) # Load the Harmony encoding for GPT-OSS models enc = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS) # Create a conversation with system, developer instructions, and a user message 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?"), ]) # Render the conversation into tokens for completion. This generates the prompt. tokens_for_model = enc.render_conversation_for_completion(convo, Role.ASSISTANT) print("Prompt Tokens (to send to model):", tokens_for_model) # --- Simulate a model response --- # In a real scenario, `tokens_for_model` would be sent to a gpt-oss model, # and the model would generate a continuation. For this quickstart, we'll # append a sample assistant response to the prompt tokens. model_raw_completion = tokens_for_model + "<|start|>assistant<|message|>Ahoy there, matey! I be shipshape and Bristol fashion. <|end|>" # Parse the model's raw completion back into structured messages parsed_messages = enc.parse_messages_from_completion_tokens(model_raw_completion, role=Role.ASSISTANT) print("\nParsed Messages (including original prompt and simulated response):") for msg in parsed_messages: # Accessing content might depend on the content type (e.g., TextContent, DeveloperContent) content_value = msg.content.text if hasattr(msg.content, 'text') else str(msg.content) print(f"Role: {msg.role.name}, Content: {content_value}")
Debug
Known issues
breakingThe `openai-harmony` format is mandatory for OpenAI's gpt-oss series models. These models were specifically trained on this format and will not function correctly or reliably if it is not used.
fix
Always use the `openai-harmony` library to construct and parse prompts and completions when working with gpt-oss models. Do not manually construct the prompt strings.
affects: All versions with gpt-oss models
gotchaThe 'analysis' channel, used by gpt-oss models for internal chain-of-thought reasoning, is not safety-filtered. Content from this channel should *never* be shown directly to end-users as it may contain harmful or unrefined outputs.
fix
Ensure your application logic explicitly filters and only displays messages from the 'final' or 'commentary' channels to end-users, or apply strict content moderation to any 'analysis' channel output if it must be used for debugging.
affects: All versions
gotchaCommon mistakes include incorrect role mapping (e.g., mapping 'system' to `Role.DEVELOPER`) or missing essential imports (`SystemContent`, `Message`, etc.) when constructing Harmony templates, leading to runtime errors or unexpected model behavior.
fix
Refer to the official documentation and quickstart examples to ensure correct import paths and proper usage of `Role` and content types when building conversations.
affects: All versions
breakingWhen using Harmony-based GPT-5 models, some users have reported receiving malformed JSON outputs (concatenation of multiple JSONs) when interacting with OpenAI SDK versions >= 1.100.2, particularly when using `client.beta.chat.completions.parse` with `response_format`.
fix
Monitor for updates from OpenAI regarding this specific issue. If encountering this, consider using an older, compatible version of the OpenAI SDK or carefully handling the raw response to attempt manual parsing if absolutely necessary, while awaiting a fix.
affects: SDK versions >= 1.100.2 (when interacting with GPT-5 models)
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'openai_harmony'
The 'openai-harmony' Python package has not been installed or is not accessible in the current Python environment.
fix
Install the library using pip: `pip install openai-harmony`
openai_harmony.HarmonyError: error downloading or loading vocab file
The underlying 'tiktoken-rs' dependency, used by openai-harmony for tokenization, cannot download or locate the necessary vocabulary files, often due to network restrictions in air-gapped environments or incorrect cache directory settings.
fix
Manually download the required 'tiktoken' vocabulary file (its hash might be `fb374d419588a4632f3f557e76b4b70aebbca790`) and set the `TIKTOKEN_RS_CACHE_DIR` environment variable to the directory where the file is stored before loading the encoding.
RuntimeError: rendering or parsing failures
The input conversation or the model's generated output does not conform to the strict OpenAI Harmony format (e.g., incorrect JSON structure, missing required channels, or invalid role mappings), which the library is designed to render and parse.
fix
Ensure all conversation components (messages, roles, and content) are constructed using the `openai_harmony` classes (e.g., `Message`, `Conversation`, `SystemContent`, `DeveloperContent`) and adhere to the specified Harmony format structure and channel requirements.
AttributeError: 'list' object has no attribute 'shape' (or similar errors when passing Harmony tokens to model.generate)
The `render_conversation_for_completion` method of `openai-harmony` returns a Python list of token IDs, which needs to be converted into a tensor (e.g., `torch.tensor`) before being passed as `input_ids` to a `transformers` model's `generate` method.
fix
Convert the list of token IDs to an appropriate tensor format, usually by wrapping it in a list to create a batch and then converting to a PyTorch or TensorFlow tensor: `outputs = model.generate(input_ids=torch.tensor([prefill_ids]), max_new_tokens=2000)`
Upgrade
Version history
0.0.8latest on PyPI · released Nov 5, 2025
Audit
Dependencies

No dependency data recorded yet.

Agent activity
46 hits · last 30 days
node
42
OpenAI (training)
1
Resources
openai-harmony — pip install openai-harmony · libregistry