langgraph快速搭建agent后端和react前端

官方文档

一、后端

1.安装基础依赖

python 复制代码
pip install --upgrade "langgraph-cli[inmem]"

2.下载模版项目

在终端运行

python 复制代码
langgraph new ./example --template new-langgraph-project-python

这里是在当前文件夹下新建文件夹example,里面是下载的langgraph模版项目文件

显示这样就是成功。如果失败,说明网络问题。

3.安装项目依赖

python 复制代码
cd example
pip install -e .

4.配置项目环境变量

将.env.example文件修改为.env,这样就是环境变量文件了,重要的key都放在这里,和代码文件隔离

填写LANGSMITH_API_KEY,需要去langsmith注册账号,获取key

5.部署后端服务

python 复制代码
langgraph dev

就会看到

6.核心代码

是src.agent.graph.py

python 复制代码
"""LangGraph single-node graph template.

Returns a predefined response. Replace logic and configuration as needed.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Dict, TypedDict

from langgraph.graph import StateGraph
from langgraph.runtime import Runtime

# 上下文参数
class Context(TypedDict):
    """Context parameters for the agent.

    Set these when creating assistants OR when invoking the graph.
    See: https://langchain-ai.github.io/langgraph/cloud/how-tos/configuration_cloud/
    """

    my_configurable_param: str

# 状态参数,定义输入参数
@dataclass
class State:
    """Input state for the agent.

    Defines the initial structure of incoming data.
    See: https://langchain-ai.github.io/langgraph/concepts/low_level/#state
    """

    changeme: str = "example"

# 一个节点,接收state和runtime,返回output
async def call_model(state: State, runtime: Runtime[Context]) -> Dict[str, Any]:
    """Process input and returns output.

    Can use runtime context to alter behavior.
    """
    return {
        "changeme": "output from call_model. "
        f"Configured with {runtime.context.get('my_configurable_param')}"
    }


# 定义图
graph = (
    StateGraph(State, context_schema=Context)
    .add_node(call_model)
    .add_edge("__start__", "call_model")
    .compile(name="New Graph")
)

图形化后是

二、前端

官方文档

前置条件,在本地或者云端已经部署了langgraph的服务

然后本地安装前端项目,并启动

python 复制代码
git clone https://github.com/langchain-ai/agent-chat-ui.git

cd agent-chat-ui

pnpm install

启动前端

python 复制代码
pnpm dev

这样本地就有两个项目了

如果没有pnpm,就安装

python 复制代码
brew install pnpm

三、最终效果

因为前端的显示是消息,所以要修改示例代码,我的简易代码

python 复制代码
from typing import Annotated

from typing_extensions import TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages


class State(TypedDict):
    # Messages have the type "list". The `add_messages` function
    # in the annotation defines how this state key should be updated
    # (in this case, it appends messages to the list, rather than overwriting them)
    messages: Annotated[list, add_messages]


def call_llm(state: State) -> State:
    return {
        "messages": [
            {
                "role": "assistant",
                "content": "你好,我是小爱同学,请问你是谁?"
            }
        ]
    }

graph_builder = StateGraph(State)

graph_builder.add_node("call_llm", call_llm)

graph_builder.add_edge(START, "call_llm")
graph_builder.add_edge("call_llm", END)

graph = graph_builder.compile()

四、本地客户端访问langgraph服务

官方文档

代码

python 复制代码
from langgraph_sdk import get_client
import asyncio

client = get_client(url="http://localhost:2024")

async def main():
    async for chunk in client.runs.stream(
        None,  # Threadless run
        "agent", # Name of assistant. Defined in langgraph.json.
        input={
        "messages": [{
            "role": "human",
            "content": "hello",
            }],
        },
    ):
        print(f"Receiving new event of type: {chunk.event}...")
        print(chunk.data)
        print("\n\n")

asyncio.run(main())

效果

相关推荐
是一碗螺丝粉15 小时前
LangChain 链(Chains)完全指南:从线性流程到智能路由
前端·langchain·aigc
前端付豪15 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
神秘的猪头15 小时前
🔌 给 AI 装上“三头六臂”!实战大模型接入第三方 MCP 全攻略
langchain·llm·mcp
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
神秘的猪头1 天前
🔌 把 MCP 装进大脑!手把手带你构建能“热插拔”工具的 AI Agent
langchain·llm·mcp
是一碗螺丝粉3 天前
5分钟上手LangChain.js:用DeepSeek给你的App加上AI能力
前端·人工智能·langchain
是一碗螺丝粉3 天前
LangChain 核心组件深度解析:模型与提示词模板
前端·langchain·aigc
大模型真好玩3 天前
大模型训练全流程实战指南工具篇(七)——EasyDataset文档处理流程
人工智能·langchain·deepseek
勇气要爆发4 天前
吴恩达《LangChain LLM 应用开发精读笔记》1-Introduction_介绍
笔记·langchain·吴恩达