CoolFace
Apppublic

findEthics/Atlas

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
integration-guide.md631 linesDownload Raw Back to api
1# API Integration Guide: User Authentication & Anonymous Mode Support2 3## Overview4 5The 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.6 7## Required API Changes8 9### 1. Accept User ID in Chat Requests10 11The `/chat` endpoint needs to accept an optional `user_id` parameter to associate sessions with authenticated users.12 13**Current Request Structure:**14```python15class ChatRequest(BaseModel):16    prompt: str17    use_search: bool = True18    max_new_tokens: int = 100019    temperature: float = 0.720    history: List[dict] = []21```22 23**Updated Request Structure:**24```python25class ChatRequest(BaseModel):26    prompt: str27    use_search: bool = True28    max_new_tokens: int = 100029    temperature: float = 0.730    history: List[dict] = []31    user_id: Optional[str] = None  # Optional field - defaults to anonymous mode32    force_search: Optional[bool] = None  # Override smart search optimization33    search_decision_mode: str = "balanced"  # "conservative", "balanced", "aggressive"34```35 36### Anonymous Mode Support37 38The `user_id` parameter is **completely optional**. When omitted or set to null/empty string, the system operates in anonymous mode:39 40- **Anonymous requests**: No user tracking or identification41- **Same functionality**: Full chat capabilities without authentication42- **No setup required**: Works immediately without any configuration43- **Privacy-focused**: No personal data collection or storage44 45### Search Optimization Parameters46 47Atlas includes intelligent search optimization with new optional parameters:48 49#### `force_search: Optional[bool]`50- **Purpose**: Override the smart search optimization engine51- **Default**: `null` (use smart optimization)52- **Values**: 53  - `true` - Always perform web search regardless of context54  - `false` - Never perform web search (use only conversation history)  55  - `null` - Use intelligent search decision engine56 57#### `search_decision_mode: str`58- **Purpose**: Control the sensitivity of the search optimization engine59- **Default**: `"balanced"`60- **Values**:61  - `"conservative"` - Prefer using conversation history, minimize searches62  - `"balanced"` - Smart balance between search and history usage63  - `"aggressive"` - Prefer web search for most requests64 65### 2. Modify Session Creation/Tracking66 67Update the session management to include `user_id` when provided:68 69**In the `/chat` endpoint:**70```python71# Handle session management with user_id72if analytics_available:73    if not session_id:74        # Create new session with user_id if provided75        session = await create_session(76            user_agent=user_agent,77            user_id=request.user_id  # Pass user_id from request78        )79        session_id = session.session_id80    else:81        # Get existing session or create new one if not found82        session = await get_session(session_id)83        if not session:84            session = await create_session(85                user_agent=user_agent,86                user_id=request.user_id  # Pass user_id from request87            )88            session_id = session.session_id89```90 91### 3. Update Analytics/Database Schema92 93Ensure the session and message tracking includes `user_id`:94 95**Session Collection:**96```javascript97{98  _id: ObjectId,99  session_id: String,100  user_id: String, // New field - will be null for anonymous sessions101  user_agent: String,102  created_at: Date,103  // ... other fields104}105```106 107**Message Collection:**108```javascript109{110  _id: ObjectId,111  session_id: String,112  user_id: String, // New field - copied from session or request113  message: String,114  response: String,115  timestamp: Date,116  // ... other fields117}118```119 120### 4. Frontend Integration Examples121 122#### Anonymous Usage (No Authentication Required)123 124The simplest way to use the API - no user_id needed:125 126```javascript127// Anonymous request - user_id completely omitted128const response = await fetch('/chat', {129  method: 'POST',130  headers: {131    'Content-Type': 'application/json'132  },133  body: JSON.stringify({134    prompt: "What is artificial intelligence?",135    use_search: true,136    max_new_tokens: 1000,137    temperature: 0.7138  })139});140 141// Anonymous request - user_id explicitly set to null142const response = await fetch('/chat', {143  method: 'POST',144  headers: {145    'Content-Type': 'application/json'146  },147  body: JSON.stringify({148    prompt: "Explain quantum computing",149    user_id: null, // Explicitly anonymous150    use_search: true151  })152});153 154// Anonymous request with session tracking (optional)155const response = await fetch('/chat', {156  method: 'POST',157  headers: {158    'Content-Type': 'application/json',159    'X-Session-ID': sessionId // For conversation continuity160  },161  body: JSON.stringify({162    prompt: "Continue our previous discussion",163    use_search: false,164    history: previousMessages165  })166});167```168 169#### Authenticated Usage (With User Tracking)170 171For applications with user authentication:172 173```javascript174// Authenticated request with user tracking175const response = await fetch('/chat', {176  method: 'POST',177  headers: {178    'Content-Type': 'application/json',179    'X-Session-ID': sessionId180  },181  body: JSON.stringify({182    prompt: userMessage,183    user_id: authenticatedUserId, // From your authentication system184    use_search: true,185    // ... other parameters186  })187});188```189 190#### Flexible Integration Pattern191 192Handle both authenticated and anonymous users seamlessly:193 194```javascript195async function sendChatMessage(prompt, authenticatedUserId = null) {196  const requestBody = {197    prompt: prompt,198    use_search: true,199    max_new_tokens: 1000,200    temperature: 0.7201  };202 203  // Only include user_id if user is authenticated204  if (authenticatedUserId) {205    requestBody.user_id = authenticatedUserId;206  }207  // For anonymous users, user_id is simply omitted208 209  const response = await fetch('/chat', {210    method: 'POST',211    headers: {212      'Content-Type': 'application/json'213    },214    body: JSON.stringify(requestBody)215  });216 217  return await response.json();218}219 220// Usage examples:221// Anonymous: sendChatMessage("Hello, how are you?")222// Authenticated: sendChatMessage("Hello, how are you?", "user123")223```224 225## Anonymous Usage Patterns226 227### Quick Start (No Setup Required)228 229The fastest way to integrate Atlas API is through anonymous mode:230 231```bash232# Simple cURL example - no authentication needed233curl -X POST https://your-atlas-api.com/chat \234  -H "Content-Type: application/json" \235  -d '{236    "prompt": "What is machine learning?",237    "use_search": true238  }'239```240 241### Frontend Integration Examples242 243#### React/JavaScript244```javascript245// Simple React hook for anonymous chat246function useAnonymousChat() {247  const [messages, setMessages] = useState([]);248  249  const sendMessage = async (prompt) => {250    const response = await fetch('/chat', {251      method: 'POST',252      headers: { 'Content-Type': 'application/json' },253      body: JSON.stringify({254        prompt,255        use_search: true,256        history: messages257      })258    });259    260    const result = await response.json();261    setMessages(prev => [...prev, 262      { role: 'user', content: prompt },263      { role: 'assistant', content: result.response }264    ]);265    266    return result;267  };268  269  return { messages, sendMessage };270}271```272 273#### Python Client274```python275import requests276 277def anonymous_chat(prompt, use_search=True):278    """Send anonymous chat request to Atlas API"""279    response = requests.post('https://your-atlas-api.com/chat', 280        json={281            'prompt': prompt,282            'use_search': use_search,283            'max_new_tokens': 1000,284            'temperature': 0.7285        }286    )287    return response.json()288 289# Usage290result = anonymous_chat("Explain neural networks")291print(result['response'])292```293 294#### Node.js/Express295```javascript296const express = require('express');297const axios = require('axios');298 299app.post('/proxy-chat', async (req, res) => {300  try {301    const response = await axios.post('https://your-atlas-api.com/chat', {302      prompt: req.body.message,303      use_search: true,304      // user_id omitted for anonymous usage305    });306    307    res.json(response.data);308  } catch (error) {309    res.status(500).json({ error: 'Chat request failed' });310  }311});312```313 314### Progressive Enhancement315 316Start with anonymous mode and add authentication later:317 318```javascript319class ChatClient {320  constructor(apiUrl) {321    this.apiUrl = apiUrl;322    this.userId = null; // Start anonymous323  }324  325  // Enable authentication when ready326  authenticate(userId) {327    this.userId = userId;328  }329  330  // Logout returns to anonymous mode331  logout() {332    this.userId = null;333  }334  335  async sendMessage(prompt, options = {}) {336    const requestBody = {337      prompt,338      use_search: options.useSearch ?? true,339      max_new_tokens: options.maxTokens ?? 1000,340      temperature: options.temperature ?? 0.7,341      history: options.history ?? []342    };343    344    // Include user_id only if authenticated345    if (this.userId) {346      requestBody.user_id = this.userId;347    }348    349    const response = await fetch(`${this.apiUrl}/chat`, {350      method: 'POST',351      headers: { 'Content-Type': 'application/json' },352      body: JSON.stringify(requestBody)353    });354    355    return await response.json();356  }357}358 359// Usage:360const client = new ChatClient('https://your-atlas-api.com');361 362// Anonymous usage363await client.sendMessage("Hello!");364 365// Later, add authentication366client.authenticate("user123");367await client.sendMessage("Now I'm authenticated!");368 369// Return to anonymous370client.logout();371await client.sendMessage("Back to anonymous!");372```373 374## Benefits375 376### For Anonymous Users3771. **Zero Setup**: Start using immediately without any configuration3782. **Privacy-First**: No tracking or data collection3793. **Full Functionality**: Complete access to AI chat and search features3804. **No Registration**: Use the service without creating accounts381 382### For Authenticated Users3831. **User-Specific History**: Access chat history across sessions3842. **Personalization**: Tailored responses based on user preferences3853. **Analytics**: Detailed usage tracking and insights3864. **Data Association**: All interactions linked to user account387 388### For Developers3891. **Flexible Integration**: Support both usage modes seamlessly3902. **Backward Compatibility**: Existing anonymous implementations continue working3913. **Progressive Enhancement**: Start anonymous, add authentication later3924. **Simple API**: Same endpoints work for both modes393 394## Implementation Notes395 396### Anonymous Mode Behavior397- **Default Mode**: When `user_id` is omitted, null, or empty string, the system operates anonymously398- **No Validation Required**: Anonymous requests bypass user ID validation entirely  399- **Same Performance**: Anonymous requests have identical response times and functionality400- **Session Support**: Anonymous users can still use session IDs for conversation continuity401 402### Authentication Integration403- **Optional Field**: `user_id` is completely optional in all API requests404- **Flexible Validation**: System accepts null, undefined, or missing user_id values405- **Backward Compatibility**: Existing anonymous implementations continue working unchanged406- **Progressive Enhancement**: Applications can add authentication without breaking existing functionality407 408### Technical Details409- **Database Handling**: null `user_id` values are stored and queried efficiently410- **Analytics Separation**: Anonymous usage is tracked separately from authenticated usage411- **Session Management**: API server's session_id works independently of user authentication412- **Error Handling**: Anonymous requests have the same error handling as authenticated requests413 414### Best Practices415- **Start Simple**: Begin with anonymous mode for faster integration416- **Add Authentication Later**: Implement user tracking when needed417- **Handle Both Modes**: Design your frontend to work with or without user_id418- **Test Both Paths**: Ensure your application works in anonymous and authenticated modes419 420## API Reference421 422### POST /chat423 424Send a chat message and receive an AI-generated response with optional web search.425 426#### Request Body427 428```json429{430  "prompt": "string (required) - The user's message or question",431  "user_id": "string (optional) - User identifier for authenticated requests. Omit for anonymous mode",432  "use_search": "boolean (optional, default: true) - Whether to use web search for context", 433  "max_new_tokens": "integer (optional, default: 1000) - Maximum response length",434  "temperature": "number (optional, default: 0.7) - Response creativity (0.0-1.0)",435  "history": "array (optional, default: []) - Previous conversation messages",436  "force_search": "boolean (optional) - Override smart search optimization",437  "search_decision_mode": "string (optional, default: 'balanced') - Search sensitivity: 'conservative', 'balanced', 'aggressive'"438}439```440 441#### Anonymous Request Examples442 443**Minimal Anonymous Request:**444```json445{446  "prompt": "What is artificial intelligence?"447}448```449 450**Anonymous Request with Options:**451```json452{453  "prompt": "Explain quantum computing in simple terms",454  "use_search": true,455  "max_new_tokens": 500,456  "temperature": 0.5457}458```459 460**Anonymous Request with Conversation History:**461```json462{463  "prompt": "Can you elaborate on that?",464  "use_search": false,465  "history": [466    {"role": "user", "content": "What is machine learning?"},467    {"role": "assistant", "content": "Machine learning is a subset of AI..."}468  ]469}470```471 472**Anonymous Request with Search Optimization:**473```json474{475  "prompt": "What are the latest developments in AI?",476  "search_decision_mode": "aggressive",477  "force_search": true478}479```480 481**Anonymous Request with Conservative Search:**482```json483{484  "prompt": "Tell me more about neural networks",485  "search_decision_mode": "conservative",486  "history": [487    {"role": "user", "content": "What is machine learning?"},488    {"role": "assistant", "content": "Machine learning uses algorithms to learn from data..."}489  ]490}491```492 493#### Authenticated Request Examples494 495**Basic Authenticated Request:**496```json497{498  "prompt": "What is my chat history?",499  "user_id": "user123"500}501```502 503**Full Authenticated Request:**504```json505{506  "prompt": "Help me understand neural networks",507  "user_id": "user123",508  "use_search": true,509  "max_new_tokens": 1500,510  "temperature": 0.8,511  "history": []512}513```514 515#### Response Format516 517Both anonymous and authenticated requests return the same response format:518 519```json520{521  "response": "string - The AI-generated response",522  "search_results": "array - Search results used (if search was performed)",523  "search_decision": {524    "should_search": "boolean - Whether search was determined necessary",525    "reason": "string - Explanation for search decision",526    "confidence": "number - Confidence score (0.0-1.0)",527    "decision_method": "string - Method used (rule_based, hybrid, etc.)"528  },529  "cache_info": {530    "cache_hit": "boolean - Whether results came from cache",531    "flow_type": "string - Request flow type used",532    "cache_type": "string - Type of caching system used"533  }534}535```536 537### Headers538 539#### Optional Headers540 541- **X-Session-ID**: `string` - Session identifier for conversation continuity542- **Content-Type**: `application/json` - Required for POST requests543- **User-Agent**: `string` - Client identification (automatically tracked)544 545#### Example with Session Header546 547```bash548curl -X POST https://your-atlas-api.com/chat \549  -H "Content-Type: application/json" \550  -H "X-Session-ID: session-uuid-here" \551  -d '{552    "prompt": "Continue our conversation",553    "use_search": false554  }'555```556 557### Error Responses558 559Both anonymous and authenticated requests use the same error format:560 561```json562{563  "detail": "string - Error description",564  "error_code": "string - Machine-readable error code",565  "status_code": "number - HTTP status code"566}567```568 569#### Common Error Scenarios570 571**Invalid Request (400):**572```json573{574  "detail": "prompt field is required",575  "error_code": "MISSING_REQUIRED_FIELD",576  "status_code": 400577}578```579 580**Server Error (500):**581```json582{583  "detail": "Internal server error occurred",584  "error_code": "INTERNAL_ERROR", 585  "status_code": 500586}587```588 589### Rate Limiting590 591- **Anonymous Users**: Standard rate limits apply592- **Authenticated Users**: Same rate limits (no difference)593- **Rate Limit Headers**: Included in all responses594  - `X-RateLimit-Limit`: Requests per time window595  - `X-RateLimit-Remaining`: Remaining requests596  - `X-RateLimit-Reset`: Time when limit resets597 598## Testing Your Integration599 600### Quick Test Commands601 602**Test Anonymous Mode:**603```bash604# Basic anonymous request605curl -X POST https://your-atlas-api.com/chat \606  -H "Content-Type: application/json" \607  -d '{"prompt": "Hello, how are you?"}'608 609# Anonymous with search disabled610curl -X POST https://your-atlas-api.com/chat \611  -H "Content-Type: application/json" \612  -d '{"prompt": "What is 2+2?", "use_search": false}'613```614 615**Test Authenticated Mode:**616```bash617# Basic authenticated request618curl -X POST https://your-atlas-api.com/chat \619  -H "Content-Type: application/json" \620  -d '{"prompt": "Hello!", "user_id": "test-user-123"}'621```622 623### Integration Checklist624 625- [ ] Anonymous requests work without user_id626- [ ] Authenticated requests work with user_id627- [ ] Error handling works for both modes628- [ ] Session continuity works (with X-Session-ID header)629- [ ] Search functionality works in both modes630- [ ] Response format is consistent631- [ ] Rate limiting is properly handled