4.3 — Tier 2 — Claude Haiku: Cheap But Smart Analyst
Tier 2 — Claude Haiku: Cheap But Smart Analyst
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.
MODULE 4: AI Signal Engine — 4-Tier Decision System Banana
LESSON 4.3: Tier 2 — Claude Haiku: Cheap But Smart Analyst
Haiku Kya Cheez Hai Aur Hum Ise Kyun Use Kar Rahe Hain?
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.
Anthropic API Setup & Authentication — Pehla Qadam
Chalo, practical kaam karte hain. Sabse pehle, aapko Anthropic ki API key chahiye hogi.
- Account Banao: anthropic.com pe jao aur account banao. Console mein login karo.
- API Key Nikalo: Settings ya API Keys ke section mein jao aur ek new key generate karo. Isko copy karke kisi safe jagah, jaise password manager, mein save karlo. Is key ko code mein direct paste nahi karna. Kabhi nahi.
- Environment Variable Set Karo: Hum professional tareeqay se kaam karenge. Apne system mein ek environment variable set karo.
- Windows (Command Prompt):
setx ANTHROPIC_API_KEY " आपकी-API-key-yahan" - macOS/Linux (Terminal):
echo 'export ANTHROPIC_API_KEY=" आपकी-API-key-yahan"' >> ~/.zshrc && source ~/.zshrc(agar bash use kar rahe ho to.bashrc)
- Windows (Command Prompt):
Ye karne se aapka key system-wide available hojayega aur aapka code saaf rahega.
Code Breakdown: ai/haiku.py Ko Cheertay Hain
Ab 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.- API Key Failover: Ye simple
forloop dekho. Humne ek list banayiapi_keyski. Ye pehleANTHROPIC_API_KEY_PRIMARYuthata hai. Agar wo fail hojaye (ya set na ho), toANTHROPIC_API_KEY_SECONDARYtry 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 system and user prompts hote hain.
Tier 2 uses Claude Haiku for deeper analysis while maintaining cost efficiency.
📺 Recommended Videos & Resources
- Claude 3 Haiku API Guide — Haiku model documentation
- Type: Official Documentation
- Link description: Learn Haiku API integration and parameters
- Prompt Templates for Trading Analysis — Effective trading prompts
- Type: YouTube
- Link description: Search "Claude prompt engineering trading"
- Token Counting & Cost Estimation — Understanding LLM tokens
- Type: Wikipedia
- Link description: Learn how tokens affect cost and performance
- Structured Outputs from Claude — JSON mode for parsing
- Type: Official Documentation
- Link description: Reference JSON mode for consistent outputs
- Multi-Turn Conversations with LLMs — Building conversation context
- Type: YouTube
- Link description: Search "Claude multi-turn conversation examples"
🎯 Mini-Challenge
5-Minute Practical Task: Write a function using Claude Haiku that takes market data (title, price, volume, news summary) and returns a JSON with: "analysis" (text), "is_strong_candidate" (boolean), "confidence_score" (0-1), "analysis_summary" (2-sentence max). Verify it runs under 2 seconds and costs less than $0.01.
🖼️ Visual Reference
📊 Tier 2 (Claude Haiku) Detailed Analysis
┌──────────────────────────────┐
│ From Tier 1 (Proceeds=true) │
│ - Title, news, basic score │
└────────────┬─────────────────┘
│
▼
┌──────────────────────────────┐
│ Haiku Receives: │
│ - Market title & description │
│ - Tier 1 reasoning │
│ - Price history (if available│
│ - Recent volume trend │
└────────────┬─────────────────┘
│
▼
┌──────────────────────────────┐
│ Haiku Analysis (~$0.002) │
│ - Look for price patterns │
│ - Evaluate momentum │
│ - Cross-check with market age│
└────────────┬─────────────────┘
│
▼
┌──────────────────────────────┐
│ Return Decision: │
│ { │
│ "candidate": true, │
│ "confidence": 0.85, │
│ "summary": "Strong uptrend"│
│ } │
└────────────┬─────────────────┘
│
┌────┴─────┐
│ (YES) │ (NO)
▼ ▼
┌────────┐ ┌──────┐
│ Tier 3 │ │ STOP │
│(Sonnet)│ │ │
└────────┘ └──────┘
Lesson Summary
Quiz: Tier 2 — Claude Haiku: Cheap But Smart Analyst
4 questions to test your understanding. Score 60% or higher to pass.