Skip to main content
Translate any foreign‐language article into English using OpenAI’s chat completion API. In this tutorial, you’ll:
  1. Set up the OpenAI Python client
  2. Load the article text into a variable
  3. Craft a translation prompt
  4. Implement an article_translator function
  5. Execute the function and display the result

1. Prerequisites

  • Python 3.7+
  • An OpenAI API key
  • The openai Python package installed:
Never hard-code your API key in source files. Use environment variables or a secrets manager:

2. Initialize the OpenAI Client

Import and configure the client with your API key.

3. Prepare the Article Text & Prompt

Chat models cannot fetch URLs directly, so load your article content into a string. Later, you can extend this for web scraping or file input.
You can replace the hard-coded article variable with any string input or file contents for batch translation.

4. Define the Translator Function

Create a reusable function that sends the system and user messages to the chat completion endpoint.
A low temperature (e.g., 0.1) ensures a faithful translation.

API Parameters Overview


5. Run the Translator

Execute the script and print the translated text.

What’s Next?

  • Batch-translate multiple articles
  • Scrape article URLs automatically before translation
  • Summarize translated content or detect sentiment

Watch Video

Practice Lab