Skip to main content

Function calling

Open In Colab

Function calling allows Mistral models to connect to external tools. By integrating Mistral models with external tools such as user defined functions or APIs, users can easily build applications catering to specific use cases and practical problems. In this guide, for instance, we wrote two functions for tracking payment status and payment date. We can use these two tools to provide answers for payment-related queries.

Available models

Currently, function calling is available for the following models:

  • Mistral Large
  • Mistral Small
  • Codestral 22B
  • Ministral 8B
  • Ministral 3B
  • Pixtral 12B
  • Mixtral 8x22B
  • Mistral Nemo

Four steps

At a glance, there are four steps with function calling:

  • User: specify tools and query
  • Model: Generate function arguments if applicable
  • User: Execute function to obtain tool results
  • Model: Generate final answer
drawing

In this guide, we will walk through a simple example to demonstrate how function calling works with Mistral models in these four steps.

Before we get started, let’s assume we have a dataframe consisting of payment transactions. When users ask questions about this dataframe, they can use certain tools to answer questions about this data. This is just an example to emulate an external database that the LLM cannot directly access.

import pandas as pd

# Assuming we have the following data
data = {
'transaction_id': ['T1001', 'T1002', 'T1003', 'T1004', 'T1005'],
'customer_id': ['C001', 'C002', 'C003', 'C002', 'C001'],
'payment_amount': [125.50, 89.99, 120.00, 54.30, 210.20],
'payment_date': ['2021-10-05', '2021-10-06', '2021-10-07', '2021-10-05', '2021-10-08'],
'payment_status': ['Paid', 'Unpaid', 'Paid', 'Paid', 'Pending']
}

# Create DataFrame
df = pd.DataFrame(data)

Step 1. User: specify tools and query

drawing

Tools

Users can define all the necessary tools for their use cases.

  • In many cases, we might have multiple tools at our disposal. For example, let’s consider we have two functions as our two tools: retrieve_payment_status and retrieve_payment_date to retrieve payment status and payment date given transaction ID.
def retrieve_payment_status(df: data, transaction_id: str) -> str:
if transaction_id in df.transaction_id.values:
return json.dumps({'status': df[df.transaction_id == transaction_id].payment_status.item()})
return json.dumps({'error': 'transaction id not found.'})

def retrieve_payment_date(df: data, transaction_id: str) -> str:
if transaction_id in df.transaction_id.values:
return json.dumps({'date': df[df.transaction_id == transaction_id].payment_date.item()})
return json.dumps({'error': 'transaction id not found.'})
  • In order for Mistral models to understand the functions, we need to outline the function specifications with a JSON schema. Specifically, we need to describe the type, function name, function description, function parameters, and the required parameter for the function. Since we have two functions here, let’s list two function specifications in a list.
tools = [
{
"type": "function",
"function": {
"name": "retrieve_payment_status",
"description": "Get payment status of a transaction",
"parameters": {
"type": "object",
"properties": {
"transaction_id": {
"type": "string",
"description": "The transaction id.",
}
},
"required": ["transaction_id"],
},
},
},
{
"type": "function",
"function": {
"name": "retrieve_payment_date",
"description": "Get payment date of a transaction",
"parameters": {
"type": "object",
"properties": {
"transaction_id": {
"type": "string",
"description": "The transaction id.",
}
},
"required": ["transaction_id"],
},
},
}
]
  • Then we organize the two functions into a dictionary where keys represent the function name, and values are the function with the df defined. This allows us to call each function based on its function name.
import functools

names_to_functions = {
'retrieve_payment_status': functools.partial(retrieve_payment_status, df=df),
'retrieve_payment_date': functools.partial(retrieve_payment_date, df=df)
}

User query

Suppose a user asks the following question: “What’s the status of my transaction?” A standalone LLM would not be able to answer this question, as it needs to query the business logic backend to access the necessary data. But what if we have an exact tool we can use to answer this question? We could potentially provide an answer!

messages = [{"role": "user", "content": "What's the status of my transaction T1001?"}]

Step 2. Model: Generate function arguments

drawing

How do Mistral models know about these functions and know which function to use? We provide both the user query and the tools specifications to Mistral models. The goal in this step is not for the Mistral model to run the function directly. It’s to 1) determine the appropriate function to use , 2) identify if there is any essential information missing for a function, and 3) generate necessary arguments for the chosen function.

tool_choice

Users can use tool_choice to speficy how tools are used:

  • "auto": default mode. Model decides if it uses the tool or not.
  • "any": forces tool use.
  • "none": prevents tool use.
import os
from mistralai import Mistral

api_key = os.environ["MISTRAL_API_KEY"]
model = "mistral-large-latest"

client = Mistral(api_key=api_key)
response = client.chat.complete(
model = model,
messages = messages,
tools = tools,
tool_choice = "any",
)
response

We get the response including tool_calls with the chosen function name retrieve_payment_status and the arguments for this function.

Output:

ChatCompletionResponse(id='7cbd8962041442459eb3636e1e3cbf10', object='chat.completion', model='mistral-large-latest', usage=Usage(prompt_tokens=94, completion_tokens=30, total_tokens=124), created=1721403550, choices=[Choices(index=0, finish_reason='tool_calls', message=AssistantMessage(content='', tool_calls=[ToolCall(function=FunctionCall(name='retrieve_payment_status', arguments='{"transaction_id": "T1001"}'), id='D681PevKs', type='function')], prefix=False, role='assistant'))])

Let’s add the response message to the messages list.

messages.append(response.choices[0].message)

Step 3. User: Execute function to obtain tool results

drawing

How do we execute the function? Currently, it is the user’s responsibility to execute these functions and the function execution lies on the user side. In the future, we may introduce some helpful functions that can be executed server-side.

Let’s extract some useful function information from model response including function_name and function_params. It’s clear here that our Mistral model has chosen to use the function retrieve_payment_status with the parameter transaction_id set to T1001.

import json

tool_call = response.choices[0].message.tool_calls[0]
function_name = tool_call.function.name
function_params = json.loads(tool_call.function.arguments)
print("\nfunction_name: ", function_name, "\nfunction_params: ", function_params)

Output

function_name:  retrieve_payment_status 
function_params: {'transaction_id': 'T1001'}

Now we can execute the function and we get the function output '{"status": "Paid"}'.

function_result = names_to_functions[function_name](**function_params)
function_result

Output

'{"status": "Paid"}'

Step 4. Model: Generate final answer

drawing

We can now provide the output from the tools to Mistral models, and in return, the Mistral model can produce a customised final response for the specific user.

messages.append({"role":"tool", "name":function_name, "content":function_result, "tool_call_id":tool_call.id})

response = client.chat.complete(
model = model,
messages = messages
)
response.choices[0].message.content

Output:

The status of your transaction with ID T1001 is "Paid". Is there anything else I can assist you with?