Smart Consultation Integration Guide & API Reference
This page is the authoritative reference overview for Pet Smart Consultation. It summarizes the complete state machine, step-by-step API catalog, cross-step context passing, round control guidelines, and shared SSE protocol. For detailed schemas, request bodies, and code snippets, see the individual endpoint pages in the sidebar.
Main Workflow & Timing Sequence
Smart Consultation is a state-machine driven interactive loop across multiple stages:
Optional: GET /ai-doc/pre-question (retrieve preset guidance questions)
↓
POST /session-records/sessions (create session, fixed module_type=1)
↓
┌─ Round 1 Q&A ────────────────────────────────────────┐
│ 1. POST /ai-doc/keywords │
│ ↓ │
│ 2. POST /ai-doc/reason-info (SSE, wait for done) │
│ ↓ │
│ 3. POST /ai-doc/analysis │
│ ↓ │
│ 4. POST /ai-doc/related-question │
│ ↓ │
│ 5. Save User Answer: POST /session-records/messages │
└──────────────────────────────────────────────────────┘
↓ Advance directly to Round 2
┌─ Round 2 Q&A ── Same five steps ─────────────────────┐
└──────────────────────────────────────────────────────┘
↓ Advance directly to Round 3
┌─ Round 3 Q&A ── Same five steps ─────────────────────┐
│ ↓ │
│ POST /ai-doc/if-continue-ask (SSE, wait for done) │
│ ├─ True: Continue to Round 4 (same five steps) │
│ └─ False: Proceed to supplemental image check │
└──────────────────────────────────────────────────────┘
↓
POST /ai-doc/if-need-image (determine if photos are needed)
├─ Image needed: Upload via /oss/images, then call /ai-doc/pic-result (backend context only, hidden from user)
└─ No image needed: Proceed to summary
↓
POST /ai-doc/summary (SSE, stream consultation summary text, wait for done)
↓
POST /ai-doc/report (submit structured report task, submit once)
↓
GET /ai-tasks/{task_id} (poll async task progress until succeeded)
↓
GET /medical-record?session_id=<SESSION_ID> (retrieve complete medical report)API Catalog & Step-by-Step List
| Step | Endpoint | Method | Type | Purpose & Timing |
|---|---|---|---|---|
| 1 | /ai-doc/pre-question | GET | JSON | Optional. Fetch preset guidance questions before starting. |
| 2 | /session-records/sessions | POST | JSON | Required. Initialize session and obtain global session_id. |
| 3 | /ai-doc/keywords | POST | JSON | Step 1 of each round: Extract symptom keywords and entities. |
| 4 | /ai-doc/reason-info | POST | SSE | Step 2 of each round: Stream model thinking process (reasoning bubble). |
| 5 | /ai-doc/analysis | POST | JSON | Step 3 of each round: Get condition analysis summary. |
| 6 | /ai-doc/related-question | POST | JSON | Step 4 of each round: Get proactive follow-up question and options. |
| 7 | /session-records/messages | POST | JSON | Step 5 of each round: Save user answer text or selected bubble. |
| 8 | /ai-doc/if-continue-ask | POST | SSE | Decision. Called after Round 3 to check if info is sufficient. |
| 9 | /ai-doc/if-need-image | POST | JSON | Multimodal Decision. Check if supplemental photo is recommended. |
| 10 | /oss/images | POST | JSON | Direct upload to OSS for safe public temporary image URL. |
| 11 | /ai-doc/pic-result | POST | JSON | Submit supplemental image for model analysis (hidden from UI). |
| 12 | /ai-doc/summary | POST | SSE | Stream consultation summary markdown text. |
| 13 | /ai-doc/report | POST | JSON | Submit structured medical report generation task, get task_id. |
| 14 | /ai-tasks/{task_id} | GET | JSON | Poll task status at a fixed 4-second interval until succeeded. |
| 15 | /medical-record | GET | JSON | Retrieve full structured consultation and diagnosis report. |
Core Context Passing Chain
Step 2 Create Session
└── session_id ──────────────┬──> Steps 3~12: Global session_id for all consultation requests
└──> Step 13: session_id to submit report task
Step 10 Upload Image
└── url ─────────────────────────> Step 11: img_url in pic-result (pass original value)
Step 13 Submit Report Task
└── task.task_id ────────────────> Step 14: Poll task /ai-tasks/{task_id}
(If task is null, report was generated synchronously; read report_id and jump to Step 15)
Step 14 Task Completion
└── Polled to succeeded ─────────> Step 15: GET /medical-record?session_id=<SESSION_ID>Key Guidelines & Best Practices
1. Round Control Strategy
- Backend does not hardcode an upper round limit.
- Recommended client strategy: advance directly through rounds 1-3, then call
if-continue-askonce after round 3; the reference client fixes the cap at 3 mandatory rounds plus 1 optional round (4 in total), and integrators may choose their own cap. - If
Trueand under client maximum (e.g. 4~5 rounds), continue asking; otherwise transition to image check or summary.
2. Shared SSE Protocol
Streaming endpoints (reason-info, if-continue-ask, summary) return Content-Type: text/event-stream:
- Event frames:
data: <JSON>with event type specified inside JSONtypefield. - Four event types:
metadata(stream start),content(chunk streaming, do not advance workflow),done(success completion),error(failure).
3. Report Generation & Polling
- Submit
POST /ai-doc/reportonly once per session; never submit once perreport_type. - Query once, then poll at a fixed 4-second interval (measured generation takes about 20~30 s), with a 5-minute ceiling.
- Stop polling as soon as the status reaches
succeeded,failedorcanceled. - When
succeeded, callGET /medical-record?session_id=<SESSION_ID>. - For in-depth report fields and UI component mapping, see Report Fields & UI Mapping.
Default Round Schedule and Handling Each User Answer
if-continue-ask is called only when the continuation decision is needed, and only once per consultation. The recommended default schedule is at least 3 rounds: after round 3 you make a single decision; True starts round 4, False ends the question phase.
| Round | After the answer is saved |
|---|---|
| Round 1 | Go straight to round 2; do not check continuation. |
| Round 2 | Go straight to round 3; do not check continuation. |
| Round 3 | Call if-continue-ask: True starts round 4; False goes to if-need-image. |
| Round 4 | Maximum round of this default schedule reached; after the answer is saved go straight to if-need-image. |
Do not call if-continue-ask after rounds 1 or 2, and do not call it more than once per round. The round ceiling is a frontend policy: if you choose a looser ceiling (for example 4~5 rounds), still make exactly one continuation decision per applicable round and move to if-need-image once you reach your own ceiling.
Each user answer follows the same order: after related-question returns the questions, show them to the user; when the user answers, first call POST /session-records/messages to save the answer, then branch by the current round. Recommended save rules:
| Content to save | role | content_type | Rule |
|---|---|---|---|
| Text answer | user | 1 | Store the user's original answer in content. |
| Supplemental consultation image | user | 2 | Put the exact url value from inside the complete upload success response's data into image; do not rewrite it. |
| Model output used for replay | assistant | 1 | Save only when the product needs replay; use display-safe text or parseable JSON. |
Never share a session_id between users or different consultation flows. For client retries, apply idempotency controls at the same business-session level so that the same user answer is not saved repeatedly.
Session Creation and Pet-Profile Context
module_type is always 1, content must be non-empty, and pet_profile_id must be a valid numeric ID. Retain these response fields for later calls (all paths are inside the response data object):
| Field | Subsequent use |
|---|---|
session_id | Session identifier for every later consultation request. |
medical_record_id | ID of the created medical record. To query by this ID, send the same value as the report_id query parameter. |
initial_message | First message saved by the platform from the creation request; the original complaint is in initial_message.content. |
If you use the preset questions first, GET /ai-doc/pre-question also requires a valid numeric pet_profile_id. After the session is created, every later request must stay in the same pet-profile context.
Multi-Turn Branch and Reading the if-continue-ask Result
Run each round in the five steps listed in the catalog above. After round 3, read the business result of if-continue-ask only from its terminal type=done frame. This endpoint reports the decision in the content string of the business result:
data: {"type":"done","data":{"session_id":"<SESSION_ID>","data":{"content":"True"},"raw_content":"True","gateway_request_id":"<REQUEST_ID>"}}contentisTrue: start round 4, beginning again fromPOST /ai-doc/keywords.contentisFalse: end the question phase and callPOST /ai-doc/if-need-image.
True and False are strings, not JSON booleans. Read the complete done frame of the SSE stream and then read content from the business result object in that frame; do not rely on intermediate streamed text.
Supplemental Image Branch
POST /ai-doc/if-need-image decides after the question phase whether an image is required. The complete success response is below; is_pic is not a top-level field of response data but a field of the business result object inside it (path data.is_pic relative to response data):
{
"code": 200,
"message": "success",
"data": {
"session_id": "<SESSION_ID>",
"data": {
"is_pic": "True",
"pic_explain": "Please upload a clear, evenly lit photo of the affected area."
},
"raw_content": "Raw model output",
"gateway_request_id": "<REQUEST_ID>"
}
}Path within response data | Value | Next step |
|---|---|---|
data.is_pic | "True" | Display the complete pic_explain, upload an image, and continue with the supplemental image branch. |
data.is_pic | "False" | Do not upload an image; call POST /ai-doc/summary. |
is_pic is a string, not a JSON boolean. If the field is missing or has another value, stop automatic progression and record the complete response.
If the result requires an image:
- Upload the local image with
multipart/form-datatoPOST /oss/images. - Read the complete upload success response, take
urlfrom responsedata, and persist that exact string. - For session replay, save the persisted
urlas an image message if needed. - Put the same persisted
url, unchanged, in theimg_urlfield ofPOST /ai-doc/pic-result. - After receiving the supplemental image result (the recognition result is used by the backend to enrich consultation context and must not be displayed to the user on the UI), go straight to generating the consultation summary.
Do not send arbitrary image URLs
pic-result.img_url is not a generic image URL field. The service validates current-user ownership, ready status, image media type, the consultation-image purpose, and the canonical OSS address. URLs such as https://example.com/..., hand-built OSS addresses, and assets uploaded by another user are rejected.
Image uploads support jpg, jpeg, png, webp, and gif, up to 10 MiB per file.
lang versus locale
Profile and display APIs use the query parameter ?locale=...; Smart Consultation stores AI session language in the request body field lang. They may have the same BCP 47 value, but they are separate parameters and must not be substituted for one another.
| Client language | Profile/display request | Smart Consultation session body |
|---|---|---|
| Simplified Chinese | ?locale=zh-CN | "lang": "zh-CN" |
| Traditional Chinese (Hong Kong) | ?locale=zh-Hant-HK | "lang": "zh-Hant-HK" |
| English (United States) | ?locale=en-US | "lang": "en-US" |
The platform requires a complete regional BCP 47 value. Before selecting one, call GET /locales to confirm it is active in the target environment. A session keeps the language used at creation time:
- Prefer omitting
langin later AI requests so the session language is retained. - If
langis supplied later, it must exactly equal the creation value. - A different value returns HTTP
400(message:请求语言与会话语言不一致; internal identifierSESSION_LOCALE_MISMATCH); the service does not switch a session language implicitly.
Failure Handling
Where these identifiers are visible
The names below are server-side reason identifiers: for streaming endpoints they appear in the SSE error event's code field (the same event also carries the public numeric error_code); a plain HTTP 4xx/5xx returns only {code, message, data} — neither the identifier nor a numeric code — so decide from the HTTP status and message; for a failed asynchronous task the numeric code is in the task object's data.error_code.
| Trigger (internal identifier / publicly visible response) | Retry? | Correct action |
|---|---|---|
Network timeout or SSE retryable: true | Limited retry | Keep the request parameters unchanged and retry. |
| No terminal SSE event | Limited retry | Treat the stream as failed and restart the whole stream. Do not use partial content as the result. |
MEDIA_URL_NOT_ALLOWED or MEDIA_URL_INVALIDHTTP 400, message 媒体URL不是当前服务登记的OSS地址 | Do not retry directly | Upload the image again and reuse the returned url unchanged. |
MEDIA_ASSET_NOT_FOUND or MEDIA_ASSET_NOT_READYHTTP 400, message 媒体资产不存在或无权限 / 媒体资产尚未就绪 | Inspect first | Use an image uploaded by the current user and wait until it is ready. |
MEDIA_POLICY_REJECTEDHTTP 400, message 媒体资产用途不匹配 | Do not retry directly | Upload an eligible image again through POST /oss/images that meets the consultation input policy. |
SESSION_LOCALE_MISMATCHHTTP 400, message 请求语言与会话语言不一致 | Do not retry directly | Omit lang or use the exact language selected for the session. |
Report task is failed | Inspect first | Record task_id, session_id, and error_code; retry with POST /ai-tasks/{task_id}/retry only when the code is retryable. |