chatjs.langchain

news/2025/10/6 11:31:50/文章来源:https://www.cnblogs.com/lightsong/p/19127441

chatjs.langchain

https://chatjs.langchain.com/

https://github.com/langchain-ai/chat-langchain

Chat LangChain

This repo is an implementation of a chatbot specifically focused on question answering over the LangChain documentation. Built with LangChain, LangGraph, and Next.js.

Deployed version: chat.langchain.com

Looking for the JS version? Click here.

The app leverages LangChain and LangGraph's streaming support and async API to update the page in real time for multiple users.

 

Technical description

There are two components: ingestion and question-answering.

Ingestion has the following steps:

  1. Pull html from documentation site as well as the Github Codebase
  2. Load html with LangChain's RecursiveURLLoader and SitemapLoader
  3. Split documents with LangChain's RecursiveCharacterTextSplitter
  4. Create a vectorstore of embeddings, using LangChain's Weaviate vectorstore wrapper (with OpenAI's embeddings).

Question-Answering has the following steps:

  1. Given the chat history and new user input, determine what a standalone question would be using an LLM.
  2. Given that standalone question, look up relevant documents from the vectorstore.
  3. Pass the standalone question and relevant documents to the model to generate and stream the final answer.
  4. Generate a trace URL for the current chat session, as well as the endpoint to collect feedback.

 

 

https://github.com/langchain-ai/chat-langchain/blob/master/backend/retrieval_graph/graph.py

"""Main entrypoint for the conversational retrieval graph.This module defines the core structure and functionality of the conversational
retrieval graph. It includes the main graph definition, state management,
and key functions for processing & routing user queries, generating research plans to answer user questions,
conducting research, and formulating responses.
"""from typing import Any, Literal, TypedDict, castfrom langchain_core.messages import BaseMessage
from langchain_core.runnables import RunnableConfig
from langgraph.graph import END, START, StateGraphfrom backend.retrieval_graph.configuration import AgentConfiguration
from backend.retrieval_graph.researcher_graph.graph import graph as researcher_graph
from backend.retrieval_graph.state import AgentState, InputState
from backend.utils import format_docs, load_chat_modelasync def create_research_plan(state: AgentState, *, config: RunnableConfig
) -> dict[str, list[str]]:"""Create a step-by-step research plan for answering a LangChain-related query.Args:state (AgentState): The current state of the agent, including conversation history.config (RunnableConfig): Configuration with the model used to generate the plan.Returns:dict[str, list[str]]: A dictionary with a 'steps' key containing the list of research steps."""class Plan(TypedDict):"""Generate research plan."""steps: list[str]configuration = AgentConfiguration.from_runnable_config(config)structured_output_kwargs = ({"method": "function_calling"} if "openai" in configuration.query_model else {})model = load_chat_model(configuration.query_model).with_structured_output(Plan, **structured_output_kwargs)messages = [{"role": "system", "content": configuration.research_plan_system_prompt}] + state.messagesresponse = cast(Plan, await model.ainvoke(messages, {"tags": ["langsmith:nostream"]}))return {"steps": response["steps"],"documents": "delete","query": state.messages[-1].content,}async def conduct_research(state: AgentState) -> dict[str, Any]:"""Execute the first step of the research plan.This function takes the first step from the research plan and uses it to conduct research.Args:state (AgentState): The current state of the agent, including the research plan steps.Returns:dict[str, list[str]]: A dictionary with 'documents' containing the research results and'steps' containing the remaining research steps.Behavior:- Invokes the researcher_graph with the first step of the research plan.- Updates the state with the retrieved documents and removes the completed step."""result = await researcher_graph.ainvoke({"question": state.steps[0]})return {"documents": result["documents"], "steps": state.steps[1:]}def check_finished(state: AgentState) -> Literal["respond", "conduct_research"]:"""Determine if the research process is complete or if more research is needed.This function checks if there are any remaining steps in the research plan:- If there are, route back to the `conduct_research` node- Otherwise, route to the `respond` nodeArgs:state (AgentState): The current state of the agent, including the remaining research steps.Returns:Literal["respond", "conduct_research"]: The next step to take based on whether research is complete."""if len(state.steps or []) > 0:return "conduct_research"else:return "respond"async def respond(state: AgentState, *, config: RunnableConfig
) -> dict[str, list[BaseMessage]]:"""Generate a final response to the user's query based on the conducted research.This function formulates a comprehensive answer using the conversation history and the documents retrieved by the researcher.Args:state (AgentState): The current state of the agent, including retrieved documents and conversation history.config (RunnableConfig): Configuration with the model used to respond.Returns:dict[str, list[str]]: A dictionary with a 'messages' key containing the generated response."""configuration = AgentConfiguration.from_runnable_config(config)model = load_chat_model(configuration.response_model)# TODO: add a re-ranker heretop_k = 20context = format_docs(state.documents[:top_k])response = await model.ainvoke([{"role": "system","content": configuration.response_system_prompt.format(context=context),},*state.messages,])return {"messages": [response], "answer": response.content}# Define the graph

builder = StateGraph(AgentState, input=InputState, config_schema=AgentConfiguration)
builder.add_node(create_research_plan)
builder.add_node(conduct_research)
builder.add_node(respond)builder.add_edge(START, "create_research_plan")
builder.add_edge("create_research_plan", "conduct_research")
builder.add_conditional_edges("conduct_research", check_finished)
builder.add_edge("respond", END)# Compile into a graph object that you can invoke and deploy.
graph = builder.compile()
graph.name = "RetrievalGraph"

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/929273.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

完整教程:Microsoft Word使用技巧分享(本科毕业论文版)

完整教程:Microsoft Word使用技巧分享(本科毕业论文版)pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consola…

旅游网站建设的参考文献稻壳ppt模板免费下载

文章目录 vite的proxy开发环境设置如果后端没有提供可以替换的/mis等可替换的后缀的处理办法接口如何区分.env.development开发和.env.production生产环境接口在生产环境下,还能使用proxy代理地址吗? vite的proxy开发环境设置 环境: vite 4…

(转)The Ten Commandments of Digital Cotrol(Part1)

(转)The Ten Commandments of Digital Cotrol(Part1)Dave Wilson, Motion Products Evangelist, Texas InstrumentsDespite the fact that I now work for the Microcontroller Division of Texas Instruments; de…

河南省大型项目建设办公室网站500页面 wordpress

说明: 面试题来源于网络书籍,公司题目以及博主原创或修改(题目大部分来源于各种公司);文中很多题目,或许大家直接编译器写完,1分钟就出结果了。但在这里博主希望每一个题目,大家都要…

手机访问跳转手机网站环保网站策划书

企业客户信息反馈平台 目录 基于SprinBootvue的企业客户信息反馈平台 一、前言 二、系统设计 三、系统功能设计 1平台功能模块 2后台登录 5.2.1管理员功能 5.2.2客户功能 四、数据库设计 五、核心代码 六、论文参考 七、最新计算机毕设选题推荐 八、源码获取&am…

Python中小整数对象池、intern机制和大整数对象池

Python中小整数对象池、intern机制和大整数对象池小整数对象池 整数在程序中的使用非常广泛,Python为了优化速度,使用了小整数对象池, 避免为整数频繁申请和销毁内存空间。Python 对小整数的定义是 [-5, 256] 这些整…

如何采用插件和子主题添加WordPress自定义CSS(附:常见错误)

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

ctf逆向常见算法----base64

ctf逆向常见算法----base64 base64顾名思义,即为使用A-Z,a-z,0-9,+,/,64个字符进行编码的一种方式,当然在日常的使用中还会出现=用作填充字符。 作为在ctf竞赛中最常用的一种编码形式,本篇文章将对其原理及代码…

唐山哪里有建设网站的百度搜索引擎属于什么引擎

博主介绍:✌从事软件开发10年之余,专注于Java技术领域、Python人工智能及数据挖掘、小程序项目开发和Android项目开发等。CSDN、掘金、华为云、InfoQ、阿里云等平台优质作者✌ 🍅文末获取源码联系🍅 👇🏻 精…

02020409 EF Core基础09-一对一、多对多、EF Core基于关系的复杂查询

02020409 EF Core基础09-一对一、多对多、EF Core基于关系的复杂查询 1. 一对一(视频3-20) 1.1 一对一关系 采购申请单 ↔ 采购订单 订单 ↔ 快递单一对一:对方都是对方的唯一。一个订单单对应一个快递单,一个快递…

02020503 EF Core高级03-分页查询、IQuerable底层的实现形式、DataReader、DataTable、EF Core中的异步方法

02020503 EF Core高级03-分页查询、IQuerable底层的实现形式、DataReader、DataTable、EF Core中的异步方法 1. EF Core分页查询(视频3-27) 1.1 分页查询的实现 1、Skip(3).Take(8) 最好显式指定排序规则,Skip表示跳…

02020502 EF Core高级02-IQuerable会延迟执行、分部和动态构建IQuerable、IQuerable的复用

02020502 EF Core高级02-IQuerable会延迟执行、分部和动态构建IQuerable、IQuerable的复用 1. IQuerable会延迟执行(视频3-25) 1、测试一下:只查询,但是不遍历IQueryable,查看是否有执行SQL语句。 2、在查询之后、…

在 PyCharm 中,环境:bert_env , 执行 import wandb 报错。但是,在CMD窗口,环境:bert_env , 执行 import wandb 正常。

同一个wandb包,使用相同的conda虚拟环境,在pycharm中导入失败,在command窗口中导入成功。 同一个ssl包,使用相同的conda虚拟环境,在pycharm中导入失败,在command窗口中导入成功。在 PyCharm 中,环境:bert_env …

设计网站排行北京有哪些网站建设公司

[html] 当html中使用map标签时,area中coords值如何精确定位呢? 在 area 标签上支持的属性有 shape、coords、href、alt、target、type、download、hreflang、media、rel; coords 值如何精确定位圆形,在绘制一个圆形时,其 shapeci…

libopenssl1_0_0-1.0.2p-3.49.1.x86_64安装教程(RPM包手动安装步骤+依赖解决附安装包下载)

libopenssl1_0_0-1.0.2p-3.49.1.x86_64安装教程(RPM包手动安装步骤+依赖解决附安装包下载)​ ​第一步:先检查下系统环境​ 这包是 ​x86_64 架构的(也就是常见的 64 位 Linux 系统),你得确认自己的系统是 64 位…

Linux_T(Sticky Bit)粘滞位详解 - 详解

Linux_T(Sticky Bit)粘滞位详解 - 详解pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "M…

和顺网站建设电商推广和网络推广的策略

桥梁模式 定义 桥梁模式(Bridge Pattern)也叫做桥接模式。 将抽象和显示解耦,使得两者可以独立地变化。 优缺点、应用场景 优点 抽象和实现的解耦。 这是桥梁模式的主要特点,它完全是为了解决继承的缺点而提出的设计模式。优…

P2831 [NOIP 2016 提高组] 愤怒的小鸟 题解

传送门 洛谷 题目大意 每关给你最多18只小猪(后文皆为18只),问你最少用几条过原点抛物线全部干掉。 注意这里 \(m\) 其实没用,因为你要是会算最优解了为啥还需要部分分啊? 思路 \(n\leq18\) ,不是暴搜就是状压。…

t型布局网站怎么做移动网站开发公司

无限网络应用越来越广泛,由此应运而生了许多可以蹭网的软件,家里的网速突然变慢了,也许就是隔壁的小哥哥小姐姐在蹭网络,那么如何避免被蹭网?今天小编给各位小伙伴推荐几款路由器管理软件,发现网络变慢了&a…

网站建设功能要求做男女之间的事情的网站

1.1 APT攻击简介 1.1.1APT攻击概念 网络安全,尤其是Internet互联网安全正在面临前所未有的挑战,这主要就来自于有组织、有特定目标、持续时间极长的新型攻击和威胁,国际上有的称之为APT(Advanced Persistent Threat)攻…