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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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
---
language: en
license: apache-2.0
library_name: transformers
pipeline_tag: text-generation
tags:
  - mistral
  - lora
  - merged
  - gguf
  - text-generation
base_model: mistralai/Mistral-7B-Instruct-v0.2
---








# 🌍 Geopolitical Analysis Agent

**Advanced strategic forecasting and simulation engine combining RAG, SQLite, ChromaDB, and Claude AI**

## What Is This?

A production-ready geopolitical analysis system that:
- **Answers complex "what-if" questions** about world events
- **Models quantitative scenarios** (tank stocks, production rates, timelines)
- **Combines structured data + unstructured knowledge** via RAG
- **Provides rigorous analysis** like a think tank war games coordinator
- **Prepares training data** for fine-tuning specialized models

## Key Features

### 🧠 Intelligent RAG Architecture
- **Vector search** with ChromaDB for semantic retrieval
- **Structured database** with SQLite for facts, metrics, inventories
- **Hybrid retrieval** combining both sources for comprehensive context

### πŸ“Š Quantitative Modeling
- Project military inventories over time
- Calculate attrition rates and production capacities
- Model economic sustainability scenarios
- Compare alternative pathways

### πŸ’Ύ Production-Ready Stack
- FastAPI backend with async support
- SQLAlchemy ORM for database management
- Sentence Transformers for embeddings
- Claude Sonnet 4 for analysis
- Clean HTML/JS frontend

### 🎯 Example Queries

```
"Where will Russia's tank stock be in 5 years with 15% annual 
losses and 200 tanks/year production?"

"What's China's timeline to semiconductor parity with Taiwan 
if sanctions continue vs. if they're lifted?"

"How long can Iran sustain its proxy network at $60/barrel 
vs $100/barrel oil prices?"

"Model European energy security in 2030 under three scenarios: 
diversified LNG, accelerated renewables, or partial Russian 
reconciliation"
```

## Quick Start

### 1. Install

```bash
cd geopolitical-agent/backend
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
```

### 2. Configure

Create `.env` file:
```bash
ANTHROPIC_API_KEY=your_key_here
```

### 3. Initialize

```bash
python -c "from models.database import init_db; init_db()"
```

### 4. Run

```bash
python app.py
```

Server starts on http://localhost:8000

### 5. Open Frontend

Open `frontend/index.html` in browser or:
```bash
cd frontend
python -m http.server 8080
```

### 6. Load Sample Data

Click "Load Sample Data" button in UI or:
```bash
curl -X POST http://localhost:8000/api/data/load-sample-data
```

## Architecture

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              Frontend (HTML/JS)                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                  β”‚ REST API
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚           FastAPI Backend                       β”‚
β”‚                                                 β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚      Analysis Service (Claude + RAG)     β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚            β”‚                    β”‚               β”‚
β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚   β”‚  RAG Service    β”‚   β”‚  Data Ingestion  β”‚   β”‚
β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚            β”‚                    β”‚               β”‚
β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚   β”‚   ChromaDB      β”‚   β”‚     SQLite       β”‚   β”‚
β”‚   β”‚  (Vectors)      β”‚   β”‚   (Structured)   β”‚   β”‚
β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

## Project Structure

```
geopolitical-agent/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ app.py                    # Main FastAPI app
β”‚   β”œβ”€β”€ config.py                 # Configuration
β”‚   β”œβ”€β”€ requirements.txt          # Dependencies
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ database.py          # SQLAlchemy models
β”‚   β”‚   └── embeddings.py        # ChromaDB manager
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ rag_service.py       # RAG orchestration
β”‚   β”‚   β”œβ”€β”€ analysis_service.py  # Analysis engine
β”‚   β”‚   └── data_ingestion.py    # Data loading
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”œβ”€β”€ query.py             # Query endpoints
β”‚   β”‚   └── data.py              # Data endpoints
β”‚   └── data/
β”‚       β”œβ”€β”€ geopolitical.db      # SQLite database
β”‚       └── chroma_db/           # Vector store
β”œβ”€β”€ frontend/
β”‚   └── index.html               # Web interface
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ sample_data/             # Sample datasets
β”‚   └── training/                # Fine-tuning prep
└── docs/
    β”œβ”€β”€ SETUP.md                 # Setup guide
    └── API.md                   # API documentation
```

## Database Schema

### Countries
- Basic country attributes
- GDP, population, military budget
- Regional categorization

### Military Assets
- Equipment inventories (tanks, aircraft, etc.)
- Operational rates
- Production and attrition rates

### Geopolitical Events
- Timeline of significant events
- Impact scoring
- Related countries tracking

### Metrics Time Series
- Economic indicators
- Production statistics
- Any quantitative metric over time

### Knowledge Sources
- Document provenance tracking
- Credibility scoring
- Source metadata

## API Examples

### Analyze Query
```bash
curl -X POST http://localhost:8000/api/query/analyze \
  -H "Content-Type: application/json" \
  -d '{
    "query": "Your geopolitical question here",
    "use_cache": true
  }'
```

### Add Knowledge
```bash
curl -X POST http://localhost:8000/api/data/add-document \
  -H "Content-Type: application/json" \
  -d '{
    "text": "Your geopolitical knowledge document",
    "metadata": {"type": "report", "country": "China"}
  }'
```

Full API documentation: `docs/API.md`

## Fine-Tuning Preparation

### Export Training Data

```python
from models.database import SessionLocal, AnalysisCache
import json

db = SessionLocal()
analyses = db.query(AnalysisCache).all()

training_data = []
for analysis in analyses:
    training_data.append({
        "messages": [
            {
                "role": "system",
                "content": "You are a geopolitical analysis expert..."
            },
            {
                "role": "user",
                "content": analysis.query_text
            },
            {
                "role": "assistant",
                "content": analysis.analysis_result
            }
        ]
    })

with open("training_data.jsonl", "w") as f:
    for item in training_data:
        f.write(json.dumps(item) + "\n")
```

### LoRA Training

Use the exported data to fine-tune a LoRA adapter on geopolitical data:

1. Export queries/responses from `analysis_cache` table
2. Format as JSONL for LoRA training
3. Train LoRA adapter on domain-specific data
4. Deploy fine-tuned model for specialized analysis

## Extending the System

### Add New Countries

```python
from models.database import SessionLocal, Country

db = SessionLocal()
country = Country(
    name="Pakistan",
    iso_code="PAK",
    region="South Asia",
    population=235000000,
    gdp_usd=376000000000,
    military_budget_usd=11000000000
)
db.add(country)
db.commit()
```

### Add Military Assets

```python
from models.database import MilitaryAsset

asset = MilitaryAsset(
    country_id=country.id,
    asset_type="Fighter Aircraft",
    asset_name="JF-17 Thunder",
    quantity=150,
    operational_rate=0.75,
    production_rate_yearly=25,
    attrition_rate_yearly=0.05
)
db.add(asset)
db.commit()
```

### Add Knowledge Documents

```python
from services.data_ingestion import DataIngestionService

service = DataIngestionService()
service.add_knowledge_document(
    text="Your geopolitical analysis or fact...",
    metadata={
        "type": "intelligence_assessment",
        "country": "Iran",
        "classification": "open_source"
    }
)
```

## Configuration

Edit `backend/config.py`:

```python
# Embedding model (smaller = faster, larger = better)
EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"

# RAG retrieval settings
TOP_K_RESULTS = 5              # Number of relevant chunks
SIMILARITY_THRESHOLD = 0.7      # Minimum relevance score

# Claude settings
DEFAULT_MODEL = "claude-sonnet-4-20250514"
MAX_TOKENS = 4000
TEMPERATURE = 0.3               # Lower = more analytical
```

## Performance Tips

1. **Adjust retrieval**: Tune `TOP_K_RESULTS` and `SIMILARITY_THRESHOLD`
2. **Enable caching**: Set `use_cache=true` for repeated queries
3. **Batch document ingestion**: Use bulk-add for multiple documents
4. **Index optimization**: Add SQLite indexes for frequent queries

## Use Cases

### Strategic Planning
- War games scenario modeling
- Resource sustainability analysis
- Timeline projections

### Intelligence Analysis
- Capability gap assessments
- Economic constraint modeling
- Production capacity tracking

### Academic Research
- Geopolitical trend analysis
- Historical pattern recognition
- Comparative case studies

### Policy Analysis
- Sanction impact modeling
- Alliance dynamics assessment
- Economic leverage analysis

## Roadmap

- [ ] Real-time data ingestion from news sources
- [ ] Multi-agent debate for competing analyses
- [ ] Temporal reasoning for historical patterns
- [ ] Export to PDF reports
- [ ] WebSocket streaming for long analyses
- [ ] Named Entity Recognition for auto-tagging
- [ ] Graph database for relationship modeling

## Contributing

Areas for contribution:
1. **Data**: Add domain-specific geopolitical datasets
2. **Models**: Integrate specialized embedding models
3. **Analysis**: Enhance quantitative modeling functions
4. **UI**: Improve frontend visualization
5. **Documentation**: Add tutorials and examples

## License

MIT License - See LICENSE file

## Citation

If you use this system in research:

```bibtex
@software{geopolitical_analysis_agent,
  title={Geopolitical Analysis Agent: RAG-based Strategic Forecasting},
  author={[Your Name]},
  year={2025},
  url={https://github.com/yourusername/geopolitical-agent}
}
```

## Support

- Documentation: `docs/`
- API Reference: `docs/API.md`
- Setup Guide: `docs/SETUP.md`
- Issues: GitHub Issues

## Acknowledgments

Built with:
- [FastAPI](https://fastapi.tiangolo.com/)
- [ChromaDB](https://www.trychroma.com/)
- [Anthropic Claude](https://www.anthropic.com/)
- [Sentence Transformers](https://www.sbert.net/)

---

**Ready to analyze the world? Start with `python app.py`** πŸš€