用Ragas从文档构建单跳查询测试集

介绍如何用Ragas把Markdown文档构建成知识图谱,经标题抽取、标题切分和关键短语抽取等变换后,结合自定义人物画像生成单跳查询测试集。

## 从文档中创建自定义的单跳查询 ### 装入样本文档 我用的文件来自 [GitLab手册样本](<https://huggingface.co/datasets/vibrantlabsai/Sample_Docs_Markdown>)。您可以通过运行以下命令来下载。 ``` ! git clone https://huggingface.co/datasets/vibrantlabsai/Sample_Docs_Markdown ``` ``` from langchain_community.document_loaders import DirectoryLoader path = "Sample_Docs_Markdown/" loader = DirectoryLoader(path, glob="**/*.md") docs = loader.load() ``` ### 创建 KG 随文档创建一个基础知识图 ``` from ragas.testset.graph import KnowledgeGraph from ragas.testset.graph import Node, NodeType kg = KnowledgeGraph() for doc in docs: kg.nodes.append( Node( type=NodeType.DOCUMENT, properties={ "page_content": doc.page_content, "document_metadata": doc.metadata, }, ) ) ``` ### 设置 LLM 和嵌入模型 你可以使用任何一个 [您的选择](<https://docs.ragas.io/en/stable/howtos/customizations/customize_models/>)我用的是开放的模特儿 ``` from openai import OpenAI from ragas.llms import llm_factory from ragas.embeddings import OpenAIEmbeddings openai_client = OpenAI() llm = llm_factory("gpt-4o-mini", client=openai_client) embedding = OpenAIEmbeddings(client=openai_client) ``` ### 设置变换器 这里我们使用 2 提取器和 2 关系构建器 。 - 标题提取器: 从文档中提取头条 - 键词提取器: 从文档中提取密钥句 - 标题分割器: 根据头条将文档分割成节点 。 ``` from ragas.testset.transforms import apply_transforms from ragas.testset.transforms import ( HeadlinesExtractor, HeadlineSplitter, KeyphrasesExtractor, ) headline_extractor = HeadlinesExtractor(llm=llm) headline_splitter = HeadlineSplitter(min_tokens=300, max_tokens=1000) keyphrase_extractor = KeyphrasesExtractor( llm=llm, property_name="keyphrases", max_num=10 ) transforms = [ headline_extractor, headline_splitter, keyphrase_extractor, ] apply_transforms(kg, transforms=transforms) ``` 产出 ``` Applying KeyphrasesExtractor: 6%| | 2/36 [00:01<00:20, 1Property 'keyphrases' already exists in node '514fdc'. Skipping! Applying KeyphrasesExtractor: 11%| | 4/36 [00:01<00:10, 2Property 'keyphrases' already exists in node '84a0f6'. Skipping! Applying KeyphrasesExtractor: 64%|▋| 23/36 [00:03<00:01, Property 'keyphrases' already exists in node '93f19d'. Skipping! Applying KeyphrasesExtractor: 72%|▋| 26/36 [00:04<00:00, 1Property 'keyphrases' already exists in node 'a126bf'. Skipping! Applying KeyphrasesExtractor: 81%|▊| 29/36 [00:04<00:00, Property 'keyphrases' already exists in node 'c230df'. Skipping! Applying KeyphrasesExtractor: 89%|▉| 32/36 [00:04<00:00, 1Property 'keyphrases' already exists in node '4f2765'. Skipping! Property 'keyphrases' already exists in node '4a4777'. Skipping! ``` ### 配置人物为 您也可以通过使用 [自动个人a 生成器](<https://docs.ragas.io/en/stable/howtos/customizations/testgenerator/_persona_generator/>) ``` from ragas.testset.persona import Persona person1 = Persona( name="gitlab employee", role_description="A junior gitlab employee curious on workings on gitlab", ) persona2 = Persona( name="Hiring manager at gitlab", role_description="A hiring manager at gitlab trying to underestand hiring policies in gitlab", ) persona_list = [person1, persona2] ``` ## SingleHop 查询 继承从 `SingleHopQuerySynthesizer` 并修改生成查询创建情景的函数。 **步骤**: - 为查询创建找到合格的节点。 在此我用提取的密钥句选择所有节点 。 - 对于每个合格的节点 - 用一个或多个人匹配密钥句 。 - 创建所有可能的组合( 节点、 Persona、 查询样式、 查询长度) - 从组合中样本所需的查询次数 ``` from ragas.testset.synthesizers.single_hop import ( SingleHopQuerySynthesizer, SingleHopScenario, ) from dataclasses import dataclass from ragas.testset.synthesizers.prompts import ( ThemesPersonasInput, ThemesPersonasMatchingPrompt, ) @dataclass class MySingleHopScenario(SingleHopQuerySynthesizer): theme_persona_matching_prompt = ThemesPersonasMatchingPrompt() async def _generate_scenarios(self, n, knowledge_graph, persona_list, callbacks): property_name = "keyphrases" nodes = [] for node in knowledge_graph.nodes: if node.type.name == "CHUNK" and node.get_property(property_name): nodes.append(node) number_of_samples_per_node = max(1, n // len(nodes)) scenarios = [] for node in nodes: if len(scenarios) >= n: break themes = node.properties.get(property_name, [""]) prompt_input = ThemesPersonasInput(themes=themes, personas=persona_list) persona_concepts = await self.theme_persona_matching_prompt.generate( data=prompt_input, llm=self.llm, callbacks=callbacks ) base_scenarios = self.prepare_combinations( node, themes, personas=persona_list, persona_concepts=persona_concepts.mapping, ) scenarios.extend( self.sample_combinations(base_scenarios, number_of_samples_per_node) ) return scenarios query = MySingleHopScenario(llm=llm) scenarios = await query.generate_scenarios( n=5, knowledge_graph=kg, persona_list=persona_list ) scenarios[0] ``` 产出 ``` SingleHopScenario( nodes=1 term=what is an ally persona=name='Hiring manager at gitlab' role_description='A hiring manager at gitlab trying to underestand hiring policies in gitlab' style=Web search like queries length=long) ``` ``` result = await query.generate_sample(scenario=scenarios[-1]) ``` ### 修改快捷键以自定义查询样式 这里我用一个只生成是/否问题的指示来取代默认的提示。 这是一个可选步骤 。 ``` instruction = """Generate a Yes/No query and answer based on the specified conditions (persona, term, style, length) and the provided context. Ensure the answer is entirely faithful to the context, using only the information directly from the provided context. ### Instructions: 1. **Generate a Yes/No Query**: Based on the context, persona, term, style, and length, create a question that aligns with the persona's perspective, incorporates the term, and can be answered with 'Yes' or 'No'. 2. **Generate an Answer**: Using only the content from the provided context, provide a 'Yes' or 'No' answer to the query. Do not add any information not included in or inferable from the context.""" ``` ``` prompt = query.get_prompts()["generate_query_reference_prompt"] prompt.instruction = instruction query.set_prompts(**{"generate_query_reference_prompt": prompt}) result = await query.generate_sample(scenario=scenarios[-1]) ``` ``` result.user_input ``` 产出 ``` 'Does the Diversity, Inclusion & Belonging (DIB) Team at GitLab have a structured approach to encourage collaborations among team members through various communication methods?' ``` ``` result.reference ``` 产出 ``` 'Yes' ``` 11月 13, 2026 12月 16, 2025

查看原始来源