Alright bacho, welcome back.
Pichle lesson mein humne Tier 1 dekha tha — saste, fast, rule-based filters. Lekin market hamesha seedhay rules pe nahi chalti. Sometimes you need a bit of 'nuance', thori si 'intelligence'. Lekin har choti cheez ke liye GPT-4 ya Claude Opus ko call karna aisa hai jaise anda lene ke liye new Land Cruiser nikaal li ho. Akalmand kaam nahi hai, ajeeb sa show-off hai aur petrol ka kharcha alag.
That's where Tier 2 comes in. Ye hamara gatekeeper hai, hamara sasta lekin smart chowkidaar. Iska naam hai Claude Haiku.
Seedhi baat hai: paisa bachane ke liye.
Anthropic company ke teen main models hain: Haiku (sabse fast aur cheap), Sonnet (beech wala), aur Opus (sabse powerful aur mehenga). Haiku per call sirf $0.00025 per 1k input tokens lagta hai. Iska matlab hai ke ek aam analysis call aapko PKR 0.50 ( पचास पैसे) se bhi kam mein parti hai. Han, sahi parha. Aadha rupia.
Itna sasta hai ke isko hum liberally use kar sakte hain. Ye hamara first line of AI defense hai. Hamare scanner.py se jab bhi koi naya market ya event ata hai, hum pehle Haiku se puchte hain, "Bhai, is mein dum hai? Ispe aage time aur paisa lagana chahiye ya ignore karun?"
Haiku 90% fazool ideas ko pehle hi "No" bol deta hai. Sirf jo 10% promising lagte hain, wohi aage Tier 3 (Sonnet) ya Tier 4 (Opus/Gemini) ke paas jaate hain. This is the core of our 4-Tier system: Fail fast, fail cheap.
Chalo, practical kaam karte hain. Sabse pehle, aapko Anthropic ki API key chahiye hogi.
setx ANTHROPIC_API_KEY " आपकी-API-key-yahan"echo 'export ANTHROPIC_API_KEY=" आपकी-API-key-yahan"' >> ~/.zshrc && source ~/.zshrc (agar bash use kar rahe ho to .bashrc)Ye karne se aapka key system-wide available hojayega aur aapka code saaf rahega.
ai/haiku.py Ko Cheertay HainAb aate hain asal code pe jo hamare project mein ai/haiku.py file mein hai. Ye function hamare bot ka workhorse hai. Har cheez yahin se guzarti hai.
# ai/haiku.py
import requests
import json
import os
import time # Failover ke liye add kar rahe hain
# Model ka version hardcode karna aam taur pe a good practice hai
# taake updates se hamara system na phat jaye.
MODEL = 'claude-3-haiku-20240307'
API_URL = 'https://api.anthropic.com/v1/messages'
def haiku_call(prompt, module='unknown', max_tokens=1000):
"""
Tier 2: Claude Haiku — cheap analyst that gates expensive models.
Ye function primary aur secondary API keys ke beech failover bhi handle karta hai.
"""
# API Key Failover Logic
# Pehle primary key try karo, na chale to secondary.
api_keys = [
os.environ.get('ANTHROPIC_API_KEY_PRIMARY'),
os.environ.get('ANTHROPIC_API_KEY_SECONDARY')
]
for i, api_key in enumerate(api_keys):
if not api_key:
print(f'[HAIKU] API Key #{i+1} not found, skipping.')
continue
print(f"[HAIKU] Attempting call with API Key #{i+1} for module: {module}")
headers = {
'x-api-key': api_key,
'anthropic-version': '2023-06-01',
'content-type': 'application/json'
}
body = {
'model': MODEL,
'max_tokens': max_tokens,
'messages': [{'role': 'user', 'content': prompt}]
}
try:
r = requests.post(API_URL, headers=headers, json=body, timeout=30)
if r.status_code == 200:
data = r.json()
text_response = data['content'][0]['text']
# Cost Calculation - Pata hona chahiye kitna kharcha ho raha hai
input_tokens = data.get('usage', {}).get('input_tokens', 0)
output_tokens = data.get('usage', {}).get('output_tokens', 0)
# Haiku pricing: $0.25/M input, $1.25/M output tokens
cost = ((input_tokens / 1_000_000) * 0.25) + ((output_tokens / 1_000_000) * 1.25)
print(f"[HAIKU] Success! Cost: ${cost:.6f} (PKR ~{(cost * 278):.4f})")
return text_response
# Handle specific error codes
elif r.status_code == 429: # Rate limit error
print(f"[HAIKU] Error 429: Rate limit exceeded with key #{i+1}. Trying next key...")
time.sleep(2) # Thora sa wait karo
else:
print(f'[HAIKU] Error {r.status_code} with key #{i+1}: {r.text[:200]}')
# Agar invalid key ka error hai to agle pe jao, warna break
if 'authentication_error' in r.text:
continue
else:
break
except requests.exceptions.RequestException as e:
print(f'[HAIKU] Request failed with key #{i+1}: {e}')
print("[HAIKU] All API keys failed. Returning None.")
return None
Chalo isko torrtay hain:
MODEL & API_URL: Ye constants hain. Inko upar define karne se code saaf rehta hai. Humne model ka poora naam date ke saath use kiya hai. This is a pro move, kyunke agar Anthropic naya default model launch kare to hamara prompt ajeeb behave na karne lag jaye.for loop dekho. Humne ek list banayi api_keys ki. Ye pehle ANTHROPIC_API_KEY_PRIMARY uthata hai. Agar wo fail hojaye (ya set na ho), to ANTHROPIC_API_KEY_SECONDARY try karta hai. Real world trading bots mein redundancy bohot zaroori hai. Ek key ka credit khatam ho sakta hai, ya woh temporarily block ho sakti hai. Bot rukna nahi chahiye.headers: Ye request ka metadata hai.
x-api-key: Yahan aapki secret key jaati hai.anthropic-version: Ye batata hai ke hum API ka konsa version use kar rahe hain. Important for stability.content-type: Hum bata rahe hain ke hum JSON format mein data bhej rahe hain.body: Ye hamara asal message hai.
model: Hum konsa model use kar rahe hain.max_tokens: AI ko kitna lamba jawab dena hai, uski limit. Kharcha control karne ke liye zaroori hai.messages: Ye list of dictionaries hai. Ismein `