Commit
·
c3a42ce
1
Parent(s):
91c95f0
Add context mode endpoints (fresh vs relevant) and update API documentation
Browse files- API_DOCUMENTATION.md +271 -11
- flask_api_standalone.py +158 -1
API_DOCUMENTATION.md
CHANGED
|
@@ -62,7 +62,9 @@ Host: huggingface.co
|
|
| 62 |
"endpoints": {
|
| 63 |
"health": "GET /api/health",
|
| 64 |
"chat": "POST /api/chat",
|
| 65 |
-
"initialize": "POST /api/initialize"
|
|
|
|
|
|
|
| 66 |
}
|
| 67 |
}
|
| 68 |
```
|
|
@@ -139,6 +141,7 @@ Content-Type: application/json
|
|
| 139 |
| `history` | array | ❌ No | Conversation history as array of `[user, assistant]` pairs |
|
| 140 |
| `session_id` | string | ❌ No | Unique session identifier for context continuity |
|
| 141 |
| `user_id` | string | ❌ No | User identifier (defaults to "anonymous") |
|
|
|
|
| 142 |
|
| 143 |
**Response (Success):**
|
| 144 |
```json
|
|
@@ -186,6 +189,34 @@ Content-Type: application/json
|
|
| 186 |
}
|
| 187 |
```
|
| 188 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
---
|
| 190 |
|
| 191 |
### 4. Initialize Orchestrator
|
|
@@ -228,6 +259,132 @@ Content-Type: application/json
|
|
| 228 |
|
| 229 |
---
|
| 230 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
## Code Examples
|
| 232 |
|
| 233 |
### Python
|
|
@@ -244,13 +401,15 @@ def check_health():
|
|
| 244 |
return response.json()
|
| 245 |
|
| 246 |
# Send chat message
|
| 247 |
-
def send_message(message, session_id=None, user_id=None, history=None):
|
| 248 |
payload = {
|
| 249 |
"message": message,
|
| 250 |
"session_id": session_id,
|
| 251 |
"user_id": user_id or "anonymous",
|
| 252 |
"history": history or []
|
| 253 |
}
|
|
|
|
|
|
|
| 254 |
|
| 255 |
response = requests.post(
|
| 256 |
f"{BASE_URL}/api/chat",
|
|
@@ -280,13 +439,25 @@ if __name__ == "__main__":
|
|
| 280 |
print(f"Response: {result['message']}")
|
| 281 |
print(f"Reasoning: {result.get('reasoning', {})}")
|
| 282 |
|
| 283 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
history = result['history']
|
| 285 |
result2 = send_message(
|
| 286 |
message="Can you explain neural networks?",
|
| 287 |
session_id="my-session-123",
|
| 288 |
user_id="user-456",
|
| 289 |
-
history=history
|
|
|
|
| 290 |
)
|
| 291 |
print(f"Follow-up Response: {result2['message']}")
|
| 292 |
```
|
|
@@ -302,14 +473,52 @@ async function checkHealth() {
|
|
| 302 |
return await response.json();
|
| 303 |
}
|
| 304 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
// Send chat message
|
| 306 |
-
async function sendMessage(message, sessionId = null, userId = null, history = []) {
|
| 307 |
const payload = {
|
| 308 |
message: message,
|
| 309 |
session_id: sessionId,
|
| 310 |
user_id: userId || 'anonymous',
|
| 311 |
history: history
|
| 312 |
};
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
const response = await fetch(`${BASE_URL}/api/chat`, {
|
| 315 |
method: 'POST',
|
|
@@ -345,14 +554,20 @@ async function main() {
|
|
| 345 |
console.log('Response:', result.message);
|
| 346 |
console.log('Reasoning:', result.reasoning);
|
| 347 |
|
| 348 |
-
// Continue conversation
|
|
|
|
| 349 |
const result2 = await sendMessage(
|
| 350 |
'Can you explain neural networks?',
|
| 351 |
'my-session-123',
|
| 352 |
'user-456',
|
| 353 |
-
result.history
|
|
|
|
| 354 |
);
|
| 355 |
console.log('Follow-up Response:', result2.message);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
}
|
| 357 |
} catch (error) {
|
| 358 |
console.error('Error:', error);
|
|
@@ -368,6 +583,18 @@ main();
|
|
| 368 |
# Check health
|
| 369 |
curl -X GET "https://jatinautonomouslabs-research-ai-assistant-api.hf.space/api/health"
|
| 370 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
# Send chat message
|
| 372 |
curl -X POST "https://jatinautonomouslabs-research-ai-assistant-api.hf.space/api/chat" \
|
| 373 |
-H "Content-Type: application/json" \
|
|
@@ -375,6 +602,7 @@ curl -X POST "https://jatinautonomouslabs-research-ai-assistant-api.hf.space/api
|
|
| 375 |
"message": "What is machine learning?",
|
| 376 |
"session_id": "my-session-123",
|
| 377 |
"user_id": "user-456",
|
|
|
|
| 378 |
"history": []
|
| 379 |
}'
|
| 380 |
|
|
@@ -404,15 +632,38 @@ async function checkHealth() {
|
|
| 404 |
return response.data;
|
| 405 |
}
|
| 406 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 407 |
// Send chat message
|
| 408 |
-
async function sendMessage(message, sessionId = null, userId = null, history = []) {
|
| 409 |
try {
|
| 410 |
-
const
|
| 411 |
message: message,
|
| 412 |
session_id: sessionId,
|
| 413 |
user_id: userId || 'anonymous',
|
| 414 |
history: history
|
| 415 |
-
}
|
|
|
|
|
|
|
|
|
|
| 416 |
headers: {
|
| 417 |
'Content-Type': 'application/json'
|
| 418 |
}
|
|
@@ -434,13 +685,22 @@ async function sendMessage(message, sessionId = null, userId = null, history = [
|
|
| 434 |
console.log('API Status:', health);
|
| 435 |
|
| 436 |
if (health.orchestrator_ready) {
|
|
|
|
|
|
|
|
|
|
| 437 |
const result = await sendMessage(
|
| 438 |
'What is machine learning?',
|
| 439 |
'my-session-123',
|
| 440 |
-
'user-456'
|
|
|
|
|
|
|
| 441 |
);
|
| 442 |
|
| 443 |
console.log('Response:', result.message);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
}
|
| 445 |
} catch (error) {
|
| 446 |
console.error('Error:', error.message);
|
|
|
|
| 62 |
"endpoints": {
|
| 63 |
"health": "GET /api/health",
|
| 64 |
"chat": "POST /api/chat",
|
| 65 |
+
"initialize": "POST /api/initialize",
|
| 66 |
+
"context_mode_get": "GET /api/context/mode",
|
| 67 |
+
"context_mode_set": "POST /api/context/mode"
|
| 68 |
}
|
| 69 |
}
|
| 70 |
```
|
|
|
|
| 141 |
| `history` | array | ❌ No | Conversation history as array of `[user, assistant]` pairs |
|
| 142 |
| `session_id` | string | ❌ No | Unique session identifier for context continuity |
|
| 143 |
| `user_id` | string | ❌ No | User identifier (defaults to "anonymous") |
|
| 144 |
+
| `context_mode` | string | ❌ No | Context retrieval mode: `"fresh"` (no user context) or `"relevant"` (only relevant context). Defaults to `"fresh"` if not set. |
|
| 145 |
|
| 146 |
**Response (Success):**
|
| 147 |
```json
|
|
|
|
| 189 |
}
|
| 190 |
```
|
| 191 |
|
| 192 |
+
**Context Mode Feature:**
|
| 193 |
+
|
| 194 |
+
The `context_mode` parameter controls how user context is retrieved and used:
|
| 195 |
+
|
| 196 |
+
- **`"fresh"`** (default): No user context is included. Each conversation starts fresh, ideal for:
|
| 197 |
+
- General questions requiring no prior context
|
| 198 |
+
- Avoiding context contamination
|
| 199 |
+
- Faster responses (no context retrieval overhead)
|
| 200 |
+
|
| 201 |
+
- **`"relevant"`**: Only relevant user context is included based on relevance classification. The system:
|
| 202 |
+
- Analyzes all previous interactions for the session
|
| 203 |
+
- Classifies which interactions are relevant to the current query
|
| 204 |
+
- Includes only relevant context summaries
|
| 205 |
+
- Ideal for:
|
| 206 |
+
- Follow-up questions that build on previous conversations
|
| 207 |
+
- Maintaining continuity within a research session
|
| 208 |
+
- Personalized responses based on user history
|
| 209 |
+
|
| 210 |
+
**Example with Context Mode:**
|
| 211 |
+
```json
|
| 212 |
+
{
|
| 213 |
+
"message": "Can you remind me what we discussed about quantum computing?",
|
| 214 |
+
"session_id": "session-123",
|
| 215 |
+
"user_id": "user-456",
|
| 216 |
+
"context_mode": "relevant"
|
| 217 |
+
}
|
| 218 |
+
```
|
| 219 |
+
|
| 220 |
---
|
| 221 |
|
| 222 |
### 4. Initialize Orchestrator
|
|
|
|
| 259 |
|
| 260 |
---
|
| 261 |
|
| 262 |
+
### 5. Get Context Mode
|
| 263 |
+
|
| 264 |
+
**Endpoint:** `GET /api/context/mode`
|
| 265 |
+
|
| 266 |
+
**Description:** Retrieve the current context retrieval mode for a session.
|
| 267 |
+
|
| 268 |
+
**Request:**
|
| 269 |
+
```http
|
| 270 |
+
GET /api/context/mode?session_id=session-123 HTTP/1.1
|
| 271 |
+
Host: huggingface.co
|
| 272 |
+
```
|
| 273 |
+
|
| 274 |
+
**Query Parameters:**
|
| 275 |
+
|
| 276 |
+
| Parameter | Type | Required | Description |
|
| 277 |
+
|-----------|------|----------|-------------|
|
| 278 |
+
| `session_id` | string | ✅ Yes | Session identifier |
|
| 279 |
+
|
| 280 |
+
**Response (Success):**
|
| 281 |
+
```json
|
| 282 |
+
{
|
| 283 |
+
"success": true,
|
| 284 |
+
"session_id": "session-123",
|
| 285 |
+
"context_mode": "fresh",
|
| 286 |
+
"description": {
|
| 287 |
+
"fresh": "No user context included - starts fresh each time",
|
| 288 |
+
"relevant": "Only relevant user context included based on relevance classification"
|
| 289 |
+
}
|
| 290 |
+
}
|
| 291 |
+
```
|
| 292 |
+
|
| 293 |
+
**Response Fields:**
|
| 294 |
+
|
| 295 |
+
| Field | Type | Description |
|
| 296 |
+
|-------|------|-------------|
|
| 297 |
+
| `success` | boolean | Whether the request was successful |
|
| 298 |
+
| `session_id` | string | Session identifier |
|
| 299 |
+
| `context_mode` | string | Current mode: `"fresh"` or `"relevant"` |
|
| 300 |
+
| `description` | object | Description of each mode |
|
| 301 |
+
|
| 302 |
+
**Status Codes:**
|
| 303 |
+
- `200 OK` - Success
|
| 304 |
+
- `400 Bad Request` - Missing `session_id` parameter
|
| 305 |
+
- `500 Internal Server Error` - Server error
|
| 306 |
+
- `503 Service Unavailable` - Orchestrator not ready or context mode not available
|
| 307 |
+
|
| 308 |
+
**Error Response:**
|
| 309 |
+
```json
|
| 310 |
+
{
|
| 311 |
+
"success": false,
|
| 312 |
+
"error": "session_id query parameter is required"
|
| 313 |
+
}
|
| 314 |
+
```
|
| 315 |
+
|
| 316 |
+
---
|
| 317 |
+
|
| 318 |
+
### 6. Set Context Mode
|
| 319 |
+
|
| 320 |
+
**Endpoint:** `POST /api/context/mode`
|
| 321 |
+
|
| 322 |
+
**Description:** Set the context retrieval mode for a session (fresh or relevant).
|
| 323 |
+
|
| 324 |
+
**Request Headers:**
|
| 325 |
+
```http
|
| 326 |
+
Content-Type: application/json
|
| 327 |
+
```
|
| 328 |
+
|
| 329 |
+
**Request Body:**
|
| 330 |
+
```json
|
| 331 |
+
{
|
| 332 |
+
"session_id": "session-123",
|
| 333 |
+
"mode": "relevant",
|
| 334 |
+
"user_id": "user-456"
|
| 335 |
+
}
|
| 336 |
+
```
|
| 337 |
+
|
| 338 |
+
**Request Fields:**
|
| 339 |
+
|
| 340 |
+
| Field | Type | Required | Description |
|
| 341 |
+
|-------|------|----------|-------------|
|
| 342 |
+
| `session_id` | string | ✅ Yes | Session identifier |
|
| 343 |
+
| `mode` | string | ✅ Yes | Context mode: `"fresh"` or `"relevant"` |
|
| 344 |
+
| `user_id` | string | ❌ No | User identifier (defaults to "anonymous") |
|
| 345 |
+
|
| 346 |
+
**Response (Success):**
|
| 347 |
+
```json
|
| 348 |
+
{
|
| 349 |
+
"success": true,
|
| 350 |
+
"session_id": "session-123",
|
| 351 |
+
"context_mode": "relevant",
|
| 352 |
+
"message": "Context mode set successfully"
|
| 353 |
+
}
|
| 354 |
+
```
|
| 355 |
+
|
| 356 |
+
**Response Fields:**
|
| 357 |
+
|
| 358 |
+
| Field | Type | Description |
|
| 359 |
+
|-------|------|-------------|
|
| 360 |
+
| `success` | boolean | Whether the request was successful |
|
| 361 |
+
| `session_id` | string | Session identifier |
|
| 362 |
+
| `context_mode` | string | The mode that was set |
|
| 363 |
+
| `message` | string | Success message |
|
| 364 |
+
|
| 365 |
+
**Status Codes:**
|
| 366 |
+
- `200 OK` - Context mode set successfully
|
| 367 |
+
- `400 Bad Request` - Invalid request (missing fields, invalid mode)
|
| 368 |
+
- `500 Internal Server Error` - Server error or failed to set mode
|
| 369 |
+
- `503 Service Unavailable` - Orchestrator not ready or context mode not available
|
| 370 |
+
|
| 371 |
+
**Error Response:**
|
| 372 |
+
```json
|
| 373 |
+
{
|
| 374 |
+
"success": false,
|
| 375 |
+
"error": "mode must be 'fresh' or 'relevant'"
|
| 376 |
+
}
|
| 377 |
+
```
|
| 378 |
+
|
| 379 |
+
**Usage Notes:**
|
| 380 |
+
|
| 381 |
+
- The context mode persists for the session until changed
|
| 382 |
+
- Setting `mode` to `"relevant"` enables relevance classification, which analyzes all previous interactions to include only relevant context
|
| 383 |
+
- Setting `mode` to `"fresh"` disables context retrieval, providing faster responses without user history
|
| 384 |
+
- The mode can also be set per-request via the `context_mode` parameter in `/api/chat`
|
| 385 |
+
|
| 386 |
+
---
|
| 387 |
+
|
| 388 |
## Code Examples
|
| 389 |
|
| 390 |
### Python
|
|
|
|
| 401 |
return response.json()
|
| 402 |
|
| 403 |
# Send chat message
|
| 404 |
+
def send_message(message, session_id=None, user_id=None, history=None, context_mode=None):
|
| 405 |
payload = {
|
| 406 |
"message": message,
|
| 407 |
"session_id": session_id,
|
| 408 |
"user_id": user_id or "anonymous",
|
| 409 |
"history": history or []
|
| 410 |
}
|
| 411 |
+
if context_mode:
|
| 412 |
+
payload["context_mode"] = context_mode
|
| 413 |
|
| 414 |
response = requests.post(
|
| 415 |
f"{BASE_URL}/api/chat",
|
|
|
|
| 439 |
print(f"Response: {result['message']}")
|
| 440 |
print(f"Reasoning: {result.get('reasoning', {})}")
|
| 441 |
|
| 442 |
+
# Set context mode to relevant for follow-up
|
| 443 |
+
import requests
|
| 444 |
+
requests.post(
|
| 445 |
+
f"{BASE_URL}/api/context/mode",
|
| 446 |
+
json={
|
| 447 |
+
"session_id": "my-session-123",
|
| 448 |
+
"mode": "relevant",
|
| 449 |
+
"user_id": "user-456"
|
| 450 |
+
}
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
# Continue conversation with relevant context
|
| 454 |
history = result['history']
|
| 455 |
result2 = send_message(
|
| 456 |
message="Can you explain neural networks?",
|
| 457 |
session_id="my-session-123",
|
| 458 |
user_id="user-456",
|
| 459 |
+
history=history,
|
| 460 |
+
context_mode="relevant"
|
| 461 |
)
|
| 462 |
print(f"Follow-up Response: {result2['message']}")
|
| 463 |
```
|
|
|
|
| 473 |
return await response.json();
|
| 474 |
}
|
| 475 |
|
| 476 |
+
// Get context mode for a session
|
| 477 |
+
async function getContextMode(sessionId) {
|
| 478 |
+
const response = await fetch(`${BASE_URL}/api/context/mode?session_id=${sessionId}`);
|
| 479 |
+
if (!response.ok) {
|
| 480 |
+
throw new Error(`API Error: ${response.status}`);
|
| 481 |
+
}
|
| 482 |
+
return await response.json();
|
| 483 |
+
}
|
| 484 |
+
|
| 485 |
+
// Set context mode for a session
|
| 486 |
+
async function setContextMode(sessionId, mode, userId = null) {
|
| 487 |
+
const payload = {
|
| 488 |
+
session_id: sessionId,
|
| 489 |
+
mode: mode
|
| 490 |
+
};
|
| 491 |
+
if (userId) {
|
| 492 |
+
payload.user_id = userId;
|
| 493 |
+
}
|
| 494 |
+
|
| 495 |
+
const response = await fetch(`${BASE_URL}/api/context/mode`, {
|
| 496 |
+
method: 'POST',
|
| 497 |
+
headers: {
|
| 498 |
+
'Content-Type': 'application/json'
|
| 499 |
+
},
|
| 500 |
+
body: JSON.stringify(payload)
|
| 501 |
+
});
|
| 502 |
+
|
| 503 |
+
if (!response.ok) {
|
| 504 |
+
const error = await response.json();
|
| 505 |
+
throw new Error(`API Error: ${response.status} - ${error.error || error.message}`);
|
| 506 |
+
}
|
| 507 |
+
|
| 508 |
+
return await response.json();
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
// Send chat message
|
| 512 |
+
async function sendMessage(message, sessionId = null, userId = null, history = [], contextMode = null) {
|
| 513 |
const payload = {
|
| 514 |
message: message,
|
| 515 |
session_id: sessionId,
|
| 516 |
user_id: userId || 'anonymous',
|
| 517 |
history: history
|
| 518 |
};
|
| 519 |
+
if (contextMode) {
|
| 520 |
+
payload.context_mode = contextMode;
|
| 521 |
+
}
|
| 522 |
|
| 523 |
const response = await fetch(`${BASE_URL}/api/chat`, {
|
| 524 |
method: 'POST',
|
|
|
|
| 554 |
console.log('Response:', result.message);
|
| 555 |
console.log('Reasoning:', result.reasoning);
|
| 556 |
|
| 557 |
+
// Continue conversation with relevant context
|
| 558 |
+
await setContextMode('my-session-123', 'relevant', 'user-456');
|
| 559 |
const result2 = await sendMessage(
|
| 560 |
'Can you explain neural networks?',
|
| 561 |
'my-session-123',
|
| 562 |
'user-456',
|
| 563 |
+
result.history,
|
| 564 |
+
'relevant'
|
| 565 |
);
|
| 566 |
console.log('Follow-up Response:', result2.message);
|
| 567 |
+
|
| 568 |
+
// Check current context mode
|
| 569 |
+
const modeInfo = await getContextMode('my-session-123');
|
| 570 |
+
console.log('Current context mode:', modeInfo.context_mode);
|
| 571 |
}
|
| 572 |
} catch (error) {
|
| 573 |
console.error('Error:', error);
|
|
|
|
| 583 |
# Check health
|
| 584 |
curl -X GET "https://jatinautonomouslabs-research-ai-assistant-api.hf.space/api/health"
|
| 585 |
|
| 586 |
+
# Get context mode
|
| 587 |
+
curl -X GET "https://jatinautonomouslabs-research-ai-assistant-api.hf.space/api/context/mode?session_id=my-session-123"
|
| 588 |
+
|
| 589 |
+
# Set context mode to relevant
|
| 590 |
+
curl -X POST "https://jatinautonomouslabs-research-ai-assistant-api.hf.space/api/context/mode" \
|
| 591 |
+
-H "Content-Type: application/json" \
|
| 592 |
+
-d '{
|
| 593 |
+
"session_id": "my-session-123",
|
| 594 |
+
"mode": "relevant",
|
| 595 |
+
"user_id": "user-456"
|
| 596 |
+
}'
|
| 597 |
+
|
| 598 |
# Send chat message
|
| 599 |
curl -X POST "https://jatinautonomouslabs-research-ai-assistant-api.hf.space/api/chat" \
|
| 600 |
-H "Content-Type: application/json" \
|
|
|
|
| 602 |
"message": "What is machine learning?",
|
| 603 |
"session_id": "my-session-123",
|
| 604 |
"user_id": "user-456",
|
| 605 |
+
"context_mode": "relevant",
|
| 606 |
"history": []
|
| 607 |
}'
|
| 608 |
|
|
|
|
| 632 |
return response.data;
|
| 633 |
}
|
| 634 |
|
| 635 |
+
// Get context mode
|
| 636 |
+
async function getContextMode(sessionId) {
|
| 637 |
+
const response = await axios.get(`${BASE_URL}/api/context/mode`, {
|
| 638 |
+
params: { session_id: sessionId }
|
| 639 |
+
});
|
| 640 |
+
return response.data;
|
| 641 |
+
}
|
| 642 |
+
|
| 643 |
+
// Set context mode
|
| 644 |
+
async function setContextMode(sessionId, mode, userId = null) {
|
| 645 |
+
const payload = {
|
| 646 |
+
session_id: sessionId,
|
| 647 |
+
mode: mode
|
| 648 |
+
};
|
| 649 |
+
if (userId) payload.user_id = userId;
|
| 650 |
+
|
| 651 |
+
const response = await axios.post(`${BASE_URL}/api/context/mode`, payload);
|
| 652 |
+
return response.data;
|
| 653 |
+
}
|
| 654 |
+
|
| 655 |
// Send chat message
|
| 656 |
+
async function sendMessage(message, sessionId = null, userId = null, history = [], contextMode = null) {
|
| 657 |
try {
|
| 658 |
+
const payload = {
|
| 659 |
message: message,
|
| 660 |
session_id: sessionId,
|
| 661 |
user_id: userId || 'anonymous',
|
| 662 |
history: history
|
| 663 |
+
};
|
| 664 |
+
if (contextMode) payload.context_mode = contextMode;
|
| 665 |
+
|
| 666 |
+
const response = await axios.post(`${BASE_URL}/api/chat`, payload, {
|
| 667 |
headers: {
|
| 668 |
'Content-Type': 'application/json'
|
| 669 |
}
|
|
|
|
| 685 |
console.log('API Status:', health);
|
| 686 |
|
| 687 |
if (health.orchestrator_ready) {
|
| 688 |
+
// Set context mode to relevant
|
| 689 |
+
await setContextMode('my-session-123', 'relevant', 'user-456');
|
| 690 |
+
|
| 691 |
const result = await sendMessage(
|
| 692 |
'What is machine learning?',
|
| 693 |
'my-session-123',
|
| 694 |
+
'user-456',
|
| 695 |
+
[],
|
| 696 |
+
'relevant'
|
| 697 |
);
|
| 698 |
|
| 699 |
console.log('Response:', result.message);
|
| 700 |
+
|
| 701 |
+
// Check current mode
|
| 702 |
+
const modeInfo = await getContextMode('my-session-123');
|
| 703 |
+
console.log('Context mode:', modeInfo.context_mode);
|
| 704 |
}
|
| 705 |
} catch (error) {
|
| 706 |
console.error('Error:', error.message);
|
flask_api_standalone.py
CHANGED
|
@@ -104,7 +104,9 @@ def root():
|
|
| 104 |
'endpoints': {
|
| 105 |
'health': 'GET /api/health',
|
| 106 |
'chat': 'POST /api/chat',
|
| 107 |
-
'initialize': 'POST /api/initialize'
|
|
|
|
|
|
|
| 108 |
}
|
| 109 |
})
|
| 110 |
|
|
@@ -177,6 +179,7 @@ def chat():
|
|
| 177 |
history = data.get('history', [])
|
| 178 |
session_id = data.get('session_id')
|
| 179 |
user_id = data.get('user_id', 'anonymous')
|
|
|
|
| 180 |
|
| 181 |
logger.info(f"Chat request - User: {user_id}, Session: {session_id}")
|
| 182 |
logger.info(f"Message length: {len(message)} chars, preview: {message[:100]}...")
|
|
@@ -192,6 +195,14 @@ def chat():
|
|
| 192 |
# Set user_id for session tracking
|
| 193 |
if session_id:
|
| 194 |
orchestrator.set_user_id(session_id, user_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
|
| 196 |
# Run async process_request in event loop
|
| 197 |
loop = asyncio.new_event_loop()
|
|
@@ -253,6 +264,150 @@ def initialize():
|
|
| 253 |
'message': 'Initialization failed. Check logs for details.'
|
| 254 |
}), 500
|
| 255 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
# Initialize on startup
|
| 257 |
if __name__ == '__main__':
|
| 258 |
logger.info("=" * 60)
|
|
@@ -270,6 +425,8 @@ if __name__ == '__main__':
|
|
| 270 |
logger.info(" GET /api/health")
|
| 271 |
logger.info(" POST /api/chat")
|
| 272 |
logger.info(" POST /api/initialize")
|
|
|
|
|
|
|
| 273 |
logger.info("=" * 60)
|
| 274 |
|
| 275 |
app.run(
|
|
|
|
| 104 |
'endpoints': {
|
| 105 |
'health': 'GET /api/health',
|
| 106 |
'chat': 'POST /api/chat',
|
| 107 |
+
'initialize': 'POST /api/initialize',
|
| 108 |
+
'context_mode_get': 'GET /api/context/mode',
|
| 109 |
+
'context_mode_set': 'POST /api/context/mode'
|
| 110 |
}
|
| 111 |
})
|
| 112 |
|
|
|
|
| 179 |
history = data.get('history', [])
|
| 180 |
session_id = data.get('session_id')
|
| 181 |
user_id = data.get('user_id', 'anonymous')
|
| 182 |
+
context_mode = data.get('context_mode') # Optional: 'fresh' or 'relevant'
|
| 183 |
|
| 184 |
logger.info(f"Chat request - User: {user_id}, Session: {session_id}")
|
| 185 |
logger.info(f"Message length: {len(message)} chars, preview: {message[:100]}...")
|
|
|
|
| 195 |
# Set user_id for session tracking
|
| 196 |
if session_id:
|
| 197 |
orchestrator.set_user_id(session_id, user_id)
|
| 198 |
+
|
| 199 |
+
# Set context mode if provided
|
| 200 |
+
if context_mode and hasattr(orchestrator.context_manager, 'set_context_mode'):
|
| 201 |
+
if context_mode in ['fresh', 'relevant']:
|
| 202 |
+
orchestrator.context_manager.set_context_mode(session_id, context_mode, user_id)
|
| 203 |
+
logger.info(f"Context mode set to '{context_mode}' for session {session_id}")
|
| 204 |
+
else:
|
| 205 |
+
logger.warning(f"Invalid context_mode '{context_mode}', ignoring. Use 'fresh' or 'relevant'")
|
| 206 |
|
| 207 |
# Run async process_request in event loop
|
| 208 |
loop = asyncio.new_event_loop()
|
|
|
|
| 264 |
'message': 'Initialization failed. Check logs for details.'
|
| 265 |
}), 500
|
| 266 |
|
| 267 |
+
# Context mode management endpoints
|
| 268 |
+
@app.route('/api/context/mode', methods=['GET'])
|
| 269 |
+
def get_context_mode():
|
| 270 |
+
"""
|
| 271 |
+
Get current context mode for a session
|
| 272 |
+
|
| 273 |
+
GET /api/context/mode?session_id=session-123
|
| 274 |
+
|
| 275 |
+
Returns:
|
| 276 |
+
{
|
| 277 |
+
"success": true,
|
| 278 |
+
"session_id": "session-123",
|
| 279 |
+
"context_mode": "fresh" | "relevant",
|
| 280 |
+
"description": {
|
| 281 |
+
"fresh": "No user context included - starts fresh each time",
|
| 282 |
+
"relevant": "Only relevant user context included based on relevance classification"
|
| 283 |
+
}
|
| 284 |
+
}
|
| 285 |
+
"""
|
| 286 |
+
try:
|
| 287 |
+
session_id = request.args.get('session_id')
|
| 288 |
+
|
| 289 |
+
if not session_id:
|
| 290 |
+
return jsonify({
|
| 291 |
+
'success': False,
|
| 292 |
+
'error': 'session_id query parameter is required'
|
| 293 |
+
}), 400
|
| 294 |
+
|
| 295 |
+
if not orchestrator_available or orchestrator is None:
|
| 296 |
+
return jsonify({
|
| 297 |
+
'success': False,
|
| 298 |
+
'error': 'Orchestrator not ready'
|
| 299 |
+
}), 503
|
| 300 |
+
|
| 301 |
+
if not hasattr(orchestrator.context_manager, 'get_context_mode'):
|
| 302 |
+
return jsonify({
|
| 303 |
+
'success': False,
|
| 304 |
+
'error': 'Context mode not available'
|
| 305 |
+
}), 503
|
| 306 |
+
|
| 307 |
+
context_mode = orchestrator.context_manager.get_context_mode(session_id)
|
| 308 |
+
|
| 309 |
+
return jsonify({
|
| 310 |
+
'success': True,
|
| 311 |
+
'session_id': session_id,
|
| 312 |
+
'context_mode': context_mode,
|
| 313 |
+
'description': {
|
| 314 |
+
'fresh': 'No user context included - starts fresh each time',
|
| 315 |
+
'relevant': 'Only relevant user context included based on relevance classification'
|
| 316 |
+
}
|
| 317 |
+
})
|
| 318 |
+
|
| 319 |
+
except Exception as e:
|
| 320 |
+
logger.error(f"Get context mode error: {e}", exc_info=True)
|
| 321 |
+
return jsonify({
|
| 322 |
+
'success': False,
|
| 323 |
+
'error': str(e)
|
| 324 |
+
}), 500
|
| 325 |
+
|
| 326 |
+
@app.route('/api/context/mode', methods=['POST'])
|
| 327 |
+
def set_context_mode():
|
| 328 |
+
"""
|
| 329 |
+
Set context mode for a session
|
| 330 |
+
|
| 331 |
+
POST /api/context/mode
|
| 332 |
+
{
|
| 333 |
+
"session_id": "session-123",
|
| 334 |
+
"mode": "fresh" | "relevant",
|
| 335 |
+
"user_id": "user-456" (optional)
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
Returns:
|
| 339 |
+
{
|
| 340 |
+
"success": true,
|
| 341 |
+
"session_id": "session-123",
|
| 342 |
+
"context_mode": "fresh" | "relevant",
|
| 343 |
+
"message": "Context mode set successfully"
|
| 344 |
+
}
|
| 345 |
+
"""
|
| 346 |
+
try:
|
| 347 |
+
data = request.get_json()
|
| 348 |
+
|
| 349 |
+
if not data:
|
| 350 |
+
return jsonify({
|
| 351 |
+
'success': False,
|
| 352 |
+
'error': 'Request body is required'
|
| 353 |
+
}), 400
|
| 354 |
+
|
| 355 |
+
session_id = data.get('session_id')
|
| 356 |
+
mode = data.get('mode')
|
| 357 |
+
user_id = data.get('user_id', 'anonymous')
|
| 358 |
+
|
| 359 |
+
if not session_id:
|
| 360 |
+
return jsonify({
|
| 361 |
+
'success': False,
|
| 362 |
+
'error': 'session_id is required'
|
| 363 |
+
}), 400
|
| 364 |
+
|
| 365 |
+
if not mode:
|
| 366 |
+
return jsonify({
|
| 367 |
+
'success': False,
|
| 368 |
+
'error': 'mode is required'
|
| 369 |
+
}), 400
|
| 370 |
+
|
| 371 |
+
if mode not in ['fresh', 'relevant']:
|
| 372 |
+
return jsonify({
|
| 373 |
+
'success': False,
|
| 374 |
+
'error': "mode must be 'fresh' or 'relevant'"
|
| 375 |
+
}), 400
|
| 376 |
+
|
| 377 |
+
if not orchestrator_available or orchestrator is None:
|
| 378 |
+
return jsonify({
|
| 379 |
+
'success': False,
|
| 380 |
+
'error': 'Orchestrator not ready'
|
| 381 |
+
}), 503
|
| 382 |
+
|
| 383 |
+
if not hasattr(orchestrator.context_manager, 'set_context_mode'):
|
| 384 |
+
return jsonify({
|
| 385 |
+
'success': False,
|
| 386 |
+
'error': 'Context mode not available'
|
| 387 |
+
}), 503
|
| 388 |
+
|
| 389 |
+
success = orchestrator.context_manager.set_context_mode(session_id, mode, user_id)
|
| 390 |
+
|
| 391 |
+
if success:
|
| 392 |
+
return jsonify({
|
| 393 |
+
'success': True,
|
| 394 |
+
'session_id': session_id,
|
| 395 |
+
'context_mode': mode,
|
| 396 |
+
'message': 'Context mode set successfully'
|
| 397 |
+
})
|
| 398 |
+
else:
|
| 399 |
+
return jsonify({
|
| 400 |
+
'success': False,
|
| 401 |
+
'error': 'Failed to set context mode'
|
| 402 |
+
}), 500
|
| 403 |
+
|
| 404 |
+
except Exception as e:
|
| 405 |
+
logger.error(f"Set context mode error: {e}", exc_info=True)
|
| 406 |
+
return jsonify({
|
| 407 |
+
'success': False,
|
| 408 |
+
'error': str(e)
|
| 409 |
+
}), 500
|
| 410 |
+
|
| 411 |
# Initialize on startup
|
| 412 |
if __name__ == '__main__':
|
| 413 |
logger.info("=" * 60)
|
|
|
|
| 425 |
logger.info(" GET /api/health")
|
| 426 |
logger.info(" POST /api/chat")
|
| 427 |
logger.info(" POST /api/initialize")
|
| 428 |
+
logger.info(" GET /api/context/mode")
|
| 429 |
+
logger.info(" POST /api/context/mode")
|
| 430 |
logger.info("=" * 60)
|
| 431 |
|
| 432 |
app.run(
|