Create an Agent with the Python API
On this page
Your First Mistral Agent
The previous three lessons established the vocabulary; this one gets your hands on the keyboard. You will create an agent via the Python API, progressively enriching it with instructions, generation parameters, and tools, then launch a conversation with it. The progression is intentionally incremental: each addition modifies an observable behavior, showing you why the same create() method can produce either a generic assistant or an expert with a locked-down style.
Prerequisites
Installation takes two steps. First, the official SDK.
pip install mistralai
Next, make your API key available in the environment rather than hard-coding it in your code. Accidentally committing a key to a repository is the first security incident for any LLM project.
export MISTRAL_API_KEY="your-api-key"
You then build the client in a single line. This client object serves as the entry point for the rest of the lesson.
from mistralai.client import Mistral
import os
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
Create a Minimal Agent
The client.beta.agents.create() method takes three required parameters and several optional ones. Let’s start with the bare minimum.
agent = client.beta.agents.create(
model="mistral-medium-latest",
name="Simple Assistant",
description="A conversational agent with persistent state."
)
print(f"Agent created: {agent.id}")
This agent is minimalist: no specific instructions, no tools, no guardrails. It behaves like an enhanced Chat Completions endpoint with persistence. Note the identifier returned in agent.id: this is what you store on the application side, as it is the only stable reference to this configuration.
Define Behavior with Instructions
Instructions act as the system prompt and are the primary lever for controlling behavior. The example below transforms a generic assistant into a legal expert whose scope, format, and limits are explicitly bounded.
agent = client.beta.agents.create(
model="mistral-large-latest",
name="Legal Expert",
description="Agent specialized in French business law.",
instructions="""You are an expert in French business law.
Rules:
- Always respond in French
- Cite relevant legal articles
- Specify when a question requires a lawyer's opinion
- Structure your responses with headings and lists
- Never give definitive legal advice"""
)
Observe the structure of this prompt: a role definition at the start, followed by numbered rules. This sectional organization helps the model prioritize constraints. Be specific about the role, tone, and limits rather than writing “be helpful.” Above all, anticipate edge cases—what should the agent do if the question falls outside its domain? The line about seeking a lawyer’s opinion addresses this precisely. Finally, treat instructions like code: you will test and revise them multiple times before they produce the expected behavior.
Control Generation
The completion_args configure the sampler, meaning how the model chooses its words. An agent tasked with restating facts does not need the same freedom as a brainstorming agent.
agent = client.beta.agents.create(
model="mistral-large-latest",
name="Precise Agent",
description="Agent with controlled generation parameters.",
instructions="Respond factually and concisely.",
completion_args={
"temperature": 0.2, # Less creativity, more precision
"top_p": 0.9, # Probability nucleus
"max_tokens": 2048 # Response length limit
}
)
temperature— Ranges from 0.0 (deterministic) to 1.0 (creative). For factual tasks, prefer 0.1–0.3.top_p— Cumulative probability filtering. 0.9 is a good default.max_tokens— Strict limit on output tokens.
Equip the Agent with Tools
An agent becomes truly autonomous when it can act beyond text. The following configuration gives it both web access and code execution: faced with a question comparing today’s rates, it will fetch the values and calculate the result without your intervention.
agent = client.beta.agents.create(
model="mistral-large-latest",
name="Research Agent",
description="Agent with web search and code execution.",
instructions="Use web search for current information and code for calculations.",
tools=[
{"type": "web_search"},
{"type": "code_interpreter"}
],
completion_args={"temperature": 0.3, "top_p": 0.95}
)
Available tools include: web_search, web_search_premium, code_interpreter, image_generation, document_library.
Manage the Agent Lifecycle
Your agents are persistent resources on the Mistral side, and you will administer them like any other resource: find them, modify them, delete them. Listing is particularly useful during development, where you quickly end up with dozens of test agents whose IDs you’ve lost.
# List all your agents
agents = client.beta.agents.list()
for a in agents.data:
print(f"{a.name} ({a.id})")
# Retrieve an agent by its ID
agent = client.beta.agents.get(agent_id="ag-xxxxxxxx")
Updates are partial: only the provided fields are modified; the others remain as they are. This allows you to refine instructions in production without redeclaring the entire configuration.
agent = client.beta.agents.update(
agent_id=agent.id,
instructions="New updated instructions.",
tools=[{"type": "web_search"}, {"type": "code_interpreter"}]
)
Deletion, however, is permanent.
client.beta.agents.delete(agent_id=agent.id)
Complete Example
Let’s bring it all together in a fully functional agent: creation, conversation, and reading the response. You can use this script as-is; just change the name and instructions, and you will have your own operational analyst in minutes.
from mistralai.client import Mistral
import os
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
# Create the agent
agent = client.beta.agents.create(
model="mistral-large-latest",
name="Tech Analyst",
description="Analyzes technology trends with web sources.",
instructions="""You are a technology analyst.
- Use web search for recent data
- Always cite your sources
- Structure your analyses into key points""",
tools=[{"type": "web_search"}],
completion_args={"temperature": 0.3}
)
# Start a conversation
response = client.beta.conversations.start(
agent_id=agent.id,
inputs="What are the latest advancements in agentic AI in 2026?"
)
# Display the response
for entry in response.outputs:
if hasattr(entry, "content"):
print(entry.content)
The final loop deserves a moment of attention: it iterates over response.outputs instead of reading a single field because a tool-equipped agent produces multiple entries—the search execution, then the text. This is the key point to watch for in the next lesson.
Key Takeaways
client.beta.agents.create()creates an agent with model, name, and description (required)- Instructions define behavior—this is the primary lever
completion_argscontrol generation (temperature, top_p, max_tokens)- An agent can have multiple tools enabled simultaneously
- Agents are reusable configurations, not conversation instances