18.1 C
New York
Sunday, June 8, 2025

The best way to Allow Operate Calling in Mistral Brokers Utilizing the Customary JSON Schema Format


On this tutorial, we’ll exhibit find out how to allow perform calling in Mistral Brokers utilizing the usual JSON schema format. By defining your perform’s enter parameters with a transparent schema, you may make your customized instruments seamlessly callable by the agent—enabling highly effective, dynamic interactions.

We can be utilizing the AviationStack API to retrieve real-time flight standing knowledge, showcasing how exterior APIs might be built-in as callable capabilities inside a Mistral Agent.

Step 1: Establishing dependencies

Putting in the Mistral library

Loading the Mistral API Key

You may get an API key from https://console.mistral.ai/api-keys

from getpass import getpass
MISTRAL_API_KEY = getpass('Enter Mistral API Key: ')

Loading the Aviation Stack API Key

You’ll be able to join a free API key from their dashboard to get began.

AVIATIONSTACK_API_KEY = getpass('Enter Aviation Stack API: ')

Step 2: Defining the Customized Operate

Subsequent, we outline a Python perform get_flight_status() that calls the AviationStack API to retrieve the real-time standing of a flight. The perform accepts an elective flight_iata parameter and returns key particulars corresponding to airline identify, flight standing, departure and arrival airports, and scheduled instances. If no matching flight is discovered, it gracefully returns an error message.

import requests
from typing import Dict
def get_flight_status(flight_iata=None):
    """
    Retrieve flight standing utilizing elective filters: dep_iata, arr_iata, flight_iata.
    """
    params = {
        "access_key": AVIATIONSTACK_API_KEY,
        "flight_iata": flight_iata  
    }

    response = requests.get("http://api.aviationstack.com/v1/flights", params=params)
    knowledge = response.json()

    if "knowledge" in knowledge and knowledge["data"]:
        flight = knowledge["data"][0]
        return {
            "airline": flight["airline"]["name"],
            "flight_iata": flight["flight"]["iata"],
            "standing": flight["flight_status"],
            "departure_airport": flight["departure"]["airport"],
            "arrival_airport": flight["arrival"]["airport"],
            "scheduled_departure": flight["departure"]["scheduled"],
            "scheduled_arrival": flight["arrival"]["scheduled"],
        }
    else:
        return {"error": "No flight discovered for the offered parameters."}

Step 3: Creating the Mistral consumer and Agent

On this step, we create a Mistral Agent that makes use of tool-calling to fetch real-time flight info. The agent, named Flight Standing Agent, is configured to make use of the “mistral-medium-2505” mannequin and is supplied with a customized perform instrument named get_flight_status. This instrument is outlined utilizing a JSON schema that accepts a single required parameter: the flight’s IATA code (e.g., “AI101”). As soon as deployed, the agent can robotically invoke this perform each time it detects a related consumer question, enabling seamless integration between pure language inputs and structured API responses.

from mistralai import Mistral
consumer = Mistral(MISTRAL_API_KEY)

flight_status_agent = consumer.beta.brokers.create(
    mannequin="mistral-medium-2505",
    description="Gives real-time flight standing utilizing aviationstack API.",
    identify="Flight Standing Agent",
    instruments=[
        {
            "type": "function",
            "function": {
                "name": "get_flight_status",
                "description": "Retrieve the current status of a flight by its IATA code (e.g. AI101).",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "flight_iata": {
                            "type": "string",
                            "description": "IATA code of the flight (e.g. AI101)"
                        },
                    },
                    "required": ["flight_iata"]
                }
            }
        }
    ]
)

Step 4: Beginning the Dialog and dealing with Operate Calling

On this step, we provoke a dialog with the Flight Standing Agent by asking a pure language query: “What’s the present standing of AI101?”. The Mistral mannequin detects that it ought to invoke the get_flight_status perform and returns a perform name request. We parse the arguments, run the perform regionally utilizing the AviationStack API, and return the consequence again to the agent utilizing FunctionResultEntry. Lastly, the mannequin incorporates the API response and generates a pure language reply with the present flight standing, which we print to the console.

from mistralai import FunctionResultEntry
import json

# Person begins a dialog
response = consumer.beta.conversations.begin(
    agent_id=flight_status_agent.id,
    inputs=[{"role": "user", "content": "What's the current status of AI101?"}]
)

# Test if mannequin requested a perform name
if response.outputs[-1].kind == "perform.name" and response.outputs[-1].identify == "get_flight_status":
    args = json.masses(response.outputs[-1].arguments)

    # Run the perform
    function_result = json.dumps(get_flight_status(**args))

    # Create consequence entry
    result_entry = FunctionResultEntry(
        tool_call_id=response.outputs[-1].tool_call_id,
        consequence=function_result
    )

    # Return consequence to agent
    response = consumer.beta.conversations.append(
        conversation_id=response.conversation_id,
        inputs=[result_entry]
    )

    print(response.outputs[-1].content material)
else:
    print(response.outputs[-1].content material)

Try the Pocket book on GitHub. All credit score for this analysis goes to the researchers of this mission. Additionally, be at liberty to comply with us on Twitter and don’t overlook to hitch our 95k+ ML SubReddit and Subscribe to our Publication.


I’m a Civil Engineering Graduate (2022) from Jamia Millia Islamia, New Delhi, and I’ve a eager curiosity in Information Science, particularly Neural Networks and their software in varied areas.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles