Using a custom middleware in the AgentScope framework to integrate Alibaba Cloud Bailian Knowledge Studio as an agent’s knowledge memory, supporting both static injection and agentic autonomous retrieval modes
This guide targets developers using AgentScope as the runtime for hosting agents. It demonstrates how to integrate Alibaba Cloud Bailian Knowledge Studio into an AgentScope agent via a custom middleware—treating it as the agent’s knowledge memory. The entire workflow is implemented programmatically (high-code), with no reliance on manual console operations. Example code is based on AgentScope v2.0.4.
Principle: Knowledge Base as the Agent’s Memory
Large language models (LLMs) are stateless—each inference is independent. AgentScope injects external capabilities into agents via its middleware mechanism; RAG retrieval, long-term memory, and traceability are all implemented as middleware modules without modifying core agent logic.
AgentScope provides a built-in RAGMiddleware, which accepts a list of KnowledgeBase objects (encapsulating local embedding models and vector databases) and injects retrieved results before inference. However, Alibaba Cloud Bailian Knowledge Studio is a managed service: embedding, vector storage, and retrieval are all handled server-side—no local vector database is required.
In this practice, we implement a custom middleware—KnowledgeStudioRAGMiddleware—that directly calls Knowledge Studio’s knowledge search API. It integrates search results into AgentScope agents using two distinct modes:
| Mode | Trigger Timing | Implementation Approach | Corresponding AgentScope Middleware Hook |
|---|---|---|---|
| static | Before the first inference of each reply() call | Use user message as query; inject results into system_prompt | on_system_prompt |
| agentic | Model decides autonomously | Expose search_knowledge tool; agent invokes it on demand | list_tools |
AgentScope middleware offers six hook points. This practice uses two:
on_system_prompt (Transformer-type, serially modifies the system prompt) and list_tools (Tool source-type, declares tools provided by the middleware). See the AgentScope Middleware Documentation.Environment Setup
Install Dependencies
Prepare Required Parameters
| Parameter | How to Obtain | Example |
|---|---|---|
| DashScope API Key | Create on the Settings → API Key page | sk-xxxxxxxx |
| Workspace ID | Business space ID from the console URL | llm-xxxxxxxx |
| Knowledge Search Service ID | Acquired after creating and publishing a service under Knowledge Services → Knowledge Search | aid-xxxxxxxx |
Step 1: Build the Knowledge Base via API
The entire knowledge base setup—file upload → index creation → ingestion—is performed programmatically via API. Below is a reusable implementation. For full API details, see Create Knowledge Base & Ingest and Register File.
Step 2: Wrap the Retrieval Client
Encapsulate Knowledge Studio’s knowledge search API into a lightweight class for use by the middleware. The knowledge search API operates on a published search service (agent); retrieval policies (e.g., reranking, top_k) are configured in the console. At runtime, only agent_id and the query intent need to be passed.
Step 3: Implement KnowledgeStudioRAGMiddleware
This is the core of the practice: a custom subclass of MiddlewareBase supporting both static and agentic modes. Inspired by AgentScope’s built-in RAGMiddleware, but with Knowledge Studio API as the backend.
ToolBase in AgentScope is an abstract base class. To define a custom tool, implement:- Class attributes:
name,description,input_schema(in JSON Schema format) - Class attributes:
is_concurrency_safe,is_read_only(for permission & concurrency control) check_permissions()method (returningPermissionDecision; search tools default toALLOW)call()method (an async generator that yieldsToolChunks)
Step 4: Assemble and Run the Agent
Assemble an AgentScope agent using DashScopeChatModel + KnowledgeStudioRAGMiddleware, demonstrating end-to-end execution for both modes.
Initialize Model and Agent
Mode 1: Static Injection
on_system_prompt. The middleware automatically retrieves and appends results to the system_prompt, transparent to the model.
Mode 2: Agentic Autonomous Retrieval
search_knowledge.
Combining Both Modes
AgentScope supports attaching multiple middleware instances with different modes—enabling both automatic injection and on-demand tool access:
Mode Comparison & Selection Guidance
| Dimension | static Injection | agentic Retrieval | Combined Mode |
|---|---|---|---|
| Retrieval Decision | Fixed (every inference) | Autonomous (on-demand) | Both |
| AgentScope Hook | on_system_prompt | list_tools | Both hooks used |
| Context Length | Injects top_k chunks per inference | Tool results enter context only when invoked | Both contribute |
| Multi-turn Retrieval | Not supported (one-time retrieval) | Supported (model may call tool multiple times) | Supported |
| Ideal Use Case | FAQ-style Q&A, clear intent | Complex queries requiring judgment | High-reliability scenarios |
Alignment with Built-in RAGMiddleware | Consistent design (static mode) | Consistent design (agentic mode) | Consistent design |
This custom middleware follows the same design principles and parameter naming (
mode, top_k) as AgentScope’s built-in RAGMiddleware. The key difference lies in the retrieval backend: the built-in version relies on local KnowledgeBase (embedding model + vector DB), whereas this implementation directly calls the Knowledge Studio knowledge search API.Extension: Integration with AgentScope Persistent State
AgentScope’s AgentState can be serialized to JSON and stored in Redis for cross-session state recovery. The knowledge base ID is persisted alongside the agent as part of the middleware configuration:
Knowledge Studio retrieval is stateless—each call is independent, and the service does not retain conversation context. Conversation history is managed entirely by AgentScope’s
AgentState, decoupled from knowledge retrieval. For multi-turn tool history handling, see the Multi-Turn Chat Cookbook.update_session_state only updates existing sessions. On first use, you must call upsert_session to initialize the session record—otherwise a KeyError will be raised.Frequently Asked Questions
Why not use AgentScope’s built-in RAGMiddleware?
The built-in RAGMiddleware depends on local KnowledgeBase objects, requiring local embedding models and vector databases. Knowledge Studio is a fully managed service—embedding, vector storage, and retrieval happen entirely server-side. This custom middleware bypasses local infrastructure entirely by calling the knowledge search API directly.
Won’t static mode be too slow if it retrieves every time?
Typical latency for Knowledge Studio’s knowledge search API is 200–500 ms. For latency-sensitive applications, switch to agentic mode (on-demand retrieval) or reduce top_k. Empirically, with top_k=3, static-mode agent response time (including model generation) stays within 3–5 seconds.
What if the model doesn’t invoke the tool in agentic mode?
Ensure the system_prompt explicitly instructs: “You may call the search_knowledge tool to retrieve from the knowledge base.” Empirically, qwen-plus reliably invokes the tool when questions reference knowledge-base content. If not, try a stronger model (e.g., qwen-max).
Can I use Knowledge Studio’s knowledge/chat API alongside AgentScope?
Yes—but they’re mutually exclusive alternatives, not complementary. Knowledge Studio’s knowledge/chat is a managed agent service ideal for users who don’t want to build their own agents. AgentScope is a framework for building highly customizable agents—with custom toolchains, middleware, and human-in-the-loop interactions.