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9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# Deployment Guide - Runpod Cloud

After local testing is complete, follow this guide to deploy your Feedback Analysis Agent to Runpod.

---

## βœ… Pre-Deployment Checklist

Before deploying to Runpod, ensure:

- [ ] All local tests pass: `python3 scripts/validate_local.py` shows 7/7 βœ…
- [ ] API server runs locally: `python3 run.py` starts without errors
- [ ] Endpoints tested: Use TESTING_CHECKLIST.md or curl commands
- [ ] Git repository clean: `git status` shows no uncommitted changes
- [ ] All code committed: `git log --oneline | head -5` shows your commits
- [ ] Docker image builds: `docker build -t feedback-analysis:latest .` succeeds
- [ ] Requirements.txt updated: All dependencies listed

---

## πŸ“¦ Step 1: Prepare Docker Image

### 1.1 Build Docker Image Locally

```bash
cd /Users/galbd/Desktop/personal/software/ai_agent_gov/Feedback_Analysis_RAG_Agent_runpod

# Build the image
docker build -t feedback-analysis:latest .

# Verify it built
docker images | grep feedback-analysis
```

**Expected output:**
```
REPOSITORY           TAG      IMAGE ID      CREATED        SIZE
feedback-analysis    latest   abc123def456  2 minutes ago   2.5GB
```

### 1.2 Test Docker Image Locally (Optional)

```bash
# Run container
docker run -p 8001:8000 feedback-analysis:latest

# In another terminal, test
curl -X POST http://localhost:8001/health
```

**Expected:** `{"status":"ok"}`

---

## πŸ”‘ Step 2: Set Up Docker Registry

### Option A: Docker Hub (Easiest)

**2A.1 Create Docker Hub Account**
- Go to https://hub.docker.com
- Sign up for free account
- Note your username (e.g., `galbendavids`)

**2A.2 Login to Docker**
```bash
docker login
# Enter your Docker Hub username and password
```

**2A.3 Tag and Push Image**
```bash
# Tag with your Docker Hub username
docker tag feedback-analysis:latest galbendavids/feedback-analysis:latest

# Push to Docker Hub
docker push galbendavids/feedback-analysis:latest

# Verify it's uploaded
# Visit https://hub.docker.com/r/YOUR_USERNAME/feedback-analysis
```

### Option B: Private Registry (Advanced)
- Use AWS ECR, Google Container Registry, or Azure Container Registry
- Follow their documentation for authentication and push

---

## πŸš€ Step 3: Create Runpod Template

### 3.1 Access Runpod Console

1. Go to https://www.runpod.io
2. Sign in to your account (create if needed)
3. Click **"Console"** in top menu
4. Go to **"Serverless"** or **"Pods"** section

### 3.2 Create New Template

**For Serverless Endpoints (Recommended):**

1. Click **"Create New"** β†’ **"API Endpoint Template"**
2. Fill in:
   - **Template Name:** `feedback-analysis-sql`
   - **Docker Image:** `galbendavids/feedback-analysis:latest`
   - **Ports:** `8000`
   - **GPU:** None (CPU-only is fine)
   - **Memory:** 4GB minimum
   - **Environment Variables:**
     ```
     GEMINI_API_KEY=your_key_here (optional)
     OPENAI_API_KEY=sk-... (optional)
     ```

3. Click **"Save Template"**

**For Pods (Traditional VM):**

1. Click **"Create"** β†’ **"New Pod"**
2. Select template
3. Choose GPU type (optional, not needed for this workload)
4. Set min/max auto-scale settings
5. Click **"Run Pod"**

### 3.3 Configure Networking

- **Expose Port:** 8000
- **HTTPS:** Enabled automatically
- **Public URL:** Runpod generates automatically

---

## πŸ§ͺ Step 4: Test Deployed Endpoint

### 4.1 Get Endpoint URL

After deployment, Runpod provides a URL like:
```
https://your-endpoint-id.runpod-pods.net/
```

Or for Serverless:
```
https://api.runpod.io/v1/YOUR_ENDPOINT_ID/run
```

### 4.2 Test Basic Connectivity

```bash
# For Pods (direct connection)
curl -X POST https://your-endpoint-id.runpod-pods.net/health

# For Serverless (requires different format)
# See Runpod API documentation
```

**Expected response:**
```json
{"status":"ok"}
```

### 4.3 Test Query Endpoint

```bash
curl -X POST https://your-endpoint-id.runpod-pods.net/query \
  -H "Content-Type: application/json" \
  -d '{"query":"Χ›ΧžΧ” משΧͺΧžΧ©Χ™Χ Χ›ΧͺΧ‘Χ• ΧͺΧ•Χ“Χ”","top_k":5}'
```

**Expected response:**
```json
{
  "query": "Χ›ΧžΧ” משΧͺΧžΧ©Χ™Χ Χ›ΧͺΧ‘Χ• ΧͺΧ•Χ“Χ”",
  "summary": "1168 ΧžΧ©Χ•Χ‘Χ™Χ ΧžΧ›Χ™ΧœΧ™Χ Χ‘Χ™Χ˜Χ•Χ™Χ™ ΧͺΧ•Χ“Χ”.",
  "results": [...]
}
```

### 4.4 Test All Endpoints

Use the same curl commands from TESTING_CHECKLIST.md, but replace:
- `http://localhost:8000` β†’ `https://your-endpoint-id.runpod-pods.net`

Or use Swagger UI:
- `https://your-endpoint-id.runpod-pods.net/docs`

---

## πŸ’° Step 5: Configure Auto-Scaling (Optional)

In Runpod Pod settings:

1. **Minimum GPUs:** 0 (not needed)
2. **Maximum GPUs:** 1 (if you add GPU support)
3. **Idle timeout:** 5 minutes
4. **Auto-pause:** Enabled (to save costs)

---

## πŸ” Step 6: Add API Keys (Optional)

If you want LLM summaries (not required, system works without):

### 6.1 In Runpod Dashboard

1. Go to Pod settings
2. Add Environment Variables:
   ```
   GEMINI_API_KEY=your_actual_key
   OPENAI_API_KEY=sk-your_actual_key
   ```
3. Restart pod

### 6.2 Get API Keys

**For Google Gemini:**
1. Go to https://makersuite.google.com/app/apikeys
2. Click "Create API Key"
3. Copy the key

**For OpenAI:**
1. Go to https://platform.openai.com/api-keys
2. Create new secret key
3. Copy the key

---

## πŸ“Š Step 7: Monitor & Manage

### 7.1 Check Logs

In Runpod dashboard:
1. Click on your pod/endpoint
2. View **Logs** tab
3. Look for errors or warnings

### 7.2 Performance Metrics

Monitor:
- **CPU usage:** Should be <50% at rest
- **Memory:** Should be <80% usage
- **Response times:** Query endpoint 1-3 seconds
- **Uptime:** Should be 99%+

### 7.3 Scale & Pricing

- **Auto-scaling:** Runpod manages based on demand
- **Costs:** Typically $0.25-$0.50/hour for 4GB CPU-only pod
- **Savings:** Pod auto-pauses when idle (no charge)

---

## πŸ”„ Step 8: Update Deployment

### When You Update Code

1. **Make changes locally**
   ```bash
   # Edit code, test locally
   git add .
   git commit -m "feat: new feature"
   git push origin main
   ```

2. **Rebuild Docker image**
   ```bash
   docker build -t feedback-analysis:v2 .
   docker tag feedback-analysis:v2 galbendavids/feedback-analysis:v2
   docker push galbendavids/feedback-analysis:v2
   ```

3. **Update Runpod template**
   - Edit template image: `galbendavids/feedback-analysis:v2`
   - Save
   - Restart pod with new image

4. **Or redeploy**
   - Delete old pod
   - Create new pod from updated template

---

## ✨ Advanced: Optimization for Cloud

### A. Pre-download Models in Dockerfile

To avoid long first-request delays in cloud, add to Dockerfile:

```dockerfile
# After RUN pip install requirements.txt

# Pre-download embedding model
RUN python3 -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')"

# Pre-download sentiment model
RUN python3 -c "from transformers import pipeline; pipeline('sentiment-analysis', model='nlptown/bert-base-multilingual-uncased-sentiment')"
```

This adds ~2GB to image, but eliminates download on first request.

### B. Use GPU for Faster Embeddings

```dockerfile
# Install GPU support
RUN pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
RUN pip install faiss-gpu
```

Then in Runpod, select a GPU pod (more expensive but faster).

### C. Enable Caching

Add to `app/config.py`:
```python
EMBEDDING_CACHE_SIZE = 10000  # Cache more embeddings
INDEX_RELOAD_INTERVAL = 3600  # Reload index hourly
```

---

## πŸ› Troubleshooting

### Problem: Pod won't start
```
Error: Container failed to start
```
**Fix:** Check Dockerfile syntax and ensure image builds locally first.

### Problem: Out of memory
```
OOMKilled or similar
```
**Fix:** Increase allocated memory in pod settings (go from 4GB to 8GB).

### Problem: Slow responses
```
Queries taking >10 seconds
```
**Fix:** 
- Add GPU support
- Pre-download models (see optimization section)
- Increase allocated CPU cores

### Problem: Model not found
```
Error: Model 'xyz' not found
```
**Fix:** Add model download to Dockerfile (see optimization section).

### Problem: HTTPS certificate error
```
SSL Certificate verification failed
```
**Fix:** Runpod handles this automatically, should not occur.

---

## πŸ“ˆ Monitoring & Alerts

### Set Up Alerts (Optional)

1. Go to Runpod **Billing** tab
2. Set max spend limit
3. Enable email alerts

### Check Status

```bash
# Query your endpoint
curl -X POST https://your-endpoint-id.runpod-pods.net/health

# If it fails, pod may be down
# Check Runpod dashboard for status
```

---

## πŸ”„ Rollback Plan

If deployment has issues:

1. **Keep previous image tagged**
   ```bash
   docker tag galbendavids/feedback-analysis:v1 galbendavids/feedback-analysis:latest-stable
   docker push galbendavids/feedback-analysis:latest-stable
   ```

2. **If new deployment fails, revert**
   - Update Runpod template back to `latest-stable`
   - Restart pod
   - Investigate issue locally

3. **Don't delete old pods immediately**
   - Keep for at least 1 day
   - Then delete if new version stable

---

## 🎯 Testing Checklist Before Going Live

Before sharing endpoint with users:

- [ ] `/health` endpoint responds
- [ ] `/query` endpoint returns results
- [ ] Hebrew queries work correctly
- [ ] Response times acceptable (<5s for most queries)
- [ ] Error handling working (try invalid JSON)
- [ ] Swagger UI accessible at `/docs`
- [ ] SSL/HTTPS working (URL is secure)
- [ ] Logs show no errors
- [ ] Auto-scaling responding to load

---

## πŸ“‹ Production Deployment Checklist

Before announcing to users:

- [ ] Load tested with 100+ concurrent requests
- [ ] Backup plan documented
- [ ] Monitoring alerts set up
- [ ] Support procedure documented
- [ ] SLA defined (99.9% uptime target, etc.)
- [ ] Rate limiting configured (optional)
- [ ] API key authentication enforced (optional)
- [ ] CORS settings reviewed
- [ ] Backup of deployment config saved
- [ ] Runpod support ticket submitted for any questions

---

## πŸ“ž Support & Resources

- **Runpod Docs:** https://docs.runpod.io
- **Runpod Community:** https://forums.runpod.io
- **FastAPI Docs:** https://fastapi.tiangolo.com
- **Docker Docs:** https://docs.docker.com

---

## πŸŽ“ What's Next

After successful deployment:

1. **Monitor the endpoint** - Check logs daily
2. **Gather feedback** - What works well, what needs improvement
3. **Iterate** - Make improvements, redeploy
4. **Scale** - Add more features, more data
5. **Secure** - Add authentication, rate limiting as needed

---

## βœ… Congratulations!

Your SQL-based feedback analysis agent is now live in the cloud! πŸŽ‰

**Summary:**
- βœ… Local validation complete
- βœ… Docker image built
- βœ… Deployed to Runpod
- βœ… Cloud endpoint tested
- βœ… Ready for production

**Next:** Share the endpoint URL with users or integrate into your application.

---

*Last Updated: Today*  
*Version: 1.0*  
*Status: Production Ready* ✨