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 
 
 
 
 
 
 
 
 
439ebb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b28fb0
 
 
 
 
 
 
 
 
 
 
 
439ebb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
# API Integration Guide: User Authentication & Anonymous Mode Support

## Overview

The Atlas API supports both authenticated and anonymous usage modes. When users are authenticated, the frontend can send their `user_id` along with chat requests to associate session data with specific users. For anonymous usage, the `user_id` parameter can be omitted or set to null, and the system will handle the request without any user tracking.

## Required API Changes

### 1. Accept User ID in Chat Requests

The `/chat` endpoint needs to accept an optional `user_id` parameter to associate sessions with authenticated users.

**Current Request Structure:**
```python
class ChatRequest(BaseModel):
    prompt: str
    use_search: bool = True
    max_new_tokens: int = 1000
    temperature: float = 0.7
    history: List[dict] = []
```

**Updated Request Structure:**
```python
class ChatRequest(BaseModel):
    prompt: str
    use_search: bool = True
    max_new_tokens: int = 1000
    temperature: float = 0.7
    history: List[dict] = []
    user_id: Optional[str] = None  # Optional field - defaults to anonymous mode
    force_search: Optional[bool] = None  # Override smart search optimization
    search_decision_mode: str = "balanced"  # "conservative", "balanced", "aggressive"
```

### Anonymous Mode Support

The `user_id` parameter is **completely optional**. When omitted or set to null/empty string, the system operates in anonymous mode:

- **Anonymous requests**: No user tracking or identification
- **Same functionality**: Full chat capabilities without authentication
- **No setup required**: Works immediately without any configuration
- **Privacy-focused**: No personal data collection or storage

### Search Optimization Parameters

Atlas includes intelligent search optimization with new optional parameters:

#### `force_search: Optional[bool]`
- **Purpose**: Override the smart search optimization engine
- **Default**: `null` (use smart optimization)
- **Values**: 
  - `true` - Always perform web search regardless of context
  - `false` - Never perform web search (use only conversation history)  
  - `null` - Use intelligent search decision engine

#### `search_decision_mode: str`
- **Purpose**: Control the sensitivity of the search optimization engine
- **Default**: `"balanced"`
- **Values**:
  - `"conservative"` - Prefer using conversation history, minimize searches
  - `"balanced"` - Smart balance between search and history usage
  - `"aggressive"` - Prefer web search for most requests

### 2. Modify Session Creation/Tracking

Update the session management to include `user_id` when provided:

**In the `/chat` endpoint:**
```python
# Handle session management with user_id
if analytics_available:
    if not session_id:
        # Create new session with user_id if provided
        session = await create_session(
            user_agent=user_agent,
            user_id=request.user_id  # Pass user_id from request
        )
        session_id = session.session_id
    else:
        # Get existing session or create new one if not found
        session = await get_session(session_id)
        if not session:
            session = await create_session(
                user_agent=user_agent,
                user_id=request.user_id  # Pass user_id from request
            )
            session_id = session.session_id
```

### 3. Update Analytics/Database Schema

Ensure the session and message tracking includes `user_id`:

**Session Collection:**
```javascript
{
  _id: ObjectId,
  session_id: String,
  user_id: String, // New field - will be null for anonymous sessions
  user_agent: String,
  created_at: Date,
  // ... other fields
}
```

**Message Collection:**
```javascript
{
  _id: ObjectId,
  session_id: String,
  user_id: String, // New field - copied from session or request
  message: String,
  response: String,
  timestamp: Date,
  // ... other fields
}
```

### 4. Frontend Integration Examples

#### Anonymous Usage (No Authentication Required)

The simplest way to use the API - no user_id needed:

```javascript
// Anonymous request - user_id completely omitted
const response = await fetch('/chat', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    prompt: "What is artificial intelligence?",
    use_search: true,
    max_new_tokens: 1000,
    temperature: 0.7
  })
});

// Anonymous request - user_id explicitly set to null
const response = await fetch('/chat', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    prompt: "Explain quantum computing",
    user_id: null, // Explicitly anonymous
    use_search: true
  })
});

// Anonymous request with session tracking (optional)
const response = await fetch('/chat', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-Session-ID': sessionId // For conversation continuity
  },
  body: JSON.stringify({
    prompt: "Continue our previous discussion",
    use_search: false,
    history: previousMessages
  })
});
```

#### Authenticated Usage (With User Tracking)

For applications with user authentication:

```javascript
// Authenticated request with user tracking
const response = await fetch('/chat', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-Session-ID': sessionId
  },
  body: JSON.stringify({
    prompt: userMessage,
    user_id: authenticatedUserId, // From your authentication system
    use_search: true,
    // ... other parameters
  })
});
```

#### Flexible Integration Pattern

Handle both authenticated and anonymous users seamlessly:

```javascript
async function sendChatMessage(prompt, authenticatedUserId = null) {
  const requestBody = {
    prompt: prompt,
    use_search: true,
    max_new_tokens: 1000,
    temperature: 0.7
  };

  // Only include user_id if user is authenticated
  if (authenticatedUserId) {
    requestBody.user_id = authenticatedUserId;
  }
  // For anonymous users, user_id is simply omitted

  const response = await fetch('/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(requestBody)
  });

  return await response.json();
}

// Usage examples:
// Anonymous: sendChatMessage("Hello, how are you?")
// Authenticated: sendChatMessage("Hello, how are you?", "user123")
```

## Anonymous Usage Patterns

### Quick Start (No Setup Required)

The fastest way to integrate Atlas API is through anonymous mode:

```bash
# Simple cURL example - no authentication needed
curl -X POST https://your-atlas-api.com/chat \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "What is machine learning?",
    "use_search": true
  }'
```

### Frontend Integration Examples

#### React/JavaScript
```javascript
// Simple React hook for anonymous chat
function useAnonymousChat() {
  const [messages, setMessages] = useState([]);
  
  const sendMessage = async (prompt) => {
    const response = await fetch('/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        prompt,
        use_search: true,
        history: messages
      })
    });
    
    const result = await response.json();
    setMessages(prev => [...prev, 
      { role: 'user', content: prompt },
      { role: 'assistant', content: result.response }
    ]);
    
    return result;
  };
  
  return { messages, sendMessage };
}
```

#### Python Client
```python
import requests

def anonymous_chat(prompt, use_search=True):
    """Send anonymous chat request to Atlas API"""
    response = requests.post('https://your-atlas-api.com/chat', 
        json={
            'prompt': prompt,
            'use_search': use_search,
            'max_new_tokens': 1000,
            'temperature': 0.7
        }
    )
    return response.json()

# Usage
result = anonymous_chat("Explain neural networks")
print(result['response'])
```

#### Node.js/Express
```javascript
const express = require('express');
const axios = require('axios');

app.post('/proxy-chat', async (req, res) => {
  try {
    const response = await axios.post('https://your-atlas-api.com/chat', {
      prompt: req.body.message,
      use_search: true,
      // user_id omitted for anonymous usage
    });
    
    res.json(response.data);
  } catch (error) {
    res.status(500).json({ error: 'Chat request failed' });
  }
});
```

### Progressive Enhancement

Start with anonymous mode and add authentication later:

```javascript
class ChatClient {
  constructor(apiUrl) {
    this.apiUrl = apiUrl;
    this.userId = null; // Start anonymous
  }
  
  // Enable authentication when ready
  authenticate(userId) {
    this.userId = userId;
  }
  
  // Logout returns to anonymous mode
  logout() {
    this.userId = null;
  }
  
  async sendMessage(prompt, options = {}) {
    const requestBody = {
      prompt,
      use_search: options.useSearch ?? true,
      max_new_tokens: options.maxTokens ?? 1000,
      temperature: options.temperature ?? 0.7,
      history: options.history ?? []
    };
    
    // Include user_id only if authenticated
    if (this.userId) {
      requestBody.user_id = this.userId;
    }
    
    const response = await fetch(`${this.apiUrl}/chat`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(requestBody)
    });
    
    return await response.json();
  }
}

// Usage:
const client = new ChatClient('https://your-atlas-api.com');

// Anonymous usage
await client.sendMessage("Hello!");

// Later, add authentication
client.authenticate("user123");
await client.sendMessage("Now I'm authenticated!");

// Return to anonymous
client.logout();
await client.sendMessage("Back to anonymous!");
```

## Benefits

### For Anonymous Users
1. **Zero Setup**: Start using immediately without any configuration
2. **Privacy-First**: No tracking or data collection
3. **Full Functionality**: Complete access to AI chat and search features
4. **No Registration**: Use the service without creating accounts

### For Authenticated Users
1. **User-Specific History**: Access chat history across sessions
2. **Personalization**: Tailored responses based on user preferences
3. **Analytics**: Detailed usage tracking and insights
4. **Data Association**: All interactions linked to user account

### For Developers
1. **Flexible Integration**: Support both usage modes seamlessly
2. **Backward Compatibility**: Existing anonymous implementations continue working
3. **Progressive Enhancement**: Start anonymous, add authentication later
4. **Simple API**: Same endpoints work for both modes

## Implementation Notes

### Anonymous Mode Behavior
- **Default Mode**: When `user_id` is omitted, null, or empty string, the system operates anonymously
- **No Validation Required**: Anonymous requests bypass user ID validation entirely  
- **Same Performance**: Anonymous requests have identical response times and functionality
- **Session Support**: Anonymous users can still use session IDs for conversation continuity

### Authentication Integration
- **Optional Field**: `user_id` is completely optional in all API requests
- **Flexible Validation**: System accepts null, undefined, or missing user_id values
- **Backward Compatibility**: Existing anonymous implementations continue working unchanged
- **Progressive Enhancement**: Applications can add authentication without breaking existing functionality

### Technical Details
- **Database Handling**: null `user_id` values are stored and queried efficiently
- **Analytics Separation**: Anonymous usage is tracked separately from authenticated usage
- **Session Management**: API server's session_id works independently of user authentication
- **Error Handling**: Anonymous requests have the same error handling as authenticated requests

### Best Practices
- **Start Simple**: Begin with anonymous mode for faster integration
- **Add Authentication Later**: Implement user tracking when needed
- **Handle Both Modes**: Design your frontend to work with or without user_id
- **Test Both Paths**: Ensure your application works in anonymous and authenticated modes

## API Reference

### POST /chat

Send a chat message and receive an AI-generated response with optional web search.

#### Request Body

```json
{
  "prompt": "string (required) - The user's message or question",
  "user_id": "string (optional) - User identifier for authenticated requests. Omit for anonymous mode",
  "use_search": "boolean (optional, default: true) - Whether to use web search for context", 
  "max_new_tokens": "integer (optional, default: 1000) - Maximum response length",
  "temperature": "number (optional, default: 0.7) - Response creativity (0.0-1.0)",
  "history": "array (optional, default: []) - Previous conversation messages",
  "force_search": "boolean (optional) - Override smart search optimization",
  "search_decision_mode": "string (optional, default: 'balanced') - Search sensitivity: 'conservative', 'balanced', 'aggressive'"
}
```

#### Anonymous Request Examples

**Minimal Anonymous Request:**
```json
{
  "prompt": "What is artificial intelligence?"
}
```

**Anonymous Request with Options:**
```json
{
  "prompt": "Explain quantum computing in simple terms",
  "use_search": true,
  "max_new_tokens": 500,
  "temperature": 0.5
}
```

**Anonymous Request with Conversation History:**
```json
{
  "prompt": "Can you elaborate on that?",
  "use_search": false,
  "history": [
    {"role": "user", "content": "What is machine learning?"},
    {"role": "assistant", "content": "Machine learning is a subset of AI..."}
  ]
}
```

**Anonymous Request with Search Optimization:**
```json
{
  "prompt": "What are the latest developments in AI?",
  "search_decision_mode": "aggressive",
  "force_search": true
}
```

**Anonymous Request with Conservative Search:**
```json
{
  "prompt": "Tell me more about neural networks",
  "search_decision_mode": "conservative",
  "history": [
    {"role": "user", "content": "What is machine learning?"},
    {"role": "assistant", "content": "Machine learning uses algorithms to learn from data..."}
  ]
}
```

#### Authenticated Request Examples

**Basic Authenticated Request:**
```json
{
  "prompt": "What is my chat history?",
  "user_id": "user123"
}
```

**Full Authenticated Request:**
```json
{
  "prompt": "Help me understand neural networks",
  "user_id": "user123",
  "use_search": true,
  "max_new_tokens": 1500,
  "temperature": 0.8,
  "history": []
}
```

#### Response Format

Both anonymous and authenticated requests return the same response format:

```json
{
  "response": "string - The AI-generated response",
  "search_results": "array - Search results used (if search was performed)",
  "search_decision": {
    "should_search": "boolean - Whether search was determined necessary",
    "reason": "string - Explanation for search decision",
    "confidence": "number - Confidence score (0.0-1.0)",
    "decision_method": "string - Method used (rule_based, hybrid, etc.)"
  },
  "cache_info": {
    "cache_hit": "boolean - Whether results came from cache",
    "flow_type": "string - Request flow type used",
    "cache_type": "string - Type of caching system used"
  }
}
```

### Headers

#### Optional Headers

- **X-Session-ID**: `string` - Session identifier for conversation continuity
- **Content-Type**: `application/json` - Required for POST requests
- **User-Agent**: `string` - Client identification (automatically tracked)

#### Example with Session Header

```bash
curl -X POST https://your-atlas-api.com/chat \
  -H "Content-Type: application/json" \
  -H "X-Session-ID: session-uuid-here" \
  -d '{
    "prompt": "Continue our conversation",
    "use_search": false
  }'
```

### Error Responses

Both anonymous and authenticated requests use the same error format:

```json
{
  "detail": "string - Error description",
  "error_code": "string - Machine-readable error code",
  "status_code": "number - HTTP status code"
}
```

#### Common Error Scenarios

**Invalid Request (400):**
```json
{
  "detail": "prompt field is required",
  "error_code": "MISSING_REQUIRED_FIELD",
  "status_code": 400
}
```

**Server Error (500):**
```json
{
  "detail": "Internal server error occurred",
  "error_code": "INTERNAL_ERROR", 
  "status_code": 500
}
```

### Rate Limiting

- **Anonymous Users**: Standard rate limits apply
- **Authenticated Users**: Same rate limits (no difference)
- **Rate Limit Headers**: Included in all responses
  - `X-RateLimit-Limit`: Requests per time window
  - `X-RateLimit-Remaining`: Remaining requests
  - `X-RateLimit-Reset`: Time when limit resets

## Testing Your Integration

### Quick Test Commands

**Test Anonymous Mode:**
```bash
# Basic anonymous request
curl -X POST https://your-atlas-api.com/chat \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Hello, how are you?"}'

# Anonymous with search disabled
curl -X POST https://your-atlas-api.com/chat \
  -H "Content-Type: application/json" \
  -d '{"prompt": "What is 2+2?", "use_search": false}'
```

**Test Authenticated Mode:**
```bash
# Basic authenticated request
curl -X POST https://your-atlas-api.com/chat \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Hello!", "user_id": "test-user-123"}'
```

### Integration Checklist

- [ ] Anonymous requests work without user_id
- [ ] Authenticated requests work with user_id
- [ ] Error handling works for both modes
- [ ] Session continuity works (with X-Session-ID header)
- [ ] Search functionality works in both modes
- [ ] Response format is consistent
- [ ] Rate limiting is properly handled