vocab-assistant/vocab_assistant/lib/vocab_assistant.ex
2025-03-16 20:30:59 -07:00

76 lines
2.5 KiB
Elixir

defmodule VocabAssistant do
@moduledoc """
VocabAssistant keeps the contexts that define your domain
and business logic.
Contexts are also responsible for managing your data, regardless
if it comes from the database, an external API or others.
"""
require Logger
@google_translate_url "https://www.googleapis.com/language/translate/v2"
def generate_sentence(word, language \\ "Hindi") do
client =
Anthropix.init(
"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"
)
system_prompt =
"
You are a language-learning assistant tasked with helping the user to learn vocabulary in #{language}.
A #{language} word will be provided; respond with a simple phrase or sentence in #{language} using that word.
Use markdown to bold the vocab word in question.
Ensure that the sentence has just enough complexity to associate the word with relevant context
(again, using other beginner-friendly words -- ideally within the 1000 most frequently-used words).
Try to incorporate the most closely-related word in the sentence, e.g. for 'curtain' use 'window', not just 'room'.
Respond with just the marked-up sentence, nothing else. If the given word is in English, use its #{language} translation.
"
msg = [
%{
role: "user",
content:
"Please provide a short, simple sentence in #{language} using the word \"#{word}\"."
}
]
{:ok, %{"content" => [%{"text" => sentence}]}} =
Anthropix.chat(client,
model: "claude-3-7-sonnet-20250219",
system: system_prompt,
messages: msg
)
sentence
end
def google_translate(text, to, key) do
Logger.debug(@google_translate_url)
query = "#{@google_translate_url}?q=#{URI.encode(text)}&target=#{to}&key=#{key}"
# Capture errors
try do
{:ok, response} = HTTPoison.get(query, timeout: 10_000)
if response.status_code == 200 do
# Extract the translation
translation_from(response.body)
else
{:error, "Translation failed at #{query}"}
end
catch
kind, reason ->
Logger.debug("Failed to translate: #{inspect(kind)} , #{inspect(reason)}")
{:error, "Translation failed at #{query}"}
end
end
defp translation_from(body) do
result = JSON.decode!(body)
case result["data"]["translations"] do
[translation | _] -> {:ok, translation["translatedText"]}
[] -> {:error, "No translation found"}
end
end
end