课程目标✅ 理解回调Callbacks的作用与核心场景 ✅ 掌握LangChainCallbackHandler的基础用法 ✅ 学会对话持久化存到文件 / 数据库 ✅ 能给你的链加上日志追踪调试问题更轻松一、核心概念回调Callbacks1. 什么是回调回调就是钩子函数在 LangChain 的组件执行前后自动触发用来打印日志、记录耗时监控模型调用次数、token 消耗给前端实时推送生成进度做错误捕获、重试逻辑2. 内置回调StdOutCallbackHandler最常用的控制台日志回调能帮你打印链里每一步的执行细节是调试必备python运行from langchain.callbacks import StdOutCallbackHandler from langchain_openai import OpenAI from langchain.chains import LLMChain from langchain.prompts import PromptTemplate # 1. 初始化模型回调 llm OpenAI(temperature0, callbacks[StdOutCallbackHandler()]) # 2. 组装链 prompt PromptTemplate(input_variables[topic], template解释一下{topic}) chain LLMChain(llmllm, promptprompt) # 3. 执行控制台会自动打印完整执行过程 chain.run(LangChain回调)你运行后会看到模型调用、prompt 拼接、token 消耗等日志调试超方便二、自定义回调实现日志追踪如果想把日志存到文件、数据库或者做更复杂的监控可以继承BaseCallbackHandler写自定义回调python运行from langchain.callbacks.base import BaseCallbackHandler import time class MyCustomCallback(BaseCallbackHandler): def on_llm_start(self, serialized, prompts, **kwargs): print(f[日志] 模型开始调用prompt{prompts[0][:100]}...) self.start_time time.time() def on_llm_end(self, response, **kwargs): duration time.time() - self.start_time print(f[日志] 模型调用结束耗时{duration:.2f}秒) print(f[日志] 模型回复{response.generations[0][0].text[:100]}...) # 使用自定义回调 llm OpenAI(temperature0, callbacks[MyCustomCallback()]) chain LLMChain(llmllm, promptprompt) chain.run(LangChain自定义回调)你可以在这些钩子方法里把数据写入文件、发送到日志服务器实现持久化监控。三、对话持久化把聊天记录存起来之前用的ConversationBufferMemory是存在内存里的程序重启就丢了。LangChain 支持把对话历史持久化到文件 / 数据库这里给你 2 种常用方案方案 1文件持久化简单易上手python运行from langchain.memory import ConversationBufferMemory from langchain.chains import ConversationChain import json # 1. 初始化记忆 memory ConversationBufferMemory() conv_chain ConversationChain(llmOpenAI(temperature0), memorymemory) # 2. 对话 conv_chain.predict(input你好我在学LangChain) conv_chain.predict(input回调是什么) # 3. 保存对话到文件 history memory.load_memory_variables({})[history] with open(chat_history.json, w, encodingutf-8) as f: json.dump(history, f, ensure_asciiFalse, indent2) # 4. 下次启动时加载对话 from langchain.memory.chat_message_histories import FileChatMessageHistory from langchain.memory import ConversationBufferMemory chat_history FileChatMessageHistory(chat_history.json) memory ConversationBufferMemory(chat_memorychat_history, return_messagesTrue) conv_chain ConversationChain(llmOpenAI(temperature0), memorymemory)方案 2SQLite 数据库持久化适合长期使用python运行from langchain.memory.chat_message_histories import SQLChatMessageHistory from langchain.memory import ConversationBufferMemory # 连接SQLite数据库存储对话历史 chat_history SQLChatMessageHistory( session_iduser_123, # 每个用户/会话一个ID connection_stringsqlite:///chat_history.db ) memory ConversationBufferMemory(chat_memorychat_history, return_messagesTrue) conv_chain ConversationChain(llmOpenAI(temperature0), memorymemory) # 对话会自动保存到数据库重启不丢失 conv_chain.predict(input我又来了接着聊回调)四、课后作业30 分钟搞定用StdOutCallbackHandler给一个LLMChain加上控制台日志运行并观察输出。写一个自定义回调实现模型调用开始 / 结束时打印耗时和 prompt 前 100 字符。用FileChatMessageHistory实现对话持久化第一次运行和模型聊 2 轮第二次运行加载历史对话接着聊验证历史不丢失作业 1用StdOutCallbackHandler给LLMChain加控制台日志python运行from langchain_openai import OpenAI from langchain.chains import LLMChain from langchain.prompts import PromptTemplate from langchain.callbacks import StdOutCallbackHandler # 1. 初始化模型 控制台日志回调 llm OpenAI( temperature0, callbacks[StdOutCallbackHandler()] # 开启内置日志回调 ) # 2. 定义提示词模板 prompt PromptTemplate( input_variables[topic], template请用大白话解释一下{topic} ) # 3. 组装链 chain LLMChain(llmllm, promptprompt) # 4. 执行控制台会自动打印完整执行过程 result chain.run(LangChain的回调机制) print(\n最终回答, result)运行后你会在控制台看到模型调用、提示词拼接、Token 消耗等完整日志方便调试。作业 2自定义回调记录模型调用耗时和 Promptpython运行from langchain.callbacks.base import BaseCallbackHandler from langchain_openai import OpenAI from langchain.chains import LLMChain from langchain.prompts import PromptTemplate import time # 1. 自定义回调类 class MyCustomCallback(BaseCallbackHandler): def on_llm_start(self, serialized, prompts, **kwargs): # 模型调用开始时触发 self.start_time time.time() print(\n [日志] 模型调用开始 ) print(f收到的Prompt前100字符\n{prompts[0][:100]}...) def on_llm_end(self, response, **kwargs): # 模型调用结束时触发 duration time.time() - self.start_time print(\n [日志] 模型调用结束 ) print(f耗时{duration:.2f} 秒) print(f模型回复前100字符\n{response.generations[0][0].text[:100]}...) # 2. 初始化模型 自定义回调 llm OpenAI( temperature0, callbacks[MyCustomCallback()] ) # 3. 组装链并执行 prompt PromptTemplate(input_variables[topic], template解释一下{topic}) chain LLMChain(llmllm, promptprompt) chain.run(LangChain的持久化)作业 3用FileChatMessageHistory实现对话持久化第 1 步第一次运行保存对话python运行from langchain_openai import OpenAI from langchain.chains import ConversationChain from langchain.memory import ConversationBufferMemory from langchain.memory.chat_message_histories import FileChatMessageHistory # 1. 初始化文件持久化历史 chat_history FileChatMessageHistory(chat_history.json) memory ConversationBufferMemory( chat_memorychat_history, return_messagesTrue ) # 2. 初始化对话链 llm OpenAI(temperature0) conv_chain ConversationChain(llmllm, memorymemory) # 3. 对话会自动保存到文件 print(conv_chain.predict(input你好我在学LangChain的持久化)) print(conv_chain.predict(input程序重启后对话会丢吗)) # 查看保存的消息 print(\n当前对话历史, chat_history.messages)第 2 步第二次运行加载历史接着聊python运行from langchain_openai import OpenAI from langchain.chains import ConversationChain from langchain.memory import ConversationBufferMemory from langchain.memory.chat_message_histories import FileChatMessageHistory # 1. 从文件加载历史对话 chat_history FileChatMessageHistory(chat_history.json) memory ConversationBufferMemory( chat_memorychat_history, return_messagesTrue ) # 2. 初始化对话链 llm OpenAI(temperature0) conv_chain ConversationChain(llmllm, memorymemory) # 3. 接着之前的对话聊 print(conv_chain.predict(input你还记得我们刚才聊了什么吗)) # 验证能看到之前的对话历史 print(\n加载后的对话历史, chat_history.messages)