LangChain 源码剖析-内置中间件详解(Built-in middleware)LangChain 提供了针对常见用例的预构建中间件。每种中间件均可开箱即用,并可根据您的具体需求进行配置。内置的中间件以下中间件可与任何大型语言模型(LLM)供应商兼容:Summarization:当接近令牌限制时,自动总结对话历史。 Human-in-the-loop:暂停执行,以便人工批准工具调用。 Model call limit:限制模型调用的次数,以防止成本过高。 Tool call limit:通过限制调用次数来控制工具执行。 Model fallback:当主模型失败时,自动回退到替代模型。 PII detection:检测和处理个人身份信息(PII)。 To-dolist:为代理人配备任务规划和跟踪能力。 LLM tool selector:在调用主模型之前,使用LLM选择相关工具。 Tool retry:使用指数回退自动重试失败的工具调用。 Model retry:使用指数回退自动重试失败的模型调用。 LLM tool emulator:出于测试目的,使用LLM模拟工具执行。 Context editing:通过修剪或清除工具使用来管理对话上下文。 Shell tool:将持久shell会话暴露给代理以执行命令。 File search:在文件系统文件上提供Glob和Grep搜索工具。Summarization当接近令牌限制时,自动总结对话历史,在压缩旧上下文的同时保留最近的消息。总结对以下方面有用:超过上下文窗口的长时间对话。历史悠久的多回合对话。保留完整对话上下文很重要的应用程序。API参考fromlangchain.agentsimportcreate_agentfromlangchain.agents.middlewareimportSummarizationMiddleware agent=create_agent(model="gpt-4o",tools=[your_weather_tool,your_calculator_tool],middleware=[SummarizationMiddleware(model="gpt-4o-mini",trigger=("tokens",4000),keep=("messages",20),),],)完整案例fromlangchain.agentsimportcreate_agentfromlangchain.agents.middlewareimportSummarizationMiddleware# Single condition: trigger if tokens = 4000 AND messages = 10agent=create_agent(model="gpt-4o",tools=[your_weather_tool,your_calculator_tool],middleware=[SummarizationMiddleware(model="gpt-4o-mini",trigger=[("tokens",4000),("messages",10)],keep=("messages",20),),],)# Multiple conditionsagent2=create_agent(model="gpt-4o",tools=[your_weather_tool,your_calculator_tool],middleware=[SummarizationMiddleware(model="gpt-4o-mini",trigger=[("tokens",3000),("messages",6),],keep=("messages",20),),],)# Using fractional limitsagent3=create_agent(model="gpt-4o",tools=[your_weather_tool,your_calculator_tool],middleware=[SummarizationMiddleware(model="gpt-4o-mini",trigger=("fraction",0.8),keep=("fraction",0.3),),],)Human-in-the-loop在执行工具调用之前,暂停代理执行以供人工批准、编辑或拒绝工具调用。Human in the loop在以下方面很有用:需要人工批准的高风险操作(例如数据库写入、金融交易)。强制性人工监督的合规工作流程。人工反馈引导代理的长期对话。API参考fromlangchain.agentsimportcreate_agentfromlangchain.agents.middlewareimportHumanInTheLoopMiddlewarefromlanggraph.checkpoint.memoryimportInMemorySaverdefread_email_tool(email_id:str)-str:"""Mock function to read an email by its ID."""returnf"Email content for ID:{email_id}"defsend_email_tool(recipient:str,subject:str,body:str)-str:"""Mock function to send an email."""returnf"Email sent to{recipient}with subject '{subject}'"agent=create_agent(model="gpt-4o",tools=[your_read_email_tool,your_send_email_tool],checkpointer=InMemorySaver(),middleware=[HumanInTheLoopMiddleware(interrupt_on={"your_send_email_tool":{"allowed_decisions":["approve","edit","reject"],},"your_read_email_tool":False,}),],)ModelCallLimitMiddleware 继承 AgentMiddleware限制模型调用的次数,以防止无限循环或过高的成本。模型调用限制适用于以下情况:防止失控的代理进行过多的API调用。对生产部署实施成本控制。在特定呼叫预算内测试代理行为。API参考:fromlangchain.agentsimportcreate