How to beginner · 3 min read

How to translate code comments with AI

Quick answer
Use the OpenAI Python SDK to send code comments as input to a chat model like gpt-4o with a prompt instructing translation. The model returns the translated comments, enabling automated multilingual code documentation.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the official openai Python package and set your API key as an environment variable for secure authentication.

bash
pip install openai>=1.0
output
Collecting openai
  Downloading openai-1.x.x-py3-none-any.whl (xx kB)
Installing collected packages: openai
Successfully installed openai-1.x.x

Step by step

This example sends code comments to the gpt-4o model with a prompt to translate them from English to Spanish. The response contains the translated comments.

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

code_comments = """# This function adds two numbers\n# It returns the sum of a and b"""

messages = [
    {"role": "user", "content": f"Translate the following code comments from English to Spanish:\n{code_comments}"}
]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=messages
)

translated_comments = response.choices[0].message.content
print("Translated comments:")
print(translated_comments)
output
Translated comments:
# Esta función suma dos números
# Devuelve la suma de a y b

Common variations

  • Use gpt-4o-mini for faster, cheaper translations with slightly less accuracy.
  • Implement asynchronous calls with asyncio and await for concurrent translation tasks.
  • Translate comments in other languages by changing the prompt instructions.
python
import os
import asyncio
from openai import OpenAI

async def translate_comments_async(comments: str, target_language: str) -> str:
    client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
    messages = [
        {"role": "user", "content": f"Translate the following code comments to {target_language}:\n{comments}"}
    ]
    response = await client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages
    )
    return response.choices[0].message.content

async def main():
    comments = """# Initialize the database connection\n# Handle errors gracefully"""
    translated = await translate_comments_async(comments, "French")
    print("Translated comments:")
    print(translated)

if __name__ == "__main__":
    asyncio.run(main())
output
Translated comments:
# Initialiser la connexion à la base de données
# Gérer les erreurs de manière appropriée

Troubleshooting

  • If you get an authentication error, verify your OPENAI_API_KEY environment variable is set correctly.
  • For rate limit errors, reduce request frequency or switch to a smaller model like gpt-4o-mini.
  • If translations are inaccurate, clarify the prompt with explicit instructions or provide examples.

Key Takeaways

  • Use the OpenAI Python SDK with gpt-4o to translate code comments efficiently.
  • Customize prompts to specify source and target languages for accurate translations.
  • Async calls enable scalable translation of multiple code files concurrently.
  • Handle API errors by checking environment variables and adjusting model choice.
  • Clear prompt instructions improve translation quality and relevance.
Verified 2026-04 · gpt-4o, gpt-4o-mini
Verify ↗