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/

相关推荐
小鸡吃米…1 小时前
机器学习 - K - 中心聚类
人工智能·机器学习·聚类
好奇龙猫2 小时前
【AI学习-comfyUI学习-第三十节-第三十一节-FLUX-SD放大工作流+FLUX图生图工作流-各个部分学习】
人工智能·学习
沈浩(种子思维作者)2 小时前
真的能精准医疗吗?癌症能提前发现吗?
人工智能·python·网络安全·健康医疗·量子计算
minhuan2 小时前
大模型应用:大模型越大越好?模型参数量与效果的边际效益分析.51
人工智能·大模型参数评估·边际效益分析·大模型参数选择
Cherry的跨界思维2 小时前
28、AI测试环境搭建与全栈工具实战:从本地到云平台的完整指南
java·人工智能·vue3·ai测试·ai全栈·测试全栈·ai测试全栈
MM_MS2 小时前
Halcon变量控制类型、数据类型转换、字符串格式化、元组操作
开发语言·人工智能·深度学习·算法·目标检测·计算机视觉·视觉检测
ASF1231415sd2 小时前
【基于YOLOv10n-CSP-PTB的大豆花朵检测与识别系统详解】
人工智能·yolo·目标跟踪
水如烟3 小时前
孤能子视角:“意识“的阶段性回顾,“感质“假说
人工智能
Carl_奕然3 小时前
【数据挖掘】数据挖掘必会技能之:A/B测试
人工智能·python·数据挖掘·数据分析
旅途中的宽~3 小时前
《European Radiology》:2024血管瘤分割—基于MRI T1序列的分割算法
人工智能·计算机视觉·mri·sci一区top·血管瘤·t1