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

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 two optional channels: harness (node → raw text) and harness_violations (recorded failures). Helpers: harness_of, violations_of, with_harness.

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".

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)

harness_gate(on_violation="repair", otherwise=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
python examples/real_llm_demo.py --provider ollama       # local 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.1

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.1
File Size Uploaded Provenance Actions
langgraph_harness-0.1.1.tar.gz 17.2 kB Without provenance Details for langgraph_harness-0.1.1.tar.gz

Built distribution (wheel)

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

Total release size: 32.1 kB

Release files / langgraph_harness-0.1.1.tar.gz

Download URL langgraph_harness-0.1.1.tar.gz
Size 17.2 kB
Tags Source
SHA-256 checksum
How to use checksums
6ac4e4767f5baac15cd850d68a5b15c005ec2ad06b8bb3e3643e27d245a08225
BLAKE2b-256 checksum
How to use checksums
63e50dd4cbdcb856dfeb708ebd7593a8972a224a104c8fe06815bca3837322ac
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.1-py3-none-any.whl

Download URL langgraph_harness-0.1.1-py3-none-any.whl
Size 14.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
588b9c5829adc9c98ccd8fda6a59a90904a4ebd32db19fd86a3312474381073f
BLAKE2b-256 checksum
How to use checksums
e4d503b822d60aacd4865cb0ea2e74ff7c99778bf475e9e1bba42b8294a1e6c2
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.1

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