54 lines
1.9 KiB
Python
54 lines
1.9 KiB
Python
# src/anki_generator/clients/llm.py
|
|
from typing import Dict, Optional
|
|
import json
|
|
from anthropic import Anthropic
|
|
from anki_generator.settings import get_settings, Settings
|
|
|
|
class AnthropicClient:
|
|
def __init__(self, settings: Optional[Settings] = None):
|
|
self.settings = settings or get_settings()
|
|
self.client = Anthropic(api_key=self.settings.anthropic_api_key.get_secret_value())
|
|
self.model = self.settings.anthropic_model
|
|
self.max_tokens = self.settings.max_tokens
|
|
self.temperature = self.settings.temperature
|
|
|
|
def get_card_info(self, word: str, source: str) -> Dict:
|
|
"""Get card information from Anthropic API"""
|
|
prompt = f"""
|
|
Create an Anki card for the German word "{word}" (source: {source}).
|
|
IMPORTANT: Respond with ONLY the JSON object, no other text.
|
|
Format:
|
|
{{
|
|
"german_word": "",
|
|
"part_of_speech": "",
|
|
"english_meaning": "",
|
|
"article": "",
|
|
"plural_form": "",
|
|
"example_sentence": "",
|
|
"sentence_translation": "",
|
|
"usage_notes": "",
|
|
"related_words": "",
|
|
"image_search_term": "",
|
|
"tags": []
|
|
}}
|
|
"""
|
|
|
|
message = self.client.messages.create(
|
|
model=self.model,
|
|
max_tokens=self.max_tokens,
|
|
temperature=self.temperature,
|
|
system="You are a helpful German language teaching assistant. Return ONLY valid JSON without any additional text or explanations.",
|
|
messages=[
|
|
{
|
|
"role": "user",
|
|
"content": prompt
|
|
}
|
|
]
|
|
)
|
|
|
|
try:
|
|
return json.loads(message.content[0].text)
|
|
except (json.JSONDecodeError, IndexError) as e:
|
|
print(message)
|
|
raise ValueError(f"Failed to parse API response as JSON: {e}")
|