AI Agent — Unified Intelligent Assistant
Orchestrator thông minh — điều phối 9+ AI services (ASR, OCR, LLM, TTS, CodeFinder, Face Recognition, Patient Simulator). Tự động intent routing, multi-LLM reasoning, WebSocket streaming.
Tính năng nổi bật
Intent Routing
Tự động phân loại request và chọn sub-service phù hợp
Multi-LLM
Gemma4, Qwen3 14B, Qwen2.5 7B — tự động chọn model
SSE Streaming
Response streaming real-time cho chat và code
WebSocket
Chat duplex streaming với auth tích hợp
OpenAI Compatible
Drop-in /v1/chat/completions + /v1/models
Pipelines
Audio→Diagnosis, Image→Codes, Audio→Consult
Shell Exec
Chạy lệnh shell tự nhiên qua NL → command
Session Mgmt
Context-aware, multi-turn conversation
GPU Monitor
Theo dõi GPU status real-time
Authentication
Tất cả endpoints (trừ /, /health, /capabilities) yêu cầu API token trong header:
Token scope: ai_agent — được cấu hình trong shared/api_auth_middleware.py.
WebSocket auth: Query param ?token=xxx hoặc JSON frame đầu tiên: {"type":"auth","token":"xxx"}.
Intent System
AI Agent tự động phân loại intent từ message người dùng. Có thể force intent qua parameter force_intent.
chat
Hội thoại chung
transcribe
ASR → Medical Transcribe
ocr
OCR → DeepSeek OCR
search_code
Search → CodeFinder
translate
Dịch thuật → LLM
summarize
Tóm tắt → LLM
analyze
Phân tích → LLM
tts
Text → Speech
code
Sinh code → Qwen3
debug
Debug code → Qwen3
patient_sim
Bệnh nhân ảo
face_recognize
Nhận dạng khuôn mặt
shell
Shell command
auto
Tự động detect
Danh mục Endpoints
| Method | Endpoint | Tags | Description |
|---|---|---|---|
| GET | / | Info | Service info |
| GET | /health | Info | Health check |
| GET | /capabilities | Info | Danh sách sub-services |
| GET | /status | Info | Status tất cả sub-services |
| POST | /run | Agent | Run agent (auto-intent + streaming) |
| POST | /run/multipart | Agent | Run with audio+image upload |
| POST | /chat | Chat | Chat force-intent |
| POST | /chat/raw | Agent | Direct LLM with messages array |
| POST | /v1/chat/completions | OpenAI | OpenAI-compatible chat |
| GET | /v1/models | OpenAI | List available LLM models |
| POST | /transcribe | ASR | Speech-to-text |
| POST | /ocr | OCR | Image-to-text |
| POST | /face | Face | Face recognition |
| POST | /analyze | Analysis | Phân tích văn bản |
| POST | /translate | Translation | Dịch thuật |
| POST | /summarize | Analysis | Tóm tắt văn bản |
| POST | /search | Search | Medical code search |
| POST | /tts | TTS | Text-to-speech |
| POST | /patient | Medical Edu | Patient simulator |
| POST | /code | Code | Code generation (Qwen3) |
| POST | /debug | Code | Code debugging (Qwen3) |
| POST | /shell | Shell | Execute shell command |
| GET | /gpu | Monitoring | GPU status |
| GET | /sessions | Sessions | List sessions |
| DELETE | /sessions/{id} | Sessions | Xóa session |
| GET | /sessions/{id} | Sessions | Get session detail |
| WS | /ws/chat | Agent | WebSocket streaming chat |
| POST | /pipeline/audio-to-diagnosis | Pipeline | Audio → diagnosis |
| POST | /pipeline/audio-full-consult | Pipeline | Audio → consult (with TTS) |
| POST | /pipeline/image-to-codes | Pipeline | Image → medical codes |
| POST | /pipeline/image-full-analysis | Pipeline | Image → full analysis |
Info Endpoints
/InfoThông tin service: tên, version, port, status, link docs.
Response:
/healthInfoHealth check. Returns 503 nếu agent chưa ready.
/capabilitiesInfoDanh sách tất cả sub-services: id, name, description, tags, GPU.
/statusInfoAuthKiểm tra health status của tất cả sub-services (ASR, OCR, 3x LLM, TTS, CodeFinder, Face Recog, Patient Sim).
Agent Endpoints
/runAgentAuthEndpoint chính của AI Agent. Tự động detect intent, chọn LLM, điều phối sub-services.
Request Body (JSON):
| Param | Type | Default | Description |
|---|---|---|---|
message | string | "" | Nội dung message |
session_id | string|null | null | Session ID cho multi-turn |
language | string | "vi" | Ngôn ngữ (vi/en) |
force_intent | string|null | null | Force intent (chat/transcribe/ocr/...) |
force_llm | string|null | null | Force LLM (gemma4_service/qwen3_service) |
stream | bool | false | SSE streaming response |
Streaming (SSE): Khi stream=true, response là SSE stream. Mỗi chunk là text fragment. Kết thúc với data: [DONE].
cURL:
curl -X POST https://pnt.badt.vn/ai-agent/run \
-H "Authorization: Bearer $AI_AGENT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"message":"tóm tắt bệnh án: sốt 39°C, ho khan 5 ngày","language":"vi"}'
Response:
/run/multipartAgentAuthGiống /run nhưng dùng multipart/form-data để upload audio/image.
Form fields: message, session_id, language, force_intent + file fields audio (WAV/MP3), image (JPG/PNG).
/chat/rawAgentAuthDirect LLM call với messages array. Dùng cho PHP agent loop tool-calling.
Request Body:
| Param | Type | Default | Description |
|---|---|---|---|
messages | array | Array of {role, content} objects | |
system | string|null | null | System prompt override |
force_llm | string|null | null | gemma4_service / qwen3_service / qwen_service |
max_tokens | int | 2048 | Max tokens |
temperature | float | 0.3 | Sampling temp |
cURL:
curl -X POST https://pnt.badt.vn/ai-agent/chat/raw \
-H "Authorization: Bearer $AI_AGENT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"messages":[{"role":"user","content":"Xin chào"}],"force_llm":"gemma4_service"}'
Chat & OpenAI-Compatible Endpoints
/chatChatAuthChat với force_intent="chat". Hỗ trợ SSE streaming.
Request Body: message, session_id, language, stream, max_tokens, temperature.
/v1/chat/completionsOpenAIAuthOpenAI-compatible chat completion. Drop-in cho bất kỳ app nào dùng openai SDK.
Request Body:
| Param | Type | Default | Description |
|---|---|---|---|
model | string|null | null | gemma4_service / qwen3_service / qwen_service (auto nếu null) |
messages | array | Array of {role, content} objects | |
temperature | float | 0.7 | Sampling temp |
max_tokens | int | 2048 | Max tokens |
stream | bool | false | Streaming (reserved) |
system | string|null | null | System prompt convenience field |
cURL:
curl -X POST https://pnt.badt.vn/ai-agent/v1/chat/completions \
-H "Authorization: Bearer $AI_AGENT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"model":"gemma4_service","messages":[{"role":"user","content":"Hello"}],"temperature":0.7}'
Response:
/v1/modelsOpenAIAuthList available LLM models (gemma4_service, qwen3_service, qwen_service).
ASR & OCR & Face Endpoints
/transcribeASRAuthSpeech-to-text. Upload file audio, nhận transcription.
multipart/form-data:
| Field | Type | Default | Description |
|---|---|---|---|
file | file | Audio file (WAV/MP3/OGG) | |
language | string | "vi" | Ngôn ngữ |
analyze | bool | false | Phân tích nội dung sau ASR |
curl -X POST https://pnt.badt.vn/ai-agent/transcribe \
-H "Authorization: Bearer $AI_AGENT_TOKEN" \
-F "file=@recording.wav" -F "language=vi"
/ocrOCRAuthImage-to-text. Upload ảnh, nhận văn bản trích xuất.
Fields: file (image), analyze (bool), search (bool → tìm mã y tế).
/faceFaceAuthFace recognition. Upload ảnh khuôn mặt, nhận kết quả nhận dạng.
Analysis, Translation & Search Endpoints
/analyzeAnalysisAuthPhân tích văn bản với LLM. Force intent "analyze".
Request: message, session_id, language.
/translateTranslationAuthDịch thuật với LLM.
Request Body:
| Param | Type | Default | Description |
|---|---|---|---|
text | string | Văn bản cần dịch | |
source_lang | string | "auto" | Ngôn ngữ nguồn |
target_lang | string | "vi" | Ngôn ngữ đích |
session_id | string|null | null | Session ID |
curl -X POST https://pnt.badt.vn/ai-agent/translate \
-H "Authorization: Bearer $AI_AGENT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"text":"Hello doctor","source_lang":"en","target_lang":"vi"}'
Response:
/summarizeAnalysisAuthTóm tắt văn bản với LLM. Force intent "summarize".
Request: text, max_tokens, session_id.
/searchSearchAuthMedical code search thông qua CodeFinder adapter.
Request Body:
| Param | Type | Default | Description |
|---|---|---|---|
query | string | Từ khóa tìm kiếm | |
code_types | array|null | null | ["ICD10","ICPC2","CPT","SERVICE","PROCEDURE"] |
top_k | int | 10 | Số kết quả |
hybrid | bool | true | Hybrid search |
curl -X POST https://pnt.badt.vn/ai-agent/search \
-H "Authorization: Bearer $AI_AGENT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"query":"tăng huyết áp","code_types":["ICD10"],"top_k":5}'
TTS & Medical Endpoints
/ttsTTSAuthText-to-speech. Chuyển văn bản thành giọng nói.
Request: text, language ("vi"/"en"), speed (1.0).
/patientMedical EduAuthTương tác với bệnh nhân ảo (Patient Simulator).
Request: message, patient_id, session_id.
Code & Shell Endpoints
/codeCodeAuthCode generation. Tự động route sang Qwen3 14B cho code quality tốt nhất. Hỗ trợ SSE streaming.
Request: message, session_id, language, stream.
curl -X POST https://pnt.badt.vn/ai-agent/code \
-H "Authorization: Bearer $AI_AGENT_TOKEN" \
-H "Content-Type: application/json" \
-d '{"message":"Viết Python Flask REST API cho CRUD bệnh nhân","stream":false}'
/debugCodeAuthCode debugging. Paste code + error message → Qwen3 phân tích và sửa lỗi. Hỗ trợ SSE streaming.
/shellShellAuthExecute shell command trên server.
Request Body:
| Param | Type | Default | Description |
|---|---|---|---|
command | string | Raw command hoặc NL description (VD: "hiển thị 20 dòng cuối log") | |
workdir | string|null | null | Working directory |
timeout | int | 60 | Timeout seconds |
Note: Dangerous commands (rm -rf /, mkfs, fork-bomb) bị block. Feature có thể tắt qua config SHELL_EXEC_ENABLED.
Monitoring & Session Endpoints
/gpuMonitoringAuthGPU status real-time: temperature, utilization, memory usage cho tất cả GPU (RTX 3060, 3070, 5060 Ti).
/sessionsSessionsAuthList tất cả active sessions.
/sessions/{session_id}SessionsAuthGet session detail: messages history với role + content + timestamp.
/sessions/{session_id}SessionsAuthXóa session. Returns 404 nếu không tìm thấy.
WebSocket Endpoint
/ws/chat?token=xxxAgentWebSocket streaming chat với auth tích hợp.
Auth:
- Query param:
/ws/chat?token=AI_AGENT_TOKEN - Hoặc JSON frame đầu tiên:
{"type":"auth","token":"xxx"}
Flow:
- Client gửi auth → server trả
{"type":"auth_ok"} - Client gửi JSON:
{"message":"...","session_id":"...","language":"vi","force_intent":"...","force_llm":"..."} - Server stream text fragments, chunk đầu là metadata
{"intent":"...","model":"..."} - Kết thúc:
[DONE]
JavaScript example:
const ws = new WebSocket("wss://pnt.badt.vn/ai-agent/ws/chat?token=" + token);
ws.onmessage = (e) => {
if (e.data === "[DONE]") { ws.close(); return; }
// Parse JSON or plain text
try { const meta = JSON.parse(e.data); console.log("Meta:", meta); }
catch { console.log("Chunk:", e.data); }
};
ws.send(JSON.stringify({message:"Xin chào",language:"vi"}));
Pipeline Endpoints
Pipeline kết hợp nhiều service trong một request.
/pipeline/audio-to-diagnosisPipelineAuthAudio → Diagnosis: Nhận audio đầu vào → ASR transcription → LLM phân tích triệu chứng. multipart/form-data với file + language.
/pipeline/audio-full-consultPipelineAuthAudio → Consult + TTS: ASR → LLM tư vấn → TTS đọc lại kết quả. Trả về cả text + audio_base64.
/pipeline/image-to-codesPipelineAuthImage → Medical Codes: OCR trích xuất text → LLM tìm mã ICD10/ICPC2.
/pipeline/image-full-analysisPipelineAuthImage → Full Analysis: OCR → LLM phân tích chi tiết nội dung ảnh.
Thông số kỹ thuật
Error Codes
| HTTP Status | Meaning | Common Causes |
|---|---|---|
| 200 | Success | Request processed successfully |
| 401 | Unauthorized | Missing/invalid API token |
| 403 | Forbidden | Shell exec disabled or dangerous command blocked |
| 404 | Not Found | Session ID không tồn tại |
| 502 | Bad Gateway | Sub-service LLM timeout hoặc lỗi |
| 503 | Service Unavailable | Agent chưa ready |