Skip to main content

What Is an AI Harness? Build a Minimal Python Example

Learn what an AI harness controls, how it differs from a model or framework, and how to build a small Python example with tool access, state, checks, and retries.

What Is An AI Harness & Build A Minimal One Yourself

Summarize this article with AI

Open a quick summary in your preferred AI assistant; for Gemini and Copilot, paste the copied prompt after opening.

Claude ChatGPT Gemini Perplexity Copilot Grok

KEY TAKEAWAYS:

  • An AI harness supplies the execution loop, context, tools, state, checks, and stop rules around a model. Together they form an AI agent.
  • A runtime harness operates the agent; an evaluation harness runs test cases and scores behavior. Frameworks may supply either set of building blocks.
  • Start with one read-only task, trusted identity, explicit state, bounded retries, and a clear escalation path.
  • The local Python example below uses a deterministic model stand-in. It demonstrates controls, not real-model answer quality.

An AI harness is the software around a language model that lets an agent work within a defined process. It manages context, tool execution, state, permissions, validation, retries, and stopping. Those controls help a product handle failure, but they do not make model output automatically correct. This guide explains the parts and builds a small harness for one policy question. The example uses fictional policy text and a local model stand-in. You can run its control flow without an API key, then replace the stand-in only after defining the production data and access boundary.

What Is an AI Harness?

An AI harness is the runtime and control layer that connects a model to its task and environment. The model proposes an answer or next action. The harness supplies allowed context, executes permitted tools, records state, checks results, and decides whether to continue or stop.

Microsoft’s agent harness documentation describes this runtime role. Birgitta Böckeler’s article on Martin Fowler’s site examines how context and feedback help people steer coding agents. The exact boundary varies by system; the term is not a single standard architecture.

Agent = model + harnessOuter system: AgentModel plus the surrounding harness and environmentCenter: ModelProposes answers or actions from the supplied contextHarness: allowed tool executionCheck identity and permissions before reading a sourceHarness: validation and stateRecord evidence; accept, retry once, or escalateHarness: stop rulesEnd on success, missing source, denial, or exhausted budget

The model is one component inside the agent. The surrounding controls make the proposed action reviewable and enforceable.

For more context, read:

AI harness components around a model, including instructions, tools, state, guardrails, feedback, and human review
The center is the model; the full agent includes the surrounding harness. The controls diagram above separates these responsibilities.

Model, Agent, Runtime Harness, and Evaluation Harness

These terms describe different responsibilities. They can appear in one product, and a framework can include a ready-made harness.

Term Responsibility Policy-assistant example
Model Generates a proposal from input context Drafts an answer from a policy passage
Agent Model plus harness working toward a task The complete policy assistant
Runtime harness Context, tool execution, state, limits and checks during the run Retrieves an allowed source and blocks unsupported output
Framework Reusable building blocks; may include an assembled harness Tool adapters, checkpointers, middleware or a complete loop
Evaluation harness Runs identified cases, captures evidence and applies scorers Tests missing sources, access denial, and retry exhaustion
Workspace or sandbox Files and resources available to execution, with isolation limits A temporary directory with no unrestricted shell or network access
Harness.io A separate software-delivery platform and brand Not the generic architecture term used in this guide

Harness.io is a named product. A generic AI harness does not require it. Likewise, agent frameworks are implementation choices rather than a fixed layer below every harness.

What the Harness Must Control

Design controls around a failure you can observe. A prompt states the intended behavior; application code must enforce permissions, budgets, and acceptance rules.

  • Task contract: Define the supported input, output, source rules, and escalation path.
  • Tool access: Allow only required functions and validate their arguments. Authenticate outside the model and authorize at the data service.
  • State: Record task status, source versions, tool results, attempts, and stop reason.
  • Context: Send only the evidence needed for the next call. Keep authoritative state outside generated summaries.
  • Validation: Use deterministic checks for schemas, permissions, and exact requirements. Use human or model judging for softer qualities with stated limits.
  • Lifecycle: Set maximum calls, retries, elapsed time, and spend. Stop on cancellation or an exhausted budget.

The OWASP LLM application risks help explain why source text and tool access need separate controls. A retrieved document is data, not permission to change the application’s rules.

Illustration of controls surrounding an AI workflow
Controls and traces can be consistent across runs even when model wording differs.

Workspace, Sandbox, and Context Budgets

A workspace holds files, task notes, and intermediate artifacts. A sandbox limits what execution can affect. Set allowed directories, read/write scope, network destinations, process permissions, CPU and memory limits, and cleanup rules in the execution environment.

The policy demo below needs no file writes, shell commands, or model tools beyond one read-only retrieval function. A deployed coding harness needs stronger isolation and explicit command controls. A prompt asking an agent to stay in one folder is not a sandbox.

As history grows, preserve source IDs, task status, unresolved questions, and verified results in structured state. Compact older conversation text within a token budget. Do not replace current permissions or authoritative evidence with a model-written summary.

Anthropic’s long-running agent engineering article illustrates how progress artifacts help later sessions continue work. Persisted state still needs access checks, retention rules, and a recovery owner.

Build a Minimal AI Harness in Python

The task is: answer “How do I request annual leave?” from the current policy visible to an authenticated employee. The assistant may quote the policy. It may not approve leave, change HR records, or invent an exception.

The flow is trusted identity → read-only retrieval → explicit state → draft → validation → one retry or escalation. Save the code as policy_harness.py and run python3 policy_harness.py. It uses only the Python standard library and fictional fixture data.

from dataclasses import dataclass, field
from time import monotonic

QUESTION = "How do I request annual leave?"
POLICY = {
    "id": "leave-policy",
    "version": "demo-v1",
    "group": "employees",
    "text": "Submit an annual-leave request to your manager in the HR portal.",
}


@dataclass(frozen=True)
class Identity:
    user_id: str
    groups: tuple


@dataclass
class RunState:
    status: str = "started"
    model_calls: int = 0
    trace: list = field(default_factory=list)


def retrieve_policy(identity, available):
    # Read-only fixture; production identity comes from server auth.
    if "employees" not in identity.groups:
        raise PermissionError("not authorized")
    return dict(POLICY) if available else None


def validate(draft, source):
    # An intentionally narrow, extractive contract for this demo.
    return (
        isinstance(draft, dict)
        and set(draft) == {"answer", "source_id", "version"}
        and draft["answer"] == source["text"]
        and draft["source_id"] == source["id"]
        and draft["version"] == source["version"]
    )


def run(question, identity, model, available=True):
    state = RunState()
    deadline = monotonic() + 5  # illustrative wall-time budget

    def stop(reason):
        state.status = "escalated"
        state.trace.append("escalate:" + reason)
        return {"status": state.status, "reason": reason,
                "answer": None, "trace": state.trace}

    state.trace.append("identity-attached")
    if question != QUESTION:
        return stop("unsupported-question")
    try:
        source = retrieve_policy(identity, available)
    except PermissionError:
        return stop("not-authorized")
    state.trace.append("read-only-retrieval")
    if not source:
        return stop("missing-source")
    state.trace.append("source:" + source["id"] + ":" + source["version"])

    for attempt in range(2):  # initial call plus one retry
        if monotonic() >= deadline:
            return stop("time-budget")
        state.model_calls += 1
        state.trace.append("model-call:" + str(state.model_calls))
        try:
            draft = model(question, dict(source), attempt)
        except Exception:
            return stop("model-error")
        if monotonic() >= deadline:
            return stop("time-budget")
        if validate(draft, source):
            state.status = "answered"
            state.trace.append("validated")
            return {"status": state.status, **draft, "trace": state.trace}
        state.trace.append("validation-failed")
    return stop("validation-limit")


def fixture_model(question, source, attempt):
    # Deterministic stand-in, not a language model call.
    return {"answer": source["text"],
            "source_id": source["id"], "version": source["version"]}


if __name__ == "__main__":
    employee = Identity("employee-demo", ("employees",))
    print(run(QUESTION, employee, fixture_model))
    print(run(QUESTION, employee, fixture_model, available=False))

Understand the Control Boundary

The local identity fixture stands in for a server-authenticated session. In a web product, derive identity and groups from that session. Never trust a group or user ID supplied by the model or copied from request text.

Retrieval enforces the employee group before returning a source. The model receives a copy of approved policy data. The state records tool use, source version, model-call count, validation, and stop reason.

The validator requires an exact quote and matching source ID and version. This deliberately narrow contract is easy to check. It is not a general method for judging a paraphrased answer’s truth. A real policy service must also verify document validity, effective date, access scope, and requested topic.

The loop allows at most two model calls. Missing sources and denied access stop before generation. Model errors escalate immediately. The five-second value is illustrative; the demo checks elapsed time around calls. Real adapters need request timeouts and cancellation because this check cannot interrupt a blocked call.

Inspect the Success and Missing-Source Traces

The local fixture was executed for both paths. These traces show deterministic control flow, not live language-model behavior.

SUCCESS
identity-attached → read-only-retrieval → source:leave-policy:demo-v1 → model-call:1 → validated
status: answered
source: leave-policy, demo-v1

MISSING SOURCE
identity-attached → read-only-retrieval → escalate:missing-source
status: escalated
answer: None

Additional local checks covered denied identity, an unsupported question, one validation retry followed by success, and two failed validations followed by escalation. Replacing the stand-in with a real model requires new tests for tool choice, source use, prompt injection, cost, and answer quality.

If the task only needs an exact policy quote, ordinary retrieval code may be enough. Add model-based decisions only when they improve a task that you can evaluate. For a framework-based tool loop, see building a LangChain agent.

Set Production Acceptance Rules Before Adding Autonomy

Define pass conditions and owners before a pilot. A fluent response cannot compensate for an access leak, repeated side effect, or missing source.

Requirement Acceptance check Evidence and owner
Access control Unauthorized records returned: zero Denied-user and cross-tenant tests; backend owner
Source-based answers Source-required cases cite the permitted current policy; missing evidence escalates Source IDs, versions and answer review; policy owner
Bounded execution Stops at call, time, token and cost limits; cancellation works Budget-exhaustion and timeout traces; runtime owner
Retry safety Retries do not repeat a side effect Idempotency and recovery tests before adding writes; service owner
Output quality Matches the team’s defined support and clarity rubric Independent human review or calibrated judge; product owner
Recovery and operations Run can resume or stop safely after a dependency failure Checkpoint, restore and escalation tests; operations owner

Use code checks for objective rules such as allowed IDs, schemas, and retry counts. Model judging can help review clarity or answer support, but it can make mistakes. Compare it with human labels and never let it replace the permission check.

Capture request and run IDs, configuration versions, selected sources, tool outcomes, validations, latency, usage, and stop reasons. Redact private fields and secrets. A trace should explain the execution without storing unnecessary personal data or hidden reasoning.

Human review is needed where the workflow requires judgment or approval. Show the proposed operation, arguments, evidence, and access context. Approval does not override a missing permission. A later write tool also needs idempotency and a defined recovery path.

To build on this, read:

Where Teams Use AI Harnesses

Harness design is useful when a model interacts with private context, several tools, or a process with explicit completion rules. The controls differ by workflow.

Coding and DevOps Assistance

A coding harness supplies repository context, permitted files, test commands, and review gates. A DevOps agent harness can gather approved logs and draft a diagnosis. Production changes still require service permissions and deployment controls. Keep investigation tools separate from consequential actions.

Document and Support Work

A policy assistant needs permitted, current documents and a clear no-answer path. A support workflow may add a read-only account lookup and a human handoff. Chatbot integration then becomes a data-access and workflow design task, as well as a model connection.

Multi-Step Operations

Teams designing agent harnesses may combine classification, retrieval, a draft ticket, and review. Record each step and protect repeated operations. Do not grant write access simply because a read-only pilot was successful.

AI harness use cases in coding, document work, and operations
Use-case illustration. Each workflow needs its own tools, permissions, and acceptance checks.

Move From a Demo to an Owned Product

AI harness engineering needs owners for source quality, tool permissions, runtime limits, evaluation, and incidents. Start with one workflow and keep a small regression set of real failure cases. Re-run it after changing models, prompts, retrieval, or tools.

Use agent governance to assign those responsibilities and define review thresholds. Keep controls and traces consistent across runs; do not promise identical model outputs.

Designveloper’s AI development services can support the application and integration work around a bounded workflow. Begin with its data boundary, pass conditions, escalation route, and operating owner.

Moving a minimal AI harness into an operated business workflow
Production adoption adds authenticated services, monitoring, recovery, and named ownership.

FAQs About AI Harnesses

Is a Harness the Same as a Prompt?

No. A prompt supplies instructions. A harness also executes tools, holds state, enforces limits, checks results, and handles failures. A prompt cannot grant or enforce server-side permissions.

Does Every Agent Need a Custom Harness?

No. An existing framework or agent product may supply much of the harness. Assess its controls and extension points against your workflow before building another layer.

How Is an Evaluation Harness Different?

A runtime harness operates an agent on a task. An evaluation harness runs defined cases and captures results for scoring and comparison. They can share code, but evaluating a case and serving a user have different responsibilities.

Can a Harness Guarantee Correct Answers?

No. It can enforce specific boundaries and make failures observable. Retrieval, model behavior, and validators can still fail. Test the full system with independent expected outcomes and keep a human path for unresolved cases.

Can I Build One Without a Framework?

Yes. The local example uses a function, explicit state, one retrieval tool, a validator, and bounded retry logic. Its simplicity makes the controls visible. Production adapters still need authentication, timeouts, persistence, and monitoring.

Start with one read-only workflow, inspect its failure traces, and name an owner for every control before adding actions. A small, testable boundary is easier to operate as real data and integrations change.

Read more

View all posts

Got an idea? Let's build together.

Let's turn your idea into AI-powered software, intelligent workflows, or digital products that help your business scale.

AI estimation

Drop your idea. AI will give you a raw estimation to help you plan your next move. Learn more

What are you looking to build?
Attach supporting files (optional)

PDF, DOCX, TXT, Markdown, JSON, CSV, XLSX · Up to 3 files, 10 MB each

or