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.
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.
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
Commençons par créer divers agents dotés de tâches et de capacités multiples.
from mistralai import CompletionArgs, ResponseFormat, JSONSchemafrom pydantic import BaseModelclass CalcResult(BaseModel): reasoning: str result: str# Create your agentsfinance_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(), ) ) ))
from mistralai.client.models import CompletionArgs, ResponseFormat, JSONSchemafrom pydantic import BaseModelclass CalcResult(BaseModel): reasoning: str result: str# Create your agentsfinance_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(), ) ) ))
// First, let's make the following importimport { z } from 'zod';import { responseFormatFromZodObject } from '@mistralai/mistralai/extra/structChat.js';//Then, we define and create our agentsconst CalcResult = z.object({ reasoning: z.string(), result: z.string(),});let financeAgent = await client.beta.agents.create({ model: 'mistral-large-latest', description: 'Agent used to answer financial related requests', name: 'finance-agent',});let webSearchAgent = await 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' }],});let ecbInterestRateAgent = await 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: 'getEuropeanCentralBankInterestRate', description: 'Retrieve the real interest rate of European central bank.', parameters: { type: 'object', properties: { date: { type: 'string', }, }, required: ['date'], }, }, }, ],});const graphAgent = await 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' }],});const calculatorAgent = await 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.', completionArgs: { responseFormat: responseFormatFromZodObject(CalcResult), },});
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_agentfinance_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_agentecb_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_agentweb_search_agent = client.beta.agents.update( agent_id=web_search_agent.id, handoffs=[graph_agent.id, calculator_agent.id])
// Allow the financeAgent to handoff the conversation to the ecbInterestRateAgent or webSearchAgentfinanceAgent = await client.beta.agents.update({ agentId: financeAgent.id, updateAgentRequest: { handoffs: [ecbInterestRateAgent.id, webSearchAgent.id], },});// Allow the ecbInterestRateAgent to handoff the conversation to the grapAgent or calculatorAgentecbInterestRateAgent = await client.beta.agents.update({ agentId: ecbInterestRateAgent.id, updateAgentRequest: { handoffs: [graphAgent.id, calculatorAgent.id], },});// Allow the webSearchAgent to handoff the conversation to the graphAgent or calculatorAgentwebSearchAgent = await client.beta.agents.update({ agentId: webSearchAgent.id, updateAgentRequest: { handoffs: [graphAgent.id, calculatorAgent.id], },});
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.
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")
let response = await client.beta.conversations.start({ agentId: financeAgent.id, inputs: 'Fetch the current US bank interest rate and calculate the compounded effect if investing for the next 10y',});
curl --location "https://api.mistral.ai/v1/conversations" \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header "Authorization: Bearer $MISTRAL_API_KEY" \ --data '{ "inputs": "Fetch the current US bank interest rate and calculate the compounded effect if investing for the next 10y", "stream": false, "agent_id": "<agent_id>" }'
É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.handoffagent_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.executionname='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.outputcontent=[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.handoffagent_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.outputcontent=' {"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'
"Given the interest rate of the European Central Bank as of jan 2025, plot a graph of the compounded interest rate over the next 10 years"
Le second exemple demande le taux d’intérêt de la Banque centrale européenne et le tracé d’un graphique des intérêts composés. Un appel de fonction local est alors nécessaire, puisque le ecb-interest-rate-agent sera certainement sollicité.
from mistralai import FunctionResultEntryresponse = client.beta.conversations.start( agent_id=finance_agent.id, inputs="Given the interest rate of the European Central Bank as of jan 2025, plot a graph of the compounded interest rate over the next 10 years")if response.outputs[-1].type == "function.call" and response.outputs[-1].name == "get_european_central_bank_interest_rate": # Add a dummy result for the function call user_entry = FunctionResultEntry( tool_call_id=response.outputs[-1].tool_call_id, result="2.5%", ) response = client.beta.conversations.append( conversation_id=response.conversation_id, inputs=[user_entry] )# A full code snippet to download all generated images and plots from the response could look like so:from mistralai.models import ToolFileChunkfor i, chunk in enumerate(response.outputs[-1].content): # Check if chunk corresponds to a ToolFileChunk if isinstance(chunk, ToolFileChunk): # Download using the ToolFileChunk ID file_bytes = client.files.download(file_id=chunk.file_id).read() # Save the file locally with open(f"plot_generated_{i}.png", "wb") as file: file.write(file_bytes)
from mistralai.client.models import FunctionResultEntryresponse = client.beta.conversations.start( agent_id=finance_agent.id, inputs="Given the interest rate of the European Central Bank as of jan 2025, plot a graph of the compounded interest rate over the next 10 years")if response.outputs[-1].type == "function.call" and response.outputs[-1].name == "get_european_central_bank_interest_rate": # Add a dummy result for the function call user_entry = FunctionResultEntry( tool_call_id=response.outputs[-1].tool_call_id, result="2.5%", ) response = client.beta.conversations.append( conversation_id=response.conversation_id, inputs=[user_entry] )# A full code snippet to download all generated images and plots from the response could look like so:from mistralai.client.models import ToolFileChunkfor i, chunk in enumerate(response.outputs[-1].content): # Check if chunk corresponds to a ToolFileChunk if isinstance(chunk, ToolFileChunk): # Download using the ToolFileChunk ID file_bytes = client.files.download(file_id=chunk.file_id).read() # Save the file locally with open(f"plot_generated_{i}.png", "wb") as file: file.write(file_bytes)
// First, let's add the following imports:import type { FunctionResultEntry, MessageOutputEntry,} from '@mistralai/mistralai/models/components/index.js';// Then, let's start the conversation:response = await client.beta.conversations.start({ agentId: financeAgent.id, inputs: 'Given the interest rate of the European Central Bank as of jan 2025, plot a graph of the compounded interest rate over the next 10 years',});let output = response.outputs[response.outputs.length - 1];if ( output.type === 'function.call' && output.name === 'getEuropeanCentralBankInterestRate') { // Add a dummy result for the function call let userEntry: FunctionResultEntry = { toolCallId: output.toolCallId, result: '2.5%', }; response = await client.beta.conversations.append({ conversationId: response.conversationId, conversationAppendRequest: { inputs: [userEntry], }, });}
curl --location "https://api.mistral.ai/v1/conversations" \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header "Authorization: Bearer $MISTRAL_API_KEY" \ --data '{ "inputs": "Given the interest rate of the European Central Bank as of jan 2025, plot a graph of the compounded interest rate over the next 10 years", "stream": false, "agent_id": "<agent_id>" }'
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_067f7e71523d7be3800005c4ac560a7b## Event type: agent.handoffagent_id='ag_067f7e714f6e751480002beb3bfe0779' agent_name='ecb-interest-rate-agent' object='conversation.entry' type='agent.handoff' created_at=datetime.datetime(2025, 4, 10, 15, 43, 18, 590169, tzinfo=TzInfo(UTC)) id='handoff_067f7e71697176098000aa403030a74e'## Event type: function.calltool_call_id='NqCFiwvSV' name='get_european_central_bank_interest_rate' arguments='{"date": "2025-01-01"}' object='conversation.entry' type='function.call' created_at=datetime.datetime(2025, 4, 10, 15, 43, 20, 173505, tzinfo=TzInfo(UTC)) id='fc_067f7e7182c67b9c80006f27131026a8'## User added event function.result:tool_call_id='NqCFiwvSV' result='2.5%' object='conversation.entry' type='function.result' created_at=None id=None## Event type: agent.handoff:agent_id='ag_067f7e7147e077a280005b4ae524d317' agent_name='graph-drawing-agent' object='conversation.entry' type='agent.handoff' created_at=datetime.datetime(2025, 4, 10, 15, 43, 26, 261436, tzinfo=TzInfo(UTC)) id='handoff_067f7e71e42e7e2080009fc4fd68164a'## Event type: message.output:content="To plot the graph of the compounded interest rate over the next 10 years, we can use the formula for compound interest:\n\n\\[ A = P \\left(1 + \\frac{r}{n}\\right)^{nt} \\]\n\nwhere:\n- \\( A \\) is the amount of money accumulated after n years, including interest.\n- \\( P \\) is the principal amount (the initial amount of money).\n- \\( r \\) is the annual interest rate (decimal).\n- \\( n \\) is the number of times that interest is compounded per year.\n- \\( t \\) is the time the money is invested for, in years.\n\nGiven:\n- The annual interest rate \\( r = 2.5\\% = 0.025 \\).\n- Assuming the interest is compounded annually (\\( n = 1 \\)).\n- We will calculate the compounded amount for each year over the next 10 years.\n\nLet's assume the principal amount \\( P = 1000 \\) (you can choose any amount as it will not affect the rate plot).\n\nWe will calculate the compounded amount for each year and plot it." object='conversation.entry' type='message.output' created_at=datetime.datetime(2025, 4, 10, 15, 43, 39, 385339, tzinfo=TzInfo(UTC)) id='msg_067f7e72b62a768f800022b2504adfc9' agent_id='ag_067f7e7147e077a280005b4ae524d317' model='mistral-medium-latest' role='assistant'## Event type: tool.execution:name='code_interpreter' object='conversation.entry' type='tool.execution' created_at=datetime.datetime(2025, 4, 10, 15, 43, 39, 385463, tzinfo=TzInfo(UTC)) id='tool_exec_067f7e72b62a7e3a800072733a6a57f2'## Event type: message.output:content=[ToolFileChunk(tool='code_interpreter', file_id='40420c94-5f99-477f-8891-943f0defbe3b', type='tool_file', file_name='plot_0.png', file_type='png'), TextChunk(text='\n\nThe graph shows the compounded interest over 10 years with an annual interest rate of 2.5%. The principal amount is set to $1000, and the interest is compounded once per year. The y-axis represents the amount of money, and the x-axis represents the number of years.', type='text')] object='conversation.entry' type='message.output' created_at=datetime.datetime(2025, 4, 10, 15, 43, 39, 898738, tzinfo=TzInfo(UTC)) id='msg_067f7e72be6173f48000e85e9976305a' agent_id='ag_067f7e7147e077a280005b4ae524d317' model='mistral-medium-latest' role='assistant'