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/

相关推荐
Faker66363aaa1 分钟前
织物破损检测与分类-YOLO11-C3k2-MSMHSA-CGLU模型详解
人工智能·分类·数据挖掘
mwq301231 分钟前
anthropic-academy:工具使用(一)
人工智能
mwq301233 分钟前
Claude 完整代码教程(转载)
人工智能
DisonTangor5 分钟前
【阿里拥抱开源】阿里inclusionAI开源多模态Ming-flash-omni 2.0
人工智能·开源·aigc
MaoziShan8 分钟前
CMU Subword Modeling | 01 Things Smaller than Words
人工智能·机器学习·自然语言处理
文艺倾年10 分钟前
【免训练&测试时扩展】Code Agent可控进化
人工智能·软件工程·强化学习·vibecoding
宇擎智脑科技11 分钟前
SurrealDB:面向AI原生应用的新一代多模型数据库深度解析
数据库·人工智能·ai-native
一品威客爱开发12 分钟前
网游 APP 开发:聚焦交互体验与多端协同
人工智能
前沿AI12 分钟前
中关村科金 × 中国电信 以「文旅大模型 + 智能客服」点亮自贡灯会智慧服务新标杆
人工智能
木斯佳12 分钟前
HarmonyOS实战(解决方案篇)—企业AI资产利旧:如何将已有智能体快速接入鸿蒙生态
人工智能·华为·harmonyos