Skip to content

Instantly share code, notes, and snippets.

@czue
Created April 2, 2024 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save czue/fef1ab90294ea99181982aae2857dd56 to your computer and use it in GitHub Desktop.
Save czue/fef1ab90294ea99181982aae2857dd56 to your computer and use it in GitHub Desktop.
Translations with OpenAI
# this is the core translation code from https://www.youtube.com/watch?v=2ItlnKhe37U
# It uses the OpenAI API to translate messages from one language to another.
import dataclasses
from typing import List
from django.conf import settings
from openai import OpenAI
from apps.translations.models import InputText, Language
client = OpenAI(api_key=settings.OPENAI_API_KEY)
SYSTEM_PROMPT_TRANSLATE = """
You are TranslateGPT.
Your job is to translate text from {from_lang} to {to_lang}.
I will give you {from_lang} text to translate and you should respond with the {to_lang} translation of the text.
Do not provide any other commentary or information. Just the translated text.
Please also do your best to preserve formatting and templated variables (do NOT translate the variables).
"""
@dataclasses.dataclass
class TextWithTranslation:
input_text: InputText
language: Language
translation: str
def translate_messages(messages: List[InputText], language: Language) -> List[TextWithTranslation]:
formatted_prompt = SYSTEM_PROMPT_TRANSLATE.format(
from_lang="English",
to_lang=language.name,
)
translated_messages = []
for message in messages:
open_ai_messages = [
{
"role": "system",
"content": formatted_prompt,
},
{
"role": "user",
"content": str(message),
},
]
openai_response = client.chat.completions.create(
model=settings.OPENAI_MODEL,
messages=open_ai_messages,
)
translation = openai_response.choices[0].message.content.strip()
translated_messages.append(TextWithTranslation(message, language, translation))
return translated_messages
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment