Skip to main content

langgraph-harness

Per-node HARNESS parsing, injection and enforcement for LangGraph nodes.

A LangGraph graph is a set of plain callables. StateGraph.add_node accepts metadata, retry/cache policies, an input schema, error handlers and timeouts — but it has no notion of a per-node instruction document. create_react_agent has a single graph-level prompt (plus pre_model_hook / post_model_hook for global interception). So today the answer to "can each node's agent parse its own HARNESS?" is: not natively.

langgraph-harness adds that missing layer:

from langgraph_harness import Harness, harnessed, current_harness, harness_messages

PLANNER = Harness.from_text("""
- MUST: return a JSON object [require="steps"]
- MUST NOT: mention internal tool names [forbid=tool_]
- SHOULD: keep the plan under 200 words
""", name="planner")

@harnessed(PLANNER, validate=True)
def planner(state, config=None):
    messages = [*harness_messages(), *state["messages"]]
    response = llm.invoke(messages)
    return {"messages": [response]}

current_harness() inside the node returns that node's harness — not a global prompt, and not another node's document.

Why a node decorator (and not only an edge or a state field)?

Form What it can do Why it is not enough alone
Node decorator Binds the document to one node, exposes it inside the node, validates the output — (this is the primary form)
State field Carries the node→harness registry and violations across steps Every node still has to read it manually
Edge Routes to a repair/fallback node when rules fail An edge runs after the node; it cannot inject instructions into the node's LLM call

The package therefore ships all three, with the decorator as the entry point: @harnessed(...) binds and injects, HarnessState records, and harness_gate(...) routes.

Install

pip install langgraph-harness

On PyPI: https://pypi.org/project/langgraph-harness/.

Requires Python 3.10+ and langgraph>=1.0.

The HARNESS format

A harness is a small Markdown document. Only bullet lines that start with MUST, MUST NOT or SHOULD are parsed as rules:

# Planner harness

- MUST: return a JSON object [require="steps"]
- MUST NOT: mention internal tool names [forbid=tool_]
- SHOULD: keep the plan short
  • MUST / MUST NOT are enforced; SHOULD failures are warnings.
  • [require=REGEX] — the output must match the regex.
  • [forbid=REGEX] — the output must not match the regex.
  • Rules without an annotation are still injected into the prompt; they simply cannot be verified automatically.

Three forms

1. Node decorator (primary)

from langgraph_harness import harnessed, current_harness

@harnessed("harnesses/planner.md", validate=True)
def planner(state):
    harness = current_harness()          # this node's document
    ...

Options:

Option Default Meaning
validate False Check the node's returned text against require / forbid
on_violation "raise" "raise" → HarnessViolation; "record" → append to harness_violations
inject_messages False Prepend a SystemMessage with the harness to a copy of state["messages"]
name function name Node name used in errors

2. State

from typing import Annotated
from langgraph.graph.message import add_messages
from langgraph_harness import HarnessState

class State(HarnessState):
    messages: Annotated[list, add_messages]

HarnessState adds three optional channels: harness (node → raw text), harness_violations (violations of the latest attempt, cleared once a node complies) and harness_repair_count (how many repair attempts have run). Helpers: harness_of, violations_of, with_harness, repair_count_of, record_repair_attempt.

3. Edge gate

from langgraph.graph import END, START, StateGraph
from langgraph_harness import harness_gate

builder.add_conditional_edges(
    "planner",
    harness_gate(on_violation="repair", otherwise=END),
)

When state["harness_violations"] is non-empty the router returns "repair".

Without a bound, a repair node that keeps failing sends the graph back forever and ends in GraphRecursionError. Set max_retries to cap it:

@harnessed(PLANNER, validate=True, on_violation="record", count_repairs=True)
def planner(state): ...

builder.add_conditional_edges(
    "planner",
    harness_gate(on_violation="repair", max_retries=2, on_exhausted="give_up"),
)

count_repairs=True increments harness_repair_count on each violation; after max_retries attempts the router goes to on_exhausted instead of looping. A node that finally complies clears harness_violations, so the gate returns otherwise.

API at a glance

Harness.from_text(text, name=...)      # parse Markdown
Harness.from_file(path, name=...)      # parse a file
parse_harness(text, name=...)          # same, functional form
load_harness(str | Path | Harness)     # resolve any of the three

harnessed(harness, *, validate, on_violation, inject_messages, name)
current_harness()                      # inside a harnessed node
harness_messages() / harness_prompt()  # render to a SystemMessage / str

HarnessState                           # TypedDict mix-in
violations_of(state) / harness_of(state, node) / with_harness(state, node, text)
repair_count_of(state) / record_repair_attempt(state)

harness_gate(on_violation="repair", otherwise=END,
             max_retries=None, on_exhausted=END)

validate_output(text, harness) -> Report(violations, warnings)

How it works

@harnessed binds the parsed harness to a contextvars.ContextVar for the duration of the call and resets it in a finally block. Context variables are task-local, so concurrent nodes (sync or async) do not see each other's harness. The decorated wrapper also exposes __harness__, __harness_name__ and __harness_node__ for introspection.

Verification

pytest -q
# 26 passed

The integration tests build a real StateGraph with two nodes that each call current_harness() and assert they see only their own document, and a graph where a violating node is routed to a repair node by harness_gate.

Real-model demo

examples/real_llm_demo.py runs two nodes with conflicting harnesses and asserts that each node answers with its own word:

python examples/real_llm_demo.py --mock                  # deterministic, no key
OPENAI_API_KEY=...   python examples/real_llm_demo.py --provider openai
DEEPSEEK_API_KEY=... python examples/real_llm_demo.py --provider deepseek
GEMINI_API_KEY=...   python examples/real_llm_demo.py --provider gemini
OLLAMA_MODEL=qwen2.5:1.5b python examples/real_llm_demo.py --provider ollama

Publishing

  • .github/workflows/ci.yml runs the test suite on Python 3.10–3.13.
  • .github/workflows/publish.yml builds the sdist/wheel, runs twine check, and uploads to PyPI on a GitHub release. It works with a PYPI_API_TOKEN repository secret or with PyPI trusted publishing (no secret).

Locally:

python -m build
twine check dist/*
TWINE_USERNAME=__token__ TWINE_PASSWORD=pypi-... twine upload dist/*

Limitations

  • Regex checks are shallow: they prove a string contains (or avoids) a pattern, not that the model semantically followed the rule. Use the harness as a guardrail, not as a proof.
  • inject_messages=True prepends a SystemMessage to the node's copy of state["messages"]; the node owns the LLM call and should not echo that message back into state.
  • The package does not call an LLM. It parses, injects, validates and routes; the model invocation stays in your node.

License

MIT

Metadata

Release files for langgraph-harness 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for langgraph-harness 0.1.3
File Size Uploaded Provenance Actions
langgraph_harness-0.1.3.tar.gz 19.6 kB Without provenance Details for langgraph_harness-0.1.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for langgraph-harness 0.1.3
File Interpreter ABI Platform Actions
langgraph_harness-0.1.3-py3-none-any.whl Python 3 none any Details for langgraph_harness-0.1.3-py3-none-any.whl

Total release size: 36.2 kB

Release files / langgraph_harness-0.1.3.tar.gz

Download URL langgraph_harness-0.1.3.tar.gz
Size 19.6 kB
Tags Source
SHA-256 checksum
How to use checksums
4cf52dd82786ae699f8268000534804139fc45516c0746b27756366b73d132f1
BLAKE2b-256 checksum
How to use checksums
f99ca57b97eb25b22746b7a10b509a8bca7e64a2663eacbfeeba5b3a092f239a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.4

Release files / langgraph_harness-0.1.3-py3-none-any.whl

Download URL langgraph_harness-0.1.3-py3-none-any.whl
Size 16.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
657a8a654be9a07bd0368b5f2df01998229efc3b593ed2c87d670ca3261e2574
BLAKE2b-256 checksum
How to use checksums
9ccc8da91dd78eada0a8c7b869405e3a8c7f9a4c4cd624fcf70f6edab603771a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.4

Security for langgraph-harness 0.1.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page