-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2_sequential.ts
More file actions
116 lines (107 loc) · 2.93 KB
/
Copy path2_sequential.ts
File metadata and controls
116 lines (107 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import Anthropic from "@anthropic-ai/sdk";
import dotenv from "dotenv";
import { getLocation } from "../functions/get_location";
import { type WeatherInput, getWeather } from "../functions/get_weather";
dotenv.config();
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
// シーケンシャル実行パターン
async function sequentialToolUse() {
const tools = [
{
name: "get_location",
description: "ユーザーの現在位置を取得します",
input_schema: {
type: "object" as const,
properties: {},
required: [],
},
},
{
name: "get_weather",
description: "指定された場所の天気情報を取得します",
input_schema: {
type: "object" as const,
properties: {
location: {
type: "string" as const,
description: "場所(例:東京)",
},
},
required: ["location"],
},
},
];
console.log("モデルに問い合わせ...");
const locationResponse = await anthropic.messages.create({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1000,
messages: [
{
role: "user",
content: "現在地の天気を教えて",
},
],
tools,
});
console.log("Location Response:", JSON.stringify(locationResponse, null, 2));
// 位置情報を使って天気を取得
if (locationResponse.stop_reason === "tool_use") {
const locationContent =
locationResponse.content[locationResponse.content.length - 1];
if (locationContent.type === "tool_use") {
try {
console.log("ツール実行..位置情報を取得...");
const locationResult = await getLocation();
console.log(
"Location Result:",
JSON.stringify(locationResult, null, 2),
);
console.log("モデルに問い合わせ...(最終応答)");
const weatherResponse = await anthropic.messages.create({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1000,
messages: [
{
role: "user",
content: "現在地の天気を教えて",
},
{
role: "assistant",
content: JSON.stringify(locationContent),
},
{
role: "user",
content: JSON.stringify(locationResult),
},
],
tools,
});
console.log(
"Weather Response:",
JSON.stringify(weatherResponse, null, 2),
);
// 天気情報の取得
if (weatherResponse.stop_reason === "tool_use") {
const weatherContent =
weatherResponse.content[weatherResponse.content.length - 1];
if (weatherContent.type === "tool_use") {
const toolArgs = weatherContent.input as WeatherInput;
console.log(
`ツール実行..天気を取得...引数: ${JSON.stringify(toolArgs)}`,
);
const weatherResult = await getWeather(toolArgs);
console.log(
"Weather Result:",
JSON.stringify(weatherResult, null, 2),
);
}
}
} catch (error) {
console.error("Error:", error);
}
}
}
}
sequentialToolUse().catch(console.error);