Example

Parse role and channel boundaries without guessing

Turn four framed lines into structured messages, then feed the parser a malformed line and inspect the error record.

A protocol is a contract about boundaries: which bytes are a role, which are a channel, where content starts, and what happens when a line does not match. A model’s output is text; the serving layer turns that text into messages. If the parser silently drops a malformed line, the next turn runs with missing context.

This example parses a four-line sample into system/analysis, user/final, assistant/analysis and assistant/final messages. It uses a deliberately small [role|channel] content grammar, not the full Harmony format. The point is the shape of the parse result: a list of messages and a list of errors, both preserved. The page does not claim access to OpenAI’s serving internals; it tests a documented-style message boundary.

Run it

From the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch31/harmony.py --json

Python 3.11 or later, standard library only. No model, network, provider credentials or GPU. It finishes immediately.

Implementation

The parser strips each line, skips blanks, and matches a role made of letters and a channel made of letters or underscores. Anything else becomes an error string rather than disappearing. run_demo supplies one message per boundary.

def parse_harmony(text: str) -> ParseResult:
    # Simple parser for lines like: [role|channel] content
    messages: List[HarmonyMessage] = []
    errors: List[str] = []
    for line in text.splitlines():
        line = line.strip()
        if not line:
            continue
        match = re.match(r"^\[([a-zA-Z]+)\|([a-zA-Z_]+)\]\s*(.*)$", line)
        if not match:
            errors.append(f"unparsed: {line}")
            continue
        role, channel, content = match.groups()
        messages.append(HarmonyMessage(role=role, channel=channel, content=content))
    return ParseResult(messages=messages, errors=errors)

Expected outcome

Observed with the command above (exit 0):

{
  "messages": [
    {
      "role": "system",
      "channel": "analysis",
      "content": "You are helpful."
    },
    {
      "role": "user",
      "channel": "final",
      "content": "What is 2+2?"
    },
    {
      "role": "assistant",
      "channel": "analysis",
      "content": "Compute 2+2=4."
    },
    {
      "role": "assistant",
      "channel": "final",
      "content": "4"
    }
  ],
  "errors": []
}

The analysis and final channels are separate messages with the same assistant role. A consumer can choose to show only final while still retaining the analysis text. The parser reported no errors because every line matched the grammar.

Mechanism and limitations

Documented: parse_harmony returns a ParseResult with a message list and an error list. Each message has role, channel and content. A non-matching line is recorded as unparsed: .... The tests check a two-message parse, a malformed line, the demo, JSON serialisation and the empty input.

Observed: the command exited 0 with the four messages above and an empty error list. The targeted tests.test_ch31_harmony is part of the canonical suite; no independent test count is claimed here.

Not shown: the actual Harmony token grammar, special tokens, tool-call messages, streaming boundaries, or any provider’s internal parser. This regex is not a conforming implementation of a published format, and a line-oriented grammar cannot represent content that contains newlines. The errors list is the important safety property; it is not a recovery strategy.

Challenge this result

Feed the parser a line with a role containing a digit, a missing closing bracket, and an empty content field. Predict which lines become errors and which become messages with empty content. Then add content containing a newline and explain why the line-oriented parser splits it. Finally, state what a protocol implementation must do with an error: reject the request, repair the message, or preserve it for the caller. Those are different contracts.

Source and verification

Canonical source: examples/ch31/harmony.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch31_harmony.py . Chapter: Inference Protocols and Harmony . The run above is a fresh local execution on Windows 11 with Python 3.13.15; it parses a local sample and makes no provider claim.

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.