Python API
RAGFlow Python API 的完整参考。在继续之前,请确保您已准备好 RAGFlow API 密钥进行身份验证。
运行以下命令下载 Python SDK:
pip install ragflow-sdk
错误代码
| 代码 | 消息 | 描述 |
|---|---|---|
| 400 | 错误请求 | 无效的请求参数 |
| 401 | 未授权 | 未授权访问 |
| 403 | 禁止 | 访问被拒绝 |
| 404 | 未找到 | 资源未找到 |
| 500 | 内部服务器错误 | 服务器内部错误 |
| 1001 | 无效的块 ID | 无效的块 ID |
| 1002 | 块更新失败 | 块更新失败 |
OpenAI 兼容 API
创建聊天完成
通过 OpenAI API 为给定的历史聊天对话创建模型响应。
参数
model: str,必需
用于生成响应的模型。服务器会自动解析此参数,因此您可以暂时将其设置为任何值。
messages: list[object],必需
用于生成响应的历史聊天消息列表。此列表必须包含至少一条 user 角色的消息。
stream: boolean
是否以流的形式接收响应。如果您希望一次性接收整个响应而不是流式响应,请将此参数显式设置为 false。
返回值
- 成功:类似 OpenAI 的响应消息
- 失败:
Exception
Examples
from openai import OpenAI
model = "model"
client = OpenAI(api_key="ragflow-api-key", base_url=f"http://ragflow_address/api/v1/chats_openai/<chat_id>")
stream = True
reference = True
completion = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who are you?"},
{"role": "assistant", "content": "I am an AI assistant named..."},
{"role": "user", "content": "Can you tell me how to install neovim"},
],
stream=stream,
extra_body={"reference": reference}
)
if stream:
for chunk in completion:
print(chunk)
if reference and chunk.choices[0].finish_reason == "stop":
print(f"Reference:\n{chunk.choices[0].delta.reference}")
print(f"Final content:\n{chunk.choices[0].delta.final_content}")
else:
print(completion.choices[0].message.content)
if reference:
print(completion.choices[0].message.reference)
知识库管理
创建知识库
RAGFlow.create_dataset(
name: str,
avatar: Optional[str] = None,
description: Optional[str] = None,
embedding_model: Optional[str] = "BAAI/bge-large-zh-v1.5@BAAI",
permission: str = "me",
chunk_method: str = "naive",
parser_config: DataSet.ParserConfig = None
) -> DataSet
创建知识库。
参数
name: str,必需
要创建的数据集的唯一名称。必须遵守以下要求:
- 最多 128 个字符。
- 不区分大小写。
avatar: str
头像的 Base64 编码。默认为 None
description: str
要创建的数据集的简要描述。默认为 None。
permission
指定谁可以访问要创建的数据集。可用选项:
"me":(默认)只有您可以管理数据集。"team":所有团队成员都可以管理数据集。
chunk_method, str
要创建的数据集的分块方法。可用选项:
"naive":通用(默认)"manual":手动"qa":问答"table":表格"paper":论文"book":书籍"laws":法律"presentation":演示文稿"picture":图片"one":单个"email":邮件
parser_config
数据集的解析器配置。ParserConfig 对象的属性根据选定的 chunk_method 而变化:
chunk_method="naive":
{"chunk_token_num":512,"delimiter":"\\n","html4excel":False,"layout_recognize":True,"raptor":{"use_raptor":False}}.chunk_method="qa":
{"raptor": {"use_raptor": False}}chunk_method="manuel":
{"raptor": {"use_raptor": False}}chunk_method="table":
Nonechunk_method="paper":
{"raptor": {"use_raptor": False}}chunk_method="book":
{"raptor": {"use_raptor": False}}chunk_method="laws":
{"raptor": {"use_raptor": False}}chunk_method="picture":
Nonechunk_method="presentation":
{"raptor": {"use_raptor": False}}chunk_method="one":
Nonechunk_method="knowledge-graph":
{"chunk_token_num":128,"delimiter":"\\n","entity_types":["organization","person","location","event","time"]}chunk_method="email":
None
返回值
- 成功:一个
dataset对象。 - 失败:
Exception
Examples
from ragflow_sdk import RAGFlow
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
dataset = rag_object.create_dataset(name="kb_1")
删除知识库
RAGFlow.delete_datasets(ids: list[str] | None = None)
按 ID 删除知识库。
参数
ids: list[str] 或 None,必需
要删除的数据集 ID。默认为 None。
- 如果为
None,将删除所有数据集。 - 如果是 ID 数组,只删除指定的数据集。
- 如果是空数组,不删除任何数据集。
返回值
- 成功:不返回值。
- 失败:
Exception
Examples
rag_object.delete_datasets(ids=["d94a8dc02c9711f0930f7fbc369eab6d","e94a8dc02c9711f0930f7fbc369eab6e"])
列出知识库
RAGFlow.list_datasets(
page: int = 1,
page_size: int = 30,
orderby: str = "create_time",
desc: bool = True,
id: str = None,
name: str = None
) -> list[DataSet]
列出知识库。
参数
page: int
指定数据集将显示在哪一页。默认为 1。
page_size: int
每页的数据集数量。默认为 30。
orderby: str
数据集排序的字段。可用选项:
"create_time"(默认)"update_time"
desc: bool
指示检索到的数据集是否应按降序排列。默认为 True。
id: str
要检索的数据集 ID。默认为 None。
name: str
要检索的数据集名称。默认为 None。
返回值
- 成功:
DataSet对象列表。 - 失败:
Exception。
示例
列出所有数据集
for dataset in rag_object.list_datasets():
print(dataset)
按 ID 检索数据集
dataset = rag_object.list_datasets(id = "id_1")
print(dataset[0])
更新知识库
DataSet.update(update_message: dict)
更新当前知识库的配置。
Parameters
update_message: dict[str, str|int], Required
A dictionary representing the attributes to update, with the following keys:
"name":strThe revised name of the dataset.- Basic Multilingual Plane (BMP) only
- Maximum 128 characters
- Case-insensitive
"avatar": (Body parameter),string
The updated base64 encoding of the avatar.- Maximum 65535 characters
"embedding_model": (Body parameter),string
The updated embedding model name.- Ensure that
"chunk_count"is0before updating"embedding_model". - Maximum 255 characters
- Must follow
model_name@model_factoryformat
- Ensure that
"permission": (Body parameter),string
The updated dataset permission. Available options:"me": (Default) Only you can manage the dataset."team": All team members can manage the dataset.
"pagerank": (Body parameter),int
refer to Set page rank- Default:
0 - Minimum:
0 - Maximum:
100
- Default:
"chunk_method": (Body parameter),enum<string>
The chunking method for the dataset. Available options:"naive": General (default)"book": Book"email": Email"laws": Laws"manual": Manual"one": One"paper": Paper"picture": Picture"presentation": Presentation"qa": Q&A"table": Table"tag": Tag
Returns
- Success: No value is returned.
- Failure:
Exception
Examples
from ragflow_sdk import RAGFlow
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
dataset = rag_object.list_datasets(name="kb_name")
dataset = dataset[0]
dataset.update({"embedding_model":"BAAI/bge-zh-v1.5", "chunk_method":"manual"})
知识库内文件管理
上传文档
DataSet.upload_documents(document_list: list[dict])
将文档上传到当前知识库。
参数
document_list: list[dict],必需
表示要上传的文档的字典列表,每个字典包含以下键:
"display_name":(可选)在数据集中显示的文件名。"blob":(可选)要上传的文件的二进制内容。
Returns
- Success: No value is returned.
- Failure:
Exception
Examples
dataset = rag_object.create_dataset(name="kb_name")
dataset.upload_documents([{"display_name": "1.txt", "blob": "<BINARY_CONTENT_OF_THE_DOC>"}, {"display_name": "2.pdf", "blob": "<BINARY_CONTENT_OF_THE_DOC>"}])
更新文档
Document.update(update_message:dict)
更新当前文档的配置。
参数
update_message: dict[str, str|dict[]],必需
表示要更新的属性的字典,具有以下键:
"display_name":str要更新的文档名称。"meta_fields":dict[str, Any]文档的元字段。"chunk_method":str应用于文档的解析方法。"naive":通用"manual":手动"qa":问答"table":表格"paper":论文"book":书籍"laws":法律"presentation":演示文稿"picture":图片"one":单个"email":邮件
"parser_config":dict[str, Any]文档的解析配置。其属性根据选定的"chunk_method"而变化:"chunk_method"="naive":
{"chunk_token_num":128,"delimiter":"\\n","html4excel":False,"layout_recognize":True,"raptor":{"use_raptor":False}}.chunk_method="qa":
{"raptor": {"use_raptor": False}}chunk_method="manuel":
{"raptor": {"use_raptor": False}}chunk_method="table":
Nonechunk_method="paper":
{"raptor": {"use_raptor": False}}chunk_method="book":
{"raptor": {"use_raptor": False}}chunk_method="laws":
{"raptor": {"use_raptor": False}}chunk_method="presentation":
{"raptor": {"use_raptor": False}}chunk_method="picture":
Nonechunk_method="one":
Nonechunk_method="knowledge-graph":
{"chunk_token_num":128,"delimiter":"\\n","entity_types":["organization","person","location","event","time"]}chunk_method="email":
None
Returns
- Success: No value is returned.
- Failure:
Exception
Examples
from ragflow_sdk import RAGFlow
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
dataset = rag_object.list_datasets(id='id')
dataset = dataset[0]
doc = dataset.list_documents(id="wdfxb5t547d")
doc = doc[0]
doc.update([{"parser_config": {"chunk_token_num": 256}}, {"chunk_method": "manual"}])
下载文档
Document.download() -> bytes
下载当前文档。
返回值
下载的文档(字节格式)。
Examples
from ragflow_sdk import RAGFlow
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
dataset = rag_object.list_datasets(id="id")
dataset = dataset[0]
doc = dataset.list_documents(id="wdfxb5t547d")
doc = doc[0]
open("~/ragflow.txt", "wb+").write(doc.download())
print(doc)
列出文档
Dataset.list_documents(
id: str = None,
keywords: str = None,
page: int = 1,
page_size: int = 30,
order_by: str = "create_time",
desc: bool = True,
create_time_from: int = 0,
create_time_to: int = 0
) -> list[Document]
列出当前知识库中的文档。
参数
id: str
要检索的文档 ID。默认为 None。
keywords: str
用于匹配文档标题的关键词。默认为 None。
page: int
指定文档将显示在哪一页。默认为 1。
page_size: int
每页的最大文档数。默认为 30。
orderby: str
文档排序的字段。可用选项:
"create_time"(默认)"update_time"
desc: bool
指示检索到的文档是否应按降序排列。默认为 True。
create_time_from: int
用于过滤在此时间之后创建的文档的 Unix 时间戳。0 表示无过滤。默认为 0。
create_time_to: int
用于过滤在此时间之前创建的文档的 Unix 时间戳 。0 表示无过滤。默认为 0。
返回值
- 成功:
Document对象列表。 - 失败:
Exception。
Document 对象包含以下属性:
id:文档 ID。默认为""。name:文档名称。默认为""。thumbnail:文档的缩略图。默认为None。dataset_id:与文档关联的数据集 ID。默认为None。chunk_method:分块方法名称。默认为"naive"。source_type:文档的源类型。默认为"local"。type:文档的类型或类别。默认为""。保留供未来使用。created_by:str文档的创建者。默认为""。size:int文档大小(字节)。默认为0。token_count:int文档中的令牌数。默认为0。chunk_count:int文档中的块数。默认为0。progress:float当前处理进度(百分比)。默认为0.0。progress_msg:str指示当前进度状态的消息。默认为""。process_begin_at:datetime文档处理的开始时间。默认为None。process_duration:float处理持续时间(秒)。默认为0.0。run:str文档的 处理状态:"UNSTART"(默认)"RUNNING""CANCEL""DONE""FAIL"
status:str保留供未来使用。parser_config:ParserConfigConfiguration object for the parser. Its attributes vary based on the selectedchunk_method:chunk_method="naive":
{"chunk_token_num":128,"delimiter":"\\n","html4excel":False,"layout_recognize":True,"raptor":{"use_raptor":False}}.chunk_method="qa":
{"raptor": {"use_raptor": False}}chunk_method="manuel":
{"raptor": {"use_raptor": False}}chunk_method="table":
Nonechunk_method="paper":
{"raptor": {"use_raptor": False}}chunk_method="book":
{"raptor": {"use_raptor": False}}chunk_method="laws":
{"raptor": {"use_raptor": False}}chunk_method="presentation":
{"raptor": {"use_raptor": False}}chunk_method="picure":
Nonechunk_method="one":
Nonechunk_method="email":
None
Examples
from ragflow_sdk import RAGFlow
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
dataset = rag_object.create_dataset(name="kb_1")
filename1 = "~/ragflow.txt"
blob = open(filename1 , "rb").read()
dataset.upload_documents([{"name":filename1,"blob":blob}])
for doc in dataset.list_documents(keywords="rag", page=0, page_size=12):
print(doc)
删除文档
DataSet.delete_documents(ids: list[str] = None)
按 ID 删除文档。
参数
ids: list[list]
要删除的文档 ID。默认为 None。如果未指定,将删除数据集中的所有文档。
Returns
- Success: No value is returned.
- Failure:
Exception
Examples
from ragflow_sdk import RAGFlow
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
dataset = rag_object.list_datasets(name="kb_1")
dataset = dataset[0]
dataset.delete_documents(ids=["id_1","id_2"])
解析文档
DataSet.async_parse_documents(document_ids:list[str]) -> None
解析当前知识库中的文档。
参数
document_ids: list[str],必需
要解析的文档 ID。
Returns
- Success: No value is returned.
- Failure:
Exception
Examples
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
dataset = rag_object.create_dataset(name="dataset_name")
documents = [
{'display_name': 'test1.txt', 'blob': open('./test_data/test1.txt',"rb").read()},
{'display_name': 'test2.txt', 'blob': open('./test_data/test2.txt',"rb").read()},
{'display_name': 'test3.txt', 'blob': open('./test_data/test3.txt',"rb").read()}
]
dataset.upload_documents(documents)
documents = dataset.list_documents(keywords="test")
ids = []
for document in documents:
ids.append(document.id)
dataset.async_parse_documents(ids)
print("Async bulk parsing initiated.")
停止解析文档
DataSet.async_cancel_parse_documents(document_ids:list[str])-> None
停止解析指定文档。
参数
document_ids: list[str],必需
应停止解析的文档 ID。
Returns
- Success: No value is returned.
- Failure:
Exception
Examples
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
dataset = rag_object.create_dataset(name="dataset_name")
documents = [
{'display_name': 'test1.txt', 'blob': open('./test_data/test1.txt',"rb").read()},
{'display_name': 'test2.txt', 'blob': open('./test_data/test2.txt',"rb").read()},
{'display_name': 'test3.txt', 'blob': open('./test_data/test3.txt',"rb").read()}
]
dataset.upload_documents(documents)
documents = dataset.list_documents(keywords="test")
ids = []
for document in documents:
ids.append(document.id)
dataset.async_parse_documents(ids)
print("Async bulk parsing initiated.")
dataset.async_cancel_parse_documents(ids)
print("Async bulk parsing cancelled.")
知识库内块管理
添加块
Document.add_chunk(content:str, important_keywords:list[str] = []) -> Chunk
向当前文档添加块。
参数
content: str,必需
块的文本内容。
important_keywords: list[str]
要与块关联的关键词或短语。
返回值
- 成功:一个
Chunk对象。 - 失败:
Exception。
Chunk 对象包含以下属性:
id:str:块 ID。content:str块的文本内容。important_keywords:list[str]与块关联的关键词或短语列表。create_time:str块创建(添加到文档)的时间。create_timestamp:float表示块创建时间的时间戳,以 1970 年 1 月 1 日以来的秒数表示。dataset_id:str关联数据集的 ID。document_name:str关联文档的名称。document_id:str关联文档的 ID。available:bool块在数据集中的可用性状态。值选项:False:不可用True:可用(默认)
Examples
from ragflow_sdk import RAGFlow
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
datasets = rag_object.list_datasets(id="123")
dataset = datasets[0]
doc = dataset.list_documents(id="wdfxb5t547d")
doc = doc[0]
chunk = doc.add_chunk(content="xxxxxxx")