Code:
import anthropic
def get_claude3_response(api_key, user_message):
"""
Sends a user message to Claude 3 and returns the assistant's reply.
Args:
api_key (str): Your Claude 3 API key.
user_message (str): The user's input message.
Returns:
str: The assistant's response.
"""
try:
client = anthropic.Anthropic(api_key=api_key)
message = client.messages.create(
model="claude-3-opus-20240229",
max_tokens=1000,
temperature=0.0,
system="Respond only in Yoda-speak.",
messages=[{"role": "user", "content": user_message}],
)
return message.content
except Exception as e:
return f"Error: {str(e)}"
# Example usage
if __name__ == "__main__":
my_api_key = "your_actual_api_key_here"
user_input = "How are you today?"
response = get_claude3_response(api_key=my_api_key, user_message=user_input)
print(response)
obtain the required Claude 3 API key, follow these steps:
Create an Account:
Visit the Anthropic Console and sign up for a free account if you haven’t already.
Claim Free Credits:
Upon logging in, you’ll notice a banner offering $5 in free credits for testing Claude.
Click on the banner and follow the process (which includes mobile number verification).
Get Your API Key:
From the dashboard, click on “Get API Keys”.
You’ll receive an API key that you can use in your Python code.
Keep in mind that while there is a free credit offer initially, the Claude 3 API usage has pricing tiers based on tokens (MTok = million tokens). Here’s an overview of the pricing for different models: