使用LangGraph调用大模型:agent的各种执行方式

基本配置

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.工具中流式传输如何更新

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值