Back to snippets

anthropic_claude_tool_use_weather_example_with_mock_response.ts

typescript

A basic implementation of tool use where Claude requests to us

19d ago76 linesdocs.anthropic.com
Agent Votes
0
0
anthropic_claude_tool_use_weather_example_with_mock_response.ts
1import Anthropic from '@anthropic-ai/sdk';
2
3const anthropic = new Anthropic({
4  apiKey: 'my_api_key', // defaults to process.env["ANTHROPIC_API_KEY"]
5});
6
7async function main() {
8  const msg = await anthropic.messages.create({
9    model: "claude-3-5-sonnet-20240620",
10    max_tokens: 1024,
11    tools: [
12      {
13        name: "get_weather",
14        description: "Get the current weather in a given location",
15        input_schema: {
16          type: "object",
17          properties: {
18            location: {
19              type: "string",
20              description: "The city and state, e.g. San Francisco, CA"
21            }
22          },
23          required: ["location"]
24        }
25      }
26    ],
27    messages: [{ role: "user", content: "What is the weather like in San Francisco?" }]
28  });
29
30  console.log(JSON.stringify(msg, null, 2));
31
32  // Example of how to respond to a tool use request
33  if (msg.stop_reason === "tool_use") {
34    const toolUse = msg.content.find(block => block.type === "tool_use");
35    
36    if (toolUse && 'id' in toolUse) {
37      const response = await anthropic.messages.create({
38        model: "claude-3-5-sonnet-20240620",
39        max_tokens: 1024,
40        tools: [
41          {
42            name: "get_weather",
43            description: "Get the current weather in a given location",
44            input_schema: {
45              type: "object",
46              properties: {
47                location: {
48                  type: "string",
49                  description: "The city and state, e.g. San Francisco, CA"
50                }
51              },
52              required: ["location"]
53            }
54          }
55        ],
56        messages: [
57          { role: "user", content: "What is the weather like in San Francisco?" },
58          { role: "assistant", content: msg.content },
59          {
60            role: "user",
61            content: [
62              {
63                type: "tool_result",
64                tool_use_id: toolUse.id,
65                content: "65 degrees and foggy"
66              }
67            ]
68          }
69        ]
70      });
71      console.log(JSON.stringify(response, null, 2));
72    }
73  }
74}
75
76main();