ragas官方文档中文版(六十)

发布时间:2026/7/9 9:42:17
ragas官方文档中文版(六十) 操作指南本节中的每个指南都针对您作为有经验的用户在使用 Ragas 时可能遇到的实际问题提供了专注的解决方案。这些指南设计得简洁直接为您的问题提供快速解决方案。我们假设您对 Ragas 的概念有基本了解且能够熟练使用。如果不是请先浏览 快速入门 Get Started部分。AG-UIAG-UI 是一种基于事件的协议用于将智能体更新流式传输到用户界面。该协议标准化了消息、工具调用和状态事件使不同的智能体运行时能够轻松接入可视化前端。 ragas.integrations.ag_ui 模块帮助您将这些事件流转换为 Ragas 消息对象并使用现代 experiment 装饰器模式对实时 AG-UI 端点运行实验。本指南假设您已经有一个兼容 AG-UI 的智能体在运行例如使用 Google ADK、PydanticAI 或 CrewAI 构建的智能体并且您熟悉在 Ragas 中创建数据集。安装集成AG-UI 辅助工具位于可选的 extras 包中。将其与评估器 LLM 所需的依赖一起安装。在 Jupyter 或 IPython 中运行时包含 nest_asyncio 以便您可以重用笔记本的事件循环。pipinstallragas[ag-ui]python-dotenv nest_asyncio配置您的评估器 LLM 凭证。例如如果使用 OpenAI 模型# .envOPENAI_API_KEYsk-...在 Python 中加载环境变量后再运行示例fromdotenvimportload_dotenvimportnest_asyncio load_dotenv()# If youre inside Jupyter/IPython, patch the running event loop once.nest_asyncio.apply()构建实验数据集数据集可以包含单轮或多轮样本。使用 AG-UI您可以测试任一种模式——带有自由格式响应的单个问题或包含工具调用的较长对话。单轮样本当您只需要对最终答案文本进行评分时使用 Dataset.from_pandas() 和 user_input 、 reference 列。importpandasaspdfromragas.datasetimportDataset scientist_questionsDataset.from_pandas(pd.DataFrame([{user_input:Who originated the theory of relativity?,reference:Albert Einstein originated the theory of relativity.,},{user_input:Who discovered penicillin and when?,reference:Alexander Fleming discovered penicillin in 1928.,},]),namescientist_questions,backendinmemory,)带有工具期望的多轮样本当您想要对中间智能体行为进行评分例如它是否正确调用工具并实现用户目标时使用对话列表作为 user_input 。提供预期的工具调用JSON 格式并可选地提供参考结果用于目标准确度评估。importjsonimportpandasaspdfromragas.datasetimportDatasetfromragas.messagesimportHumanMessage weather_queriesDataset.from_pandas(pd.DataFrame([{user_input:[HumanMessage(contentWhats the weather in Paris?)],reference_tool_calls:json.dumps([{name:get_weather,args:{location:Paris}}]),# Expected outcome for AgentGoalAccuracyWithReferencereference:The user received the current weather conditions for Paris.,},{user_input:[HumanMessage(contentIs it raining in London right now?)],reference_tool_calls:json.dumps([{name:get_weather,args:{location:London}}]),reference:The user received the current weather conditions for London.,},]),nameweather_queries,backendinmemory,)从 CSV 加载对于较大的数据集将测试用例存储在 CSV 文件中并使用 Dataset API 加载fromragas.datasetimportDataset datasetDataset.load(namescientist_biographies,backendlocal/csv,root_dir./test_data,)选择指标和评估器模型该集成适用于任何 Ragas 指标。要解锁现代 collections 组合并混合自定义检查为评估器提示构建一个兼容 Instructor 的 LLM并使用同步 OpenAI 客户端进行嵌入。fromopenaiimportAsyncOpenAI,OpenAIfromragas.llmsimportllm_factoryfromragas.embeddingsimportembedding_factoryfromragas.metricsimportDiscreteMetricfromragas.metrics.collectionsimport(AgentGoalAccuracyWithReference,AnswerRelevancy,FactualCorrectness,ToolCallF1,)async_llm_clientAsyncOpenAI()evaluator_llmllm_factory(gpt-4o-mini,clientasync_llm_client)# AnswerRelevancys embeddings still run synchronously, so pair it with a sync client.embedding_clientOpenAI()evaluator_embeddingsembedding_factory(openai,modeltext-embedding-3-small,clientembedding_client,interfacemodern)conciseness_metricDiscreteMetric(nameconciseness,allowed_values[verbose,concise],prompt(Is the response concise and efficiently conveys information?\n\nResponse: {response}\n\nAnswer with only verbose or concise.),)# Metrics for single-turn QA evaluationqa_metrics[FactualCorrectness(llmevaluator_llm,modef1,atomicityhigh,coveragehigh),AnswerRelevancy(llmevaluator_llm,embeddingsevaluator_embeddings,strictness2),conciseness_metric,]# Metrics for multi-turn agent evaluation# - ToolCallF1: Rule-based metric for tool call accuracy# - AgentGoalAccuracyWithReference: LLM-based metric for goal achievementtool_metrics[ToolCallF1(),AgentGoalAccuracyWithReference(llmevaluator_llm),]使用 experiment 运行实验AG-UI 集成提供 run_ag_ui_row() 来调用您的端点并使用智能体的响应丰富每一行。将其与 experiment 装饰器结合使用来构建评估管道。⚠️ 端点必须暴露 AG-UI SSE 流。常见路径包括 /chat 、 /agent 或 /agentic_chat 。基本单轮评估在 Jupyter 或 IPython 中使用顶层 await 在 nest_asyncio.apply() 之后而不是 asyncio.run 以避免事件循环已在运行错误。对于脚本您可以使用 asyncio.run 。fromragasimportexperimentfromragas.integrations.ag_uiimportrun_ag_ui_rowfromragas.metrics.collectionsimportFactualCorrectnessexperiment()asyncdeffactual_experiment(row):# Call AG-UI endpoint and get enriched rowenrichedawaitrun_ag_ui_row(row,http://localhost:8000/chat)# Score with metricsscoreawaitFactualCorrectness(llmevaluator_llm).ascore(responseenriched[response],referencerow[reference],)return{**enriched,factual_correctness:score.value}# Run the experiment against the dataset# In Jupyter/IPython (after calling nest_asyncio.apply())factual_resultawaitfactual_experiment.arun(scientist_questions,namescientist_qa_eval)# In a standalone script, use:# factual_result asyncio.run(factual_experiment.arun(scientist_questions, namescientist_qa_eval))factual_result.to_pandas()生成的 dataframe 包含每个样本的分数、原始智能体响应以及任何检索到的上下文工具结果。结果由实验框架自动保存您可以通过 pandas 导出为 CSV。多轮工具评估对于多轮数据集和工具评估将消息和参考工具调用直接传递给指标importjsonfromragasimportexperimentfromragas.integrations.ag_uiimportrun_ag_ui_rowfromragas.messagesimportToolCallfromragas.metrics.collectionsimportAgentGoalAccuracyWithReference,ToolCallF1experiment()asyncdeftool_experiment(row):# Call AG-UI endpoint and get enriched rowenrichedawaitrun_ag_ui_row(row,http://localhost:8000/chat)# Parse reference_tool_calls from JSON string (e.g., from CSV)ref_tool_calls_rawrow.get(reference_tool_calls)ifisinstance(ref_tool_calls_raw,str):ref_tool_calls[ToolCall(**tc)fortcinjson.loads(ref_tool_calls_raw)]else:ref_tool_callsref_tool_calls_rawor[]# Score with tool metrics using the modern collections APIf1_resultawaitToolCallF1().ascore(user_inputenriched[messages],reference_tool_callsref_tool_calls,)goal_resultawaitAgentGoalAccuracyWithReference(llmevaluator_llm).ascore(user_inputenriched[messages],referencerow.get(reference,),)return{**enriched,tool_call_f1:f1_result.value,agent_goal_accuracy:goal_result.value,}# Run the experiment# In Jupyter/IPythontool_resultawaittool_experiment.arun(weather_queries,nameweather_tool_eval)# Or in a script# tool_result asyncio.run(tool_experiment.arun(weather_queries, nameweather_tool_eval))tool_result.to_pandas()如果请求失败实验会记录错误并为该样本返回占位符值以便实验可以继续处理剩余样本。直接处理 AG-UI 事件有时您可能希望单独收集事件日志——也许来自已记录的运行或预发布环境——并离线评估它们。转换辅助工具公开了与 run_ag_ui_row() 相同的解析逻辑。fromragas.integrations.ag_uiimportconvert_to_ragas_messagesfromag_ui.coreimportTextMessageChunkEvent events[TextMessageChunkEvent(message_idassistant-1,roleassistant,deltaHello from AG-UI!,timestamp2024-12-01T00:00:00Z,)]ragas_messagesconvert_to_ragas_messages(events,metadataTrue)如果您已经有 MessagesSnapshotEvent 可以跳过流式重构并调用 convert_messages_snapshot 。fromragas.integrations.ag_uiimportconvert_messages_snapshotfromag_ui.coreimportMessagesSnapshotEvent,UserMessage,AssistantMessage snapshotMessagesSnapshotEvent(messages[UserMessage(idmsg-1,contentHello?),AssistantMessage(idmsg-2,contentHi! How can I help you today?),])ragas_messagesconvert_messages_snapshot(snapshot)转换后的消息可用于构建自定义评估工作流或直接传递给指标评分函数。提取辅助工具集成提供辅助函数从消息中提取特定数据fromragas.integrations.ag_uiimport(extract_response,# Get concatenated AI response textextract_tool_calls,# Get all tool calls from AI messagesextract_contexts,# Get tool results/contexts)messagesconvert_to_ragas_messages(events)responseextract_response(messages)# Hello! The weather is sunny.tool_callsextract_tool_calls(messages)# [ToolCall(nameget_weather, args{location: SF})]contextsextract_contexts(messages)# [Sunny, 72F in San Francisco]生产实验提示自定义标头 通过 run_ag_ui_row() 的 extra_headers 参数传递认证令牌或租户 ID。超时 如果您的智能体执行长时间运行的工具调用请调整 timeout 参数。元数据调试 设置 metadataTrue 以在每条消息上保留 AG-UI 运行、线程和消息 ID以便于追溯。实验命名 对 .arun() 使用描述性的 name 参数以便于识别结果。完整的生产示例请参见 examples/ragas_examples/ag_ui_agent_experiments/experiments.py 其中提供端点配置的 CLI 参数基于 CSV 的测试数据集适当的日志记录和错误处理带时间戳的结果输出交互式演练笔记本也可在 howtos/integrations/ag_ui.ipynb 获取。API 参考主 APIrun_ag_ui_row(row, endpoint_url, …) - 对 AG-UI 端点运行单行数据并返回包含响应、消息、工具调用和上下文的丰富数据。转换函数convert_to_ragas_messages(events, metadataFalse) - 将 AG-UI 事件序列转换为 Ragas 消息convert_messages_snapshot(snapshot, metadataFalse) - 将 AG-UI 消息快照转换为 Ragas 消息convert_messages_to_ag_ui(messages) - 将 Ragas 消息转换为 AG-UI 格式提取辅助工具extract_response(messages) - 提取拼接的 AI 响应文本extract_tool_calls(messages) - 从 AI 消息中提取所有工具调用extract_contexts(messages) - 从消息中提取工具结果/上下文底层 APIcall_ag_ui_endpoint(endpoint_url, user_input, …) - 调用 AG-UI 端点并收集流式事件AGUIEventCollector - 从流式事件中收集并重构消息

相关新闻