惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
B
Blog RSS Feed
大猫的无限游戏
大猫的无限游戏
J
Java Code Geeks
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 【当耐特】
MongoDB | Blog
MongoDB | Blog
Hugging Face - Blog
Hugging Face - Blog
有赞技术团队
有赞技术团队
T
The Blog of Author Tim Ferriss
B
Blog
小众软件
小众软件
T
Tailwind CSS Blog
MyScale Blog
MyScale Blog
I
InfoQ
Engineering at Meta
Engineering at Meta
Blog — PlanetScale
Blog — PlanetScale
P
Proofpoint News Feed
H
Help Net Security
雷峰网
雷峰网
S
SegmentFault 最新的问题
V
Visual Studio Blog
爱范儿
爱范儿

博客园 - zhaofeng555

欧氏距离 vs 余弦相似度 相似度2-欧式距离 相似度1-余弦相似度 Oh-My-OpenCode介绍 OpenCode 里的 Atlas / Sisyphus / Prometheus区别 安装opencode langchain的第一个小例子 springai第二个例子使用配置类配置chatclient springai访问本地alloma第一个例子 springai访问本地alloma的qwen3报错 C/c++趣味程序百例 mac 安装stale disffusion笔记 mac 安装TA-Lib包 centos7 install docker CentOS7 内核升级从3.10升级到4.4(以kernel-lt 为例) 一个数组中有一个重复的数字,O(n) 找出来 找数组中重复的数字 mysql server 端命令 mac安装python3 pandas tushare
langchain第二个小例子
zhaofeng555 · 2026-01-11 · via 博客园 - zhaofeng555
from langchain_ollama.chat_models import ChatOllama
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory


print("--- LangChain + Ollama 聊天模式 ---")

# 1. 初始化 DeepSeek 模型
llm = ChatOllama(model="deepseek-r1:1.5b", temperature=0)

# 2. 定义提示词模板
# MessagesPlaceholder 会在运行时被对话历史填充
prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个乐于助人的 AI 助手。"),
    MessagesPlaceholder(variable_name="history"),
    ("human", "{question}"),
])

# 3. 构建链
chain = prompt | llm

# 4. 管理内存:创建一个字典来存储不同用户的历史记录
store = {}

def get_session_history(session_id: str) -> BaseChatMessageHistory:
    if session_id not in store:
        store[session_id] = ChatMessageHistory()
    return store[session_id]

# 5. 使用 RunnableWithMessageHistory 包装我们的链
# 这样 LangChain 会自动处理历史记录的读取和更新
with_message_history = RunnableWithMessageHistory(
    chain,
    get_session_history,
    input_messages_key="question",
    history_messages_key="history",
)

# 6. 进入对话循环
print("--- 已进入 DeepSeek 聊天模式 (输入 'exit' 退出) ---")
session_config = {"configurable": {"session_id": "user_001"}} # 区分不同会话的 ID

while True:
    user_input = input("你: ")
    if user_input.lower() in ["exit", "quit", "退出"]:
        break
        
    # 调用带记忆的链
    response = with_message_history.invoke(
        {"question": user_input},
        config=session_config
    )
    
    print(f"AI: {response.content}\n")