> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Project 2 Translating an Article

> Build an article translation tool using OpenAI's chat completion API to translate foreign-language articles into English.

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](https://platform.openai.com/account/api-keys)
* The `openai` Python package installed:
  ```bash theme={null}
  pip install openai
  ```

<Callout icon="triangle-alert" color="#FF6B6B">
  Never hard-code your API key in source files. Use environment variables or a secrets manager:

  ```bash theme={null}
  export OPENAI_API_KEY="sk-..."
  ```
</Callout>

***

## 2. Initialize the OpenAI Client

Import and configure the client with your API key.

```python theme={null}
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.

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

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

<Callout icon="lightbulb" color="#1CB2FE">
  You can replace the hard-coded `article` variable with any string input or file contents for batch translation.
</Callout>

***

## 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.

```python theme={null}
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

| Parameter     | Description                             | Example       |
| ------------- | --------------------------------------- | ------------- |
| `model`       | The chat model to use                   | `"gpt-4"`     |
| `messages`    | Conversation history with roles         | List of dicts |
| `temperature` | Controls randomness (0 = deterministic) | `0.1`         |

***

## 5. Run the Translator

Execute the script and print the translated text.

```python theme={null}
if __name__ == "__main__":
    translation = article_translator(prompt)
    print(translation)
```

```plaintext theme={null}
$ 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

## Links and References

* [OpenAI Python SDK](https://github.com/openai/openai-python)
* [Chat Completion API Docs](https://platform.openai.com/docs/api-reference/chat)
* [Environment Variables Best Practices](https://12factor.net/config)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/introduction-to-openai/module/b6b7bec7-ed21-47d5-afbb-663df59f5e97/lesson/d8712d1a-af45-4f6a-b138-47f41d7b18df" />

  <Card title="Practice Lab" icon="installation" cta="Learn more" href="https://learn.kodekloud.com/user/courses/introduction-to-openai/module/b6b7bec7-ed21-47d5-afbb-663df59f5e97/lesson/0556be30-c3c7-41cc-95a8-e2e9040f33a3" />
</CardGroup>
