On this tutorial, we’ll discover the way to create sensible, multi-agent workflows utilizing the Mistral Brokers API’s Handoffs function. This lets completely different brokers work collectively by passing duties to one another, enabling complicated issues to be solved in a modular and environment friendly approach. We’ll construct a system the place brokers collaborate to reply inflation-related questions—performing calculations, fetching information on-line, and creating visualizations—to ship clear, correct, and dynamic responses.
Step 1: Establishing dependencies
Putting in the libraries
pip set up mistralai pydantic
Loading the Mistral API Key
You will get an API key from https://console.mistral.ai/api-keys
from getpass import getpass
MISTRAL_API_KEY = getpass('Enter Mistral API Key: ')
Step 2: Agent Conditions and Setup
Initializing the Agent
from mistralai import CompletionArgs, ResponseFormat, JSONSchema
from pydantic import BaseModel
from mistralai import Mistral
shopper = Mistral(MISTRAL_API_KEY)
Creating the Customized Operate
The adjust_for_inflation perform calculates how a lot a given sum of money could be value after accounting for inflation over time. It makes use of the compound components based mostly on the variety of years and the annual inflation charge. If the tip 12 months is earlier than the beginning 12 months, it returns an error. In any other case, it returns the adjusted worth together with the enter particulars. For instance, adjust_for_inflation(1000, 1899, 2025, 10) reveals what ₹1000 from 1899 could be value in 2025 at 10% inflation.
def adjust_for_inflation(quantity: float, start_year: int, end_year: int, annual_inflation_rate: float):
"""
Calculates inflation-adjusted worth utilizing compound components.
"""
if end_year
Creating Structured Output for Mathematical Reasoning
class CalcResult(BaseModel):
reasoning: str
outcome: str
inflation_tool = {
"kind": "perform",
"perform": {
"title": "adjust_for_inflation",
"description": "Calculate the worth of cash adjusted for inflation over a time interval.",
"parameters": {
"kind": "object",
"properties": {
"quantity": {
"kind": "quantity",
"description": "Authentic sum of money"
},
"start_year": {
"kind": "integer",
"description": "The beginning 12 months for inflation adjustment"
},
"end_year": {
"kind": "integer",
"description": "The ending 12 months for inflation adjustment"
},
"annual_inflation_rate": {
"kind": "quantity",
"description": "Annual inflation charge in p.c"
}
},
"required": ["amount", "start_year", "end_year", "annual_inflation_rate"]
}
}
}
Step 3: Creating the Brokers
Defining the completely different brokers
On this setup, we outline a multi-agent system utilizing Mistral Brokers API to deal with inflation-related financial queries. The principle agent (economics-agent) acts as a coordinator that routes duties to specialised brokers. The inflation-agent performs inflation adjustment calculations utilizing a customized perform. If the inflation charge is lacking from the question, the websearch-agent fetches it from the web. The calculator-agent handles complicated numerical computations with step-by-step reasoning, whereas the graph-agent makes use of the code interpreter to visualise inflation developments over time. Collectively, these brokers collaborate through handoffs to ship correct, dynamic responses to financial queries.
# Fundamental Agent
economics_agent = shopper.beta.brokers.create(
mannequin="mistral-large-latest",
title="economics-agent",
description="Handles financial queries and delegates inflation calculations.",
)
# Inflation Operate Agent
inflation_agent = shopper.beta.brokers.create(
mannequin="mistral-large-latest",
title="inflation-agent",
description="Agent that calculates inflation-adjusted worth utilizing a customized perform.",
instruments=[inflation_tool],
)
# Net Search Agent
websearch_agent = shopper.beta.brokers.create(
mannequin="mistral-large-latest",
title="websearch-agent",
description="Agent that may search the web for lacking financial information akin to inflation charges.",
instruments=[{"type": "web_search"}]
)
# Calculator Agent
from pydantic import BaseModel
class CalcResult(BaseModel):
reasoning: str
outcome: str
calculator_agent = shopper.beta.brokers.create(
mannequin="mistral-large-latest",
title="calculator-agent",
description="Agent used to make detailed calculations.",
directions="When doing calculations, clarify step-by-step.",
completion_args=CompletionArgs(
response_format=ResponseFormat(
kind="json_schema",
json_schema=JSONSchema(
title="calc_result",
schema=CalcResult.model_json_schema(),
)
)
)
)
# Graph Agent
graph_agent = shopper.beta.brokers.create(
mannequin="mistral-large-latest",
title="graph-agent",
description="Agent that generates graphs utilizing code interpreter.",
directions="Use code interpreter to attract inflation developments.",
instruments=[{"type": "code_interpreter"}]
)
Defining the Handoffs Duties
This configuration defines how brokers delegate duties amongst one another:
- The Fundamental Agent (economics_agent) serves because the entry level and delegates queries both to the inflation_agent (for inflation calculations) or the websearch_agent (to fetch lacking information like inflation charges).
- The inflation_agent, after receiving both the consumer question or web-fetched information, can additional go duties to the calculator_agent (for detailed math) or graph_agent (to visualise developments).
- The websearch_agent can go management to the inflation_agent after retrieving required data, just like the inflation charge.
- calculator_agent and graph_agent are thought-about terminal brokers. Nonetheless, optionally available mutual handoff is enabled in case one must do follow-up work (e.g., graphing a calculated outcome or vice versa).
# Fundamental Agent arms off to inflation_agent and websearch_agent
economics_agent = shopper.beta.brokers.replace(
agent_id=economics_agent.id,
handoffs=[inflation_agent.id, websearch_agent.id]
)
# Inflation Agent can delegate to calculator_agent or graph_agent if deeper evaluation or visualization is required
inflation_agent = shopper.beta.brokers.replace(
agent_id=inflation_agent.id,
handoffs=[calculator_agent.id, graph_agent.id]
)
# Net Search Agent can hand off to inflation_agent (after discovering the lacking charge)
websearch_agent = shopper.beta.brokers.replace(
agent_id=websearch_agent.id,
handoffs=[inflation_agent.id]
)
# Calculator and Graph brokers are terminal--they do not hand off additional
# But when wanted, we may allow them to hand off to one another:
calculator_agent = shopper.beta.brokers.replace(
agent_id=calculator_agent.id,
handoffs=[graph_agent.id] # Elective
)
graph_agent = shopper.beta.brokers.replace(
agent_id=graph_agent.id,
handoffs=[calculator_agent.id] # Elective
)
Step 4: Operating the Agent
Instance A: What’s the present inflation charge in India?
On this instance, the immediate “What’s the present inflation charge in India?” is handed to the economics_agent, which is the primary entry level for dealing with financial queries. For the reason that query requires real-time information that isn’t included within the agent’s static data, the economics_agent mechanically arms off the question to the websearch_agent, which is provided with internet search capabilities.
immediate = "What's the present inflation charge in India?"
response = shopper.beta.conversations.begin(
agent_id=economics_agent.id,
inputs=immediate
)
print(response.outputs[-1].content material[0].textual content)
Instance B: What’s the inflation-adjusted worth of 5,000 from the 12 months 2010 to 2023 with an annual inflation charge of 6.5%. Clarify calculation steps and plot a graph with information labels
This code block sends the immediate to an economics agent, checks if the agent triggers a selected perform name (adjust_for_inflation), executes that perform regionally with the supplied arguments, after which returns the computed outcome again to the agent. Lastly, it prints the agent’s response, which incorporates the inflation calculation clarification, together with the Python code to plot the development.
import json
from mistralai.fashions import FunctionResultEntry
immediate = """What's the inflation-adjusted worth of 5,000 from the 12 months 2010 to 2023 with annual inflation charge of 6.5%.
Clarify calculation steps and plot a graph with information labels"""
response = shopper.beta.conversations.begin(
agent_id=economics_agent.id,
inputs=immediate
)
# Examine for perform name
if response.outputs[-1].kind == "perform.name" and response.outputs[-1].title == "adjust_for_inflation":
args = json.hundreds(response.outputs[-1].arguments)
# Run native perform
function_result = json.dumps(adjust_for_inflation(**args))
# Return outcome to Mistral
result_entry = FunctionResultEntry(
tool_call_id=response.outputs[-1].tool_call_id,
outcome=function_result
)
response = shopper.beta.conversations.append(
conversation_id=response.conversation_id,
inputs=[result_entry]
)
print(response.outputs[-1].content material)
else:
print(response.outputs[-1].content material)
The next code block was returned by the agent to plot the development of inflation-adjusted worth over time.
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 proportion to decimal
# Calculate the variety of years
num_years = end_year - start_year + 1
# Calculate the adjusted worth for annually
years = np.arange(start_year, end_year + 1)
adjusted_values = original_amount * (1 + inflation_rate) ** (years - start_year)
# Plot the graph
plt.determine(figsize=(10, 6))
plt.plot(years, adjusted_values, marker="o", linestyle="-", shade="b")
# Add information labels
for 12 months, worth in zip(years, adjusted_values):
plt.textual content(12 months, worth, f'${worth:.2f}', ha="proper")
# Add titles and labels
plt.title('Inflation-Adjusted Worth Over Time')
plt.xlabel('Yr')
plt.ylabel('Adjusted Worth')
# Save the plot as a picture
plt.savefig('inflation_adjusted_value.png')
# Present the plot
plt.present()
Try the Pocket book. All credit score for this analysis goes to the researchers of this challenge. Additionally, be happy to observe us on Twitter and don’t neglect to hitch our 98k+ ML SubReddit and Subscribe to our E-newsletter.