这是indexloc提供的服务,不要输入任何密码
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 105 additions & 0 deletions examples/anthropic-api/README.md
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/)
79 changes: 79 additions & 0 deletions examples/anthropic-api/advanced_example.py
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()
17 changes: 17 additions & 0 deletions examples/anthropic-api/basic_example.py
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
Comment on lines +1 to +5
Copy link

Copilot AI Nov 5, 2025

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.

Suggested change
from anthropic import Anthropic
# Initialize the client
client = Anthropic(
api_key="your-api-key-here" # Replace with your actual API key
import os
from anthropic import Anthropic
# WARNING: Never hardcode API keys in code or commit them to version control.
# Always use environment variables for secrets in production and development.
# Initialize the client
api_key = os.environ.get("ANTHROPIC_API_KEY")
if not api_key:
raise RuntimeError("Please set the ANTHROPIC_API_KEY environment variable.")
client = Anthropic(
api_key=api_key

Copilot uses AI. Check for mistakes.
)

# 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)
1 change: 1 addition & 0 deletions examples/anthropic-api/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
anthropic>=0.40.0
35 changes: 35 additions & 0 deletions examples/anthropic-api/test_api.py
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)