Agent
Core Agent class constructor, methods, and usage patterns.
#Agent
Agent is the primary single-agent scope. It owns credentials/client wiring, tools, skills/resources, runtime defaults, and invocation methods.
#Construction
from maivn import Agent, MemoryConfig, SystemToolsConfig
agent = Agent(
name='researcher',
description='Researches a question and cites evidence.',
system_prompt='Prefer primary sources.',
api_key='your-api-key',
model='auto',
memory_config=MemoryConfig(enabled=True),
system_tools_config=SystemToolsConfig(
allowed_tools=['web_search', 'repl'],
),
)name is required. Credentials can come from api_key, the terminal environment, an explicitly selected env_file or api_key_file, or a preconfigured client. base_url overrides the API address. See Authentication for precedence. Other constructor controls include timeout, private_data, system_tools_config, max_cycles, final-output/nested-synthesis flags, hooks, tools, skills, resources, tags, skill sets, attached skill IDs, and MCP servers. max_cycles is keyword-only. See Capping model-loop cycles.
Per-call allow_private_in_system_tools wins over the agent's value and over system_tools_config.allow_private_data for that call. See Per-call private-data switch.
agent_id defaults to name, and version defaults to 1. Trigger builders inherit that deployed identity. .target(...) remains an explicit override. When an agent with its own agent_id runs as a delegate or swarm member, it runs under that same id (so its bound memory and resources are reachable), and traces label it, like the parent, by its name.
allow_private_in_system_tools defaults to False. Enabling it permits raw private values to reach system tools and should be an explicit risk decision. Privacy controls reduce exposure but are not certifications or guarantees. See Private Data.
#Tool registration
@agent.toolify(description='Look up an order')
def lookup_order(order_id: str) -> dict[str, str]:
return {'order_id': order_id, 'state': 'ready'}Use add_tool(...) for an existing function/model and add_toolset(...) for a connector instance. list_tools() returns registered ToolMetadata. compile_tools() returns the current compiled metadata and schemas. validate_tool_configuration() checks final-output routing.
toolify and add_tool accept name, description, permissions, destructive/always-execute/final-tool flags, metadata and tags, plus before/after hooks. add_toolset filters by method names or tags.
#Invocation
The sync invocation signature is:
def invoke(
messages: SdkMessagesInput,
*,
force_final_tool: bool | None = None,
targeted_tools: list[str] | None = None,
structured_output: type[BaseModel] | None = None,
thread_id: str | None = None,
verbose: bool = False,
reasoning: Literal['minimal', 'low', 'medium', 'high', 'xhigh', 'max'] | None = None,
routing_preference: Literal['speed', 'cost', 'quality'] | None = None,
memory_config: MemoryConfig | Mapping[str, object] | None = None,
allow_private_in_system_tools: bool | None = None,
model: RuntimeModelChoice | None = None,
system_tools_config: SystemToolsConfig | Mapping[str, object] | None = None,
max_cycles: int | None = None,
stream_response: bool = False,
options: RunOptions | None = None,
origin: str | None = None,
) -> InvokeResponse:
...ainvoke(...) has the same keyword surface and returns an awaitable InvokeResponse. stream(...) and astream(...) have the same controls and yield StreamEvent values. astream(...) also takes cancel_on_close: bool = False, which cancels the runtime session when you close the stream early.
#Per-call private-data switch
allow_private_in_system_tools on invoke, ainvoke, stream, astream and the structured-output builder's invoke and ainvoke defaults to None, which keeps the agent's value. True or False wins for that call, over both the agent's allow_private_in_system_tools and system_tools_config.allow_private_data.
#Capping model-loop cycles
max_cycles caps how many model-loop cycles a run may use. It takes an integer from 1 to 1000 and is available on the Agent constructor (keyword-only), on RunOptions, and on invoke, ainvoke, stream, astream and the time-travel streams. A per-call value beats RunOptions.max_cycles, which beats the agent's value. Out-of-range values raise ValueError. The platform never runs more than 20 cycles, so it uses the smaller of your value and 20: a larger value behaves as 20. The cap counts cycles that may call tools, and it is exact: after the last one the model gets one more turn, with every tool withheld, to answer from what the cycles returned. A run that still has not finished raises MaivnSDKError with error_code='max_iterations_exceeded'. With verbose=True each cycle prints a Cycle n/m line, and a normalized stream carries it as an enrichment event with the phase cycle_started. It is not RunConfig.recursion_limit, which limits delegation depth.
max_cycles requires a platform release that supports it. Against an older platform, setting it makes the request fail with a validation error, and leaving it unset works everywhere. To bound how long a run takes, use a hosted job and its max_duration_seconds.
routing_preference leans automatic routing of a plain chat request toward speed, cost or quality. It does not change the route of a run with tools or structured output, except that 'quality' moves such a run up one tier. A named tier or exact model ignores it. When the preference has no effect, the run's model_routing event records routing_preference_ignored with the reason.
from maivn.messages import HumanMessage
response = agent.invoke(
[HumanMessage(content='Find the current order state.')],
targeted_tools=['lookup_order'],
thread_id='thread-42',
)
print(response.response)InvokeResponse contains final_message, response, optional result, session/thread/root-event identifiers, event positions, usage/token metadata, stop reason, and tool-call summary. It has no status or error field.
agent.session_usage(response.session_id) (async asession_usage) returns the provider-reported ProviderUsage for the session and the work it started. See Usage and Cost.
stream_response=True asks the SDK to consume the event stream internally while still returning one InvokeResponse. Use stream() when the caller needs each event.
#Thread handles
thread(thread_id=None, *, options=None) binds a conversation without sending a request. Use send / asend for completed responses and stream / astream for events, with the same tools, hooks, message lists, and invocation arguments as this agent:
conversation = agent.thread()
response = conversation.send('Remember that the order is 42.')
response = conversation.send('Look up that order.', targeted_tools=['lookup_order'])Use state / astate for state and events / aevents for current-turn replay. time_travel(checkpoint_id, message, *, branch_from_message_id=None, options=None, **kwargs) rewinds the thread to a checkpoint and returns the new path's InvokeResponse, running local tools like send; atime_travel, time_travel_stream and atime_travel_stream are its async and streaming forms (maivn 3.1.0 or later). The handle fixes the thread ID. See Sessions and Streaming for cursor lifetime, explicit dispatch methods, and stream cleanup.
#Structured output
from pydantic import BaseModel
class Summary(BaseModel):
answer: str
response = agent.structured_output(Summary).invoke('Summarize the order.')
summary = response.resultThe structured_output(Model) builder preserves invoke/ainvoke/stream/astream. Direct structured_output=Model remains available on invocation methods. force_final_tool targets a registered final_tool=True tool and is a different mechanism.
#Final tool selection
When a run produces several final-tool calls, the first successful call supplies the final value. Calls published together retain their authored order regardless of parallel completion timing. Later calls cannot replace the selected value. Fatal run errors still terminate the run as errors.
The final event's message metadata exposes three flat fields:
final_tool_policy:"first_successful".final_tool_call_count: the cumulative number of final-tool calls counted by the run.final_tool_selected_call_id: the call ID that supplied the selected final value.
If bounded final-value generation and repair exhaust their attempts, the run terminates with value_fill_exhausted. invoke raises MaivnSDKError carrying that error_code, plus the session and root event IDs for diagnostics. Native final-tool prompting is also bounded: a model that continues returning prose after three reminders terminates with final_tool_contract_unfulfilled.
#Follow-up questions
from maivn import FollowupQuestion
def answer(question: FollowupQuestion, schema: dict[str, object]) -> object:
print(question.question)
return 'US East'
response = agent.allow_followup_questions(
input_handler=answer,
max_questions=3,
max_questions_per_thread=10,
response_schema={'type': 'string'},
timeout=60,
).invoke('Plan the deployment.', thread_id='thread-42')The builder handles runtime-authored agent_followup checkpoints inline, submits the typed answer, and continues the same thread. The default handler is default_terminal_followup. See Interrupts and follow-up questions.
#System tools and model routing
SystemToolsConfig.allowed_tools is the invocation allowlist. web_search retrieves current public information. repl runs sandboxed Python for calculation and analysis. Availability remains subject to workspace policy and plan limits.
model accepts a tier name, an exact model ID, a ModelChoice, or a ModelConfig. A scoped ModelConfig can select response, thinking, compose_argument, and repl through ModelChoice, and planning through PlanningChoice. Omitted parts use platform routing. The tiers are listed under Model selection. See also the guide.
from maivn import ModelChoice, ModelConfig
analyst = Agent(name='analyst', api_key='your-api-key')
response = analyst.invoke(
'Analyze the dataset.',
model=ModelConfig(
response=ModelChoice(tier='balanced'),
repl=ModelChoice(tier='fast'),
),
)#Events and terminal output
events(include=..., exclude=..., on_event=..., auto_verbose=False) returns an invocation wrapper that reports selected compatibility events. verbose=True on invocation methods enables local terminal reporting. Since maivn 3.1.0 auto_verbose defaults to False, so events() no longer prints the terminal trace; pass auto_verbose=True for the earlier behavior. See Filtering with events() for the shape of each on_event dict, including task_list_updated.
A plain install uses Tier 0 text output. maivn[rich] enables Tier 1 Rich output on a capable terminal. MAIVN_TERMINAL_TIER=plain|0 forces plain. rich|1 requests Rich but degrades to plain if the optional dependency is unavailable. CI, NO_COLOR, TERM=dumb, and non-TTY output also select plain unless a supported explicit Rich override applies.
#Batch, scheduling and cleanup
batch(inputs, *, max_concurrency=None, return_exceptions=False, **invoke_kwargs) and abatch(...) preserve input order and return list[InvokeResponse | BaseException]. Both default to min(32, os.cpu_count() + 4) concurrent calls, capped at the number of inputs. With return_exceptions=True a failing input yields its exception in place; otherwise a failure is raised to the caller.
preview_redaction(prompt, **options) and apreview_redaction preview the shielded copy this agent would send, with its system_prompt prepended exactly as invoke does. The keyword options are those of Client.preview_redaction. Use them instead of the client method when the agent has a system prompt. See Preview redaction.
cron(expression, tz=..., mode='remote', ...), interval(...), and at(datetime, ...) create invocation builders. See Scheduling. serve() and serving() announce a running agent to the platform so its triggers can reach it; see Serve an agent.
close() takes no arguments and is safe to call twice. It stops the agent's own MCP servers (stdio processes and HTTP sessions; they start again on next use) and releases the connection pools of a client the agent created itself. It never closes a Client that you passed in; the code that created that client owns it. See MCP lifecycle.
See Tools, Sessions and Streaming, and Shared Data Models.
Live Available Models
Active, tool-capable model IDs accepted by ModelConfig.
Loading models
The current table controls remain available while records load.