468 KiB
468 KiB
In [15]:
tools = [
{
"name": "print_sentiment_scores",
"description": "Prints the sentiment scores of a given text.",
"input_schema": {
"type": "object",
"properties": {
"positive_score": {"type": "number", "description": "The positive sentiment score, ranging from 0.0 to 1.0."},
"negative_score": {"type": "number", "description": "The negative sentiment score, ranging from 0.0 to 1.0."},
"neutral_score": {"type": "number", "description": "The neutral sentiment score, ranging from 0.0 to 1.0."}
},
"required": ["positive_score", "negative_score", "neutral_score"]
}
}
]In [5]:
from anthropic import Anthropic
from dotenv import load_dotenv
import json
load_dotenv()
client = Anthropic()
tweet = "I'm a HUGE hater of pickles. I actually despise pickles. They are garbage."
query = f"""
<text>
{tweet}
</text>
Only use the print_sentiment_scores tool.
"""
response = client.messages.create(
model="claude-3-sonnet-20240229",
max_tokens=4096,
tools=tools,
messages=[{"role": "user", "content": query}]
)In [6]:
responseOut [6]:
ToolsBetaMessage(id='msg_01BhF4TkK8vDM6z5m4FNGRnB', content=[TextBlock(text='Here is the sentiment analysis for the given text:', type='text'), ToolUseBlock(id='toolu_01Mt1an3KHEz5RduZRUUuTWz', input={'positive_score': 0.0, 'negative_score': 0.791, 'neutral_score': 0.209}, name='print_sentiment_scores', type='tool_use')], model='claude-3-sonnet-20240229', role='assistant', stop_reason='tool_use', stop_sequence=None, type='message', usage=Usage(input_tokens=374, output_tokens=112))In [9]:
import json
json_sentiment = None
for content in response.content:
if content.type == "tool_use" and content.name == "print_sentiment_scores":
json_sentiment = content.input
break
if json_sentiment:
print("Sentiment Analysis (JSON):")
print(json.dumps(json_sentiment, indent=2))
else:
print("No sentiment analysis found in the response.")Sentiment Analysis (JSON):
{
"positive_score": 0.0,
"negative_score": 0.791,
"neutral_score": 0.209
}
In [ ]:
def analyze_sentiment(content):
query = f"""
<text>
{content}
</text>
Only use the print_sentiment_scores tool.
"""
response = client.messages.create(
model="claude-3-sonnet-20240229",
max_tokens=4096,
tools=tools,
messages=[{"role": "user", "content": query}]
)
json_sentiment = None
for content in response.content:
if content.type == "tool_use" and content.name == "print_sentiment_scores":
json_sentiment = content.input
break
if json_sentiment:
print("Sentiment Analysis (JSON):")
print(json.dumps(json_sentiment, indent=2))
else:
print("No sentiment analysis found in the response.")
In [11]:
analyze_sentiment("OMG I absolutely love taking bubble baths soooo much!!!!")Sentiment Analysis (JSON):
{
"positive_score": 0.8,
"negative_score": 0.0,
"neutral_score": 0.2
}
In [12]:
analyze_sentiment("Honestly I have no opinion on taking baths")Sentiment Analysis (JSON):
{
"positive_score": 0.056,
"negative_score": 0.065,
"neutral_score": 0.879
}
In [ ]:
tool_choice={"type": "tool", "name": "print_sentiment_scores"}In [ ]:
def analyze_sentiment(content):
query = f"""
<text>
{content}
</text>
Only use the print_sentiment_scores tool.
"""
response = client.messages.create(
model="claude-3-sonnet-20240229",
max_tokens=4096,
tools=tools,
tool_choice={"type": "tool", "name": "print_sentiment_scores"},
messages=[{"role": "user", "content": query}]
)
json_sentiment = None
for content in response.content:
if content.type == "tool_use" and content.name == "print_sentiment_scores":
json_sentiment = content.input
break
if json_sentiment:
print("Sentiment Analysis (JSON):")
print(json.dumps(json_sentiment, indent=2))
else:
print("No sentiment analysis found in the response.")In [14]:
tools = [
{
"name": "print_entities",
"description": "Prints extract named entities.",
"input_schema": {
"type": "object",
"properties": {
"entities": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string", "description": "The extracted entity name."},
"type": {"type": "string", "description": "The entity type (e.g., PERSON, ORGANIZATION, LOCATION)."},
"context": {"type": "string", "description": "The context in which the entity appears in the text."}
},
"required": ["name", "type", "context"]
}
}
},
"required": ["entities"]
}
}
]
text = "John works at Google in New York. He met with Sarah, the CEO of Acme Inc., last week in San Francisco."
query = f"""
<document>
{text}
</document>
Use the print_entities tool.
"""
response = client.messages.create(
model="claude-3-sonnet-20240229",
max_tokens=4096,
tools=tools,
messages=[{"role": "user", "content": query}]
)
json_entities = None
for content in response.content:
if content.type == "tool_use" and content.name == "print_entities":
json_entities = content.input
break
if json_entities:
print("Extracted Entities (JSON):")
print(json.dumps(json_entities, indent=2))
else:
print("No entities found in the response.")Extracted Entities (JSON):
{
"entities": [
{
"name": "John",
"type": "PERSON",
"context": "John works at Google in New York."
},
{
"name": "Google",
"type": "ORGANIZATION",
"context": "John works at Google in New York."
},
{
"name": "New York",
"type": "LOCATION",
"context": "John works at Google in New York."
},
{
"name": "Sarah",
"type": "PERSON",
"context": "He met with Sarah, the CEO of Acme Inc., last week in San Francisco."
},
{
"name": "Acme Inc.",
"type": "ORGANIZATION",
"context": "He met with Sarah, the CEO of Acme Inc., last week in San Francisco."
},
{
"name": "San Francisco",
"type": "LOCATION",
"context": "He met with Sarah, the CEO of Acme Inc., last week in San Francisco."
}
]
}
In [27]:
import wikipedia
#tool definition
tools = [
{
"name": "print_article_classification",
"description": "Prints the classification results.",
"input_schema": {
"type": "object",
"properties": {
"subject": {
"type": "string",
"description": "The overall subject of the article",
},
"summary": {
"type": "string",
"description": "A paragaph summary of the article"
},
"keywords": {
"type": "array",
"items": {
"type": "string",
"description": "List of keywords and topics in the article"
}
},
"categories": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string", "description": "The category name."},
"score": {"type": "number", "description": "The classification score for the category, ranging from 0.0 to 1.0."}
},
"required": ["name", "score"]
}
}
},
"required": ["subject","summary", "keywords", "categories"]
}
}
]
#The function that generates the json for a given article subject
def generate_json_for_article(subject):
page = wikipedia.page(subject, auto_suggest=True)
query = f"""
<document>
{page.content}
</document>
Use the print_article_classification tool. Example categories are Politics, Sports, Technology, Entertainment, Business.
"""
response = client.messages.create(
model="claude-3-haiku-20240307",
max_tokens=4096,
tools=tools,
messages=[{"role": "user", "content": query}]
)
json_classification = None
for content in response.content:
if content.type == "tool_use" and content.name == "print_article_classification":
json_classification = content.input
break
if json_classification:
print("Text Classification (JSON):")
print(json.dumps(json_classification, indent=2))
else:
print("No text classification found in the response.")In [29]:
generate_json_for_article("Jeff Goldblum")Text Classification (JSON):
{
"subject": "Jeff Goldblum",
"summary": "Jeffrey Lynn Goldblum is an American actor and musician who has starred in some of the highest-grossing films, such as Jurassic Park and Independence Day. He has had a long and successful career in both film and television, with roles in a wide range of movies and TV shows. Goldblum is also an accomplished jazz musician and has released several albums with his band, The Mildred Snitzer Orchestra.",
"keywords": [
"actor",
"musician",
"Jurassic Park",
"Independence Day",
"film",
"television",
"jazz"
],
"categories": [
{
"name": "Entertainment",
"score": 0.9
}
]
}
In [37]:
generate_json_for_article("Octopus")Text Classification (JSON):
{
"subject": "Octopus",
"summary": "This article provides a comprehensive overview of octopuses, including their anatomy, physiology, behavior, ecology, and evolutionary history. It covers topics such as their complex nervous systems, camouflage and color-changing abilities, intelligence, and relationships with humans.",
"keywords": [
"octopus",
"cephalopod",
"mollusc",
"marine biology",
"animal behavior",
"evolution"
],
"categories": [
{
"name": "Science",
"score": 0.9
},
{
"name": "Nature",
"score": 0.8
}
]
}
In [38]:
generate_json_for_article("Herbert Hoover")Text Classification (JSON):
{
"subject": "Herbert Hoover",
"summary": "The article provides a comprehensive biography of Herbert Hoover, the 31st President of the United States. It covers his early life, career as a mining engineer and humanitarian, his presidency during the Great Depression, and his post-presidency activities.",
"keywords": [
"Herbert Hoover",
"Great Depression",
"Republican Party",
"U.S. President",
"mining engineer",
"Commission for Relief in Belgium",
"U.S. Food Administration",
"Secretary of Commerce",
"Smoot\u2013Hawley Tariff Act",
"New Deal"
],
"categories": [
{
"name": "Politics",
"score": 0.9
},
{
"name": "Business",
"score": 0.7
},
{
"name": "History",
"score": 0.8
}
]
}
In [ ]:
translate("how much does this cost")In [ ]:
print(json.dumps(translations_from_claude, ensure_ascii=False, indent=2))
