有做不锈钢工程的网站网站风格主要包括
2026/5/21 13:39:40 网站建设 项目流程
有做不锈钢工程的网站,网站风格主要包括,赣州市建设工程质量监督平台网站,广东省广州市番禺区南村镇Tool Calling Agent 的局限性又在于#xff1a;虽然它可以自主选择工具#xff0c;但在其架构中#xff0c;每次仅能执行一次函数调用#xff08;无论是单个外部函数还是多个外部函数#xff09;**。因此#xff0c;当任务需要依次执行 A 工具、B 工具和 C 工具时#x…Tool Calling Agent的局限性又在于虽然它可以自主选择工具但在其架构中每次仅能执行一次函数调用无论是单个外部函数还是多个外部函数**。因此当任务需要依次执行 A 工具、B 工具和 C 工具时它无法支持这种自主控制的过程。因此面对这种更复杂的需求就需要引入了Full Autonomous自治循环代理架构即如下图所示Full Autonmonous以两种主要的方式去扩展了Agent对工作流的控制分别是多步骤决策Agent可以控制一系列决策而不仅仅是一个决策。工具访问Agent可以选择并使用多种工具来完成任务。满足上述两个条件典型且通用的代理架构就是基于ReAct思想而形成的代理模式。ReAct的核心理念还是在于为大模型配备足够丰富的外部工具使用合适的提示词引导大模型在接收到用户输入后进入自主思考和循环执行的状态以实现最终目标。1. LangGraph中ReAct的构建原理在LangGraph开发框架中有一些预构建的组件。上节课介绍的ToolNode是其中一个它用于处理外部函数调用其内部结合了LangGraph底层的图结构能够接收JSON Schema形式的数据执行工具函数并返回结果。除此之外LangGraph的预构建组件中还包含了ReAct代理架构该架构与我们在《ReAct 智能应用架构深度剖析》中手动实现的思路和流程基本一致。不同之处在于在LangGraph框架中ReAct组件被改造成适配图结构的循环代理其具体过程是大模型可以在一个while循环中被重复调用。每一步代理来自主决定调用哪些工具及其输入然后执行这些工具并将输出作为观察结果反馈给大模型。当代理判断不再需要调用更多工具时while循环便会终止输出最终的结果。因此我们需要理解的关键概念是LangGraph预构建的ReAct组件其实就是通过接入大模型搭配着Tool Calling Agent再结合Router Agent共同构建起来的图这个图以自治循环代理的架构形式提供服务。其图结构如下图所示这种代理实现的机制表明了在LangGraph中实现的预构建ReAct代理结构它支持Tool calling 允许大模型根据需要选择和使用各种工具。Memory使代理能够保留和使用先前步骤中的信息。Planning 授权大模型制定并遵循多步骤计划以实现目标。而其在图结构中的具体构建的工作流如下图所示如图所示Agent节点使用消息列表的形式来调用大语言模型Messages Modifier指的是在传递到大模型之前修饰用户的原始输入内容可以是SystemMessage作为背景信息添加的消息列表的开头、Runnable可运行等不同状态如果生成的AIMessage包含tool_calls则该图将调用tools。tools节点执行工具每个tool_call1 个工具并且将响应作为ToolMessage对象添加到消息列表。然后Agent节点再次调用大语言模型。重复该过程直到响应中不再存在tool_calls最终由Agent节点将完整的消息列表作为包含键messages的字典返回。那么如何实现上述这个非常复杂的过程呢非常简单既然我们一直提到的是预构建组件则说明整个过程已经由LangGraph内部封装好了其提供给开发者使用的接口就是create_react_agent方法。在这个案例中我们将通过一个多工具场景需求来测试LangGraph中ReAct代理的构建方法和效果。我们设计了几个工具以实现实时数据的查询和管理。首先用户可以通过一个工具根据城市名称实时获取当前天气信息。接着如果用户希望将查询到的天气数据保存到本地数据库中可以使用另一个工具完成数据的插入操作。此外我们还提供了一个工具允许用户基于本地数据库中的天气数据进行提问数据进行提问。通过这些工具的组合我们能够快速验证如何在复杂的应用场景中有效地整合不同功能并实际的感知LangGraph框架下ReAct代理模式带来的开发便捷性和可扩展性。首先我们接入实时天气数据查询的在线API代码定义如下OpenWeather API的注册与使用注册地址https://openweathermap.org/importrequestsimportjsondefget_weather(loc): Function to query current weather. :param loc: Required parameter, of type string, representing the specific city name for the weather query. \ Note that for cities in China, the corresponding English city name should be used. For example, to query the weather for Beijing, \ the loc parameter should be input as Beijing. :return: The result of the OpenWeather API query for current weather, with the specific URL request address being: https://api.openweathermap.org/data/2.5/weather. \ The return type is a JSON-formatted object after parsing, represented as a string, containing all important weather information. # Step 1.构建请求urlhttps://api.openweathermap.org/data/2.5/weather# Step 2.设置查询参数params{q:loc,appid:xxxxxxxxxxxxxxxxxxxxxxxx,# 替换为自己的API keyunits:metric,# 使用摄氏度而不是华氏度lang:zh_cn# 输出语言为简体中文}# Step 3.发送GET请求responserequests.get(url,paramsparams)# Step 4.解析响应dataresponse.json()returnjson.dumps(data)测试一下get_weather函数的有效性正常情况下可以得到输入城市名的实时天气信息。测试代码如下所示从返回的结果是Json数据类型包含了非常丰富的实时天气数据如天气条件、温度、湿度、风速、天气描述等信息这里我们选择一些重要的数据参数进行存储操作存储至Mysql数据库中。提取的参数如下字段名称描述city_id城市的唯一标识符city_name城市名称main_weather主要天气状况description天气的详细描述temperature当前温度feels_like体感温度temp_min最低温度temp_max最高温度接下来设计一个用于存储实时天气信息的表。这里我们定义一个新的模型Weather并包括上述所提取出来的的字段。连接Mysql数据库及创建表的代码如下所示fromsqlalchemyimportcreate_engine,Column,Integer,String,Floatfromsqlalchemy.ormimportsessionmaker,declarative_base# 创建基类Basedeclarative_base()# 定义 WeatherInfo 模型classWeather(Base):__tablename__weathercity_idColumn(Integer,primary_keyTrue)# 城市IDcity_nameColumn(String(50))# 城市名称main_weatherColumn(String(50))# 主要天气状况descriptionColumn(String(100))# 描述temperatureColumn(Float)# 温度feels_likeColumn(Float)# 体感温度temp_minColumn(Float)# 最低温度temp_maxColumn(Float)# 最高温度# 数据库连接 URI这里要替换成自己的Mysql 连接信息以下是各个字段的对应解释# gptMySQL 数据库的用户名。# gptMySQL 数据库的密码。# localhostMySQL 服务器的 IP 地址。# langgraph要连接的数据库的名称。# charsetutf8mb4设置数据库的字符集为 utf8mb4支持更广泛的 Unicode 字符DATABASE_URImysqlpymysql://gpt:gptlocalhost:20100/langgraph?charsetutf8mb4enginecreate_engine(DATABASE_URI)# 如果表不存在则创建表Base.metadata.create_all(engine)# 创建会话Sessionsessionmaker(bindengine)接下来使用LangChain的tool装饰器将普通的函数注册为LangGraph中支持的工具服务根据需求的设计我们要依次创建三个外部函数分别是get_weather工具用于根据城市名称实时查询该城市的当前天气数据。insert_weather_to_db工具如果用户想要把查询到的天气数据插入到数据库的表中则使用此函数完成数据库的插入操作。query_weather_from_db工具如果用户想基于本地数据库的天气数据直接进行提问则使用此函数完成数据库的查询操作。fromlangchain_core.toolsimporttoolfromtypingimportUnion,OptionalfrompydanticimportBaseModel,Fieldimportrequests## 第一个工具classWeatherLoc(BaseModel):location:strField(descriptionThe location name of the city)classWeatherInfo(BaseModel):Extracted weather information for a specific city.city_id:intField(...,descriptionThe unique identifier for the city)city_name:strField(...,descriptionThe name of the city)main_weather:strField(...,descriptionThe main weather condition)description:strField(...,descriptionA detailed description of the weather)temperature:floatField(...,descriptionCurrent temperature in Celsius)feels_like:floatField(...,descriptionFeels-like temperature in Celsius)temp_min:floatField(...,descriptionMinimum temperature in Celsius)temp_max:floatField(...,descriptionMaximum temperature in Celsius)tool(args_schemaWeatherLoc)defget_weather(location): Function to query current weather. :param loc: Required parameter, of type string, representing the specific city name for the weather query. \ Note that for cities in China, the corresponding English city name should be used. For example, to query the weather for Beijing, \ the loc parameter should be input as Beijing. :return: The result of the OpenWeather API query for current weather, with the specific URL request address being: https://api.openweathermap.org/data/2.5/weather. \ The return type is a JSON-formatted object after parsing, represented as a string, containing all important weather information. # Step 1.构建请求urlhttps://api.openweathermap.org/data/2.5/weather# Step 2.设置查询参数params{q:location,appid:5c939a7cc59eb8696f4cd77bf75c5a9a,# 输入API keyunits:metric,# 使用摄氏度而不是华氏度lang:zh_cn# 输出语言为简体中文}# Step 3.发送GET请求responserequests.get(url,paramsparams)# Step 4.解析响应dataresponse.json()returnjson.dumps(data)## 第二个工具tool(args_schemaWeatherInfo)definsert_weather_to_db(city_id,city_name,main_weather,description,temperature,feels_like,temp_min,temp_max):Insert weather information into the database.sessionSession()# 确保为每次操作创建新的会话try:# 创建天气实例weatherWeather(city_idcity_id,city_namecity_name,main_weathermain_weather,descriptiondescription,temperaturetemperature,feels_likefeels_like,temp_mintemp_min,temp_maxtemp_max)# 使用 merge 方法来插入或更新如果已有记录则更新session.merge(weather)# 提交事务session.commit()return{messages:[f天气数据已成功存储至Mysql数据库。]}exceptExceptionase:session.rollback()# 出错时回滚return{messages:[f数据存储失败错误原因{e}]}finally:session.close()# 关闭会话## 第三个工具classQueryWeatherSchema(BaseModel):Schema for querying weather information by city name.city_name:strField(...,descriptionThe name of the city to query weather information)tool(args_schemaQueryWeatherSchema)defquery_weather_from_db(city_name:str):Query weather information from the database by city name.sessionSession()try:# 查询天气数据weather_datasession.query(Weather).filter(Weather.city_namecity_name).first()ifweather_data:return{city_id:weather_data.city_id,city_name:weather_data.city_name,main_weather:weather_data.main_weather,description:weather_data.description,temperature:weather_data.temperature,feels_like:weather_data.feels_like,temp_min:weather_data.temp_min,temp_max:weather_data.temp_max}else:return{messages:[f未找到城市 {city_name} 的天气信息。]}exceptExceptionase:return{messages:[f查询失败错误原因{e}]}finally:session.close()# 关闭会话然后定义实时联网检索外部工具通过该函数获取最新的网络数据信息。## 第四个工具classSearchQuery(BaseModel):query:strField(descriptionQuestions for networking queries)tool(args_schemaSearchQuery)deffetch_real_time_info(query):Get real-time Internet informationurlhttps://google.serper.dev/searchpayloadjson.dumps({q:query,num:1,})headers{X-API-KEY:22a84d67009121271e4a5eb21d809e11d3bc8d45,Content-Type:application/json}responserequests.post(url,headersheaders,datapayload)datajson.loads(response.text)# 将返回的JSON字符串转换为字典iforganicindata:returnjson.dumps(data[organic],ensure_asciiFalse)# 返回organic部分的JSON字符串else:returnjson.dumps({error:No organic results found},ensure_asciiFalse)# 如果没有organic键返回错误信息然后把所有定义的工具存储在一个列表中如下代码所示tools[fetch_real_time_info,get_weather,insert_weather_to_db,query_weather_from_db]tools定义模型importgetpassimportosfromlangchain_openaiimportChatOpenAIfromdotenvimportload_dotenv load_dotenv()keyos.getenv(DASHSCOPE_API_KEY)base_urlos.getenv(DASHSCOPE_API_BASE)llmChatOpenAI(modelqwen-plus,api_keykey,base_urlbase_url,temperature0)当有了工具列表和模型后就可以通过create_react_agent这个LangGraph框架中预构建的方法来创建自治循环代理ReAct的工作流其必要的参数如下model 支持工具调用的LangChain聊天模型。tools 工具列表、ToolExecutor 或 ToolNode 实例。state_schema图的状态模式。必须有messages和is_last_step键。默认为定义这两个键的Agent State。fromlanggraph.prebuiltimportcreate_react_agent graphcreate_react_agent(llm,toolstools)fromIPython.displayimportImage,display display(Image(graph.get_graph().draw_mermaid_png()))2.构建步骤解析我们可以逐步的分析和解释一下这一行代码中涉及的图构建过程2.1 Step 1. 定义图状态模式LangGraph中的主要图类型是StateGraph。每个节点通过State中的参数获取有效信息执行完节点的内部逻辑后更新该State状态中的值。不同的状态模式可以通过注释设置状态的特定属性例如覆盖现有值或添加到现有属性。伪代码如下fromtypingimportAnnotatedfromtyping_extensionsimportTypedDictfromlanggraph.graph.messageimportadd_messagesclassState(TypedDict):messages:Annotated[list,add_messages]2.2 Step 2. 定义Router Function设置边缘条件有条件的原因是根据节点的输出可以采用多个路径之一。在该节点运行之前所采用的路径是未知的由大模型决定。条件边缘调用代理后如果代理说要采取行动那么应该调用调用工具的函数。如果代理说已经完成那么就应该完成。正常边调用工具后它应该始终返回给代理来决定下一步做什么。伪代码如下# 定义决定是否继续执行任务的路由函数defshould_continue(state:State):messagesstate[messages]last_messagemessages[-1]# 如果不是工具调用则结束ifnotlast_message.tool_calls:returnEND# 如果是的话则进入工具库中选择函数执行else:returntools2.3 Step 3. 定义大模型的交互函数接下来需要通过一个节点函数加载我想要使用的大模型。它需要满足两个标准应该与消息一起使用因为图的状态主要是消息列表聊天历史记录。需要与工具调用一起使用其内部使用的是预构建的ToolNode。伪代码如下fromtypingimportLiteralfromlangchain_core.runnablesimportRunnableConfig# 定义大模型交互的节点函数asyncdefcall_model(state:State,config:RunnableConfig):messagesstate[messages]responseawaitmodel.ainvoke(messages,config)# 将调用大模型后得到的响应追加到消息列表中return{messages:response}2.4 Step 4. 构建图结构最后把上述所有的组件放在一起构建图结构这与我们手动构建图的方式基本一致伪代码如下fromlanggraph.graphimportEND,START,StateGraph# 定义一个新图workflowStateGraph(State)# 添加两个节点workflow.add_node(agent,call_model)workflow.add_node(tools,tool_node)# 设置起始节点为 agentworkflow.add_edge(START,agent)# 添加条件边 -- Router Agentworkflow.add_conditional_edges(agent,should_continue,[tools,END],)# 添加回调边workflow.add_edge(tools,agent)# 编译图appworkflow.compile()理解了上面的create_react_agent方法内部的构建原理后其实就能明白当通过create_react_agent(llm, toolstools)一行代码的执行现在得到的已经是一个编译后、可执行的图了。我们可以通过mermaid方法来可视化经过create_react_agent方法构造出来的图结构代码如下所示fromIPython.displayimportImage,display display(Image(graph.get_graph().draw_mermaid_png()))返回的是编译好的LangGraph可运行程序可直接用于聊天交互。调用方式则和之前使用的方法一样我们可以依次针对不同复杂程度的需求依次进行提问。首先是测试是否可以不使用工具直接调用大模型生成响应。finan_responsegraph.invoke({messages:[你好请你介绍一下你自己]})finan_response

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询