Using Gemini 3.6 Flash via Unorouter API for Text Generation
Learn how to use Google's free Gemini 3.6 Flash model through the Unorouter API for text generation tasks.
Introduction
Gemini 3.6 Flash is Google's latest fast, efficient model available for free through various API providers. Unorouter provides a unified gateway to access this and other free models. This tutorial walks you through setting up and using the API for text generation.
Prerequisites
- Python 3.8+
-
requestslibrary:pip install requests - Unorouter API key (free at https://unorouter.com)
Step-by-Step Setup
1. Get Your API Key
- Sign up at unorouter.com
- Navigate to API Keys in your dashboard
- Copy your API key
- Set as environment variable:
export UNOROUTER_API_KEY="your-key-here"
2. Basic Text Generation
import requests
import os
UNOROUTER_URL = "https://api.unorouter.com/v1/chat/completions"
def generate_text(prompt: str, model: str = "google/gemini-3.6-flash:free") -> str:
"""Generate text using Unorouter API with Gemini 3.6 Flash."""
headers = {
"Authorization": f"Bearer {os.getenv('UNOROUTER_API_KEY')}",
"Content-Type": "application/json"
}
data = {
"model": model,
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.7,
"max_tokens": 1000
}
response = requests.post(UNOROUTER_URL, headers=headers, json=data, timeout=30)
if response.status_code == 200:
return response.json()["choices"][0]["message"]["content"]
else:
raise Exception(f"Error: {response.status_code} - {response.text}")
# Test it
if __name__ == "__main__":
prompt = "Write a haiku about AI and coding"
try:
result = generate_text(prompt)
print(f"Prompt: {prompt}")
print(f"Response: {result}")
except Exception as e:
print(f"Error: {e}")
Advanced Usage
Streaming Responses
import json
def stream_text(prompt: str, model: str = "google/gemini-3.6-flash:free"):
"""Stream text generation for real-time output."""
headers = {
"Authorization": f"Bearer {os.getenv('UNOROUTER_API_KEY')}",
"Content-Type": "application/json"
}
data = {
"model": model,
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.7,
"max_tokens": 1000,
"stream": True
}
response = requests.post(
UNOROUTER_URL,
headers=headers,
json=data,
timeout=30,
stream=True
)
for line in response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith('data: '):
line = line[6:]
if line.strip() == '[DONE]':
break
try:
chunk = json.loads(line)
content = chunk["choices"][0]["delta"].get("content", "")
print(content, end="", flush=True)
except:
pass
print()
Conversation Context
class ChatSession:
def __init__(self, system_prompt: str = None):
self.messages = []
if system_prompt:
self.messages.append({"role": "system", "content": system_prompt})
def send(self, user_message: str) -> str:
self.messages.append({"role": "user", "content": user_message})
headers = {
"Authorization": f"Bearer {os.getenv('UNOROUTER_API_KEY')}",
"Content-Type": "application/json"
}
data = {
"model": "google/gemini-3.6-flash:free",
"messages": self.messages,
"temperature": 0.7,
"max_tokens": 1000
}
response = requests.post(UNOROUTER_URL, headers=headers, json=data, timeout=30)
if response.status_code == 200:
reply = response.json()["choices"][0]["message"]["content"]
self.messages.append({"role": "assistant", "content": reply})
return reply
else:
raise Exception(f"Error: {response.status_code} - {response.text}")
# Usage
if __name__ == "__main__":
chat = ChatSession("You are a helpful coding assistant.")
print(chat.send("How do I reverse a string in Python?"))
print(chat.send("Can you show me with a function?"))
Error Handling & Best Practices
import time
def robust_generate(prompt: str, retries: int = 3) -> str:
"""Generate with retry logic for rate limits."""
for attempt in range(retries):
try:
return generate_text(prompt)
except Exception as e:
if "429" in str(e) or "503" in str(e):
wait = 2 ** attempt
print(f"Rate limited. Waiting {wait}s...")
time.sleep(wait)
else:
raise
raise Exception("Max retries exceeded")
Best Practices:
- Use environment variables for API keys
- Set appropriate timeouts (30s recommended)
- Monitor rate limits - Free tier has limits
- Use streaming for long responses
- Cache responses during development
- Handle errors gracefully with retries
Conclusion
The Unorouter API with Gemini 3.6 Flash provides free, fast text generation perfect for prototyping, content creation, and learning. With simple Python integration, you can build powerful AI applications without API costs.
Top comments (0)