2. langgraph中的react agent使用 (在react agent添加历史消息)

1. 导入必要的库

首先,我们需要导入所需的库。这里我们使用 langchain_openai 来与 智谱AI 模型进行交互,并使用 langchain_core.tools 来定义自定义工具。

python 复制代码
from langchain_openai import ChatOpenAI
from typing import Literal
from langchain_core.tools import tool

2. 初始化 智谱AI 模型

接下来,我们初始化 智谱AI 模型。这里需要指定模型的参数,包括温度、模型名称、API 密钥和 API 基地址。

python 复制代码
model = ChatOpenAI(
    temperature=0,
    model="glm-4-plus",
    openai_api_key="your_api_key",
    openai_api_base="https://open.bigmodel.cn/api/paas/v4/"
)

3. 定义自定义工具

我们定义一个获取天气信息的工具 get_weather,该工具接受一个城市名称作为参数,并返回相应的天气信息。

python 复制代码
@tool
def get_weather(city: Literal["nyc", "sf"]):
    """Use this to get weather information."""
    if city == "nyc":
        return "It might be cloudy in nyc"
    elif city == "sf":
        return "It's always sunny in sf"
    else:
        raise AssertionError("Unknown city")

4. 创建工具列表

将定义好的工具添加到工具列表中。

python 复制代码
tools = [get_weather]

5. 初始化记忆存储

使用 MemorySaver 来存储对话过程中的状态。

python 复制代码
from langgraph.checkpoint.memory import MemorySaver

memory = MemorySaver()

6. 创建反应式代理

使用 create_react_agent 函数创建一个反应式代理,该代理将模型和工具结合在一起。

python 复制代码
from langgraph.prebuilt import create_react_agent

graph = create_react_agent(model, tools=tools, checkpointer=memory)

7. 定义打印流函数

为了更好地展示对话过程,我们定义一个 print_stream 函数,用于打印流式输出的消息。

python 复制代码
def print_stream(stream):
    for s in stream:
        message = s["messages"][-1]
        if isinstance(message, tuple):
            print(message)
        else:
            message.pretty_print()

8. 发送查询并打印结果

配置输入参数,并发送查询请求,最后打印结果。

python 复制代码
config = {"configurable": {"thread_id": "1"}}
inputs = {"messages": [("user", "What's the weather in NYC?")]}

print_stream(graph.stream(inputs, config=config, stream_mode="values"))

输出结果如下:

复制代码
==============================[1m Human Message [0m=================================

What's the weather in NYC?
================================[1m Ai Message [0m==================================
Tool Calls:
  get_weather (call_9208192282885233822)
 Call ID: call_9208192282885233822
  Args:
    city: nyc
================================[1m Tool Message [0m=================================
Name: get_weather

It might be cloudy in nyc
================================[1m Ai Message [0m==================================

It might be cloudy in NYC.

9. 发送另一个查询并打印结果

再次配置输入参数,发送新的查询请求,并打印结果。

python 复制代码
inputs = {"messages": [("user", "What's it known for?")]}
print_stream(graph.stream(inputs, config=config, stream_mode="values"))

输出结果如下:

复制代码
==============================[1m Human Message [0m=================================

What's it known for?
================================[1m Ai Message [0m==================================

New York City is known for a multitude of things, making it one of the most iconic and influential cities in the world. Here are some highlights:

1. **Statue of Liberty**: A symbol of freedom and democracy, this iconic statue is located on Liberty Island.

2. **Central Park**: An expansive urban park in the heart of Manhattan, known for its lush landscapes, recreational activities, and cultural events.

3. **Broadway**: The pinnacle of American theater, Broadway is famous for its high-quality performances and historic theaters.

4. **Times Square**: A bustling commercial intersection known for its bright lights, massive digital billboards, and the annual New Year's Eve ball drop.

5. **Empire State Building**: An Art Deco skyscraper that once held the title of the world's tallest building and remains a symbol of New York's skyline.

6. **Museums and Art**: Home to world-renowned institutions like the Metropolitan Museum of Art, the Museum of Modern Art (MoMA), and the Guggenheim.

7. **Diverse Cuisine**: Reflecting its status as a melting pot, NYC offers an incredible variety of global cuisines.

8. **Financial Hub**: Wall Street and the New York Stock Exchange are central to the global economy.

9. **Fashion Capital**: Known for its influence on global fashion trends, hosting events like New York Fashion Week.

10. **Cultural Diversity**: A city of immigrants, NYC boasts a rich tapestry of cultures, languages, and traditions.

These are just a few aspects that contribute to NYC's global reputation and appeal.

参考链接:https://langchain-ai.github.io/langgraph/how-tos/create-react-agent-memory/

相关推荐
G皮T3 小时前
【人工智能】ChatGPT、DeepSeek-R1、DeepSeek-V3 辨析
人工智能·chatgpt·llm·大语言模型·deepseek·deepseek-v3·deepseek-r1
九年义务漏网鲨鱼3 小时前
【大模型学习 | MINIGPT-4原理】
人工智能·深度学习·学习·语言模型·多模态
元宇宙时间3 小时前
Playfun即将开启大型Web3线上活动,打造沉浸式GameFi体验生态
人工智能·去中心化·区块链
开发者工具分享3 小时前
文本音频违规识别工具排行榜(12选)
人工智能·音视频
产品经理独孤虾4 小时前
人工智能大模型如何助力电商产品经理打造高效的商品工业属性画像
人工智能·机器学习·ai·大模型·产品经理·商品画像·商品工业属性
老任与码4 小时前
Spring AI Alibaba(1)——基本使用
java·人工智能·后端·springaialibaba
蹦蹦跳跳真可爱5894 小时前
Python----OpenCV(图像増强——高通滤波(索贝尔算子、沙尔算子、拉普拉斯算子),图像浮雕与特效处理)
人工智能·python·opencv·计算机视觉
雷羿 LexChien4 小时前
从 Prompt 管理到人格稳定:探索 Cursor AI 编辑器如何赋能 Prompt 工程与人格风格设计(上)
人工智能·python·llm·编辑器·prompt
两棵雪松5 小时前
如何通过向量化技术比较两段文本是否相似?
人工智能
heart000_15 小时前
128K 长文本处理实战:腾讯混元 + 云函数 SCF 构建 PDF 摘要生成器
人工智能·自然语言处理·pdf