444 KiB
444 KiB
In [1]:
import boto3
bedrock_client = boto3.client(service_name='bedrock-runtime', region_name="us-west-2")
model_id = "anthropic.claude-3-5-sonnet-20241022-v2:0"In [2]:
messages = [{
"role": "user",
"content": [{"text": "Multiply 1984135 by 9343116. Only respond with the result"}]
}]
inference_config={"maxTokens":400}
# Send the message.
response = bedrock_client.converse(
modelId=model_id,
messages=messages,
inferenceConfig=inference_config,
)In [ ]:
In [3]:
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}")
In [4]:
calculator("multiply",1984135, 9343116)Out [4]:
18538003464660
In [5]:
calculator_tool = {
"toolSpec": {
"name": "calculator",
"description": "A simple calculator that performs basic arithmetic operations.",
"inputSchema": {
"json": {
"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"]
}
}
}
}In [6]:
messages = [{
"role": "user",
"content": [{"text": "Multiply 1984135 by 9343116. Only respond with the result"}]
}]
inference_config={"maxTokens":400}
tool_config = {"tools":[calculator_tool]}
# Send the message.
response = bedrock_client.converse(
modelId=model_id,
messages=messages,
inferenceConfig=inference_config,
toolConfig=tool_config,
)In [7]:
responseOut [7]:
{'ResponseMetadata': {'RequestId': 'b14ffd1a-bc1d-4c3c-9a1f-6430df41e7c6',
'HTTPStatusCode': 200,
'HTTPHeaders': {'date': 'Thu, 14 Nov 2024 19:23:51 GMT',
'content-type': 'application/json',
'content-length': '322',
'connection': 'keep-alive',
'x-amzn-requestid': 'b14ffd1a-bc1d-4c3c-9a1f-6430df41e7c6'},
'RetryAttempts': 0},
'output': {'message': {'role': 'assistant',
'content': [{'toolUse': {'toolUseId': 'tooluse_WuZT0fT3RweHPlnhvLpxJA',
'name': 'calculator',
'input': {'operation': 'multiply',
'operand1': 1984135,
'operand2': 9343116}}}]}},
'stopReason': 'tool_use',
'usage': {'inputTokens': 469, 'outputTokens': 93, 'totalTokens': 562},
'metrics': {'latencyMs': 1587}}In [8]:
response['stopReason']Out [8]:
'tool_use'
In [9]:
response['output']Out [9]:
{'message': {'role': 'assistant',
'content': [{'toolUse': {'toolUseId': 'tooluse_WuZT0fT3RweHPlnhvLpxJA',
'name': 'calculator',
'input': {'operation': 'multiply',
'operand1': 1984135,
'operand2': 9343116}}}]}}In [10]:
tool_requests = response['output']['message']['content'][0]['toolUse']
tool_name = tool_requests["name"]
tool_inputs = tool_requests["input"]
print("The Tool Name Claude Wants To Call:", tool_name)
print("The Inputs Claude Wants To Call It With:", tool_inputs)The Tool Name Claude Wants To Call: calculator
The Inputs Claude Wants To Call It With: {'operation': 'multiply', 'operand1': 1984135, 'operand2': 9343116}
In [11]:
operation = tool_inputs["operation"]
operand1 = tool_inputs["operand1"]
operand2 = tool_inputs["operand2"]
result = calculator(operation, operand1, operand2)
print("RESULT IS", result)RESULT IS 18538003464660
In [12]:
messages = [{
"role": "user",
"content": [{"text": "Multiply 1984135 by 9343116. Only respond with the result"}]
}]
inference_config={"maxTokens":400}
tool_config = {"tools":[calculator_tool]}
# Send the message.
response = bedrock_client.converse(
modelId=model_id,
messages=messages,
inferenceConfig=inference_config,
toolConfig=tool_config,
)In [13]:
responseOut [13]:
{'ResponseMetadata': {'RequestId': 'fd808949-f573-4d19-a6b7-7ee3e7bb6aa9',
'HTTPStatusCode': 200,
'HTTPHeaders': {'date': 'Thu, 14 Nov 2024 19:23:53 GMT',
'content-type': 'application/json',
'content-length': '322',
'connection': 'keep-alive',
'x-amzn-requestid': 'fd808949-f573-4d19-a6b7-7ee3e7bb6aa9'},
'RetryAttempts': 0},
'output': {'message': {'role': 'assistant',
'content': [{'toolUse': {'toolUseId': 'tooluse_urHoc59wRCCBdYy5-g_ZRA',
'name': 'calculator',
'input': {'operation': 'multiply',
'operand1': 1984135,
'operand2': 9343116}}}]}},
'stopReason': 'tool_use',
'usage': {'inputTokens': 469, 'outputTokens': 93, 'totalTokens': 562},
'metrics': {'latencyMs': 1821}}In [14]:
messages = [{
"role": "user",
"content": [{"text": "Why is the earth round?"}]
}]
inference_config={"maxTokens":400}
tool_config = {"tools":[calculator_tool]}
# Send the message.
response = bedrock_client.converse(
modelId=model_id,
messages=messages,
system=[{"text": "You have access to tools, but only use them when necessary. If a tool is not required, respond as normal"}],
inferenceConfig=inference_config,
toolConfig=tool_config,
)In [15]:
responseOut [15]:
{'ResponseMetadata': {'RequestId': 'ca04ab66-73d1-4524-9696-be1bdf49a044',
'HTTPStatusCode': 200,
'HTTPHeaders': {'date': 'Thu, 14 Nov 2024 19:24:01 GMT',
'content-type': 'application/json',
'content-length': '1459',
'connection': 'keep-alive',
'x-amzn-requestid': 'ca04ab66-73d1-4524-9696-be1bdf49a044'},
'RetryAttempts': 0},
'output': {'message': {'role': 'assistant',
'content': [{'text': "The Earth is round (technically an oblate spheroid) due to fundamental physics, not because of a calculation, so I'll explain without using any tools.\n\nThe Earth's spherical shape is primarily due to gravity. Here's why:\n\n1. Gravitational force: When the Earth was forming billions of years ago, matter was pulled together by mutual gravitational attraction. This force pulls equally from all directions toward the center of mass.\n\n2. Hydrostatic equilibrium: When an object is massive enough, its own gravity overcomes the rigid forces in the material it's made of. This causes the object to deform until the gravitational forces are balanced, resulting in a spherical shape.\n\n3. Rotation effect: The Earth isn't perfectly spherical because its rotation causes a slight bulging at the equator and flattening at the poles, making it an oblate spheroid.\n\nAny object in space with sufficient mass (generally above 1000 kilometers in diameter) will naturally form into a spherical shape due to these gravitational effects. This is why other large celestial bodies like the Sun, Moon, and other planets are also spherical.\n\nThis is a fundamental result of physics and gravitational forces rather than something that requires calculation or specific tools to explain."}]}},
'stopReason': 'end_turn',
'usage': {'inputTokens': 482, 'outputTokens': 270, 'totalTokens': 752},
'metrics': {'latencyMs': 8488}}In [16]:
response['stopReason']Out [16]:
'end_turn'
In [17]:
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 = {
"toolSpec": {
"name": "calculator",
"description": "A simple calculator that performs basic arithmetic operations.",
"inputSchema": {
"json": {
"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"]
}
}
}
}
def prompt_claude(prompt):
messages = [{
"role": "user",
"content": [{"text": prompt}]
}]
inference_config={"maxTokens":400}
tool_config = {"tools":[calculator_tool]}
# Send the message.
response = bedrock_client.converse(
modelId=model_id,
messages=messages,
inferenceConfig=inference_config,
toolConfig=tool_config,
)
stop_reason = response['stopReason']
if stop_reason == 'tool_use':
# Tool use requested. Call the tool and send the result to the model.
msg = {
"role": "assistant",
"content": [{"text": response['output']['message']["content"][0]["text"]}]
}
messages.append(msg)
tool_requests = response['output']['message']['content'][-1]
if response["stopReason"] == "tool_use":
tool = tool_requests['toolUse']
if tool['name'] == 'calculator':
result = calculator(tool['input']['operation'], tool['input']['operand1'], tool['input']['operand2'])
print("Calculation result is:", result)
elif stop_reason== "end_turn":
print("result is:", response['output']['message']['content'][0]["text"])
In [18]:
prompt_claude("I had 23 chickens but 2 flew away. How many are left?")Calculation result is: 21
In [19]:
prompt_claude("What is 201 times 2")Calculation result is: 402
In [ ]:
prompt_claude("Write me a haiku about the ocean")In [ ]:
import wikipedia
def generate_wikipedia_reading_list(research_topic, article_titles):
wikipedia_articles = []
for t in article_titles:
results = wikipedia.search(t)
try:
page = wikipedia.page(results[0])
title = page.title
url = page.url
wikipedia_articles.append({"title": title, "url": url})
except:
continue
add_to_research_reading_file(wikipedia_articles, research_topic)
def add_to_research_reading_file(articles, topic):
with open("output/research_reading.md", "a", encoding="utf-8") as file:
file.write(f"## {topic} \n")
for article in articles:
title = article["title"]
url = article["url"]
file.write(f"* [{title}]({url}) \n")
file.write(f"\n\n")In [ ]:
# Here's your starter code!
import wikipedia
def generate_wikipedia_reading_list(research_topic, article_titles):
wikipedia_articles = []
for t in article_titles:
results = wikipedia.search(t)
try:
page = wikipedia.page(results[0])
title = page.title
url = page.url
wikipedia_articles.append({"title": title, "url": url})
except:
continue
add_to_research_reading_file(wikipedia_articles, research_topic)
def add_to_research_reading_file(articles, topic):
with open("output/research_reading.md", "a", encoding="utf-8") as file:
file.write(f"## {topic} \n")
for article in articles:
title = article["title"]
url = article["url"]
file.write(f"* [{title}]({url}) \n")
file.write(f"\n\n")
def get_research_help(topic, num_articles=3):
#Implement this function!
pass