This document is the canonical reference for Agent and MTPAgent.
Constructor
Source: agent.py
pythonAgent(
provider: ProviderAdapter,
registry: ToolRegistry | None = None,
*,
tools: ToolRegistry | None = None,
debug_mode: bool = False,
debug_logger: Callable[[str], None] | None = None,
debug_max_chars: int | None = None,
strict_dependency_mode: bool = False,
instructions: str | None = None,
system_instructions: str | None = None,
stream_chunk_size: int = 40,
max_history_messages: int = 200,
send_media_to_model: bool = True,
enforce_provider_capabilities: bool = True,
allow_stream_fallback: bool = True,
autoresearch: bool = False,
research_instructions: str | None = None,
stream_tool_events: bool = True,
stream_tool_results: bool = True,
session_store: SessionStore | None = None,
mode: str = "standalone",
members: dict[str, Agent] | None = None,
)mode options:
standalone(default): regular single-agent behavior.member: marks this instance as a delegated sub-agent.delegator/orchestration: enables member delegation tools.
When mode is delegator or orchestration, each member is exposed as a tool:
agent.member.<member_name>- input:
{"task": ..., "max_rounds": 5, "tool_call_limit": ...} - output: member agent final text response.
Capability enforcement options:
enforce_provider_capabilities=True(default): fail fast when requested features are unsupported by the active provider.allow_stream_fallback=True(default): if provider has no nativefinalize_stream, stream APIs degrade safely by chunking thefinalize()output.send_media_to_model=True(default): include media payloads in model messages (still subject to capability guardrails).
Autoresearch options:
autoresearch=False(default): normal run-loop completion behavior.autoresearch=True: persistent run behavior where direct assistant text does not end the run by itself; the model should terminate explicitly viaagent.terminate, user cancellation, or round/budget limits.research_instructions: additional system instruction text appended only whenautoresearch=True.
When autoresearch=True, MTP injects:
- internal autoresearch system instructions
- internal tool:
agent.terminate(reason: str, summary: str)
Tool-event streaming options:
stream_tool_events=True(default): include tool lifecycle events inrun_loop_events/run_events.stream_tool_results=True(default): include tool output/error payloads intool_finishedevents.- If
stream_tool_events=False, tool lifecycle events are suppressed regardless ofstream_tool_results. debug_max_chars=None(default): do not truncate debug payloads. Set an integer limit if you want shorter debug lines.
Runtime methods
Basic execution
run(user_input: Any) -> strarun(user_input: Any) -> strrun_loop(user_input: Any, max_rounds: int = 5, *, tool_call_limit: int | None = None, input_schema: dict | None = None) -> strarun_loop(...) -> str
run/arun/run_loop/arun_loop also accept optional user_id, session_id, and metadata. When session_store is configured and session_id is provided, message history is loaded and persisted automatically.
Built-in stores:
JsonSessionStorePostgresSessionStoreMySQLSessionStore
user_input can be a string, dict, list, or model-like object (model_dump/dict supported).
Structured input
input_schemais supported on:run_looparun_looprun_outputarun_outputrun_stream/events wrappers viaMTPAgent
If validation fails, run exits early with RunOutput.output_validation_error.
Structured output
output_schemais supported on:run_outputarun_output
When provided, MTP parses final text as JSON and validates against the schema.
Output model pipeline
run_output and arun_output support:
output_modeloutput_model_promptparser_modelparser_model_prompt
Pipeline order:
- primary run generates final text
- optional
output_modelrefines it - optional
parser_modelpost-processes it - optional
output_schemavalidation runs
RunOutput
Source: agent.py
Fields:
run_idinputfinal_textmessagestool_resultsuser_idsession_idmetadatacancelledtotal_tool_callsoutputoutput_validation_errorpausedpause_reasonterminatedtermination_reason
Cancellation and continuation
cancel_run(run_id: str) -> boolcontinue_run(run_output: RunOutput | None = None, run_id: str | None = None, ...) -> RunOutputacontinue_run(...) -> RunOutput
Paused runs (for example from StopAgentRun) can be resumed by run_id or prior RunOutput.
Streaming
run_loop_stream(...) -> Iterator[str]run_loop_events(...) -> Iterator[dict]arun_loop_events(...) -> AsyncIterator[dict]
When provider capabilities are enabled:
- media inputs (
images,audios,videos,files) are validated against provider-declared supported modalities. - stream requests validate native finalize-stream support and either:
- fail fast with a clear error, or
- degrade to finalize-output chunk streaming when fallback is enabled.
MTPAgent.print_response(..., stream_events=True) prints readable terminal logs by default. Use event_format="json" for raw JSON lines. debug_mode controls event verbosity for print_response(..., stream_events=True):
False: normal concise logsTrue: detailed debug logs (plans, batches, tool lifecycle, payloads, top-level XML context sections, metrics blocks)
In autoresearch mode:
- direct assistant text chunks can appear as intermediate progress updates.
- completion is expected via
agent.terminate(emitted asrun_terminatedevent beforerun_completed).
Dynamic tool management
add_tool(tool: RegisteredTool | Callable) -> Noneset_tools(tools: list[RegisteredTool | Callable]) -> None
This enables post-initialization tool updates without rebuilding the agent.
Tool control-flow exceptions
Source: exceptions.py
RetryAgentRun("feedback"): injects feedback and asks the model to replan.StopAgentRun("reason"): pauses/stops the current run and returns withpaused=True.
Async provider contract
Providers may now implement optional async hooks:
anext_action(...)afinalize(...)
If not implemented, agent async APIs use thread fallback for sync provider methods.
MTPAgent wrapper
Source: simple_agent.py
MTPAgent mirrors the same features:
run,arunrun_output,arun_outputrun_streamrun_events,arun_eventscontinue_run,acontinue_runcancel_runprint_response
See full persistence examples and provider-specific setup: