news 2026/7/13 18:40:14

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

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
ragas官方文档中文版(六十七)

操作指南

本节中的每个指南都针对您作为有经验的用户在使用 Ragas 时可能遇到的实际问题提供了专注的解决方案。这些指南设计得简洁直接,为您的问题提供快速解决方案。我们假设您对 Ragas 的概念有基本了解且能够熟练使用。如果不是,请先浏览 快速入门 (Get Started)部分。

使用 Llama 4 评估 LlamaStack Web Search 接地性

在本教程中,我们将测量 LlamaStack 网页搜索智能体生成响应的接地性。LlamaStack 是由 Meta 维护的开源框架,用于简化大语言模型驱动应用的开发和部署。评估将使用 Ragas 指标和 Meta Llama 4 Maverick 作为评判模型进行。

设置并运行 LlamaStack 服务器

此命令安装使用 Together 推理提供程序的 LlamaStack 服务器所需的所有依赖项。

使用 conda 命令

!pipinstallragas langchain-together uv!uv run--withllama-stack llama stack build--templatetogether --image-type conda

使用 venv 命令

!pipinstallragas langchain-together uv!uv run--withllama-stack llama stack build--templatetogether --image-type venv
importosimportsubprocessdefrun_llama_stack_server_background():log_file=open("llama_stack_server.log","w")process=subprocess.Popen("uv run --with llama-stack llama stack run together --image-type venv",shell=True,stdout=log_file,stderr=log_file,text=True,)print(f"Starting LlamaStack server with PID:{process.pid}")returnprocessdefwait_for_server_to_start():importrequestsfromrequests.exceptionsimportConnectionErrorimporttime url="http://0.0.0.0:8321/v1/health"max_retries=30retry_interval=1print("Waiting for server to start",end="")for_inrange(max_retries):try:response=requests.get(url)ifresponse.status_code==200:print("\nServer is ready!")returnTrueexceptConnectionError:print(".",end="",flush=True)time.sleep(retry_interval)print("\nServer failed to start after",max_retries*retry_interval,"seconds")returnFalse# use this helper if needed to kill the serverdefkill_llama_stack_server():# Kill any existing llama stack server processesos.system("ps aux | grep -v grep | grep llama_stack.distribution.server.server | awk '{print $2}' | xargs kill -9")

启动 LlamaStack 服务器

server_process=run_llama_stack_server_background()assertwait_for_server_to_start()
Starting LlamaStack serverwithPID:95508Waitingforserver to start....Serverisready!

构建搜索智能体

fromllama_stack_clientimportLlamaStackClient,Agent,AgentEventLogger client=LlamaStackClient(base_url="http://0.0.0.0:8321",)agent=Agent(client,model="meta-llama/Llama-3.1-8B-Instruct",instructions="You are a helpful assistant. Use web search tool to answer the questions.",tools=["builtin::websearch"],)user_prompts=["In which major did Demis Hassabis complete his undergraduate degree? Search the web for the answer.","Ilya Sutskever is one of the key figures in AI. From which institution did he earn his PhD in machine learning? Search the web for the answer.","Sam Altman, widely known for his role at OpenAI, was born in which American city? Search the web for the answer.",]session_id=agent.create_session("test-session")forpromptinuser_prompts:response=agent.create_turn(messages=[{"role":"user","content":prompt,}],session_id=session_id,)forloginAgentEventLogger().log(response):log.print()

现在,让我们深入了解智能体的执行步骤,看看我们的智能体表现如何。

session_response=client.agents.session.retrieve(session_id=session_id,agent_id=agent.agent_id,)

评估智能体响应

我们希望测量 LlamaStack 网页搜索智能体生成响应的接地性。为此,我们需要 EvaluationDataset 和指标来评估接地响应。Ragas 提供了一系列现成的指标,可用于测量检索和生成的各个方面。

用于测量响应接地性的指标:

  1. 忠实度(Faithfulness)
  2. 响应接地性(Response Groundedness)
构建 Ragas 评估数据集

要使用 Ragas 进行评估,我们将创建一个 EvaluationDataset 。

importjson# This function extracts the search results for the trace of each querydefextract_retrieved_contexts(turn_object):results=[]forstepinturn_object.steps:ifstep.step_type=="tool_execution":tool_responses=step.tool_responsesforresponseintool_responses:content=response.contentifcontent:try:parsed_result=json.loads(content)results.append(parsed_result)exceptjson.JSONDecodeError:print("Warning: Unable to parse tool response content as JSON.")continueretrieved_context=[]forresultinresults:top_content_list=[item["content"]foriteminresult["top_k"]]retrieved_context.extend(top_content_list)returnretrieved_context
fromragas.dataset_schemaimportEvaluationDataset samples=[]references=["Demis Hassabis completed his undergraduate degree in Computer Science.","Ilya Sutskever earned his PhD from the University of Toronto.","Sam Altman was born in Chicago, Illinois.",]fori,turninenumerate(session_response.turns):samples.append({"user_input":turn.input_messages[0].content,"response":turn.output_message.content,"reference":references[i],"retrieved_contexts":extract_retrieved_contexts(turn),})ragas_eval_dataset=EvaluationDataset.from_list(samples)
ragas_eval_dataset.to_pandas()
user_inputretrieved_contextsresponsereference
0In which major did Demis Hassabis complete his…[Demis Hassabis holds a Bachelor’s degree in C…Demis Hassabis completed his undergraduate deg…Demis Hassabis completed his undergraduate deg…
1Ilya Sutskever is one of the key figures in AI…[Jump to content Main menu Search Donate Creat…Ilya Sutskever earned his PhD in machine learn…Ilya Sutskever earned his PhD from the Univers…
2Sam Altman, widely known for his role at OpenA…[Sam AltmanBiography, OpenAI, Microsoft, & …Sam Altman was born in Chicago, Illinois, USA.
设置 Ragas 指标
fromragas.metricsimportAnswerAccuracy,Faithfulness,ResponseGroundednessfromlangchain_togetherimportChatTogetherfromragas.llmsimportLangchainLLMWrapper llm=ChatTogether(model="meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",)evaluator_llm=LangchainLLMWrapper(llm)ragas_metrics=[AnswerAccuracy(llm=evaluator_llm),Faithfulness(llm=evaluator_llm),ResponseGroundedness(llm=evaluator_llm),]

评估

最后,让我们运行评估。

fromragasimportevaluate results=evaluate(dataset=ragas_eval_dataset,metrics=ragas_metrics)results.to_pandas()
fromragasimportevaluate results=evaluate(dataset=ragas_eval_dataset,metrics=ragas_metrics)results.to_pandas()
user_inputretrieved_contextsresponsereferencenv_accuracyfaithfulnessnv_response_groundedness
0In which major did Demis Hassabis complete his…[Demis Hassabis holds a Bachelor’s degree in C…Demis Hassabis completed his undergraduate deg…Demis Hassabis completed his undergraduate deg…1.01.01.00
1Ilya Sutskever is one of the key figures in AI…[Jump to content Main menu Search Donate Creat…Ilya Sutskever earned his PhD in machine learn…Ilya Sutskever earned his PhD from the Univers…1.00.50.75
2Sam Altman, widely known for his role at OpenA…[Sam Altman Biography, OpenAI, Microsoft, & …Sam Altman was born in Chicago, Illinois, USA.Sam Altman was born in Chicago, Illinois.1.01.01.00
kill_llama_stack_server()
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/7/13 18:31:06

如何快速配置洛雪音乐高品质音源:新手完整指南

如何快速配置洛雪音乐高品质音源:新手完整指南 【免费下载链接】lxmusic- lxmusic(洛雪音乐)全网最新最全音源 项目地址: https://gitcode.com/gh_mirrors/lx/lxmusic- 想要在洛雪音乐中享受全网最高品质的音乐体验吗?音源配置是关键!…

作者头像 李华
网站建设 2026/7/13 18:29:44

鸣潮终极自动化指南:基于图像识别的智能后台战斗助手

鸣潮终极自动化指南:基于图像识别的智能后台战斗助手 【免费下载链接】ok-wuthering-waves 鸣潮 后台自动战斗 自动刷声骸 一键日常 Automation for Wuthering Waves 项目地址: https://gitcode.com/GitHub_Trending/ok/ok-wuthering-waves 还在为《鸣潮》中…

作者头像 李华
网站建设 2026/7/13 18:27:07

AtlasOS:解锁Windows游戏性能潜能的终极优化框架

AtlasOS:解锁Windows游戏性能潜能的终极优化框架 【免费下载链接】Atlas 🚀 An open and lightweight modification to Windows, designed to optimize performance, privacy and usability. 项目地址: https://gitcode.com/GitHub_Trending/atlas1/At…

作者头像 李华
网站建设 2026/7/13 18:26:20

如何通过API逆向工程实现国家中小学智慧教育平台电子教材的自动化下载

如何通过API逆向工程实现国家中小学智慧教育平台电子教材的自动化下载 【免费下载链接】tchMaterial-parser 国家中小学智慧教育平台 电子课本下载工具,帮助您从智慧教育平台中获取电子课本的 PDF 文件网址并进行下载,让您更方便地获取课本内容。 项目…

作者头像 李华
网站建设 2026/7/13 18:25:26

xAI Grok Build CLI 网络分析:文件与仓库上传、存储目的地揭秘

xAI 的 Grok Build CLI 实际发送给 xAI 的内容:网络层面分析这是一次经过严谨测量且可复现的拆解,研究结果有捕获到的工件和复现命令作为支撑。所有捕获的流量均来自本人机器上的操作,使用的是一个包含虚假“金丝雀”机密的一次性仓库&#x…

作者头像 李华