Testing OpenRouter API: Free AI Model Access
Learn how to test and use free AI models through OpenRouter's unified API.
Prerequisites
- OpenRouter account (free at https://openrouter.ai)
- Python 3.8+ with
requests:pip install requests - API key from OpenRouter dashboard
Quick Test with curl
curl -X POST https://openrouter.ai/api/v1/chat/completions \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "google/gemini-2.0-flash-exp:free", "messages": [{"role": "user", "content": "Say hello in 3 languages"}] }' Python Integration
import requests import os OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions" def test_openrouter(prompt: str, model: str = "google/gemini-2.0-flash-exp:free") -> str: """Test OpenRouter API with a prompt.""" headers = { "Authorization": f"Bearer {os.getenv('OPENROUTER_API_KEY')}", "Content-Type": "application/json" } data = { "model": model, "messages": [{"role": "user", "content": prompt}], "temperature": 0.7, "max_tokens": 150 } response = requests.post(OPENROUTER_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 = "Explain the difference between REST and GraphQL in 2 sentences" try: result = test_openrouter(prompt) print(f"Q: {prompt}") print(f"A: {result}") except Exception as e: print(f"Error: {e}") Free Models Available
OpenRouter offers many free models (look for :free suffix):
| Model | Best For |
|---|---|
google/gemini-2.0-flash-exp:free | General chat, coding |
meta-llama/llama-3.1-8b-instruct:free | Reasoning, analysis |
mistralai/mistral-7b-instruct:free | Fast responses |
microsoft/phi-3-mini-128k-instruct:free | Long context |
Best Practices
- Use environment variables for API keys
- Monitor rate limits - Free tier has limits
- Set max_tokens to control response length
- Handle errors gracefully with retries
- Test multiple models to find the best fit
Conclusion
OpenRouter provides a unified interface to dozens of free AI models. Perfect for testing, learning, and building AI-powered applications without API costs.
