Spaces:
Sleeping
Sleeping
File size: 11,053 Bytes
8d87603 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 |
# ๐ค AI Analysis: LLM vs Heuristic
## What is "Heuristic Analysis"?
**Heuristic** = Analysis based on **rules and simple calculations**, NOT using the AI language model.
### Two Types of AI Analysis:
```
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ AI TACTICAL ANALYSIS โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ ๐ค LLM Analysis (Preferred) โ
โ โโ Uses: Qwen2.5-Coder-1.5B model โ
โ โโ Time: ~15 seconds โ
โ โโ Quality: โญโญโญโญโญ Natural language โ
โ โโ Context: Understands game situation โ
โ โโ Example: "Enemy is massing tanks near โ
โ north. Build anti-tank defenses โ
โ and prepare counter-attack." โ
โ โ
โ ๐ Heuristic Analysis (Fallback) โ
โ โโ Uses: Simple IF-THEN rules โ
โ โโ Time: Instant (0.001 seconds) โ
โ โโ Quality: โญโญโญ Generic but reliable โ
โ โโ Context: Counts units/buildings โ
โ โโ Example: "Battlefield is balanced. โ
โ Scout and take map control." โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
```
## ๐ How Heuristic Analysis Works
### Algorithm (Simple Rules):
```python
def _heuristic_analysis(game_state):
# 1. COUNT everything
player_units = count_units(player=0)
enemy_units = count_units(player=1)
player_buildings = count_buildings(player=0)
enemy_buildings = count_buildings(player=1)
credits = player_credits
power = player_power
# 2. CALCULATE advantage score
score = (player_units - enemy_units) +
0.5 ร (player_buildings - enemy_buildings)
# 3. DETERMINE situation
if score > 1:
situation = "AHEAD" # Winning
elif score < -1:
situation = "BEHIND" # Losing
else:
situation = "EVEN" # Balanced
# 4. SELECT pre-written messages
if situation == "AHEAD":
summary = "You hold the initiative. Maintain pressure."
tips = ["Expand territory", "Scout flanks", "Pressure enemy"]
elif situation == "BEHIND":
summary = "You're under pressure. Stabilize defenses."
tips = ["Build defenses", "Protect economy", "Hold position"]
else: # EVEN
summary = "Battlefield is balanced. Scout and control map."
tips = ["Scout enemy", "Build units", "Control resources"]
# 5. ADD specific tips based on resources
if power < power_consumption:
tips.add("Build Power Plant")
if credits < 300:
tips.add("Protect Harvester")
if player_units < enemy_units:
tips.add("Train more Infantry and Tanks")
# 6. RETURN generic coaching
coach = "Keep economy safe and strike when you see opening."
return {
'summary': summary,
'tips': tips[:4], # Max 4 tips
'coach': coach,
'source': 'heuristic' # โ Important flag!
}
```
## ๐ When is Heuristic Used?
### 3 Scenarios:
#### 1. **Model Not Loaded Yet** โณ
```
Game just started โ Model still loading
โ Use heuristic until model ready
โ Switch to LLM after ~15 seconds
```
#### 2. **LLM Busy Processing** ๐
```
LLM processing NL command โ Queue full
โ Return heuristic INSTANTLY
โ User gets immediate feedback
โ LLM analysis appears later when ready
```
#### 3. **LLM Error/Timeout** โ
```
LLM request failed or timed out
โ Fallback to heuristic (always works!)
โ Better generic advice than nothing
```
## ๐ Example Output Comparison
### LLM Analysis (15s, Natural):
```json
{
"summary": "Your tank forces are positioned well but enemy has air superiority. Their helicopters are harassing your harvesters in the northwest quadrant. Consider building SAM sites near your refineries and advancing your tank column while they're distracted.",
"tips": [
"Build 2-3 SAM sites near western refineries",
"Push tank column toward enemy war factory",
"Keep infantry with tanks for anti-air support",
"Scout their helicopter production rate"
],
"coach": "You have material advantage but must counter their air harassment - protect economy and push when helicopters retreat.",
"source": "llm"
}
```
**Characteristics:**
- โ
Specific to current situation
- โ
Mentions exact threats (helicopters, northwest)
- โ
Strategic reasoning (push while distracted)
- โ
Natural, flowing language
- โฑ๏ธ Takes 15 seconds
### Heuristic Analysis (Instant, Generic):
```json
{
"summary": "Battlefield is balanced. Scout and take map control.",
"tips": [
"Train Infantry and add Tanks for frontline",
"Scout enemy base and pressure weak flanks",
"Protect Harvester and secure more ore",
"Build a Power Plant to restore production speed"
],
"coach": "Keep your economy safe and strike when you see an opening.",
"source": "heuristic"
}
```
**Characteristics:**
- โ
Always valid advice
- โ
Covers basic strategy
- โ Not situation-specific
- โ Template-based language
- โก Instant (0.001s)
## ๐ฏ Quality Comparison
| Feature | LLM Analysis | Heuristic Analysis |
|---------|--------------|-------------------|
| **Speed** | 15 seconds | Instant |
| **Accuracy** | Context-aware | Generic but correct |
| **Language** | Natural, flowing | Template-based |
| **Specificity** | Exact threats/opportunities | General principles |
| **Reliability** | 95% (can timeout) | 100% (never fails) |
| **CPU Usage** | High | Negligible |
| **Memory** | 1GB model | ~1KB rules |
## ๐ก Why Both Are Useful
### LLM (Qwen2.5-Coder):
- **Best for:** Detailed tactical advice
- **Provides:** Specific, context-aware guidance
- **Example:** "Enemy massing tanks at north bridge - build anti-tank defenses there"
### Heuristic:
- **Best for:** Instant feedback, basic strategy
- **Provides:** Reliable, always-available advice
- **Example:** "Build more units and scout enemy position"
### Combined Strategy:
```
User plays game
โ
Every 60s: AI analysis triggered
โ
Is LLM available and not busy?
โโ YES โ Use LLM (15s wait, great advice)
โโ NO โ Use Heuristic (instant, good advice)
โ
User sees analysis immediately (heuristic)
or after 15s (LLM)
```
## ๐ How to Tell Which One You Got
### In the UI:
The analysis object has a `source` field:
```javascript
// Frontend can check:
if (analysis.source === 'heuristic') {
console.log('๐ Using rule-based analysis (instant)');
} else if (analysis.source === 'llm') {
console.log('๐ค Using AI model analysis (15s)');
}
```
### Visual Indicators (Could Add):
**LLM Analysis:**
```
๐ค AI Tactical Analysis
โโโโโโโโโโโโโโโโโโโโ
Your tank forces are positioned well...
```
**Heuristic Analysis:**
```
๐ Quick Tactical Overview
โโโโโโโโโโโโโโโโโโโโ
Battlefield is balanced. Scout and...
```
## ๐ Performance in Production
### On HuggingFace (2 vCPU):
**Scenario 1: Normal Operation**
```
Game running smoothly
โ LLM available
โ User gets LLM analysis every 60s
โ High quality, natural language advice
```
**Scenario 2: User Spamming Commands**
```
User: "move tanks"
User: "build infantry"
User: "attack base"
โ LLM queue full (3 requests pending)
โ AI analysis โ Use Heuristic (instant!)
โ User still gets advice while LLM busy
โ Later LLM analysis appears when queue clears
```
**Scenario 3: Model Timeout**
```
LLM taking >15s (CPU contention)
โ Request timeout
โ Fallback to Heuristic
โ User gets SOME advice (not nothing!)
โ Next analysis tries LLM again
```
## ๐ฎ User Experience
### Player Perspective:
**What players see:**
- Tactical advice panel updates every 60 seconds
- Sometimes advice is very specific ("Build SAM sites in northwest")
- Sometimes advice is more general ("Scout and control map")
- Advice is ALWAYS useful and valid
- Never waits more than a moment for advice
**What players DON'T see:**
- Whether LLM or heuristic was used (both look professional)
- Model loading times (heuristic covers gap)
- Queue management (seamless fallback)
- CPU limitations (instant response via heuristic)
### Best of Both Worlds:
```
RELIABILITY (Heuristic) + QUALITY (LLM) = Great UX
```
- **Heuristic** ensures advice is ALWAYS available
- **LLM** makes advice INTERESTING and SPECIFIC when available
- **Fallback** strategy means no frustration
## ๐ง Technical Details
### Code Flow:
```python
# ai_analysis.py - summarize_combat_situation()
def summarize_combat_situation(game_state, language):
# 1. Quick check: Is model loaded?
if not self.model_available:
return self._heuristic_analysis(game_state, language)
# 2. Try LLM with timeout
result = self.generate_response(
prompt=build_prompt(game_state),
timeout=15.0
)
# 3. LLM success?
if result['status'] == 'ok':
return parse_llm_response(result) # ๐ค LLM analysis
# 4. LLM failed/busy โ Instant fallback
else:
return self._heuristic_analysis(game_state, language) # ๐ Heuristic
```
### Heuristic Implementation:
The heuristic analysis is **multi-language** and covers:
1. **Situation Assessment** (ahead/even/behind)
2. **Power Management** (low power warning)
3. **Economy** (protect harvesters if low credits)
4. **Army Composition** (unit balance advice)
5. **Defense** (fortify if building disadvantage)
6. **Generic Coaching** (motivational message)
All in **English, French, and Chinese**! ๐
## ๐ฏ Summary
### What is Heuristic Analysis?
**Simple rule-based advice** that's instant and always works.
### When is it used?
- Model not loaded yet
- LLM busy with other requests
- LLM timeout or error
### Why is it good?
- **Instant** (no waiting)
- **Reliable** (never fails)
- **Valid** (always correct advice)
- **Fallback** (ensures users always get help)
### Why have LLM too?
- **Better quality** (context-aware)
- **Natural language** (more engaging)
- **Specific advice** (adapts to exact situation)
- **Strategic depth** (understands complex scenarios)
---
**Think of it like:**
- **Heuristic** = Experienced player giving quick tips
- **LLM** = Professional coach analyzing replay in detail
**Both are valuable!** Heuristic ensures you always get advice (speed + reliability), while LLM makes the advice amazing when available (quality + depth). ๐ฏ
|