rag-module 0.3.3

Enterprise RAG module with chat context storage, vector search, session management, and model downloading. Rust implementation with Node.js compatibility.
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
# RAG Module - UI Integration Guide

## Overview

The RAG Module provides two distinct search functionalities optimized for different data types:

1. **Chat History Search** - Fast filter-based search for conversation data
2. **Estate Resources Search** - AI-powered semantic search for cloud infrastructure data

---

## 🗨️ Chat History Search

### Function: `search_chat_history()`

**Purpose**: Search through conversation history using metadata filters (no AI/embeddings - optimized for speed)

### Request Structure

```rust
pub struct ChatSearchOptions {
    pub context_id: Option<String>,        // Required: Conversation context ID
    pub role: Option<String>,              // Optional: "user" or "assistant"
    pub from_timestamp: Option<i64>,       // Optional: Unix timestamp start
    pub to_timestamp: Option<i64>,         // Optional: Unix timestamp end
    pub from_message_index: Option<i32>,   // Optional: Start message index
    pub to_message_index: Option<i32>,     // Optional: End message index
    pub limit: Option<usize>,              // Optional: Max results (default: 50, max: 200)
    pub include_metadata: bool,            // Include full metadata in response
}
```

### Example Request

```json
{
  "context_id": "ctx_123456",
  "role": "user",
  "from_timestamp": 1698765432,
  "to_timestamp": 1698765532,
  "limit": 25,
  "include_metadata": true
}
```

### Response Structure

```json
[
  {
    "id": "msg_789",
    "context_id": "ctx_123456",
    "role": "user",
    "content": "What are my running EC2 instances?",
    "timestamp": 1698765450,
    "message_index": 15,
    "metadata": {
      "session_id": "sess_456",
      "user_id": "user_789"
    }
  },
  {
    "id": "msg_790",
    "context_id": "ctx_123456", 
    "role": "assistant",
    "content": "You have 5 running EC2 instances...",
    "timestamp": 1698765455,
    "message_index": 16,
    "metadata": {
      "session_id": "sess_456",
      "response_time_ms": 1250
    }
  }
]
```

### Usage Examples

**Get recent chat for a context:**
```rust
let options = ChatSearchOptions {
    context_id: Some("ctx_123456".to_string()),
    role: None,
    from_timestamp: None,
    to_timestamp: None,
    from_message_index: None,
    to_message_index: None,
    limit: Some(50),
    include_metadata: true,
};

let results = search_service.search_chat_history(options).await?;
```

**Get only user messages in time range:**
```rust
let options = ChatSearchOptions {
    context_id: Some("ctx_123456".to_string()),
    role: Some("user".to_string()),
    from_timestamp: Some(1698765000),
    to_timestamp: Some(1698766000),
    limit: Some(100),
    include_metadata: false,
};
```

---

## ☁️ Estate Resources Search

### Function: `search_estate_resources()`

**Purpose**: AI-powered semantic search through cloud infrastructure data with spell correction and intelligent filtering

### Request Structure

```rust
pub struct EstateSearchOptions {
    pub resource_types: Option<Vec<String>>,    // e.g., ["ec2", "rds", "s3"]
    pub account_ids: Option<Vec<String>>,       // AWS/Azure/GCP account IDs
    pub regions: Option<Vec<String>>,           // e.g., ["us-east-1", "eu-west-1"]
    pub services: Option<Vec<String>>,          // e.g., ["lambda", "dynamodb"]
    pub states: Option<Vec<String>>,            // e.g., ["running", "stopped"]
    pub environment: Option<String>,            // e.g., "production", "staging"
    pub application: Option<String>,            // Application name
    pub synced_after: Option<i64>,              // Unix timestamp for freshness
    pub limit: Option<usize>,                   // Max results (default: 15, max: 50)
    pub score_threshold: Option<f32>,           // Minimum relevance (0.0-1.0)
    pub include_metadata: bool,                 // Include full metadata
    pub use_anonymous_ids: bool,                // Use anonymous resource IDs
}
```

### Example Requests

**Basic semantic search:**
```json
{
  "query": "show me all running EC2 instances in production",
  "options": {
    "environment": "production",
    "states": ["running"],
    "resource_types": ["ec2"],
    "limit": 20,
    "score_threshold": 0.3,
    "include_metadata": true,
    "use_anonymous_ids": false
  }
}
```

**Complex multi-service search:**
```json
{
  "query": "lambda functions connected to RDS databases with high CPU usage",
  "options": {
    "services": ["lambda", "rds"],
    "regions": ["us-east-1", "us-west-2"],
    "limit": 15,
    "score_threshold": 0.4,
    "include_metadata": true
  }
}
```

### Response Structure

```json
[
  {
    "id": "res_abc123",
    "score": 0.89,
    "resource_type": "ec2",
    "service": "ec2",
    "account_id": "123456789012",
    "region": "us-east-1",
    "state": "running",
    "name": "web-server-prod-01",
    "environment": "production",
    "application": "web-app",
    "last_synced": 1698765432,
    "metadata": {
      "instance_type": "t3.large",
      "vpc_id": "vpc-12345",
      "security_groups": ["sg-67890"],
      "tags": {
        "Environment": "production",
        "Application": "web-app",
        "Owner": "team-alpha"
      }
    },
    "content": "EC2 instance web-server-prod-01 running in us-east-1..."
  }
]
```

### Usage Examples

**Search for resources by natural language:**
```rust
let options = EstateSearchOptions {
    resource_types: None,
    account_ids: None,
    regions: Some(vec!["us-east-1".to_string()]),
    services: None,
    states: Some(vec!["running".to_string()]),
    environment: Some("production".to_string()),
    application: None,
    synced_after: None,
    limit: Some(20),
    score_threshold: Some(0.3),
    include_metadata: true,
    use_anonymous_ids: false,
};

let results = search_service.search_estate_resources(
    "databases with high connection count",
    options,
    Some(iam_context)
).await?;
```

---

## 🔍 Search Features

### Chat History Search Features:
- **Ultra-fast filtering** (no AI processing)
- 📅 **Time-based queries** (timestamp ranges)
- 🎭 **Role filtering** (user/assistant messages)
- 📊 **Message indexing** (sequential message numbers)
- 🔐 **Context isolation** (per-conversation search)

### Estate Resources Search Features:
- 🤖 **AI-powered semantic search** (understands intent)
- ✍️ **Spell correction** ("lamda" → "lambda")
- 🌍 **Multi-cloud support** (AWS, Azure, GCP)
- 🎯 **Smart filtering** (resource types, regions, states)
- 📈 **Relevance scoring** (0.0-1.0 similarity scores)
- 🔒 **IAM integration** (permission-based filtering)
- 🎭 **Anonymous IDs** (privacy protection)
-**Freshness filtering** (recently synced data)

---

## 📊 Response Formats

### Chat Search Response Fields:
- `id`: Message unique identifier
- `context_id`: Conversation context
- `role`: "user" or "assistant"  
- `content`: Message text content
- `timestamp`: Unix timestamp
- `message_index`: Sequential message number
- `metadata`: Additional message data

### Estate Search Response Fields:
- `id`: Resource unique identifier
- `score`: Relevance score (0.0-1.0)
- `resource_type`: Type of resource (ec2, rds, s3, etc.)
- `service`: Cloud service name
- `account_id`: Cloud account identifier
- `region`: Geographic region
- `state`: Current state (running, stopped, etc.)
- `name`: Resource name/identifier
- `environment`: Environment tag (prod, staging, etc.)
- `application`: Application tag
- `last_synced`: Last data sync timestamp
- `metadata`: Full resource metadata and tags
- `content`: Searchable text representation

---

## 🚨 Error Handling

### Common Error Responses:

```json
{
  "error": "InvalidContextId",
  "message": "Context ID is required for chat history search",
  "code": 400
}
```

```json
{
  "error": "SearchLimitExceeded", 
  "message": "Maximum limit for chat search is 200",
  "code": 400
}
```

```json
{
  "error": "InsufficientPermissions",
  "message": "User lacks permission to access resource res_123",
  "code": 403
}
```

```json
{
  "error": "EmbeddingGenerationFailed",
  "message": "Failed to generate embeddings for query",
  "code": 500
}
```

---

## ⚡ Performance Guidelines

### Chat History Search:
- **Speed**: < 50ms typical response time
- **Limits**: Max 200 results per request
- **Optimization**: Use specific context_id and time ranges
- **Caching**: Results cached per context

### Estate Resources Search:
- **Speed**: 200-800ms typical response time (AI processing)
- **Limits**: Max 50 results per request  
- **Optimization**: Use filters to reduce search space
- **Scoring**: Higher score_threshold = faster results

---

## 🔧 Integration Examples

### TypeScript/JavaScript Integration:

```typescript
interface ChatSearchOptions {
  context_id?: string;
  role?: "user" | "assistant";
  from_timestamp?: number;
  to_timestamp?: number;
  from_message_index?: number;
  to_message_index?: number;
  limit?: number;
  include_metadata: boolean;
}

interface EstateSearchOptions {
  resource_types?: string[];
  account_ids?: string[];
  regions?: string[];
  services?: string[];
  states?: string[];
  environment?: string;
  application?: string;
  synced_after?: number;
  limit?: number;
  score_threshold?: number;
  include_metadata: boolean;
  use_anonymous_ids: boolean;
}

// Chat history search
const chatResults = await ragModule.searchChatHistory({
  context_id: "ctx_123456",
  role: "user",
  limit: 50,
  include_metadata: true
});

// Estate resources search  
const estateResults = await ragModule.searchEstateResources(
  "show me all lambda functions in production",
  {
    environment: "production",
    services: ["lambda"],
    limit: 20,
    score_threshold: 0.4,
    include_metadata: true,
    use_anonymous_ids: false
  }
);
```

### React Component Example:

```tsx
import React, { useState } from 'react';

const SearchInterface = () => {
  const [chatResults, setChatResults] = useState([]);
  const [estateResults, setEstateResults] = useState([]);
  
  const searchChat = async (contextId: string) => {
    const results = await ragModule.searchChatHistory({
      context_id: contextId,
      limit: 50,
      include_metadata: true
    });
    setChatResults(results);
  };
  
  const searchEstate = async (query: string) => {
    const results = await ragModule.searchEstateResources(query, {
      limit: 20,
      score_threshold: 0.3,
      include_metadata: true,
      use_anonymous_ids: false
    });
    setEstateResults(results);
  };
  
  return (
    <div>
      <button onClick={() => searchChat('ctx_123')}>
        Search Chat History
      </button>
      <button onClick={() => searchEstate('running instances')}>
        Search Resources
      </button>
      
      {/* Render results */}
      {chatResults.map(result => (
        <div key={result.id}>
          <strong>{result.role}:</strong> {result.content}
        </div>
      ))}
      
      {estateResults.map(result => (
        <div key={result.id}>
          <strong>Score: {result.score}</strong> - {result.name}
        </div>
      ))}
    </div>
  );
};
```

---

## 📋 Best Practices

### For Chat History Search:
1. Always provide `context_id` for best performance
2. Use time ranges to limit scope
3. Set appropriate limits based on UI pagination
4. Cache results when possible
5. Handle empty results gracefully

### For Estate Resources Search:  
1. Use natural language queries for best results
2. Set `score_threshold` between 0.3-0.5 for balanced results
3. Apply filters to reduce search scope
4. Handle spelling variations (module auto-corrects)
5. Consider using `use_anonymous_ids` for privacy
6. Implement proper error handling for permissions
7. Show relevance scores in UI for user confidence

This integration guide provides everything the UI team needs to implement both search functionalities effectively!