Skip to main content

Overview

The AnthropicClient provides a unified interface for interacting with Anthropic’s Claude models, including Claude 3.7 Sonnet, Claude 4.5, and Haiku variants.

Installation

Basic Usage

Constructor

LLMConfig | None
default:"None"
Configuration object. If None, creates default config with:
  • api_key from ANTHROPIC_API_KEY environment variable
  • model set to "claude-haiku-4-5-latest"
  • max_tokens from parameter (default: 16384)
bool
default:"False"
Enable response caching (stored in ./llm_cache)
AsyncAnthropic | None
default:"None"
Optional pre-configured AsyncAnthropic client instance. If not provided, creates one from config.
int
default:"16384"
Maximum output tokens. Defaults to 16384, but see model-specific limits below.

Supported Models

The client supports all Claude models with model-specific max token limits:

Claude 4.5 (64K output)

  • claude-sonnet-4-5-latest
  • claude-sonnet-4-5-20250929
  • claude-haiku-4-5-latest

Claude 3.7 Sonnet (64K output)

  • claude-3-7-sonnet-latest
  • claude-3-7-sonnet-20250219
Claude 3.7 supports up to 128K output tokens with the anthropic-beta: output-128k-2025-02-19 header, but this is not currently implemented.

Claude 3.5 (8K output)

  • claude-3-5-haiku-latest
  • claude-3-5-haiku-20241022
  • claude-3-5-sonnet-latest
  • claude-3-5-sonnet-20241022
  • claude-3-5-sonnet-20240620

Claude 3 (4K output)

  • claude-3-opus-latest
  • claude-3-opus-20240229
  • claude-3-sonnet-20240229
  • claude-3-haiku-20240307

Claude 2 (4K output)

  • claude-2.1
  • claude-2.0

Max Tokens Resolution

The client uses intelligent max token resolution with the following precedence:
  1. Explicit parameter to generate_response()
  2. Instance max_tokens set during initialization
  3. Model-specific maximum from the mapping above
  4. Default fallback: 8192 tokens

Structured Output via Tools

The client uses Anthropic’s tool-calling API for structured outputs:
The tool definition is created automatically:

Error Handling

The client implements comprehensive error handling:

Rate Limits

Content Policy Violations

Automatic Retries

The client automatically retries (max 2 times) for:
  • Validation errors (with error context for self-correction)
  • Transient API errors
  • JSON parsing failures

Token Usage Tracking

The client tracks token usage from the API response:

JSON Fallback Extraction

If tool use fails, the client attempts to extract JSON from text:

Example: Multi-turn Conversation

Performance Tips

  1. Use Haiku for simple tasks: Claude Haiku is 3x cheaper and faster than Sonnet
  2. Set appropriate max_tokens: Don’t request 64K if you only need 1K
  3. Enable caching for repeated queries with same context
  4. Use model_size parameter: Let Graphiti choose the right model