AutoRAG 数据创建教程:用 LLM 构建属于你自己的 RAG 评估数据集 📅 发布时间:2026/9/18 8:52:25 👁 浏览次数: AutoRAG 数据创建教程用 LLM 构建属于你自己的 RAG 评估数据集【免费下载链接】AutoRAGAutoRAG: Now your agent can find anything in your computer. It gets smarter if you are using it frequently.项目地址: https://gitcode.com/GitHub_Trending/au/AutoRAG在 RAG检索增强生成系统的研发中最稀缺的资源往往不是模型而是高质量的评估数据。本文基于 AutoRAG 仓库中的 legacy 数据创建教程tutorial.md系统讲解如何借助 LLM 从零构建 AutoRAG 可直接使用的corpus data语料数据与qa data问答评估数据你将掌握 LlamaIndex / LangChain 文档加载与切分、语料转换函数、单跳 QA 批量生成、自定义/多提示词prompt按比例分配以及基于已有问答数据的 retrieval_gt 补齐流程并深入到 legacy/autorag/data/legacy 下的源码实现理解每一步背后的参数含义与底层逻辑。为什么需要合成评估数据RAG 系统的评估离不开数据但大多数场景下我们手头要么没有现成的高质量问答对要么数据量远远不够。自 LLM 出现以来用 LLM 合成数据synthetic data成为解决这一问题的常用且有效的手段。AutoRAG 的设计目标是尽量与 Python 的原生数据类型primitive data types这里特指 pandasDataFrame协作以获得良好的可扩展性与便利性。因此在使用 AutoRAG 之前你需要将原始数据转换为两种 AutoRAG 约定的数据集corpus data语料数据RAG 检索的候选池由原始文档加载、切分后的 passage段落构成qa data问答评估数据包含用户问题、标准答案与检索标准答案retrieval_gt用于评测检索、重排、生成等各环节。整个数据创建流程可概括为三条主线原始文档 → corpus data、corpus data → qa data以及已有 query / qa 时的 retrieval_gt 补齐。下面逐一展开。前置知识AutoRAG 的数据格式约定动手之前必须先了解数据格式否则生成的 parquet 文件无法被 AutoRAG 正确解析。完整规范见 data_format.md这里提炼两个核心数据集的结构。QA 数据集qa.parquetqa.parquet必须包含以下四列列名类型说明qidstring每条 query 的唯一标识不可重复否则可能引发不可预期行为querystring用户的问题可想象或采集用户对 RAG 系统的真实提问retrieval_gt2D list检索标准答案外层 list 中的每个内层 list 是一组或关系满足其一即可不同内层 list 之间是与关系必须都命中generation_gtlist标准答案列表一个问题可以对应多个合理的标准答案若只有一个标准答案也可存为 stringretrieval_gt使用 2D list 是有讲究的评测指标支持与 / 或两种组合语义。例如New Jeans 和 Aespa 哪个女团成员更多这类问题需要同时查阅两篇文档与而语料中可能有多个文档都提到New Jeans 有五名成员这些文档之间就是或。对应数据形如[ [NewJeans1, NewJeans2], [Aespa1, Aespa2, Aespa3], ]含义是必须从第一组中命中其一且从第二组中命中其一才能完整作答。如果信息不足也可以保存为 1D list 或 string此时按与关系处理。注意retrieval_gt中的 doc id 必须存在于 corpus 数据集的doc_id列中AutoRAG 开始评估时会校验这一点且retrieval_gt直接决定检索类节点retrieval、query expansion、passage reranker的优化方向。Corpus 数据集corpus.parquetcorpus.parquet必须包含以下列列名类型说明doc_idstring每个 passage 的唯一标识不可重复contentsstringpassage 的实际文本内容须先完成文档切分metadatadict必须包含last_modified_datetime键datetime.datetime实例可选page用于展示来源页使用 prev_next_augmenter 时还需prev_id、next_idpath可选stringpassage 的原始文件路径便于追溯与调试start_end_idx可选(int, int)passage 在原始解析文档中的起止位置便于用新语料更新 QA如果完全没有 metadata可传空字典转换函数会自动补齐默认值如last_modified_datetime取datetime.now()。另外请确保数据集索引已重置否则可能引发异常。从原始文档构建 Corpus 数据构建 corpus 的标准三步流程为用 LlamaIndex、LangChain 等加载器把原始文档加载为文本用 LangChain、LlamaIndex 的切分器把文本切成 passage调用转换函数把切分结果转成 AutoRAG 的 corpus 格式。AutoRAG 在 legacy/autorag/data/legacy/corpus 提供了三类对象的转换函数llama_documents_to_parquet接收 LlamaIndexDocument列表llama_text_node_to_parquet接收 LlamaIndexTextNode列表langchain_documents_to_parquet接收 LangChainDocument列表。三个函数签名一致均接受output_filepath可选parquet 保存路径目录须已存在、扩展名须为.parquet与upsert默认False为True时若文件已存在则覆盖写入并返回 corpusDataFrame。使用 LlamaIndexfrom llama_index.core import SimpleDirectoryReader from llama_index.core.node_parser import TokenTextSplitter from autorag.data.legacy.corpus import llama_text_node_to_parquet documents SimpleDirectoryReader(your_dir_path).load_data() nodes TokenTextSplitter(chunk_size512, chunk_overlap128).get_nodes_from_documents(documentsdocuments) corpus_df llama_text_node_to_parquet(nodes, path/to/corpus.parquet)从源码看llama_index.pyllama_text_node_to_parquet会以node.node_id作为doc_id以node.text作为contents并调用add_essential_metadata_llama_text_node处理 metadata若缺少last_modified_datetime则自动填充当前时间同时从relationships中提取prev_id/next_id由切分器记录的相邻节点关系为后续使用 prev/next passage 增强类节点做好准备。而llama_documents_to_parquetllama_index.py则用uuid.uuid4()为每个文档生成新的doc_id。使用 LangChainfrom langchain_community.document_loaders import DirectoryLoader from langchain_text_splitters import RecursiveCharacterTextSplitter from autorag.data.legacy.corpus import langchain_documents_to_parquet documents DirectoryLoader(your_dir_path, glob**/*.md).load() documents RecursiveCharacterTextSplitter(chunk_size512, chunk_overlap128).split_documents(documents) corpus_df langchain_documents_to_parquet(documents, path/to/corpus.parquet)langchain_documents_to_parquetlangchain.py同样以uuid.uuid4()生成doc_id以doc.page_content作为contents并通过add_essential_metadata补齐last_modified_datetime。从 Corpus 数据生成 QA 数据语料就绪后核心环节是用 LLM 为每条 passage 生成问题query与标准答案generation_gt。AutoRAG 提供make_single_content_qa作为入口配合generate_qa_llama_index即可生成单内容single contentQA 数据也就是常说的single-hop / single-document问答对——每个问题只依赖一条 passage 即可作答retrieval_gt只包含一个 doc id。这是最基础的 QA 数据集形态。import pandas as pd from llama_index.llms.openai import OpenAI from autorag.data.legacy.qacreation import generate_qa_llama_index, make_single_content_qa corpus_df pd.read_parquet(path/to/corpus.parquet) llm OpenAI(modelgpt-3.5-turbo, temperature1.0) qa_df make_single_content_qa(corpus_df, 50, generate_qa_llama_index, llmllm, question_num_per_content1, output_filepathpath/to/qa.parquet, cache_batch64)参数与执行细节make_single_content_qabase.py的核心参数如下参数默认值说明corpus_df—语料 DataFrame须含contents与doc_id列content_size—要生成 QA 的 passage 数量大于语料规模时会告警并自动截断为语料大小content_size须大于 0qa_creation_func—实际的 QA 生成函数如generate_qa_llama_index、generate_qa_llama_index_by_ratio其输入必须含contents参数output_filepathNoneparquet 保存路径为None时仅返回 DataFrame 不落盘upsertFalse为True时覆盖已存在的输出文件random_state42从 corpus 中随机抽样语料的随机种子cache_batch32每生成多少个 passage 的 QA 后触发一次缓存保存内部流程为按random_state从 corpus 随机抽样content_size条 → 按cache_batch分块调用qa_creation_func→ 将返回的{query, generation_gt}展开为行 → 生成唯一qid→ 把retrieval_gt包装成 2D list[[doc_id]]、generation_gt包装为 list。注意generate_qa_llama_index本身还接受question_num_per_content每个 passage 生成的问题数默认 1、max_retries默认 3与batch异步批大小默认 4等参数这些会通过**kwargs透传。自动保存特性从 AutoRAG v0.2.9 起加入了自动保存auto-save数据生成过程中一旦出错无需担心全部丢失已生成的结果会按cache_batch的节奏自动写入output_filepath。cache_batch越小保存越频繁但整体处理时间也会相应变长默认值为 32。默认提示词内部实现当不传prompt时generate_qa_llama_index会读取包内自带的 llama_index_default_prompt.txtllama_index.py。该提示词要求 LLM 从给定文本中抽取问答对、答案必须是完整句子、问题尽量详细、输出数量必须严格等于给定值并且问题中不得出现in the given text之类的措辞。随后每个 content 会发起异步补全请求通过parse_output解析形如[Q]: ... / [A]: ...的输出llama_index.py若解析出的问答对数与question_num_per_content不符会在max_retries次内重试仍失败则抛出InterruptedError。generate_answers则用于为已有 query 生成答案其内置系统提示词要求答案保留提问语言如韩语问题输出韩语答案这也是make_qa_with_existing_qa内部使用的答案生成函数。使用自定义 Prompt你可以完全自定义 QA 生成提示词。自定义提示词必须包含两个占位符二者缺一不可validate_llama_index_prompt会显式校验并抛ValueError{{text}}content 字符串{{num_questions}}要生成的问题数量。import pandas as pd from llama_index.llms.openai import OpenAI from autorag.data.legacy.qacreation import generate_qa_llama_index, make_single_content_qa prompt Generate question and answer pairs for the given passage. Passage: {{text}} Number of questions to generate: {{num_questions}} Example: [Q]: What is this? [A]: This is a sample question. Result: corpus_df pd.read_parquet(path/to/corpus.parquet) llm OpenAI(modelgpt-3.5-turbo, temperature1.0) qa_df make_single_content_qa(corpus_df, content_size50, qa_creation_funcgenerate_qa_llama_index, llmllm, promptprompt, question_num_per_content1)运行时占位符会被替换为真实内容prompt.replace({{text}}, content).replace({{num_questions}}, str(question_num))见 llama_index.py因此自定义提示词建议仍遵循[Q]:/[A]:的输出格式以便parse_output正确解析。使用多个 Prompt 按比例生成如果希望生成多种类型的问答对例如事实型、推理型、多跳型混合可以使用generate_qa_llama_index_by_ratio多个提示词按各自比例在每个 passage 上随机分配。为此需要传入一个字典键为提示词文本文件路径值为该提示词的使用比例比例之和不必为 1。import pandas as pd from llama_index.llms.openai import OpenAI from autorag.data.legacy.qacreation import generate_qa_llama_index_by_ratio, make_single_content_qa ratio_dict { prompt1.txt: 1, prompt2.txt: 2, prompt3.txt: 3 } corpus_df pd.read_parquet(path/to/corpus.parquet) llm OpenAI(modelgpt-3.5-turbo, temperature1.0) qa_df make_single_content_qa(corpus_df, content_size50, qa_creation_funcgenerate_qa_llama_index_by_ratio, llmllm, prompts_ratioratio_dict, question_num_per_content1, batch6)警告所有提示词文件必须同时包含{{text}}和{{num_questions}}两个占位符。从源码看llama_index.py该函数先按random_state默认 42洗牌 content 索引再用distribute_list_by_ratio按比例精确切分末段自动吸收取整误差最后把每条 content 与其分配的提示词配对后批量异步生成。当已有问答数据时补齐 retrieval_gt真实用户产生的问答数据非常宝贵应优先于合成数据使用。但已有数据往往缺少retrieval_gt从语料中定位证据段落。手工查找困难且必须保证准确AutoRAG 的做法是用 embedding 模型 向量数据库检索相关 passage 作为候选再由你人工确认其相关性不相关者应从数据集中剔除。该功能在两种情况下都可用只有 query或 query 与generation_gt都已具备。统一入口是make_qa_with_existing_qa其关键参数包括embedding_model默认openai_embed_3_large可换成 AutoRAG 支持的其他模型、top_k每个 query 参考的证据数量默认 3、collectionchromadb collection默认为None时创建临时 collection若已提前灌入语料则跳过重复向量化、random_state默认 42、cache_batch默认 32与upsert。情形一只有 query 数据先用现有 query 检索得到retrieval_gt再把 query 与检索到的 passage 一起交给 LLM 生成generation_gt必须传answer_creation_func与llmexisting_qa_df必须包含query列。import pandas as pd from llama_index.llms.openai import OpenAI from autorag.data.legacy.qacreation import make_qa_with_existing_qa, generate_answers corpus_df pd.read_parquet(path/to/corpus.parquet) existing_qa_df pd.read_parquet(path/to/existing_qa.parquet) # It has to contain query column llm OpenAI(modelgpt-3.5-turbo, temperature1.0) qa_df make_qa_with_existing_qa(corpus_df, existing_qa_df, content_size50, answer_creation_funcgenerate_answers, llmllm, output_filepathpath/to/qa.parquet, cache_batch64, embedding_modelopenai_embed_3_large, top_k5)内部实现base.py会加载 embedding 模型 → 将 corpus 灌入向量库并给 query 批量向量化 → 异步检索每个 query 的 top_k 文档 → 把命中的 passage 拼接成Document 1\n...形式的上下文 → 交给answer_creation_func即generate_answers逐条生成答案。也支持使用chromadb.PersistentClient把语料向量持久化到本地避免重复向量化import pandas as pd import chromadb from llama_index.llms.openai import OpenAI from autorag.data.legacy.qacreation import make_qa_with_existing_qa, generate_answers client chromadb.PersistentClient(path/to/chromadb) collection client.get_or_create_collection(auto-rag) corpus_df pd.read_parquet(path/to/corpus.parquet) existing_qa_df pd.read_parquet(path/to/existing_qa.parquet) # It has to contain query column llm OpenAI(modelgpt-3.5-turbo, temperature1.0) qa_df make_qa_with_existing_qa(corpus_df, existing_qa_df, content_size50, answer_creation_funcgenerate_answers, collectioncollection, llmllm, output_filepathpath/to/qa.parquet, cache_batch64, embedding_modelopenai_embed_3_large, top_k5)情形二query 与 generation_gt 都已有此时 query 和标准答案原样保留只需检索并追加retrieval_gt无需传answer_creation_func与llm必须传exist_gen_gtTrueexisting_qa_df必须包含query和generation_gt两列且每条generation_gt必须是List[str]形式源码中会校验numpy.ndarray也可接受否则抛ValueError。import pandas as pd from llama_index.llms.openai import OpenAI from autorag.data.legacy.qacreation import make_qa_with_existing_qa corpus_df pd.read_parquet(path/to/corpus.parquet) existing_qa_df pd.read_parquet( path/to/existing_qa.parquet) # It has to contain query and generation_gt columns. llm OpenAI(modelgpt-3.5-turbo, temperature1.0) qa_df make_qa_with_existing_qa(corpus_df, existing_qa_df, content_size50, exist_gen_gtTrue, output_filepathpath/to/qa.parquet, cache_batch64, embedding_modelopenai_embed_3_large, top_k5)同样支持 chromadb 持久化import pandas as pd import chromadb from llama_index.llms.openai import OpenAI from autorag.data.legacy.qacreation import make_qa_with_existing_qa client chromadb.PersistentClient(path/to/chromadb) collection client.get_or_create_collection(auto-rag) corpus_df pd.read_parquet(path/to/corpus.parquet) existing_qa_df pd.read_parquet( path/to/existing_qa.parquet) # It has to contain query and generation_gt columns. llm OpenAI(modelgpt-3.5-turbo, temperature1.0) qa_df make_qa_with_existing_qa(corpus_df, existing_qa_df, content_size50, exist_gen_gtTrue, collectioncollection, output_filepathpath/to/qa.parquet, cache_batch64, embedding_modelopenai_embed_3_large, top_k5)注意以上数据创建接口位于仓库 legacy 目录属于旧版legacy数据创建方案其中make_qa_with_existing_qa在 base.py 中已被标注为 deprecatedDeprecationWarning。对于历史项目或需要复现旧版教程的场景可按上文使用新项目建议优先查看 data_creation 主目录下的新式教程如 qa_creation 对应的 query 生成与答案生成模块。从原始文档到评估数据集完整工作流回顾把上述步骤串起来一条可复现的完整流水线如下切分语料用SimpleDirectoryReader/DirectoryLoader加载原始文档用TokenTextSplitter/RecursiveCharacterTextSplitter切分为 512 字符overlap 128的 passage生成 corpus调用llama_text_node_to_parquet/langchain_documents_to_parquet写出corpus.parquet自动补齐last_modified_datetime等 metadata合成 QAmake_single_content_qagenerate_qa_llama_index或generate_qa_llama_index_by_ratio混用多提示词生成qa.parquet借助cache_batch自动保存防止中断丢失已有数据补齐对真实用户 query用make_qa_with_existing_qa检索retrieval_gt再人工复核相关性或直接沿用已有generation_gtexist_gen_gtTrue。产出满足 data_format.md 约定的corpus.parquet与qa.parquet后即可直接用于 AutoRAG 的优化与评估流程。可参考仓库 sample_dataset 下的真实数据集加载脚本如 hotpotqa、triviaqa进一步核对数据集结构确保与 AutoRAG 的输入约定完全一致。【免费下载链接】AutoRAGAutoRAG: Now your agent can find anything in your computer. It gets smarter if you are using it frequently.项目地址: https://gitcode.com/GitHub_Trending/au/AutoRAG创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考