LangChain 快速入门:从基础到生产级 AI 智能体搭建
本快速入门教程将带你在几分钟内从简单的环境配置开始一步步搭建出一个功能完整的AI智能体。如果使用AI编码助手或集成开发环境如Claude Code、Cursor建议安装LangChain Docs MCP服务器能让你的智能体获取最新的LangChain文档和示例发挥最佳效果。准备工作搭建示例中的智能体需要完成以下三步基础配置示例中使用Anthropic的Claude大模型也可替换为LangChain支持的任意模型仅需修改代码中的模型名并配置对应模型的API密钥即可。安装LangChain Python包注册Anthropic的Claude账号获取对应的API密钥在终端中设置ANTHROPIC_API_KEY环境变量供LangChain调用。一、搭建基础AI智能体首先创建一个基础智能体该智能体具备基础的问答能力和工具调用能力核心使用Claude Sonnet 4.5作为语言模型自定义一个简单的天气查询函数作为工具并通过基础系统提示词规范智能体行为。基础智能体完整代码from langchain.agents import create_agentdef get_weather(city: str) - str: Get weather for a given city. returnfIts always sunny in {city}!# 创建智能体实例agent create_agent( modelclaude-sonnet-4-5-20250929, tools[get_weather], system_promptYou are a helpful assistant,)# 运行智能体agent.invoke( {messages: [{role: user, content: what is the weather in sf}]})代码逐行详解导入智能体创建核心函数from langchain.agents import create_agent该函数是LangChain中创建智能体的核心入口可快速整合模型、工具、提示词等组件。定义工具函数自定义get_weather函数接收city城市名参数返回固定格式的天气信息函数的文档字符串Get weather for a given city.是关键LangChain会将其作为工具描述传递给大模型让模型理解工具的用途。创建智能体调用create_agent传入三个核心参数model指定使用的大模型标识此处为Claude Sonnet 4.5的最新版本tools传入智能体可调用的工具列表支持多个工具传入system_prompt系统提示词定义智能体的基础角色此处为“贴心助手”。运行智能体调用agent.invoke()方法触发智能体执行入参为字典格式messages是对话消息列表包含用户角色user和具体的查询内容此处查询旧金山sf的天气。二、搭建生产级实用智能体基于基础智能体进一步搭建具备生产环境核心特性的天气预报智能体该智能体实现了企业级开发的关键能力也是实际业务中使用LangChain的标准范式。生产级智能体核心特性精细化系统提示词精准定义智能体行为和角色自定义工具支持运行时上下文注入、对接外部数据大模型个性化参数配置保证响应的一致性结构化输出格式让智能体结果可预测、易解析集成对话记忆支持多轮类聊天交互支持用户专属上下文信息传递。接下来将分6个步骤拆解生产级智能体的搭建过程最后提供完整的整合代码和运行效果。步骤1定义精细化系统提示词系统提示词是智能体的“行为准则”生产环境中需要具体、可执行的提示词明确智能体的角色、可调用的工具、工具的使用规则。代码实现SYSTEM_PROMPT You are an expert weather forecaster, who speaks in puns.You have access to two tools:- get_weather_for_location: use this to get the weather for a specific location- get_user_location: use this to get the users locationIf a user asks you for the weather, make sure you know the location. If you can tell from the question that they mean wherever they are, use the get_user_location tool to find their location.代码详解明确角色双关语风格的专业天气预报员让智能体的输出具备固定风格工具清单清晰列出可调用的两个工具及核心用途降低模型的工具调用理解成本执行规则明确天气查询的核心逻辑——必须获取位置若用户未指定则调用get_user_location工具获取用户所在位置让智能体的工具调用更规范。步骤2创建自定义工具工具是智能体与外部系统交互的桥梁生产级工具需要支持运行时上下文如用户ID、设备信息和智能体记忆交互LangChain通过tool装饰器和ToolRuntime实现这一能力同时工具需要完善的文档字符串说明。代码实现from dataclasses import dataclassfrom langchain.tools import tool, ToolRuntime# 天气查询工具tooldef get_weather_for_location(city: str) - str: Get weather for a given city. returnfIts always sunny in {city}!# 自定义运行时上下文schemadataclassclass Context: Custom runtime context schema. user_id: str# 用户位置获取工具依赖运行时上下文tooldef get_user_location(runtime: ToolRuntime[Context]) - str: Retrieve user information based on user ID. user_id runtime.context.user_id returnFloridaif user_id 1elseSF代码详解基础工具定义使用tool装饰器修饰普通函数LangChain会自动为函数添加工具元数据名称、描述、参数无需手动配置装饰后的函数可直接传入智能体的tools参数自定义运行时上下文通过dataclasses.dataclass定义Context类仅包含user_id字段作为运行时传递用户专属信息的载体生产环境中可扩展为包含用户昵称、设备、地区等更多信息上下文依赖工具get_user_location工具的入参为ToolRuntime[Context]实现运行时上下文注入通过runtime.context.user_id获取当前请求的用户ID并根据用户ID返回不同的位置实现用户专属逻辑工具文档字符串每个工具的文档字符串是模型识别工具的关键必须清晰说明工具用途和参数含义。步骤3配置大模型参数为了保证智能体响应的一致性和稳定性需要对大模型进行个性化参数配置LangChain通过init_chat_model函数统一初始化各类聊天模型不同模型的参数可按需调整。代码实现from langchain.chat_models import init_chat_modelmodel init_chat_model( claude-sonnet-4-5-20250929, temperature0.5, timeout10, max_tokens1000)代码详解模型初始化入口init_chat_model是LangChain的统一模型初始化函数支持切换任意兼容的聊天模型仅需修改模型标识核心参数说明temperature温度系数控制模型输出的随机性取值010表示输出完全确定1表示随机性最高生产环境中一般设置00.5timeout模型请求超时时间单位为秒避免因模型服务卡顿导致智能体挂起max_tokens模型单次输出的最大令牌数限制响应长度避免输出过长。步骤4定义结构化输出格式生产环境中智能体的输出需要可预测、易解析如供前端渲染、数据库存储LangChain支持通过dataclass或Pydantic模型定义结构化响应格式强制模型按照指定schema输出结果。代码实现from dataclasses import dataclass# 定义智能体响应的结构化schemadataclassclass ResponseFormat: Response schema for the agent. # 必选字段双关语风格的响应 punny_response: str # 可选字段天气状况信息值为None时不返回 weather_conditions: str | None None代码详解采用dataclass定义结构化schema生产环境中若需要更复杂的校验如参数类型、取值范围可替换为Pydantic模型LangChain完全兼容字段设计区分必选/可选punny_response为必选字段保证智能体的核心输出weather_conditions为可选字段设置默认值None无需返回时可置空字段类型注解通过str | None明确字段类型让模型清晰知道输出要求减少格式错误。步骤5添加对话记忆基础智能体不具备记忆能力多轮对话中无法识别上下文LangChain通过检查点Checkpointer实现对话记忆示例中使用内存级记忆生产环境中可替换为持久化存储如数据库。代码实现from langgraph.checkpoint.memory import InMemorySaver# 初始化内存级检查点用于存储对话记忆checkpointer InMemorySaver()代码详解InMemorySaver是LangChain内置的内存级对话记忆适合测试和小型应用数据仅保存在程序运行内存中程序重启后丢失生产环境中需使用持久化Checkpointer如基于SQL、Redis、MongoDB的实现将对话历史保存到数据库实现跨会话、跨服务的记忆能力检查点会自动关联会话唯一标识实现多会话的记忆隔离。步骤6组装并运行生产级智能体将上述所有组件模型、提示词、工具、上下文、结构化输出、记忆通过create_agent整合为一个完整的智能体然后调用运行方法测试效果同时支持多轮连续对话。核心组装代码from langchain.agents.structured_output import ToolStrategy# 组装生产级智能体agent create_agent( modelmodel, system_promptSYSTEM_PROMPT, tools[get_user_location, get_weather_for_location], context_schemaContext, response_formatToolStrategy(ResponseFormat), checkpointercheckpointer)组装参数详解相比基础智能体生产级智能体新增了3个核心配置context_schema指定运行时上下文的schema即步骤2定义的Context类让智能体支持上下文注入response_format通过ToolStrategy绑定结构化输出schema即步骤4定义的ResponseFormat类强制模型输出结构化结果checkpointer绑定对话记忆的检查点即步骤5定义的checkpointer让智能体具备多轮记忆能力。运行智能体并实现多轮对话# 定义会话配置thread_id为会话唯一标识实现多会话隔离config {configurable: {thread_id: 1}}# 第一轮对话查询户外天气未指定位置智能体会自动调用get_user_location工具response agent.invoke( {messages: [{role: user, content: what is the weather outside?}]}, configconfig, contextContext(user_id1) # 传入运行时上下文用户ID为1)print(response[structured_response])# 第二轮对话感谢智能体复用同一个thread_id智能体可识别上下文response agent.invoke( {messages: [{role: user, content: thank you!}]}, configconfig, contextContext(user_id1))print(response[structured_response])运行结果说明第一轮输出智能体识别到用户未指定位置自动调用get_user_location工具根据user_id1返回Florida再调用get_weather_for_location获取天气最终返回双关语风格的结构化结果包含必选的punny_response和可选的weather_conditions第二轮输出复用thread_id1智能体通过对话记忆识别到上一轮的上下文用户在Florida查询过天气返回对应的感谢回复weather_conditions置空为None会话隔离若新建thread_id如thread_id2则为全新会话智能体无历史记忆。三、生产级智能体完整整合代码为了方便直接运行以下是上述所有步骤的完整整合代码已简化部分非核心参数如设置temperature0让输出完全确定from dataclasses import dataclassfrom langchain.agents import create_agentfrom langchain.chat_models import init_chat_modelfrom langchain.tools import tool, ToolRuntimefrom langgraph.checkpoint.memory import InMemorySaverfrom langchain.agents.structured_output import ToolStrategy# 1. 定义精细化系统提示词SYSTEM_PROMPT You are an expert weather forecaster, who speaks in puns.You have access to two tools:- get_weather_for_location: use this to get the weather for a specific location- get_user_location: use this to get the users locationIf a user asks you for the weather, make sure you know the location. If you can tell from the question that they mean wherever they are, use the get_user_location tool to find their location.# 2. 定义运行时上下文schema和自定义工具dataclassclass Context: Custom runtime context schema. user_id: strtooldef get_weather_for_location(city: str) - str: Get weather for a given city. returnfIts always sunny in {city}!tooldef get_user_location(runtime: ToolRuntime[Context]) - str: Retrieve user information based on user ID. user_id runtime.context.user_id returnFloridaif user_id 1elseSF# 3. 配置大模型参数model init_chat_model( claude-sonnet-4-5-20250929, temperature0)# 4. 定义结构化响应格式dataclassclass ResponseFormat: Response schema for the agent. punny_response: str weather_conditions: str | None None# 5. 初始化对话记忆checkpointer InMemorySaver()# 6. 组装生产级智能体agent create_agent( modelmodel, system_promptSYSTEM_PROMPT, tools[get_user_location, get_weather_for_location], context_schemaContext, response_formatToolStrategy(ResponseFormat), checkpointercheckpointer)# 运行智能体多轮对话config {configurable: {thread_id: 1}}# 第一轮查询天气response agent.invoke( {messages: [{role: user, content: what is the weather outside?}]}, configconfig, contextContext(user_id1))print(response[structured_response])# 第二轮感谢回复response agent.invoke( {messages: [{role: user, content: thank you!}]}, configconfig, contextContext(user_id1))print(response[structured_response])四、最终智能体核心能力总结通过本教程搭建的生产级天气预报智能体具备了企业级AI智能体的核心能力也是LangChain在实际业务中的标准应用形态具体能力如下支持用户上下文识别可根据用户ID等信息提供专属服务能智能选择并调用工具根据用户问题的规则自动触发工具执行具备多轮对话记忆通过会话ID实现上下文关联和会话隔离输出结构化、可解析的结果适配生产环境的后续数据处理支持自定义输出风格通过系统提示词定义智能体的说话方式模型参数可配置保证响应的一致性和稳定性。学AI大模型的正确顺序千万不要搞错了2026年AI风口已来各行各业的AI渗透肉眼可见超多公司要么转型做AI相关产品要么高薪挖AI技术人才机遇直接摆在眼前有往AI方向发展或者本身有后端编程基础的朋友直接冲AI大模型应用开发转岗超合适就算暂时不打算转岗了解大模型、RAG、Prompt、Agent这些热门概念能上手做简单项目也绝对是求职加分王给大家整理了超全最新的AI大模型应用开发学习清单和资料手把手帮你快速入门学习路线:✅大模型基础认知—大模型核心原理、发展历程、主流模型GPT、文心一言等特点解析✅核心技术模块—RAG检索增强生成、Prompt工程实战、Agent智能体开发逻辑✅开发基础能力—Python进阶、API接口调用、大模型开发框架LangChain等实操✅应用场景开发—智能问答系统、企业知识库、AIGC内容生成工具、行业定制化大模型应用✅项目落地流程—需求拆解、技术选型、模型调优、测试上线、运维迭代✅面试求职冲刺—岗位JD解析、简历AI项目包装、高频面试题汇总、模拟面经以上6大模块看似清晰好上手实则每个部分都有扎实的核心内容需要吃透我把大模型的学习全流程已经整理好了抓住AI时代风口轻松解锁职业新可能希望大家都能把握机遇实现薪资/职业跃迁这份完整版的大模型 AI 学习资料已经上传CSDN朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2433349.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!