Python AI Tutorial for Beginners: Your First AI Integration
Learn how to integrate AI into your Python projects using free APIs - no GPU required, no complex setup.
Introduction
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.
Prerequisites
- Python 3.8+
-
requestslibrary:pip install requests - Free API keys (all available at no cost)
Option 1: OpenRouter (Multiple Free Models)
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"]
# Usage
print(openrouter_chat("Write a Python function to reverse a string"))
Option 2: Hugging Face Inference API
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"]
# Usage
print(hf_inference("Translate to Spanish: Hello world"))
Option 3: Google Gemini (Free Tier)
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"]
# Usage
print(gemini_generate("Explain decorators in Python"))
Complete Example: AI-Powered Code Reviewer
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"])
# Usage
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}")
Error Handling Template
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")
# Usage
result = robust_ai_call(openrouter_chat, "Hello!")
Best Practices
-
Secure keys: Use
.envfiles, never commit API keys - Handle rate limits: Implement backoff (shown above)
- Set timeouts: Prevent hanging (30s recommended)
-
Choose right model:
- Code:
google/gemini-2.0-flash-exp:free - Chat:
meta-llama/llama-3.1-8b-instruct:free - Fast:
mistralai/mistral-7b-instruct:free
- Code:
- Validate AI output: Don't trust blindly
- Cache during development: Save API calls
Free API Comparison
| 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 |
Conclusion
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:
- Build a CLI tool with AI commands
- Create a chatbot with conversation memory
- Add AI to your web app (Flask/FastAPI)
- Explore function calling for structured output
Published as part of the AI Tutorials series on Dev.to
Top comments (0)