Quick code tutorial: Call a tool
You can call a tool with an agent programmatically with the watsonx.ai API and SDKs.
This tutorial demonstrates calling a tool with a foundation model. Work with Python, Node.js, or Curl. This example uses the mistralai/mistral-large foundation model, which supports text generation and tool calling. The model is provided
with a tool called add and a message with the question “What is 2 plus 4?“. The response of the model is a message that contains the tool that is called and the method of calling that tool.
You can complete this tutorial in less than 5 minutes.
- Detailed information
- Automating tasks with AI agents
- Building agent-driven workflows with the chat API
- Foundation models that support your use case
Prerequisite
Complete the one-time steps to gather your credentials and other information and prepare your system. See Prerequisite one-time tasks.
Call a tool
Sample JSON response:
{
"id": "chat-a00942a130e84f83bc0090c38c2f419f",
"model_id": "mistralai/mistral-large",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"tool_calls": [
{
"id": "chatcmpl-tool-77cbe4e94d88489383a0c6ed1b644674",
"type": "function",
"function": {
"name": "add",
"arguments": "{\"a\": 2, \"b\": 4}"
}
}
]
},
"finish_reason": "tool_calls"
}
]
}
-
Call a function called
addwith the arguments {a: 2, b: 4}. The function returns the sum of the two numbers, which is 6. This value must be passed to the model as part of the next message, together with the tool call identifier. The message object might look like the following sample:[ { "role": "user", "content": [ { "type": "text", "text": "What is 2 plus 4?" } ] }, { "role": "assistant", "tool_calls": [ { "id": "chatcmpl-tool-77cbe4e94d88489383a0c6ed1b644674", "type": "function", "function": { "name": "add", "arguments": "{\"a\": 2, \"b\": 4}" } } ] }, { "role": "tool", "tool_call_id": "chatcmpl-tool-77cbe4e94d88489383a0c6ed1b644674", "content": [ { "type": "text", "text": "6" } ] } ]
The model responds with a natural language answer that includes the response of the tool call.
Next steps
- Try your request against another foundation model by changing the value of the
model_idparameter. See List supported models. - Try another quick start coding tutorial.
- Try the Build and deploy an agent tutorial.