Restructure project files to follow the addon layout: - Move models to addons/itsulu_blog_publisher/models/ - Move services (LLM providers, routers) to addons/itsulu_blog_publisher/services/ - Move wizards to addons/itsulu_blog_publisher/wizards/ - Move views (XML templates) to addons/itsulu_blog_publisher/views/ - Move data (cron, mail templates) to addons/itsulu_blog_publisher/data/ - Move security (ACL) to addons/itsulu_blog_publisher/security/ - Move tests and factories to addons/itsulu_blog_publisher/tests/ - Move BDD features to addons/itsulu_blog_publisher/features/ - Create __init__.py files for all Python packages This enables proper Odoo module discovery and import structure. Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
135 lines
4.7 KiB
Python
135 lines
4.7 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 odoo.exceptions import UserError
|
|
|
|
_logger = logging.getLogger(__name__)
|
|
|
|
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) -> tuple:
|
|
"""
|
|
:returns: (raw_text, 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 raw_text, tokens_used
|