How to Create a Simple AI Translator App with OpenRouter API, Python, and Streamlit – As a Python and AI enthusiast, I’ve always been fascinated by the capabilities of AI in natural language processing and use Python with it.
Recently, I wrote an introduction article about OpenRouter, where I basically covered this tutorial as well at the end of the article.
In this tutorial, I’ll walk you through the steps to build this app, which leverages various free AI models available on OpenRouter for translation.
Prerequisites
Before we begin, make sure you have the following:
- Python 3.6+ installed on your machine.
- Basic knowledge of Python programming.
- Familiarity with Streamlit for building web applications.
- An API key from OpenRouter. You can sign up and get one here.
Building a Simple AI Translator App with OpenRouter API, Python, and Streamlit
This tutorial assumes you have an active internet connection and valid API access to OpenRouter. Always handle API keys securely and respect the usage policies of any third-party services you integrate.
Setting Up the Environment
First, let’s install the necessary Python packages. Open your terminal and run:
pip install streamlit requests python-dotenv
streamlit
: For building the web interface.requests
: To handle HTTP requests to the OpenRouter API.python-dotenv
: To manage environment variables securely.
Managing Environment Variables
To keep your API key secure, we’ll use a .env
file. In your project directory, create a .env
file:
touch .env
Add your OpenRouter API key to the .env
file:
OPENROUTER_API_KEY=your_openrouter_api_key
Replace your_openrouter_api_key
with your actual API key.
Building the AI Translator App
Let’s dive into the code. Create a new Python file named app.py
and start by importing the required libraries:
import streamlit as st
import requests
import json
import os
from dotenv import load_dotenv
Loading Environment Variables
Load the environment variables and retrieve your API key:
# Load environment variables
load_dotenv()
# Get API key from environment variable
OPENROUTER_API_KEY = os.getenv('OPENROUTER_API_KEY')
REFERRER = "https://walterpinem.com/"
APP_NAME = "Simple AI Translator"
Defining Available AI Models
Create a list of free AI models available through OpenRouter:
# Free AI models
AI_MODELS = [
"google/gemini-2.5-pro-exp-03-25:free",
"google/gemma-3-1b-it:free",
"google/gemma-3-4b-it:free",
"google/gemma-3-12b-it:free",
"google/gemma-3-27b-it:free",
"google/gemini-2.0-flash-lite-preview-02-05:free",
"google/gemini-2.0-pro-exp-02-05:free",
"google/gemini-2.0-flash-thinking-exp:free",
"google/gemini-2.0-flash-thinking-exp-1219:free",
"google/gemini-2.0-flash-exp:free",
"google/learnlm-1.5-pro-experimental:free",
"google/gemini-flash-1.5-8b-exp",
"google/gemma-2-9b-it:free",
"deepseek/deepseek-chat-v3-0324:free",
"deepseek/deepseek-r1-zero:free",
"deepseek/deepseek-r1-distill-llama-70b:free",
"deepseek/deepseek-r1:free",
"deepseek/deepseek-chat:free",
"meta-llama/llama-3.3-70b-instruct:free",
"meta-llama/llama-3.2-3b-instruct:free",
"meta-llama/llama-3.2-1b-instruct:free",
"meta-llama/llama-3.2-11b-vision-instruct:free",
"meta-llama/llama-3.1-8b-instruct:free",
"meta-llama/llama-3-8b-instruct:free",
"qwen/qwen2.5-vl-3b-instruct:free",
"qwen/qwen2.5-vl-32b-instruct:free",
"qwen/qwq-32b:free",
"qwen/qwen2.5-vl-72b-instruct:free",
"deepseek/deepseek-r1-distill-qwen-32b:free",
"deepseek/deepseek-r1-distill-qwen-14b:free",
"qwen/qwq-32b-preview:free",
"qwen/qwen-2.5-coder-32b-instruct:free",
"qwen/qwen-2.5-72b-instruct:free",
"qwen/qwen-2.5-vl-7b-instruct:free",
"qwen/qwen-2-7b-instruct:free",
"allenai/molmo-7b-d:free",
"bytedance-research/ui-tars-72b:free",
"featherless/qwerky-72b:free",
"mistralai/mistral-small-3.1-24b-instruct:free",
"open-r1/olympiccoder-7b:free",
"open-r1/olympiccoder-32b:free",
"rekaai/reka-flash-3:free",
"moonshotai/moonlight-16b-a3b-instruct:free",
"nousresearch/deephermes-3-llama-3-8b-preview:free",
"cognitivecomputations/dolphin3.0-r1-mistral-24b:free",
"cognitivecomputations/dolphin3.0-mistral-24b:free",
"mistralai/mistral-small-24b-instruct-2501:free",
"sophosympatheia/rogue-rose-103b-v0.2:free",
"nvidia/llama-3.1-nemotron-70b-instruct:free",
"mistralai/mistral-nemo:free",
"mistralai/mistral-7b-instruct:free",
"microsoft/phi-3-mini-128k-instruct:free",
"microsoft/phi-3-medium-128k-instruct:free",
"openchat/openchat-7b:free",
"undi95/toppy-m-7b:free",
"huggingfaceh4/zephyr-7b-beta:free",
"gryphe/mythomax-l2-13b:free"
]
Feel free to add more models, including paid ones, if you have access. Find more models on OpenRouter’s Models page.
Creating the Translation Function
Define a function to handle the translation using the OpenRouter API:
def translate_text(text, source_lang, target_lang, model):
response = requests.post(
url="https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
"HTTP-Referer": REFERRER,
"X-Title": APP_NAME,
},
data=json.dumps({
"model": model,
"messages": [
{
"role": "system",
"content": f"You are a translator. Translate the given text from {source_lang} to {target_lang}. Only provide the translation, no additional explanations."
},
{
"role": "user",
"content": text
}
]
})
)
if response.status_code == 200:
return response.json()['choices'][0]['message']['content']
else:
return f"Error: {response.status_code}, {response.text}"
This function sends a POST request to the OpenRouter API with the user’s input and returns the translated text.
Building the Streamlit User Interface
Now, let’s construct the web interface using Streamlit:
# Streamlit UI
st.title("AI Translator")
# Input text area
input_text = st.text_area("Enter text to translate:", height=150)
# Language selection
col1, col2 = st.columns(2)
with col1:
source_lang = st.selectbox("Source Language", ["English", "Spanish", "French", "German", "Chinese", "Japanese"])
with col2:
target_lang = st.selectbox("Target Language", ["Spanish", "English", "French", "German", "Chinese", "Japanese"])
# Model selection
selected_model = st.selectbox("Select AI Model", AI_MODELS)
- Title and Text Input: Sets the app title and a text area for user input.
- Language Selection: Provides dropdown menus to select source and target languages.
- Model Selection: Allows users to choose from the list of AI models.
Adding the Translate Button
Implement the logic for the “Translate” button:
# Translate button
if st.button("Translate"):
if input_text and source_lang != target_lang:
with st.spinner("Translating..."):
translated_text = translate_text(input_text, source_lang, target_lang, selected_model)
st.subheader("Translated Text:")
st.write(translated_text)
elif source_lang == target_lang:
st.warning("Please select different languages for source and target.")
else:
st.warning("Please enter some text to translate.")
- Validation: Checks if the input text is provided and source and target languages are different.
- Translation: Calls the
translate_text
function and displays the result. - User Feedback: Provides warnings if validations fail.
Adding Sidebar Information
Include additional information about the app in the sidebar:
# Add a note about the API usage
st.sidebar.markdown("This translator uses the OpenRouter API to access various AI models for translation.")
st.sidebar.markdown("Different models may have different capabilities and performance characteristics.")
st.sidebar.markdown("For more info, you can read [**this tutorial**](https://walterpinem.com/getting-started-with-openrouter/).")
Running the App
Save your app.py
file and run the Streamlit app using:
streamlit run app.py
This command will open the app in your default web browser.
Exploring the App
- Input Text: Type or paste the text you want to translate.
- Select Languages: Choose the source language of your text and the target language for translation.
- Choose AI Model: Select an AI model from the dropdown. Different models may yield different translation results.
- Translate: Click the “Translate” button to see the translated text.
Understanding the Code
Let’s break down some key parts of the code:
The translate_text
Function
This function is the core of the app. It constructs the API request and handles the response.
- Headers: Include authorization and app metadata.
- Payload: Specifies the model and the messages, following OpenAI’s chat completion format.
- Error Handling: Returns an error message if the request fails.
Streamlit Interface
- Title and Text Area: Provides a user-friendly interface for input.
- Columns: Organizes the language selection side by side.
- Spinner: Gives visual feedback during the translation process.
- Subheader and Write: Displays the translated text.
Model Flexibility
By allowing users to select from different AI models, the app demonstrates how model choice can affect translation quality and performance.
Customizing the App
Feel free to enhance the app by:
- Adding More Languages: Expand the
source_lang
andtarget_lang
lists. - Including Paid Models: If you have access, add paid AI models to the
AI_MODELS
list. - Improving Error Messages: Provide more detailed feedback based on different HTTP status codes.
- Styling: Use Streamlit’s styling options to improve the app’s appearance.
Putting It All Together
Here’s the complete Python script:
import streamlit as st
import requests
import json
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Get API key from environment variable
OPENROUTER_API_KEY = os.getenv('OPENROUTER_API_KEY')
REFERRER = "https://walterpinem.com/" # Replace with your actual site URL
APP_NAME = "Simple AI Translator"
# Free AI models
AI_MODELS = [
"google/gemini-2.5-pro-exp-03-25:free",
"google/gemma-3-1b-it:free",
"google/gemma-3-4b-it:free",
"google/gemma-3-12b-it:free",
"google/gemma-3-27b-it:free",
"google/gemini-2.0-flash-lite-preview-02-05:free",
"google/gemini-2.0-pro-exp-02-05:free",
"google/gemini-2.0-flash-thinking-exp:free",
"google/gemini-2.0-flash-thinking-exp-1219:free",
"google/gemini-2.0-flash-exp:free",
"google/learnlm-1.5-pro-experimental:free",
"google/gemini-flash-1.5-8b-exp",
"google/gemma-2-9b-it:free",
"deepseek/deepseek-chat-v3-0324:free",
"deepseek/deepseek-r1-zero:free",
"deepseek/deepseek-r1-distill-llama-70b:free",
"deepseek/deepseek-r1:free",
"deepseek/deepseek-chat:free",
"meta-llama/llama-3.3-70b-instruct:free",
"meta-llama/llama-3.2-3b-instruct:free",
"meta-llama/llama-3.2-1b-instruct:free",
"meta-llama/llama-3.2-11b-vision-instruct:free",
"meta-llama/llama-3.1-8b-instruct:free",
"meta-llama/llama-3-8b-instruct:free",
"qwen/qwen2.5-vl-3b-instruct:free",
"qwen/qwen2.5-vl-32b-instruct:free",
"qwen/qwq-32b:free",
"qwen/qwen2.5-vl-72b-instruct:free",
"deepseek/deepseek-r1-distill-qwen-32b:free",
"deepseek/deepseek-r1-distill-qwen-14b:free",
"qwen/qwq-32b-preview:free",
"qwen/qwen-2.5-coder-32b-instruct:free",
"qwen/qwen-2.5-72b-instruct:free",
"qwen/qwen-2.5-vl-7b-instruct:free",
"qwen/qwen-2-7b-instruct:free",
"allenai/molmo-7b-d:free",
"bytedance-research/ui-tars-72b:free",
"featherless/qwerky-72b:free",
"mistralai/mistral-small-3.1-24b-instruct:free",
"open-r1/olympiccoder-7b:free",
"open-r1/olympiccoder-32b:free",
"rekaai/reka-flash-3:free",
"moonshotai/moonlight-16b-a3b-instruct:free",
"nousresearch/deephermes-3-llama-3-8b-preview:free",
"cognitivecomputations/dolphin3.0-r1-mistral-24b:free",
"cognitivecomputations/dolphin3.0-mistral-24b:free",
"mistralai/mistral-small-24b-instruct-2501:free",
"sophosympatheia/rogue-rose-103b-v0.2:free",
"nvidia/llama-3.1-nemotron-70b-instruct:free",
"mistralai/mistral-nemo:free",
"mistralai/mistral-7b-instruct:free",
"microsoft/phi-3-mini-128k-instruct:free",
"microsoft/phi-3-medium-128k-instruct:free",
"openchat/openchat-7b:free",
"undi95/toppy-m-7b:free",
"huggingfaceh4/zephyr-7b-beta:free",
"gryphe/mythomax-l2-13b:free"
]
# Function to translate text
def translate_text(text, source_lang, target_lang, model):
response = requests.post(
url="https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
"HTTP-Referer": REFERRER,
"X-Title": APP_NAME,
},
data=json.dumps({
"model": model,
"messages": [
{
"role": "system",
"content": f"You are a translator. Translate the given text from {source_lang} to {target_lang}. Only provide the translation, no additional explanations."
},
{
"role": "user",
"content": text
}
]
})
)
if response.status_code == 200:
return response.json()['choices'][0]['message']['content']
else:
return f"Error: {response.status_code}, {response.text}"
# Streamlit UI
st.title("AI Translator")
# Input text area
input_text = st.text_area("Enter text to translate:", height=150)
# Language selection
col1, col2 = st.columns(2)
with col1:
# Add more languages as needed
source_lang = st.selectbox("Source Language", ["English", "Spanish", "French", "German", "Chinese", "Japanese"])
with col2:
# Add more languages as needed
target_lang = st.selectbox("Target Language", ["Spanish", "English", "French", "German", "Chinese", "Japanese"])
# Model selection
selected_model = st.selectbox("Select AI Model", AI_MODELS)
# Translate button
if st.button("Translate"):
if input_text and source_lang != target_lang:
with st.spinner("Translating..."):
translated_text = translate_text(input_text, source_lang, target_lang, selected_model)
st.subheader("Translated Text:")
st.write(translated_text)
elif source_lang == target_lang:
st.warning("Please select different languages for source and target.")
else:
st.warning("Please enter some text to translate.")
# Add a note about the API usage
st.sidebar.markdown("This translator uses the OpenRouter API to access various AI models for translation.")
st.sidebar.markdown("Different models may have different capabilities and performance characteristics.")
st.sidebar.markdown("For more info, you can read [**this tutorial**](https://walterpinem.com/getting-started-with-openrouter/).")
Check it on Github repository.
By following this tutorial, you’ve created a simple AI Translator app that leverages the power of AI models through the OpenRouter API.
This project not only demonstrates how to integrate AI into applications but also provides a foundation for more complex language processing tools.
How to Create an Audiobook App Using Python and Streamlit
How to Create an Audiobook App Using Python and Streamlit – I often listen to podcasts and ... Read More
Feel free to share your experiences, suggest improvements, or ask questions in the comments below. Happy coding!