3. langgraph中的react agent使用 (在react agent添加系统提示)

环境准备

确保你已经安装了以下库:

  • langchain
  • langchain_openai
  • langgraph

你可以使用以下命令进行安装:

bash 复制代码
pip install langchain langchain_openai langgraph

代码实现

1. 初始化模型

首先,我们需要初始化智谱AI的聊天模型。

python 复制代码
from langchain_openai import ChatOpenAI

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

2. 定义自定义工具

我们将使用一个自定义工具来返回纽约和旧金山的天气信息。

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

@tool
def get_weather(city: Literal["nyc", "sf"]):
    """使用此工具获取天气信息."""
    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")

tools = [get_weather]

3. 添加系统提示

我们可以添加一个系统提示来指定响应的语言。

python 复制代码
prompt = "Respond in Italian"

4. 定义执行图

使用langgraph库创建一个React代理。

python 复制代码
from langgraph.prebuilt import create_react_agent

graph = create_react_agent(model, tools=tools, state_modifier=prompt)

5. 定义输出流处理函数

定义一个函数来处理输出流。

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

6. 运行并打印结果

输入一个用户消息并运行模型,打印输出结果。

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

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

输出结果如下:

复制代码
================================[1m Human Message [0m=================================
What's the weather in NYC?
================================[1m Ai Message [0m==================================
Tool Calls:
  get_weather (call_9208187369440656653)
 Call ID: call_9208187369440656653
  Args:
    city: nyc
================================[1m Tool Message [0m=================================
Name: get_weather

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

Il tempo a New York potrebbe essere nuvoloso.

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

相关推荐
停停的茶2 小时前
深度学习(目标检测)
人工智能·深度学习·目标检测
Y200309162 小时前
基于 CIFAR10 数据集的卷积神经网络(CNN)模型训练与集成学习
人工智能·cnn·集成学习
老兵发新帖2 小时前
主流神经网络快速应用指南
人工智能·深度学习·神经网络
AI量化投资实验室3 小时前
15年122倍,年化43.58%,回撤才20%,Optuna机器学习多目标调参backtrader,附python代码
人工智能·python·机器学习
java_logo3 小时前
vllm-openai Docker 部署手册
运维·人工智能·docker·ai·容器
倔强青铜三3 小时前
苦练Python第67天:光速读取任意行,linecache模块解锁文件处理新姿势
人工智能·python·面试
算家计算3 小时前
重磅突破!全球首个真实物理环境机器人基准测试正式发布,具身智能迎来 “ImageNet 时刻”
人工智能·资讯
新智元3 小时前
苹果 M5「夜袭」高通英特尔!AI 算力狂飙 400%,Pro 三剑客火速上新
人工智能·openai
GoppViper3 小时前
什么是GEO生成式引擎优化?GEO科普:定义、原理与应用指南
人工智能·搜索引擎
新智元3 小时前
谷歌 × 耶鲁联手发布抗癌神器!AI 推理精准狙击「隐身」癌细胞
人工智能·openai