环境准备
首先,确保你已经安装了以下库:
langchain_openai
langchain_core
langgraph
你可以使用以下命令进行安装:
pip install langchain_openai langchain_core langgraph
代码实现
1. 导入必要的库
from langchain_openai import ChatOpenAI
from typing import Literal
from langchain_core.tools import tool
from langgraph.prebuilt import create_react_agent
from IPython.display import Image, display
2. 初始化智谱AI 模型
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. 定义工具函数
@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. 创建工具列表
tools = [get_weather]
5. 创建反应式代理
graph = create_react_agent(model, tools=tools)
6. 显示代理图
display(Image(graph.get_graph().draw_mermaid_png()))
7. 定义打印流函数
def print_stream(stream):
for s in stream:
message = s["messages"][-1]
if isinstance(message, tuple):
print(message)
else:
message.pretty_print()
8. 测试获取天气信息
inputs = {"messages": [("user", "what is the weather in sf")]}
print_stream(graph.stream(inputs, stream_mode="values"))
输出:
==============================[1m Human Message [0m=================================
what is the weather in sf
================================[1m Ai Message [0m==================================
Tool Calls:
get_weather (call_9208187678678973525)
Call ID: call_9208187678678973525
Args:
city: sf
================================[1m Tool Message [0m=================================
Name: get_weather
It's always sunny in sf
================================[1m Ai Message [0m==================================
The weather in San Francisco is always sunny.
9. 测试其他问题
inputs = {"messages": [("user", "who built you?")]}
print_stream(graph.stream(inputs, stream_mode="values"))
输出:
==============================[1m Human Message [0m=================================
who built you?
================================[1m Ai Message [0m==================================
I am ChatGLM(智谱清言), an AI assistant, developed by Zhipu AI and KEG Lab of Tsinghua University.
参考链接:https://langchain-ai.github.io/langgraph/how-tos/create-react-agent/