当前位置: 首页 > news >正文

LangChain Day4 课程:回调、持久化、日志追踪

课程目标✅ 理解回调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)
http://www.zskr.cn/news/1398064.html

相关文章:

  • 基于CT+NMF+ANN的鲁棒图像水印技术:原理、实现与优化
  • 扩散模型驱动3D生成:从2D先验到3D空间扩散的技术演进
  • THz通信信道噪声特性与性能优化分析
  • 低成本FSR传感器与嵌入式AI实现机器人动态重量感知
  • 2026四川淬火带钢标杆名录:65mn弹簧带钢排行榜/65mn弹簧带钢推荐榜/65mn弹簧带钢生产厂家/65mn弹簧带钢购买/选择指南 - 优质品牌商家
  • 保姆级教程:用Unity UGUI从零打造一个可缩放、可展开的2D小地图(附完整C#脚本)
  • Cocos Creator 2.x 游戏接入 Google AdMob 广告的完整避坑指南(iOS平台)
  • 告别单调雪花!在Unity里用ParticleSystem模拟风吹雪、暴风雪效果的进阶配置指南
  • 2026数字人制作平台TOP5真人 1:1 复刻 + 实时驱动平台推荐
  • 居家养老安全响应系统技术拆解:8分钟完成“跌倒-报警-救援”闭环的架构设计
  • 为什么92%的预约系统在活动峰值崩溃?Lovable底层时序调度器设计原理与3种降级预案详解
  • 0049__gif 格式图片详细解析
  • 达人建联工具怎么选?小青苔达人营销工具功能与使用场景整理
  • Linux终端PS1配置避坑指南:从环境变量加载顺序到永久生效的正确姿势
  • 基于Vision Transformer的无监督域自适应行人重识别:提示与调优两阶段方法
  • 1.5V升压3.3V、5V芯片PW5100需电容电感靠近IC放置
  • 超声波雷达:智能驾驶的“贴身护卫”,技术内幕与未来战局
  • 你的模型F1分数真的‘最佳’吗?避开阈值选择中的3个常见误区(Python示例)
  • 嵌入式人脸年龄估计:轻量CNN与自适应混合损失函数实战
  • Spring Boot 接口统一返回值封装,告别杂乱响应格式
  • NPS调研合作伙伴
  • Go语言邮件服务:SMTP发送
  • Go语言短信服务:多渠道发送
  • 别再直接让 AI 生成测试用例了:用 Superpowers 做需求分析的 5 步实操
  • 2026年AI Agent技术生态开源项目合集
  • 基于BERT-BiGRU与心理学量表从旅游评论中识别用户新奇寻求人格
  • Tableau同比环比实战:从基础表计算到动态参数化对比
  • Simscape进阶实战:构建三维碰撞仿真模型解析小球与斜面的动力学交互
  • Blender模型导出Unity前必做的7步检查清单(附FBX导出避坑指南)
  • 【Java-Day03】判断 / 选择 / 循环语句