-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintro.py
More file actions
93 lines (76 loc) · 2.87 KB
/
intro.py
File metadata and controls
93 lines (76 loc) · 2.87 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
from anthropic import Anthropic
from dotenv import load_dotenv
load_dotenv()
client = Anthropic()
def calculator(operation, operand1, operand2):
if operation == "add":
return operand1 + operand2
elif operation == "subtract":
return operand1 - operand2
elif operation == "multiply":
return operand1 * operand2
elif operation == "divide":
if operand2 == 0:
raise ValueError("Cannot divide by zero.")
return operand1 / operand2
else:
raise ValueError(f"Unsupported operation: {operation}")
calculator_tool = {
"name": "calculator",
"description": "A simple calculator that performs basic arithmetic operations.",
"input_schema": {
"type": "object",
"properties": {
"operation": {
"type": "string",
"enum": ["add", "subtract", "multiply", "divide"],
"description": "The arithmetic operation to perform."
},
"operand1": {
"type": "number",
"description": "The first operand."
},
"operand2": {
"type": "number",
"description": "The second operand."
}
},
"required": ["operation", "operand1", "operand2"]
}
}
# A relatively simple math problem
# response = client.messages.create(
# model="claude-3-haiku-20240307",
# system="You have access to tools, but only use them when necessary. If a tool is not required, respond as normal",
# messages=[{"role": "user", "content":"Multiply 1984135 by 9343116. Only respond with the result"}],
# max_tokens=400,
# tools=[calculator_tool]
# )
# print(response)
def prompt_claude(prompt):
response = client.messages.create(
model="claude-3-haiku-20240307",
system="You have access to tools, but only use them when necessary. If a tool is not required, respond as normal",
messages=[{"role": "user", "content": prompt}],
max_tokens=400,
tools=[calculator_tool]
)
if response.stop_reason == "tool_use":
tool_use = response.content[-1]
tool_name = tool_use.name
tool_input = tool_use.input
if tool_name == "calculator":
print("Claude wants to use the calculator tool")
operation = tool_input["operation"]
operand1 = tool_input["operand1"]
operand2 = tool_input["operand2"]
try:
result = calculator(operation, operand1, operand2)
print("Calculation result is:", result)
except ValueError as e:
print(f"Error: {str(e)}")
elif response.stop_reason == "end_turn":
print("Claude didn't want to use a tool")
print("Claude responded with:")
print(response.content[0].text)
prompt_claude("Write me a haiku about the ocean")