Generative AI

How to create a Smart-agent Agent's activity using Agents Agents API's Handoffs

In this lesson, we will examine how we can build a wise work flow, many agents using the Agents Aspents API's Handoffs. This allows different agents to work together by part of each other, making complex problems solve and effective. We will build a program when agents are partnering to respond to statistics related to increases, download online data, and create clear answers – bringing clear, accurate, and powerful answers.

Step 1: Setting to rely on

Installing libraries

pip install mistralai pydantic

Loading the inapor of an Appropriate API

You can get the API key from

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

Step 2: Agent Requirements and Setup

Starts an agent

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

client = Mistral(MISTRAL_API_KEY)

To create a custom activity

Mov_For_For_Inflation is calculated how much the amount provided by cash may be provided after accounting due to time. It uses a compound formula according to the number of years and rate of inflation. If the end year is before the first year, it returns an error. Besides, it returns a fixed amount and installation details. For example, Correctself_for_efor_Indlation (1000, 18999, 2025, 10) Indicates what ₹ 1000 from 1899 can be worth 2029 in 10% inflation.

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)

To create a systematic consequence of mathematical

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

To explain different agents

In this tip, it describes a multiple job agent using the agents Age Age to treat Inflation related questions. A large agent (economy-agent) works as a coordinator who submits the activities to special providers. Inflation-agent makes calculation of prices for prices using custom service. If inflation rate is lost in question, the WebSearch-agent downloads the Internet. Calculator-agent hosts complex mix of steps by step by step, while graph-agent uses Code Translator to visualize infilation trend over time. Together, these people interact with Handoffs to bring about accurate, powerful answers to economic questions.

# 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 bond obligations

This configuration means how agents are sent for functions among each other:

  • The main agent (economic_agent) works as a point of access and submits questions or inflation_agent (by calculating inflation) or Websearch_agent (downloading data as prices).
  • Inflation_agent after receiving a user's question or data downloading data, can convey functions to calculator_agent (with detailed statistics) or graph_agent (visualization (visuality (visuality (visuality (visuality (visuality (s) (visual graph_a scale
  • Websearch_agent can convey the inflation control of inflation_agent after receiving the necessary information, such as prices.
  • Calculator_agedent and graph_agent is considered to be the Genentinal Agents. However, hadoff agrees in a choice to be enabled if any person needs to follow the following work (eg a list of calculated results or vice versa).
# 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 Agent

Example A: What is the price rate available in India?

In this example, soon “is the current level of inflation in India?” Transferred to Economics_agent, a point of entry into handling economic questions. As the question requires real-time data unattended from agent's agent information, Economics_agent automatically removes a question on the WebSearch_gent, installed web search skills.

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)

For example b: What fixed amount of 5,000 prices since 2010 to 2023 at the Revenue of 6.5%. Describe counters and organize graph with data labels

This Block code sends the DMPT to economic agent, assessing whether an agent is graven (repairing_Forfor_inflation), and returns the combined result in the agent. Finally, prints an agent feedback, including a reflection of inflation, and the Python code for processing.

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)

This next block of Code was reinstated by an inflation for inflation.

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()

Look The brochure. All credit for this study goes to research for this project. Also, feel free to follow it Sane and don't forget to join ours 98k + ml subreddit Then sign up for Our newspaper.


I am the student of the community engineering (2022) from Jamia Millia Islamia, New Delhi, and I am very interested in data science, especially neural networks and their application at various locations.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button