Integrate Knowledge Studio as the knowledge memory for AgentScope agents via a custom middleware, supporting both static injection and agentic retrieval modes
This recipe is for developers using AgentScope as the runtime for their AI agents. It demonstrates how to connect Knowledge Studio to an AgentScope Agent via a custom middleware, serving as the agent's knowledge memory. Fully code-driven, no console operations required. Code verified with AgentScope 2.0.4 + Knowledge Studio production environment.
Principle: Knowledge Base as Agent Memory
LLMs are inherently stateless — each inference is independent. AgentScope uses a middleware mechanism to inject external capabilities into agents (RAG retrieval, long-term memory, tracing, etc.) without modifying the agent's core logic.
AgentScope ships with a built-in RAGMiddleware that works with KnowledgeBase objects (wrapping a local embedding model and vector store) and injects retrieval results before reasoning. Knowledge Studio, however, is a managed service — embedding, vector storage, and retrieval all run server-side, eliminating the need for a local vector store.
This recipe implements a custom KnowledgeStudioRAGMiddleware that calls the Knowledge Studio knowledge search API directly, integrating retrieval results into the AgentScope Agent in two modes:
| Mode | When | Implementation | AgentScope Middleware Hook |
|---|---|---|---|
| static | Before first reasoning in each reply | Use user message as query, inject results into system prompt | on_system_prompt |
| agentic | Model decides | Expose search_knowledge tool, agent calls autonomously | list_tools |
AgentScope middleware has 6 hook positions. This recipe uses two:
on_system_prompt (Transformer type, serial pipeline modifying system prompt) and list_tools (Tool source type, declaring tools provided by the middleware). See AgentScope Middleware Docs.Prerequisites
Install Dependencies
Required Parameters
| Parameter | How to Obtain | Example |
|---|---|---|
| DashScope API Key | Create at Settings → API Key | sk-xxxxxxxx |
| Workspace ID | Business space ID from the console URL | llm-xxxxxxxx |
| Knowledge Search Service ID | Create and publish at Knowledge Service → Knowledge Search | aid-xxxxxxxx |
Step 1: Build Knowledge Base via API
Knowledge base setup (file upload → create index → import) is fully API-driven. The following wraps it into a reusable function. Full API details: Create Index and Register File.
Step 2: Wrap the Retrieval Client
Wrap the Knowledge Studio knowledge search API into a lightweight class for the middleware to call. The knowledge search API works with a published search service (agent); retrieval strategies (rerank, top_k, etc.) are configured in the console, and the API call only requires agent_id and the query.
Step 3: Implement KnowledgeStudioRAGMiddleware
This is the core of the recipe — a custom MiddlewareBase subclass implementing both static and agentic modes. Modeled after AgentScope's built-in RAGMiddleware, but with the retrieval backend changed to the Knowledge Studio API.
AgentScope's
ToolBase is an abstract base class. Custom tools need to implement:- Class attributes
name,description,input_schema(JSON Schema format) - Class attributes
is_concurrency_safe,is_read_only(permission & concurrency control) check_permissionsmethod (returnsPermissionDecision, search tools can simply ALLOW)callmethod (async generator,yield ToolChunkto return results)
Step 4: Assemble and Run the Agent
Assemble an AgentScope Agent with DashScopeChatModel + KnowledgeStudioRAGMiddleware, demonstrating both modes end-to-end.
Create Model and Agent
Mode 1: Static Injection
on_system_prompt before each ReAct reasoning step. The middleware auto-retrieves and injects results into the system prompt — the model never needs to know about the retrieval process.
Mode 2: Agentic Retrieval
Combining Both Modes
AgentScope allows mounting two instances with different modes — both auto-inject and on-demand tool:
Mode Comparison and Selection
| Dimension | Static Injection | Agentic Retrieval | Combined |
|---|---|---|---|
| Retrieval decision | Fixed (always before reasoning) | Model decides (on demand) | Both |
| AgentScope hook | on_system_prompt | list_tools | Both |
| Context length | top_k chunks injected each time | Tool results on demand | Combined |
| Multi-round retrieval | No (one-shot) | Yes (model can call tool multiple times) | Yes |
| Best for | FAQ, clear-intent queries | Complex QA, needs judgment | High-reliability |
| vs. built-in RAGMiddleware | Same design (static mode) | Same design (agentic mode) | Same design |
This custom middleware is designed to be consistent with AgentScope's built-in
RAGMiddleware — same two modes, same parameter naming (mode, top_k). The difference is the retrieval backend: the built-in RAGMiddleware works with a local KnowledgeBase (embedding model and vector store), while this middleware calls the Knowledge Studio knowledge search API directly.Extension: Integrate with AgentScope Persistent State
AgentScope's AgentState can be serialized to JSON and stored in Redis, enabling cross-session state recovery. The knowledge base ID persists as middleware configuration alongside the Agent:
Knowledge Studio retrieval is stateless — each search call is independent, the server does not preserve conversation context. Conversation history is managed by AgentScope's
AgentState, decoupled from knowledge base retrieval. For multi-turn conversation with tool history, see the Multi-Turn Chat cookbook.FAQ
Why not use AgentScope's built-in RAGMiddleware?
The built-in RAGMiddleware works with local KnowledgeBase objects, requiring a local embedding model and vector store. Knowledge Studio is a managed service where embedding, vector storage, and retrieval all run server-side. This middleware calls the knowledge search API directly, eliminating the need to deploy and maintain a local vector store.
Is static mode too slow (retrieves every reasoning step)?
The Knowledge Studio knowledge search API typically responds in 200-500ms. If latency is a concern, switch to agentic mode for on-demand retrieval, or reduce top_k. With top_k=3, the static mode Agent responds in 3-5 seconds (including model generation time).
What if the model doesn't call the tool in agentic mode?
Ensure the system prompt explicitly mentions "you can call the search_knowledge tool to retrieve from the knowledge base." In testing, qwen-plus autonomously calls the tool when the question involves knowledge base content. If the model still doesn't call it, try a more capable model (e.g., qwen-max).