1. 案例目标本案例展示了如何使用LlamaIndex的Workflow框架构建一个具有反思功能的结构化输出系统。该系统通过重试和错误反思机制确保大语言模型生成的输出符合预定义的JSON结构。当输出不符合要求时系统会自动提供错误反馈并重新生成直到获得有效的结构化输出或达到最大重试次数。2. 技术栈与核心依赖llama-index- LlamaIndex核心框架提供工作流功能llama-index-core- LlamaIndex核心组件包含工作流、事件和上下文管理llama-index-llms-ollama- Ollama本地语言模型集成pydantic- 数据验证和设置管理Ollama- 本地运行大语言模型的工具3. 环境配置注意本案例使用Ollama本地运行大语言模型。在运行前请确保已安装并启动Ollama并下载所需模型如llama3# 安装Ollama并下载模型 # 访问 https://ollama.com 获取安装说明 # 下载模型ollama pull llama3安装必要依赖!pip install -U llama-index llama-index-llms-ollama4. 案例实现4.1 工作流事件定义定义了两个自定义事件来控制工作流的状态转换from llama_index.core.workflow import Event class ExtractionDone(Event): output: str passage: str class ValidationErrorEvent(Event): error: str wrong_output: str passage: str4.2 数据模型定义使用Pydantic定义要提取的数据结构from pydantic import BaseModel class Car(BaseModel): brand: str model: str power: int class CarCollection(BaseModel): cars: list[Car]4.3 反思工作流类创建ReflectionWorkflow类继承自Workflow包含以下核心方法extract()- 生成结构化输出validate()- 验证输出是否符合要求import json from llama_index.core.workflow import ( Workflow, StartEvent, StopEvent, Context, step, ) from llama_index.llms.ollama import Ollama EXTRACTION_PROMPT Context information is below: --------------------- {passage} --------------------- Given the context information and not prior knowledge, create a JSON object from the information in the context. The JSON object must follow the JSON schema: {schema} REFLECTION_PROMPT You already created this output previously: --------------------- {wrong_answer} --------------------- This caused the JSON decode error: {error} Try again, the response must contain only valid JSON code. Do not add any sentence before or after the JSON object. Do not repeat the schema. class ReflectionWorkflow(Workflow): max_retries: int 3 step async def extract( self, ctx: Context, ev: StartEvent | ValidationErrorEvent ) - StopEvent | ExtractionDone: current_retries await ctx.store.get(retries, default0) if current_retries self.max_retries: return StopEvent(resultMax retries reached) else: await ctx.store.set(retries, current_retries 1) if isinstance(ev, StartEvent): passage ev.get(passage) if not passage: return StopEvent(resultPlease provide some text in input) reflection_prompt elif isinstance(ev, ValidationErrorEvent): passage ev.passage reflection_prompt REFLECTION_PROMPT.format( wrong_answerev.wrong_output, errorev.error ) llm Ollama( modelllama3, request_timeout30, # 手动设置上下文窗口以限制内存使用 context_window8000, ) prompt EXTRACTION_PROMPT.format( passagepassage, schemaCarCollection.schema_json() ) if reflection_prompt: prompt reflection_prompt output await llm.acomplete(prompt) return ExtractionDone(outputstr(output), passagepassage) step async def validate( self, ev: ExtractionDone ) - StopEvent | ValidationErrorEvent: try: CarCollection.model_validate_json(ev.output) except Exception as e: print(Validation failed, retrying...) return ValidationErrorEvent( errorstr(e), wrong_outputev.output, passageev.passage ) return StopEvent(resultev.output)4.4 工作流运行初始化并运行反思工作流w ReflectionWorkflow(timeout120, verboseTrue) # 运行工作流 ret await w.run( passageI own two cars: a Fiat Panda with 45Hp and a Honda Civic with 330Hp. ) print(ret)5. 案例效果该反思工作流实现了以下功能能够从非结构化文本中提取结构化数据自动验证输出是否符合预定义的JSON结构当验证失败时提供错误反馈并重新生成限制最大重试次数防止无限循环使用本地模型保护数据隐私示例输出{ cars: [ { brand: Fiat, model: Panda, power: 45 }, { brand: Honda, model: Civic, power: 330 } ] }6. 案例实现思路本案例的实现基于以下核心思路事件驱动循环通过事件系统实现生成-验证-重试的循环流程结构化验证使用Pydantic模型验证JSON输出的结构和类型错误反馈将验证错误信息反馈给模型指导其生成正确的输出重试机制设置最大重试次数平衡成功率和资源消耗本地模型使用Ollama本地运行模型确保数据隐私和降低延迟7. 扩展建议多模型支持支持切换不同的语言模型比较不同模型的输出质量动态重试策略根据错误类型调整重试策略如针对特定错误类型提供更精确的反馈复杂结构支持支持更复杂的嵌套数据结构和验证规则批量处理扩展为批量处理多个文本提高处理效率性能监控添加性能指标收集如重试次数、处理时间等人机交互在多次重试失败后引入人工干预机制缓存机制对相似输入实现缓存减少重复计算8. 总结本案例展示了如何使用LlamaIndex的Workflow框架构建一个具有反思功能的结构化输出系统。通过事件驱动的工作流设计实现了生成、验证和重试的循环过程确保输出符合预定义的结构。该系统特别适用于需要高精度结构化数据提取的场景如信息抽取、数据转换等。通过本地模型和自定义验证逻辑可以在保证数据隐私的同时提高输出的准确性和可靠性。
阅读完成 · 觉得有帮助?