以编程方式使用文档

许多 LLM 应用程序从向量数据库、知识图谱或其他索引中检索文档,作为检索增强生成 (RAG) 管道的一部分。LangSmith 为检索器步骤提供专用渲染,使检查检索到的文档和诊断检索问题变得更加容易。

要启用检索器专用渲染,请完成以下两个步骤。

设置 run_type 为 retriever

run_type="retriever" 传递给 traceable 装饰器(Python)或 traceable 包装器(TypeScript)。这告诉 LangSmith 将该步骤视为检索运行,并在 LangSmith UI:

from langsmith import traceable

@traceable(run_type="retriever")
def retrieve_docs(query):
    ...

如果您使用的是 RunTree API 而不是 traceable,则在创建 run_type="retriever" 时传递 RunTree object.

以预期的格式返回文档

从检索器函数返回字典列表(Python)或对象列表(TypeScript)。列表中的每个项目代表一个检索到的文档,必须包含以下字段:

字段类型描述
page_contentstring检索文档的文本内容。
typestring必须始终为 "Document".
metadataobject关于文档的键值对元数据,如来源 URL、块 ID 或分数。此元数据会随文档一起显示在追踪中。

以下示例展示应用了这两个要求的完整检索器实现:

from langsmith import traceable

def _convert_docs(results):
    return [
        {
            "page_content": r,
            "type": "Document",
            "metadata": {"foo": "bar"}
        }
        for r in results
    ]

@traceable(run_type="retriever")
def retrieve_docs(query):
    # Returning hardcoded placeholder documents.
    # In production, replace with a real vector database or document index.
    contents = ["Document contents 1", "Document contents 2", "Document contents 3"]
    return _convert_docs(contents)

retrieve_docs("User query")
interface Document {
    page_content: string;
    type: string;
    metadata: { foo: string };
}

function convertDocs(results: string[]): Document[] {
    return results.map((r) => ({
        page_content: r,
        type: "Document",
        metadata: { foo: "bar" }
    }));
}

const retrieveDocs = traceable((query: string): Document[] => {
    // Returning hardcoded placeholder documents.
    // In production, replace with a real vector database or document index.
    const contents = ["Document contents 1", "Document contents 2", "Document contents 3"];
    return convertDocs(contents);
}, {
    name: "retrieveDocs",
    run_type: "retriever"
});

await retrieveDocs("User query");

在 LangSmith UI 中,您会找到每个检索到的文档及其内容和元数据。

相关