Quickstart: call your own functions
In this quickstart, you describe a Python function to a model, let the model ask for it when a question needs it, run the function, and send the result back so the model can answer. It takes about 10 minutes. This pattern, called function calling, connects a model to your own data and systems. For every option, see Function calling.
Before you begin
- A Mistral API key. To create one, see Create your first API key.
- Python 3.10 or later and uv.
Set up your environment
Create a project, install the Mistral SDK, and export your API key:
uv init call-functions --python 3.12 && cd call-functions
uv add mistralai
export MISTRAL_API_KEY="your-api-key"1. Write the script
Create functions.py. It defines get_order_status, describes it to the model as a tool, and runs the three-step exchange:
import json
import os
from mistralai.client import Mistral
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
def get_order_status(order_id: str) -> dict:
"""Your own code. Here, a lookup in a small table."""
orders = {"A-1042": "shipped", "A-1043": "in preparation"}
return {"order_id": order_id, "status": orders.get(order_id, "unknown")}
tools = [
{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Get the delivery status of an order.",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "The order ID, for example A-1042."},
},
"required": ["order_id"],
},
},
}
]
messages = [{"role": "user", "content": "Where is my order A-1042?"}]
# 1. The model reads the question and asks for get_order_status.
response = client.chat.complete(model="mistral-small-latest", messages=messages, tools=tools)
assistant = response.choices[0].message
messages.append(assistant.model_dump(exclude_unset=True))
# 2. Your code runs the function and adds its result to the conversation.
for call in assistant.tool_calls or []:
raw = call.function.arguments
args = json.loads(raw) if isinstance(raw, str) else raw
print(f"Model asked for: {call.function.name}({args})")
result = get_order_status(**args)
messages.append(
{
"role": "tool",
"name": call.function.name,
"tool_call_id": call.id,
"content": json.dumps(result),
}
)
# 3. The model answers the question with the result.
final = client.chat.complete(model="mistral-small-latest", messages=messages, tools=tools)
print(final.choices[0].message.content)The model never runs your code: it returns the name of the function and its arguments, and your script decides whether to run it. In your own code, check the name and the arguments before you run anything.
2. Run it
uv run functions.pyYou should see
The function call that the model asked for, then an answer built from its result. The wording of the answer varies between runs:
Model asked for: get_order_status({'order_id': 'A-1042'})
Your order A-1042 has been shipped.