news 2026/2/26 4:01:43

我如何使用 LlamaIndex 工作流简化我的研究和演示过程

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
我如何使用 LlamaIndex 工作流简化我的研究和演示过程

原文:towardsdatascience.com/how-i-streamline-my-research-and-presentation-with-llamaindex-workflows-3d75a9a10564?source=collection_archive---------3-----------------------#2024-09-10

一个通过 AI 工作流实现可靠性、灵活性和可控性的示例

https://medium.com/@lzchen.cs?source=post_page---byline--3d75a9a10564--------------------------------https://towardsdatascience.com/?source=post_page---byline--3d75a9a10564-------------------------------- Lingzhen Chen

·发表于 Towards Data Science ·16 分钟阅读·2024 年 9 月 10 日

LlamaIndex 最近推出了一项新功能:工作流。对于那些希望创建既可靠又灵活的 AI 解决方案的人来说,这非常有用。为什么呢?因为它允许你定义具有控制流的自定义步骤。它支持循环、反馈和错误处理。它就像一个 AI 驱动的管道。但与通常实现为有向无环图(DAG)的典型管道不同,工作流还支持循环执行,使其成为实现代理式和其他更复杂过程的良好候选。

[## Introducing workflows beta: a new way to create complex AI applications with LlamaIndex …

LlamaIndex 是一个简单灵活的数据框架,用于将自定义数据源连接到大型语言模型(LLMs)。

www.llamaindex.ai](https://www.llamaindex.ai/blog/introducing-workflows-beta-a-new-way-to-create-complex-ai-applications-with-llamaindex?source=post_page-----3d75a9a10564--------------------------------)

在这篇文章中,我将展示如何使用 LlamaIndex 工作流简化我的研究过程,帮助我研究某个主题的最新进展,然后将这些研究成果转化为 PowerPoint 演示文稿。

当涉及到查找新的研究出版物或论文时,ArXiv.org是我主要的来源。然而,网站上的论文非常多。截至 2024 年 9 月,ArXiv 上大约有 250 万篇论文,其中 17,000 篇是仅在 8 月份提交的(统计数据在这里)。即使限制在一个特定主题下,要阅读的内容依然非常庞大。但这并不是一个新问题。长期以来,学术研究人员必须浏览大量的文献以进行自己的研究。过去两年大型语言模型(LLM)的兴起为我们提供了诸如ResearchGPT、papersGPT和许多在OpenAI平台上为特定研究目的构建的定制 GPT 工具,这些工具有助于文献搜索、摘要提取和展示。

尽管这些工具很有用,但我选择使用 LlamaIndex 工作流来构建自己的工作流,原因有几个关键点:

我将设置一个工作流,用户提供一个研究主题(例如:“使用 GenAI 制作 PowerPoint 幻灯片”),然后从 arxiv.org 网站拉取几篇论文,并使用 LLM 对每篇论文进行总结。更具体地说,我希望总结的一些关键信息包括:方法类型、模型的组件、预训练或微调方法、数据集、评估方法指标和结论。所有这些的输出将是一个 PowerPoint 演示文稿,每篇论文一张幻灯片,包含来自总结的关键洞见。

在我解释如何实现这个工作流之前,理解 LlamaIndex 工作流中的两个关键概念非常重要:事件步骤

LlamaIndex 提供了几个笔记本示例和视频系列,详细介绍了这些概念。

除了基本组件外,我的工作流还使用了:

你可以在Github上找到这个工作流的完整代码。要运行它,你需要 Tavily 搜索、Semantic Scholar 和 Azure OpenAI 的 API 密钥(由于这个实现使用了 Azure 资源,但你可以很容易地将其切换为 OpenAI 或其他模型,使用 LlamaIndex)。在接下来的部分,我将介绍一些构建这个工作流的关键细节和步骤。

主工作流

主工作流由两个嵌套的子工作流组成:

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/96f12d1104e4621f16076bdf2db26ea8.png

主工作流概述(作者提供的图像)

摘要生成子工作流

让我们仔细看看这些子工作流。首先是summary_gen工作流,它相当简单。它遵循一个简单的线性过程。它基本上作为一个“数据处理”工作流,某些步骤会向 LLM 发送请求。

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/6b509b343f1fef98f8c97632785d934f.png

摘要生成工作流(作者提供的图像)

工作流首先通过获取用户输入(一个研究主题)开始,并经过以下步骤:

@step(num_workers=4)asyncdeffilter_papers(self,ev:PaperEvent)->FilteredPaperEvent:llm=new_gpt4o_mini(temperature=0.0)response=awaitprocess_citation(ev.paper,llm)returnFilteredPaperEvent(paper=ev.paper,is_relevant=response)

process_citation()函数中,我们使用LlamaIndex 的 FunctionCallingProgram来获取结构化的响应:

IS_CITATION_RELEVANT_PMT=""" You help a researcher decide whether a paper is relevant to their current research topic: {topic} You are given the title and abstract of a paper. title: {title} abstract: {abstract} Give a score indicating the relevancy to the research topic, where: Score 0: Not relevant Score 1: Somewhat relevant Score 2: Very relevant Answer with integer score 0, 1 or 2 and your reason. """classIsCitationRelevant(BaseModel):score:intreason:strasyncdefprocess_citation(citation,llm):program=FunctionCallingProgram.from_defaults(llm=llm,output_cls=IsCitationRelevant,prompt_template_str=IS_CITATION_RELEVANT_PMT,verbose=True,)response=awaitprogram.acall(title=citation.title,abstract=citation.summary,topic=citation.topic,description="Data model for whether the paper is relevant to the research topic.",)returnresponse
@step(pass_context=True)asyncdefpaper2summary_dispatcher(self,ctx:Context,ev:Paper2SummaryDispatcherEvent)->Paper2SummaryEvent:ctx.data["n_pdfs"]=0forpdf_nameinPath(ev.papers_path).glob("*.pdf"):img_output_dir=self.papers_images_path/pdf_name.stem img_output_dir.mkdir(exist_ok=True,parents=True)summary_fpath=self.paper_summary_path/f"{pdf_name.stem}.md"ctx.data["n_pdfs"]+=1self.send_event(Paper2SummaryEvent(pdf_path=pdf_name,image_output_dir=img_output_dir,summary_path=summary_fpath,))
SUMMARIZE_PAPER_PMT=""" You are an AI specialized in summarizing scientific papers. Your goal is to create concise and informative summaries, with each section preferably around 100 words and limited to a maximum of 200 words, focusing on the core approach, methodology, datasets, evaluation details, and conclusions presented in the paper. After you summarize the paper, save the summary as a markdown file. Instructions: - Key Approach: Summarize the main approach or model proposed by the authors. Focus on the core idea behind their method, including any novel techniques, algorithms, or frameworks introduced. - Key Components/Steps: Identify and describe the key components or steps in the model or approach. Break down the architecture, modules, or stages involved, and explain how each contributes to the overall method. - Model Training/Finetuning: Explain how the authors trained or finetuned their model. Include details on the training process, loss functions, optimization techniques, and any specific strategies used to improve the model’s performance. - Dataset Details: Provide an overview of the datasets used in the study. Include information on the size, type and source. Mention whether the dataset is publicly available and if there are any benchmarks associated with it. - Evaluation Methods and Metrics: Detail the evaluation process used to assess the model's performance. Include the methods, benchmarks, and metrics employed. - Conclusion: Summarize the conclusions drawn by the authors. Include the significance of the findings, any potential applications, limitations acknowledged by the authors, and suggested future work. Ensure that the summary is clear and concise, avoiding unnecessary jargon or overly technical language. Aim to be understandable to someone with a general background in the field. Ensure that all details are accurate and faithfully represent the content of the original paper. Avoid introducing any bias or interpretation beyond what is presented by the authors. Do not add any information that is not explicitly stated in the paper. Stick to the content presented by the authors. """

如果此工作流独立运行,执行将在此处结束。然而,由于这是主流程的一个子工作流,完成后将触发下一个子工作流——slide_gen

幻灯片生成子工作流

此工作流基于前一步骤中创建的摘要生成幻灯片。以下是slide_gen工作流的概述:

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/573a6a77435fb934c9b90afff1c6acce.png

幻灯片生成工作流(图片来自作者)

当前一个子工作流完成且摘要 Markdown 文件准备好时,启动以下工作流:

@step(pass_context=True)asyncdefgather_feedback_outline(self,ctx:Context,ev:OutlineEvent)->OutlineFeedbackEvent|OutlineOkEvent:"""Present user the original paper summary and the outlines generated, gather feedback from user"""print(f"the original summary is:{ev.summary}")print(f"the outline is:{ev.outline}")print("Do you want to proceed with this outline? (yes/no):")feedback=input()iffeedback.lower().strip()in["yes","y"]:returnOutlineOkEvent(summary=ev.summary,outline=ev.outline)else:print("Please provide feedback on the outline:")feedback=input()returnOutlineFeedbackEvent(summary=ev.summary,outline=ev.outline,feedback=feedback)
@step(pass_context=True)asyncdefslide_gen(self,ctx:Context,ev:OutlinesWithLayoutEvent)->SlideGeneratedEvent:agent=ReActAgent.from_tools(tools=self.azure_code_interpreter.to_tool_list()+[self.all_layout_tool],llm=new_gpt4o(0.1),verbose=True,max_iterations=50,)prompt=(SLIDE_GEN_PMT.format(json_file_path=ev.outlines_fpath.as_posix(),template_fpath=self.slide_template_path,final_slide_fname=self.final_slide_fname,)+REACT_PROMPT_SUFFIX)agent.update_prompts({"agent_worker:system_prompt":PromptTemplate(prompt)})res=self.azure_code_interpreter.upload_file(local_file_path=self.slide_template_path)logging.info(f"Uploaded file to Azure:{res}")response=agent.chat(f"An example of outline item in json is{ev.outline_example.json()},"f" generate a slide deck")local_files=self.download_all_files_from_session()returnSlideGeneratedEvent(pptx_fpath=f"{self.workflow_artifacts_path}/{self.final_slide_fname}")
@step(pass_context=True)asyncdefvalidate_slides(self,ctx:Context,ev:SlideGeneratedEvent)->StopEvent|SlideValidationEvent:"""Validate the generated slide deck"""ctx.data["n_retry"]+=1ctx.data["latest_pptx_file"]=Path(ev.pptx_fpath).name img_dir=pptx2images(Path(ev.pptx_fpath))image_documents=SimpleDirectoryReader(img_dir).load_data()llm=mm_gpt4o program=MultiModalLLMCompletionProgram.from_defaults(output_parser=PydanticOutputParser(SlideValidationResult),image_documents=image_documents,prompt_template_str=SLIDE_VALIDATION_PMT,multi_modal_llm=llm,verbose=True,)response=program()ifresponse.is_valid:returnStopEvent(self.workflow_artifacts_path.joinpath(self.final_slide_fname))else:ifctx.data["n_retry"]<self.max_validation_retries:returnSlideValidationEvent(result=response)else:returnStopEvent(f"The slides are not fixed after{self.max_validation_retries}retries!")

用于验证的标准是:

SLIDE_VALIDATION_PMT=""" You are an AI that validates the slide deck generated according to following rules: - The slide need to have a front page - The slide need to have a final page (e.g. a 'thank you' or 'questions' page) - The slide texts are clearly readable, not cut off, not overflowing the textbox and not overlapping with other elements If any of the above rules are violated, you need to provide the index of the slide that violates the rule, as well as suggestion on how to fix it. """

为了运行完整的端到端工作流,我们通过以下步骤启动过程:

classSummaryAndSlideGenerationWorkflow(Workflow):@stepasyncdefsummary_gen(self,ctx:Context,ev:StartEvent,summary_gen_wf:SummaryGenerationWorkflow)->SummaryWfReadyEvent:print("Need to run reflection")res=awaitsummary_gen_wf.run(user_query=ev.user_query)returnSummaryWfReadyEvent(summary_dir=res)@stepasyncdefslide_gen(self,ctx:Context,ev:SummaryWfReadyEvent,slide_gen_wf:SlideGenerationWorkflow)->StopEvent:res=awaitslide_gen_wf.run(file_dir=ev.summary_dir)returnStopEvent()asyncdefrun_workflow(user_query:str):wf=SummaryAndSlideGenerationWorkflow(timeout=2000,verbose=True)wf.add_workflows(summary_gen_wf=SummaryGenerationWorkflow(timeout=800,verbose=True))wf.add_workflows(slide_gen_wf=SlideGenerationWorkflow(timeout=1200,verbose=True))result=awaitwf.run(user_query=user_query,)print(result)@click.command()@click.option("--user-query","-q",required=False,help="The user query",default="powerpoint slides automation",)defmain(user_query:str):asyncio.run(run_workflow(user_query))if__name__=="__main__":draw_all_possible_flows(SummaryAndSlideGenerationWorkflow,filename="summary_slide_gen_flows.html")main()

结果

现在让我们看一下为论文LayoutGPT: 基于大语言模型的组合视觉规划与生成生成的一个中间总结示例:

# Summary of "LayoutGPT: Compositional Visual Planning and Generation with Large Language Models"## Key ApproachThe paper introduces LayoutGPT,a framework leveraging large language models(LLMs)forcompositional visual planningandgeneration.The core ideaisto utilize LLMs to generate2Dand3Dscene layoutsfromtextual descriptions,integrating numericalandspatial reasoning.LayoutGPT employs a novel prompt construction methodandin-context learning to enhance the model's ability to understandandgeneratecomplexvisual scenes.## Key Components/Steps1\.**Prompt Construction**:LayoutGPT uses detailed task instructionsandCSS-like structures to guide the LLMsingenerating layouts.2\.**In-Context Learning**:Demonstrative exemplars are provided to the LLMs to improve their understandingandgeneration capabilities.3\.**NumericalandSpatial Reasoning**:The model incorporates reasoning capabilities to handle numericalandspatial relationshipsinscene generation.4\.**Scene Synthesis**:LayoutGPT generates2Dkeypoint layoutsand3Dscene layouts,ensuring spatial coherenceandobjectplacement accuracy.## Model Training/FinetuningLayoutGPTisbuilt on GPT-3.5andGPT-4models,utilizingin-context learning rather than traditional finetuning.The training process involves providing the modelwithstructured promptsandexamples to guide its generation process.Loss functionsandoptimization techniques arenotexplicitly detailed,asthe focusison leveraging pre-trained LLMswithminimal additional training.## Dataset DetailsThe study uses several datasets:-**NSR-1K**:A new benchmarkfornumericalandspatial reasoning,createdfromMSCOCO annotations.-**3D-FRONT**:Usedfor3Dscene synthesis,containing diverse indoor scenes.-**HRS-Bench**:For evaluating color binding accuracyingenerated scenes.These datasets are publicly availableandserveasbenchmarksforevaluating the model's performance.## Evaluation Methods and MetricsThe evaluation involves:-**Quantitative Metrics**:Precision,recall,andF1 scoresforlayout accuracy,numerical reasoning,andspatial reasoning.-**Qualitative Analysis**:Visual inspection of generated scenes to assess spatial coherenceandobjectplacement.-**Comparative Analysis**:Benchmarking against existing methods like GLIGENandATISS to demonstrate improvementsinlayout generation.## ConclusionThe authors conclude that LayoutGPT effectively integrates LLMsforvisual planningandscene generation,achieving state-of-the-art performancein2Dand3Dlayout tasks.The framework's ability to handle numerical and spatial reasoning is highlighted as a significant advancement. Limitations include the focus on specific scene types and the need for further exploration of additional visual reasoning tasks. Future work suggests expanding the model's capabilities to more diverseandcomplexvisual scenarios.

毋庸置疑,总结对于 LLM 来说并不是一个特别具有挑战性的任务。只需提供论文的图像,LLM 便能有效地捕捉到提示中概述的所有关键内容,并且相当好地遵循了样式要求。

至于最终结果,以下是生成的几张演示文稿幻灯片示例:

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/2fb32b9b194336ba795dc312262a1d0b.png

生成的幻灯片(图片由作者提供)

https://github.com/OpenDocCN/towardsdatascience-blog-zh-2024/raw/master/docs/img/1ca329172991fe913dde582b525f045c.png

生成的幻灯片(图片由作者提供)

在填写摘要内容时,按照模板的布局保持文本风格,将总结要点以项目符号格式呈现,并包含幻灯片中所需的所有相关论文时,工作流程运行得很好。唯一的问题是,有时主内容占位符中的文本没有调整大小以适应文本框,文本溢出幻灯片边界。这类错误可能通过使用更有针对性的幻灯片验证提示来修复。

最后的想法

在本文中,我展示了如何使用 LlamaIndex 工作流程来简化我的研究和展示过程,从查询学术论文到生成最终的 PowerPoint 幻灯片。以下是我在实施该工作流程时的一些想法和观察,以及我认为可能改进的方面。

**gpt-4o**模型与**gpt-4o-mini**模型:虽然声称gpt-4o-mini的性能与gpt-4o相当,但我发现gpt-4o-mini在完成复杂任务时明显存在问题,如在工作流程中作为 ReAct 代理进行规划和修正错误。然而,它在简单任务(如内容摘要)中表现得足够好。

创建中间文件:生成中间文件(摘要的 Markdown 文件和摘要布局的 JSON 文件)是一个有用的方法,它减轻了代理必须跟踪内容和幻灯片样式的负担,同时生成幻灯片的代码。

处理边缘案例:从头到尾运行工作流程揭示了许多边缘案例,特别是在验证幻灯片样式时。目前,通过迭代修改相关提示来处理这些问题。但我认为,促进某种类型的协作和人类参与机制将大大有助于此,同时也能提供更高的准确性。

python-pptx 的局限性。工作流程受限于 python-pptx 在 PowerPoint 幻灯片中能够实际渲染和操作的内容。因此,值得进一步考虑其他高效的幻灯片生成方式,例如使用 VBA。

用于摘要生成的代理和工具:与严格的逐步摘要生成过程不同,使用一个或多个具有工具访问权限的代理(目前是步骤函数)可以使工作流程更灵活,更适应未来的变化。

增强人类参与的互动。目前的实现不允许太多用户交互。让最终用户更多地参与工作流程,尤其是在涉及用户判断的任务中,如内容验证和精炼,这非常有益。一个方法是增加更多步骤,工作流程可以向用户请求验证,并考虑用户的反馈。人类的参与对于实时修复错误和进行更改是无价的。

论文查询引擎。还可以为每篇论文构建查询引擎,使用户能够提出问题并根据需要修改摘要。这有助于工作流结果的个性化。

综上所述,LlamaIndex 工作流是一个非常灵活且可定制的工具,用于构建复杂且量身定制的 AI 解决方案。它让我可以自由定义我的流程,同时具备可控性和灵活性,并能够利用库中的许多内置工具。

下一步是什么?

如前所述,主要的改进将是实现更多人机协作(human-in-the-loop)类型的功能。例如,允许设置更多的交互式检查点,用户可以在需要时覆盖步骤执行,将交互步骤集成到工作流中,并提供用户在任何阶段检查工作流是否产生满意输出的机会。与提供更好用户体验的目标一致,构建Streamlit 前端也是一个不错的补充,可以提供更多关于工作流执行的深入信息。拥有前端将使得用户能够实时监控工作流的进展,并根据需要更快速地调整轨迹。此外,获取用户反馈和验证、可视化中间结果和最终输出将为工作流增加透明度。所以请关注下一篇文章,了解这些变化!😃

感谢阅读!查看我的GitHub以获取完整实现。我期待听到你的想法、意见和反馈。我目前在Inmeta担任数据科学顾问,Inmeta 是Crayon Group的一部分。欢迎在LinkedIn与我建立联系。😊

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/2/20 0:11:09

Langchain-Chatchat文档相似度去重算法详解

Langchain-Chatchat 文档相似度去重算法深度解析 在企业知识库系统日益智能化的今天&#xff0c;一个看似微小却影响深远的问题正悄然浮现&#xff1a;为什么同一个问题会得到多个几乎相同、甚至相互矛盾的答案&#xff1f; 答案往往藏在数据源头——那些被反复上传的操作手册、…

作者头像 李华
网站建设 2026/2/26 2:37:51

CoAP低功耗通信NB-IoT设备适配

CoAP与NB-IoT协同设计&#xff1a;构建超低功耗物联网通信系统 在城市地下管网深处、农田边缘的传感器桩、偏远山区的水文监测站&#xff0c;越来越多的设备正悄然运行着。它们可能数月无人问津&#xff0c;电池却要支撑五年甚至十年&#xff1b;信号微弱到手机无法连接&#x…

作者头像 李华
网站建设 2026/2/25 16:34:03

如何在全职工作的同时为一切腾出时间

原文&#xff1a;towardsdatascience.com/how-i-make-time-for-everything-even-with-a-full-time-job-d459e169646f 我以前常说&#xff0c;“我没有足够的时间。”实际上&#xff0c;我只是优先级错了&#xff0c;自从那时起&#xff0c;我显著提高了我的时间管理技能。 如此…

作者头像 李华
网站建设 2026/2/22 0:14:32

电子签名:笔迹特征比对核心算法详解

目录 一、核心算法体系&#xff08;汉王 ESP560 适配版&#xff09; 1. 底层核心算法 2. 算法设计逻辑&#xff08;针对 ESP560&#xff09; 二、笔迹特征提取&#xff08;算法前置环节&#xff09; 1. 原始数据预处理 2. 核心特征维度&#xff08;共 8 类&#xff0c;ES…

作者头像 李华
网站建设 2026/2/25 4:09:59

Vite 项目中 `node_modules/.vite/deps` 文件夹详解

在使用 Vite 构建的项目中&#xff0c;你可能会注意到一个特殊的隐藏文件夹&#xff1a; node_modules/.vite/deps/这个目录是 Vite 的依赖预构建&#xff08;Dependency Pre-Bundling&#xff09;机制的核心产物。它对开发服务器的启动速度、HMR&#xff08;热更新&#xff09…

作者头像 李华