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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
# CMW Platform Agent API Endpoints Documentation

**Date:** 2025-10-10  
**Version:** 1.0  
**Status:** Production Ready

## Overview

The CMW Platform Agent now exposes two REST API endpoints that allow external applications to interact with the agent programmatically. These endpoints support both single-turn and multi-turn conversations with session persistence.

## Base URL

```
http://localhost:7860
```

## Authentication

No authentication is required for these endpoints. All requests are processed with session isolation.

## Endpoints

### 1. `/ask` - Final Answer Endpoint

Returns the complete assistant response after processing is finished.

**Method:** `POST`  
**Path:** `/gradio_api/call/ask`  
**Content-Type:** `application/json`

#### Request Format

```json
{
  "data": ["Your question here", "username", "password", "base_url"],
  "session_hash": "optional-session-id"
}
```

#### Parameters

- `data[0]` (string, required): The user's question
- `data[1]` (string, optional): Username for Comindware Platform authentication
- `data[2]` (string, optional): Password for Comindware Platform authentication  
- `data[3]` (string, optional): Base URL of the Comindware Platform (e.g., "https://your-platform.com")
- `session_hash` (string, optional): Session identifier for multi-turn conversations

#### Response Format

**Success Response:**
```json
{
  "event_id": "unique-event-id"
}
```

**Final Result (via GET):**
```json
{
  "data": ["Complete assistant response"]
}
```

#### Example Usage

**cURL:**
```bash
# Submit question with authentication
curl -X POST http://localhost:7860/gradio_api/call/ask \
  -H "Content-Type: application/json" \
  -d '{"data": ["Hello, who are you?", "myuser", "mypass", "https://my-platform.com"]}'

# Get result (replace EVENT_ID with actual ID)
curl -N http://localhost:7860/gradio_api/call/ask/EVENT_ID
```

**Python Client:**
```python
from gradio_client import Client

client = Client("http://localhost:7860/")
result = client.predict(
    question="Hello, who are you?",
    username="myuser",
    password="mypass", 
    base_url="https://my-platform.com",
    api_name="/ask"
)
print(result)
```

**Using Environment Variables:**
```python
import os
from dotenv import load_dotenv
from gradio_client import Client

# Load from root .env file
load_dotenv()

client = Client("http://localhost:7860/")
result = client.predict(
    question="Hello, who are you?",
    username=os.getenv("CMW_LOGIN"),
    password=os.getenv("CMW_PASSWORD"), 
    base_url=os.getenv("CMW_BASE_URL"),
    api_name="/ask"
)
print(result)
```

### 2. `/ask_stream` - Streaming Endpoint

Returns incremental chunks of the assistant response as it's being generated.

**Method:** `POST`  
**Path:** `/gradio_api/call/ask_stream`  
**Content-Type:** `application/json`

#### Request Format

```json
{
  "data": ["Your question here", "username", "password", "base_url"],
  "session_hash": "optional-session-id"
}
```

#### Parameters

- `data[0]` (string, required): The user's question
- `data[1]` (string, optional): Username for Comindware Platform authentication
- `data[2]` (string, optional): Password for Comindware Platform authentication  
- `data[3]` (string, optional): Base URL of the Comindware Platform (e.g., "https://your-platform.com")
- `session_hash` (string, optional): Session identifier for multi-turn conversations

#### Response Format

**Success Response:**
```json
{
  "event_id": "unique-event-id"
}
```

**Streaming Results (via GET):**
```
event: generating
data: ["Hello"]

event: generating
data: ["Hello, w"]

event: generating
data: ["Hello, wo"]

event: generating
data: ["Hello, wor"]

event: generating
data: ["Hello, worl"]

event: generating
data: ["Hello, world!"]

event: complete
data: ["Hello, world!"]
```

#### Example Usage

**cURL:**
```bash
# Submit question
curl -X POST http://localhost:7860/call/ask_stream \
  -H "Content-Type: application/json" \
  -d '{"data": ["Stream this please"]}'

# Get streaming result (replace EVENT_ID with actual ID)
curl -N http://localhost:7860/call/ask_stream/EVENT_ID
```

**Python Client:**
```python
from gradio_client import Client

client = Client("http://localhost:7860/")
job = client.submit(
    question="Stream this please",
    api_name="/ask_stream"
)

# Iterate through streaming chunks
for chunk in job:
    print(f"Chunk: {chunk}")
```

## Session Management

### Multi-turn Conversations

Both endpoints support session persistence using the `session_hash` parameter:

```python
# First message in a session
client = Client("http://localhost:7860/")
result1 = client.predict(
    question="What is 2+2?",
    api_name="/ask",
    session_hash="my-session-123"
)

# Follow-up message in the same session
result2 = client.predict(
    question="What about 3+3?",
    api_name="/ask", 
    session_hash="my-session-123"
)
```

### Session Behavior

- **With session_hash:** Messages are part of the same conversation context
- **Without session_hash:** Each request is treated as a new conversation
- **Session isolation:** Different session hashes maintain separate conversation histories

## Error Handling

### Common Error Responses

**Connection Error:**
```json
{
  "error": "Connection refused"
}
```

**Timeout Error:**
```json
{
  "error": "Request timeout"
}
```

**Invalid Request:**
```json
{
  "error": "Invalid request format"
}
```

### Error Event (Streaming)

For streaming endpoints, errors are returned as events:

```
event: error
data: ["Error message here"]
```

## Rate Limiting

- **Concurrent requests:** Limited by Gradio's queue system (default: 1)
- **Rate limits:** No explicit rate limiting implemented
- **Queue timeout:** 30 seconds per request

## Response Times

- **Final endpoint (`/ask`):** 2-10 seconds depending on complexity
- **Streaming endpoint (`/ask_stream`):** First chunk within 1-2 seconds, then incremental updates

## Best Practices

### 1. Use Appropriate Endpoint

- **Use `/ask`** for simple queries where you need the complete response
- **Use `/ask_stream`** for better user experience with real-time feedback

### 2. Session Management

- **Always use session_hash** for multi-turn conversations
- **Generate unique session IDs** for different users/conversations
- **Reuse session_hash** within the same conversation thread

### 3. Error Handling

```python
try:
    result = client.predict(question="Hello", api_name="/ask")
    print(result)
except Exception as e:
    print(f"Error: {e}")
    # Handle error appropriately
```

### 4. Streaming Best Practices

```python
# For streaming, always iterate through chunks
job = client.submit(question="Stream this", api_name="/ask_stream")
for chunk in job:
    # Process each chunk
    print(f"Received: {chunk}")
```

## Integration Examples

### JavaScript/Node.js

```javascript
const fetch = require('node-fetch');

// Final endpoint
async function askQuestion(question) {
    const response = await fetch('http://localhost:7860/call/ask', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ data: [question] })
    });
    
    const { event_id } = await response.json();
    
    // Get result
    const resultResponse = await fetch(`http://localhost:7860/call/ask/${event_id}`);
    const result = await resultResponse.json();
    
    return result.data[0];
}
```

### Python with requests

```python
import requests
import json

def ask_question(question, session_hash=None):
    # Submit question
    payload = {"data": [question]}
    if session_hash:
        payload["session_hash"] = session_hash
    
    response = requests.post(
        "http://localhost:7860/call/ask",
        headers={"Content-Type": "application/json"},
        json=payload
    )
    
    event_id = response.json()["event_id"]
    
    # Get result
    result_response = requests.get(f"http://localhost:7860/call/ask/{event_id}")
    return result_response.json()["data"][0]
```

## Testing

### Test Script

A test script is available at `agent_ng/_tests/api_test.py`:

```bash
# Run tests
python agent_ng/_tests/api_test.py

# With custom URL
BASE_URL=http://your-server:7860/ python agent_ng/_tests/api_test.py

# With session hash
SESSION_HASH=test-session-123 python agent_ng/_tests/api_test.py
```

### Manual Testing

1. **Start the agent:**
   ```bash
   python -m agent_ng.app_ng_modular
   ```

2. **Test final endpoint:**
   ```bash
   curl -X POST http://localhost:7860/call/ask \
     -H "Content-Type: application/json" \
     -d '{"data": ["Hello"]}'
   ```

3. **Test streaming endpoint:**
   ```bash
   curl -X POST http://localhost:7860/call/ask_stream \
     -H "Content-Type: application/json" \
     -d '{"data": ["Stream this"]}'
   ```

## Troubleshooting

### Common Issues

1. **"Application is initializing..."**
   - Wait for the agent to fully initialize
   - Check logs for initialization errors

2. **Connection refused**
   - Ensure the agent is running on the correct port
   - Check firewall settings

3. **Timeout errors**
   - Increase timeout values
   - Check server performance

4. **Empty responses**
   - Verify the question is not empty
   - Check agent configuration

### Debug Mode

Enable debug logging by setting environment variables:

```bash
export GRADIO_DEBUG=1
export LOG_LEVEL=DEBUG
python -m agent_ng.app_ng_modular
```

## Changelog

### Version 1.0 (2025-10-10)
- Initial release of API endpoints
- Added `/ask` final answer endpoint
- Added `/ask_stream` streaming endpoint
- Implemented session management
- Added comprehensive documentation

## Support

For issues or questions regarding the API endpoints:

1. Check this documentation
2. Review the test script examples
3. Check the agent logs for error details
4. Verify the agent is running and accessible

---

**Note:** This documentation covers the API endpoints as implemented in the CMW Platform Agent. For Gradio-specific API details, refer to the [official Gradio documentation](https://www.gradio.app/guides/querying-gradio-apps-with-curl).