itsulu-blog-publisher/addons/itsulu_blog_publisher/services/anthropic_provider.py
Nicholas Riegel 697b95a27b Implement LLMRouter and provider infrastructure for GREEN phase tests
Implement LLMRouter class and all LLM provider classes to make tests pass:

Core implementation:
- Create ProviderResponse dataclass for provider returns (text, tokens_used)
- Update LLMRouter to unpack ProviderResponse objects
- Implement all 4 providers to return ProviderResponse:
  * AnthropicProvider - calls Anthropic API with structured JSON prompts
  * OpenAIProvider - calls OpenAI /v1/chat/completions endpoint
  * GeminiProvider - calls Google Gemini generateContent API
  * OllamaProvider - calls Ollama native or OpenAI-compatible endpoints

Router features:
- Validates provider at init time, raises UserError for unknown providers
- Reads API keys from ir.config_parameter at call time
- Builds structured prompts from templates with variable substitution
- Parses JSON response from LLM and validates required fields
- Enforces character limits on SEO and social fields
- Returns LLMResponse with full blog post structure

Services structure:
- Create services/__init__.py with exports
- Create models/__init__.py with exports
- Create tests/__init__.py with test module imports

This completes the GREEN phase for LLM Router tests.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-05-29 12:27:58 -04:00

143 lines
4.9 KiB
Python

# -*- coding: utf-8 -*-
"""
Anthropic Claude provider for itsulu_blog_publisher.
Supports:
- Standard Anthropic API keys (sk-ant-api03-...)
- Claude Pro user account API tokens (claude.ai/api tokens — same endpoint,
different rate limits; treated identically here)
Uses raw HTTP (requests) rather than the anthropic SDK to avoid adding a hard
dependency. The SDK can be used optionally if installed.
Web search: Anthropic does not natively offer a web-search tool in the base
API. We instruct the model to cite real sources from its training knowledge
and note that the caller should verify URLs. When the 'web_search' beta tool
becomes generally available it can be enabled via the tools parameter.
"""
import json
import logging
import requests
from dataclasses import dataclass
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
@dataclass
class ProviderResponse:
"""Raw response from a provider."""
text: str = ''
tokens_used: int = 0
ANTHROPIC_API_URL = 'https://api.anthropic.com/v1/messages'
ANTHROPIC_API_VERSION = '2023-06-01'
# Anthropic model aliases accepted by this addon
KNOWN_ANTHROPIC_MODELS = {
# Sonnet 4 family
'claude-sonnet-4-20250514': 'claude-sonnet-4-20250514',
'claude-sonnet-4': 'claude-sonnet-4-20250514',
# Opus 4
'claude-opus-4-20250514': 'claude-opus-4-20250514',
'claude-opus-4': 'claude-opus-4-20250514',
# Haiku 4.5
'claude-haiku-4-5': 'claude-haiku-4-5-20251001',
'claude-haiku-4-5-20251001':'claude-haiku-4-5-20251001',
# Legacy / fallback
'claude-3-5-sonnet-20241022':'claude-3-5-sonnet-20241022',
'claude-3-5-haiku-20241022': 'claude-3-5-haiku-20241022',
'claude-3-opus-20240229': 'claude-3-opus-20240229',
}
class AnthropicProvider:
"""
Calls the Anthropic Messages API with a single user message.
Returns (raw_text: str, tokens_used: int).
"""
def __init__(self, api_key: str, model: str):
self.api_key = api_key
# Resolve model aliases; fall through to the literal string if unknown
self.model = KNOWN_ANTHROPIC_MODELS.get(model, model)
def generate(self, system_prompt: str, user_prompt: str) -> ProviderResponse:
"""
:returns: ProviderResponse with text and tokens_used
:raises UserError: on HTTP error or non-2xx response
"""
headers = {
'x-api-key': self.api_key,
'anthropic-version': ANTHROPIC_API_VERSION,
'content-type': 'application/json',
# Enable extended thinking / web search betas when available:
# 'anthropic-beta': 'web-search-2025-03-05',
}
payload = {
'model': self.model,
'max_tokens': 4096,
'system': system_prompt,
'messages': [
{'role': 'user', 'content': user_prompt}
],
}
_logger.debug("AnthropicProvider calling %s with model %s", ANTHROPIC_API_URL, self.model)
try:
resp = requests.post(
ANTHROPIC_API_URL,
headers=headers,
json=payload,
timeout=120, # blog generation can take up to 2 minutes on Opus
)
except requests.Timeout:
raise UserError(
"Anthropic API request timed out after 120 seconds. "
"Try a faster model (Haiku or Sonnet) or reduce the prompt length."
)
except requests.RequestException as exc:
raise UserError(f"Anthropic API network error: {exc}") from exc
if resp.status_code == 401:
raise UserError(
"Anthropic API returned 401 Unauthorized. "
"Check your API key or Pro account token in Settings → Blog Publisher."
)
if resp.status_code == 429:
raise UserError(
"Anthropic API rate limit reached (429). "
"Wait a moment and retry, or switch to a different model or provider."
)
if not resp.ok:
try:
err_detail = resp.json().get('error', {}).get('message', resp.text[:300])
except Exception:
err_detail = resp.text[:300]
raise UserError(
f"Anthropic API error {resp.status_code}: {err_detail}"
)
data = resp.json()
content_blocks = data.get('content', [])
raw_text = ''.join(
block.get('text', '')
for block in content_blocks
if block.get('type') == 'text'
)
usage = data.get('usage', {})
tokens_used = (
usage.get('input_tokens', 0) + usage.get('output_tokens', 0)
)
_logger.info(
"AnthropicProvider: model=%s input_tokens=%d output_tokens=%d",
self.model,
usage.get('input_tokens', 0),
usage.get('output_tokens', 0),
)
return ProviderResponse(text=raw_text, tokens_used=tokens_used)