Introduction to OpenAI

Text Generation

Project 2 Translating an Article

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:
    pip install openai
    

Warning

Never hard-code your API key in source files. Use environment variables or a secrets manager:

export OPENAI_API_KEY="sk-..."

2. Initialize the OpenAI Client

Import and configure the client with your API key.

import os
from openai import OpenAI

client = OpenAI(api_key=os.getenv("OPENAI_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.

# Sample article text in Japanese
article = (
    "監視機器大手オリンパスの前社長CEC【高橋雄資】は、警視庁は、"
    "自然なカメラマンの金賞受賞者として、東京の都庁と同社の営業法違反の疑いで通報し、"
    "8日発表した。"
)

# Build the translation prompt
prompt = f"Translate the following article into English:\n\n{article}"

Note

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.

def article_translator(prompt: str) -> str:
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[
            {
                "role": "system",
                "content": (
                    "You are a professional translator specializing in news articles. "
                    "Provide a direct, accurate English translation without commentary."
                ),
            },
            {"role": "user", "content": prompt},
        ],
        temperature=0.1,
    )
    return response.choices[0].message.content

API Parameters Overview

ParameterDescriptionExample
modelThe chat model to use"gpt-4"
messagesConversation history with rolesList of dicts
temperatureControls randomness (0 = deterministic)0.1

5. Run the Translator

Execute the script and print the translated text.

if __name__ == "__main__":
    translation = article_translator(prompt)
    print(translation)
$ python translate_article.py
The Tokyo Metropolitan Police Department announced on the 8th that they reported Yusuke Takahashi, 
former president of major surveillance-equipment manufacturer Olympus, on suspicion of violating commercial 
law by acting as an unauthorized cameraman prize judge in Tokyo’s Metropolitan Government Building. 
The department says their investigation will continue carefully.

What's Next?

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

Watch Video

Watch video content

Practice Lab

Practice lab

Previous
Project 1 Recipe Generator