You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将LangChain对话集成到React聊天机器人,管理最近5轮上下文

对话功能实现方案:React端 + Python/LLM端处理

React端处理

  • 对话历史存储:用React的useState(小型项目)或Redux(复杂项目)维护对话数组,每个元素包含角色和内容,结构示例:
    const [conversationHistory, setConversationHistory] = useState([
      { role: "assistant", content: "你好,有什么可以帮你的?" }
    ]);
    
  • 发送请求时携带上下文:用户输入新问题后,先将用户消息加入历史,再调用FastAPI时把最近5轮对话(每轮含用户提问+助理回复,所以取10条数据)作为参数传递:
    const handleSendMessage = async (userInput) => {
      // 先添加用户消息到本地历史
      const updatedHistory = [...conversationHistory, { role: "user", content: userInput }];
      setConversationHistory(updatedHistory);
    
      // 调用FastAPI,携带最近5轮对话上下文
      const response = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ conversation_history: updatedHistory.slice(-10) })
      });
    
      const data = await response.json();
      // 添加助理回复到历史并更新UI
      setConversationHistory([...updatedHistory, { role: "assistant", content: data.response }]);
    };
    
  • UI渲染:遍历conversationHistory数组,根据role字段渲染不同样式的用户/助理消息气泡。

Python/LLM端处理(结合LangChain)

  • 依赖准备:确保安装langchain、openai、fastapi相关包
  • 用ConversationBufferWindowMemory管理上下文:设置k=5保留最近5轮对话,FastAPI接口接收React传来的对话历史,初始化并加载Memory:
    from fastapi import FastAPI
    from langchain.memory import ConversationBufferWindowMemory
    from langchain.chat_models import ChatOpenAI
    from langchain.chains import LLMChain
    from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
    from pydantic import BaseModel
    
    app = FastAPI()
    
    # 定义请求体模型
    class ChatRequest(BaseModel):
        conversation_history: list[dict]
    
    # 初始化LLM和对话模板
    llm = ChatOpenAI(model_name="gpt-3.5-turbo")
    prompt = ChatPromptTemplate.from_messages([
        ("system", "你需要结合对话上下文,把用户问题格式化为符合内部API要求的查询语句,调用内部API后返回结果。"),
        MessagesPlaceholder(variable_name="history"),
        ("human", "{input}")
    ])
    
    @app.post("/api/chat")
    async def chat(request: ChatRequest):
        # 初始化对话内存,k=5表示保留最近5轮对话
        memory = ConversationBufferWindowMemory(k=5, return_messages=True)
        
        # 将前端传来的历史对话加载到内存中
        for msg in request.conversation_history:
            if msg["role"] == "user":
                memory.chat_memory.add_user_message(msg["content"])
            elif msg["role"] == "assistant":
                memory.chat_memory.add_ai_message(msg["content"])
        
        # 创建对话链
        chain = LLMChain(llm=llm, prompt=prompt, memory=memory)
        
        # 获取最后一条用户输入
        last_user_input = [msg for msg in request.conversation_history if msg["role"] == "user"][-1]["content"]
        
        # 生成符合要求的查询语句
        query = chain.run(input=last_user_input)
        
        # 调用内部API(替换为你的实际内部API调用逻辑)
        internal_api_response = call_internal_api(query)
        
        # 返回结果给React端
        return {"response": internal_api_response}
    
    def call_internal_api(query):
        # 内部API调用实现示例
        return f"内部API返回结果:{query}"
    
  • 关键说明:
    • ConversationBufferWindowMemory会自动截取最近5轮对话,无需手动处理上下文截断逻辑
    • 每次请求重新初始化Memory并加载历史,属于无状态服务模式;如果需要跨请求保留会话,可以给用户分配唯一会话ID,用Redis等存储对应Memory内容

内容的提问来源于stack exchange,提问作者saishree godbole

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 16:55:15