Skip to content

Documentation navigation

Sessions, Streaming & ModelConfig

How invoke and stream relate, sync versus async, ModelConfig, live available models, and what a session response carries.

#Sessions, invocation and streaming

A session is one run of your agent: you give it a message, it works through the request, and it hands back a result. You can run it and wait for the answer, or watch it work live as it goes. This guide covers how to start a session, read what comes back, tune a single run, and run many at once.

#What a session is

Every call to invoke(), stream() or one of their async variants starts a session, one turn of work for an Agent or Swarm. Within that turn the runtime evaluates your request, runs any tools it needs, and produces a response. When the turn ends, the session is complete.

Most useful conversations span more than one turn. To keep turns connected, pass a thread_id:

Python
from maivn import Agent
from maivn.messages import HumanMessage

agent = Agent(name='assistant', api_key='...')

# First turn
agent.invoke(
    [HumanMessage(content='My name is Dana.')],
    thread_id='conversation-1',
)

# Later turn: same thread, so the agent has the earlier context
agent.invoke(
    [HumanMessage(content='What is my name?')],
    thread_id='conversation-1',
)

A thread_id is just a string you choose. Reuse it across turns that belong to the same conversation, and use a fresh one to start a clean session. Threads govern the conversational recall an agent carries from turn to turn. Continuity uses a bounded recent-history tail rather than replaying the entire conversation. See History and run limits for the message cap and current runtime boundaries, and Memory and Recall for the cross-thread reuse layer (skills, bound resources, promoted insights).

Note Independent runs should use different threads (or none). A shared thread_id makes concurrent calls write into the same conversation, which is rarely what you want for unrelated work. See Running many at once.

#Explicit thread operations

For a conversation in application code, bind a thread once and keep using the same handle. Client, Agent, and Swarm all expose thread():

Python
conversation = agent.thread()  # Selects a new local ID; sends no request.
first = conversation.send([HumanMessage(content='My name is Dana.')])
second = conversation.send('What is my name?')
print(second.response)

# Reattach using an ID saved by your application.
conversation = agent.thread(conversation.thread_id)

send / asend return the usual InvokeResponse, and stream / astream yield the usual events. They use the owner's normal execution path, so full message lists, tools, hooks, attachments and structured output all work. Scope defaults still apply, and you can pass per-call invocation arguments as usual. The handle fixes thread_id and rejects attempts to change it.

Use state / astate to inspect the thread, or events / aevents to replay the current turn's events. The handle retains the observed session ID and last event position, so it can reconnect after a partially consumed stream. Starting a new turn resets them. Positions belong to one session, not the entire conversation. A handle with an observed session keeps replaying that run; attach a fresh handle to follow a turn started by another client. Event replay observes execution; it does not start a local Python tool broker. Consume the original invocation stream when local tools need to run.

A handle permits one active send or stream at a time. Close an unfinished stream before starting the next operation. Explicit invoke(..., thread_id=...) and RunOptions(thread_id=...) remain supported.

A thread belongs to the user_id that started it. Continuing it as another user fails with the error code thread_user_mismatch: a terminal run error raises MaivnSDKError with error_code='thread_user_mismatch', and an HTTP refusal raises MaivnHTTPError with that code. Use the owner's user_id, or start a new thread.

Since maivn 3.1.0, invoke, stream and the handle's send and stream send the agent's or swarm's system_prompt scoped to the turn. The model still receives it on every turn, but the thread's stored history keeps no copy, so a long thread no longer repeats it. start_thread stores the prompt in the thread, because post_thread_message and time_travel_thread send only the user message and rely on the stored prompt. A thread started with invoke or send and then continued with post_thread_message therefore runs that continuation without the system prompt. Keep one thread on one path: send throughout, or start_thread followed by post_thread_message.

#Dispatch and receive an acceptance receipt

The explicit thread APIs also have async counterparts on Agent, Swarm, and Client: astart_thread, apost_thread_message, atime_travel_thread, asubmit_approval, aget_thread, and athread_events. Scope methods retain the same resource preparation, system prompt, and options as their synchronous counterparts.

start_thread, post_thread_message, and time_travel_thread return an acceptance receipt without waiting for completion. They forward supported run options, skills, tools, private data, and swarm members to the runtime. Merely following a receipt with thread_events does not execute SDK-local Python tools. Prefer the bound handle's send or stream when using those tools.

Python
from maivn import RunOptions


async def continue_conversation(agent):
    started = await agent.astart_thread("Prepare a short summary.")
    async for event in agent.athread_events(
        started.thread_id,
        options=RunOptions(resume_from_position=started.stream_position),
    ):
        print(event.event_type)
    return await agent.apost_thread_message(started.thread_id, "Make it shorter.")

post_thread_message and time_travel_thread, including their async and streaming variants, require exactly one message: a string, a message object, or a one-element sequence. Empty or multiple-message sequences raise ValueError before a thread request is sent. Use start_thread when supplying an initial conversation. Earlier SDK versions silently kept only the last message in continuation calls. This restriction does not apply to invoke, stream, or bound-handle send and stream: those accept full message lists on every turn.

#Time travel

A thread keeps checkpoints. get_thread returns a ThreadState whose checkpoints are ThreadCheckpoint records (checkpoint_id, parent_checkpoint_id, branch_id, status, message_count and timestamps). time_travel_thread starts a new active path from one of them, on the same thread, and returns the same acceptance receipt:

Python
state = agent.get_thread('conversation-1')
earlier = state.checkpoints[0]

accepted = agent.time_travel_thread(
    'conversation-1',
    checkpoint_id=earlier.checkpoint_id,
    message='Answer again, but shorter.',
    # branch_from_message_id='msg-...',  # optional: branch from a specific message
)

time_travel_thread_stream and atime_travel_thread_stream run the same request as an event stream and execute local Python tools, like stream. The receipt form does not. The message must be a single message, as with post_thread_message.

A bound handle can time travel and wait for the answer, like send:

Python
conversation = agent.thread('conversation-1')
earlier = conversation.state().checkpoints[0]

response = conversation.time_travel(earlier.checkpoint_id, 'Answer again, but shorter.')
print(response.response)

BoundThread.time_travel(checkpoint_id, message, *, branch_from_message_id=None, options=None, **kwargs) blocks until the new path finishes and returns an InvokeResponse. It streams the run underneath, so local Python tools execute and interrupts are answered before it returns. atime_travel is the async form, and time_travel_stream and atime_travel_stream yield the events while keeping the handle's replay cursor current. These need maivn 3.1.0 or later.

#Interrupts and approvals

When a run pauses for input, ThreadState.interrupt describes it. Answer a typed interrupt with submit_interrupt_response(thread_id, interrupt_id, answer=..., responded_by=..., surface='sdk'). Answer a legacy thread tool approval with submit_approval(thread_id, interrupt_id, decision=ApprovalDecision(approved=..., decided_by=..., reason=...)). Each has an async twin (asubmit_interrupt_response, asubmit_approval) and returns a ThreadAccepted receipt. These methods live on Client; Agent and Swarm expose submit_approval and asubmit_approval. See Interrupts for the follow-up question flow that most applications use instead.

#invoke vs stream vs ainvoke vs astream

The four entry points differ on two axes: sync or async, and wait for the result or watch it live.

MethodSync/AsyncReturnsUse when
invokesyncInvokeResponseYou just want the final answer
streamsyncIterator[StreamEvent]You want to render progress as it happens
ainvokeasyncInvokeResponseSame as invoke, inside an event loop
astreamasyncAsyncIterator[StreamEvent]Same as stream, inside an event loop

All four exist on Client, Agent and Swarm. Agent and Swarm share the tuning keywords below, except that targeted_tools and structured_output are Agent only.

#invoke — run and wait

invoke() runs the agent and returns a single InvokeResponse once the turn is finished.

Python
response = agent.invoke([HumanMessage(content='What is the weather in Austin?')])
print(response.response)

#stream — watch it work live

stream() yields events as the turn unfolds: tool execution, phase changes, assistant text deltas, and a terminal final event carrying the completed payload. Each item is a StreamEvent with canonical event_type/data and compatibility name/payload properties.

Python
for event in agent.stream([HumanMessage(content='Think through this problem')]):
    if event.name == 'system_tool_chunk':
        print(event.payload.get('text', ''), end='')
    elif event.name == 'final':
        print('\nDone')

Status-message and enrichment events may appear on the same stream. Consumers should branch on event names rather than enabling a separate invocation flag.

To learn which model served a run, watch for model_routing events. Each one names a model in its model field, and the most recent one names the model serving the run at that point (if a provider attempt fails and the call moves to another model, a later event names the model that took over):

Python
served_model = None
for event in agent.stream([HumanMessage(content='Draft a launch plan.')]):
    if event.event_type == 'model_routing':
        served_model = event.payload.get('model') or served_model

See Model routing events.

For product integrations, treat stream() as the raw transport layer. If you are forwarding execution state to a browser or app, normalize the raw events first:

Python
from maivn.events import normalize_stream

raw_events = agent.stream(
    [HumanMessage(content='Think through this problem')],
)

for event in normalize_stream(raw_events, default_agent_name='assistant'):
    send_to_frontend(event.model_dump())

See Frontend Events for the wire format, ready-made client examples, and the enrichment phase labels surfaced during a turn.

#ainvoke / astream — the async variants

ainvoke() and astream() use asynchronous execution and streaming. They take the same parameters and can be awaited or iterated inside an event loop.

Python
# Awaitable single result
response = await agent.ainvoke([HumanMessage(content='Summarize Q1')])

# Async event stream
async for event in agent.astream([HumanMessage(content='Walk me through it')]):
    handle(event)

#Stopping a stream early

When you leave before exhaustion, close the iterator so the SDK can release its HTTP reader and stream worker. Use closing for synchronous streams and aclosing for asynchronous streams:

Python
from contextlib import closing, aclosing

with closing(agent.stream('Explain the plan')) as events:
    for event in events:
        if event.event_type == 'final':
            break

async with aclosing(agent.astream('Explain the plan')) as events:
    async for event in events:
        if event.event_type == 'final':
            break

The synchronous bridge keeps a bounded event buffer and propagates closure to its asynchronous source. A bare break does not close an iterator you retain.

By default, closing a stream only disconnects: the run keeps going on the server, and you can replay it later. To cancel remote execution yourself, call client.cancel(session_id) (or await client.acancel(session_id)).

Client.astream and Agent.astream take cancel_on_close=False. Set it to True and closing the stream before the root final or error event cancels the accepted root invocation, including a run waiting on an interrupt. The cancel request waits at most two seconds, and a failed cancel is logged without hiding the original stream failure. It is local policy and is never sent in the invoke payload. The synchronous stream() and Swarm.astream have no such argument.

Python
from contextlib import aclosing

async with aclosing(agent.astream('Explain the plan', cancel_on_close=True)) as events:
    async for event in events:
        if event.event_type == 'final':
            break
Swarm note Swarm.invoke() / Swarm.stream() and their async variants work the same way, and all tuning arguments are keyword-only. See Multi-Agent.

#Reading results

A finished turn returns a InvokeResponse. The two fields you reach for most often are response and result.

FieldWhat it holds
responseThe final assistant text for the turn
resultStructured output (the final-tool payload), when applicable
responsesCompatibility list containing response when non-empty
final_messageCanonical final message contract
usage / token_usageRaw usage metadata and normalized token-count dictionary
stop_reasonProvider/runtime stop reason, when supplied
session_id / thread_idInvocation and conversation identifiers
tool_call_count / tool_namesHow many tools ran and which
artifactsReturnable artifacts selected by the completed invocation

Use .response when you want the natural-language answer, and .result when the turn produced a typed object you intend to consume programmatically.

Python
# Conversational answer
response = agent.invoke([HumanMessage(content='Summarize this thread.')])
print(response.response)

# Structured answer (see Structured Output guide for the full pattern)
response = agent.invoke(
    [HumanMessage(content='Build the weather report.')],
    force_final_tool=True,
)
print(response.result)  # the validated final-tool object

When a turn produces no structured output, .result is empty and .response carries the answer. When you force a final tool, .result holds the validated schema. The two are complementary, not exclusive: a turn can populate both.

For per-call token accounting, read response.token_usage. See Billing and Usage.

#Tuning a run without internals

Two knobs let you shape the trade-off between speed and depth on a per-call basis. Most calls should use broad intent hints and let the runtime handle the details. When you need stricter control, ModelConfig lets you scope tier or exact-model choices to the public configurable framework parts.

#model - tier or scoped model config

Python
response = agent.invoke(
    [HumanMessage(content='Draft a launch plan.')],
    model='balanced',
)
ValueIntent
'auto'Let the runtime pick an appropriate tier for the request (default)
'fast'Favor speed and lower latency
'balanced'A middle ground between speed and capability
'max'Favor maximum capability for hard requests
'ultra'Request the runtime's ultra tier when available

Leave model unset (or 'auto') and the runtime chooses for you. The selection logic is intentionally internal for the broad tier path. Any other string is treated as an exact model ID and forces that model.

For scoped control, pass a ModelConfig:

Python
from maivn import ModelChoice, ModelConfig

response = agent.invoke(
    [HumanMessage(content='Review this incident report and draft the response.')],
    model=ModelConfig(
        response=ModelChoice(model_id='provider/model-id'),
        thinking=ModelChoice(tier='max'),
        repl=ModelChoice(tier='fast'),
    ),
)

ModelConfig supports these parts:

PartWhat it controls
responseFinal/direct assistant response generation
thinkingThe think system tool
compose_argumentModel-based composition of a tool argument
replREPL code generation and repair
planningPlanning model selection, using PlanningChoice

The response and system-tool parts accept ModelChoice with one of the tiers auto, fast, balanced, max, or ultra, or an exact model_id. Planning uses PlanningChoice with auto, standard, advanced, or deep, or an exact model_id. Set exactly one of tier and model ID in each choice. Unspecified parts keep the runtime default.

To apply one exact model ID to all parts, including planning, use:

Python
response = agent.invoke(
    [HumanMessage(content='Summarize the account.')],
    model=ModelConfig.for_all(model_id='provider/model-id', include_planning=True),
)

for_all leaves planning unset by default because planning has a separate tier vocabulary. include_planning=True requires an exact model ID.

#reasoning — how much deliberation to allow

Python
response = agent.invoke(
    [HumanMessage(content='Reconcile these conflicting reports.')],
    reasoning='high',
)

reasoning ranges from 'minimal' through 'low', 'medium', 'high' and 'xhigh' to 'max'. Lower settings return faster; higher settings allow more deliberation for complex, multi-step reasoning. 'xhigh' and 'max' ask for the deepest reasoning a model offers. If the model does not offer the level you ask for, mAIvn uses the closest level it does offer, preferring a lower one. Higher levels use more tokens and take longer. Like model, it is a hint. Leave it unset to use the runtime default.

#verbose — local tracing

verbose=True enables terminal tracing for a call:

Python
response = agent.invoke([HumanMessage(content='Debug this')], verbose=True)

For structured, filterable event reporting use the event builder, agent.events(include=..., on_event=...). Since maivn 3.1.0 it no longer prints the terminal trace unless you pass auto_verbose=True. See events() for the include/exclude categories and the on_event callback.

The session start line shows the tier or model you asked for (tier fast, or model <id>); the Model line that follows shows the model the run resolved to. With a max_cycles cap, the trace prints a Cycle n/m line at the start of each model-loop cycle. In a swarm run, the plain terminal output prefixes each member's streamed lines with the member's name, such as [researcher] ..., and prints the final answer once. A call refused by a before_execute hook prints Blocked <tool>: <reason> and counts under Tools Blocked in the summary, not under Tools Executed.

#RunOptions

RunOptions bundles per-call settings. Pass it as options= to invoke, stream, the thread methods and Client calls. Keywords you pass directly (thread_id, reasoning, model, memory_config and so on) override the same fields in options.

Python
from maivn import RunOptions

response = agent.invoke(
    'Summarize the account.',
    options=RunOptions(
        thread_id='conversation-1',
        user_id='customer-123',
        max_expense_usd='0.50',
        routing_preference='cost',
    ),
)
FieldWhat it does
thread_id, session_idConversation and run identifiers.
user_idThe customer the run acts for. The default 'sdk-user' owns no private memory; see Memory and Recall.
model, model_directive, planning, system_model_choicesModel choices. Prefer the model= keyword on invoke.
routing_preference'speed', 'cost' or 'quality'. Applies to automatic routing of plain chat requests. Runs with tools or structured output ignore 'speed' and 'cost'; 'quality' moves them up one tier.
reasoning'minimal', 'low', 'medium', 'high', 'xhigh' or 'max'.
max_expense_usdOptional USD ceiling for the run, as a decimal string such as '0.50' (positive, up to 12 decimal places). Capped runs skip paid hosted search, sandbox execution and background memory enrichment.
max_outputOutput-token limit passed to the model.
stream_response, stream_deltasstream_response streams synthesized response updates when supported; stream_deltas=False turns off live text deltas.
resume_from_positionStart replay from an event position.
redaction_preview_idRun on an approved redaction preview; see Preview redaction.
attached_skill_ids, auto_skills, auto_skills_query, auto_skills_limitSkill injection; see Skills.
timeoutHTTP timeout in seconds, applied by the SDK.

tool_execution_timeout (default 600 seconds, values above 600 sent as 600) is sent as the timeout of each SDK tool. A tool that runs longer ends with a timeout, and the value bounds how long a human-approval tool can wait. A tool that outlives the timeout no longer costs you the run's answer: the late result is logged as a warning and the stream continues. max_cycles (1 to 1000) caps the run's tool-calling cycles exactly, then allows one tool-free turn for the answer; the platform never runs more than 20, so larger values behave as 20. A run that still has not finished raises MaivnSDKError with error_code='max_iterations_exceeded'. 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. For a run time limit, use a hosted job and its max_duration_seconds.

#targeted_tools and structured_output

These Agent parameters can be used together. Swarm does not accept them. Tool selection runs before the SDK adds or promotes a requested structured-output model as a final tool.

#targeted_tools — run only these tools

Pass a list of tool names to restrict the turn to those tools (plus their dependencies):

Python
response = agent.invoke(
    [HumanMessage(content='Run diagnostics.')],
    targeted_tools=['fetch_data', 'analyze_data'],
)

#structured_output — validated typed output

Pass a Pydantic type to request that schema and validate the returned result. The builder and inline keyword use the same final-tool execution path, including any required tool work. Invalid output and failed runs still need error handling:

Python
from pydantic import BaseModel, Field

class SentimentAnalysis(BaseModel):
    sentiment: str = Field(..., description='positive, negative, or neutral')
    confidence: float = Field(..., ge=0, le=1)

response = agent.structured_output(SentimentAnalysis).invoke(
    [HumanMessage(content='Analyze: "I love this product!"')]
)
print(response.result)  # a validated SentimentAnalysis instance

The structured_output= parameter on invoke() is the advanced, inline form of the same idea. For most code, prefer agent.structured_output(Model).invoke(...). See Structured Output for the full comparison with the final_tool pattern.

#Selection and final-tool rules

  • targeted_tools selects registered tools and their declared tool dependencies. Empty or unknown selections raise ValueError.
  • structured_output=Model then adds or promotes that model as a forced final constructor. It can be combined with targeted tool selection.
  • Without a structured-output model, force_final_tool=True requires a registered final tool. When targeting tools, include the intended final tool in the selection.

#Running many at once

When you have a list of independent requests, batch() runs them concurrently and returns the responses in input order:

Python
batch_inputs = [
    [HumanMessage(content='Summarize ticket A')],
    [HumanMessage(content='Summarize ticket B')],
    [HumanMessage(content='Summarize ticket C')],
]

responses = agent.batch(batch_inputs, max_concurrency=3)
for response in responses:
    print(response.response)
  • Each input item is passed as the first argument to invoke(), so for an Agent each item is normally a Sequence[BaseMessage].
  • max_concurrency caps how many run at once (must be >= 1; anything else raises ValueError). Leave it unset and both batch() and abatch() use min(32, os.cpu_count() + 4), capped at the number of inputs. An empty input list returns [].
  • Any keyword invoke() accepts can be passed once and is shared by every item (for example model='fast' or force_final_tool=True).
  • Order is preserved even when calls finish out of order. By default an exception in any one call is raised to the caller. Pass return_exceptions=True to get the exception in that item's place while the other items still return, so the result

is a list[InvokeResponse | BaseException].

abatch() is the async variant with the same semantics:

Python
responses = await agent.abatch(batch_inputs, max_concurrency=3)
Note Batch items are independent runs. Only share a thread_id across items when you intentionally want concurrent calls writing to the same conversation.

#Scheduling a run later

Use cron or interval for a durable remote trigger (the default), or pass mode='local' for the in-process compatibility scheduler. at is the local one-shot builder. A durable registration needs a key and deployed owner:

Python
trigger = (
    agent.cron('0 9 * * MON-FRI', tz='America/New_York')
    .key('daily-ops-briefing')
    .invoke('Compose the daily ops briefing.')
)

The trigger inherits the agent's agent_id and version (by default its name and version 1). Use .target('agent-123', version=2) to select another deployed target explicitly.

See the Scheduled Invocation guide for the distinct remote trigger and local scheduler lifecycle APIs.

#Advanced: inspect compiled tools

compile_tools() resolves the current local tool metadata and model-visible schemas without executing a request:

Python
tools = agent.compile_tools()
for tool in tools:
    print(tool.name, tool.input_schema)

This does not expose a full serialized invocation request or start a session.

#Next Steps

Live Available Models

Active, tool-capable model IDs accepted by ModelConfig.

Loading models

The current table controls remain available while records load.