mistralM

Docs

sideBar

Function calling

Définissez une fonction avec un schéma JSON, fournissez-la à un agent et renvoyez le résultat de la fonction dans la conversation.

Le cœur d’un agent repose sur sa capacité à utiliser des outils, qui lui permet d’utiliser et d’appeler des outils et des workflows selon la tâche à accomplir.

Notre API fournit des outils intégrés comme websearch, code_interpreter, image_generation et document_library. Vous pouvez toutefois aussi utiliser le function calling standard en définissant un schéma JSON pour votre fonction.

Vous pouvez aussi enregistrer des serveurs MCP comme connecteurs pour utiliser des outils externes dans les conversations et les agents.

Pour plus d’informations sur le function calling, nous vous recommandons de consulter notre documentation sur le function calling.

Créer un agent

Pour utiliser le function calling, nous pouvons soit créer un agent, soit utiliser directement l’API Conversations sans agent. Nous vous montrons ci-dessous comment créer un agent avec function calling et l’utiliser.

Définir la fonction

Nous devons définir la fonction que le modèle doit appeler en cas de besoin ; ici, il s’agit d’une fonction factice à des fins de démonstration.

from typing import Dict

def get_european_central_bank_interest_rate(date: str) -> Dict[str, str]:
    """
    Retrieve the real interest rate of the European Central Bank for a given date.

    Parameters:
    - date (str): The date for which to retrieve the interest rate in the format YYYY-MM-DD.

    Returns:
    - dict: A dictionary containing the date and the corresponding interest rate.
    """
    # This is a mock implementation. In a real scenario, you would fetch this data from an API or database.
    # For demonstration, let's assume the interest rate is fixed at 2.5% for any date.
    interest_rate = "2.5%"

    return {
        "date": date,
        "interest_rate": interest_rate
    }

Une fois la fonction définie, nous fournissons un schéma correspondant à cette même fonction.

ecb_interest_rate_agent = client.beta.agents.create(
    model="mistral-medium-latest",
    description="Can find the current interest rate of the European central bank",
    name="ecb-interest-rate-agent",
    tools=[
        {
            "type": "function",
            "function": {
                "name": "get_european_central_bank_interest_rate",
                "description": "Retrieve the real interest rate of European central bank.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "date": {
                            "type": "string",
                        },
                    },
                    "required": [
                        "date",
                    ]
                },
            },
        },
    ],
)
Sortie
{
  "model": "mistral-medium-latest",
  "name": "ecb-interest-rate-agent",
  "description": "Can find the current interest rate of the European central bank",
  "id": "ag_06835a34f2c476518000c372a505c2c4",
  "version": 0,
  "created_at": "2025-05-27T11:34:39.175924Z",
  "updated_at": "2025-05-27T11:34:39.175926Z",
  "instructions": "You can provide interest rate and information regarding the European central bank.",
  "tools": [
    {
      "function": {
        "name": "get_european_central_bank_interest_rate",
        "parameters": {
          "type": "object",
          "properties": {
            "date": {
              "type": "string"
            }
          },
          "required": [
            "date"
          ]
        },
        "description": "Retrieve the real interest rate of European central bank.",
        "strict": false
      },
      "type": "function"
    }
  ],
  "completion_args": {
    "stop": null,
    "presence_penalty": null,
    "frequency_penalty": null,
    "temperature": 0.3,
    "top_p": null,
    "max_tokens": null,
    "random_seed": null,
    "prediction": null,
    "response_format": null,
    "tool_choice": "auto"
  },
  "handoffs": null,
  "object": "agent"
}

La création de l’agent renvoie l’objet agent, qui contient l’identifiant de l’agent que nous utiliserons pour démarrer une conversation.

Utiliser un agent

Ensuite, pour l’utiliser, nous démarrons une conversation ou poursuivons une conversation existante.

response = client.beta.conversations.start(
    agent_id=ecb_interest_rate_agent.id,
    inputs=[{"role": "user", "content": "What is the current 2025 real interest rate?"}]
)
Sortie
{
  "conversation_id": "conv_06835a34f58773bd8000f46c0d11e42c",
  "outputs": [
    {
      "tool_call_id": "6TI17yZkV",
      "name": "get_european_central_bank_interest_rate",
      "arguments": "{\"date\": \"2024-06-06\"}",
      "object": "entry",
      "type": "function.call",
      "created_at": "2025-05-27T11:34:39.610632Z",
      "completed_at": null,
      "id": "fc_06835a34f9c47fc88000e0370a295774"
    }
  ],
  "usage": {
    "prompt_tokens": 91,
    "completion_tokens": 29,
    "total_tokens": 120,
    "connector_tokens": null,
    "connectors": null
  },
  "object": "conversation.response"
}

Renvoyer le résultat de la fonction

Le modèle renvoie soit une réponse, soit un appel de fonction : nous devons le détecter et renvoyer le résultat de la fonction attendue.

from mistralai import FunctionResultEntry
import json

if response.outputs[-1].type == "function.call" and response.outputs[-1].name == "get_european_central_bank_interest_rate":

    # Running our function
    function_result = json.dumps(get_european_central_bank_interest_rate(**json.loads(response.outputs[-1].arguments)))

    # Providing the result to our Agent
    user_function_calling_entry = FunctionResultEntry(
        tool_call_id=response.outputs[-1].tool_call_id,
        result=function_result,
    )

    # Retrieving the final response
    response = client.beta.conversations.append(
        conversation_id=response.conversation_id,
        inputs=[user_function_calling_entry]
    )
    print(response.outputs[-1])
else:

    # In case the model did not call our function
    print(response.outputs[-1])
Sortie
{
  "content": "The current interest rate as of June 6, 2024, is 2.5%. This information is relevant for understanding the economic conditions in 2025.",
  "object": "entry",
  "type": "message.output",
  "created_at": "2025-05-27T11:34:40.142767Z",
  "completed_at": "2025-05-27T11:34:40.801117Z",
  "id": "msg_06835a35024879bc80005b1bf9ab0f12",
  "agent_id": "ag_06835a34f2c476518000c372a505c2c4",
  "model": "mistral-medium-latest",
  "role": "assistant"
}