Skip to main content

如何构建过滤器

前提条件

本指南假定您已熟悉以下内容:

我们可能希望进行查询分析,以提取可传递给检索器的过滤器。一种我们让 LLM 表示这些过滤器的方式是使用 Zod 模式。然后就存在一个问题,即将该 Zod 模式转换为可以传递给特定检索器的过滤器。

这可以手动完成,但 LangChain 也提供了一些“转换器”,能够将通用语法转换为每个检索器特定的过滤器。在这里,我们将介绍如何使用这些转换器。

环境配置

安装依赖

yarn add @langchain/core zod

在此示例中,yearauthor 均为用于过滤的属性。

import { z } from "zod";

const searchSchema = z.object({
query: z.string(),
startYear: z.number().optional(),
author: z.string().optional(),
});

const searchQuery: z.infer<typeof searchSchema> = {
query: "RAG",
startYear: 2022,
author: "LangChain",
};
import { Comparison, Comparator } from "langchain/chains/query_constructor/ir";

function constructComparisons(
query: z.infer<typeof searchSchema>
): Comparison[] {
const comparisons: Comparison[] = [];
if (query.startYear !== undefined) {
comparisons.push(
new Comparison("gt" as Comparator, "start_year", query.startYear)
);
}
if (query.author !== undefined) {
comparisons.push(
new Comparison("eq" as Comparator, "author", query.author)
);
}
return comparisons;
}

const comparisons = constructComparisons(searchQuery);
import { Operation, Operator } from "langchain/chains/query_constructor/ir";

const _filter = new Operation("and" as Operator, comparisons);
import { ChromaTranslator } from "@langchain/community/structured_query/chroma";

new ChromaTranslator().visitOperation(_filter);
{
"$and": [
{ start_year: { "$gt": 2022 } },
{ author: { "$eq": "LangChain" } }
]
}

下一步

你现在已了解如何从任意查询创建特定筛选器。

接下来,查看本节中其他一些查询分析指南,例如如何使用少样本提示(few-shotting)来提升性能


Was this page helpful?


You can also leave detailed feedback on GitHub.