Skip to main content

Knowledge Q&A

SSE-streaming knowledge-based Q&A

POST
/api/v2/apps/knowledge/chat
cURL
curl -X POST "https://{workspaceId}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat" \
  -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{
    "input": {
      "messages": [
        {"role": "user", "content": [{"type": "text", "text": "什么是阿里云百炼知识库?"}]}
      ]
    },
    "parameters": {
      "agent_options": {
        "agent_id": "aid-xxxxxxxxxxxxxxxx"
      }
    },
    "stream": true
  }'
{ "output": { "choices": [ { "message": { "role": "assistant", "type": "ai", "content": "阿里云百炼知识库是阿里云百炼平台提供的知识管理服务,支持文档导入、自动切片、语义检索与问答。", "extra": { "step_change": "generation_start", "step": "generating", "group": "generating" }, "tool_calls": [] }, "finish_reason": "" } ], "request_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }, "code": "200", "message": "Success", "request_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }
A knowledge-based intelligent Q&A API. The response is delivered via Server-Sent Events (SSE) in a streaming fashion, decomposing the answer generation process into three sequential phases: planning (reasoning about what to search and which knowledge base to query), tool calling (executing retrieval operations), and generation (producing the final answer). Before calling this API, you must first create and publish a Q&A service in the console.
Responses are delivered as SSE events with the following lifecycle: plan_start → plan_end → tool_calling → tool_return → generation_start → generation_end. The entire sequence plan → tool_calling → tool_return may repeat multiple times (for multi-round retrieval).

Basic Information

ItemDescription
Invocation methodHTTP API call with SSE streaming output
Request URLPOST https://{workspaceId}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat
Content-Typeapplication/json
AcceptRecommended: text/event-stream
AuthenticationAuthorization: Bearer <API-Key>
Rate limitingDefault per-user limit: 25 QPS

Execution Phases

Execution phase (group)Description
planningPlanning phase — includes both start and end events
generatingGeneration phase — includes both start and end events
Current step (step)Description
planningIn planning phase
tool_callingInvoking tools (the group remains planning)
generatingIn generation phase
Due to model behavior, the step_change field may be absent. Prioritize using the persistent step field instead. In empty payloads, step, step_change, and group fields may all be missing. A tool_call consists of two distinct events: tool_calling (emitting tool_calls) and tool_return (receiving tool results).

Step Transition Events

stepstep_changeEventDescription
planningplan_startPlanning startsstep transitions to planning; subsequent content contains planning text
planning— (empty)Planning in progresscontent contains streamed planning text
planningplan_endPlanning endsstep is about to change; at event emission, step is still planning
tool_callingtool_callingTool invocationEmits full tool_calls (including tool name and arguments); includes usage for this round
tool_callingtool_returnTool returnsrole is "tool"; content contains summary of returned data; structured result resides in additional_kwargs.extra_json.docs (e.g., retrieved documents for search tools)
generatinggeneration_startGeneration startsSubsequent content contains streamed final answer text
generating— (empty)Generation in progresscontent contains streamed answer text
generatinggeneration_endGeneration endsfinish_reason is "stop"; includes final usage

Event Lifecycle

Available Tools

During the tool-calling phase, the model selects from the following tools. The tool name appears in tool_calls[].function.name. The arguments field is a JSON string requiring secondary parsing to extract actual parameters. Tool return values appear in additional_kwargs.extra_json.docs within tool_return frames.
function.nameToolargumentsReturns docs[]
semantic_searchKnowledge base search{"query", "target_ids"}Array of matched document chunks, including full text and multi-dimensional scores
obtain_fileRetrieve full file content{"file_id", "max_tokens"}File-level metadata (including Markdown presigned URL); full content in message.content
execute_sqlExecute SQL query (NL2SQL){"sql", "knowledge_base_id"}SQL result rows; each row contains _citation_index plus queried column values
section_browseSection-level search{"knowledge_base_id", "file_id", "section_path"}Section preview (first 300 characters)
section_peruseSection deep-read{"knowledge_base_id", "file_id", "section_path", "max_tokens"}Full section content
  • max_tokens (for obtain_file / section_peruse) is a numeric string, e.g., "989482".
  • target_ids / knowledge_base_id refer to knowledge base (pipeline) IDs; section_path uses > as hierarchical delimiter, e.g., Open API Documentation>API Invocation Guide.
  • Multiple tools may be chained in one request (e.g., semantic_search locates a file → obtain_file retrieves its full content).

Temporary Files (session_files)

When File Pre-parsing is enabled in the console, users can upload temporary files during a conversation. File IDs are obtained via the addFile API. Full workflow:
  1. Call applyFileUploadLease to obtain an upload lease and OSS presigned URL
  2. Upload the file to OSS using the provided PUT URL
  3. Call addFile to register the file and retrieve its fileId
  4. Pass that fileId in parameters.agent_options.session_files of this API (up to 10 files allowed)
If File Pre-parsing is disabled in the console, the session_files parameter will be ignored.

Client-Side Response Assembly Guidance

GoalAssembly Strategy
Complete planning textConcatenate message.content from all frames where step == "planning"
Final answer textConcatenate message.content from all frames where step == "generating"
Citation sourcesExtract from additional_kwargs.extra_json.docs in tool_return frames; match _citation_index to corresponding positions in answer text
Usage statisticsUse top-level usage in generation_end frame (final answer usage); retrieval usage appears in respective tool_calling frames

Multi-turn Conversations

The platform does not retain conversation state. Each request must include the full messages history. We recommend limiting history length (e.g., last 10 turns) to avoid exceeding the model’s context window.

Authorizations

string
header
required

DashScope API Key,在控制台 API Key 页面 获取。

Body

application/json
object
required

输入参数。

object
required

配置参数字段。

boolean
defaulttrue
required

是否开启流式输出。必须填 true,当前版本仅支持流式响应;填 false 或不填请求将失败。

Response

200-text/event-stream
object
string

状态码,成功为 200。

string

状态信息,成功为 Success。

string

请求 ID(DashScope 平台级,全流不变)。

object