mistralM

Docs

sideBar

Handoffs

Créez des workflows agentiques dans lesquels des agents confient des tâches ou des conversations entières à d’autres agents en cours d’action.
exclamationMark

L’API Agents v1 sera bientôt obsolète. Créez les nouveaux agents avec l’Agents SDK.

Lorsque vous créez et utilisez des agents, souvent avec accès à des outils spécifiques, il arrive que l’on souhaite appeler d’autres agents en cours d’action. Cette capacité à confier des tâches à des agents ou à transférer une conversation à d’autres agents, qui permet d’élaborer et de concevoir des workflows pour les diverses tâches que vous souhaitez automatiser, s’appelle les Handoffs.

handoffs_graph

Créer un workflow agentique

Pour créer un workflow reposant sur les handoffs, nous devons d’abord créer tous les agents que notre workflow utilisera. Le nombre de handoffs enchaînés dans un workflow n’est pas limité. Vous êtes libre de créer plusieurs agents utilisant divers outils, modèles et handoffs, et d’orchestrer votre propre workflow avec ces agents.

Créer plusieurs agents

handoffs_graph

Commençons par créer divers agents dotés de tâches et de capacités multiples.

from mistralai 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

handoffs_graph

Une fois tous nos agents créés, nous mettons à jour les agents définis précédemment 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

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’enchaîner des actions en envoyant une requête au finance_agent.

Nous fournissons aussi le paramètre handoff_execution, qui propose actuellement deux modes : server ou client.

  • server : exécute le transfert (handoff) comme prévu, en interne sur nos serveurs cloud ; c’est le paramètre par défaut.
  • client : lorsqu’un transfert est déclenché, une réponse est fournie directement à l’utilisateur, ce qui lui permet de gérer lui-même le transfert.

Déclenchons deux comportements différents à titre d’exemple :

"Fetch the current US bank interest rate and calculate the compounded effect if investing for the next 10y"

Le premier exemple demande le taux d’intérêt de la banque centrale américaine : nous nous attendons donc à faire intervenir le websearch-agent, puis à calculer les intérêts composés sur 10 ans. Cela devrait passer par le calculator-agent.

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

Vous trouverez ci-dessous les événements de sortie de la conversation, dans leur 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'