Skip to content

Harness

A bare Agent is just a model loop. The harness is the set of opt-in primitives you compose onto it to give it richer capabilities — context assembly, persistent knowledge, sub-task spawning, and the supporting middleware they wire in.

This page is the configuration reference for those primitives. For the conversational entry point (agent.ask(), tools, HITL, observing events), see Agent Communication.

Constructor#

Agent(
    name: str,
    prompt: str | Callable | Iterable = (),
    *,
    config: ModelConfig | None = None,
    tools: Iterable = (),
    middleware: Iterable = (),
    observers: Iterable = (),
    dependencies: dict | None = None,
    variables: dict | None = None,
    response_schema: ResponseProto | type | None = None,
    hitl_hook: HumanHook | None = None,
    plugins: Iterable[Plugin] = (),
)

The loop-related parameters (config, tools, middleware, observers, prompt, …) are covered in Agent Communication and the parameter-specific guides. Context policies use middleware=; persistent knowledge is configured through plugins=[KnowledgePlugin(...)]. Legacy knowledge= and tasks= remain available during their deprecation period. The legacy assembly= parameter is deprecated and will be removed in 1.4.0.

Context policies through middleware=#

Wrap your AssemblyPolicy instances in Middleware(AssemblerMiddleware, policies=[...]). Add Middleware(HaltCheckMiddleware) immediately after it when using AlertPolicy.

assembly= is deprecated

Agent(assembly=...) keeps its existing behavior and emits a DeprecationWarning where the agent is constructed. It will be removed in 1.4.0. Migrate to middleware= as shown below.

from ag2 import Agent
from ag2.assembly import AssemblerMiddleware
from ag2.middleware import HaltCheckMiddleware, Middleware
from ag2.policies import (
    AlertPolicy,
    SlidingWindowPolicy,
    WorkingMemoryPolicy,
)

agent = Agent(
    "assistant",
    config=config,
    middleware=[
        Middleware(
            AssemblerMiddleware,
            policies=[
                WorkingMemoryPolicy(),              # inject /memory/working.md
                AlertPolicy(),                      # deliver alerts, halt on FATAL
                SlidingWindowPolicy(max_events=50), # cap history footprint
            ],
        ),
        Middleware(HaltCheckMiddleware),
    ],
)

Order matters — see the ordering rule in the assembly doc. AssemblerMiddleware.validate_order() will flag known problematic compositions.

KnowledgePlugin#

Groups everything that involves the KnowledgeStore: the store itself, optional bootstrap, and optional compaction + aggregation strategies.

from ag2.knowledge import KnowledgePlugin, MemoryKnowledgeStore

store = MemoryKnowledgeStore()

plugin = KnowledgePlugin(
    store,                         # required KnowledgeStore
    expose_tool=True,
    write_event_log=True,
    bootstrap=None,
    compact=None,
    compact_trigger=None,
    aggregate=None,
    aggregate_trigger=None,
)
Option What it does
store Registered in context.dependencies[KnowledgeStore] so policies like WorkingMemoryPolicy / EpisodicMemoryPolicy can read it.
expose_tool When True (default), the agent gets a plugin-provided knowledge action-group tool that lets the LLM call read / write / list / delete on the store. Set to False when the store should be policy-only — the model never sees the tool, and the bootstrap SKILL.md text drops its "use the knowledge tool" sentence.
write_event_log When True (default), the agent persists its stream history to /log/{stream_id}.jsonl at the end of each ask(). Set to False to keep the store free of stream logs (e.g. when the store is purely user-facing memory).
compact / compact_trigger Wires a compaction middleware that fires compact() between turns when the trigger thresholds are exceeded.
aggregate / aggregate_trigger Wires an aggregation middleware that fires aggregate() on the configured cadence. Failures emit AggregationFailed on the stream — see Aggregation › Wiring onto an Agent for the full lifecycle event triple.
bootstrap Runs once on first use to seed the store. None falls back to DefaultBootstrap(mention_tool=expose_tool), so the generated SKILL.md text matches whether the LLM can actually call the knowledge tool.
from ag2 import Agent
from ag2.aggregate import AggregateTrigger, ConversationSummaryAggregate
from ag2.assembly import AssemblerMiddleware
from ag2.middleware import Middleware
from ag2.compact import CompactTrigger, TailWindowCompact
from ag2.knowledge import KnowledgePlugin, DiskKnowledgeStore
from ag2.policies import WorkingMemoryPolicy
from pathlib import Path

store = DiskKnowledgeStore(Path("./knowledge"))

agent = Agent(
    "assistant",
    config=main_config,
    plugins=[KnowledgePlugin(
        store=store,
        compact=TailWindowCompact(target=100),
        compact_trigger=CompactTrigger(max_events=200),
        aggregate=ConversationSummaryAggregate(config=summarizer_config),
        aggregate_trigger=AggregateTrigger(every_n_turns=10, on_end=True),
    )],
    middleware=[Middleware(AssemblerMiddleware, policies=[WorkingMemoryPolicy()])],
)

Provide each strategy together with its trigger. Omit compaction or aggregation to leave that maintenance disabled.

Migrating from knowledge=#

Agent(knowledge=...) emits one DeprecationWarning at construction in 1.3 and will be removed in 1.4.0. Move the same settings into a plugin:

1
2
3
4
5
6
7
8
9
from ag2 import Agent
from ag2.config import OpenAICompletionsConfig
from ag2.knowledge import KnowledgePlugin, MemoryKnowledgeStore

agent = Agent(
    "assistant",
    config=OpenAICompletionsConfig(model="gpt-5"),
    plugins=[KnowledgePlugin(store=MemoryKnowledgeStore())],
)

Move expose_tool, write_event_log, bootstrap, compact, compact_trigger, aggregate, and aggregate_trigger unchanged into KnowledgePlugin. KnowledgeConfig and its current imports remain available; only the Agent parameter is deprecated. Supplying both configurations raises ValueError before bootstrap. For policy-only memory, use KnowledgePlugin(store, expose_tool=False). Custom StoreBootstrap, CompactStrategy, and AggregateStrategy implementations keep their protocols.

Construction performs no store I/O. Bootstrap precedes tool schema resolution and middleware/observer setup, uses the existing /.initialized sentinel, and coordinates concurrent calls on the configured plugin. On completion, aggregation runs before compaction; logging follows observer completion. Aggregation retains its trigger-driven cleanup on failures and cancellation. Final logging runs only when the enclosing execution scope exits normally: run handles (including Agent.ask) close that scope normally even when their background turn failed; a failing AgentReply.ask propagates through the scope and skips logging, as before migration.

The store is a plugin dependency default. Explicit Agent or invocation dependencies={KnowledgeStore: other_store} overrides it for policies, tools, bootstrap, and maintenance together. Legacy knowledge= retains its previous precedence during the compatibility period. An invocation-only plugin is removed after that invocation, including its tools and dependency default. A worker needs its own plugin; delegation does not inherit the parent's tools.

Tool approval and automatic writes#

The knowledge tool uses ordinary tool middleware and tool precedence. Attach the existing approval_required() middleware to gate model-requested reads, writes, lists, and deletes. Denying a call prevents that tool action. Bootstrap, aggregation, compaction archives, and event logs are automatic maintenance; an individual tool approval does not gate those writes. Approval is never enabled automatically. Set write_event_log=False to opt out of conversation logs independently of tool exposure and other maintenance.

Subagent delegation#

Build each worker as an Agent with its own config, prompt and tools, then expose it to the parent through Agent.as_tool(). A worker receives only the tools you configure on it. Give it delegate tools only when further delegation is intended. The model can request several delegates in one response to run them concurrently.

To cap concurrency, share a tool middleware function that closes over one semaphore across the delegates. See Limiting concurrency. To let the model compose a worker per objective, use dynamic_agent().

Migrating from TaskConfig#

Deprecated — removal in 1.4.0

TaskConfig, Agent(tasks=...), Agent.tasks, and the auto-injected run_subtask / run_subtasks tools remain available during the deprecation period and will be removed in 1.4.0. Move the worker's config, prompt and tools onto an explicit Agent, then register its Agent.as_tool() on the parent. See the migration guide for the field mapping and concurrency changes.

Agent.as_tool()#

Expose any Agent as a FunctionTool so another Agent can invoke it like any other tool:

from ag2 import Agent
from ag2.config import OpenAICompletionsConfig

config = OpenAICompletionsConfig(model="gpt-4o-mini")

child = Agent(
    "researcher",
    prompt="Answer the objective concisely.",
    config=config,
)

parent = Agent(
    "lead",
    config=config,
    tools=[child.as_tool(description="Delegate fact-finding to a researcher.")],
)

reply = await parent.ask("Find out where Melbourne is.")

as_tool() returns a FunctionTool named task_{child.name} that accepts an objective parameter and forwards it into the child's stream. See Subagents for sub-task streams, depth limiting, and stream factories.

Reading an agent's composition#

An Agent reports what it is made of, so you can compare two agents, assert on composition in a test, or log it. Each constructor argument has a matching read-only property:

Property Reports
name agent name
system_prompt static prompt fragments, in order
dynamic_prompt dynamic prompt hooks, in registration order
tools attached tools
middleware agent-level middleware, in registration order
dependencies / variables injected values, keyed as supplied
config / response_schema / hitl_hook model config, schema, human-input hook
observers / assembly observers, assembly policies
tasks TaskConfig or None; deprecated, removed in 1.4.0

Sequences come back as tuples and mappings as read-only views, so an agent cannot be changed through them.

def fingerprint(agent: Agent) -> tuple:
    return (
        agent.name,
        agent.system_prompt,
        tuple(t.name for t in agent.tools),
        tuple(m.description for m in agent.middleware),
        tuple(sorted(map(str, agent.dependencies))),
    )

assert fingerprint(built_one_way) == fingerprint(built_another_way)

Middleware entries#

agent.middleware and tool.middleware yield entries pairing each middleware with its description:

1
2
3
for entry in agent.middleware:
    entry.description   # what it is and how it was configured
    entry.middleware    # the object itself

Both are needed. A description says what a middleware is; identity says whether two tools share one. A single rate limiter across ten tools and ten separate ones configured identically produce equal descriptions, so is on entry.middleware is the only thing that tells them apart:

1
2
3
4
first, second = agent.tools

first.middleware[0].middleware is second.middleware[0].middleware
# True when both tools hold one instance, so they share its state

Note

Entries are built when you read the property, so agent.middleware[0] is agent.middleware[0] is False. Compare entry.middleware, never the entry itself.

Turn lifecycle#

Each await agent.ask(...) enters middleware in registration order (outermost → innermost), then reaches the LLM client. Register AssemblerMiddleware before HaltCheckMiddleware so alerts can halt the current call. Place retry, logging, or other middleware according to whether they should see the original or assembled context.

KnowledgePlugin contributes compaction and aggregation middleware through ordinary plugin composition. Keep the context assembler and halt checker in your explicit middleware list; plugin and invocation contributions follow their registration order.

Lifecycle events emitted during a turn include ObserverStarted / ObserverCompleted, CompactionCompleted, AggregationCompleted, and HaltEvent. Subscribe to any of them via an Observer or a stream subscriber.