# langchain-basic-af04 **Repository Path**: itluma2008/langchain-basic-af04 ## Basic Information - **Project Name**: langchain-basic-af04 - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 14 - **Forks**: 2 - **Created**: 2026-06-10 - **Last Updated**: 2026-06-22 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README 第一天:LangChain入门 1、为什么需要LangChain 问题1:LLMs用的好好,为什么还需要开发框架? 框架工程化的解决方案:工具调用、上下文管理、提示词、历史记录、检索、多轮推理、包括各种模型等等, 问题2:我们可以使用GPT、Qwen、DeepSeek等模型通过API进行开发,为什么还需要框架? 1、简化开发难度 2、开发者可以更专注于业务逻辑 3、学习成本更低了,使用LangChain可以统一、规范的方式进行调用,有更好的移植性。 4、现成的Agent构建方法 2、LangChain的发展 2023-》开发项目-》LangChain 2024->LangChain0.1-》稳定版 2025-》LangChain 1.0 -》将LangGraph做了更高级的封装 3、LangChain的核心模块 Model I/O Chains:LCEL 链 -》RAG Agent Tools Memory Retriveval Document Processing Vector Store 4、LangChain智能体开发 agent = create_agent( 模型, 工具|中间件, 系统提示词, 上下文结构, 响应的格式, 消息的持久化 ) 5、LangChain迁移(了解) 6、Model基本使用 6.1 初始化各种模型 ChatDeepSeek:初始化具体供应商的模型,deepseek, 就需要安装该供应商的具体依赖 langchain-deepseek init_chat_model:初始化通用聊天模型 第二天:模型|消息|提示词模板 1、可以配置化模型:init_chat_model在初始化模型时可以动态配置模型参数 model = init_chat_model(configuable_fields=[模型参数], prefix="") 面试题:top_p、top_k区别? top_p: 从概念累积达到p的候选词中随机采样。top_p=0.9,就是把所有的候选词按概率从高到低进行排序,累计到90%就截止,从这个范围内采样。候选词是动态的 top_k: 直接取概率最高的前k个词,比如top_k=50,就是固定只从最高概率的50个词选,候选词是固定的 一般先调top_p,大多数场景用0.7~0.95,top_p=1不限制全量采样 DeepSeek、OpenAI主流API推荐只用top_p,不暴露top_k model.invoke("xx", config={"configuable":{具体的模型参数}}) 2、消息 2.1 消息类型 #from langchain_core.messages import xxxMessage from langchain.messages import xxxMessage SystemMessage:系统消息,设置角色和身份 HumanMessage:用户消息,用户的要求 AIMessage:模型消息,模型输出的内容 ToolMessage:工具消息,工具之后的内容 2.2 消息内容 content content_blocks:在LangChain解决不同模型返回内容格式的不一致问题提供的一个统一内容格式 3、提示词模板 from langchain_core.prompts import PromptTemplate,ChatPromptTemplate 3.1 基础模板 PromptTemplate #方式1 template = PromptTemplate.from_template("xxxx{a}yyyyy{b}") #创建模版 template.format(a="xxx", b="yyy") #格式化模板 #方式2 template = PromptTemplate(input_variables=["a", "b"], template="xxxx{a}yyyyy{b}") #创建模版 template.format(a="xxx", b="yyy") 3.2 聊天模型ChatPromptTemplate chat_template = ChatPromptTemplate.from_messages([ SystemMessage("xxx"), HumanMessage("yyy{aa}"), AIMessage("zzz{bb}"), ToolMessage("xxx", "yyy"), ]) messages = chat_template.format_messages(aa="xxx", bb="yyy") 第三天、工具|Agent入门 1、Function Calling:模型如何调用业务方法 1.1 创建工具 - 装饰器 - 工具描述 1.2 使用工具 - 模型绑定工具 - 绑定后的模型进行请求 - 执行工具并返回结果 - 模型基于工具的结果生成最终回复 2、Agent 2.1 什么是Agent - Memeory:记忆 - Tools:工具 - Planning:规划 - Action:执行 - Collaboration:多Agent协作 ReAct循环执行: 用户输入-》模型分析【流程|工具|参数】-》Act【执行工具】-》Observe【ToolMessage加入历史消息列表中】-》模型分析【流程|工具|参数,基于新上下文继续推】-》循环直到无工具调用-》返回结果 2.2 Agent构建 create_agent( model, tools, middleware, system_prompt, context_schema, response_format, state, checkpointer, ... ) 2.3 模型 1、静态提供 2、动态提供:提供一个中间件,根据用户输入的任务不同使用不同的模型进行覆盖 具体实现过程就是定义一个中间件: @wrap_model_call def switch_model_middleware(request:ModelRequest,handler)->ModelResponse: #实现自定义任务 return handler(request.override(model=新的模型)) #最新模型 第四天:Agent 1、工具@Tool,处理工具调用过程中的错误,通过中间件弥补 @wrap_tool_call def tool_error_middleware(request:ToolRequest,handler)->ToolResponse: try: return handler(request) except Exception as e: return ToolMessage(content="提供具体错误的内容", tool_call_id=request.tool_call["id"]) 2、系统提示词 2.1 静态提示词 create_agent( system_prompt="xxx" #消息列表中构建SystemMessage ) 2.2 动态提示词:通过中间件@dynamic_prompt @dataclass class MyContext: user_role: str = "xxx" @dynamic_prompt def role_base_prompt(request)->str: #在执行的过程中会动态覆盖消息列表中的SystemMessage role = request.runtime.context["user_role"] if role == "xxx": return "xxx" elif role == "xxx": return "xxx" else: return "xxx" create_agent( context_schema=MyContext, middleware=[role_base_prompt] #动态提示词 ) 3、运行时上下文:只智能体运行过程中,可以读取一些额外的信息,用户身份、角色、权限等等。 - @dynamic_prompt:request.runtime.context - @wrap_tool_call:request.runtime.context - 工具函数:runtime:ToolRuntime[Context] @tool def get_weather(city:str, runtime:ToolRuntime[Context])->str: city = runtime.context.city return "xxx" 4、结构化输出 4.1 概念 让 Agent返回可以解析的结构化数据(Pydantic、JSON、Dict),而非纯文本 实现方式:create_agent+response_format参数启用 返回的位置:result["structured_response"]中 4.2 输出策略 response_format:Union[ ProviderStrategy[Schema], #原生模型支持结构化输出 ToolStrategy[Schema], #工具调用模型生成 type[Schema] #自动选择 ] 4.3 定义数据结构 1、pydantic[推荐]: class UserSchema(BaseModel): name:str = Field(xxx) 2、dataclass @dataclass class UserSchema: ... 3、TypedDict class UserSchema(TypedDict) ... 第五天:记忆 1、短期记忆 1.1 为什么需要记忆 - 大模型本身无状态,每次请求都是独立的 - 多轮对话中需要保存历史上下文-》实现“上下文感知” - 解决:外部存储+自动注入历史消息 1.2 工作流程 用户输入-》读取历史-》构建messages-》模型处理-》解析输出-》写入messages 1.3 核心组件 AgentState:单次Invoke中,实现状态的传递 checkpointer:多次invoke之间,实现状态的传递 memory=InMemorySaver() agent = create_agent( state_schema=AgentState #默认的 checkpointer=memory #需要指定的 ) config={"configuable":{"thread_id":"100"}} agent.invoke({}, config) 1.4 消息管理 1.裁剪 2.删除 3.摘要 2、长期记忆 短期记忆:单会话 长期记忆:跨会话,需要同一个存储设备来完成 2.1 实现过中的具体API: - Store接口: store = InMemoryStore() | PostgresqlStore() | xxxStore() store.put(namespace, key, value) # store.put(("user","james"), "chitchat", messages)) store.get(namespace, key) store.search(namespace, filter={}, query="") #相似度检索 2.2 如何使用 create_agent( tools=[save, get] store=store ) @tool def save(runtime:ToolRuntime[Context]): store = runtime.store store.put(("user","james"), "chitchat", messages) @tool def get(runtime:ToolRuntime[Context]) store = runtime.store return store.get(("user","james"), "chitchat") 第六天:PostgreSQL 1、PostgreSQL的介绍 开源免费的关系型数据库 我们课程中主要用来它做记忆存储! 支持向量存储 2、安装 3、pg的基本使用 3.1 创建库和表 create database myshop; drop database myshop; 。。。 常用的命令: \c :切换数据库 \l:列出所有的库 \dt:显示所有的表 \d:显示表结构 \q:退出 3.2 CRUD基本操作 select insert update delete 4、langchain中使用postgresql进行记忆存储 pip install langgraph-checkpoint-postgres 4.1 长期记忆:需要自定义工具,在工具中实现记忆的存储 runtime.store.put(namespace, key, value) 4.2 短期记忆:langchain框架自动实现存储,可以存储在存储或持久化对象中,一般存储时节点数据 agent.invoke()自动进行存储 PostgreSQL:myapp store表----------------长期记忆(跨会话、跨用户) --------------用户基本信息、偏好 ("users", ) (user_123) ({id:1, name:"", age:20}}) checkpoints表 ----------短期记忆(按thread_id隔离对话历史) -----聊天记录 thread_id=session_user_123 [完整messages列表] 由checkpointer自动写入,无需手动操作 5、中间件的介绍 5.1 为什么需要中间件: 业务逻辑和推理逻辑分开,解耦,通过拓展新的节点来实现这个过程 5.2 中间件的类型:6+动态提示词 - 节点类型:before_agent|before_model|after_model|after_agent - 包装类型:wrap_model_call|wrap_tool_call 执行顺序:before_agent->before_model->wrap_model_call->model->wrap_tool_call->tool->after_model->after_agent