language-learning-app/api/app/outbound/anthropic/anthropic_client.py

75 lines
2.9 KiB
Python
Raw Normal View History

import asyncio
import anthropic
class AnthropicClient():
def __init__(self, api_key: str):
self._client = anthropic.Anthropic(api_key=api_key)
@classmethod
def new(cls, api_key: str) -> "AnthropicClient":
return cls(api_key)
def _create_summarise_text_system_prompt(
self,
complexity_level: str,
from_language: str,
to_language: str,
length_preference="200-400 words",
) -> str:
return (
f"You are a language learning content creator.\n"
f"The user will provide input, you will generate an engaging realistic summary text in {to_language} "
f"at {complexity_level} proficiency level (CEFR scale).\n\n"
f"The text you generate will:\n"
f"- Contain ONLY the generated text in {to_language}.\n"
f"- Be appropriate for a {complexity_level} {to_language} speaker.\n"
f"- Never generate inappropriate (hateful, sexual, violent) content. It is preferable to return no text than to generate such content.\n"
f"- Speak directly to the reader/listener, adopting the tone and style of a semi-formal news reporter or podcaster.\n"
f"- Where appropriate (fluency level, content), use a small number of idiomatic expressions.\n"
f"- Be formatted in markdown with paragraphs and line breaks.\n"
f"- Be {length_preference} long.\n"
f"- Be inspired by the following source material "
f"(but written originally in {from_language}):\n\n"
)
def _create_prompt_summarise_text(
self,
source_material: str,
) -> str:
return (
f"Source material follows: \n\n"
f"{source_material}"
)
async def generate_summary_text(
self,
content_to_summarise: str,
complexity_level: str,
from_language: str,
to_language: str,
length_preference="200-400 words") -> str:
"""Generate text using Anthropic."""
def _call() -> str:
message = self._client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
system=self._create_summarise_text_system_prompt(
complexity_level=complexity_level,
from_language=from_language,
to_language=to_language,
length_preference=length_preference,
),
messages=[
{
"role": "user",
"content": self._create_prompt_summarise_text(
content_to_summarise
)
}
],
)
return message.content[0].text
return await asyncio.to_thread(_call)