Handoffs

Lorsque vous créez et utilisez des Agents, souvent avec accès à des outils spécifiques, il arrive que vous souhaitiez appeler d'autres Agents en cours d'action. Pour élaborer et concevoir des workflows pour diverses tâches que vous souhaitez automatiser, cette capacité à confier des tâches aux Agents ou à transférer une conversation à d'autres agents s'appelle Handoffs.

handoffs_graph
Créer un workflow agentique

Créer un workflow agentique

Lorsque vous créez un workflow basé sur les Handoffs, vous devez d'abord créer tous les Agents que votre workflow utilisera. Il n'y a aucune limite au nombre de Handoffs chaînés qu'un workflow peut avoir. Vous êtes libre de créer plusieurs Agents utilisant divers outils, modèles et handoffs, et d'orchestrer votre propre workflow à l'aide de ces Agents.

Créer plusieurs Agents

Créer plusieurs Agents

handoffs_graph

Commençons par créer divers Agents avec plusieurs tâches et capacités.

from mistralai.client import CompletionArgs, ResponseFormat, JSONSchema
from pydantic import BaseModel

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

# Create your agents
finance_agent = client.beta.agents.create(
    model="mistral-large-latest",
    description="Agent used to answer financial related requests",
    name="finance-agent",
)
web_search_agent = client.beta.agents.create(
    model="mistral-large-latest",
    description="Agent that can search online for any information if needed",
    name="websearch-agent",
    tools=[{"type": "web_search"}],
)
ecb_interest_rate_agent = client.beta.agents.create(
    model="mistral-large-latest",
    description="Can find the current interest rate of the European central bank",
    name="ecb-interest-rate-agent",
    tools=[
        {
            "type": "function",
            "function": {
                "name": "get_european_central_bank_interest_rate",
                "description": "Retrieve the real interest rate of European central bank.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "date": {
                            "type": "string",
                        },
                    },
                    "required": [
                        "date",
                    ]
                },
            },
        },
    ],
)
graph_agent = client.beta.agents.create(
    model="mistral-large-latest",
    name="graph-drawing-agent",
    description="Agent used to create graphs using the code interpreter tool.",
    instructions="Use the code interpreter tool when you have to draw a graph.",
    tools=[{"type": "code_interpreter"}]
)
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 what you are doing.",
    completion_args=CompletionArgs(
          response_format=ResponseFormat(
            type="json_schema",
            json_schema=JSONSchema(
                name="calc_result",
                schema=CalcResult.model_json_schema(),
            )
        )
    )
)
Définir les responsabilités des Handoffs

Définir les responsabilités des Handoffs

handoffs_graph

Une fois tous nos Agents créés, nous mettons à jour nos Agents précédemment définis avec une liste de handoffs disponibles.

# Allow the finance_agent to handoff the conversation to the ecb_interest_rate_agent or web_search_agent
finance_agent = client.beta.agents.update(
    agent_id=finance_agent.id,
    handoffs=[ecb_interest_rate_agent.id, web_search_agent.id]
)

# Allow the ecb_interest_rate_agent to handoff the conversation to the graph_agent or calculator_agent
ecb_interest_rate_agent = client.beta.agents.update(
    agent_id=ecb_interest_rate_agent.id,
    handoffs=[graph_agent.id, calculator_agent.id]
)

# Allow the web_search_agent to handoff the conversation to the graph_agent or calculator_agent
web_search_agent = client.beta.agents.update(
    agent_id=web_search_agent.id,
    handoffs=[graph_agent.id, calculator_agent.id]
)
Fonctionnement

Fonctionnement

Notre workflow et son comportement sont définis, nous pouvons maintenant l'exécuter.

Nous avons créé 5 agents, dont certains ont accès à des outils intégrés, et d'autres à des outils locaux comme get_european_central_bank_interest_rate.

Il est désormais possible d'avoir une chaîne d'actions en envoyant une requête au finance_agent.

Nous fournissons également le paramètre handoff_execution, qui dispose actuellement de deux modes : server ou client.

  • server : exécute le handoff comme prévu en interne sur nos serveurs cloud ; il s'agit du paramètre par défaut.
  • client : lorsqu'un handoff est déclenché, une réponse est fournie directement à l'utilisateur, lui permettant de gérer le handoff avec contrôle.

Déclenchons deux comportements différents à titre d'exemples :

« Récupère le taux d'intérêt actuel de la banque centrale américaine et calcule l'effet composé si l'on investit pour les 10 prochaines années »

Le premier exemple demande le taux d'intérêt de la banque centrale américaine, nous nous attendons donc à impliquer le websearch-agent puis à calculer l'intérêt composé sur 10 ans. Cela devrait utiliser le calculator-agent pour effectuer ce calcul.

handoffs_graph_examplea
response = client.beta.conversations.start(
    agent_id=finance_agent.id,
    inputs="Fetch the current US bank interest rate and calculate the compounded effect if investing for the next 10y"
)
Événements de sortie

Événements de sortie

Ci-dessous, vous pouvez voir les événements de sortie de la conversation dans l'ordre d'apparition pour l'exemple ci-dessus.

Conversation started: conv_067f7fce0aba70728000b32dcb0ac7e5

## Event type: agent.handoff

agent_id='ag_067f7fce04517b60800013b213ff2acb' agent_name='websearch-agent' object='conversation.entry' type='agent.handoff' created_at=datetime.datetime(2025, 4, 10, 17, 16, 18, 952817, tzinfo=TzInfo(UTC)) id='handoff_067f7fce2f3f7423800094104f3e3589'


## Event type: tool.execution

name='web_search' object='conversation.entry' type='tool.execution' created_at=datetime.datetime(2025, 4, 10, 17, 16, 23, 12996, tzinfo=TzInfo(UTC)) id='tool_exec_067f7fce7035747e800085153507b345'


## Event type: message.output

content=[TextChunk(text='The current US bank interest rate is 4.50 percent', type='text'), ToolReferenceChunk(tool='web_search', title='United States Fed Funds Interest Rate', type='tool_reference', url='https://tradingeconomics.com/united-states/interest-rate'), TextChunk(text='.\n\nI will now handoff the conversation to the calculator agent to calculate the compounded effect if investing for the next 10 years.', type='text')] object='conversation.entry' type='message.output' created_at=datetime.datetime(2025, 4, 10, 17, 16, 23, 14612, tzinfo=TzInfo(UTC)) id='msg_067f7fce703b7e01800045b2309a0750' agent_id='ag_067f7fce04517b60800013b213ff2acb' model='mistral-medium-latest' role='assistant'


## Event type: agent.handoff

agent_id='ag_067f7fce017f71a580001bf69f2cc11e' agent_name='calculator-agent' object='conversation.entry' type='agent.handoff' created_at=datetime.datetime(2025, 4, 10, 17, 16, 23, 14726, tzinfo=TzInfo(UTC)) id='handoff_067f7fce703c753680006aedb42ba7b7'


## Event type: message.output

content=' {"result": "The future value of the investment after 10 years is $1,540.10.", "reasoning": "To calculate the compounded effect of investing at the current US bank interest rate of 4.50% for the next 10 years, we use the formula for compound interest: A = P(1 + r/n)^(nt), where A is the amount of money accumulated after n years, including interest. P is the principal amount (the initial amount of money). r is the annual interest rate (decimal). n is the number of times that interest is compounded per year. t is the time the money is invested for, in years. Assuming an initial investment (P) of $1,000, an annual interest rate (r) of 4.50% (or 0.045 as a decimal), compounded annually (n = 1), over 10 years (t = 10): A = 1000(1 + 0.045/1)^(1*10) = 1000(1 + 0.045)^10 = 1000(1.045)^10 ≈ 1540.10. Therefore, the future value of the investment after 10 years is approximately $1,540.10."}' object='conversation.entry' type='message.output' created_at=datetime.datetime(2025, 4, 10, 17, 16, 30, 145207, tzinfo=TzInfo(UTC)) id='msg_067f7fcee2527cf08000744d983639dc' agent_id='ag_067f7fce017f71a580001bf69f2cc11e' model='mistral-medium-latest' role='assistant'