Large Language Models (LLMs) cannot answer questions about private data. The knowledge retrieval tool retrieves content from a knowledge base and provides it to the LLM. This enables the model to generate more accurate and relevant answers.
Prerequisites
-
Obtain an API key and configure it as an environment variable.
-
Create a knowledge base and obtain its ID. You can create a knowledge base in one of the following ways:
-
Create in the console: Create a knowledge base on the knowledge base page in the Model Studio console. For more information, see Create and use a knowledge base.
-
Create using the API: You can call the API through the Alibaba Cloud Model Studio software development kit (SDK) to create a knowledge base. For more information, see Knowledge Base API Guide.
Before creating a knowledge base via API, you must first obtain the workspace ID (workspace_id). For how to obtain it, see Obtain the App ID and Workspace ID. Only two types of knowledge bases are supported: document search and data query; this feature is applicable to basic document Q&A and does not support responses combining text and images.
You can find the knowledge base ID on the knowledge base details page in the Model Studio console.
-
How to use
You can call the knowledge retrieval feature through the Responses API by adding the file_search tool to the tools parameter and specifying the knowledge base ID in the vector_store_ids parameter.
Before you start, create and use a knowledge base and obtain its ID. Currently, the
vector_store_idsparameter supports only one knowledge base ID.
# 此处省略依赖导入与创建客户端步骤,完整可运行代码请参见下文「快速开始」
response = client.responses.create(
model="qwen3.8-max",
input="介绍一下阿里云百炼X1手机",
tools=[
{
"type": "file_search",
# 替换为您的知识库 ID,当前仅支持一个
"vector_store_ids": ["your_knowledge_base_id"]
}
]
)
print(response.output_text)
Supported models
- Qwen-Max: qwen4-max, Qwen3.8-Max series and Qwen3.7-Max series
- Qwen-Plus: Qwen3.7-Plus series, Qwen3.6-Plus series, and Qwen3.5-Plus series
- Qwen-Flash: Qwen3.7-Flash series, Qwen3.6-Flash series and Qwen3.5-Flash series
- Qwen3.8 open-source series
- Qwen3.6 open-source series (except qwen3.6-27b)
- Qwen3.5 open source series
This feature can only be called through the Responses API.
Getting started
Run the following code to call the knowledge retrieval tool through the Responses API. The tool retrieves relevant content from the specified knowledge base to generate a response.
Replace
vector_store_idsin the sample code with your knowledge base ID.
WarningMake sure to pass a valid knowledge base ID. If you pass an empty array or an invalid ID, the knowledge retrieval tool does not work. The model then uses its own knowledge to generate a response and does not return an error.
import os
from openai import OpenAI
client = OpenAI(
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"(不建议),
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
response = client.responses.create(
model="qwen3.8-max",
input="介绍一下阿里云百炼X1手机",
tools=[
{
"type": "file_search",
# 替换为您的知识库 ID,当前仅支持一个
"vector_store_ids": ["your_knowledge_base_id"]
}
]
)
print("[模型回复]")
print(response.output_text)
print(f"\n[Token 用量] 输入: {response.usage.input_tokens}, 输出: {response.usage.output_tokens}, 合计: {response.usage.total_tokens}")
import OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
// 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
});
async function main() {
const response = await openai.responses.create({
model: "qwen3.8-max",
input: "介绍一下阿里云百炼X1手机",
tools: [
{
type: "file_search",
// 替换为您的知识库 ID,当前仅支持一个
vector_store_ids: ["your_knowledge_base_id"]
}
]
});
console.log("[模型回复]");
console.log(response.output_text);
const usage = response.usage;
console.log(`\n[Token 用量] 输入: ${usage.input_tokens}, 输出: ${usage.output_tokens}, 合计: ${usage.total_tokens}`);
}
main();
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-max",
"input": "介绍一下阿里云百炼X1手机",
"tools": [
{
"type": "file_search",
"vector_store_ids": ["your_knowledge_base_id"]
}
]
}'
Running the code returns a response similar to the following:
[模型回复]
根据知识库中的内容,该产品要点包括以下几个方面:
1. **核心功能**:产品提供了...
2. **适用场景**:适用于...
3. **技术特性**:基于...
...
[Token 用量] 输入: 1568, 输出: 1724, 合计: 3292
Streaming output
The knowledge retrieval tool performs a semantic search in the knowledge base, which can take some time to process. You can enable streaming output to obtain intermediate results in real time.
import os
from openai import OpenAI
client = OpenAI(
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
stream = client.responses.create(
model="qwen3.8-max",
input="介绍一下阿里云百炼X1手机",
tools=[
{
"type": "file_search",
# 替换为您的知识库 ID,当前仅支持一个
"vector_store_ids": ["your_knowledge_base_id"]
}
],
stream=True
)
for event in stream:
# 模型回复开始
if event.type == "response.content_part.added":
print("[模型回复]")
# 流式打印模型回复
elif event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
# 响应完成,打印 Token 用量
elif event.type == "response.completed":
usage = event.response.usage
print(f"\n\n[Token 用量] 输入: {usage.input_tokens}, 输出: {usage.output_tokens}, 合计: {usage.total_tokens}")
import OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
// 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
});
async function main() {
const stream = await openai.responses.create({
model: "qwen3.8-max",
input: "介绍一下阿里云百炼X1手机",
tools: [
{
type: "file_search",
// 替换为您的知识库 ID,当前仅支持一个
vector_store_ids: ["your_knowledge_base_id"]
}
],
stream: true
});
for await (const event of stream) {
// 模型回复开始
if (event.type === "response.content_part.added") {
console.log("[模型回复]");
}
// 流式打印模型回复
else if (event.type === "response.output_text.delta") {
process.stdout.write(event.delta);
}
// 响应完成,打印 Token 用量
else if (event.type === "response.completed") {
const usage = event.response.usage;
console.log(`\n\n[Token 用量] 输入: ${usage.input_tokens}, 输出: ${usage.output_tokens}, 合计: ${usage.total_tokens}`);
}
}
}
main();
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-max",
"input": "介绍一下阿里云百炼X1手机",
"tools": [
{
"type": "file_search",
"vector_store_ids": ["your_knowledge_base_id"]
}
],
"stream": true
}'
Parameters
The file_search tool supports the following parameters:
| Parameter | Required | Description |
|---|---|---|
| Yes | Must be set to |
| Yes | A list of knowledge base IDs. Currently, you can pass only one knowledge base ID. You can find the knowledge base ID on the knowledge base details page in the Model Studio console or get it when you create a knowledge base using the API.
|
Billing
Billing involves the following aspects:
- Model call fees: Content retrieved from the knowledge base is added to the prompt. This increases the number of input tokens for the model. You are charged based on the model's standard pricing. For pricing details, see the Model Studio console.
- Tool call fees: The knowledge base feature is currently free of charge.