End-to-end walkthrough — create a Knowledge Base, then pass tool-call history through multi-turn API requests to avoid redundant retrieval
This guide shows how to pass tool-call history across turns so the model answers from prior retrieval results instead of re-running searches. The same sample document drives every step, so the results are reproducible.
Why context gets lost
The Knowledge Agent is stateless — each request stands alone and the server keeps no conversation history. A single response usually moves through several stages:
If the next turn sends only the text history (the user question and the assistant's final answer), the model loses sight of the tool calls in between. It does not know what has already been retrieved, so it searches the same content again — wasting tokens and risking inconsistent answers.
The fix is to pass the full tool-call chain (assistant.tool_calls plus the matching tool results) as history messages, so the model can answer from what it has already retrieved.
Prepare the sample document
This guide uses the Model Studio docs sample bundle — 92 official Model Studio technical documents covering API usage, model references, and best practices. Download, unzip, and upload them to a Knowledge Base. The walkthrough uses First call to the Qwen API from the bundle to demonstrate follow-up questions:
- Turn 1: Ask "How do I call the Qwen API?" (triggers multiple tool calls)
- Turn 2: Follow up with "How do I set the API Key as an environment variable?" (verifies that history is reused and no extra retrieval runs)
End-to-end walkthrough
1. Create a Knowledge Base and upload the sample
- Go to Data Ingestion → Knowledge Management, click Create, and select an edition.
- Choose Document Search as the type and Basic Document Q&A as the use case.
- Upload the sample documents. Wait for chunking and vectorization to finish — the status should change to Parsed.
2. Create a Knowledge Q&A service and bind the Knowledge Base
- Go to Knowledge Service → Knowledge Q&A and click Create Q&A Service.
- Enter a service name, then open the configuration page.
- Click + Add and bind the Knowledge Base from the previous step.
- Pick a generation model and a retrieval mode (use Multi-turn Agentic Mode for multi-turn scenarios), then click Publish.
3. Get the API parameters
In the Q&A service list, click Configure for the target service, open the Publish Channels tab, and click API Debugging in the Invocation Method section to collect the following parameters:
| Parameter | Where to find it | Example |
|---|---|---|
| endpoint | Endpoint shown on the API Debugging page. {workspaceId} is your workspace ID. | https://{workspaceId}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat |
| agent_id | Request parameter shown on the API Debugging page — the Q&A service ID. | aid-xxxxxxxx |
| API Key | Create it on Settings → API Key. | sk-xxxxxxxx |
agent_id uniquely identifies a Q&A service — each service has its own agent_id.4. First turn
Send the first request with the parameters you collected:
5. Second turn: include tool history
For the follow-up "How do I set the API Key as an environment variable?", pass the full history from turn 1 (including the tool-call chain):
6. Comparing the two approaches
Measured against First call to the Qwen API: after turn 1 asks "How do I call the Qwen API", turn 2 asks "How do I set the API Key as an environment variable?". Compare what happens with each history strategy:
| Full tool history | Text-only history | |
|---|---|---|
| Tool calls in turn 2 | 0 — answers directly from prior results | Re-runs retrieval (2 semantic_search calls observed) |
| Response speed | Fast — no retrieval round trip | Slow — retrieval runs again |
| Answer consistency | Same retrieval results power both turns | New retrieval may hit different chunks, leading to drift |
semantic_search → obtain_file), producing 6 history messages. Turn 2 with full history (7 messages) answered with 0 tool calls. Turn 2 with text-only history (3 messages) re-ran semantic_search twice. The exact counts depend on your document structure and how well the question matches, but the takeaway holds: full history eliminates redundant retrieval.
Full history makes the input longer (it carries tool results), but skips the retrieval round trip. Text-only history sends a smaller input but pays for retrieval again. In multi-turn follow-up scenarios, full history wins on both response speed and answer consistency.
Extract tool history from the SSE stream
The Agent streams output as SSE — each frame is data:{...}, with the message at obj.output.choices[0].message. message.extra.step_change marks state-change boundaries. You only need to handle three event types:
| Event | Detection condition | Data to extract |
|---|---|---|
| Tool call | step_change == "tool_calling" | The tool_calls array (all parallel calls in this round) |
| Tool return | step_change == "tool_return" and role == "tool" | content plus tool_call_id |
| Final answer | Between generation_start and generation_end | Concatenate every content chunk |
State flow
The Agent may run several rounds of tool calls before it has enough information to generate the final answer.
Message format and key rules
Organize the extracted history messages by role, in this order:
| Role | Required fields | Notes |
|---|---|---|
user | role, content | User input |
assistant (tool call) | role, content (empty), tool_calls | All parallel tool calls dispatched in this round |
tool | role, content, tool_call_id | Tool result. tool_call_id must match the id in the corresponding tool_calls[] entry. |
assistant (final answer) | role, content | The model's final answer |
tool_calls[].function.arguments is a JSON string, not an object. Keep it as a string when you send it back.Full Python implementation
The code below ties together "extract history from SSE → manage multi-turn history automatically → compare both approaches" in a single runnable script. The numbers shown were measured against the sample document and prompts on this page.
Configuration
Extract tool history from the SSE stream
Multi-turn chat manager
Compare full history vs text-only history
Caveats
Manage history length
Tool returns can be long. After several turns the total may exceed the context limit. Recommendations:
- Truncate earlier tool returns: keep full tool content only for the most recent K turns. For older turns, truncate the
toolmessage to the first N characters. - Sliding window: beyond 3 turns, replace older tool results with summaries.
Content you do not need to send back
| Content | Why |
|---|---|
reasoning_content | The model's reasoning trace — display it to the user, no need to echo it back. |
extra fields | Streaming protocol state markers, used only for client-side rendering. |
usage | Token-usage metrics, used only for monitoring and billing. |
tool_call_chunks | Streaming fragments — already merged into tool_calls. |
FAQ
What happens if I do not send tool-call history?
The model loses the retrieval context, re-searches the same content, and answer quality drops. Measured: with full history, the follow-up runs 0 tool calls and answers immediately; without it, retrieval runs again.
Can I skip the intermediate tool calls and send only the final answer?
It works, but it is not recommended. Sending only user + assistant(final answer) strips the model's memory of the Knowledge Base content, and follow-up quality noticeably drops.
Does the order of parallel tool returns matter?
The order does not affect function — the model matches by tool_call_id. But every tool message must immediately follow its corresponding assistant(tool_calls) message.