«`html
Understanding the Target Audience
The primary audience for this tutorial includes AI developers, business analysts, and product managers who are interested in leveraging AI to enhance business operations. They are typically tech-savvy professionals who understand programming and data analysis concepts.
Key pain points for this audience include:
- Difficulty in integrating multiple AI agents for collaborative tasks.
- Challenges in optimizing workflows for efficiency and accuracy.
- Need for clear documentation and examples to implement AI solutions effectively.
Goals of the audience include:
- Creating scalable and efficient multi-agent systems.
- Improving response accuracy in AI-driven applications.
- Enhancing the ability to visualize and interpret data-driven insights.
Interests span across AI technology advancements, workflow optimization strategies, and practical applications of AI in business management. Communication preferences lean towards concise, technical documentation with clear examples and step-by-step guides.
Creating Smart Multi-Agent Workflows Using the Mistral Agents API’s Handoffs Feature
This tutorial explores how to create smart, multi-agent workflows utilizing the Mistral Agents API’s handoffs feature. This functionality allows different agents to collaborate by passing tasks to one another, solving complex problems in a modular and efficient manner. We will construct a system where agents collaborate to address inflation-related questions—conducting calculations, fetching data online, and generating visualizations—to provide clear, accurate, and dynamic responses.
Step 1: Setting Up Dependencies
Installing the Libraries
Use the following command to install the necessary libraries:
pip install mistralai pydantic
Loading the Mistral API Key
Retrieve your API key from Mistral API Console.
from getpass import getpass
MISTRAL_API_KEY = getpass('Enter Mistral API Key: ')
Step 2: Agent Prerequisites and Setup
Initializing the Agent
from mistralai import CompletionArgs, ResponseFormat, JSONSchema
from pydantic import BaseModel
from mistralai import Mistral
client = Mistral(MISTRAL_API_KEY)
Creating the Custom Function
The adjust_for_inflation
function calculates the value of a given amount adjusted for inflation over time. The input includes the amount, the start and end years, and the annual inflation rate. Below is an example of the function implementation:
def adjust_for_inflation(amount: float, start_year: int, end_year: int, annual_inflation_rate: float):
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)
}
Creating Structured Output for Mathematical Reasoning
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 the Agents
Defining the Different Agents
We will define a multi-agent system using the Mistral Agents API to handle inflation-related economic queries:
# 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
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 Handoffs Responsibilities
This configuration determines how agents delegate tasks among each other:
economics_agent = client.beta.agents.update(
agent_id=economics_agent.id,
handoffs=[inflation_agent.id, websearch_agent.id]
)
inflation_agent = client.beta.agents.update(
agent_id=inflation_agent.id,
handoffs=[calculator_agent.id, graph_agent.id]
)
websearch_agent = client.beta.agents.update(
agent_id=websearch_agent.id,
handoffs=[inflation_agent.id]
)
calculator_agent = client.beta.agents.update(
agent_id=calculator_agent.id,
handoffs=[graph_agent.id]
)
graph_agent = client.beta.agents.update(
agent_id=graph_agent.id,
handoffs=[calculator_agent.id]
)
Step 4: Running the Agents
Example A: What is the Current Inflation Rate in India?
In this example, the prompt “What is the current inflation rate in India?” is sent to the economics_agent
, which serves as the main entry point for handling economic queries. Since real-time data is required, the economics_agent
hands off the query to the websearch_agent
.
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-Adjusted Value of 5,000 from 2010 to 2023 with an Annual Inflation Rate of 6.5%?
This code block sends a prompt to the economics_agent
and checks if a specific function call is triggered:
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
)
if response.outputs[-1].type == "function.call" and response.outputs[-1].name == "adjust_for_inflation":
args = json.loads(response.outputs[-1].arguments)
function_result = json.dumps(adjust_for_inflation(**args))
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)
The following code block can be used to visualize the inflation-adjusted value:
import matplotlib.pyplot as plt
import numpy as np
# Parameters
original_amount = 5000
start_year = 2010
end_year = 2023
inflation_rate = 6.5 / 100
# Calculate the number of years
num_years = end_year - start_year + 1
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 out the Notebook. 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 98k+ ML SubReddit and subscribe to our Newsletter.
```