-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path2_tool_agent.py
More file actions
90 lines (75 loc) · 2.77 KB
/
Copy path2_tool_agent.py
File metadata and controls
90 lines (75 loc) · 2.77 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
# %%
import os
import anthropic
from dotenv import load_dotenv
from doc_tools import create_document
load_dotenv()
client = anthropic.Anthropic(
api_key=os.environ.get("ANTHROPIC_API_KEY"),
)
PROMPT = "Generate a spooky story that is 1 paragraph long, and then upload it to Google docs."
TOOL_MAPPING = {
"create_document": create_document,
# "create_document": lambda title, text: print("Successfully created the document"),
}
TOOLS = [
{
"name": "create_document",
"description": "Create a new Google Document with the given title and text",
"input_schema": {
"type": "object",
"properties": {
"title": {
"type": "string",
"description": "The title of the document",
},
"text": {
"type": "string",
"description": "The text to insert into the document body",
}
},
"required": ["title", "text"],
},
},
]
# %%
initial_response = client.messages.create(
model="claude-3-7-sonnet-20250219",
max_tokens=1024,
tools=TOOLS,
messages=[{"role": "user", "content": PROMPT}],
)
print(initial_response.content)
# Response
# [TextBlock(citations=None, text="I'd be happy to create a spooky story for you and upload it to
# Google Docs. Let me write a one-paragraph spooky story and then create the document for you.", type='text'),
# ToolUseBlock(id='toolu_013aFg9xXVp4Z6m7htfEJwXJ', input={'title': 'Spooky Short Story',
# 'text': 'The old mansion at the end of Willow Street ... and escape.'}, name='create_document', type='tool_use')]
# %%
create_doc_tool_request = [block for block in initial_response.content if block.type == "tool_use"][0]
create_doc_tool_reply = {
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": create_doc_tool_request.id,
"content": str(TOOL_MAPPING[create_doc_tool_request.name](**create_doc_tool_request.input)),
}
],
}
created_doc_response = client.messages.create(
model="claude-3-7-sonnet-20250219",
max_tokens=1024,
tools=TOOLS,
messages=[
{"role": "user", "content": PROMPT},
{"role": "assistant", "content": initial_response.content},
create_doc_tool_reply
],
)
print(created_doc_response.content)
# Response
# [TextBlock(citations=None, text='I\'ve created a spooky story and uploaded it to
# Google Docs with the title "Spooky Short Story." The document has been successfully
# created and contains a one-paragraph spooky tale about Sarah\'s unsettling
# experience at an abandoned mansion on Willow Street.', type='text')]