typescriptadvanced
Anthropic Claude Tool Use Pattern
Implement tool/function calling with Claude using the Anthropic SDK for agentic workflows.
typescriptPress ⌘/Ctrl + Shift + C to copy
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
const tools: Anthropic.Tool[] = [
{
name: 'get_weather',
description: 'Get current weather for a location',
input_schema: {
type: 'object',
properties: {
location: { type: 'string', description: 'City name' },
unit: { type: 'string', enum: ['celsius', 'fahrenheit'] },
},
required: ['location'],
},
},
];
async function executeTool(name: string, input: Record<string, unknown>): Promise<string> {
switch (name) {
case 'get_weather':
return JSON.stringify({ temp: 22, condition: 'sunny', location: input.location });
default:
throw new Error(`Unknown tool: ${name}`);
}
}
async function agentChat(userMessage: string): Promise<string> {
const messages: Anthropic.MessageParam[] = [
{ role: 'user', content: userMessage },
];
while (true) {
const response = await anthropic.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
tools,
messages,
});
if (response.stop_reason === 'end_turn') {
const textBlock = response.content.find((b) => b.type === 'text');
return textBlock?.text ?? '';
}
messages.push({ role: 'assistant', content: response.content });
const toolResults: Anthropic.ToolResultBlockParam[] = [];
for (const block of response.content) {
if (block.type === 'tool_use') {
const result = await executeTool(block.name, block.input as Record<string, unknown>);
toolResults.push({ type: 'tool_result', tool_use_id: block.id, content: result });
}
}
messages.push({ role: 'user', content: toolResults });
}
}
const answer = await agentChat('What is the weather in Tokyo?');Use Cases
- agentic workflows
- function calling
- tool-augmented AI
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
Claude Messages API (Anthropic SDK)
Send messages to Claude using the official Anthropic SDK with system prompt and user turn.
Best for: AI assistant
#anthropic#claude
pythonintermediate
OpenAI Function Calling / Tool Use
Let GPT call your functions by defining tool schemas and handling responses.
Best for: AI agents
#ai#openai
pythonbeginner
Anthropic Streaming with Python
Stream Claude responses token by token using the Anthropic Python SDK with context manager.
Best for: streaming responses
#anthropic#claude
typescriptintermediate
OpenAI Tool Calling (Function Calling)
Define tools for GPT to call, parse the response, execute the function, and return results.
Best for: AI agents
#openai#tool-calling