-
Notifications
You must be signed in to change notification settings - Fork 476
Claude/anthropic api example 011 c upnhnuk d5q8wan48 cay5 #484
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Daytona39264
wants to merge
2
commits into
github:main
from
Daytona39264:claude/anthropic-api-example-011CUpnhnukD5q8wan48CAY5
+237
−0
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| # Anthropic API Examples | ||
|
|
||
| This directory contains examples demonstrating how to use the Anthropic API with Python. | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| Before running these examples, you'll need: | ||
|
|
||
| 1. **Python 3.7+** installed on your system | ||
| 2. **Anthropic Python SDK** installed: | ||
| ```bash | ||
| pip install anthropic | ||
| ``` | ||
| 3. **Anthropic API key** - Get one at https://console.anthropic.com/ | ||
|
|
||
| ## Setting Up Your API Key | ||
|
|
||
| ### Option 1: Environment Variable (Recommended) | ||
|
|
||
| Set your API key as an environment variable: | ||
|
|
||
| ```bash | ||
| export ANTHROPIC_API_KEY='your-api-key-here' | ||
| ``` | ||
|
|
||
| For Windows (PowerShell): | ||
| ```powershell | ||
| $env:ANTHROPIC_API_KEY='your-api-key-here' | ||
| ``` | ||
|
|
||
| ### Option 2: Direct in Code (For Testing Only) | ||
|
|
||
| Replace `"your-api-key-here"` in the example files with your actual API key. **Note:** This is not recommended for production code or code that will be committed to version control. | ||
|
|
||
| ## Examples | ||
|
|
||
| ### 1. Basic Example (`basic_example.py`) | ||
|
|
||
| The simplest way to get started with the Anthropic API: | ||
|
|
||
| ```bash | ||
| python basic_example.py | ||
| ``` | ||
|
|
||
| This example demonstrates: | ||
| - Initializing the Anthropic client | ||
| - Sending a single message | ||
| - Receiving and printing the response | ||
|
|
||
| ### 2. Advanced Example (`advanced_example.py`) | ||
|
|
||
| A more comprehensive example showcasing various features: | ||
|
|
||
| ```bash | ||
| python advanced_example.py | ||
| ``` | ||
|
|
||
| This example demonstrates: | ||
| - **Simple Conversation**: Basic single-turn interaction | ||
| - **Multi-turn Conversation**: Maintaining context across multiple exchanges | ||
| - **System Prompts**: Customizing Claude's behavior and personality | ||
| - **Streaming Responses**: Receiving responses in real-time as they're generated | ||
|
|
||
| ## Available Models | ||
|
|
||
| The examples use `claude-opus-4-1-20250805`, but you can use other models: | ||
|
|
||
| - `claude-opus-4-1-20250805` - Most capable model for complex tasks | ||
| - `claude-sonnet-4-5-20250929` - Great balance of intelligence and speed | ||
| - `claude-sonnet-4-2-20250514` - Fast and efficient for most tasks | ||
| - `claude-haiku-4-20250514` - Fastest model for simple tasks | ||
|
|
||
| ## Additional Resources | ||
|
|
||
| - [Anthropic API Documentation](https://docs.anthropic.com/) | ||
| - [API Reference](https://docs.anthropic.com/en/api/messages) | ||
| - [Python SDK on GitHub](https://github.com/anthropics/anthropic-sdk-python) | ||
| - [Anthropic Console](https://console.anthropic.com/) | ||
|
|
||
| ## Common Issues | ||
|
|
||
| ### ImportError: No module named 'anthropic' | ||
|
|
||
| Install the Anthropic SDK: | ||
| ```bash | ||
| pip install anthropic | ||
| ``` | ||
|
|
||
| ### Authentication Error | ||
|
|
||
| Make sure your API key is set correctly: | ||
| ```bash | ||
| echo $ANTHROPIC_API_KEY # Should display your key | ||
| ``` | ||
|
|
||
| If not set, export it again: | ||
| ```bash | ||
| export ANTHROPIC_API_KEY='your-api-key-here' | ||
| ``` | ||
|
|
||
| ## Support | ||
|
|
||
| For issues with the Anthropic API, visit: | ||
| - [Anthropic Support](https://support.anthropic.com/) | ||
| - [API Status Page](https://status.anthropic.com/) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| import os | ||
| from anthropic import Anthropic | ||
|
|
||
| # Initialize the client with API key from environment variable | ||
| # This is the recommended approach for production code | ||
| client = Anthropic( | ||
| api_key=os.environ.get("ANTHROPIC_API_KEY") | ||
| ) | ||
|
|
||
| # Example 1: Simple conversation | ||
| def simple_conversation(): | ||
| response = client.messages.create( | ||
| model="claude-opus-4-1-20250805", | ||
| max_tokens=1024, | ||
| messages=[ | ||
| {"role": "user", "content": "Hello! How can I use the Anthropic API?"} | ||
| ] | ||
| ) | ||
| print("Simple Conversation Response:") | ||
| print(response.content[0].text) | ||
| print("\n" + "="*50 + "\n") | ||
|
|
||
| # Example 2: Multi-turn conversation | ||
| def multi_turn_conversation(): | ||
| messages = [ | ||
| {"role": "user", "content": "What is the capital of France?"}, | ||
| {"role": "assistant", "content": "The capital of France is Paris."}, | ||
| {"role": "user", "content": "What is its population?"} | ||
| ] | ||
|
|
||
| response = client.messages.create( | ||
| model="claude-opus-4-1-20250805", | ||
| max_tokens=1024, | ||
| messages=messages | ||
| ) | ||
| print("Multi-turn Conversation Response:") | ||
| print(response.content[0].text) | ||
| print("\n" + "="*50 + "\n") | ||
|
|
||
| # Example 3: System prompt usage | ||
| def with_system_prompt(): | ||
| response = client.messages.create( | ||
| model="claude-opus-4-1-20250805", | ||
| max_tokens=1024, | ||
| system="You are a helpful coding assistant that provides concise, clear explanations.", | ||
| messages=[ | ||
| {"role": "user", "content": "Explain what Python list comprehensions are."} | ||
| ] | ||
| ) | ||
| print("System Prompt Response:") | ||
| print(response.content[0].text) | ||
| print("\n" + "="*50 + "\n") | ||
|
|
||
| # Example 4: Streaming response | ||
| def streaming_example(): | ||
| print("Streaming Response:") | ||
| with client.messages.stream( | ||
| model="claude-opus-4-1-20250805", | ||
| max_tokens=1024, | ||
| messages=[ | ||
| {"role": "user", "content": "Count from 1 to 5 slowly."} | ||
| ] | ||
| ) as stream: | ||
| for text in stream.text_stream: | ||
| print(text, end="", flush=True) | ||
| print("\n" + "="*50 + "\n") | ||
|
|
||
| if __name__ == "__main__": | ||
| # Make sure to set your ANTHROPIC_API_KEY environment variable | ||
| if not os.environ.get("ANTHROPIC_API_KEY"): | ||
| print("Error: Please set the ANTHROPIC_API_KEY environment variable") | ||
| print("Example: export ANTHROPIC_API_KEY='your-api-key-here'") | ||
| exit(1) | ||
|
|
||
| # Run examples | ||
| simple_conversation() | ||
| multi_turn_conversation() | ||
| with_system_prompt() | ||
| streaming_example() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| from anthropic import Anthropic | ||
|
|
||
| # Initialize the client | ||
| client = Anthropic( | ||
| api_key="your-api-key-here" # Replace with your actual API key | ||
| ) | ||
|
|
||
| # Send a message | ||
| response = client.messages.create( | ||
| model="claude-opus-4-1-20250805", | ||
| max_tokens=1000, | ||
| messages=[ | ||
| {"role": "user", "content": "Hello! How can I use the Anthropic API?"} | ||
| ] | ||
| ) | ||
|
|
||
| print(response.content[0].text) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| anthropic>=0.40.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| import os | ||
| from anthropic import Anthropic | ||
|
|
||
| # Get API key from environment variable | ||
| api_key = os.environ.get("ANTHROPIC_API_KEY") | ||
|
|
||
| if not api_key: | ||
| print("Error: ANTHROPIC_API_KEY environment variable not set") | ||
| exit(1) | ||
|
|
||
| # Initialize the client | ||
| client = Anthropic(api_key=api_key) | ||
|
|
||
| print("Testing Anthropic API connection...") | ||
| print("=" * 50) | ||
|
|
||
| # Send a test message | ||
| try: | ||
| response = client.messages.create( | ||
| model="claude-opus-4-1-20250805", | ||
| max_tokens=1000, | ||
| messages=[ | ||
| {"role": "user", "content": "Hello! How can I use the Anthropic API?"} | ||
| ] | ||
| ) | ||
|
|
||
| print("\n✓ API connection successful!") | ||
| print("\nResponse from Claude:") | ||
| print("-" * 50) | ||
| print(response.content[0].text) | ||
| print("-" * 50) | ||
|
|
||
| except Exception as e: | ||
| print(f"\n✗ Error: {e}") | ||
| exit(1) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hardcoding API keys in example code, even as placeholder text, can lead users to accidentally commit real credentials. Consider using environment variables by default (as done in advanced_example.py) or adding a clear warning comment that this approach should never be used in production or committed to version control.