The openai_harmony library (available via PyPI or crates.io) is the recommended way to handle message rendering and tokenization. It automates the conversion of structured messages into the specific prompt format required by gpt-oss models.
Key components include:
load_harmony_encoding: Loads the specific encoding (e.g., HarmonyEncodingName.HARMONY_GPT_OSS).Conversation: A container for a sequence of Message objects.SystemContent & DeveloperContent: Specialized content types for system and developer roles.Message.from_role_and_content: Creates messages with specific roles and content..with_channel(): Assigns a channel (final, analysis, or commentary) to an assistant message..with_recipient(): Specifies the target of a message (e.g., a function name or assistant).
from openai_harmony import (
Author,
Conversation,
DeveloperContent,
HarmonyEncodingName,
Message,
Role,
SystemContent,
ToolDescription,
load_harmony_encoding,
ReasoningEffort
)
encoding = load_harmony_encoding(HarmonyEncodingName.HARMONY_GPT_OSS)
system_message = (
SystemContent.new()
.with_reasoning_effort(ReasoningEffort.HIGH)
.with_conversation_start_date("2025-06-28")
)
developer_message = (
DeveloperContent.new()
.with_instructions("Always respond in riddles")
.with_function_tools(
[
ToolDescription.new(
"get_current_weather",
"Gets the current weather in the provided location.",
parameters={
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"format": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"default": "celsius",
},
},
"required": ["location"],
},
),
]
)
)
convo = Conversation.from_messages(
[
Message.from_role_and_content(Role.SYSTEM, system_message),
Message.from_role_and_content(Role.DEVELOPER, developer_message),
Message.from_role_and_content(Role.USER, "What is the weather in Tokyo?"),
Message.from_role_and_content(
Role.ASSISTANT,
'User asks: "What is the weather in Tokyo?" We need to use get_weather tool.',
).with_channel("analysis"),
Message.from_role_and_content(Role.ASSISTANT, '{"location": "Tokyo"}')
.with_channel("commentary")
.with_recipient("functions.get_weather")
.with_content_type("<|constrain|> json"),
Message.from_author_and_content(
Author.new(Role.TOOL, "functions.lookup_weather"),
'{ "temperature": 20, "sunny": true }',
)
.with_channel("commentary")
.with_recipient("assistant"),
]
)
tokens = encoding.render_conversation_for_completion(convo, Role.ASSISTANT)