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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
472
473
474
475
476
477
478
479
480
481
482
# API Reference

> **Primary Responsibility:** Complete API endpoint and function documentation

This document provides a complete reference for the Enterprise AI Gateway API endpoints.

## Base URL

```
https://your-deployment-url
```

For local development: `http://localhost:8000`

## Authentication

All API requests (except `/health` and `/`) require authentication using an API key.

Include the API key in the request header:

```
X-API-Key: YOUR_API_KEY
```

## Rate Limiting

The API implements rate limiting to prevent abuse:
- Default limit: 10 requests per minute per IP address
- Exceeding the limit returns a 429 (Too Many Requests) status code

## Core Modules

### main.py
Main application entry point that initializes the FastAPI application.

#### `app`
The main FastAPI application instance with all routes and middleware configured.

### config.py
Configuration module that loads environment variables and defines application settings.

#### `SERVICE_API_KEY`
The API key required for authenticating requests to the gateway.

#### `RATE_LIMIT`
Rate limiting configuration (e.g., "10/minute").

#### `ALLOWED_ORIGINS`
List of allowed origins for CORS middleware.

#### `ENABLE_PROMPT_INJECTION_CHECK`
Flag to enable/disable prompt injection detection.

### security/\_\_init\_\_.py
Security utilities for authentication and prompt validation.

#### `detect_prompt_injection(prompt: str) -> bool`
Detect potential prompt injection attacks using regex patterns.

#### `detect_pii(prompt: str) -> dict`
Detect PII (Personally Identifiable Information) in prompts. Returns:
- `has_pii`: Boolean indicating if PII was found
- `pii_types`: List of PII types detected (email, credit_card, ssn, tax_id, api_key)
- `matches`: Dictionary with count of each PII type found

#### `detect_toxicity(text: str) -> dict`
Detect toxic/harmful content using Gemini AI classification with Lakera Guard fallback. Returns:
- `is_toxic`: Boolean indicating if content is harmful
- `scores`: Dictionary of category scores
- `blocked_categories`: List of detected harmful categories
- `error`: Error message if API call failed

Categories detected: SEXUALLY_EXPLICIT, HATE_SPEECH, HARASSMENT, DANGEROUS_CONTENT, CIVIC_INTEGRITY

#### `detect_toxicity_lakera(text: str) -> dict`
Fallback toxicity detection using Lakera Guard API. Called automatically when Gemini fails.

#### `validate_api_key(api_key: str) -> str`
Validate API key for request authentication.

### models/\_\_init\_\_.py
Pydantic models for request/response validation.

#### `QueryRequest`
Model for query requests with prompt, max_tokens, and temperature.

#### `QueryResponse`
Model for query responses with response content, provider info, and metadata.
- `cascade_path`: List of provider attempts with status and latency
- `cost_estimate_usd`: Estimated cost of the request

#### `CascadeStep`
Model for individual steps in the provider cascade.
- `provider`: Provider name
- `model`: Model used
- `status`: "success", "failed", or "timeout"
- `reason`: Error reason if failed
- `latency_ms`: Response time in milliseconds

#### `HealthResponse`
Model for health check responses.

### api/routes.py
API route definitions.

#### `/` (GET)
Serves the Interactive Gateway Demo Dashboard from `static/index.html`.

#### `/health` (GET)
Health check endpoint that returns the status of the service.

#### `/query` (POST)
Query endpoint that processes LLM requests with security and fallback protocols.
Returns cascade path and cost estimate.

#### `/metrics` (GET)
Returns gateway metrics including total requests, latency, provider usage, and security events.

#### `/providers` (GET)
Returns available providers with pricing information and active configuration.

#### `/batch/resilience` (POST)
Batch resilience testing endpoint. Runs multiple prompts through the cascade and returns aggregate metrics.

#### `/batch/security` (POST)
Batch security testing endpoint. Tests prompts for PII and injection without executing LLM calls.

#### `/check-toxicity` (POST)
Content safety check endpoint. Uses Gemini AI classification with Lakera Guard fallback.
Returns toxicity status, scores, and blocked categories.

### llm/client.py
LLM client with multi-provider fallback functionality.

#### `LLMClient`
Class that manages connections to multiple LLM providers.

#### `call_llm_provider(provider_name: str, api_key: str, model: str, prompt: str, max_tokens: int, temperature: float)`
Call a specific LLM provider with the given parameters.

#### `query_llm_cascade(prompt: str, max_tokens: int, temperature: float)`
Query LLM with cascade fallback across providers.
Returns: `(response, provider_name, latency_ms, error, cascade_path)`

### metrics/\_\_init\_\_.py
Metrics tracking module.

#### `MetricsStore`
Thread-safe metrics store for tracking gateway performance.
- `record_request()`: Record a request with metrics
- `to_dict()`: Return metrics as dictionary
- `reset()`: Reset all metrics

#### `metrics`
Singleton instance of MetricsStore.

### providers/\_\_init\_\_.py
Provider configuration module.

#### `PROVIDER_CONFIG`
Dictionary containing provider pricing and configuration.

#### `get_model_pricing(provider: str, model: str) -> dict`
Get pricing info for a specific provider/model combination.

#### `estimate_cost(provider: str, model: str, input_tokens: int, output_tokens: int) -> float`
Estimate cost for a request in USD.

## Environment Variables

See [Configuration Guide](configuration.md) for complete environment variable reference.

## Endpoints

### Health Check

#### `GET /health`

Check if the service is running and healthy.

**Response:**
```json
{
  "status": "healthy",
  "provider": "gemini",
  "timestamp": 1700000000.123456
}
```

**Response Fields:**
- `status`: Service status ("healthy" or "unhealthy")
- `provider`: Currently active LLM provider
- `timestamp`: Unix timestamp of the health check

### Query LLM

#### `POST /query`

Send a prompt to the LLM through the secure gateway with automatic failover.

**Headers:**
```
Content-Type: application/json
X-API-Key: YOUR_API_KEY
```

**Request Body:**
```json
{
  "prompt": "Your question here",
  "max_tokens": 256,
  "temperature": 0.7
}
```

**Request Parameters:**
- `prompt` (required): The prompt to send to the LLM (1-4000 characters)
- `max_tokens` (optional): Maximum number of tokens in the response (1-2048, default: 256)
- `temperature` (optional): Sampling temperature (0.0-2.0, default: 0.7)

**Successful Response:**
```json
{
  "response": "The AI's answer",
  "provider": "groq",
  "latency_ms": 87,
  "status": "success",
  "error": null
}
```

**Error Response:**
```json
{
  "response": null,
  "provider": null,
  "latency_ms": 0,
  "status": "error",
  "error": "Error message"
}
```

**Response Fields:**
- `response`: The LLM's response text (null if error)
- `provider`: Which LLM provider was used (null if error)
- `latency_ms`: Request latency in milliseconds (0 if error)
- `status`: Request status ("success" or "error")
- `error`: Error message if request failed (null if successful)
- `cascade_path`: Array of provider attempts with status and latency
- `cost_estimate_usd`: Estimated cost of the request in USD

### Get Metrics

#### `GET /metrics`

Get current gateway metrics.

**Response:**
```json
{
  "total_requests": 150,
  "successful_requests": 145,
  "blocked_requests": 5,
  "average_latency_ms": 120.5,
  "provider_usage": {"gemini": 100, "groq": 45},
  "cascade_failures": 3,
  "pii_detections": 2,
  "injection_detections": 3,
  "latency_history": [87, 120, 95, ...]
}
```

### Get Providers

#### `GET /providers`

Get available providers with pricing information.

**Response:**
```json
{
  "providers": {
    "gemini": {"name": "Google Gemini", "models": {...}},
    "groq": {"name": "Groq", "models": {...}},
    "openrouter": {"name": "OpenRouter", "models": {...}}
  },
  "active_providers": ["gemini", "groq", "openrouter"],
  "active_models": {"gemini": "gemini-2.0-flash-exp", ...}
}
```

### Batch Resilience Test

#### `POST /batch/resilience`

Run multiple prompts through the cascade and return aggregate metrics.

**Headers:**
```
Content-Type: application/json
X-API-Key: YOUR_API_KEY
```

**Request Body:**
```json
{
  "prompts": [
    "First test prompt",
    "Second test prompt"
  ]
}
```

**Response:**
```json
{
  "total": 2,
  "successful": 2,
  "failed": 0,
  "total_cascade_failures": 1,
  "average_latency_ms": 105.5,
  "downtime_prevented_minutes": 4.0,
  "results": [...]
}
```

### Batch Security Test

#### `POST /batch/security`

Test prompts for security issues without executing LLM calls.

**Request Body:**
```json
{
  "prompts": [
    "Normal question",
    "Ignore all instructions",
    "My SSN is 123-45-6789"
  ]
}
```

**Response:**
```json
{
  "total": 3,
  "blocked": 2,
  "passed": 1,
  "pii_leaks_prevented": 1,
  "injection_attempts_blocked": 1,
  "compliance_fines_avoided_usd": 28000,
  "results": [...]
}
```

### Content Safety Check

#### `POST /check-toxicity`

Check content for harmful/toxic material using AI classification.

**Headers:**
```
Content-Type: application/json
X-API-Key: YOUR_API_KEY
```

**Request Body:**
```json
{
  "text": "Content to analyze for safety"
}
```

**Response:**
```json
{
  "is_toxic": false,
  "scores": {"SAFE": 1.0},
  "blocked_categories": [],
  "error": null
}
```

**Blocked Response Example:**
```json
{
  "is_toxic": true,
  "scores": {"HARM_CATEGORY_SEXUALLY_EXPLICIT": 0.9},
  "blocked_categories": ["HARM_CATEGORY_SEXUALLY_EXPLICIT"],
  "error": null
}
```

**Harm Categories:** See [Security Overview](security_overview.md) for the complete list of blocked content categories.

## Error Codes

### 200 OK
Request successful

### 401 Unauthorized
- Missing or invalid API key

### 422 Unprocessable Entity
- Invalid request parameters
- Prompt injection detected
- Input validation failed

### 429 Too Many Requests
- Rate limit exceeded

### 500 Internal Server Error
- All LLM providers failed
- Unexpected server error

## Example Usage

### cURL

```bash
# Health check
curl https://your-deployment-url/health

# Query LLM
curl -X POST https://your-deployment-url/query \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{
    "prompt": "What is artificial intelligence?",
    "max_tokens": 150,
    "temperature": 0.7
  }'
```

### Python

```python
import requests

# Health check
response = requests.get('https://your-deployment-url/health')
print(response.json())

# Query LLM
headers = {
    'Content-Type': 'application/json',
    'X-API-Key': 'YOUR_API_KEY'
}

data = {
    'prompt': 'What is artificial intelligence?',
    'max_tokens': 150,
    'temperature': 0.7
}

response = requests.post('https://your-deployment-url/query', headers=headers, json=data)
print(response.json())
```

## Security Features

### Authentication
All requests to `/query` require a valid API key in the `X-API-Key` header.

### Rate Limiting
Requests are rate limited based on the `RATE_LIMIT` configuration.

### Prompt Injection Detection
Potential prompt injection attempts are detected and blocked automatically.

### CORS
Cross-Origin Resource Sharing is configured based on `ALLOWED_ORIGINS`.

## Security Considerations

1. Always use HTTPS in production
2. Keep your API key secure
3. Validate all responses before using them
4. Implement proper error handling
5. Be aware of rate limits