跳到主要内容

Python API

RAGFlow Python API 的完整参考。在继续之前,请确保您已准备好 RAGFlow API 密钥进行身份验证

注意

运行以下命令下载 Python SDK:

pip install ragflow-sdk

错误代码


代码消息描述
400Bad Request无效的请求参数
401Unauthorized未授权访问
403Forbidden访问被拒绝
404Not Found资源未找到
500Internal Server Error服务器内部错误
1001Invalid Chunk ID无效的块 ID
1002Chunk Update Failed块更新失败

OpenAI 兼容 API


创建聊天完成

通过 OpenAI 的 API 为给定的历史聊天对话创建模型响应。

参数

model: str, 必填

用于生成响应的模型。服务器将自动解析此参数,因此目前您可以将其设置为任何值。

messages: list[object], 必填

用于生成响应的历史聊天消息列表。这必须包含至少一条具有 user 角色的消息。

stream: boolean

是否以流的形式接收响应。如果您希望一次性接收完整响应而不是流,请明确设置为 false

返回值

  • 成功:类似 OpenAI 的响应消息
  • 失败:Exception

示例

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":
    None
  • chunk_method="paper":
    {"raptor": {"use_raptor": False}}
  • chunk_method="book":
    {"raptor": {"use_raptor": False}}
  • chunk_method="laws":
    {"raptor": {"use_raptor": False}}
  • chunk_method="picture":
    None
  • chunk_method="presentation":
    {"raptor": {"use_raptor": False}}
  • chunk_method="one":
    None
  • chunk_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)

更新当前数据集的配置。

参数

update_message: dict[str, str|int], 必填

表示要更新的属性的字典,包含以下键:

  • "name": str 数据集的修订名称。
    • 仅支持基本多语言平面 (BMP)
    • 最多 128 个字符
    • 不区分大小写
  • "avatar": (Body 参数), string
    头像的更新 base64 编码。
    • 最多 65535 个字符
  • "embedding_model": (Body 参数), string
    更新的嵌入模型名称。
    • 确保在更新 "embedding_model" 之前 "chunk_count"0
    • 最多 255 个字符
    • 必须遵循 model_name@model_factory 格式
  • "permission": (Body 参数), string
    更新的数据集权限。可用选项:
    • "me":(默认)仅您可以管理数据集。
    • "team":所有团队成员都可以管理数据集。
  • "pagerank": (Body 参数), int
    参考设置页面排名
    • 默认:0
    • 最小:0
    • 最大:100
  • "chunk_method": (Body 参数), enum<string>
    数据集的分块方法。可用选项:
    • "naive":通用(默认)
    • "book":书籍
    • "email":电子邮件
    • "laws":法律
    • "manual":手动
    • "one":单一
    • "paper":论文
    • "picture":图片
    • "presentation":演示文稿
    • "qa":问答
    • "table":表格
    • "tag":标签

返回值

  • 成功:不返回任何值。
  • 失败: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":(可选)要上传的文件的二进制内容。

返回值

  • 成功:不返回任何值。
  • 失败: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":
      None
    • chunk_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":
      None
    • chunk_method="one":
      None
    • chunk_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]

列出当前数据集中的文档。

Parameters

id: str

The ID of the document to retrieve. Defaults to None.

keywords: str

The keywords used to match document titles. Defaults to None.

page: int

Specifies the page on which the documents will be displayed. Defaults to 1.

page_size: int

The maximum number of documents on each page. Defaults to 30.

orderby: str

The field by which documents should be sorted. Available options:

  • "create_time" (default)
  • "update_time"
desc: bool

Indicates whether the retrieved documents should be sorted in descending order. Defaults to True.

create_time_from: int

Unix timestamp for filtering documents created after this time. 0 means no filter. Defaults to 0.

create_time_to: int

Unix timestamp for filtering documents created before this time. 0 means no filter. Defaults to 0.

Returns

  • Success: A list of Document objects.
  • Failure: Exception.

A Document object contains the following attributes:

  • id: The document ID. Defaults to "".
  • name: The document name. Defaults to "".
  • thumbnail: The thumbnail image of the document. Defaults to None.
  • dataset_id: The dataset ID associated with the document. Defaults to None.
  • chunk_method The chunking method name. Defaults to "naive".
  • source_type: The source type of the document. Defaults to "local".
  • type: Type or category of the document. Defaults to "". Reserved for future use.
  • created_by: str The creator of the document. Defaults to "".
  • size: int The document size in bytes. Defaults to 0.
  • token_count: int The number of tokens in the document. Defaults to 0.
  • chunk_count: int The number of chunks in the document. Defaults to 0.
  • progress: float The current processing progress as a percentage. Defaults to 0.0.
  • progress_msg: str A message indicating the current progress status. Defaults to "".
  • process_begin_at: datetime The start time of document processing. Defaults to None.
  • process_duration: float Duration of the processing in seconds. Defaults to 0.0.
  • run: str The document's processing status:
    • "UNSTART" (default)
    • "RUNNING"
    • "CANCEL"
    • "DONE"
    • "FAIL"
  • status: str Reserved for future use.
  • parser_config: ParserConfig Configuration object for the parser. Its attributes vary based on the selected 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":
      None
    • chunk_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":
      None
    • chunk_method="one":
      None
    • chunk_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 删除文档。

Parameters

ids: list[list]

The IDs of the documents to delete. Defaults to None. If it is not specified, all documents in the dataset will be deleted.

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

解析当前数据集中的文档。

Parameters

document_ids: list[str], Required

The IDs of the documents to parse.

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

停止解析指定文档。

Parameters

document_ids: list[str], Required

The IDs of the documents for which parsing should be stopped.

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

向当前文档添加块。

Parameters

content: str, Required

The text content of the chunk.

important_keywords: list[str]

The key terms or phrases to tag with the chunk.

Returns

  • Success: A Chunk object.
  • Failure: Exception.

A Chunk object contains the following attributes:

  • id: str: The chunk ID.
  • content: str The text content of the chunk.
  • important_keywords: list[str] A list of key terms or phrases tagged with the chunk.
  • create_time: str The time when the chunk was created (added to the document).
  • create_timestamp: float The timestamp representing the creation time of the chunk, expressed in seconds since January 1, 1970.
  • dataset_id: str The ID of the associated dataset.
  • document_name: str The name of the associated document.
  • document_id: str The ID of the associated document.
  • available: bool The chunk's availability status in the dataset. Value options:
    • False: Unavailable
    • True: Available (default)

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")

列出块

Document.list_chunks(keywords: str = None, page: int = 1, page_size: int = 30, id : str = None) -> list[Chunk]

列出当前文档中的块。

Parameters

keywords: str

The keywords used to match chunk content. Defaults to None

page: int

Specifies the page on which the chunks will be displayed. Defaults to 1.

page_size: int

The maximum number of chunks on each page. Defaults to 30.

id: str

The ID of the chunk to retrieve. Default: None

Returns

  • Success: A list of Chunk objects.
  • 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("123")
dataset = dataset[0]
docs = dataset.list_documents(keywords="test", page=1, page_size=12)
for chunk in docs[0].list_chunks(keywords="rag", page=0, page_size=12):
print(chunk)

删除块

Document.delete_chunks(chunk_ids: list[str])

按 ID 删除块。

Parameters

chunk_ids: list[str]

The IDs of the chunks to delete. Defaults to None. If it is not specified, all chunks of the current document will be deleted.

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="123")
dataset = dataset[0]
doc = dataset.list_documents(id="wdfxb5t547d")
doc = doc[0]
chunk = doc.add_chunk(content="xxxxxxx")
doc.delete_chunks(["id_1","id_2"])

更新块

Chunk.update(update_message: dict)

更新当前块的内容或配置。

Parameters

update_message: dict[str, str|list[str]|int] Required

A dictionary representing the attributes to update, with the following keys:

  • "content": str The text content of the chunk.
  • "important_keywords": list[str] A list of key terms or phrases to tag with the chunk.
  • "available": bool The chunk's availability status in the dataset. Value options:
    • False: Unavailable
    • True: Available (default)

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="123")
dataset = dataset[0]
doc = dataset.list_documents(id="wdfxb5t547d")
doc = doc[0]
chunk = doc.add_chunk(content="xxxxxxx")
chunk.update({"content":"sdfx..."})

检索块

RAGFlow.retrieve(question:str="", dataset_ids:list[str]=None, document_ids=list[str]=None, page:int=1, page_size:int=30, similarity_threshold:float=0.2, vector_similarity_weight:float=0.3, top_k:int=1024,rerank_id:str=None,keyword:bool=False,highlight:bool=False) -> list[Chunk]

从指定数据集检索块。

Parameters

question: str, Required

The user query or query keywords. Defaults to "".

dataset_ids: list[str], Required

The IDs of the datasets to search. Defaults to None.

document_ids: list[str]

The IDs of the documents to search. Defaults to None. You must ensure all selected documents use the same embedding model. Otherwise, an error will occur.

page: int

The starting index for the documents to retrieve. Defaults to 1.

page_size: int

The maximum number of chunks to retrieve. Defaults to 30.

Similarity_threshold: float

The minimum similarity score. Defaults to 0.2.

vector_similarity_weight: float

The weight of vector cosine similarity. Defaults to 0.3. If x represents the vector cosine similarity, then (1 - x) is the term similarity weight.

top_k: int

The number of chunks engaged in vector cosine computation. Defaults to 1024.

rerank_id: str

The ID of the rerank model. Defaults to None.

keyword: bool

Indicates whether to enable keyword-based matching:

  • True: Enable keyword-based matching.
  • False: Disable keyword-based matching (default).
highlight: bool

Specifies whether to enable highlighting of matched terms in the results:

  • True: Enable highlighting of matched terms.
  • False: Disable highlighting of matched terms (default).
cross_languages: list[string]

The languages that should be translated into, in order to achieve keywords retrievals in different languages.

Returns

  • Success: A list of Chunk objects representing the document chunks.
  • 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="ragflow")
dataset = dataset[0]
name = 'ragflow_test.txt'
path = './test_data/ragflow_test.txt'
documents =[{"display_name":"test_retrieve_chunks.txt","blob":open(path, "rb").read()}]
docs = dataset.upload_documents(documents)
doc = docs[0]
doc.add_chunk(content="This is a chunk addition test")
for c in rag_object.retrieve(dataset_ids=[dataset.id],document_ids=[doc.id]):
print(c)

聊天助手管理


创建聊天助手

RAGFlow.create_chat(
name: str,
avatar: str = "",
dataset_ids: list[str] = [],
llm: Chat.LLM = None,
prompt: Chat.Prompt = None
) -> Chat

创建聊天助手。

Parameters

name: str, Required

The name of the chat assistant.

avatar: str

Base64 encoding of the avatar. Defaults to "".

dataset_ids: list[str]

The IDs of the associated datasets. Defaults to [""].

llm: Chat.LLM

The LLM settings for the chat assistant to create. Defaults to None. When the value is None, a dictionary with the following values will be generated as the default. An LLM object contains the following attributes:

  • model_name: str
    The chat model name. If it is None, the user's default chat model will be used.
  • temperature: float
    Controls the randomness of the model's predictions. A lower temperature results in more conservative responses, while a higher temperature yields more creative and diverse responses. Defaults to 0.1.
  • top_p: float
    Also known as “nucleus sampling”, this parameter sets a threshold to select a smaller set of words to sample from. It focuses on the most likely words, cutting off the less probable ones. Defaults to 0.3
  • presence_penalty: float
    This discourages the model from repeating the same information by penalizing words that have already appeared in the conversation. Defaults to 0.2.
  • frequency penalty: float
    Similar to the presence penalty, this reduces the model’s tendency to repeat the same words frequently. Defaults to 0.7.
prompt: Chat.Prompt

Instructions for the LLM to follow. A Prompt object contains the following attributes:

  • similarity_threshold: float RAGFlow employs either a combination of weighted keyword similarity and weighted vector cosine similarity, or a combination of weighted keyword similarity and weighted reranking score during retrieval. If a similarity score falls below this threshold, the corresponding chunk will be excluded from the results. The default value is 0.2.
  • keywords_similarity_weight: float This argument sets the weight of keyword similarity in the hybrid similarity score with vector cosine similarity or reranking model similarity. By adjusting this weight, you can control the influence of keyword similarity in relation to other similarity measures. The default value is 0.7.
  • top_n: int This argument specifies the number of top chunks with similarity scores above the similarity_threshold that are fed to the LLM. The LLM will only access these 'top N' chunks. The default value is 8.
  • variables: list[dict[]] This argument lists the variables to use in the 'System' field of Chat Configurations. Note that:
    • knowledge is a reserved variable, which represents the retrieved chunks.
    • All the variables in 'System' should be curly bracketed.
    • The default value is [{"key": "knowledge", "optional": True}].
  • rerank_model: str If it is not specified, vector cosine similarity will be used; otherwise, reranking score will be used. Defaults to "".
  • top_k: int Refers to the process of reordering or selecting the top-k items from a list or set based on a specific ranking criterion. Default to 1024.
  • empty_response: str If nothing is retrieved in the dataset for the user's question, this will be used as the response. To allow the LLM to improvise when nothing is found, leave this blank. Defaults to None.
  • opener: str The opening greeting for the user. Defaults to "Hi! I am your assistant, can I help you?".
  • show_quote: bool Indicates whether the source of text should be displayed. Defaults to True.
  • prompt: str The prompt content.

Returns

  • Success: A Chat object representing the chat assistant.
  • Failure: Exception

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(name="kb_1")
dataset_ids = []
for dataset in datasets:
dataset_ids.append(dataset.id)
assistant = rag_object.create_chat("Miss R", dataset_ids=dataset_ids)

更新聊天助手

Chat.update(update_message: dict)

更新当前聊天助手的配置。

Parameters

update_message: dict[str, str|list[str]|dict[]], Required

A dictionary representing the attributes to update, with the following keys:

  • "name": str The revised name of the chat assistant.
  • "avatar": str Base64 encoding of the avatar. Defaults to ""
  • "dataset_ids": list[str] The datasets to update.
  • "llm": dict The LLM settings:
    • "model_name", str The chat model name.
    • "temperature", float Controls the randomness of the model's predictions. A lower temperature results in more conservative responses, while a higher temperature yields more creative and diverse responses.
    • "top_p", float Also known as “nucleus sampling”, this parameter sets a threshold to select a smaller set of words to sample from.
    • "presence_penalty", float This discourages the model from repeating the same information by penalizing words that have appeared in the conversation.
    • "frequency penalty", float Similar to presence penalty, this reduces the model’s tendency to repeat the same words.
  • "prompt" : Instructions for the LLM to follow.
    • "similarity_threshold": float RAGFlow employs either a combination of weighted keyword similarity and weighted vector cosine similarity, or a combination of weighted keyword similarity and weighted rerank score during retrieval. This argument sets the threshold for similarities between the user query and chunks. If a similarity score falls below this threshold, the corresponding chunk will be excluded from the results. The default value is 0.2.
    • "keywords_similarity_weight": float This argument sets the weight of keyword similarity in the hybrid similarity score with vector cosine similarity or reranking model similarity. By adjusting this weight, you can control the influence of keyword similarity in relation to other similarity measures. The default value is 0.7.
    • "top_n": int This argument specifies the number of top chunks with similarity scores above the similarity_threshold that are fed to the LLM. The LLM will only access these 'top N' chunks. The default value is 8.
    • "variables": list[dict[]] This argument lists the variables to use in the 'System' field of Chat Configurations. Note that:
      • knowledge is a reserved variable, which represents the retrieved chunks.
      • All the variables in 'System' should be curly bracketed.
      • The default value is [{"key": "knowledge", "optional": True}].
    • "rerank_model": str If it is not specified, vector cosine similarity will be used; otherwise, reranking score will be used. Defaults to "".
    • "empty_response": str If nothing is retrieved in the dataset for the user's question, this will be used as the response. To allow the LLM to improvise when nothing is retrieved, leave this blank. Defaults to None.
    • "opener": str The opening greeting for the user. Defaults to "Hi! I am your assistant, can I help you?".
    • "show_quote: bool Indicates whether the source of text should be displayed Defaults to True.
    • "prompt": str The prompt content.

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")
datasets = rag_object.list_datasets(name="kb_1")
dataset_id = datasets[0].id
assistant = rag_object.create_chat("Miss R", dataset_ids=[dataset_id])
assistant.update({"name": "Stefan", "llm": {"temperature": 0.8}, "prompt": {"top_n": 8}})

删除聊天助手

RAGFlow.delete_chats(ids: list[str] = None)

按 ID 删除聊天助手。

Parameters

ids: list[str]

The IDs of the chat assistants to delete. Defaults to None. If it is empty or not specified, all chat assistants in the system will be deleted.

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")
rag_object.delete_chats(ids=["id_1","id_2"])

列出聊天助手

RAGFlow.list_chats(
page: int = 1,
page_size: int = 30,
orderby: str = "create_time",
desc: bool = True,
id: str = None,
name: str = None
) -> list[Chat]

列出聊天助手。

Parameters

page: int

Specifies the page on which the chat assistants will be displayed. Defaults to 1.

page_size: int

The number of chat assistants on each page. Defaults to 30.

orderby: str

The attribute by which the results are sorted. Available options:

  • "create_time" (default)
  • "update_time"
desc: bool

Indicates whether the retrieved chat assistants should be sorted in descending order. Defaults to True.

id: str

The ID of the chat assistant to retrieve. Defaults to None.

name: str

The name of the chat assistant to retrieve. Defaults to None.

Returns

  • Success: A list of Chat objects.
  • Failure: Exception.

Examples

from ragflow_sdk import RAGFlow

rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
for assistant in rag_object.list_chats():
print(assistant)

会话管理


与聊天助手创建会话

Chat.create_session(name: str = "New session") -> Session

与当前聊天助手创建会话。

Parameters

name: str

The name of the chat session to create.

Returns

  • Success: A Session object containing the following attributes:
    • id: str The auto-generated unique identifier of the created session.
    • name: str The name of the created session.
    • message: list[Message] The opening message of the created session. Default: [{"role": "assistant", "content": "Hi! I am your assistant, can I help you?"}]
    • chat_id: str The ID of the associated chat assistant.
  • Failure: Exception

Examples

from ragflow_sdk import RAGFlow

rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
assistant = rag_object.list_chats(name="Miss R")
assistant = assistant[0]
session = assistant.create_session()

更新聊天助手的会话

Session.update(update_message: dict)

更新当前聊天助手的当前会话。

Parameters

update_message: dict[str, Any], Required

A dictionary representing the attributes to update, with only one key:

  • "name": str The revised name of the session.

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")
assistant = rag_object.list_chats(name="Miss R")
assistant = assistant[0]
session = assistant.create_session("session_name")
session.update({"name": "updated_name"})

列出聊天助手的会话

Chat.list_sessions(
page: int = 1,
page_size: int = 30,
orderby: str = "create_time",
desc: bool = True,
id: str = None,
name: str = None
) -> list[Session]

列出与当前聊天助手关联的会话。

Parameters

page: int

Specifies the page on which the sessions will be displayed. Defaults to 1.

page_size: int

The number of sessions on each page. Defaults to 30.

orderby: str

The field by which sessions should be sorted. Available options:

  • "create_time" (default)
  • "update_time"
desc: bool

Indicates whether the retrieved sessions should be sorted in descending order. Defaults to True.

id: str

The ID of the chat session to retrieve. Defaults to None.

name: str

The name of the chat session to retrieve. Defaults to None.

Returns

  • Success: A list of Session objects associated with the current chat assistant.
  • Failure: Exception.

Examples

from ragflow_sdk import RAGFlow

rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
assistant = rag_object.list_chats(name="Miss R")
assistant = assistant[0]
for session in assistant.list_sessions():
print(session)

删除聊天助手的会话

Chat.delete_sessions(ids:list[str] = None)

按 ID 删除当前聊天助手的会话。

Parameters

ids: list[str]

The IDs of the sessions to delete. Defaults to None. If it is not specified, all sessions associated with the current chat assistant will be deleted.

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")
assistant = rag_object.list_chats(name="Miss R")
assistant = assistant[0]
assistant.delete_sessions(ids=["id_1","id_2"])

与聊天助手对话

Session.ask(question: str = "", stream: bool = False, **kwargs) -> Optional[Message, iter[Message]]

向指定的聊天助手提问以开始AI驱动的对话。

注意

在流式模式下,并非所有响应都包含引用,这取决于系统的判断。

Parameters

question: str, Required

The question to start an AI-powered conversation. Default to ""

stream: bool

Indicates whether to output responses in a streaming way:

  • True: Enable streaming (default).
  • False: Disable streaming.
**kwargs

The parameters in prompt(system).

Returns

  • A Message object containing the response to the question if stream is set to False.
  • An iterator containing multiple message objects (iter[Message]) if stream is set to True

The following shows the attributes of a Message object:

id: str

The auto-generated message ID.

content: str

The content of the message. Defaults to "Hi! I am your assistant, can I help you?".

reference: list[Chunk]

A list of Chunk objects representing references to the message, each containing the following attributes:

  • id str
    The chunk ID.
  • content str
    The content of the chunk.
  • img_id str
    The ID of the snapshot of the chunk. Applicable only when the source of the chunk is an image, PPT, PPTX, or PDF file.
  • document_id str
    The ID of the referenced document.
  • document_name str
    The name of the referenced document.
  • position list[str]
    The location information of the chunk within the referenced document.
  • dataset_id str
    The ID of the dataset to which the referenced document belongs.
  • similarity float
    A composite similarity score of the chunk ranging from 0 to 1, with a higher value indicating greater similarity. It is the weighted sum of vector_similarity and term_similarity.
  • vector_similarity float
    A vector similarity score of the chunk ranging from 0 to 1, with a higher value indicating greater similarity between vector embeddings.
  • term_similarity float
    A keyword similarity score of the chunk ranging from 0 to 1, with a higher value indicating greater similarity between keywords.

Examples

from ragflow_sdk import RAGFlow

rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
assistant = rag_object.list_chats(name="Miss R")
assistant = assistant[0]
session = assistant.create_session()

print("\n==================== Miss R =====================\n")
print("Hello. What can I do for you?")

while True:
question = input("\n==================== User =====================\n> ")
print("\n==================== Miss R =====================\n")

cont = ""
for ans in session.ask(question, stream=True):
print(ans.content[len(cont):], end='', flush=True)
cont = ans.content

与智能体创建会话

Agent.create_session(**kwargs) -> Session

与当前智能体创建会话。

Parameters

**kwargs

The parameters in begin component.

Returns

  • Success: A Session object containing the following attributes:
    • id: str The auto-generated unique identifier of the created session.
    • message: list[Message] The messages of the created session assistant. Default: [{"role": "assistant", "content": "Hi! I am your assistant, can I help you?"}]
    • agent_id: str The ID of the associated agent.
  • Failure: Exception

Examples

from ragflow_sdk import RAGFlow, Agent

rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
agent_id = "AGENT_ID"
agent = rag_object.list_agents(id = agent_id)[0]
session = agent.create_session()

与智能体对话

Session.ask(question: str="", stream: bool = False) -> Optional[Message, iter[Message]]

向指定智能体提问以开始AI驱动的对话。

注意

在流式模式下,并非所有响应都包含引用,这取决于系统的判断。

Parameters

question: str

The question to start an AI-powered conversation. Ifthe Begin component takes parameters, a question is not required.

stream: bool

Indicates whether to output responses in a streaming way:

  • True: Enable streaming (default).
  • False: Disable streaming.

Returns

  • A Message object containing the response to the question if stream is set to False
  • An iterator containing multiple message objects (iter[Message]) if stream is set to True

The following shows the attributes of a Message object:

id: str

The auto-generated message ID.

content: str

The content of the message. Defaults to "Hi! I am your assistant, can I help you?".

reference: list[Chunk]

A list of Chunk objects representing references to the message, each containing the following attributes:

  • id str
    The chunk ID.
  • content str
    The content of the chunk.
  • image_id str
    The ID of the snapshot of the chunk. Applicable only when the source of the chunk is an image, PPT, PPTX, or PDF file.
  • document_id str
    The ID of the referenced document.
  • document_name str
    The name of the referenced document.
  • position list[str]
    The location information of the chunk within the referenced document.
  • dataset_id str
    The ID of the dataset to which the referenced document belongs.
  • similarity float
    A composite similarity score of the chunk ranging from 0 to 1, with a higher value indicating greater similarity. It is the weighted sum of vector_similarity and term_similarity.
  • vector_similarity float
    A vector similarity score of the chunk ranging from 0 to 1, with a higher value indicating greater similarity between vector embeddings.
  • term_similarity float
    A keyword similarity score of the chunk ranging from 0 to 1, with a higher value indicating greater similarity between keywords.

Examples

from ragflow_sdk import RAGFlow, Agent

rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
AGENT_id = "AGENT_ID"
agent = rag_object.list_agents(id = AGENT_id)[0]
session = agent.create_session()

print("\n===== Miss R ====\n")
print("Hello. What can I do for you?")

while True:
question = input("\n===== User ====\n> ")
print("\n==== Miss R ====\n")

cont = ""
for ans in session.ask(question, stream=True):
print(ans.content[len(cont):], end='', flush=True)
cont = ans.content

列出智能体会话

Agent.list_sessions(
page: int = 1,
page_size: int = 30,
orderby: str = "update_time",
desc: bool = True,
id: str = None
) -> List[Session]

列出与当前智能体关联的会话。

Parameters

page: int

Specifies the page on which the sessions will be displayed. Defaults to 1.

page_size: int

The number of sessions on each page. Defaults to 30.

orderby: str

The field by which sessions should be sorted. Available options:

  • "create_time"
  • "update_time"(default)
desc: bool

Indicates whether the retrieved sessions should be sorted in descending order. Defaults to True.

id: str

The ID of the agent session to retrieve. Defaults to None.

Returns

  • Success: A list of Session objects associated with the current agent.
  • Failure: Exception.

Examples

from ragflow_sdk import RAGFlow

rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
AGENT_id = "AGENT_ID"
agent = rag_object.list_agents(id = AGENT_id)[0]
sessons = agent.list_sessions()
for session in sessions:
print(session)

删除智能体的会话

Agent.delete_sessions(ids: list[str] = None)

按 ID 删除智能体的会话。

Parameters

ids: list[str]

The IDs of the sessions to delete. Defaults to None. If it is not specified, all sessions associated with the agent will be deleted.

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")
AGENT_id = "AGENT_ID"
agent = rag_object.list_agents(id = AGENT_id)[0]
agent.delete_sessions(ids=["id_1","id_2"])

智能体管理


列出智能体

RAGFlow.list_agents(
page: int = 1,
page_size: int = 30,
orderby: str = "create_time",
desc: bool = True,
id: str = None,
title: str = None
) -> List[Agent]

列出智能体。

Parameters

page: int

Specifies the page on which the agents will be displayed. Defaults to 1.

page_size: int

The number of agents on each page. Defaults to 30.

orderby: str

The attribute by which the results are sorted. Available options:

  • "create_time" (default)
  • "update_time"
desc: bool

Indicates whether the retrieved agents should be sorted in descending order. Defaults to True.

id: str

The ID of the agent to retrieve. Defaults to None.

name: str

The name of the agent to retrieve. Defaults to None.

Returns

  • Success: A list of Agent objects.
  • Failure: Exception.

Examples

from ragflow_sdk import RAGFlow
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
for agent in rag_object.list_agents():
print(agent)

创建智能体

RAGFlow.create_agent(
title: str,
dsl: dict,
description: str | None = None
) -> None

创建智能体。

Parameters

title: str

Specifies the title of the agent.

dsl: dict

Specifies the canvas DSL of the agent.

description: str

The description of the agent. Defaults to None.

Returns

  • Success: Nothing.
  • Failure: Exception.

Examples

from ragflow_sdk import RAGFlow
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
rag_object.create_agent(
title="Test Agent",
description="A test agent",
dsl={
# ... canvas DSL here ...
}
)

更新智能体

RAGFlow.update_agent(
agent_id: str,
title: str | None = None,
description: str | None = None,
dsl: dict | None = None
) -> None

更新智能体。

Parameters

agent_id: str

Specifies the id of the agent to be updated.

title: str

Specifies the new title of the agent. None if you do not want to update this.

dsl: dict

Specifies the new canvas DSL of the agent. None if you do not want to update this.

description: str

The new description of the agent. None if you do not want to update this.

Returns

  • Success: Nothing.
  • Failure: Exception.

Examples

from ragflow_sdk import RAGFlow
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
rag_object.update_agent(
agent_id="58af890a2a8911f0a71a11b922ed82d6",
title="Test Agent",
description="A test agent",
dsl={
# ... canvas DSL here ...
}
)

删除智能体

RAGFlow.delete_agent(
agent_id: str
) -> None

删除智能体。

Parameters

agent_id: str

Specifies the id of the agent to be deleted.

Returns

  • Success: Nothing.
  • Failure: Exception.

Examples

from ragflow_sdk import RAGFlow
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
rag_object.delete_agent("58af890a2a8911f0a71a11b922ed82d6")