基本配置
LangGraph实现agent的同步异步执行,同步异步的流式输出,ReAct限制最大迭代次数
模型调用通义千问(阿里Tongyi大模型)
agent的运行
agent同步和异步执行,使用.invoke() / await .invoke() 表示完整响应,使用.stream() /.astream()表示增量流式输出。
1.同步和异步运行示例
# -*- coding: utf-8 -*-
from langgraph.prebuilt import create_react_agent
from langchain_community.chat_models.tongyi import ChatTongyi #dashscope #阿里云Tongyi大模型
from pydantic import BaseModel
import asyncio
from langgraph.errors import GraphRecursionError
#模型初始化
llm = ChatTongyi(
model="qwen-turbo",#qwen-max-latest qwen-plus
temperature=0,
verbose=True,
)
#定义一个工具函数
def get_ICBC(city: str) -> str:
"""获得中国工商银行的保险信息"""
return f"工银安盛人寿保险有限公司 简称工银安盛人寿!"
#结构化输出 可选地,structured_response如果配置了结构化输出。
# 结构化输出需要额外调用 LLM 来根据模式格式化响应。 现在Tongyi大模型好像不支持
class StructResponse(BaseModel):
conditions: str
#构建一个智能体
agent = create_react_agent(
model=llm,
tools=[get_ICBC],
# response_format=StructResponse
)
#同步调用
response1 = agent.invoke(
{"messages": [{"role": "user", "content": "你能告诉杭州中国工商银行的保险名称?"}]}
)
# print(response1)
print(response1["messages"][-1])
print("----------------------------")
#异步调用
async def async_function1():
response2 = await agent.ainvoke(
{"messages": [{"role": "user", "content": "你能告诉杭州中国工商银行的保险名称?"}]}
)
print(response2["messages"][-1])
asyncio.run(async_function1())
运行截图
2.同步和异步流式运行示例
agent支持流式响应,以实现更灵敏的应用程序。其中包括:
- 每一步后更新进度
- 生成的LLM 令牌
- 执行期间可以自定义工具消息
# -*- coding: utf-8 -*-
from langgraph.prebuilt import create_react_agent
from langchain_community.chat_models.tongyi import ChatTongyi #dashscope #阿里云Tongyi大模型
from pydantic import BaseModel
import asyncio
from langgraph.errors import GraphRecursionError
#模型初始化
llm = ChatTongyi(
model="qwen-turbo",#qwen-max-latest qwen-plus
temperature=0,
verbose=True,
)
#定义一个工具函数
def get_ICBC(city: str) -> str:
"""获得中国工商银行的保险信息"""
return f"工银安盛人寿保险有限公司 简称工银安盛人寿!"
#结构化输出 可选地,structured_response如果配置了结构化输出。
# 结构化输出需要额外调用 LLM 来根据模式格式化响应。 现在Tongyi大模型好像不支持
class StructResponse(BaseModel):
conditions: str
#构建一个智能体
agent = create_react_agent(
model=llm,
tools=[get_ICBC],
# response_format=StructResponse
)
#同步流媒体
for chunk in agent.stream(
{"messages": [{"role": "user", "content": "你能告诉杭州中国工商银行的保险名称?"}]},
stream_mode="messages" # messages updates
):
print(chunk)
print("----------------------------")
#异步流媒体
async def async_function2():
async for chunk in agent.astream(
{"messages": [{"role": "user", "content": "你能告诉杭州中国工商银行的保险名称?"}]},
stream_mode="messages" # messages updates
):
print(chunk)
asyncio.run(async_function2())
运行截图
3.最大迭代次数
为了控制agent执行时避免无限循环,需要设置递归限制。agent在引发最大步骤数GraphRecursionErro错误之前。在运行时可以定义recursion_limit参数或者通过定义agent时进行配置.with_config():
运行时和配置agent时设定代码示例
# -*- coding: utf-8 -*-
from langgraph.prebuilt import create_react_agent
from langchain_community.chat_models.tongyi import ChatTongyi #dashscope #阿里云Tongyi大模型
from pydantic import BaseModel
import asyncio
from langgraph.errors import GraphRecursionError
#模型初始化
llm = ChatTongyi(
model="qwen-turbo",#qwen-max-latest qwen-plus
temperature=0,
verbose=True,
)
#定义一个工具函数
def get_ICBC(city: str) -> str:
"""获得中国工商银行的保险信息"""
return f"工银安盛人寿保险有限公司 简称工银安盛人寿!"
#结构化输出 可选地,structured_response如果配置了结构化输出。
# 结构化输出需要额外调用 LLM 来根据模式格式化响应。 现在Tongyi大模型好像不支持
class StructResponse(BaseModel):
conditions: str
#构建一个智能体
agent = create_react_agent(
model=llm,
tools=[get_ICBC],
# response_format=StructResponse
)
#最大迭代次数
max_iterations = 3
recursion_limit = 2 * max_iterations + 1
#运行时
response = agent.invoke(
{"messages": [{"role": "user", "content": "你能告诉杭州中国工商银行的保险名称?"}]},
{"recursion_limit": recursion_limit},
)
# print(response)
print(response["messages"][-1])
print("----------------------------")
#.with_config() 配置agent时设定
agent = agent.with_config(recursion_limit=recursion_limit)
try:
response = agent.invoke(
{"messages": [{"role": "user", "content": "你能告诉杭州中国工商银行的保险名称?"}]},
)
# print(response)
print(response["messages"][-1])
except GraphRecursionError:
print("Agent 停止:达到最大迭代数")
运行截图
下一节:
1.流媒体stream_mode参数设置
2.工具中流式传输如何更新