Los modelos de lenguaje grandes (LLM) no pueden responder preguntas sobre datos privados. La herramienta de recuperación de conocimientos recupera contenido de una base de conocimientos y lo proporciona al LLM. Esto permite que el modelo genere respuestas más precisas y relevantes.
Requisitos previos
-
Obtenga una clave de API y configúrela como variable de entorno.
-
Cree una base de conocimientos y obtenga su ID. Puede crear una base de conocimientos de una de las siguientes maneras:
-
Crear en la consola: Cree una base de conocimientos en la página de bases de conocimientos en la consola de Model Studio. Para más información, consulte Crear y utilizar una base de conocimientos.
-
Crear mediante la API: Puede invocar la API a través del kit de desarrollo de software (SDK) de Alibaba Cloud Model Studio para crear una base de conocimientos. Para más información, consulte la Guía de la API de base de conocimientos.
Antes de crear una base de conocimientos mediante la API, obtenga el ID del espacio de trabajo (
workspace_id) desde la consola de Model Studio. Solo se admiten dos tipos de bases de conocimientos: búsqueda de documentos y consulta de datos. Estos tipos son adecuados para pares básicos de preguntas y respuestas de documentos y no admiten respuestas con texto enriquecido o imágenes.
Puede encontrar el ID de la base de conocimientos en la página de detalles de la base de conocimientos en la consola de Model Studio.
-
Cómo usar
Puede invocar la función de recuperación de conocimientos a través de la Responses API agregando la herramienta file_search al parámetro tools y especificando el ID de la base de conocimientos en el parámetro vector_store_ids.
Antes de comenzar, cree y utilice una base de conocimientos y obtenga su ID. Actualmente, el parámetro
vector_store_idssolo admite un ID de base de conocimientos.
# Dependency imports and client creation are omitted here. For the complete runnable code, see "Getting started" below.
response = client.responses.create(
model="qwen3.8-max",
input="Tell me about the Alibaba Cloud Model Studio X1 phone",
tools=[
{
"type": "file_search",
# Replace this with your knowledge base ID. Only one is currently supported.
"vector_store_ids": ["your_knowledge_base_id"]
}
]
)
print(response.output_text)
Modelos admitidos
- Qwen-Max: serie Qwen3.8-Max y serie Qwen3.7-Max
- Qwen-Plus: serie Qwen3.7-Plus, serie Qwen3.6-Plus y serie Qwen3.5-Plus
- Qwen-Flash: serie Qwen3.7-Flash, serie Qwen3.6-Flash y serie Qwen3.5-Flash
- Serie de código abierto Qwen3.8
- Serie de código abierto Qwen3.6 (excepto qwen3.6-27b)
- Serie de código abierto Qwen3.5
Esta función solo se puede invocar a través de la Responses API.
Introducción
Ejecute el siguiente código para invocar la herramienta de recuperación de conocimientos a través de la Responses API. La herramienta recupera contenido relevante de la base de conocimientos especificada para generar una respuesta.
Reemplace
vector_store_idsen el código de ejemplo con su ID de base de conocimientos.
AdvertenciaAsegúrese de pasar un ID de base de conocimientos válido. Si pasa una matriz vacía o un ID no válido, la herramienta de recuperación de conocimientos no funcionará. El modelo utilizará entonces su propio conocimiento para generar una respuesta y no devolverá un error.
import os
from openai import OpenAI
client = OpenAI(
# If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx" (not recommended)
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
response = client.responses.create(
model="qwen3.8-max",
input="Tell me about the Alibaba Cloud Model Studio X1 phone",
tools=[
{
"type": "file_search",
# Replace this with your knowledge base ID. Only one is currently supported.
"vector_store_ids": ["your_knowledge_base_id"]
}
]
)
print("[Model Response]")
print(response.output_text)
print(f"\n[Token Usage] Input: {response.usage.input_tokens}, Output: {response.usage.output_tokens}, Total: {response.usage.total_tokens}")
import OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
// If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
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: "Tell me about the Alibaba Cloud Model Studio X1 phone",
tools: [
{
type: "file_search",
// Replace this with your knowledge base ID. Only one is currently supported.
vector_store_ids: ["your_knowledge_base_id"]
}
]
});
console.log("[Model Response]");
console.log(response.output_text);
const usage = response.usage;
console.log(`\n[Token Usage] Input: ${usage.input_tokens}, Output: ${usage.output_tokens}, Total: ${usage.total_tokens}`);
}
main();
# The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
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": "Tell me about the Alibaba Cloud Model Studio X1 phone",
"tools": [
{
"type": "file_search",
"vector_store_ids": ["your_knowledge_base_id"]
}
]
}'
Ejecutar el código devuelve una respuesta similar a la siguiente:
[Model Response]
Based on the content in the knowledge base, the key points of this product include the following:
1. **Core features**: The product provides...
2. **Scenarios**: Suitable for...
3. **Technical attributes**: Based on...
...
[Token Usage] Input: 1568, Output: 1724, Total: 3292
Salida por secuencias
La herramienta de recuperación de conocimientos realiza una búsqueda semántica en la base de conocimientos, lo cual puede tardar algún tiempo en procesarse. Puede habilitar la salida en streaming para obtener resultados intermedios en tiempo real.
import os
from openai import OpenAI
client = OpenAI(
# If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx" (not recommended)
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)
stream = client.responses.create(
model="qwen3.8-max",
input="Tell me about the Alibaba Cloud Model Studio X1 phone",
tools=[
{
"type": "file_search",
# Replace this with your knowledge base ID. Only one is currently supported.
"vector_store_ids": ["your_knowledge_base_id"]
}
],
stream=True
)
for event in stream:
# The model response starts
if event.type == "response.content_part.added":
print("[Model Response]")
# Print the model response in a stream
elif event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
# When the response is complete, print the token usage
elif event.type == "response.completed":
usage = event.response.usage
print(f"\n\n[Token Usage] Input: {usage.input_tokens}, Output: {usage.output_tokens}, Total: {usage.total_tokens}")
import OpenAI from "openai";
import process from 'process';
const openai = new OpenAI({
// If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
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: "Tell me about the Alibaba Cloud Model Studio X1 phone",
tools: [
{
type: "file_search",
// Replace this with your knowledge base ID. Only one is currently supported.
vector_store_ids: ["your_knowledge_base_id"]
}
],
stream: true
});
for await (const event of stream) {
// The model response starts
if (event.type === "response.content_part.added") {
console.log("[Model Response]");
}
// Print the model response in a stream
else if (event.type === "response.output_text.delta") {
process.stdout.write(event.delta);
}
// When the response is complete, print the token usage
else if (event.type === "response.completed") {
const usage = event.response.usage;
console.log(`\n\n[Token Usage] Input: ${usage.input_tokens}, Output: ${usage.output_tokens}, Total: ${usage.total_tokens}`);
}
}
}
main();
# The following URL is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
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": "Tell me about the Alibaba Cloud Model Studio X1 phone",
"tools": [
{
"type": "file_search",
"vector_store_ids": ["your_knowledge_base_id"]
}
],
"stream": true
}'
Parámetros
La herramienta file_search admite los siguientes parámetros:
| Parámetro | Obligatorio | Descripción |
|---|---|---|
| Sí | Debe establecerse en |
| Sí | Una lista de IDs de bases de conocimientos. Actualmente, solo puede pasar un ID de base de conocimientos. Puede encontrar el ID de la base de conocimientos en la página de detalles de la base de conocimientos en la consola de Model Studio u obtenerlo al crear una base de conocimientos mediante la API.
|
Facturación
La facturación implica los siguientes aspectos:
- Tarifas por llamada de modelo: El contenido recuperado de la base de conocimientos se agrega al prompt. Esto aumenta el número de tokens de entrada para el modelo. Se le cobra según los precios estándar del modelo. Para obtener detalles sobre los precios, consulte la consola de Model Studio.
- Tarifas por llamada de herramienta: La función de base de conocimientos es actualmente gratuita.