Files
DevGen/devgen/providers/anthropic.py
T
sankalp 8069895bc7 feat(devgen/providers): normalize token limit error handling
Add token limit error detection and formatting across all provider modules to surface clear diagnostics when context windows are exceeded, improving error messages and preventing silent failures.

New Features
- Introduce `is_token_limit_error` checks in Anthropic, Gemini, Hugging Face, Ollama, OpenAI, and OpenRouter providers.
- Use `format_token_limit_error` to generate user‑friendly error messages for token limit overs.

Enhancements
- Centralize token limit error handling for consistent diagnostics across providers.
- Explicitly re‑raise `RuntimeError` in Hugging Face to preserve original behavior.

Bug Fixes
- None
2026-06-06 16:45:05 +05:45

34 lines
1.2 KiB
Python

import anthropic
from devgen.utils import format_token_limit_error, is_token_limit_error
class AnthropicProvider:
"""Generates content using Anthropic's Claude models."""
def generate(
self, prompt: str, api_key: str, model: str = "claude-3-opus-20240229", **kwargs
) -> str:
"""Generates a response using the Anthropic API."""
if not api_key:
raise ValueError(
"Anthropic API key is missing. "
"Set it via `devgen setup config` or pass --api-key."
)
try:
client = anthropic.Anthropic(api_key=api_key)
message = client.messages.create(
model=model,
max_tokens=1024,
messages=[{"role": "user", "content": prompt}],
)
return message.content[0].text.strip()
except Exception as e:
if is_token_limit_error(e):
raise RuntimeError(format_token_limit_error("Anthropic", e)) from e
raise RuntimeError(
f"Anthropic generation failed: {e}. "
"Check the model id and your account credits."
) from e