- Spec files
pypi-anthropic
Describes: pkg:pypi/anthropic@0.66.x
- Description
- The official Python library for the anthropic API
- Author
- tessl
- Last updated
models.md docs/
1# Models API23The Models API provides access to information about available Claude models, including their capabilities, context limits, and metadata. This helps developers select appropriate models for different use cases and understand model-specific features.45## Capabilities67### Model Listing89Retrieve a list of all available Claude models with their specifications and capabilities.1011```python { .api }12def list(**kwargs) -> List[Model]13async def list(**kwargs) -> List[Model]14```1516## Core Types1718### Model Types1920```python { .api }21class Model(TypedDict):22id: str23type: Literal["model"]24display_name: str25created_at: str2627class ModelInfo(TypedDict):28id: str29type: Literal["model"]30display_name: str31created_at: str3233class ModelParam(TypedDict):34model: str3536class ModelListParams(TypedDict, total=False):37pass38```3940## Usage Examples4142### List Available Models4344```python45from anthropic import Anthropic4647client = Anthropic()4849# Get all available models50models = client.models.list()5152for model in models:53print(f"Model ID: {model.id}")54print(f"Display Name: {model.display_name}")55print(f"Created: {model.created_at}")56print("---")57```5859### Model Selection Helper6061```python62def select_model_by_capability(models: List[Model], capability: str) -> Optional[str]:63"""Select a model based on capability requirements"""6465# Model capability mapping (example)66capabilities = {67"vision": ["claude-sonnet-4-20250514", "claude-haiku-3-20241022"],68"function_calling": ["claude-sonnet-4-20250514", "claude-haiku-3-20241022"],69"long_context": ["claude-sonnet-4-20250514"],70"speed": ["claude-haiku-3-20241022"],71}7273suitable_models = capabilities.get(capability, [])7475for model in models:76if model.id in suitable_models:77return model.id7879return None8081# Usage82models = client.models.list()83vision_model = select_model_by_capability(models, "vision")8485if vision_model:86print(f"Selected model for vision: {vision_model}")8788# Use the selected model89message = client.messages.create(90model=vision_model,91max_tokens=1024,92messages=[93{94"role": "user",95"content": [96{"type": "text", "text": "What's in this image?"},97{"type": "image", "source": {"type": "url", "url": "https://example.com/image.jpg"}}98]99}100]101)102```103104### Model Comparison105106```python107def compare_models(models: List[Model]) -> None:108"""Compare available models and their characteristics"""109110print("Available Claude Models:")111print("=" * 50)112113# Sort models by creation date (newest first)114sorted_models = sorted(models, key=lambda m: m.created_at, reverse=True)115116for model in sorted_models:117print(f"ID: {model.id}")118print(f"Name: {model.display_name}")119print(f"Created: {model.created_at}")120121# Add capability hints based on model ID122if "haiku" in model.id.lower():123print("• Optimized for: Speed and efficiency")124print("• Best for: Quick responses, simple tasks")125elif "sonnet" in model.id.lower():126print("• Optimized for: Balance of capability and speed")127print("• Best for: Most general use cases")128elif "opus" in model.id.lower():129print("• Optimized for: Maximum capability")130print("• Best for: Complex reasoning, creative tasks")131132print("-" * 30)133134# Usage135models = client.models.list()136compare_models(models)137```138139### Async Model Listing140141```python142import asyncio143from anthropic import AsyncAnthropic144145async def list_models_async():146client = AsyncAnthropic()147148models = await client.models.list()149150print(f"Found {len(models)} available models:")151for model in models:152print(f"- {model.display_name} ({model.id})")153154return models155156# Run async157models = asyncio.run(list_models_async())158```159160### Model Validation161162```python163def validate_model_for_task(model_id: str, task_type: str) -> tuple[bool, str]:164"""Validate if a model is suitable for a specific task type"""165166# Get available models167models = client.models.list()168model_ids = [m.id for m in models]169170if model_id not in model_ids:171return False, f"Model {model_id} is not available"172173# Task-specific validation174if task_type == "vision" and "haiku" not in model_id:175return True, "Model supports vision tasks"176elif task_type == "vision" and "haiku" in model_id:177return False, "This model version may have limited vision capabilities"178elif task_type == "long_document" and "opus" not in model_id and "sonnet" not in model_id:179return False, "Consider using a higher-capability model for long documents"180181return True, "Model is suitable for this task"182183# Usage184is_valid, message = validate_model_for_task("claude-sonnet-4-20250514", "vision")185print(f"Valid: {is_valid}, Message: {message}")186187if is_valid:188# Proceed with using the model189response = client.messages.create(190model="claude-sonnet-4-20250514",191max_tokens=1024,192messages=[{"role": "user", "content": "Hello!"}]193)194```195196### Model Metadata Tracking197198```python199from datetime import datetime200from typing import Dict, Any201202class ModelTracker:203def __init__(self, client: Anthropic):204self.client = client205self.usage_stats: Dict[str, Dict[str, Any]] = {}206207def get_models_with_metadata(self) -> Dict[str, Dict[str, Any]]:208"""Get models with additional metadata and usage tracking"""209models = self.client.models.list()210211model_metadata = {}212for model in models:213model_metadata[model.id] = {214"display_name": model.display_name,215"created_at": model.created_at,216"usage_count": self.usage_stats.get(model.id, {}).get("count", 0),217"last_used": self.usage_stats.get(model.id, {}).get("last_used"),218"estimated_cost_tier": self._get_cost_tier(model.id),219"capabilities": self._get_capabilities(model.id)220}221222return model_metadata223224def track_usage(self, model_id: str):225"""Track model usage"""226if model_id not in self.usage_stats:227self.usage_stats[model_id] = {"count": 0, "last_used": None}228229self.usage_stats[model_id]["count"] += 1230self.usage_stats[model_id]["last_used"] = datetime.now().isoformat()231232def _get_cost_tier(self, model_id: str) -> str:233"""Estimate cost tier based on model name"""234if "haiku" in model_id.lower():235return "low"236elif "sonnet" in model_id.lower():237return "medium"238elif "opus" in model_id.lower():239return "high"240return "unknown"241242def _get_capabilities(self, model_id: str) -> List[str]:243"""Get model capabilities"""244capabilities = ["text"]245246# Add capabilities based on model ID patterns247if any(x in model_id for x in ["sonnet", "opus"]):248capabilities.extend(["vision", "function_calling", "long_context"])249elif "haiku" in model_id:250capabilities.extend(["vision", "function_calling"])251252return capabilities253254# Usage255tracker = ModelTracker(client)256models_metadata = tracker.get_models_with_metadata()257258for model_id, metadata in models_metadata.items():259print(f"Model: {metadata['display_name']}")260print(f"Capabilities: {', '.join(metadata['capabilities'])}")261print(f"Cost Tier: {metadata['cost_tier']}")262print(f"Usage Count: {metadata['usage_count']}")263print("---")264265# Track usage when making requests266model_to_use = "claude-sonnet-4-20250514"267tracker.track_usage(model_to_use)268269response = client.messages.create(270model=model_to_use,271max_tokens=1024,272messages=[{"role": "user", "content": "Hello!"}]273)274```275276### Model Selection Strategy277278```python279def select_optimal_model(280task_description: str,281priority: str = "balanced", # "speed", "quality", "cost", "balanced"282require_vision: bool = False,283require_function_calling: bool = False284) -> str:285"""Select the optimal model based on requirements"""286287models = client.models.list()288289# Filter models based on capabilities290suitable_models = []291292for model in models:293model_id = model.id.lower()294295# Check vision requirement296if require_vision and "claude-instant" in model_id:297continue # Skip models without vision298299# Check function calling requirement300if require_function_calling and "claude-instant" in model_id:301continue # Skip models without function calling302303suitable_models.append(model)304305if not suitable_models:306raise ValueError("No models meet the specified requirements")307308# Select based on priority309if priority == "speed":310# Prefer Haiku models for speed311for model in suitable_models:312if "haiku" in model.id.lower():313return model.id314elif priority == "quality":315# Prefer Opus models for quality316for model in suitable_models:317if "opus" in model.id.lower():318return model.id319elif priority == "cost":320# Prefer Haiku models for cost efficiency321for model in suitable_models:322if "haiku" in model.id.lower():323return model.id324elif priority == "balanced":325# Prefer Sonnet models for balance326for model in suitable_models:327if "sonnet" in model.id.lower():328return model.id329330# Fallback to first suitable model331return suitable_models[0].id332333# Usage examples334speed_model = select_optimal_model(335"Quick text generation",336priority="speed"337)338339vision_model = select_optimal_model(340"Analyze an image",341priority="quality",342require_vision=True343)344345function_model = select_optimal_model(346"Call external APIs",347priority="balanced",348require_function_calling=True349)350351print(f"Speed model: {speed_model}")352print(f"Vision model: {vision_model}")353print(f"Function calling model: {function_model}")354```