refactor(devgen/providers): shared provider base class
Abstract out generate validation and error handling into BaseProvider, eliminating duplicated logic across Anthropic, OpenRouter, and OpenAI providers.
This commit is contained in:
7 files changed
+223
-259
No files matched your search
@@ -1,33 +1,19 @@
|
||||
import anthropic
|
||||
|
||||
from devgen.utils import format_token_limit_error, is_token_limit_error
|
||||
from devgen.providers.base import BaseProvider
|
||||
|
||||
|
||||
class AnthropicProvider:
|
||||
class AnthropicProvider(BaseProvider):
|
||||
"""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."
|
||||
)
|
||||
DISPLAY_NAME = "Anthropic"
|
||||
DEFAULT_MODEL = "claude-3-opus-20240229"
|
||||
|
||||
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
|
||||
def _generate(self, prompt, api_key, model, **kwargs):
|
||||
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
|
||||
Reference in new issue
Block a user