|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Anthropic Claude API Example |
| 4 | +Demonstrates using the Anthropic API with Claude models. |
| 5 | +
|
| 6 | +Requirements: |
| 7 | + pip install anthropic python-dotenv |
| 8 | +
|
| 9 | +Setup: |
| 10 | + 1. Create a .env file in the project root |
| 11 | + 2. Add your Anthropic API key: ANTHROPIC_API_KEY=sk-ant-... |
| 12 | + 3. Get your API key at: https://console.anthropic.com/ |
| 13 | +""" |
| 14 | + |
| 15 | +import os |
| 16 | +from dotenv import load_dotenv |
| 17 | +from anthropic import Anthropic |
| 18 | + |
| 19 | +# Load environment variables |
| 20 | +load_dotenv() |
| 21 | + |
| 22 | +# Initialize Anthropic client |
| 23 | +client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY")) |
| 24 | + |
| 25 | + |
| 26 | +def simple_message(): |
| 27 | + """Basic message example with Claude.""" |
| 28 | + print("=" * 60) |
| 29 | + print("1. Simple Message") |
| 30 | + print("=" * 60) |
| 31 | + |
| 32 | + message = client.messages.create( |
| 33 | + model="claude-3-5-sonnet-20241022", # or "claude-3-opus-20240229", "claude-3-haiku-20240307" |
| 34 | + max_tokens=1024, |
| 35 | + messages=[ |
| 36 | + {"role": "user", "content": "Explain machine learning in one sentence."} |
| 37 | + ] |
| 38 | + ) |
| 39 | + |
| 40 | + print(f"User: Explain machine learning in one sentence.") |
| 41 | + print(f"Claude: {message.content[0].text}\n") |
| 42 | + print(f"Tokens - Input: {message.usage.input_tokens}, Output: {message.usage.output_tokens}") |
| 43 | + print(f"Model: {message.model}\n") |
| 44 | + |
| 45 | + |
| 46 | +def streaming_response(): |
| 47 | + """Stream responses from Claude.""" |
| 48 | + print("=" * 60) |
| 49 | + print("2. Streaming Response") |
| 50 | + print("=" * 60) |
| 51 | + |
| 52 | + print("User: Write a haiku about artificial intelligence.\n") |
| 53 | + print("Claude: ", end="", flush=True) |
| 54 | + |
| 55 | + with client.messages.stream( |
| 56 | + model="claude-3-5-sonnet-20241022", |
| 57 | + max_tokens=1024, |
| 58 | + messages=[ |
| 59 | + {"role": "user", "content": "Write a haiku about artificial intelligence."} |
| 60 | + ] |
| 61 | + ) as stream: |
| 62 | + for text in stream.text_stream: |
| 63 | + print(text, end="", flush=True) |
| 64 | + print("\n") |
| 65 | + |
| 66 | + |
| 67 | +def system_prompt(): |
| 68 | + """Use system prompts to set Claude's behavior.""" |
| 69 | + print("=" * 60) |
| 70 | + print("3. System Prompt") |
| 71 | + print("=" * 60) |
| 72 | + |
| 73 | + message = client.messages.create( |
| 74 | + model="claude-3-5-sonnet-20241022", |
| 75 | + max_tokens=1024, |
| 76 | + system="You are a helpful Python expert who explains concepts clearly and concisely.", |
| 77 | + messages=[ |
| 78 | + {"role": "user", "content": "What is a decorator?"} |
| 79 | + ] |
| 80 | + ) |
| 81 | + |
| 82 | + print("System: You are a helpful Python expert...") |
| 83 | + print("User: What is a decorator?") |
| 84 | + print(f"Claude: {message.content[0].text}\n") |
| 85 | + |
| 86 | + |
| 87 | +def multi_turn_conversation(): |
| 88 | + """Demonstrate multi-turn conversations with Claude.""" |
| 89 | + print("=" * 60) |
| 90 | + print("4. Multi-turn Conversation") |
| 91 | + print("=" * 60) |
| 92 | + |
| 93 | + message = client.messages.create( |
| 94 | + model="claude-3-5-sonnet-20241022", |
| 95 | + max_tokens=1024, |
| 96 | + messages=[ |
| 97 | + {"role": "user", "content": "I'm learning Python. What should I learn first?"}, |
| 98 | + {"role": "assistant", "content": "Great! Start with these fundamentals:\n1. Variables and data types\n2. Control flow (if/else, loops)\n3. Functions\n4. Lists and dictionaries\n\nWould you like me to explain any of these?"}, |
| 99 | + {"role": "user", "content": "Yes, explain functions please."} |
| 100 | + ] |
| 101 | + ) |
| 102 | + |
| 103 | + print("User: I'm learning Python. What should I learn first?") |
| 104 | + print("Claude: [previous response about fundamentals]") |
| 105 | + print("\nUser: Yes, explain functions please.") |
| 106 | + print(f"Claude: {message.content[0].text}\n") |
| 107 | + |
| 108 | + |
| 109 | +def with_vision(): |
| 110 | + """Use Claude's vision capabilities (if using a vision-enabled model).""" |
| 111 | + print("=" * 60) |
| 112 | + print("5. Vision Example (Placeholder)") |
| 113 | + print("=" * 60) |
| 114 | + |
| 115 | + # Note: This requires an image URL or base64 encoded image |
| 116 | + print("Claude supports vision! You can send images like this:") |
| 117 | + print(""" |
| 118 | + message = client.messages.create( |
| 119 | + model="claude-3-5-sonnet-20241022", |
| 120 | + max_tokens=1024, |
| 121 | + messages=[ |
| 122 | + { |
| 123 | + "role": "user", |
| 124 | + "content": [ |
| 125 | + { |
| 126 | + "type": "image", |
| 127 | + "source": { |
| 128 | + "type": "url", |
| 129 | + "url": "https://example.com/image.jpg" |
| 130 | + } |
| 131 | + }, |
| 132 | + { |
| 133 | + "type": "text", |
| 134 | + "text": "What's in this image?" |
| 135 | + } |
| 136 | + ] |
| 137 | + } |
| 138 | + ] |
| 139 | + ) |
| 140 | + """) |
| 141 | + print() |
| 142 | + |
| 143 | + |
| 144 | +def thinking_mode(): |
| 145 | + """Demonstrate extended thinking for complex problems.""" |
| 146 | + print("=" * 60) |
| 147 | + print("6. Complex Reasoning") |
| 148 | + print("=" * 60) |
| 149 | + |
| 150 | + message = client.messages.create( |
| 151 | + model="claude-3-5-sonnet-20241022", |
| 152 | + max_tokens=2048, |
| 153 | + temperature=1.0, |
| 154 | + messages=[ |
| 155 | + { |
| 156 | + "role": "user", |
| 157 | + "content": "Solve this logic puzzle: There are 3 boxes. One contains only apples, one contains only oranges, and one contains both. All boxes are labeled incorrectly. You can pick one fruit from one box. How do you correctly label all boxes?" |
| 158 | + } |
| 159 | + ] |
| 160 | + ) |
| 161 | + |
| 162 | + print("User: [Logic puzzle about mislabeled fruit boxes]") |
| 163 | + print(f"Claude: {message.content[0].text}\n") |
| 164 | + |
| 165 | + |
| 166 | +def with_prefill(): |
| 167 | + """Use prefill to guide Claude's response format.""" |
| 168 | + print("=" * 60) |
| 169 | + print("7. Response Prefill") |
| 170 | + print("=" * 60) |
| 171 | + |
| 172 | + message = client.messages.create( |
| 173 | + model="claude-3-5-sonnet-20241022", |
| 174 | + max_tokens=1024, |
| 175 | + messages=[ |
| 176 | + {"role": "user", "content": "What are the three laws of robotics?"}, |
| 177 | + {"role": "assistant", "content": "The Three Laws of Robotics are:\n\n1."} |
| 178 | + ] |
| 179 | + ) |
| 180 | + |
| 181 | + print("User: What are the three laws of robotics?") |
| 182 | + print(f"Claude: The Three Laws of Robotics are:\n\n1.{message.content[0].text}\n") |
| 183 | + |
| 184 | + |
| 185 | +def error_handling(): |
| 186 | + """Demonstrate error handling with Anthropic API.""" |
| 187 | + print("=" * 60) |
| 188 | + print("8. Error Handling") |
| 189 | + print("=" * 60) |
| 190 | + |
| 191 | + try: |
| 192 | + message = client.messages.create( |
| 193 | + model="claude-3-5-sonnet-20241022", |
| 194 | + max_tokens=100, |
| 195 | + messages=[ |
| 196 | + {"role": "user", "content": "Hello Claude!"} |
| 197 | + ] |
| 198 | + ) |
| 199 | + print(f"✓ Success: {message.content[0].text}\n") |
| 200 | + |
| 201 | + except Exception as e: |
| 202 | + print(f"✗ Error: {type(e).__name__}") |
| 203 | + print(f" Message: {str(e)}\n") |
| 204 | + |
| 205 | + |
| 206 | +if __name__ == "__main__": |
| 207 | + # Check if API key is set |
| 208 | + if not os.getenv("ANTHROPIC_API_KEY"): |
| 209 | + print("Error: ANTHROPIC_API_KEY not found in environment variables.") |
| 210 | + print("Please create a .env file with your API key.") |
| 211 | + print("Example: ANTHROPIC_API_KEY=sk-ant-...") |
| 212 | + exit(1) |
| 213 | + |
| 214 | + print("\n" + "=" * 60) |
| 215 | + print("Anthropic Claude API Examples") |
| 216 | + print("=" * 60 + "\n") |
| 217 | + |
| 218 | + try: |
| 219 | + simple_message() |
| 220 | + streaming_response() |
| 221 | + system_prompt() |
| 222 | + multi_turn_conversation() |
| 223 | + with_vision() |
| 224 | + thinking_mode() |
| 225 | + with_prefill() |
| 226 | + error_handling() |
| 227 | + |
| 228 | + print("=" * 60) |
| 229 | + print("All examples completed successfully!") |
| 230 | + print("=" * 60) |
| 231 | + |
| 232 | + except Exception as e: |
| 233 | + print(f"\n✗ Error running examples: {e}") |
| 234 | + print("Make sure your ANTHROPIC_API_KEY is valid and you have credits.") |
0 commit comments