-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphase4_protocol.js
More file actions
449 lines (412 loc) · 16.9 KB
/
phase4_protocol.js
File metadata and controls
449 lines (412 loc) · 16.9 KB
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
/**
* @file Phase-4 Protocol Types
*
* Defines the data structures for Phase-4 Smart Campus orchestration:
* - RAG context structures
* - LLM context arrays
* - HTDI metadata
* - Request/response schemas
*
* @license SPDX-License-Identifier: Apache-2.0
*/
/**
* @typedef {Object} RAGContext
* @property {string} text - Document content chunk
* @property {string} source - Source identifier (file path, URL, etc.)
* @property {number} score - Cosine similarity [-1, 1]
* @property {Object.<string, any>} [metadata] - Optional metadata
*/
/**
* @typedef {Object} LLMContext
* @property {string} text - Context chunk text
* @property {string} source - Source identifier
* @property {number} relevance - Normalized relevance [0, 1]
* @property {'rag'|'room'|'entity'|'system'} [type] - Context type
* @property {Object.<string, any>} [metadata] - Additional metadata
*/
/**
* @typedef {Object} ProviderStatus
* @property {'ok'|'error'|'skipped'} status - Provider status
* @property {number} [latencyMs] - Provider latency in milliseconds
* @property {number} [resultsCount] - Number of results returned
* @property {string} [model] - Model used (for LLM)
* @property {string} [error] - Error message (if status='error')
*/
/**
* @typedef {Object} ContextUsage
* @property {number} ragChunks - Number of RAG chunks used
* @property {boolean} roomContext - Whether room context was included
* @property {boolean} entityContext - Whether entity context was included
*/
/**
* @typedef {Object} HTDIMetadata
* @property {string} requestId - Request ID for tracing
* @property {string} source - Request source (e.g., 'smart-campus', 'cli', 'web-ui')
* @property {string} timestamp - ISO 8601 timestamp
* @property {string} [room] - Room context (if applicable)
* @property {string[]} [entities] - Entity IDs referenced (if applicable)
* @property {Object} providersUsed - Provider telemetry
* @property {ProviderStatus} [providersUsed.rag] - RAG provider status
* @property {ProviderStatus} [providersUsed.llm] - LLM provider status
* @property {ProviderStatus} [providersUsed.smartCampus] - Smart Campus provider status
* @property {ContextUsage} [contextUsage] - Context usage statistics
*/
/**
* @typedef {Object} RoomQueryRequest
* @property {string} requestId - Request ID for tracing
* @property {string} source - Request source
* @property {string} timestamp - ISO 8601 timestamp
* @property {string} room - Room identifier
* @property {string} query - User query
* @property {boolean} [includeRag=true] - Include RAG context
* @property {boolean} [includeEntities=true] - Include entity states
* @property {string} [llmModel] - LLM model to use
* @property {string} [ragCollection='default'] - RAG collection to query
* @property {number} [ragTopK=5] - Number of RAG results
* @property {number} [ragThreshold=0.5] - Minimum RAG score threshold
* @property {number} [temperature=0.7] - LLM temperature
* @property {number} [maxTokens=1024] - Max LLM tokens
*/
/**
* @typedef {Object} RoomQueryResponse
* @property {boolean} ok - Success status
* @property {string} requestId - Request ID
* @property {string} answer - LLM-generated answer
* @property {RAGContext[]} ragContext - RAG results used
* @property {Object} roomContext - Smart Campus room context
* @property {string} roomContext.id - Room ID
* @property {string} roomContext.name - Room name
* @property {string} roomContext.description - Room description
* @property {Object[]} roomContext.entities - Room entities
* @property {HTDIMetadata} htdi - HTDI metadata
* @property {Object} llm - LLM usage stats
* @property {string} llm.model - Model used
* @property {Object} llm.usage - Token usage
* @property {number} llm.usage.prompt_tokens - Prompt tokens
* @property {number} llm.usage.completion_tokens - Completion tokens
* @property {number} llm.usage.total_tokens - Total tokens
* @property {string} llm.finishReason - Finish reason
* @property {number} latencyMs - Total orchestration latency
*/
/**
* @typedef {Object} ChatMessage
* @property {'system'|'user'|'assistant'} role - Message role
* @property {string} content - Message content
*/
/**
* @typedef {Object} ChatRequest
* @property {string} requestId - Request ID for tracing
* @property {string} source - Request source
* @property {string} timestamp - ISO 8601 timestamp
* @property {ChatMessage[]} messages - Chat history
* @property {boolean} [useRag=false] - Enable RAG context injection
* @property {string} [ragCollection='default'] - RAG collection to query
* @property {string} [ragQuery] - RAG query (defaults to last user message)
* @property {number} [ragTopK=5] - Number of RAG results
* @property {number} [ragThreshold=0.5] - Minimum RAG score threshold
* @property {string} [llmModel] - LLM model to use
* @property {number} [temperature=0.7] - LLM temperature
* @property {number} [maxTokens=1024] - Max LLM tokens
*/
/**
* @typedef {Object} ChatResponse
* @property {boolean} ok - Success status
* @property {string} requestId - Request ID
* @property {ChatMessage} message - LLM response message
* @property {RAGContext[]} [ragContext] - RAG results (if useRag=true)
* @property {HTDIMetadata} htdi - HTDI metadata
* @property {Object} llm - LLM usage stats
* @property {string} llm.model - Model used
* @property {Object} llm.usage - Token usage
* @property {string} llm.finishReason - Finish reason
* @property {number} latencyMs - Total orchestration latency
*/
/**
* @typedef {Object} HealthResponse
* @property {boolean} ok - Overall health status
* @property {'healthy'|'degraded'|'down'} status - Health status
* @property {string} timestamp - ISO 8601 timestamp
* @property {Object} providers - Provider health status
* @property {Object} providers.mlx - MLX provider health
* @property {boolean} providers.mlx.ok - MLX health status
* @property {number|null} providers.mlx.status - HTTP status code
* @property {boolean} providers.mlx.models_healthy - Models loaded status
* @property {number} providers.mlx.latencyMs - Health check latency
* @property {string} [providers.mlx.error] - Error message (if unhealthy)
* @property {Object} providers.rag - RAG provider health
* @property {boolean} providers.rag.ok - RAG health status
* @property {number|null} providers.rag.status - HTTP status code
* @property {number} providers.rag.latencyMs - Health check latency
* @property {string} [providers.rag.error] - Error message (if unhealthy)
* @property {Object} providers.smartCampus - Smart Campus provider health
* @property {boolean} providers.smartCampus.ok - Smart Campus health status
* @property {number|null} providers.smartCampus.status - HTTP status code
* @property {number} providers.smartCampus.latencyMs - Health check latency
* @property {string} [providers.smartCampus.error] - Error message (if unhealthy)
* @property {number} latencyMs - Total health check latency
*/
/**
* @typedef {Object} ErrorResponse
* @property {boolean} ok - Always false
* @property {string} requestId - Request ID
* @property {Object} error - Error details
* @property {string} error.code - Error code
* @property {string} error.message - Human-readable error message
* @property {Object} [error.details] - Per-provider error details
* @property {number} latencyMs - Total latency before error
*/
// ============================================================================
// Validation Functions
// ============================================================================
/**
* Validate RAGContext object
* @param {any} obj - Object to validate
* @returns {boolean} True if valid RAGContext
*/
export function isValidRAGContext(obj) {
if (!obj || typeof obj !== 'object') return false;
if (typeof obj.text !== 'string') return false;
if (typeof obj.source !== 'string') return false;
if (typeof obj.score !== 'number') return false;
if (obj.score < -1 || obj.score > 1) return false;
if (obj.metadata !== undefined && typeof obj.metadata !== 'object') return false;
return true;
}
/**
* Validate LLMContext object
* @param {any} obj - Object to validate
* @returns {boolean} True if valid LLMContext
*/
export function isValidLLMContext(obj) {
if (!obj || typeof obj !== 'object') return false;
if (typeof obj.text !== 'string') return false;
if (typeof obj.source !== 'string') return false;
if (typeof obj.relevance !== 'number') return false;
if (obj.relevance < 0 || obj.relevance > 1) return false;
if (obj.type !== undefined && !['rag', 'room', 'entity', 'system'].includes(obj.type)) return false;
if (obj.metadata !== undefined && typeof obj.metadata !== 'object') return false;
return true;
}
/**
* Validate HTDIMetadata object
* @param {any} obj - Object to validate
* @returns {boolean} True if valid HTDIMetadata
*/
export function isValidHTDIMetadata(obj) {
if (!obj || typeof obj !== 'object') return false;
if (typeof obj.requestId !== 'string') return false;
if (typeof obj.source !== 'string') return false;
if (typeof obj.timestamp !== 'string') return false;
// Optional fields
if (obj.room !== undefined && typeof obj.room !== 'string') return false;
if (obj.entities !== undefined && !Array.isArray(obj.entities)) return false;
if (obj.providersUsed !== undefined && typeof obj.providersUsed !== 'object') return false;
if (obj.contextUsage !== undefined && typeof obj.contextUsage !== 'object') return false;
return true;
}
/**
* Validate RoomQueryRequest object
* @param {any} obj - Object to validate
* @returns {{valid: boolean, errors: string[]}} Validation result
*/
export function validateRoomQueryRequest(obj) {
const errors = [];
if (!obj || typeof obj !== 'object') {
errors.push('Request must be an object');
return { valid: false, errors };
}
// Required fields
if (typeof obj.requestId !== 'string' || obj.requestId.trim().length === 0) {
errors.push('requestId is required and must be a non-empty string');
}
if (typeof obj.source !== 'string' || obj.source.trim().length === 0) {
errors.push('source is required and must be a non-empty string');
}
if (typeof obj.timestamp !== 'string' || obj.timestamp.trim().length === 0) {
errors.push('timestamp is required and must be a non-empty string');
}
if (typeof obj.room !== 'string' || obj.room.trim().length === 0) {
errors.push('room is required and must be a non-empty string');
}
if (typeof obj.query !== 'string' || obj.query.trim().length === 0) {
errors.push('query is required and must be a non-empty string');
}
// Optional fields (type checking)
if (obj.includeRag !== undefined && typeof obj.includeRag !== 'boolean') {
errors.push('includeRag must be a boolean');
}
if (obj.includeEntities !== undefined && typeof obj.includeEntities !== 'boolean') {
errors.push('includeEntities must be a boolean');
}
if (obj.llmModel !== undefined && typeof obj.llmModel !== 'string') {
errors.push('llmModel must be a string');
}
if (obj.ragCollection !== undefined && typeof obj.ragCollection !== 'string') {
errors.push('ragCollection must be a string');
}
if (obj.ragTopK !== undefined && (typeof obj.ragTopK !== 'number' || obj.ragTopK < 1)) {
errors.push('ragTopK must be a positive number');
}
if (obj.ragThreshold !== undefined && (typeof obj.ragThreshold !== 'number' || obj.ragThreshold < -1 || obj.ragThreshold > 1)) {
errors.push('ragThreshold must be a number between -1 and 1');
}
if (obj.temperature !== undefined && (typeof obj.temperature !== 'number' || obj.temperature < 0 || obj.temperature > 2)) {
errors.push('temperature must be a number between 0 and 2');
}
if (obj.maxTokens !== undefined && (typeof obj.maxTokens !== 'number' || obj.maxTokens < 1)) {
errors.push('maxTokens must be a positive number');
}
return { valid: errors.length === 0, errors };
}
/**
* Validate ChatRequest object
* @param {any} obj - Object to validate
* @returns {{valid: boolean, errors: string[]}} Validation result
*/
export function validateChatRequest(obj) {
const errors = [];
if (!obj || typeof obj !== 'object') {
errors.push('Request must be an object');
return { valid: false, errors };
}
// Required fields
if (typeof obj.requestId !== 'string' || obj.requestId.trim().length === 0) {
errors.push('requestId is required and must be a non-empty string');
}
if (typeof obj.source !== 'string' || obj.source.trim().length === 0) {
errors.push('source is required and must be a non-empty string');
}
if (typeof obj.timestamp !== 'string' || obj.timestamp.trim().length === 0) {
errors.push('timestamp is required and must be a non-empty string');
}
if (!Array.isArray(obj.messages) || obj.messages.length === 0) {
errors.push('messages is required and must be a non-empty array');
} else {
// Validate each message
obj.messages.forEach((msg, idx) => {
if (typeof msg !== 'object' || !msg) {
errors.push(`messages[${idx}] must be an object`);
} else {
if (!['system', 'user', 'assistant'].includes(msg.role)) {
errors.push(`messages[${idx}].role must be 'system', 'user', or 'assistant'`);
}
if (typeof msg.content !== 'string') {
errors.push(`messages[${idx}].content must be a string`);
}
}
});
}
// Optional fields (type checking)
if (obj.useRag !== undefined && typeof obj.useRag !== 'boolean') {
errors.push('useRag must be a boolean');
}
if (obj.ragCollection !== undefined && typeof obj.ragCollection !== 'string') {
errors.push('ragCollection must be a string');
}
if (obj.ragQuery !== undefined && typeof obj.ragQuery !== 'string') {
errors.push('ragQuery must be a string');
}
if (obj.ragTopK !== undefined && (typeof obj.ragTopK !== 'number' || obj.ragTopK < 1)) {
errors.push('ragTopK must be a positive number');
}
if (obj.ragThreshold !== undefined && (typeof obj.ragThreshold !== 'number' || obj.ragThreshold < -1 || obj.ragThreshold > 1)) {
errors.push('ragThreshold must be a number between -1 and 1');
}
if (obj.llmModel !== undefined && typeof obj.llmModel !== 'string') {
errors.push('llmModel must be a string');
}
if (obj.temperature !== undefined && (typeof obj.temperature !== 'number' || obj.temperature < 0 || obj.temperature > 2)) {
errors.push('temperature must be a number between 0 and 2');
}
if (obj.maxTokens !== undefined && (typeof obj.maxTokens !== 'number' || obj.maxTokens < 1)) {
errors.push('maxTokens must be a positive number');
}
return { valid: errors.length === 0, errors };
}
// ============================================================================
// Helper Functions
// ============================================================================
/**
* Convert RAGContext to LLMContext
* @param {RAGContext} ragContext - RAG context object
* @returns {LLMContext} LLM context object
*/
export function ragContextToLLMContext(ragContext) {
if (!isValidRAGContext(ragContext)) {
throw new Error('Invalid RAGContext object');
}
return {
text: ragContext.text,
source: ragContext.source,
relevance: normalizeScore(ragContext.score),
type: 'rag',
metadata: ragContext.metadata || {}
};
}
/**
* Normalize RAG score from [-1, 1] to [0, 1]
* @param {number} score - Cosine similarity score [-1, 1]
* @returns {number} Normalized score [0, 1]
*/
export function normalizeScore(score) {
if (typeof score !== 'number' || score < -1 || score > 1) {
throw new Error('Score must be a number between -1 and 1');
}
return (score + 1) / 2;
}
/**
* Generate HTDI metadata with provider telemetry
* @param {string} requestId - Request ID
* @param {string} source - Request source
* @param {Object} options - Additional options
* @returns {HTDIMetadata} HTDI metadata object
*/
export function createHTDIMetadata(requestId, source, options = {}) {
const htdi = {
requestId,
source,
timestamp: new Date().toISOString(),
providersUsed: {}
};
if (options.room) htdi.room = options.room;
if (options.entities) htdi.entities = options.entities;
if (options.providersUsed) htdi.providersUsed = options.providersUsed;
if (options.contextUsage) htdi.contextUsage = options.contextUsage;
return htdi;
}
/**
* Create error response object
* @param {string} requestId - Request ID
* @param {string} code - Error code
* @param {string} message - Error message
* @param {Object} [details] - Additional error details
* @param {number} [latencyMs=0] - Latency before error
* @returns {ErrorResponse} Error response object
*/
export function createErrorResponse(requestId, code, message, details = null, latencyMs = 0) {
const error = {
ok: false,
requestId,
error: {
code,
message
},
latencyMs
};
if (details) {
error.error.details = details;
}
return error;
}
// Export all types for documentation purposes
export default {
isValidRAGContext,
isValidLLMContext,
isValidHTDIMetadata,
validateRoomQueryRequest,
validateChatRequest,
ragContextToLLMContext,
normalizeScore,
createHTDIMetadata,
createErrorResponse
};