Ragas v0.4实验式架构迁移要点
Ragas v0.4将评估从单次指标运行改为实验式架构,指标以集合形式返回结构化结果,评估入口由evaluate()改为experiment()装饰器,LLM初始化统一为llm_factory(),样本字段ground_truths更名为reference。
## 从v0.3迁移到v0.4 Ragas v0.4 引入了一种根本性的转变,即: **基于实验的建筑**这是自v0.2以来最显著的变化,从孤立的度量评价转向紧密结合评价、分析和迭代的一致试验框架。 这一建筑变革导致了若干具体的改进: 1. **以收集为基础的计量系统** - 采用标准化方法衡量在实验中无缝运行的计量标准 2. **统一的 LLM 工厂系统** - 简化的 LLM 在通用提供者支持下初始化 3. **现代提示系统** - 基于函数的更可调和和可重复使用的提示 此指南将引导您通过关键修改, 并提供 step-by-step 迁移指令 。 ## 主要变化概览 向实验式建筑的转变侧重于三个核心改进: 1. **实验-儿童设计** - 从一次性计量运行转向结构化、综合分析的实验工作流程 2. **基于收藏的计量** - 为在实验中发挥作用而设计的计量,返回结构化结果,以更好地分析和跟踪 3. **增强的 LLM 系统** - 普遍供应商支助和现代迅速模式,以便进行更好的试验 ### 关键统计 - **标记**: 20 + 新收藏系统的核心度量衡 - **中断更改**: 7 + 主要API 变化 - **折旧**: 遗留包装课和旧的即时定义 - **新特性**: GPT-5/O系列支持,自动约束处理,通用提供者支持 ## 理解实验建筑 在移民之前,它有助于理解思想的转变: **v0.3(量子学):** ``` Data → Individual Metric → Score → Analysis ``` 每一次度量运行都是相对孤立的。你会运行一个度量,得到一个浮标分, 并处理外部的跟踪/分析。 **v0.4(实验):** ``` Data → Experiment → [Metrics Collection] → Structured Results → Integrated Analysis ``` 计量目前是在评价、分析和迭代相结合的实验背景下运作的。 - 更好地跟踪附有解释的衡量结果 - 各种试验的比较比较比较容易 - 用于分析计量行为的内置支持 - 在您的系统中流动的清洁工作流程 ## 迁移路径 我们建议按此顺序迁移: 1. **更新评价办法** (节: [评估到实验](<https://docs.ragas.io/en/stable/howtos/migrations/migrate_from_v03_to_v04/#evaluation-to-experiment>)- 切换从 `evaluate()` 改为: `experiment()` 2. **更新您的 LLM 设置** (节: [LLM 初始化](<https://docs.ragas.io/en/stable/howtos/migrations/migrate_from_v03_to_v04/#llm-initialization>)) 3. **迁移度量衡** (节: [度量衡迁移](<https://docs.ragas.io/en/stable/howtos/migrations/migrate_from_v03_to_v04/#metrics-migration>)) 4. **移动嵌入** (节: [嵌入式迁移](<https://docs.ragas.io/en/stable/howtos/migrations/migrate_from_v03_to_v04/#embeddings-migration>)) 5. **更新提示** (节: [快速系统迁移](<https://docs.ragas.io/en/stable/howtos/migrations/migrate_from_v03_to_v04/#prompt-system-migration>)- 如果你在自定义提示 6. **更新数据计划** (节: [数据Schema 变化](<https://docs.ragas.io/en/stable/howtos/migrations/migrate_from_v03_to_v04/#data-schema-changes>)) 7. **重构自定义衡量标准** (节: [自定义计量](<https://docs.ragas.io/en/stable/howtos/migrations/migrate_from_v03_to_v04/#custom-metrics>)) --- ## 评估到实验 v0.4 替换 `evaluate()` 函数带有 `experiment()`- 采取基于方法,更好地支持迭代评价工作流程和结构化成果跟踪。 ### 改变了什么 关键转变:从 **简单的评价职能** (`evaluate()`将分数返回到 **实验装饰器** (`@experiment()`)支持结构化的工作流程,并带有内置的跟踪和版本. ### 之前( v0.3 ) ``` from ragas import evaluate from ragas.metrics.collections import Faithfulness, AnswerRelevancy # Setup dataset = ... # Your dataset metrics = [Faithfulness(llm=llm), AnswerRelevancy(llm=llm)] # Simple evaluation result = evaluate(dataset=dataset, metrics=metrics, llm=llm, embeddings=embeddings) print(result) # Returns EvaluationResult with scores ``` ### 之后 (v0.4 ) (中文(简体) ). ``` from ragas import experiment from ragas.metrics.collections import Faithfulness, AnswerRelevancy from pydantic import BaseModel # Define experiment result structure class ExperimentResult(BaseModel): faithfulness: float answer_relevancy: float # Create experiment function @experiment(ExperimentResult) async def run_evaluation(row): faithfulness = Faithfulness(llm=llm) answer_relevancy = AnswerRelevancy(llm=llm) faith_result = await faithfulness.ascore( response=row.response, retrieved_contexts=row.contexts ) relevancy_result = await answer_relevancy.ascore( user_input=row.user_input, response=row.response ) return ExperimentResult( faithfulness=faith_result.value, answer_relevancy=relevancy_result.value ) # Run experiment exp_results = await run_evaluation(dataset) ``` ### 使用的好处 `experiment()` 1. **结构化结果** - 精确定义要跟踪的内容 2. **每只牛控制器** - 必要时自定义每个样本的评价 3. **版本跟踪** - 可选的 git 整合方式 `version_experiment()` 4. **长期工作流程** - 易于修改和重新运行的实验 5. **更好的一体化** - 与现代计量和数据集无缝工作 --- ## LLM 初始化 ### 改变了什么 v0.3系统需要不同的工厂功能,取决于您的使用案例: - `instructor_llm_factory()` 需要教员的衡量标准 - `llm_factory()` 用于一般LLM操作 - LangChain和LlamaIndex的各种包装类 v0.4 将所有的东西整合成一个 **单一统一工厂**: ``` from ragas.llms import llm_factory ``` 这个工厂: - 回返情况 `InstructorBaseRagasLLM` 有保证的结构化产出 - 自动检测和配置特定供应商的限制 - 支持自动的 GPT-5 和 o 系列模型 `temperature` 财务报告和财务报告 `top_p` 制约 - 与所有主要供应商合作:OpenAI,Anthropic,Cohere,Google,Azure,Bedrock等. ### 之前( v0.3 ) ``` from ragas.llms import instructor_llm_factory, llm_factory from openai import AsyncOpenAI # For metrics that need instructor llm = instructor_llm_factory( "openai", model="gpt-4o-mini", client=AsyncOpenAI(api_key="...") ) # Or, the old way (not recommended, still supported in 0.3) client = AsyncOpenAI(api_key="sk-...") llm = llm_factory("openai", model="gpt-4o-mini", client=client) ``` ### 之后 (v0.4 ) (中文(简体) ). ``` from ragas.llms import llm_factory from openai import AsyncOpenAI # Single unified approach - works everywhere client = AsyncOpenAI(api_key="sk-...") llm = llm_factory("gpt-4o-mini", client=client) ``` **关键差异 :** | 侧面 | v0.3 | v0.4 | | --- | --- | --- | | **工厂功能** | `instructor_llm_factory()` 或 时 间 `llm_factory()` | `llm_factory()` | | **提供者检测** | 通过提供者字符串手动 | 从模型名称自动 | | **返回类型** | `BaseRagasLLM` (各种情况) | `InstructorBaseRagasLLM` | | **约束性处理** | 手动配置 | 自动用于 GPT-5 / o- 系列 | | **需要Async 客户端** | 对 | 对 | ### 移徙步骤 1. **更新导入**: ``` # Remove this from ragas.llms import instructor_llm_factory # Use this instead from ragas.llms import llm_factory ``` 2. **更换工厂电话**: ``` # Old - v0.3 llm = instructor_llm_factory("openai", model="gpt-4o", client=client) # New - v0.4 llm = llm_factory("gpt-4o", client=client) ``` 3. **更新到其他提供者** (模型名称检测工作自动): ``` # OpenAI llm = llm_factory("gpt-4o-mini", client=AsyncOpenAI(api_key="...")) # Anthropic llm = llm_factory("claude-3-sonnet-20240229", client=AsyncAnthropic(api_key="...")) # Google llm = llm_factory("gemini-2.0-flash", client=...) ``` ### LLM 包装类(已过期) 如果你使用包装课,现在这些课已贬值,将来将取消: ``` # Deprecated - will be removed from ragas.llms import LangchainLLMWrapper, LlamaIndexLLMWrapper ``` ``` # Recommended - use llm_factory directly from ragas.llms import llm_factory ``` **移徙**: 将包装初始化替换为直接 `llm_factory()` 工厂现在自动处理供应商的检测。 --- ## 度量衡迁移 ### 计量为何改变 向基于实验的架构的转变需要衡量标准,以便更好地与实验工作流程相结合: - **结构化结果**: 计量器现在返回 `MetricResult` 对象(有分数+推理),而不是原始浮点数,从而能够在实验中进行更丰富的分析和跟踪 - **关键词参数**:从样本对象转向直接关键词参数,使度量衡更容易与实验管道编译和集成 - **标准化投入/产出**:基于收集的计量标准遵循一致的模式,从而更容易在顶部建立元分析和实验特征 ### 建筑结构变化 衡量系统已完全重新设计,以支持实验工作流程。 #### 基础类更改 | 侧面 | v0.3 | v0.4 | | --- | --- | --- | | **导入** | `from ragas.metrics import Metric` | `from ragas.metrics.collections import Metric` | | **基础类** | `MetricWithLLM`, `SingleTurnMetric` | `BaseMetric` (从收款) | | **计分方法** | `async def single_turn_ascore(sample: SingleTurnSample)` | `async def ascore(**kwargs)` | | **输入类型** | `SingleTurnSample` 对象 | 单个关键字参数 | | **输出类型** | `float` 分数 | `MetricResult` (与 `.value` 可选 `.reason`) | | **LLM 参数** | 初始化时要求 | 初始化时要求 | #### 计算工作流程 **v0.3方法:** ``` # 1. Create a sample object containing all data sample = SingleTurnSample( user_input="What is AI?", response="AI is artificial intelligence...", retrieved_contexts=["Context 1", "Context 2"], ground_truths=["AI definition"], ) # 2. Call metric with the sample metric = Faithfulness(llm=llm) score = await metric.single_turn_ascore(sample) # Returns: 0.85 ``` **v0.4方法:** ``` # 1. Call metric with individual arguments metric = Faithfulness(llm=llm) result = await metric.ascore( user_input="What is AI?", response="AI is artificial intelligence...", retrieved_contexts=["Context 1", "Context 2"], ) # 2. Access result properties print(result.value) # Score: 0.85 (float) print(result.reason) # Optional explanation ``` ### v0.4中可用的量表 下列指标已成功迁移到v0.4的收藏系统: #### RAG 评价计量 - **忠诚** - 反应是否基于已检索的上下文? (v0.3.9 +) - **AnswerRelevancy** - 回复是否与用户查询相关? (v0.3.9 +) - **AnswerCorrectness** - 反应是否与参考答案相符? (v0.3.9 +) - **AnswerAccuracy** - 答案是否属实? - **ContextPrecision** - 检索到的上下文是否按相关性排序? (v0.3.9 +) - 参考: `ContextPrecisionWithReference` - 无参考文献 : `ContextPrecisionWithoutReference` - 遗产名称 : `ContextUtilization` (现在的包装为ContextPrecisionWithoutReference). - **ContextRecall** - 所有相关上下文是否已成功检索 ? (v0.3.9 +) - **ContextRelevance** - 检索到的上下文中有哪些百分比相关? (v0.3.9 +) - **ContextEntityRecall** - 重要实体是否来自上下文? (v0.3.9 +) - **NoiseSensitivity** - 衡量不相关上下文的尺度有多有力? (v0.3.9 +) - **ResponseGroundedness** - 所有索赔是否都以检索到的上下文为依据? #### 文本比较量表 - **SemanticSimilarity** - 两个文本是否具有相似的语义含义? (v0.3.9 +) - **FactualCorrectness** - 事实性陈述是否被正确核实?(v0.3.9+) - **BleuScore** - 双语评价助研分数(v0.3.9 +) - **RougeScore** - 面向召回的辅助评估(v0.3.9 +) #### 基于字符串的量度( 非 LLM ) - **ExactMatch** - 精确的字符串匹配 - **StringPresence** - 子字符串存在检查 - **LevenshteinDistance** - 编辑距离相似性 - **MatchingSubstrings** - 匹配子字符串的数 - **NonLLMStringSimilarity** - 各种字符串相似性算法 #### 计量摘要 - **SummaryScore** - 总体简要质量评估(v0.3.9 +) #### 删除的量表( 无较长可用) - **AspectCritic** - 使用( U) `@discrete_metric()` 换成装饰器 - **SimpleCriteria** - 使用( U) `@discrete_metric()` 换成装饰器 - **AnswerSimilarity** - 使用( U) `SemanticSimilarity` 换成 #### 代理工具计量( M) - **ToolCallAccuracy** - `ragas.metrics.collections.ToolCallAccuracy` - **ToolCallF1** - `ragas.metrics.collections.ToolCallF1` - **TopicAdherence** - `ragas.metrics.collections.TopicAdherence` - **AgentGoalAccuracy** - `ragas.metrics.collections.AgentGoalAccuracy` #### SQL 数据计量(已移动) - **DataCompy 分数** - `ragas.metrics.collections.DataCompyScore` - **SQL 查询等效** - `ragas.metrics.collections.SQLSemanticEquivalence` #### Rubric Metrics(移徙) - **DomainSpecificRubrics** - `ragas.metrics.collections.DomainSpecificRubrics` - **InstanceSpecificRubrics** - `ragas.metrics.collections.InstanceSpecificRubrics` #### 字符串 & NLP 计量( 已移动) - **CHRF 分数** - `ragas.metrics.collections.CHRFScore` (字符n-gram F-scount) (中文(简体) ). - **引用的 Spans 对齐** - `ragas.metrics.collections.QuotedSpansAlignment` (引用核查) #### 专门计量(尚未迁移) - **多模式信仰** - 仍在旧建筑(待定迁移) - **多模式关联性** - 仍在旧建筑(待定迁移) 移民状况 大多数核心衡量标准已转移到收集系统,遗留结构上只剩下多模式衡量标准。 其余的衡量标准今后将迁移 **v0.4.x** 您仍然可以使用旧的 API 的 遗留指标, 尽管它们会显示贬值警告 。 ### 逐步迁移 #### Step 1: 更新导入 ``` # v0.3 from ragas.metrics import Faithfulness, AnswerRelevancy, ContextPrecision, ContextRecall ``` ``` # v0.4 from ragas.metrics.collections import ( Faithfulness, AnswerRelevancy, ContextPrecision, ContextRecall, ) ``` #### Step 2 : 初始化计量(不需要更改) ``` # v0.3 metric = Faithfulness(llm=llm) ``` ``` # v0.4 - Same initialization metric = Faithfulness(llm=llm) ``` #### Step 3:更新量子分数呼叫 替换 `single_turn_ascore(sample)` 与 `ascore(**kwargs)`: ``` # v0.3 sample = SingleTurnSample( user_input="What is AI?", response="AI is artificial intelligence.", retrieved_contexts=["AI is a technology..."], ground_truths=["AI definition"], ) score = await metric.single_turn_ascore(sample) print(score) # Output: 0.85 ``` ``` # v0.4 result = await metric.ascore( user_input="What is AI?", response="AI is artificial intelligence.", retrieved_contexts=["AI is a technology..."], ) print(result.value) # Output: 0.85 print(result.reason) # Optional: "Response is faithful to context" ``` #### Step 4: 处理 MetricResult 对象 在 v0.4 中, 参数返回 `MetricResult` 对象而不是原始浮点 : ``` from ragas.metrics.collections.base import MetricResult result = await metric.ascore(...) # Access the score score_value = result.value # float between 0 and 1 # Access the explanation (if available) if result.reason: print(f"Reason: {result.reason}") # Convert to float for compatibility score_float = float(result.value) ``` ### 特定移徙 #### 忠诚 **之前(v0.3):** ``` sample = SingleTurnSample( user_input="What is machine learning?", response="ML is a subset of AI.", retrieved_contexts=["ML involves algorithms..."], ) score = await metric.single_turn_ascore(sample) ``` **之后(v0.4):** ``` result = await metric.ascore( user_input="What is machine learning?", response="ML is a subset of AI.", retrieved_contexts=["ML involves algorithms..."], ) score = result.value ``` #### AnswerRelevancy **之前(v0.3):** ``` sample = SingleTurnSample( user_input="What is Python?", response="Python is a programming language..." ) score = await metric.single_turn_ascore(sample) ``` **之后(v0.4):** ``` result = await metric.ascore( user_input="What is Python?", response="Python is a programming language..." ) score = result.value ``` #### AnswerCorrectness 注:该计量标准现在使用 `reference` 改为 `ground_truths`: **之前(v0.3):** ``` sample = SingleTurnSample( user_input="What is AI?", response="AI is artificial intelligence.", ground_truths=["AI is artificial intelligence and machine learning."], ) score = await metric.single_turn_ascore(sample) ``` **之后(v0.4):** ``` result = await metric.ascore( user_input="What is AI?", response="AI is artificial intelligence.", reference="AI is artificial intelligence and machine learning.", ) score = result.value ``` #### ContextPrecision **之前(v0.3):** ``` sample = SingleTurnSample( user_input="What is RAG?", response="RAG improves LLM accuracy.", retrieved_contexts=["RAG = Retrieval Augmented Generation...", "..."], ground_truths=["RAG definition"], ) score = await metric.single_turn_ascore(sample) ``` **之后(v0.4):** ``` result = await metric.ascore( user_input="What is RAG?", response="RAG improves LLM accuracy.", retrieved_contexts=["RAG = Retrieval Augmented Generation...", "..."], reference="RAG definition", ) score = result.value ``` --- ## 快速系统迁移 ### 为何更改提示 向模块化结构的转变意味着 提示是现在 **一级组件** 可以是: - **每公吨定制** - 每个度量衡都有明确定义的即时界面 - **类型安全** - 投入/产出模型界定预期的确切结构 - **可重复使用** - 快速分类在各种衡量标准中遵循一致的模式 - **可测试** - 提示可以独立生成和检查 v0.3使用简单的基于字符串或数据类的提示,分散在各种度量衡中. v0.4将其整合为一个统一的. `BasePrompt` 具有专用输入/输出模型的架构。 ### 建筑结构变化 #### 基数提示系统 | 侧面 | v0.3 | v0.4 | | --- | --- | --- | | **即时定义** | `PydanticPrompt` 数据类或字符串 | `BasePrompt` 课程设置 `to_string()` 方法 | | **输入/输出类型** | 通用 Pydantic 模型 | 特定计量输入/产出模型 | | **访问方法** | 跨度码的散射 | 中央单位(公吨) `util.py` 模块 | | **自定义** | 困难,需要深刻的改变 | 简单的子分类 `instruction` 财务报告和财务报告 `examples` 属性 | | **组织** | 混合于度量文件 | 单独组织 `util.py` 文件 | ### v0.4 中可用的计量提示 下面的衡量标准现在有明确定义的、可自定义的提示: - **忠诚** - `FaithfulnessPrompt`, `FaithfulnessInput`, `FaithfulnessOutput` - **背景回顾** - `ContextRecallPrompt`, `ContextRecallInput`, `ContextRecallOutput` - **内容精确度** - `ContextPrecisionPrompt`, `ContextPrecisionInput`, `ContextPrecisionOutput` - **解答相关性** - `AnswerRelevancyPrompt`, `AnswerRelevancyInput`, `AnswerRelevancyOutput` - **回答正确性** - `AnswerCorrectnessPrompt`, `AnswerCorrectnessInput`, `AnswerCorrectnessOutput` - **反应依据** - `ResponseGroundednessPrompt`, `ResponseGroundednessInput`, `ResponseGroundednessOutput` - **答案准确性** - `AnswerAccuracyPrompt`, `AnswerAccuracyInput`, `AnswerAccuracyOutput` - **关联性** - `ContextRelevancePrompt`, `ContextRelevanceInput`, `ContextRelevanceOutput` - **背景实体回顾** - `ContextEntityRecallPrompt`, `ContextEntityRecallInput`, `ContextEntityRecallOutput` - **事实正确性** - `ClaimDecompositionPrompt`, `VerificationPrompt`,带有相关的输入/输出模型 - **噪音敏感性** - `NoiseAugmentationPrompt` 与相关模式 - **积分汇总** - `SummaryScorePrompt`, `SummaryScoreInput`, `SummaryScoreOutput` ### 逐步迁移 #### Step 1: 在您的计量中访问提示 ``` from ragas.metrics.collections import Faithfulness from ragas.llms import llm_factory # Create metric instance metric = Faithfulness(llm=llm) # Access the prompt object print(metric.prompt) # <ragas.metrics.collections.faithfulness.util.FaithfulnessPrompt> ``` #### Step 2: 查看提示字符串 ``` from ragas.metrics.collections.faithfulness.util import FaithfulnessInput # Create sample input sample_input = FaithfulnessInput( response="The Eiffel Tower is in Paris.", context="The Eiffel Tower is located in Paris, France.", ) # Generate prompt string prompt_string = metric.prompt.to_string(sample_input) print(prompt_string) ``` #### Step 3 : 自定义提示( 如果需要) **选项 A: 默认提示的子分类** ``` from ragas.metrics.collections import Faithfulness from ragas.metrics.collections.faithfulness.util import FaithfulnessPrompt # Create custom prompt by subclassing class CustomFaithfulnessPrompt(FaithfulnessPrompt): @property def instruction(self): return """Your custom instruction here.""" # Apply to metric metric = Faithfulness(llm=llm) metric.prompt = CustomFaithfulnessPrompt() ``` **备选办法B:为特定领域评价定制实例** ``` from ragas.metrics.collections.faithfulness.util import ( FaithfulnessInput, FaithfulnessOutput, FaithfulnessPrompt, StatementFaithfulnessAnswer, ) class DomainSpecificPrompt(FaithfulnessPrompt): examples = [ ( FaithfulnessInput( response="ML uses statistical techniques.", context="Machine learning is a field that uses algorithms to learn from data.", ), FaithfulnessOutput( statements=[ StatementFaithfulnessAnswer( statement="ML uses statistical techniques.", reason="Related to learning from data, but context doesn't explicitly mention statistical techniques.", verdict=0, ), ] ), ), ] # Apply custom prompt metric = Faithfulness(llm=llm) metric.prompt = DomainSpecificPrompt() ``` ### 常见的快捷自定义 #### 更改指令 多数衡量标准允许凌驾于指令属性之上: ``` class StrictFaithfulnessPrompt(FaithfulnessPrompt): @property def instruction(self): return """Be very strict when judging faithfulness. Only mark statements as faithful (verdict=1) if they are directly stated or strongly implied.""" ``` #### 添加域示例 域特异性实例大大提高了度量精确度(10 - 20%改进): ``` class MedicalFaithfulnessPrompt(FaithfulnessPrompt): examples = [ # Medical domain examples here ] ``` #### 更改输出格式 对于高级定制,下级为即时并覆盖 `to_string()` 方法 : ``` class CustomPrompt(FaithfulnessPrompt): def to_string(self, input: FaithfulnessInput) -> str: # Custom prompt generation logic return "..." ``` ### 正在验证自定义提示 在使用自定义提示之前, 总是要验证您的自定义提示 : ``` # Test prompt generation sample_input = FaithfulnessInput(response="Test response.", context="Test context.") custom_metric = Faithfulness(llm=llm) custom_metric.prompt = MyCustomPrompt() # View the generated prompt prompt_string = custom_metric.prompt.to_string(sample_input) print(prompt_string) # Then use it for evaluation result = await custom_metric.ascore(response="Test response.", context="Test context.") ``` ### 从 v0.3 自定义提示的迁移 如果您在 v0.3 中有自定义提示使用 `PydanticPrompt`: **前(v0.3) - 数据类方法:** ``` from ragas.prompt.pydantic_prompt import PydanticPrompt from pydantic import BaseModel class MyInput(BaseModel): response: str context: str class MyOutput(BaseModel): is_faithful: bool class MyPrompt(PydanticPrompt[MyInput, MyOutput]): instruction = "Check if response is faithful to context" input_model = MyInput output_model = MyOutput examples = [...] ``` **之后(v0.4 ) - BasePrompt方法:** ``` from ragas.metrics.collections.base import BasePrompt from pydantic import BaseModel class MyInput(BaseModel): response: str context: str class MyOutput(BaseModel): is_faithful: bool class MyPrompt(BasePrompt): @property def instruction(self): return "Check if response is faithful to context" @property def input_model(self): return MyInput @property def output_model(self): return MyOutput @property def examples(self): return [...] def to_string(self, input: MyInput) -> str: # Generate prompt string from input return f"Check if this is faithful: {input.response}" ``` ### 语言适应,使用BasePrompt.adapt() v0.4 介绍 `adapt()` 方法打开 `BasePrompt` 语言翻译实例,替换已贬值的 `PromptMixin.adapt_prompts()` 办法。 #### 前(v0.3) - PromptMixin方法 ``` from ragas.prompt.mixin import PromptMixin from ragas.metrics import Faithfulness # Metrics inherited from PromptMixin to use adapt_prompts class MyFaithfulness(Faithfulness, PromptMixin): pass metric = MyFaithfulness(llm=llm) # Adapt ALL prompts to another language adapted_prompts = await metric.adapt_prompts( language="spanish", llm=llm, adapt_instruction=True ) # Apply all adapted prompts metric.set_prompts(**adapted_prompts) ``` **v0.3方法的问题:** - 必需的混合继承(紧密结合) - 所有导句一起调整(不灵活) - 混合方法分散在编码库中 #### 之后( v0.4 ) - BasePrompt 适应() 方法 ``` from ragas.metrics.collections import Faithfulness # Create metric with default prompt metric = Faithfulness(llm=llm) # Adapt individual prompt to another language adapted_prompt = await metric.prompt.adapt( target_language="spanish", llm=llm, adapt_instruction=True ) # Apply adapted prompt metric.prompt = adapted_prompt # Use metric with adapted language result = await metric.ascore(response="...", retrieved_contexts=[...]) ``` 使用 BasePrompt 的 v0.4 .x 未来版本中将会有保存和加载提示. 目前, PromptMixin 只有它. #### 语言适应实例 **无指令文本的适应( 轻量级 ) :** ``` from ragas.metrics.collections import AnswerRelevancy metric = AnswerRelevancy(llm=llm) # Only update language field, keep instruction in English adapted_prompt = await metric.prompt.adapt( target_language="french", llm=llm, adapt_instruction=False, # Default - just updates language ) metric.prompt = adapted_prompt print(metric.prompt.language) # "french" ``` **适应指令翻译(全译):** ``` # Translate both instruction and examples adapted_prompt = await metric.prompt.adapt( target_language="german", llm=llm, adapt_instruction=True, # Translate instruction text too ) metric.prompt = adapted_prompt # Examples are also automatically translated # Both instruction and examples in German now ``` **适应自定义提示 :** ``` from ragas.metrics.collections.faithfulness.util import FaithfulnessPrompt class CustomFaithfulnessPrompt(FaithfulnessPrompt): @property def instruction(self): return "Custom instruction in English" prompt = CustomFaithfulnessPrompt(language="english") # Adapt to Italian adapted = await prompt.adapt(target_language="italian", llm=llm, adapt_instruction=True) # Check language was updated assert adapted.language == "italian" ``` #### 从v0.3迁移到v0.4 **Step 1:删除 PromptMixin 继承** ``` # v0.3 from ragas.prompt.mixin import PromptMixin from ragas.metrics import Faithfulness class MyMetric(Faithfulness, PromptMixin): # ← Remove PromptMixin pass # v0.4 from ragas.metrics.collections import Faithfulness # No mixin needed - just use the metric directly metric = Faithfulness(llm=llm) ``` **Step 2 : 将 adapt_prompts () 替换为适应()** ``` # v0.3 adapted_prompts = await metric.adapt_prompts( language="spanish", llm=llm, adapt_instruction=True ) metric.set_prompts(**adapted_prompts) # v0.4 adapted_prompt = await metric.prompt.adapt( target_language="spanish", llm=llm, adapt_instruction=True ) metric.prompt = adapted_prompt ``` #### 完整迁移示例 **之前(v0.3):** ``` from ragas.prompt.mixin import PromptMixin from ragas.metrics import Faithfulness, AnswerRelevancy class MyMetrics(Faithfulness, AnswerRelevancy, PromptMixin): pass # Setup metrics = MyMetrics(llm=llm) # Adapt multiple metrics to Spanish adapted = await metrics.adapt_prompts( language="spanish", llm=best_llm, adapt_instruction=True ) metrics.set_prompts(**adapted) metrics.save_prompts("./spanish_prompts") ``` **之后(v0.4):** ``` from ragas.metrics.collections import Faithfulness, AnswerRelevancy # Setup individual metrics faith_metric = Faithfulness(llm=llm) answer_metric = AnswerRelevancy(llm=llm) # Adapt each metric's prompt independently faith_adapted = await faith_metric.prompt.adapt( target_language="spanish", llm=best_llm, adapt_instruction=True ) faith_metric.prompt = faith_adapted answer_adapted = await answer_metric.prompt.adapt( target_language="spanish", llm=best_llm, adapt_instruction=True ) answer_metric.prompt = answer_adapted # Use metrics with adapted prompts faith_result = await faith_metric.ascore(...) answer_result = await answer_metric.ascore(...) ``` --- ## 数据Schema 变化 ### SingleTurnSample 更新 密码 `SingleTurnSample` 已用断开的更改更新了计划 : #### `ground_truths` → `reference` 密码 `ground_truths` 参数已重命名为 `reference` 总体情况: **之前(v0.3):** ``` sample = SingleTurnSample( user_input="...", response="...", ground_truths=["correct answer"], # List of strings ) ``` **之后(v0.4):** ``` sample = SingleTurnSample( user_input="...", response="...", reference="correct answer", # Single string ) ``` - 使用的 v0.3 `ground_truths` 作为 **列表** - v0.4 用途 `reference` 作为 **单字符串** - 对于多个参考文献,使用单独的评价运行 #### 更新的Schema ``` from ragas import SingleTurnSample # v0.4 complete sample sample = SingleTurnSample( user_input="What is AI?", # Required response="AI is artificial intelligence.", # Required retrieved_contexts=["Context 1", "Context 2"], # Optional reference="Correct definition of AI", # Optional (was ground_truths) ) ``` ### EvaluationDataset 更新 如果你在用的话 `EvaluationDataset`,更新数据加载: **之前(v0.3):** ``` dataset = EvaluationDataset( samples=[ SingleTurnSample(user_input="Q1", response="A1", ground_truths=["correct"]) ] ) ``` **之后(v0.4):** ``` dataset = EvaluationDataset( samples=[SingleTurnSample(user_input="Q1", response="A1", reference="correct")] ) ``` 如果从 CSV / JSON 装入, 请更新您的数据文件 : **前(v0.3) CSV格式:** ``` user_input,response,retrieved_contexts,ground_truths "Q1","A1","[""ctx1""]","[""correct""]" ``` **之后( v0.4 ) CSV 格式:** ``` user_input,response,retrieved_contexts,reference "Q1","A1","[""ctx1""]","correct" ``` --- ## 自定义计量 ### 使用基于收藏的建筑的计量 如果你已经写出了自定义的度量衡 `BaseMetric` 从收藏中,需要最小的改动: ``` from ragas.metrics.collections.base import BaseMetric, MetricResult from pydantic import BaseModel class MyCustomMetric(BaseMetric): name: str = "my_metric" dimensions: list[str] = ["my_dimension"] async def ascore(self, **kwargs) -> MetricResult: # Your metric logic score = 0.85 reason = "Explanation of the score" return MetricResult(value=score, reason=reason) ``` **主要考虑因素:** - 扩展 `BaseMetric`时,不老 `MetricWithLLM` - 执行 `async def ascore(**kwargs)` 改为 `single_turn_ascore(sample)` - 返回时 `MetricResult` 对象,不是原始浮点 - 使用关键字参数代替 `SingleTurnSample` ### 使用遗留结构的计量 如果您有自定义的度量标准扩展 `SingleTurnMetric` 或 时 间 `MetricWithLLM`: ``` # v0.3 - Legacy approach from ragas.metrics.base import MetricWithLLM class MyMetric(MetricWithLLM): async def single_turn_ascore(self, sample: SingleTurnSample) -> float: # Extract values from sample user_input = sample.user_input response = sample.response contexts = sample.retrieved_contexts or [] # Your logic return 0.85 ``` **迁移路径 :** 1. 扩展 `BaseMetric` 取自收藏 2. 更改方法签名以使用关键词参数 3. 返回时 `MetricResult` 而不是浮点 4. 添加 `dimensions` 属性( 如果不存在) ``` # v0.4 - Collections approach from ragas.metrics.collections.base import BaseMetric, MetricResult class MyMetric(BaseMetric): name: str = "my_metric" dimensions: list[str] = ["quality"] async def ascore( self, user_input: str, response: str, retrieved_contexts: list[str] | None = None, **kwargs, ) -> MetricResult: # Use keyword arguments directly contexts = retrieved_contexts or [] # Your logic score = 0.85 return MetricResult(value=score, reason="Optional explanation") ``` ### 提示系统更新 #### v0.3 - 基于数据类的提示 ``` from ragas.prompt.pydantic_prompt import PydanticPrompt from pydantic import BaseModel class Input(BaseModel): query: str document: str class Output(BaseModel): is_relevant: bool class RelevancePrompt(PydanticPrompt[Input, Output]): instruction = "Is the document relevant to the query?" input_model = Input output_model = Output examples = [...] ``` #### v0.4 - 基于函数的提示 新的方法使用简单的功能: ``` def relevance_prompt(query: str, document: str) -> str: return f"""Determine if the document is relevant to the query. Query: {query} Document: {document} Respond with YES or NO.""" ``` **福利:** - 更简单和更可调和 - 没有锅炉板类定义 - 便于测试和修改 - 本地 Python 类型提示 **移徙:** - 识别自定义参数中的提示 - 将数据类定义转换为函数 - 更新直接使用该函数的参数 --- ## 删除的特性 下列特性已经从v0.4中完全删除,如果使用,将产生错误: ### 职能 **`instructor_llm_factory()`** - 完全删除 - **合并为**: `llm_factory()` 函数 - **移徙**: 将所有呼叫替换为 `instructor_llm_factory()` 与 `llm_factory()` - **影响**: 直接断裂变化,无倒计时 **前(v0.3) - 不再工作:** ``` llm = instructor_llm_factory("openai", model="gpt-4o", client=client) ``` **之后( v0.4 ) - 使用此选项 :** ``` llm = llm_factory("gpt-4o", client=client) ``` ### 度量衡 3个度量衡已经完全从收集的API中移除。它们已经无法使用,没有直接替换: **1. AspectCritic** - 已删除 - **原因**: 由更灵活的离散度量图取代 - **备选案文**编号: 使用 `@discrete_metric()` 自定义评价的装饰符 - **使用量**: ``` # Instead of AspectCritic, use: from ragas.metrics import discrete_metric @discrete_metric( name="aspect_critic", allowed_values=["positive", "negative", "neutral"] ) def evaluate_aspect(response: str, aspect: str) -> str: # Your evaluation logic return "positive" ``` **2. SimpleCriteria** - 已删除 - **原因**: 由更灵活的离散度量图取代 - **备选案文**编号: 使用 `@discrete_metric()` 定制标准的装饰器 - **使用量**: ``` from ragas.metrics import discrete_metric @discrete_metric(name="custom_criteria", allowed_values=["pass", "fail"]) def evaluate_criteria(response: str, criteria: str) -> str: return "pass" if criteria in response else "fail" ``` **3. AnswerSimilarity** - 删除( redundant) - **原因**: 功能问题已完全涵盖 `SemanticSimilarity` - **直接替换**: `SemanticSimilarity` - **使用量**: ``` # v0.3 - No longer available from ragas.metrics import AnswerSimilarity # ERROR # v0.4 - Use this instead from ragas.metrics.collections import SemanticSimilarity metric = SemanticSimilarity(llm=llm) result = await metric.ascore(reference="Expected answer", response="Actual answer") ``` ### 折旧方法(删除于v0.4) **`Metric.ascore()` 财务报告和财务报告 `Metric.score()`** - 已删除 - **删除时**: 标注在 v0.3 中被删除,在 v0.4 中被删除 - **为什么**: 替换为基于收藏的 `ascore(**kwargs)` 模式 - **移徙**: 使用收藏计量标准代替 **基于样本的遗留方法** - 已删除 - **`single_turn_ascore(sample: SingleTurnSample)`** - 仅涉及遗产衡量标准 - **替换为**: 使用收集度量衡 `ascore(**kwargs)` --- ## 贬值的特征 这些特性仍然有效,但显示贬值警告。这些特性将被删除。 **未来发行**. ### 函数 - 已折旧 - **状态**: 仍在工作,但感到沮丧 - **原因**: 替换为 `@experiment()` 结构更好的工作流程的装饰器 - **移徙**: 见 [评估到实验](<https://docs.ragas.io/en/stable/howtos/migrations/migrate_from_v03_to_v04/#evaluation-to-experiment>) 节次 **前(v0.3) - 折旧:** ``` from ragas import evaluate result = evaluate(dataset=dataset, metrics=metrics, llm=llm, embeddings=embeddings) ``` **之后(v0.4 ) - 建议:** ``` from ragas import experiment from pydantic import BaseModel class Results(BaseModel): score: float @experiment(Results) async def run(row): result = await metric.ascore(**row.dict()) return Results(score=result.value) result = await run(dataset) ``` ### LLM 包装类 #### LangchainLLMWrapper - 过期 - **状态**: 仍在工作,但感到沮丧 - **折旧警告**: ``` Direct usage of LangChain LLMs with Ragas prompts is deprecated and will be removed in a future version. Use Ragas LLM interfaces instead ``` - **移徙**编号: 使用 `llm_factory()` 改为本地客户端 **前(v0.3) - 折旧:** ``` from ragas.llms import LangchainLLMWrapper from langchain_openai import ChatOpenAI langchain_llm = ChatOpenAI(model="gpt-4o") ragas_llm = LangchainLLMWrapper(langchain_llm) ``` **之后(v0.4 ) - 建议:** ``` from ragas.llms import llm_factory from openai import AsyncOpenAI client = AsyncOpenAI(api_key="...") ragas_llm = llm_factory("gpt-4o", client=client) ``` #### LlamaIndexLLMWrapper - 过期 - **状态**: 仍在工作,但感到沮丧 - **类似的警告** 作为 LangchainLLMWrapper - **移徙**编号: 使用 `llm_factory()` 与本地客户端 **前(v0.3) - 折旧:** ``` from ragas.llms import LlamaIndexLLMWrapper from llama_index.llms.openai import OpenAI llamaindex_llm = OpenAI(model="gpt-4o") ragas_llm = LlamaIndexLLMWrapper(llamaindex_llm) ``` **之后(v0.4 ) - 建议:** ``` from ragas.llms import llm_factory from openai import AsyncOpenAI client = AsyncOpenAI(api_key="...") ragas_llm = llm_factory("gpt-4o", client=client) ``` ### 嵌入式迁移 #### LangchainEmbeddingsWrapper & LlamaIndexEmbeddingsWrapper - 已贬值 - **状态**: 仍在工作,但显示贬值警告 - **原因**: 以直接客户端集成的本地嵌入提供者取代 - **移徙**: 见 [嵌入式迁移](<https://docs.ragas.io/en/stable/howtos/migrations/migrate_from_v03_to_v04/#embeddings-migration>) 节次 v0.4 将包装类替换为 **本地嵌入提供者** 直接与客户端库集成,而不是使用 LangChain 包装。 ### 改变了什么 | 侧面 | v0.3 | v0.4 | | --- | --- | --- | | **类** | `LangchainEmbeddingsWrapper`, `LlamaIndexEmbeddingsWrapper` | `OpenAIEmbeddings`, `GoogleEmbeddings`, `HuggingFaceEmbeddings` | | **客户端** | LangChain / LlamaIndex 包装器 | 本地客户端( OpenAI, Google 等) | | **方法** | `embed_query()`, `embed_documents()` | `embed_text()`, `embed_texts()` | | **设置** | 环绕现有的 LangChain 对象 | 直接通过本地客户端 | #### OpenAI 迁移 **之前(v0.3):** ``` from langchain_openai import OpenAIEmbeddings as LangChainEmbeddings from ragas.embeddings import LangchainEmbeddingsWrapper embeddings = LangchainEmbeddingsWrapper(LangChainEmbeddings(api_key="sk-...")) embedding = embeddings.embed_query("text") ``` **之后(v0.4):** ``` from openai import AsyncOpenAI from ragas.embeddings import OpenAIEmbeddings embeddings = OpenAIEmbeddings( client=AsyncOpenAI(api_key="sk-..."), model="text-embedding-3-small" ) embedding = embeddings.embed_text("text") # Different method name ``` #### Google 嵌入式迁移 **之前(v0.3):** ``` from langchain_community.embeddings import VertexAIEmbeddings from ragas.embeddings import LangchainEmbeddingsWrapper embeddings = LangchainEmbeddingsWrapper( VertexAIEmbeddings(model_name="textembedding-gecko@001", project="my-project") ) ``` **之后(v0.4):** ``` from ragas.embeddings import GoogleEmbeddings embeddings = GoogleEmbeddings( model="text-embedding-004", use_vertex=True, project_id="my-project" ) ``` #### HuggingFace 迁移 **之前(v0.3):** ``` from ragas.embeddings import HuggingfaceEmbeddings embeddings = HuggingfaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2") ``` **之后(v0.4):** ``` from ragas.embeddings import HuggingFaceEmbeddings # Capitalization changed embeddings = HuggingFaceEmbeddings( model="sentence-transformers/all-MiniLM-L6-v2", device="cuda", # Optional GPU acceleration ) ``` ### 使用 embedding_factory () **之前(v0.3):** ``` from ragas.embeddings import embedding_factory embeddings = embedding_factory() # Defaults to OpenAI ``` **之后(v0.4):** ``` from ragas.embeddings import embedding_factory from openai import AsyncOpenAI embeddings = embedding_factory( provider="openai", model="text-embedding-3-small", client=AsyncOpenAI(api_key="sk-..."), ) ``` ### 提示系统 #### 基于数据类的提示( PydanticPrompt ) - 过期 - **状态**: 遗产激励仍然有效,但劝阻 - **折旧**: 模块化的 BasePrompt 架构现在为首选 - **移徙**: 见 [快速系统迁移](<https://docs.ragas.io/en/stable/howtos/migrations/migrate_from_v03_to_v04/#prompt-system-migration>) 节次 **前(v0.3) - 折旧方法:** ``` from ragas.prompt.pydantic_prompt import PydanticPrompt from pydantic import BaseModel class Input(BaseModel): query: str class Output(BaseModel): is_relevant: bool class RelevancePrompt(PydanticPrompt[Input, Output]): instruction = "Is this relevant?" input_model = Input output_model = Output ``` **之后(v0.4 ) - 建议的办法:** ``` # Use BasePrompt classes instead - see Prompt System Migration section from ragas.metrics.collections.faithfulness.util import FaithfulnessPrompt class CustomPrompt(FaithfulnessPrompt): @property def instruction(self): return "Your custom instruction here" ``` ### 遗留的计量方法 #### `single_turn_ascore(sample)` - 已折旧 - **状态**:仅涉及遗产(非收集)衡量标准 - **折旧**: 使用收集度量衡 `ascore()` 换成 - **时间线**: 当所有度量值迁移时,将在今后的释放中删除 **前(v0.3) - 折旧:** ``` sample = SingleTurnSample(user_input="...", response="...", ...) score = await metric.single_turn_ascore(sample) ``` **之后(v0.4 ) - 建议:** ``` result = await metric.ascore(user_input="...", response="...") score = result.value ``` #### ContextUtilization `ContextUtilization` 现在是一个包装器周围 `ContextPrecisionWithoutReference` 用于向后兼容性 : **之前(v0.3):** ``` from ragas.metrics import ContextUtilization metric = ContextUtilization(llm=llm) score = await metric.single_turn_ascore(sample) ``` **之后(v0.4):** ``` from ragas.metrics.collections import ContextUtilization # or use the modern name directly: from ragas.metrics.collections import ContextPrecisionWithoutReference metric = ContextUtilization(llm=llm) # Still works (wrapper) # or metric = ContextPrecisionWithoutReference(llm=llm) # Preferred result = await metric.ascore(user_input="...", response="...", retrieved_contexts=[...]) score = result.value ``` --- ## 中断更改摘要 以下是v0.3和v0.4之间的断裂变化的完整列表: | 变动 | v0.3 | v0.4 | 移徙 | | --- | --- | --- | --- | | **评价办法** | `evaluate()` 函数 | `@experiment()` 装饰器 | 见 [评估到实验](<https://docs.ragas.io/en/stable/howtos/migrations/migrate_from_v03_to_v04/#evaluation-to-experiment>) | | **计量位置** | `ragas.metrics` | `ragas.metrics.collections` | 更新导入路径 | | **计分方法** | `single_turn_ascore(sample)` | `ascore(**kwargs)` | 更改方法调用 | | **分数返回类型** | `float` | `MetricResult` | 使用( U) `.value` 属性 | | **LLM工厂** | `instructor_llm_factory()` | `llm_factory()` | 使用统一的工厂 | | **嵌入方法** | 包装类( LangChain ) | 土著提供者 | 见 [嵌入式迁移](<https://docs.ragas.io/en/stable/howtos/migrations/migrate_from_v03_to_v04/#embeddings-migration>) | | **嵌入方法** | `embed_query()`, `embed_documents()` | `embed_text()`, `embed_texts()` | 更新方法调用 | | **ground_truths 参数** | `ground_truths: list[str]` | `reference: str` | 重命名, 更改类型 | | **样本类型** | `SingleTurnSample` | `SingleTurnSample` (更新) | 更新创建样本 | | **即时系统** | 基于数据类 | 基于函数 | 重构自定义提示 | --- ## 折旧和搬运 ### 已删除于 v0.4 这些特性已被完全删除, 并将产生错误 : - **`instructor_llm_factory()`** - 使用( U) `llm_factory()` 换成 - **AspectCritic** 从收藏 - 没有直接替换 - **SimpleCriteriaScore** 从收藏 - 没有直接替换 - **AnswerSimilarity** - 使用( U) `SemanticSimilarity` 换成 ### 已折旧(将在今后的释放中删除) 这些功能仍然有效, 但显示贬值警告 : - **`LangchainLLMWrapper`** - 使用( U) `llm_factory()` 直接 - **`LlamaIndexLLMWrapper`** - 使用( U) `llm_factory()` 直接 - **遗留的提示类** - 移动到基于函数的提示 - **`single_turn_ascore()`** - 使用收集量度 `ascore()` --- ## v0.4中的新特性(参考) v0.4在迁移要求之外引入了多个新的能力。虽然不需要从v0.3迁移,但这些功能对于您的升级可能有用 : - **GPT-5 和 o-Series 支持** - 最新 OpenAI 模型的自动约束处理 - **通用提供者支助** - 单身 `llm_factory()` 与所有主要供应商(Anthropic、Google、Azure等)合作。 - **基于函数的提示** - 更灵活和可混合的即时定义 - **计量器** - 简化自定义度量标准创建 `@discrete_metric`, `@numeric_metric`, `@ranking_metric` - **MetricResult 带原因** - 有选择性解释的结构化结果 - **增强的量子保存/ 丢失** - 方便的计量配置序列化 - **更好的嵌入支持** - 同步和同步嵌入操作 有关新特点的详细资料,见《公约》第2条。 [v0.4 发布注释](<https://docs.ragas.io/en/stable/howtos/releases/v0.4.0.md>). --- ## 自定义度量衡迁移 如果你使用移除的度量衡,比如 `AspectCritic` 或 时 间 `SimpleCriteria`, v0.4 提供了基于装饰器的替代品来替换它们。您也可以使用新的简化度量衡系统来替代其他自定义度量衡 : ### 分级计量(分类产出) **前(v0.3) - AspectCritic:** ``` from ragas.metrics import AspectCritic metric = AspectCritic(name="clarity", allowed_values=["clear", "unclear"]) result = await metric.single_turn_ascore(sample) ``` **之后(v0.4) - @discrete_metric 装饰器:** ``` from ragas.metrics import discrete_metric @discrete_metric(name="clarity", allowed_values=["clear", "unclear"]) def clarity(response: str) -> str: return "clear" if len(response) > 50 else "unclear" metric = clarity() result = await metric.ascore(response="...") print(result.value) # "clear" or "unclear" ``` 使用离散的度量衡来进行任何绝对的分类。所有已删除的度量衡( AspectCritic, SimpleCriteria) 都可以用这种方式替换 。 ### 数值( 连续值) 使用( U) `@numeric_metric` 对于任何在数字尺度上的评分: ``` from ragas.metrics import numeric_metric @numeric_metric(name="length_score", allowed_values=(0.0, 1.0)) def length_score(response: str) -> float: return min(len(response) / 500, 1.0) # Custom range @numeric_metric(name="quality_score", allowed_values=(0.0, 10.0)) def quality_score(response: str) -> float: return 7.5 metric = length_score() result = await metric.ascore(response="...") print(result.value) # float between 0 and 1 ``` ### 排名 计量(有序名单) 使用( U) `@ranking_metric` 以排列或命令多个项目: ``` from ragas.metrics import ranking_metric @ranking_metric(name="context_rank", allowed_values=5) def context_ranking(question: str, contexts: list[str]) -> list[str]: """Rank contexts by relevance.""" scored = [(len(set(question.split()) & set(c.split())), c) for c in contexts] return [c for _, c in sorted(scored, reverse=True)] metric = context_ranking() result = await metric.ascore(question="...", contexts=[...]) print(result.value) # Ranked list ``` ### 内容提要 这些装饰器提供自动验证,类型安全,错误处理,以及结果包 - 将50 + v0.3中的行的自定义度量码降低到仅仅5 - 10 lines in v0.4. --- ## 共同问题和解决办法 ### 问题:ImportError `instructor_llm_factory` **错误 :** ``` ImportError: cannot import name 'instructor_llm_factory' from 'ragas.llms' ``` **解决方案 :** ``` # Instead of this from ragas.llms import instructor_llm_factory # Use this from ragas.llms import llm_factory ``` ### 问题:计量返回 `MetricResult` 而不是浮点心 **错误 :** ``` score = await metric.ascore(...) print(score) # Prints: MetricResult(value=0.85, reason=None) ``` **解决方案 :** ``` result = await metric.ascore(...) score = result.value # Access the float value print(score) # Prints: 0.85 ``` ### 问题: `SingleTurnSample` 失踪 `ground_truths` **错误 :** ``` TypeError: ground_truths is not a valid keyword ``` **解决方案 :** ``` # Change from sample = SingleTurnSample(..., ground_truths=["correct"]) # To sample = SingleTurnSample(..., reference="correct") ``` ## 获取帮助 如果移民期间遇到问题: 1. **检查文档** - [计量文档](<https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/>) - [收藏品 API](<https://docs.ragas.io/en/stable/concepts/metrics/overview/>) - [LLM 配置](<https://docs.ragas.io/en/stable/howtos/concepts/llms/index.md>) 2. **GitHub 问题** - 搜索 [现有问题](<https://github.com/explodinggradients/ragas/issues>) - 创建一个新问题,提供与移民有关的具体细节 3. **社区支助** - [加入我们的Discord社区](<https://discord.gg/5djav8GGNZ>) - [安排一个电话](<https://cal.com/shahul-ragas/30min>) 与维护者在一起, --- ## 内容提要 v0.4代表着向基于实验的架构的根本转变,能够更好地整合评价、分析和迭代工作流程。 尽管存在突破性的变化,但它们都为让拉加斯成为更好的实验平台的目标服务。 移徙的道路是直截了当的: 1. 更新 LLM 初始化以供使用 `llm_factory()` 2. 导入度量衡 `ragas.metrics.collections` 3. 替换 `single_turn_ascore()` 与 `ascore()` 4. 重命名( E) `ground_truths` 改为: `reference` 5. 处理 `MetricResult` 对象而不是浮点 这些技术变化使: - **更好的实验** - 结构化的计量结果,以及进行更深入分析的理由 - **清洁的 API** - 关键字参数而不是样本对象使组成更加容易 - **综合工作流程** - 设计在试验管道内无缝工作的计量标准 - **加强功能** - 普遍供应商支助和自动限制 - **未来防守** - 以行业标准(教官库,标准化模式)为基础建设. 基于实验的架构在未来的发布中将继续改进,在你的评价上有更多的管理、分析和延展的功能。 祝你移民好运! 11月 13, 2026 12月 16, 2025
查看原始来源