How to Create a Smart Multi-Agent Workflow using Myster Agents API’s Handoffs Feature

In this tutorial, we will explore how to create a smart, multi-agent workflow using the handoffs of the Mysteral Agents API. This allows different agents to work together, to enable each other to solve the tasks, modular and efficiently. We will create a system where agents collaborate to answer inflation issues-to bring in performing calculations, concentrated nail data and to create visualization-to deliver accurate, accurate and dynamic response.

Step 1: Setting up dependence

Establishing libraries

pip install mistralai pydantic

Loading Mysterl API key

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

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

Step 2: Agent Prerequisites and Setup

Starting agent

from mistralai import CompletionArgs, ResponseFormat, JSONSchema
from pydantic import BaseModel
from mistralai import Mistral

client = Mistral(MISTRAL_API_KEY)

Custom function

Adjust_Fore_Inflation function calculates the amount of amount given to the given amount after the inflation account over time. It uses a compound formula based on the number of years and the annual inflation rate. If the final year is the beginning of the year, it gives an error. Otherwise, it gives a adjustable value with the input details. For example, Adjust_Fore_inflation (1000, 1899, 2025, 10) shows what will be worth $ 1000 out of 1899 on 10% inflation in 2025.

def adjust_for_inflation(amount: float, start_year: int, end_year: int, annual_inflation_rate: float):
    """
    Calculates inflation-adjusted value using compound formula.
    """
    if end_year < start_year:
        return {"error": "End year must be greater than or equal to start year."}

    years = end_year - start_year
    adjusted_value = amount * ((1 + annual_inflation_rate / 100) ** years)

    return {
        "original_amount": amount,
        "start_year": start_year,
        "end_year": end_year,
        "inflation_rate": annual_inflation_rate,
        "adjusted_value": round(adjusted_value, 2)
    }

adjust_for_inflation(1000, 1899, 2025, 10)

Creating a structured output for mathematical logic

class CalcResult(BaseModel):
    reasoning: str
    result: str

inflation_tool = {
    "type": "function",
    "function": {
        "name": "adjust_for_inflation",
        "description": "Calculate the value of money adjusted for inflation over a time period.",
        "parameters": {
            "type": "object",
            "properties": {
                "amount": {
                    "type": "number",
                    "description": "Original amount of money"
                },
                "start_year": {
                    "type": "integer",
                    "description": "The starting year for inflation adjustment"
                },
                "end_year": {
                    "type": "integer",
                    "description": "The ending year for inflation adjustment"
                },
                "annual_inflation_rate": {
                    "type": "number",
                    "description": "Annual inflation rate in percent"
                }
            },
            "required": ("amount", "start_year", "end_year", "annual_inflation_rate")
        }
    }
}

Step 3: Creating agents

Definition of different agents

In this setup, we define a multi-agent system using Mystery Agents API to manage financial problems related to inflation. The main agent (Economics-Agent) acts as a conjunctiva that works for special agents. The inflation-agent calculates the arrangement of inflation using a custom function. If the inflation rate is missing from the query, the Websar search-agent receives it from the Internet. Calculator-agent manages complex statistical calculations with step-by-step logic, while graph-agent uses a code interpreter to imagine inflation trends over time. Together, these agents collaborate through handoffs to provide accurate, dynamic response to economic issues.

# Main Agent
economics_agent = client.beta.agents.create(
    model="mistral-large-latest",
    name="economics-agent",
    description="Handles economic queries and delegates inflation calculations.",
)

# Inflation Function Agent
inflation_agent = client.beta.agents.create(
    model="mistral-large-latest",
    name="inflation-agent",
    description="Agent that calculates inflation-adjusted value using a custom function.",
    tools=(inflation_tool),
)

# Web Search Agent
websearch_agent = client.beta.agents.create(
    model="mistral-large-latest",
    name="websearch-agent",
    description="Agent that can search the internet for missing economic data such as inflation rates.",
    tools=({"type": "web_search"})
)


# Calculator Agent
from pydantic import BaseModel

class CalcResult(BaseModel):
    reasoning: str
    result: str

calculator_agent = client.beta.agents.create(
    model="mistral-large-latest",
    name="calculator-agent",
    description="Agent used to make detailed calculations.",
    instructions="When doing calculations, explain step by step.",
    completion_args=CompletionArgs(
        response_format=ResponseFormat(
            type="json_schema",
            json_schema=JSONSchema(
                name="calc_result",
                schema=CalcResult.model_json_schema(),
            )
        )
    )
)

# Graph Agent
graph_agent = client.beta.agents.create(
    model="mistral-large-latest",
    name="graph-agent",
    description="Agent that generates graphs using code interpreter.",
    instructions="Use code interpreter to draw inflation trends.",
    tools=({"type": "code_interpreter"})
)

Defining the responsibilities of Handoffs

This configuration defines how agents assign tasks between each other:

  • The main agent (Economics_Agent) serves as an entry point and assigns queries to inflation_gent (for inflation count) or websers_rogent (to bring missing data such as inflation rates).
  • After receiving inflation_gent, the user query or web-contained data, the calculator can pass_gent (for detailed math) or graph_gent (to imagine trends).
  • WebShurch_Gent can pass control over inflation_gent after receiving the required information as the inflation rate.
  • Calculator_gent and graph_gent are considered terminal agents. However, alternative mutual handoff is capable of (eg, calculated result or .Light graphing) if anyone needs a follow-up function.
# Main Agent hands off to inflation_agent and websearch_agent
economics_agent = client.beta.agents.update(
    agent_id=economics_agent.id,
    handoffs=(inflation_agent.id, websearch_agent.id)
)

# Inflation Agent can delegate to calculator_agent or graph_agent if deeper analysis or visualization is needed
inflation_agent = client.beta.agents.update(
    agent_id=inflation_agent.id,
    handoffs=(calculator_agent.id, graph_agent.id)
)

# Web Search Agent can hand off to inflation_agent (after finding the missing rate)
websearch_agent = client.beta.agents.update(
    agent_id=websearch_agent.id,
    handoffs=(inflation_agent.id)
)

# Calculator and Graph agents are terminal--they don't hand off further
# But if needed, we could let them hand off to each other:
calculator_agent = client.beta.agents.update(
    agent_id=calculator_agent.id,
    handoffs=(graph_agent.id)  # Optional
)

graph_agent = client.beta.agents.update(
    agent_id=graph_agent.id,
    handoffs=(calculator_agent.id)  # Optional
)

Step 4: Running an agent

Example A: What is the current inflation rate in India?

In this example, "What is the current inflation rate in India?" Economics_gent is passed, which is the main entrance point for handling economic questions. The question requires real-time data that is not included in the agent's stable Junowledge, so the Economics_Gent automatically assigns the query to the web search_rogent, equipped with web search capabilities.

prompt = "What is the current inflation rate in India?"
response = client.beta.conversations.start(
    agent_id=economics_agent.id,
    inputs=prompt
)
print(response.outputs(-1).content(0).text)

Example B: What is the inflation-inflated value from 2010 to 2023 with annual inflation rate 6.5%. Explain the calculation steps and make a graph with data labels

This code sends a prompt to the Economics Agent, investigating that the agent triggers a specific function Call L (adjust_for_inflation), providing it locally provides the task, and then reverses the agent's result. Finally, it prints the agent's response, which includes an explosive calculation explanation along the Python Code to plot the trend.

import json

from mistralai.models import FunctionResultEntry

prompt = """What is the inflation-adjusted value of 5,000 from the year 2010 to 2023 with annual inflation rate of 6.5%. 
Explain calculation steps and plot a graph with data labels"""

response = client.beta.conversations.start(
    agent_id=economics_agent.id,
    inputs=prompt
)

# Check for function call
if response.outputs(-1).type == "function.call" and response.outputs(-1).name == "adjust_for_inflation":
    args = json.loads(response.outputs(-1).arguments)

    # Run local function
    function_result = json.dumps(adjust_for_inflation(**args))

    # Return result to Mistral
    result_entry = FunctionResultEntry(
        tool_call_id=response.outputs(-1).tool_call_id,
        result=function_result
    )

    response = client.beta.conversations.append(
        conversation_id=response.conversation_id,
        inputs=(result_entry)
    )

    print(response.outputs(-1).content)
else:
    print(response.outputs(-1).content)

Over time, the following code block was returned by the agent to plot the inflation-btly value trend.

import matplotlib.pyplot as plt
import numpy as np

# Parameters
original_amount = 5000
start_year = 2010
end_year = 2023
inflation_rate = 6.5 / 100  # Convert percentage to decimal

# Calculate the number of years
num_years = end_year - start_year + 1

# Calculate the adjusted value for each year
years = np.arange(start_year, end_year + 1)
adjusted_values = original_amount * (1 + inflation_rate) ** (years - start_year)

# Plot the graph
plt.figure(figsize=(10, 6))
plt.plot(years, adjusted_values, marker="o", linestyle="-", color="b")

# Add data labels
for year, value in zip(years, adjusted_values):
    plt.text(year, value, f'${value:.2f}', ha="right")

# Add titles and labels
plt.title('Inflation-Adjusted Value Over Time')
plt.xlabel('Year')
plt.ylabel('Adjusted Value')

# Save the plot as an image
plt.savefig('inflation_adjusted_value.png')

# Show the plot
plt.show()

Check Notebook. All credit for this research goes to researchers of this project. Also, feel free to follow us Twitter And don't forget to join us 98K+ ML Subredit And subscribe Our newsletter.


I am Jamia Milia Islamia, New Delhi Civil Engineering Graduate (2022) and I am more interested in their application in the data, especially the neural network and in various fields.

Scroll to Top