Article·docs.anthropic.com
AIAPILLMAnthropicaiapillmanthropicpython
Anthropic Claude API
Integrate Anthropic's Claude API to access advanced AI capabilities for text generation, vision, and tool use. This pack guides you through setting up your environment and making your first API call.
beginner15 min5 steps
The play
- Obtain Your Anthropic API KeySign up or log in to the Anthropic console at `console.anthropic.com/settings/keys`. Generate and copy a new API key.
- Install the Anthropic Python SDKOpen your terminal or command prompt and run the following command to install the official Python client library:
- Set Your API Key Environment VariableFor secure access, set your API key as an environment variable named `ANTHROPIC_API_KEY`. Replace `YOUR_API_KEY` with the key you obtained in Step 1. **Linux/macOS:** `export ANTHROPIC_API_KEY='YOUR_API_KEY'` **Windows (Command Prompt):** `set ANTHROPIC_API_KEY='YOUR_API_KEY'` **Windows (PowerShell):** `$env:ANTHROPIC_API_KEY='YOUR_API_KEY'`
- Make Your First API Call for Text GenerationUse the provided starter code to send a prompt to Claude and receive a text completion. Save the code as a Python file (e.g., `claude_test.py`) and run it.
- Explore Advanced FeaturesRefer to the official Anthropic documentation for examples on vision capabilities, tool use, and other advanced integrations with Claude models.
Starter code
import os
from anthropic import Anthropic
# Ensure your ANTHROPIC_API_KEY environment variable is set
# Alternatively, pass api_key="your_api_key_here" directly
client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
message = client.messages.create(
model="claude-3-opus-20240229", # Consider "claude-3-sonnet-20240229" or "claude-3-haiku-20240307" for cost-effectiveness
max_tokens=100,
messages=[
{"role": "user", "content": "Hello, Claude. Write a haiku about a bustling city."}
]
)
for block in message.content:
if block.type == "text":
print(block.text)Source