4.2 — Tier 1 — Gemini Flash: Free Data Grunt
Tier 1 — Gemini Flash: Free Data Grunt
Bismillah. Chalo bachon, welcome to Lesson 4.2.
Module 4 hamare bot ka dimaagh hai, aql hai. Pichle lesson mein humne 4-Tier system ka blueprint dekha tha. Aaj hum pehli, aur sabse important, tier ko code kareinge: Gemini Flash. Isko samjho hamare bot ka "common sense" — a fast, free, and surprisingly smart worker jo pehla filter lagata hai. Ye woh grunt worker hai jo hazaron signals mein se kaam ki cheez nikaal kar senior models ko dega.
Agar yeh tier sahi se kaam nahi karti, toh aage ke saare mehenge models fazool data pe apna time aur aapke paise zaya kareinge. So, pay close attention. Yeh foundation hai.
Lesson 4.2: Tier 1 — Gemini Flash: Free Data Grunt
Duration: 35 minutes
Aaj ka Agenda:
- Gemini Flash - Scene Kya Hai? Kyun hum yeh model use kar rahe hain.
- API Setup: Google se free connection kaise banana hai.
- Code Deep Dive: Hamare
ai/gemini.pyfile ka line-by-line breakdown. - Prompt Engineering: Sahi sawaal poochne ka art.
- Integration: Yeh chhota sa function hamare
scanner.pyaurstrategiesmein kaise fit hota hai.
Gemini Flash — Hamara Pehla AI Sipahi
Socho, aapne KSE-100 (Karachi Stock Exchange) ke saare stocks pe nazar rakhni hai. Har minute naye news articles, TV headlines, aur social media posts aa rahe hain. Kya aap har cheez ke liye ek expensive, slow AI model (like GPT-4) use karoge? Bilkul nahi. That's financial suicide.
Yahan pe aata hai Gemini Flash. Yeh Google ka ek halka phulka, super-fast, aur sabse important, free model hai.
Kyun Gemini Flash?
- Cost: Zero. F-R-E-E. Google ka free tier 15 Requests Per Minute (RPM) deta hai. Start karne ke liye yeh bohot hai. Jab bot din mein 20,000 calls karega, tab cost ahem ho jaati hai.
- Speed: It's fast. Humein market data pe quick analysis chahiye, ghanton ka intezar nahi karna.
- Capability: Yeh sentiment analysis, text summarization, aur basic reasoning ke liye kaafi acha hai. "Is this news about Engro Corp positive or negative?" — is type ke sawaalon ke liye perfect hai.
Yeh hamara pehla gatekeeper hai. Iska kaam hai 90% bekaar noise ko filter karna taake sirf 10% high-potential signals aage, Tier 2 (Haiku) ke paas jaayen.
API Setup — Google Se Connection Banana
Chalo, pehle API key lete hain. Iske bina code nahi chalega.
- Go to Google AI Studio: Apne Google account se https://aistudio.google.com/ pe jao.
- Get API Key: Upar "Get API key" ka button hoga. Click karo.
- Create API Key: "Create API key in new project" pe click karke apni key generate karlo.
- Copy and Save: Is key ko copy karke kahin safe jagah pe rakho. Yeh aapke bank account ke password jaisa hai. Kisi ke saath share nahi karna.
Ab is key ko apne code mein use karna hai. Lekin direct code mein paste nahi karna!
💀 Common Galti: Hardcoding API Keys
Bohot se naye developers yeh galti karte hain. Woh apni API key direct Python file mein is tarah likh dete hain:
# BURA TARIKA - AISA KABHI NAHI KARNA
GEMINI_KEY = "AIz...YourSecretKey...xyz"
Agar aapne yeh code galti se bhi GitHub pe daal diya, toh bots aapki key ko minutes mein dhoond kar uska mis-use karna shuru kar denge, aur aapko hazaron dollars ka bill aa sakta hai. Hamesha Environment Variables use karo.
Sahi Tarika (Environment Variable):
Apne terminal (Linux/Mac) ya command prompt (Windows) mein yeh command chalao:
For Linux/macOS:
export GEMINI_API_KEY="AIz...YahanApniKeyPasteKaro...xyz"
For Windows (Command Prompt):
set GEMINI_API_KEY="AIz...YahanApniKeyPasteKaro...xyz"
Yeh sirf current session ke liye key set karega. Isko permanently set karne ke liye, aapko apni shell ki profile file (.bashrc, .zshrc) ya Windows Environment Variables settings mein add karna hoga.
Ab hamara code os.environ.get('GEMINI_API_KEY') use karke is key ko safely access kar sakta hai.
Code Deep Dive: ,[object Object]
Yeh hamare codebase ki file ai/gemini.py ka core function hai. Isko samjho, poora Tier 1 system samajh aa jayega. Let's break it down, line by line.
# ai/gemini.py
import requests # API calls ke liye
import os # Environment variables parhne ke liye
import time # Rate limiting ke liye (rukne ke liye)
import json # Data ko handle karne ke liye (abhi use nahi ho raha, but good practice)
# Step 1: Configuration
GEMINI_KEY = os.environ.get('GEMINI_API_KEY', '')
MODEL = 'gemini-1.5-flash-latest' # Google recommends using the 'latest' tag
BASE_URL = 'https://generativelanguage.googleapis.com/v1beta'
_last_call = 0 # Track karta hai ke aakhri call kab ki thi
def gemini_call(prompt, module='unknown'):
"""Tier 1: Free AI call via Gemini Flash."""
global _last_call
# Step 2: API Key Check & Fallback Trigger
if not GEMINI_KEY:
print('[GEMINI] No API key — falling back to Haiku')
return None # None return karne ka matlab hai: "Mujhse nahi ho paya, agle tier ko try karo"
# Step 3: Rate Limiting - Sabr ka Phal Meetha
# Google 15 RPM deta hai. 60 seconds / 15 = 4 seconds per call.
elapsed = time.time() - _last_call
if elapsed < 4:
# Agar pichli call ko 4 second se kam hue hain, toh baaki time wait karo
time.sleep(4 - elapsed)
# Step 4: API Request Tayyar Karna
url = f'{BASE_URL}/models/{MODEL}:generateContent?key={GEMINI_KEY}'
body = {
'contents': [{'parts': [{'text': prompt}]}],
'generationConfig': {
'temperature': 0.1, # Kam temperature = more predictable, less "creative" output. Analysis ke liye best.
'maxOutputTokens': 1000 # Response kitna lamba ho sakta hai
}
}
# Step 5: Asal API Call aur Error Handling
try:
r = requests.post(url, json=body, timeout=30) # 30 second ka timeout, warna phans jayega
_last_call = time.time() # Call ke foran baad time note karlo
if r.status_code == 200:
# Sab theek raha
data = r.json()
# Yeh response structure Google ki documentation se milta hai
return data['candidates'][0]['content']['parts'][0]['text']
# Agar koi aur status code aaya (e.g., 429 Too Many Requests)
print(f'[GEMINI] Error {r.status_code}: {r.text}')
return None # Phir se fallback
except requests.exceptions.RequestException as e:
# Network error, timeout, etc.
print(f'[GEMINI] Failed: {e}')
Tier 1 filters provide initial screening cost-effectively, reducing computational load on premium models.
---
## 📺 Recommended Videos & Resources
- **[Google Gemini API Documentation](https://ai.google.dev/)** — Gemini models and API reference
- Type: Official Documentation
- Link description: Learn Gemini Flash, Pro, and rate limits
- **[Free API Keys & Rate Limits](https://www.youtube.com/results?search_query=google+gemini+free+api+key+rate+limits)** — Understanding free tier constraints
- Type: YouTube
- Link description: Search "Gemini API free tier rate limits"
- **[Sentiment Analysis with LLMs](https://en.wikipedia.org/wiki/Sentiment_analysis)** — News and text analysis
- Type: Wikipedia
- Link description: Learn sentiment analysis for market context
- **[Real-Time News APIs](https://newsapi.org/)** — Accessing market news data
- Type: Official Website
- Link description: NewsAPI provides free market headlines
- **[Pattern Recognition in Time Series](https://www.youtube.com/results?search_query=pattern+recognition+time+series+python)** — Identifying market patterns
- Type: YouTube
- Link description: Search "pattern recognition trading Python"
---
## 🎯 Mini-Challenge
**5-Minute Practical Task:** Create a function using Gemini Flash (free) that takes a market title and recent news headlines, then returns a JSON with keys: "proceed" (boolean), "reason" (string), and "confidence" (0-1 float). Test with 3 different market scenarios and verify JSON parsing works correctly.
---
## 🖼️ Visual Reference
📊 Tier 1 (Gemini Flash) Workflow ┌─────────────────────────────┐ │ Market Input │ │ - Title: "Will BTC > 70k?" │ │ - News: ["Price near 68k.."]│ │ - Volume: $150,000 │ └────────────┬────────────────┘ │ ▼ ┌─────────────────────────────┐ │ Gemini Flash API Call │ │ (FREE - No API key needed) │ └────────────┬────────────────┘ │ ▼ ┌─────────────────────────────┐ │ Response Parsing │ │ { │ │ "proceed": true, │ │ "reason": "High volume...", │ "confidence": 0.78 │ │ } │ └────────────┬────────────────┘ │ ┌────┴─────┐ │ (YES) │ (NO) ▼ ▼ ┌────────┐ ┌──────┐ │ Tier 2 │ │ SKIP │ │ (Haiku)│ │ │ └────────┘ └──────┘
---
Lesson Summary
Quiz: Tier 1 — Gemini Flash: Free Data Grunt
4 questions to test your understanding. Score 60% or higher to pass.