SuperAPI AI 工具集

langchain-sdk-patterns

智能体与模型

查看项目

更新于 10-15 23:27

技能介绍

用途:面向使用 LangChain 1.0 Python 构建生产链路的开发者,讲解 LCEL 组合(RunnableSequence、RunnableParallel、RunnableBranch、RunnablePassthrough、RunnableLambda)及四个常见陷阱(P07、P08、P53、P57)。

主要能力:一是批处理并发,chain.batch 的 max_concurrency 默认常为 1,需显式设置,如 chain.batch(inputs, config={"max_concurrency": 10}),异步用 abatch;多数提供商安全上限约 10,20+ 需配合 asyncio.Semaphore。二是窄化 fallback,with_fallbacks 默认 exceptions_to_handle=(Exception,),在 Python <3.12 会吞掉 KeyboardInterrupt,应传入具体异常元组如 (RateLimitError, APIError, APITimeoutError)。三是模板转义,ChatPromptTemplate 默认 f-string 会解析用户输入中的花括号导致 KeyError,涉及不可信输入时用 template_format="jinja2",历史消息用 MessagesPlaceholder。四是结构化输出,Pydantic v2 默认拒绝额外字段,需在模型上设 model_config = ConfigDict(extra="ignore")。

使用方式:需 Python 3.10+(建议 3.12+)、langchain-core >=1.0,<2.0、至少一个提供商(pip install langchain-anthropic langchain-openai)、pydantic >=2.0,并先完成 langchain-model-inference。文中给出 invoke、batch、abatch、stream、astream 的选用对照,以及 return_exceptions=True 保留批量结果。

适用场景:批量 ETL、评估、并行富化、多提供商容错、用户粘贴 JSON 的工单分流。限制:具体并发上限、TPM/RPM 随提供商与套餐变化,需自行核对;资料未提供价格与平台信息。