- Set up the OpenAI Python client
- Load the article text into a variable
- Craft a translation prompt
- Implement an
article_translatorfunction - Execute the function and display the result
1. Prerequisites
- Python 3.7+
- An OpenAI API key
- The
openaiPython 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
| 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.What’s Next?
- Batch-translate multiple articles
- Scrape article URLs automatically before translation
- Summarize translated content or detect sentiment