- Studio
- Managed Agents
- Learn
Sessions
Sessions
A session is an agent's work over one or more messages, and the SDK keeps it for you. It holds every message, tool call and result, grouped in turns. Start a session to send an agent more than one message, or to start it from another system.
Where a session runs depends on how you get the agent (see Run modes):
- An agent you build with agents.Agent(...) runs its sessions in your process, until the event loop that started them shuts down. Only that event loop can find a session again.
- An agent you load with agents.Agent.load_from(agent_name=...) is one you deployed with Studio (self-hosted or Mistral-managed), and its sessions run there. Mistral stores each session, and any of your processes can find it again by its id.
Start a session
The examples use the payment reviewer of What an agent is, saved as reviewer.py. The transaction monitoring system calls on_alert for each alert it raises. It starts a session for the alert, and asks the payment reviewer to review it:
import asyncio
from mistralai import agents
from reviewer import payment_reviewer
async def on_alert(alert_id: str) -> agents.TurnState:
session = await payment_reviewer.start_session(idempotency_key=f"alert:{alert_id}")
state = await session.run(
f"Review transaction monitoring alert {alert_id}.",
idempotency_key=f"alert:{alert_id}:review",
)
if isinstance(state, agents.Busy): # another turn runs in this session: wait for it
state = await state.turn.result()
return state
async def main() -> None:
first = await on_alert("4711")
again = await on_alert("4711") # the monitoring system sent the alert twice
print(again.session_id == first.session_id, again.turn_id == first.turn_id)
asyncio.run(main())
Output:
True True
start_session() returns a session handle. session.run() sends a message and returns the turn's record. The alert came twice, but the idempotency keys made the second call return the first session and the first turn, so the review ran once. Use a key from the request, such as the alert id. Agent.start_session says when a reused key raises.
Dropping the handle does not end the session, or its sandbox if it has one. await session.cancel() ends them.
Find a session again
A handle names a session by its id, and getting one sends no request. Store the id, and bind a handle to it when you need the session again. In main() of alerts.py:
session = payment_reviewer.session(first.session_id) # sends no request
state = await session.run("Which case did you open? Reply with the case id only.")
if isinstance(state, agents.Completed):
print(state.text)
await session.cancel() # ends the session
Output:
CASE-4711
session.cancel() ends the session for good: it stops the running turn, and a later message raises agents.SessionTerminatedError. See Session.
Per-session overrides
Pass agent= to add instructions, or to change the model or the reasoning effort, for one session. In main() of alerts.py:
session = await payment_reviewer.start_session(
agent={"additional_instructions": "Answer in French."},
)
state = await session.run("Review transaction monitoring alert 4711.") # the reply is in French
await session.cancel()
The Agent is unchanged: the next session starts from its own settings. See Agent.start_session.
Session inputs
A session input is a value you give one session, such as the review desk that handles its cases. Only the tools and hooks that declare it receive it; the model never sees it. Subclass agents.SessionInput, and declare it on a tool with agents.Depends(). A session of an agent with such a tool cannot start without the value, so reviewer.py adds a second agent, desk_reviewer, and leaves the payment reviewer as it is:
from typing import Annotated
class ReviewDesk(agents.SessionInput):
input_id = "acme.review_desk"
team: str
@agents.tool
async def open_desk_case(
alert_id: str, summary: str, evidence: list[str], desk: Annotated[ReviewDesk, agents.Depends()]
) -> str:
"""Open a case file on a suspicious payment, with the evidence. Returns the case id."""
return f"CASE-{alert_id} in {desk.team}"
desk_reviewer = agents.Agent(
model="mistral-large-4",
name="desk-reviewer",
instructions=payment_reviewer.instructions,
tools=[get_alert, open_desk_case],
)
Pass the value to start_session(), in main() of alerts.py:
session = await desk_reviewer.start_session(
session_inputs={ReviewDesk.input_id: ReviewDesk(team="fraud-paris")},
)
The tool's schema still has only alert_id, summary and evidence. A session input is context, never a credential: give credentials as secrets. SessionInput says how values are checked.
A status, stop reason or kind added after your SDK version reads as agents.UnknownValue: see Unknown values.
Next
- Turns and the turn record: start a turn, and read how it ended.
- Events: follow a session while it works.
- History entries: read a turn's entries, or start a session from existing history.
- Approvals: let a person decide which tool calls run.
- Session lifecycle and listing: how a session ends, its limits, and how to list sessions.
- API reference: Session and Turn and Errors.