Agent loop
The agent-loop layer is where a model chooses the next tool or step; the kit uses the native PydanticAI Agent for the loop and wraps it in a Harness for governed runs.
Think of an agent as a worker who can choose the next step instead of following a fixed checklist. Given a request, the model may read another record, ask the person a question or finish the answer. The kit uses the native pydantic_ai.Agent for that reasoning loop. Its Harness surrounds one run with the rules the model must not decide for itself: tool visibility, approvals, limits, verified outcomes and resume. The loop chooses work; the host governs it.
Keep the two apart when you read the rest of this page. The model-driven part is the native agent, where a model picks each tool call. The Harness is deterministic runtime glue. It never reasons, never picks a tool and never rewrites model output.
Where the boundary is
Keep two roles distinct: the reasoning loop proposes the next step; the host controls which steps are permitted and how outcomes are recorded.
| This layer owns | This layer does not own |
|---|---|
| Which native agent runs, and the limits on a run (requests, tool calls, time) | The model clients and credentials (model route) |
Wrapping a native agent in a governed run: run, resume, wake, approve, cancel | The tool definitions and approval rules (tools and permissions) |
| Adapters for other agent SDKs that expose the same session shape | Where run state and history are stored (harness state) |
| Catalog loops for cases the native path does not cover | Retrieval, memory and context assembly (context and memory) |
Owners and tiers
| Import path | Tier | What it is for | Model-driven? |
|---|---|---|---|
pydantic_ai.Agent | golden-path owner | The loop. Calls tools, retries and produces output. | Yes. The model chooses each step. |
recohut_kit_pydantic_ai.harness.pydantic_ai.Harness | golden-path owner | One governed run of a native agent: scoped admission, tool policy, approvals, limits, verification, resume. | No. Wraps the native loop. |
recohut_kit_pydantic_ai.integrations.pydantic_ai.lifecycle.codex_responses_model | golden-path owner | The native model on the Codex route, with receipts. | No. A model binding. |
recohut_kit_strands.harness.strands.Harness | catalog | The same session shape around a native Strands agent. Needs a factory that builds a fresh agent per segment. | Yes, in the Strands loop. |
recohut_kit_openai_agents.harness.openai_agents.Harness | catalog | The same shape around an OpenAI Agents SDK agent. Static instructions and function tools only. | Yes, in the SDK loop. |
recohut_kit_bedrock_agents | catalog | Governed adapters for Amazon Bedrock Agents (managed, inline, multi-agent). The loop runs inside the AWS service. | Yes, in the service. |
recohut_kit.bounded_agents.BoundedLoop | catalog | A model proposes the next action. Immutable host contracts, durable approvals, budgets and deadlines decide if it may run. | Yes, as proposals. |
recohut_kit.integrations.function_calling_services.FunctionCallingLoop | catalog | A domain-free native tool-call loop with step, tool-call and token bounds. | Yes |
recohut_kit.integrations.graph_agent.AgentLoop | catalog | A GraphRAG tool loop over Codex function calls. Its default contract text is domain specific. | Yes |
recohut_kit.react_text | catalog | The pieces of a text-format ReAct loop: parser, prompt, argument coercion, scratchpad. It is not a loop. | No |
recohut_kit.integrations.react_runtime | catalog | An executor that runs a text ReAct loop with traces and stopping rules. | Yes |
recohut_kit.integrations.langgraph_agents | catalog | LangGraph supervisor, reflection, guarded and human-in-the-loop graphs. | Depends on the graph nodes |
recohut_kit.routing | catalog | A rules-first route matcher with one structured model classification as fallback. One decision, not a loop. | One classification |
Start new work from the native agent plus Harness. Everything marked catalog is kept and documented for a case the native path does not cover.
How the pieces fit
The Harness calls the native agent's run with usage limits. Limits, tool exposure and approvals are enforced around that call, so there is no second loop to maintain.
Worked examples
A governed run with a read tool and an approval-gated tool
The model below is a scripted stand-in, so the example runs offline. It calls lookup_policy, then flag_record. flag_record is an effect tool with approval=True, so the run parks until a person approves that exact call. The tool policy mapping is covered in depth on tools and permissions.
import asyncio
import tempfile
from pathlib import Path
from time import time
from pydantic_ai import Agent, DeferredToolRequests
from pydantic_ai.messages import ModelRequest, ModelResponse, TextPart, ToolCallPart, ToolReturnPart
from pydantic_ai.models.function import FunctionModel
from recohut_kit.harness.contracts import Binding, Scope, Task, ToolPolicy, Verification
from recohut_kit.learning.access import Access, Principal
from recohut_kit.learning.access import Scope as AccessScope
from recohut_kit_pydantic_ai.harness.pydantic_ai import Harness, current_action
scope = Scope("acme", "u-1", "helpdesk") # host-authored, never model-supplied
flags: dict[str, str] = {}
def lookup_policy(topic: str) -> str:
"""Look up a policy by topic."""
return "Up to 5 leave days carry over."
def flag_record(record_id: str) -> str:
"""Flag a record for review."""
return flags.setdefault(current_action().id, f"flagged {record_id}")
def script(messages, info):
done = {
part.tool_name
for message in messages if isinstance(message, ModelRequest)
for part in message.parts if isinstance(part, ToolReturnPart)
}
if "flag_record" in done:
return ModelResponse(parts=[TextPart("Flagged R-7.")])
if "lookup_policy" in done:
return ModelResponse(parts=[ToolCallPart("flag_record", {"record_id": "R-7"}, "c2")])
return ModelResponse(parts=[ToolCallPart("lookup_policy", {"topic": "leave"}, "c1")])
async def verify(run, output):
ok = isinstance(output, str) and "R-7" in output
return Verification(ok, "answer names the record", evidence=("flags:R-7",) if flags else ())
native = Agent(
FunctionModel(script),
tools=[lookup_policy, flag_record],
output_type=[str, DeferredToolRequests], # required when any tool has approval=True
instructions="Answer from the tools.",
)
harness = Harness(
native,
directory=Path(tempfile.mkdtemp()),
binding=lambda: Binding("cfg-1", "src-1"), # what this run is bound to: config and source versions
tools={
"lookup_policy": ToolPolicy(),
"flag_record": ToolPolicy(effect=True, approval=True,
authorize=lambda s, action: s == scope),
},
verify=verify,
memory_tools=False,
)
async def main():
first = await harness.run(scope, "session-1", "request-1", Task("Flag R-7 if leave carries over"), deps=None)
print(first.run.status, first.run.reason) # waiting approval_required
action = harness.runs.pending(scope, first.run.id)[0].action
principal = Principal("alice", scope.tenant, "sso") # built by the host after authentication
area = AccessScope(scope.tenant, scope.agent)
access = Access(area, authorize=lambda p, perm, owner: p == principal and perm == "approve" and owner == area)
harness.approve(scope, first.run.id, action_id=action.id, action_digest=action.digest,
reviewer="alice", expires_at=time() + 600, confirmation="msg-42",
principal=principal, access=access, validate_confirmation=lambda source: source)
final = await harness.resume(scope, first.run.id, deps=None)
print(final.completed, final.run.status, final.run.output) # True completed Flagged R-7.
asyncio.run(main())Replace FunctionModel(script) with the model from codex_responses_model for a real run. The harness adds memory tools by default; this example sets memory_tools=False so the model sees only the two tools you declared.
A runaway loop stops without success
Identical tool observations count as no progress. After repeated_observations identical results the run fails with NoProgress, and verify is never called. This is how the harness refuses to call a stuck loop finished.
import asyncio
import tempfile
from pathlib import Path
from pydantic_ai import Agent
from pydantic_ai.messages import ModelResponse, ToolCallPart
from pydantic_ai.models.function import FunctionModel
from recohut_kit.harness import Binding, NoProgress, Scope, Task, Verification
from recohut_kit.harness.contracts import ToolPolicy
from recohut_kit_pydantic_ai.harness.pydantic_ai import Harness, Limits
calls = 0
async def unchanged() -> str:
"""Return an unchanged observation."""
global calls
calls += 1
return "unchanged"
def stuck(messages, info):
return ModelResponse(parts=[ToolCallPart("unchanged", {}, f"call-{calls}")])
async def verify(run, output):
return Verification(True, "ok", evidence=("e",))
harness = Harness(
Agent(FunctionModel(stuck), tools=[unchanged], instructions="Investigate."),
directory=Path(tempfile.mkdtemp()), memory_tools=False, verify=verify,
binding=lambda: Binding("cfg-1", "src-1"),
tools={"unchanged": ToolPolicy()},
limits=Limits(repeated_observations=3),
)
scope = Scope("acme", "u-1", "helpdesk")
async def main():
try:
await harness.run(scope, "s-1", "r-1", Task("Investigate"), deps=None)
except NoProgress:
run = harness.runs.list_runs(scope)[0]
print(calls, run.status, run.reason) # 3 failed NoProgress
asyncio.run(main())The Harness surface
| Method | What it does |
|---|---|
run(scope, session_id, request_id, task, *, deps) | Admits the request once. A repeated request_id returns the existing persisted outcome. |
resume(scope, run_id, *, deps) | Claims a compatible checkpoint and continues. It does not replay an effect whose outcome is unknown. |
approve(scope, run_id, *, action_id, action_digest, reviewer, expires_at, confirmation, principal, access, ...) | Approves one exact action. It does not run the effect. |
wake(scope, run_id, *, deps) | Reauthorizes persisted work that is waiting on an external event, then continues. Needs a wait policy. |
cancel(scope, run_id) | Revokes the lease immediately. |
revise(...), clarify(...) | Steering: change the instruction of a live run, or answer a clarification. Needs the SQLite intent ledger. |
Default limits
Limits bounds one execution, independent of any spending policy.
| Field | Default |
|---|---|
model_requests | 30 |
tool_calls | 100 |
timeout_seconds | 300 |
lease_seconds | 30 |
context_tokens | 10,000 |
memory_tokens | 1,500 |
history_runs | 5 |
repeated_observations | 3 |
repair_attempts | 2 |
total_tokens | None |
Choosing between owners
| Situation | Use |
|---|---|
| A new agent that calls tools and may need approvals | Native Agent inside Harness |
| A single typed answer, no tools | generate_structured from model route, not an agent |
| Your team already builds on Strands or the OpenAI Agents SDK | The matching Harness in recohut_kit_strands or recohut_kit_openai_agents |
| The loop must run inside Amazon Bedrock Agents | recohut_kit_bedrock_agents |
| A model proposes steps but the host must approve each one and enforce deadlines | BoundedLoop |
| A model without native tool calling | react_text for the parser and prompt, react_runtime to run it |
| A multi-node LangGraph workflow | integrations.langgraph_agents |
| Pick a route from rules, ask a model only when rules do not match | recohut_kit.routing |
Check the word agent
A package named "agent" or "loop" is not always one. routing.IntentRouter makes one classification. react_text is a parser. revision_loop is a deterministic workflow with model seams. Only a component where a model picks the next tool or step in a loop is an agent loop, and the table above marks each one.
Failure behaviour, limits and gotchas
- A tool with no policy is hidden.
Harness(tools={...})is a closed allowlist. If you forget the mapping, the model sees no tools and the agent answers without them. No error is raised. - Effect tools need
authorize.ToolPolicy(effect=True)without anauthorizecallback raisesValueErrorat construction.approval=Truerequireseffect=True. - Add
DeferredToolRequeststooutput_typewhen any tool needs approval, or the run cannot park. verifydecides done. A passingVerificationneeds an evidence reference. A failed verification can ask the model to repair (disposition="repairable"with feedback) up torepair_attempts.NoProgressis raised when identical successful observations repeat. The run ends asfailedand is never marked verified.- Limits are checked after a response.
total_tokensis a ceiling, not a reservation, and a run can pass it by one response before failing. codex_modelis an async context manager. Synchronous applications usecodex_responses_model, which builds an application-lifetime model without a running loop. Withmulti_loop=Trueone model can serve several event loops.- No streaming path in the Harness.
runreturns the finished result. Anevent_stream_handlercan be passed through to observe native events, andrecohut_kit_pydantic_ai.ui.vercelencodes events for a UI. - The OpenAI Agents harness is pinned. It checks for
openai-agents==0.17.4withopenai==2.38.0and raisesHarnessErrorotherwise. It refuses native handoffs, MCP servers and dynamic instructions. - The Strands harness checks the agent factory. The factory must build a fresh agent per segment with the supplied plugins, a sequential tool executor, and no session or memory managers.
- Install extras.
recohut-kit-pydantic-ai[harness]brings the Harness dependencies. Importingrecohut_kit.harnessdoes not loadpydantic_ai. - The old path warns.
recohut_kit.harness.pydantic_aiforwards to the package path above. New code importsrecohut_kit_pydantic_ai.harness.pydantic_ai.
How is this page?
Last updated on