[Question]: How to obtain the original quoted text through HTTP or Python API?

用户在 RAGFlow 中创建知识库后,通过聊天助手的 chat_id 进行问答。返回的答案末尾包含类似 [ID:1] 的标记,用户需要从 API 响应中获取这些标记对应的原始引用文本,以便进行后续的代码处理或数据操作。

[Question]: How to obtain the original quoted text through HTTP or Python API?

[Question]: How to obtain the original quoted text through HTTP or Python API?

快速结论:RAGFlow 的聊天完成 API 默认只返回包含 [ID:n] 标记的答案文本,而不会自动附带原文。要使响应中包含原始引用内容,必须在请求中设置 "quote": true,然后从响应中的 reference.chunks 数组获取原文。

问题场景

用户在 RAGFlow 中创建知识库后,通过聊天助手的 chat_id 进行问答。返回的答案末尾包含类似 [ID:1] 的标记,用户需要从 API 响应中获取这些标记对应的原始引用文本,以便进行后续的代码处理或数据操作。

报错原文

Currently, after creating a knowledge base, I conduct Q&A using the chat_id of the chat assistant. At the end of the reply content, I can get something like "[ID:1]". Based on the analysis of the front - end interface, this should refer to the cited content. Now, I hope to parse it in the code for more flexible subsequent operations, but I haven't been able to find the relevant API or issue.

原因分析

该问题属于功能使用疑问,而非程序报错。默认情况下,RAGFlow 的聊天完成 API 并不会自动返回引用的原始文本块。如果请求中没有包含 "quote": true 参数,响应中的 reference.chunks 字段将为空或不存在,导致无法根据 [ID:n] 找到对应的原文内容。

环境排查

  • 确认 RAGFlow 服务版本是否支持 quote 参数(相关功能已在 PR #7923 中实现)。
  • 确认使用的 API 端点是否为 /api/v1/chats/{chat_id}/completions
  • 检查请求的 payload 中是否已包含 "quote": true
  • 如果使用 Python SDK,确认 SDK 版本是否已同步更新。

解决步骤

  1. 在 API 请求中添加 "quote": true 参数

    调用 /api/v1/chats/{chat_id}/completions 端点时,确保请求体包含以下字段:

    {
        "messages": [{"role": "user", "content": "your question"}],
        "quote": true
    }
  2. 从响应中提取引用内容

    设置 "quote": true 后,响应会包含 reference.chunks 数组。答案文本中的 [ID:n] 标记对应数组中的第 n 个元素(从 0 开始索引)。

  3. 使用正则表达式解析标记并获取原文

    可优先尝试以下 Python 示例代码来提取引用内容:

    import requests
    import re
    
    url = "http://your-ragflow-server/api/v1/chats/{chat_id}/completions"
    headers = {"Authorization": "Bearer <YOUR_API_KEY>"}
    payload = {
        "messages": [{"role": "user", "content": "your question"}],
        "quote": True
    }
    resp = requests.post(url, json=payload, headers=headers)
    data = resp.json()
    answer = data["answer"]
    references = data.get("reference", {})
    chunks = references.get("chunks", [])
    
    # 从答案中提取所有 [ID:n] 并打印对应的块内容
    for match in re.findall(r"\[ID:(\d+)\]", answer):
        idx = int(match)
        if idx < len(chunks):
            print(f"ID:{idx} content:", chunks[idx]["content"])
  4. 如果使用 Python SDK

    SDK 中的 Chunk 类提供了类似的方式访问块内容和元数据,具体可参考 SDK 文档。

验证方法

在请求中添加 "quote": true 后,检查 API 响应中是否包含 reference.chunks 数组。确认数组中的第 n 个元素内容与答案文本中的 [ID:n] 标记一致,且能够正确提供原始引用文本和元数据。

参考来源

infiniflow/ragflow #8788

GamsGo AI

AI 工具推荐

想把多个 AI 模型放在一个入口?

GamsGo AI 集成 ChatGPT、DeepSeek、Gemini、Claude、Midjourney、Veo 等常用模型,适合写作、绘图、视频和日常 AI 工作流。

了解 GamsGo AI

推广链接:通过此链接购买,我可能获得佣金,不影响你的价格。

celebrityanime
celebrityanime
文章: 14558

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注