MarkTechPost@AI 06月08日 15:16
How to Enable Function Calling in Mistral Agents Using the Standard JSON Schema Format
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文介绍了如何在Mistral Agents中使用标准JSON模式启用函数调用,从而实现强大的动态交互。通过定义清晰的模式,可以使自定义工具无缝地被Agent调用。文章使用AviationStack API检索实时航班状态数据,演示了如何将外部API集成到Mistral Agent中作为可调用函数。详细步骤包括安装依赖、加载API密钥、定义自定义函数、创建Mistral客户端和Agent,以及启动对话和处理函数调用。最终,Agent能够根据用户查询自动调用函数并返回结果,实现自然语言输入与结构化API响应的无缝集成。

✈️ 首先,需要安装Mistral库并加载Mistral API密钥,以便后续操作。

🛠️ 接着,定义一个Python函数`get_flight_status()`,该函数调用AviationStack API以检索航班的实时状态。该函数接受一个可选的`flight_iata`参数,并返回关键信息,如航空公司名称、航班状态、出发和到达机场以及预定时间。如果未找到匹配的航班,则返回错误消息。

🤖 接下来,创建Mistral Agent,该Agent使用工具调用来获取实时航班信息。该Agent配置为使用“mistral-medium-2505”模型,并配备一个名为`get_flight_status`的自定义函数工具。该工具使用JSON模式定义,该模式接受一个必需参数:航班的IATA代码(例如“AI101”)。

💬 最后,启动与Flight Status Agent的对话,例如询问“AI101的当前状态是什么?”。Mistral模型检测到它应该调用`get_flight_status`函数并返回一个函数调用请求。解析参数,使用AviationStack API在本地运行该函数,并将结果返回给Agent。最终,模型整合API响应并生成一个自然语言回复,其中包含当前的航班状态。

In this tutorial, we’ll demonstrate how to enable function calling in Mistral Agents using the standard JSON schema format. By defining your function’s input parameters with a clear schema, you can make your custom tools seamlessly callable by the agent—enabling powerful, dynamic interactions.

We will be using the AviationStack API to retrieve real-time flight status data, showcasing how external APIs can be integrated as callable functions within a Mistral Agent.

Step 1: Setting up dependencies

Installing the Mistral library

Loading the Mistral API Key

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

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

Loading the Aviation Stack API Key

You can sign up for a free API key from their dashboard to get started.

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

Step 2: Defining the Custom Function

Next, we define a Python function get_flight_status() that calls the AviationStack API to retrieve the real-time status of a flight. The function accepts an optional flight_iata parameter and returns key details such as airline name, flight status, departure and arrival airports, and scheduled times. If no matching flight is found, it gracefully returns an error message.

import requestsfrom typing import Dictdef get_flight_status(flight_iata=None):    """    Retrieve flight status using optional 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)    data = response.json()    if "data" in data and data["data"]:        flight = data["data"][0]        return {            "airline": flight["airline"]["name"],            "flight_iata": flight["flight"]["iata"],            "status": 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 found for the provided parameters."}

Step 3: Creating the Mistral client and Agent

In this step, we create a Mistral Agent that uses tool-calling to fetch real-time flight information. The agent, named Flight Status Agent, is configured to use the “mistral-medium-2505” model and is equipped with a custom function tool named get_flight_status. This tool is defined using a JSON schema that accepts a single required parameter: the flight’s IATA code (e.g., “AI101”). Once deployed, the agent can automatically invoke this function whenever it detects a relevant user query, enabling seamless integration between natural language inputs and structured API responses.

from mistralai import Mistralclient = Mistral(MISTRAL_API_KEY)flight_status_agent = client.beta.agents.create(    model="mistral-medium-2505",    description="Provides real-time flight status using aviationstack API.",    name="Flight Status Agent",    tools=[        {            "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: Starting the Conversation and handling Function Calling

In this step, we initiate a conversation with the Flight Status Agent by asking a natural language question: “What’s the current status of AI101?”. The Mistral model detects that it should invoke the get_flight_status function and returns a function call request. We parse the arguments, run the function locally using the AviationStack API, and return the result back to the agent using FunctionResultEntry. Finally, the model incorporates the API response and generates a natural language reply with the current flight status, which we print to the console.

from mistralai import FunctionResultEntryimport json# User starts a conversationresponse = client.beta.conversations.start(    agent_id=flight_status_agent.id,    inputs=[{"role": "user", "content": "What's the current status of AI101?"}])# Check if model requested a function callif response.outputs[-1].type == "function.call" and response.outputs[-1].name == "get_flight_status":    args = json.loads(response.outputs[-1].arguments)    # Run the function    function_result = json.dumps(get_flight_status(**args))    # Create result entry    result_entry = FunctionResultEntry(        tool_call_id=response.outputs[-1].tool_call_id,        result=function_result    )    # Return result to agent    response = client.beta.conversations.append(        conversation_id=response.conversation_id,        inputs=[result_entry]    )    print(response.outputs[-1].content)else:    print(response.outputs[-1].content)

Check out the Notebook on GitHub. All credit for this research goes to the researchers of this project. Also, feel free to follow us on Twitter and don’t forget to join our 95k+ ML SubReddit and Subscribe to our Newsletter.

The post How to Enable Function Calling in Mistral Agents Using the Standard JSON Schema Format appeared first on MarkTechPost.

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

Mistral Agent 函数调用 JSON Schema API集成
相关文章