Learn how to integrate AI into your Python projects using free APIs - no GPU required, no complex setup.
AI integration doesn't require expensive hardware or complex ML knowledge. With free APIs like OpenRouter, Hugging Face, and Google AI Studio, you can add AI capabilities to any Python project in minutes.
requests library: pip install requests
import requests
import os
def openrouter_chat(prompt: str, model: str = "google/gemini-2.0-flash-exp:free") -> str:
"""Chat with free models via OpenRouter."""
response = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {os.getenv('OPENROUTER_API_KEY')}",
"Content-Type": "application/json"
},
json={
"model": model,
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.7,
"max_tokens": 500
},
timeout=30
)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"]
print(openrouter_chat("Write a Python function to reverse a string"))
python
import requests
import os
def hf_inference(prompt: str, model: str = "google/flan-t5-base") -> str:
"""Use Hugging Face free inference API."""
response = requests.post(
f"https://api-inference.huggingface.co/models/{model}",
headers={"Authorization": f"Bearer {os.getenv('HF_TOKEN')}"} if os.getenv('HF_TOKEN') else {},
json={"inputs": prompt},
timeout=30
)
response.raise_for_status()
return response.json()[0]["generated_text"]
print(hf_inference("Translate to Spanish: Hello world"))
php
import requests
import os
def gemini_generate(prompt: str) -> str:
"""Generate text with Google's free Gemini model."""
api_key = os.getenv("GEMINI_API_KEY")
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={api_key}"
response = requests.post(
url,
headers={"Content-Type": "application/json"},
json={
"contents": [{"parts": [{"text": prompt}]}],
"generationConfig": {"temperature": 0.7, "maxOutputTokens": 500}
},
timeout=30
)
response.raise_for_status()
return response.json()["candidates"][0]["content"]["parts"][0]["text"]
print(gemini_generate("Explain decorators in Python"))
python
import requests
import os
import json
class AICodeReviewer:
def __init__(self):
self.api_key = os.getenv("OPENROUTER_API_KEY")
self.url = "https://openrouter.ai/api/v1/chat/completions"
def review(self, code: str, language: str = "python") -> dict:
prompt = f"""Review this {language} code for:
1. Bugs and logic errors
2. Performance issues
3. Best practices
4. Security concerns
Code:
```
{% endraw %}
{language}
{code}
{% raw %}
```
Return JSON: {{"issues": [...], "suggestions": [...], "rating": 1-10}}"""
response = requests.post(
self.url,
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": "google/gemini-2.0-flash-exp:free",
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.3,
"max_tokens": 1000
},
timeout=30
)
response.raise_for_status()
return json.loads(response.json()["choices"][0]["message"]["content"])
reviewer = AICodeReviewer()
code = """
def process_users(users):
for user in users:
if user['age'] > 18:
print(user['name'])
"""
result = reviewer.review(code)
print(f"Rating: {result['rating']}/10")
for issue in result['issues']:
print(f"- {issue}")
python
import time
import requests
def robust_ai_call(func, *args, retries=3, **kwargs):
"""Wrapper with exponential backoff for rate limits."""
for attempt in range(retries):
try:
return func(*args, **kwargs)
except requests.exceptions.HTTPError as e:
if e.response.status_code in (429, 503):
wait = 2 ** attempt
print(f"Rate limited, waiting {wait}s...")
time.sleep(wait)
else:
raise
raise Exception("Max retries exceeded")
result = robust_ai_call(openrouter_chat, "Hello!")
.env files, never commit API keysgoogle/gemini-2.0-flash-exp:free
meta-llama/llama-3.1-8b-instruct:free
mistralai/mistral-7b-instruct:free
| Provider | Free Models | Rate Limit | Best For |
|---|---|---|---|
| OpenRouter | 20+ | Varies | Model variety |
| Hugging Face | 1000+ | Generous | Specialized models |
| Google AI | 1 (Gemini) | 15 RPM | Quality, speed |
| Together.ai | Several | Good | Open source models |
Adding AI to Python is now as simple as making an HTTP request. Start with one provider, experiment with prompts, and build something amazing - all for free!
Next Steps:
Published as part of the AI Tutorials series on Dev.to