Returning Tool Data to Claude
In the previous lesson, your Node.js app intercepted the tool_use block and executed myWeatherFunction("Paris").
Now, let's say the function returned {"temp": "72F", "conditions": "Sunny"}. We need to hand this back to Claude so it can finally answer the user.
The chatHistory Array is Critical
To complete the loop, we must build out our chatHistory array with extreme precision. Claude needs to see exactly what just happened.
1. The User's Request
chatHistory.push({
role: 'user',
content: 'What is the weather in Paris today?'
});
2. Claude's Tool Use Request (The previous API response)
We must append the exact tool_use block that Claude generated back into the history.
chatHistory.push({
role: 'assistant',
content: response.content // Contains the 'tool_use' block from the previous step
});
3. Your Tool Result
Now, we append a new message from the user. This message contains a special tool_result block that hands the data over.
chatHistory.push({
role: 'user',
content: [
{
type: 'tool_result',
tool_use_id: 'toolu_01A09q90qw90ll', // MUST match the ID Claude gave you!
content: JSON.stringify({"temp": "72F", "conditions": "Sunny"})
}
]
});
The Final API Call
Now that our history contains the user's question, Claude's request to use the tool, and our result from the tool, we send it back to the API one more time.
const finalResponse = await anthropic.messages.create({
model: 'claude-3-haiku-20240307',
max_tokens: 500,
tools: tools,
messages: chatHistory // The newly updated history
});
console.log(finalResponse.content[0].text);
// Output: "It is currently 72 degrees and sunny in Paris today!"
Summary of the Loop
- Send the prompt and tools.
- Intercept the
tool_useresponse. - Run your local code.
- Append Claude's
tool_useresponse to the history. - Append your
tool_resultdata to the history. - Send the history back to the API.
- Get the final human-readable answer.
This pattern is the foundation of "Agentic AI." By combining an LLM with external tools, you are building an AI Agent that can take actions in the real world.