Anthropic Conversation Format (Python)
Anthropic Conversation Format (Python)
Section titled “Anthropic Conversation Format (Python)”Page Overview
Official Documentation
- Anthropic Messages
- Anthropic Streaming Messages
📝 Introduction
Section titled “📝 Introduction”This is a complete Python example in Anthropic format for calling the Anthropic API through the anthropic SDK.
💡 Request Example
Section titled “💡 Request Example”Basic Python Text Conversation ✅
Section titled “Basic Python Text Conversation ✅”import anthropic # Import the anthropic moduleimport httpx # The anthropic library depends on httpx for network requestsimport os # Used to read the API key from environment variables (recommended)
# --- Configuration ---# Strongly recommended: store your API key in environment variables instead of hardcoding it in your code.# For example, set it in your terminal: export ANTHROPIC_API_KEY="sk-your-anthropic-api-key"# Or in Windows PowerShell: $env:ANTHROPIC_API_KEY="sk-your-anthropic-api-key"ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
# If you haven't set an environment variable, or want to test temporarily, you can uncomment the line below and enter your keyANTHROPIC_API_KEY = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Replace with your Anthropic API key
# Custom Base URL (only needed if you access Anthropic through a specific proxy)# For example, if your previous sg.4All API.com/v1 also proxies Anthropic requests# ANTHROPIC_BASE_URL = "https://sg.4All API.com/v1"ANTHROPIC_BASE_URL = "https://sg.4All API.com" # Defaults to None; the SDK will use Anthropic's official endpoint
# Model selection (choose based on your API key permissions and requirements)# Claude 3 Opus: "claude-3-opus-20240229" (most capable, may require higher permissions or a paid plan)# Claude 3 Sonnet: "claude-3-sonnet-20240229" (balanced performance and cost)# Claude 3 Haiku: "claude-3-haiku-20240307" (fastest and most economical)MODEL_NAME = "claude-3-7-sonnet-20250219" # Sonnet is used by default; you can change it
# --- Security Warning ---if not os.getenv("ANTHROPIC_API_KEY") and ANTHROPIC_API_KEY and "sk-anthropic-xxxx" not in ANTHROPIC_API_KEY: print("**********************************************************************************") print("Warning: The API key appears to be hardcoded in the code.") print("This may be convenient for testing, but be aware that writing sensitive information such as API keys directly into code") print("poses serious security risks, especially when sharing code, committing it to version control systems (such as Git), or deploying it to production.") print("It is strongly recommended to manage API keys in safer ways such as environment variables in production.") print("For example: export ANTHROPIC_API_KEY='your_actual_api_key'") print("**********************************************************************************")
# 1. Verify the API keyif not ANTHROPIC_API_KEY: raise ValueError( "API key (ANTHROPIC_API_KEY) is not set.\n" "Please set it by defining the ANTHROPIC_API_KEY environment variable or by providing ANTHROPIC_API_KEY directly in the code (not recommended for production)." )else: print(f"API Key in use (partially shown): '{ANTHROPIC_API_KEY[:12]}...{ANTHROPIC_API_KEY[-4:]}'") # Show the sk-anthropic- prefix plus part of the key
if ANTHROPIC_BASE_URL: print(f"Custom Base URL in use: {ANTHROPIC_BASE_URL}")else: print("Using Anthropic's default Base URL.")
# 2. Configure the API clienttry: client_params = { "api_key": ANTHROPIC_API_KEY, "timeout": httpx.Timeout(300.0, connect=60.0), # Total timeout 300 seconds, connection timeout 60 seconds "max_retries": 1, } if ANTHROPIC_BASE_URL: client_params["base_url"] = ANTHROPIC_BASE_URL
client = anthropic.Anthropic(**client_params)
except Exception as e: print(f"An error occurred while creating the Anthropic client: {e}") exit()
# 3. Prepare the message payload for the API request# Anthropic's messages API format is similar to OpenAI'smessages_payload = [ {"role": "user", "content": "你好,你能做什么?请用中文回答。"}]
# 4. Send the request and handle the responsetry: print(f"\nAttempting to call the Anthropic API (model: {MODEL_NAME})...") response = client.messages.create( model=MODEL_NAME, max_tokens=200, # It is recommended to use at least 150-200 tokens for Claude 3 Sonnet for meaningful replies temperature=0.7, # Temperature parameter controlling the randomness of generated text messages=messages_payload # system="You are a helpful assistant." # Optional system prompt )
# 5. Extract and print the model's reply if response.content and isinstance(response.content, list) and len(response.content) > 0: # Typically, for non-streaming responses, the content is in response.content[0].text assistant_reply = response.content[0].text print("\nModel reply:") print(assistant_reply) else: print("\nFailed to obtain a valid reply from the API.") if response.stop_reason: print(f"Stop reason: {response.stop_reason}") # print("Full response object:", response.model_dump_json(indent=2)) # For debugging
# Print usage information (if available) if response.usage: print("\nUsage information:") print(f" Input Tokens: {response.usage.input_tokens}") print(f" Output Tokens: {response.usage.output_tokens}")
except anthropic.APIStatusError as e: print(f"\nAnthropic API returned an error status code: {e.status_code}") print(f"Error type: {e.type}" if hasattr(e, 'type') and e.type else "") print(f"Error message: {e.message}" if hasattr(e, 'message') and e.message else "") print(f"Response details: {e.response}") # Contains the raw httpx.Response if e.status_code == 401: print("Error details: The API key is invalid or missing. Please check your ANTHROPIC_API_KEY.") elif e.status_code == 403: print("Error details: Authentication succeeded, but the key is not authorized to access the requested resource/model, or usage limits have been exceeded, or there is an account issue.") print(f" - Please check whether your Anthropic account has access to model '{MODEL_NAME}'.") print(" - Check your account usage, billing status, and API key permissions.") print(" - Try another model, such as 'claude-3-haiku-20240307' or 'claude-3-sonnet-20240229'.") elif e.status_code == 404: print(f"Error details: The requested resource was not found. Most likely the model name '{MODEL_NAME}' is incorrect or unavailable.") print(" - Please check the Anthropic documentation for the correct model name.") elif e.status_code == 429: print("Error details: Anthropic API rate limit reached. Please try again later or check your rate-limiting strategy.") elif e.status_code >= 500: print("Error details: Anthropic server-side error. Please try again later.")except anthropic.APIConnectionError as e: print(f"\nUnable to connect to the Anthropic API: {e}") print(" - Please check your network connection.") print(f" - If you are using a custom Base URL ('{ANTHROPIC_BASE_URL}'), make sure it is correct and accessible.")except anthropic.RateLimitError as e: print(f"\nAnthropic API rate limit reached: {e}")except anthropic.AuthenticationError as e: print(f"\nAnthropic API authentication failed: {e}") print(" - Please double-check that your ANTHROPIC_API_KEY is correct and valid.")except Exception as e: print(f"\nAn unknown error occurred while calling the API: {e}") print(f"Error type: {type(e).__name__}")How to Use:
Section titled “How to Use:”- Install the anthropic library (if you haven’t already): pip install anthropic
- Set the API key: Recommended: set the ANTHROPIC_API_KEY environment variable.
- Create a .env variable file
- In the same directory as your Python script (for example, xxxx.py), create a file named .env (note: the file name is exactly .env, with a dot and no other prefix).
- In that .env file, enter the following content and fill in your API key and base URL: # .env file contents OPENAI_API_KEY=“sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx” OPENAI_BASE_URL=“https://sg.4All API.com/v1”
You can also add other configuration variables later, for example:
Section titled “You can also add other configuration variables later, for example:”DEFAULT_MODEL=“claude-4-6-sonnet-20250219”
Section titled “DEFAULT_MODEL=“claude-4-6-sonnet-20250219””MAX_TOKENS_DEFAULT=150
Section titled “MAX_TOKENS_DEFAULT=150”2. Or, directly modify the line `ANTHROPIC_API_KEY = "sk-anthropic-..."` in the code (not recommended for shared or production code).
2. **Select a model**:
- The code defaults to `MODEL_NAME = "claude-4-6-sonnet-20250219"`.- If you want to use Opus or Haiku, you can obtain different model names from the `4All API.com` console and update this variable. **Make sure your API key is authorized to access the model you choose.** As you previously encountered with the 403 error, the Opus model may have stricter access requirements.3. **Custom Base URL (if needed)**:
- If you access Anthropic through a proxy server such as `https://api.4All API.com/v1`, and that proxy server also handles Anthropic requests.