cURL
Knowledge Base–grounded Q&A. The endpoint streams the answer over SSE in three phases: first planning (deciding what to search and which Knowledge Base), then tool calling (running the retrieval), then generation (producing the answer). Create and publish the Q&A service in the console first.
Pass
This snippet shows only
During the tool-calling phase the model picks from the tools below; the tool name is in
After enabling in-chat file parsing in the console, you can pass a file mid-conversation. The file ID comes from the addFile (register file) endpoint. Full flow:
The Q&A pipeline is adapted for model-side context caching (KV Cache): the request prefix stays stable across multi-turn dialogue and multi-round tool calls, so cached input tokens are billed at a discounted rate and time-to-first-token drops. Two cache modes exist, and only one applies per request:
Add
The two cache modes are supported on different model sets. The model is configured on the platform side — this endpoint exposes no model-selection parameter — so which cache mode is available depends on the model your Q&A service actually runs on:
Cache gains fall into two categories — intra-request gains are more stable and more significant than cross-request ones.
Strongly recommended: multiple retrieval and reasoning rounds within one request. When one question triggers multiple tool-calling rounds (repeated
Break-even: for the same cached prefix, explicit caching charges 125% of the input price for creation and 10% for a later hit. Creating it once and fully reusing it once costs 135%, versus 200% without caching. Savings for the entire request still depend on the actual numbers of tokens created and hit.
Not recommended (no gain, or even more expensive):
The platform doesn't persist conversation state — pass the full
The response streams SSE events in this lifecycle:
plan_start → plan_end → tool_calling → tool_return → generation_start → generation_end. The plan → tool_calling → tool_return segment can repeat multiple times (multi-round retrieval).Basics
| Item | Value |
|---|---|
| Call | HTTP, SSE streaming output |
| Endpoint | POST https://{workspaceId}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat |
| Content-Type | application/json |
| Accept | text/event-stream recommended |
| Auth | Authorization: Bearer <API-Key> |
| Rate limit | By default, a maximum of 10 requests per 10 seconds per user; retry later if throttled |
Filter by document tags
Pass search_filters in parameters.agent_options.kb_search_configs for a specific Knowledge Base to dynamically narrow retrieval by document tags during Q&A.
| Name | Type | Required | Description |
|---|---|---|---|
parameters.agent_options.kb_search_configs | array<object> | No | Request-time filters, one element per Knowledge Base |
kb_search_configs[].id | string | Yes | ID of a Knowledge Base bound to the current Q&A service; required in every element |
kb_search_configs[].search_filters | array<object> | No | Retrieval filter conditions, up to 20 per Knowledge Base |
search_filters[].tags | array<string> | No | Document tag array; OR within one condition, AND between conditions |
parameters. Pass input and stream as in the complete request example. Replace agent_id with your Q&A service ID and id with a Knowledge Base ID bound to that service:
- Place
search_filtersinside akb_search_configselement, not at the request's top level; a top-level value is ignored. An unbound Knowledge Base ID or more than 20 filter conditions for one Knowledge Base returns HTTP 400 with error codeParamValue.Error. - Unstructured Knowledge Bases, such as document search, support only
tagsandmeta.tagsmust be an array, not a scalar; a scalar may return no retrieval results rather than an API error. - Tags within one condition are combined with OR: a chunk matches any tag. Conditions are combined with AND. For example,
[{"tags": ["TagA", "TagB"]}]matches either tag, whereas[{"tags": ["TagA"]}, {"tags": ["TagB"]}]requires both. - Service preset filters and request-time filters are combined with AND; request-time filters can only narrow the scope. Configure presets in the console or through the Agent create/update APIs.
search_filters: []adds no conditions and does not clear preset filters.
Execution phases
Phase (group) | Description |
|---|---|
planning | Planning; includes start and end events |
generating | Generating; includes start and end events |
Step (step) | Description |
|---|---|
planning | Planning |
tool_calling | Tool calling (group stays planning) |
generating | Generating |
step_change may be absent due to the model — prefer the persistent step. On empty frames, step, step_change, and group may all be absent. A tool_call consists of two events: tool_calling (emits tool_calls) and tool_return (tool result).Step transition events
step | step_change | Event | Description |
|---|---|---|---|
planning | plan_start | Plan start | step becomes planning; subsequent content is the planning text |
planning | empty | Planning | content is the planning text stream |
planning | plan_end | Plan end | step is about to change; still planning at this event |
tool_calling | tool_calling | Tool call | Emits full tool_calls (name + args); carries this round's usage |
tool_calling | tool_return | Tool return | role is tool; content is a summary; additional_kwargs.extra_json is the structured result (docs for retrieval) |
generating | generation_start | Generation start | Subsequent content is the answer text stream |
generating | empty | Generating | content is the answer text stream |
generating | generation_end | Generation end | finish_reason is stop; carries the final usage |
Event lifecycle
Tool catalog
During the tool-calling phase the model picks from the tools below; the tool name is in tool_calls[].function.name. arguments is a JSON string — parse it once more to get the actual parameters. The tool result lives in the tool_return frame's additional_kwargs.extra_json.docs.
function.name | Tool | arguments | Return docs[] |
|---|---|---|---|
semantic_search | Knowledge Base search | {"query", "target_ids"} | Matched chunk array with body and multi-dim scores |
obtain_file | Fetch full file content | {"file_id", "max_tokens"} | File-level info (incl. Markdown presigned URL); full text in message.content |
execute_sql | Run SQL (NL2SQL) | {"sql", "knowledge_base_id"} | SQL result rows; each row = _citation_index + query columns |
section_browse | Section browse | {"knowledge_base_id", "file_id", "section_path"} | Section preview (first 300 chars) |
section_peruse | Section peruse | {"knowledge_base_id", "file_id", "section_path", "max_tokens"} | Full section content |
max_tokens(obtain_file/section_peruse) is a numeric string, e.g."989482".target_ids/knowledge_base_idis the Knowledge Base (pipeline) ID;section_pathlooks likeAPI Docs>Calling conventions(>-separated levels).- Multiple tools can be chained in one request (e.g.
semantic_searchto locate a file →obtain_filefor full text).
In-chat files (session_files)
After enabling in-chat file parsing in the console, you can pass a file mid-conversation. The file ID comes from the addFile (register file) endpoint. Full flow:
- Call applyFileUploadLease to get an upload lease and an OSS presigned URL
- PUT the file to OSS using the returned URL
- Call addFile to register the file and get a
fileId - Pass that
fileIdin this endpoint'sparameters.agent_options.session_files(up to 10)
Context caching
The Q&A pipeline is adapted for model-side context caching (KV Cache): the request prefix stays stable across multi-turn dialogue and multi-round tool calls, so cached input tokens are billed at a discounted rate and time-to-first-token drops. Two cache modes exist, and only one applies per request:
| Implicit cache | Explicit cache | |
|---|---|---|
| How to enable | On by default when the model supports it; cannot be turned off | Pass enable_cache_control: true in the request |
| Hit determinism | Non-deterministic; the system auto-detects common prefixes | Deterministic when the prefix matches and the cache is valid |
| Cache creation cost | 100% of input price (no extra charge) | 125% of input price |
| Cache hit price | 20% of input price | 10% of input price |
| TTL | Non-deterministic; cleaned up by the system periodically | 5 minutes, reset on every hit |
| Minimum cacheable length | 1024 tokens | 1024 tokens |
Pricing ratios and TTL are subject to the official Model Studio docs — Context Cache and Explicit Cache Best Practices — and your console bill. Internal benchmarks put the implicit-cache hit rate at roughly 75% of explicit caching; this is an empirical figure, not an official metric.
Enabling explicit caching
Add enable_cache_control under parameters.agent_options (default false); all other parameters stay unchanged:
Model support
The two cache modes are supported on different model sets. The model is configured on the platform side — this endpoint exposes no model-selection parameter — so which cache mode is available depends on the model your Q&A service actually runs on:
| Model | Explicit cache | Implicit cache |
|---|---|---|
| qwen3.8-max (current default) | Supported | Supported |
| qwen3.8-flash | Supported | Supported |
| qwen4-max | Supported | Supported |
| qwen3.7-plus | Supported | Supported |
| qwen3.6-plus | Supported | Not supported |
When to use it
Cache gains fall into two categories — intra-request gains are more stable and more significant than cross-request ones.
Strongly recommended: multiple retrieval and reasoning rounds within one request. When one question triggers multiple tool-calling rounds (repeated semantic_search / execute_sql / section browsing plus intermediate reasoning), the cache breakpoint moves forward with each new tool result, and the previous round's full context (including retrieval results) becomes a stable prefix for the next. More complex questions, more retrieval rounds, and longer results generally offer more reuse. These gains do not depend on cross-request prefix stability; explicit-cache hits still require a matching prefix, the minimum length, and a valid cache lifetime.
Recommended: cross-request reuse:
| Scenario | Why |
|---|---|
| Multi-turn continuous dialogue | From the second turn on, requests can reuse the previous turn's full history prefix; longer dialogue offers more reuse |
| Long system prompt / large table schemas | Structured Knowledge Base schemas are stitched into the system prompt — large and stable within a session, ideal cache content |
| Repeated follow-ups on the same long document / session file | High share of stable prefix; create once, hit many times |
| Latency-sensitive workloads needing deterministic hits | Explicit caching is deterministic and unaffected by backend scheduling |
| Scenario | Why |
|---|---|
| One-shot single-turn short Q&A | Creates but never hits — you pay the 25% creation premium for nothing |
| Prefix shorter than 1024 tokens | Below the minimum cacheable length; nothing gets cached |
| Low-frequency calls spaced over 5 minutes apart | The explicit cache expires in 5 minutes; the next request re-creates it |
| Cross-request reuse in multimodal document scenarios | Image content blocks participate in prefix computation and easily diverge across requests; count only on intra-request gains |
| Switching Knowledge Bases / service configs every session | Different prefixes (schemas, KB info) cannot be reused |
"Not recommended" only means explicit caching doesn't pay off there. If the service runs on qwen3.6-plus (which doesn't support implicit caching), leaving
enable_cache_control off doesn't fall back to implicit caching — it means no caching at all. If you still want some cache benefit in these scenarios, evaluate and enable it anyway.Observing cache hits
cached_tokens in the final frame's usage is the number of input tokens that hit the cache in this request:
cached_tokensis accumulated across the multiple model calls within the request;- No hit when first creating a cache is normal, but later tool-calling rounds within the same request can reuse the earlier prefix; the first request's accumulated value is not necessarily 0;
- Later hits depend on model support, cache lifetime, and prefix stability. Observe actual
cached_tokens; neither a positive value from the second turn nor continuous growth is guaranteed; - You can also check the
cache_tokensmetric under "Model Monitoring" in the Model Studio console, or filter bycachein "Billing Details".
Notes and limits
- The two cache modes are mutually exclusive:
enable_cache_control: truemeans explicit caching only, no implicit caching. On qwen3.6-plus there is no implicit cache, so when the service runs on this model, leaving it off means no cache — not a "fallback to implicit". - No hit on the first turn is normal: any cache must be created first;
cached_tokens=0doesn't indicate a malfunction. - 5-minute TTL for explicit cache: every hit resets it to 5 minutes; after a long pause, the next request re-creates the cache.
- Tool-definition changes invalidate the cache: tool definitions are part of the system prompt used in cache computation. For structured Knowledge Bases, carrying
search_filterssuppresses theexecute_sqltool — if filters come and go within one session, the tool list changes and the system prefix misses. Keepkb_search_configsstable within a session. - The prefix must be byte-for-byte stable: rebinding Knowledge Bases, changing service configs (e.g. custom instructions, the session-file switch), or a platform-side model change all alter the prefix and force cache re-creation.
- Cross-request hits are unstable in multimodal scenarios: with image input, image content blocks participate in prefix computation and easily diverge across requests; gains in such scenarios come mainly from intra-request multi-round retrieval — don't estimate by cross-request hits.
- Backtracking limit on very long turns: cache matching backtracks at most 20 content blocks from the breakpoint; extreme turns with many messages (multiple tool calls + image blocks) may exceed the range and miss.
- Caches are isolated by account and model: no sharing across accounts, or across models within one account.
input_tokens≠ created + hit: the backend appends a few tokens (usually under 10) after the prompt; they count toward total input but not toward cache statistics.
Verifying the benefit
- Add
enable_cache_control: trueand run a complex question that triggers multi-round retrieval; check whether the final frame'scached_tokensis greater than 0; - Follow up 2-3 more turns in the same session (within 5 minutes); check whether
cached_tokensgrows with history and compare time-to-first-token; - A/B against the same request without the parameter and record actual
cached_tokens, time-to-first-token, and billing for both groups. The current default qwen3.8-max supports implicit caching, so the baseline may also hit the cache; do not assume it is 0. Decide whether to keep explicit caching on based on "When to use it".
Client assembly guide
| Goal | How |
|---|---|
| Planning text | Accumulate message.content across all step == "planning" frames |
| Final answer | Accumulate message.content across all step == "generating" frames |
| Citations | Take from tool_return's additional_kwargs.extra_json.docs, mapped by _citation_index |
| Usage | Take top-level usage from the generation_end frame (answer usage); retrieval usage is on the corresponding tool_calling frame |
Multi-turn dialogue
The platform doesn't persist conversation state — pass the full messages history on every request. Cap history length (around the last 10 turns) to stay within the model's context window.Authorizations
string
header
required
DashScope API Key, obtained from the API Key page in the console.