2026/6/12 12:24:29
网站建设
项目流程
东莞网站推广春,dw企业网站开发教程,个人怎么创建微信公众号,芜湖网站建设怎么做文章目录10.1 tool 装饰器10.2 StructuredTool10.3 处理工具错误10.4 调用内置工具包和拓展工具10.5 自定义默认工具10.6 如何使用内置工具包方案#xff1a;
普通函数 Tool对象#xff08;最简单#xff09;from langchain.tools import Tool# 1. 定义普通函数
def weathe…文章目录10.1 tool 装饰器10.2 StructuredTool10.3 处理工具错误10.4 调用内置工具包和拓展工具10.5 自定义默认工具10.6 如何使用内置工具包方案普通函数 Tool对象最简单fromlangchain.toolsimportTool# 1. 定义普通函数defweather_query(city:str)-str:查询天气 - 普通函数weather_data{北京:{temperature:25°C,weather:晴},上海:{temperature:28°C,weather:多云},}ifcityinweather_data:dataweather_data[city]returnf{city}:{data[temperature]},{data[weather]}returnf未找到{city}天气defattraction_search(query:str)-str:搜索景点 - 普通函数returnf找到了关于{query}的5个景点...# 2. 创建Tool对象weather_toolTool(nameweather_query,description查询城市天气,funcweather_query# 直接传入函数)attraction_toolTool(nameattraction_search,description搜索旅游景点,funcattraction_search)# 3. 使用工具列表tools[weather_tool,attraction_tool]LangChain 提供了三种创建工具的方式使用 tool装饰器 – 定义自定义工具的最简单方式。使用 StructuredTool.from_function 类方法 – 这类似于tool装饰器但允许更多配置和同步和异步实现的规范。通过子类化BaseTool – 这是最灵活的方法它提供了最大程度的控制但需要更多的工作量和代码。tool 或 StructuredTool.from_function 类方法对于大多数用例应该足够了。 提示 如果工具具有精心选择的名称、描述和 JSON 模式模型的性能会更好。10.1 tool 装饰器这个tool装饰器是定义自定义工具的最简单方式。该装饰器默认使用函数名称作为工具名称但可以通过传递字符串作为第一个参数来覆盖。此外装饰器将使用函数的文档字符串作为工具的描述 - 因此必须提供文档字符串。同步如下#示例tools_decorator.pyfromlangchain_core.toolsimporttooltooldefmultiply(a:int,b:int)-int:Multiply two numbers.returna*b# 检查与该工具关联的一些属性print(multiply.name)print(multiply.description)print(multiply.args)#输出结果multiply multiply(a:int,b:int)-int-Multiply two numbers.{a:{title:A,type:integer},b:{title:B,type:integer}}创建一个异步实现如下所示#示例tools_async.pyfromlangchain_core.toolsimporttooltoolasyncdefamultiply(a:int,b:int)-int:Multiply two numbers.returna*b您还可以通过将它们传递给工具装饰器来自定义工具名称和 JSON 参数frompydanticimportBaseModel,FieldclassCalculatorInput(BaseModel):a:intField(descriptionfirst number)b:intField(descriptionsecond number)tool(multiplication-tool,args_schemaCalculatorInput,return_directTrue)defmultiply(a:int,b:int)-int:Multiply two numbers.returna*b# 检查与该工具关联的一些属性print(multiply.name)print(multiply.description)print(multiply.args)print(multiply.return_direct)#结果multiplication-tool multiplication-tool(a:int,b:int)-int-Multiply two numbers.{a:{title:A,description:first number,type:integer},b:{title:B,description:second number,type:integer}}True10.2 StructuredToolStructuredTool.from_function类方法提供了比tool装饰器更多的可配置性而无需太多额外的代码。fromlangchain_core.toolsimportStructuredToolimportasynciodefmultiply(a:int,b:int)-int:Multiply two numbers.returna*basyncdefamultiply(a:int,b:int)-int:Multiply two numbers.returna*basyncdefmain():calculatorStructuredTool.from_function(funcmultiply,coroutineamultiply)print(calculator.invoke({a:2,b:3}))print(awaitcalculator.ainvoke({a:2,b:5}))# 运行异步主函数asyncio.run(main())#结果610可以配置自定义参数fromlangchain_core.toolsimportStructuredToolfrompydanticimportBaseModel,FieldimportasyncioclassCalculatorInput(BaseModel):a:intField(descriptionfirst number)b:intField(descriptionsecond number)defmultiply(a:int,b:int)-int:Multiply two numbers.returna*b# 创建一个异步包装器函数asyncdefasync_addition(a:int,b:int)-int:Multiply two numbers.returnabasyncdefmain():calculatorStructuredTool.from_function(funcmultiply,nameCalculator,descriptionmultiply numbers,args_schemaCalculatorInput,return_directTrue,#coroutine async_addition# coroutine ... - 如果需要也可以指定异步方法)print(calculator.invoke({a:2,b:3}))#print(await calculator.ainvoke({a: 2, b: 5}))print(calculator.name)print(calculator.description)print(calculator.args)# 运行异步主函数asyncio.run(main())10.3 处理工具错误如果您正在使用带有代理的工具您可能需要一个错误处理策略以便代理可以从错误中恢复并继续执行。 一个简单的策略是在工具内部抛出 ToolException并使用 handle_tool_error 指定一个错误处理程序。 当指定了错误处理程序时异常将被捕获错误处理程序将决定从工具返回哪个输出。 您可以将 handle_tool_error 设置为 True、字符串值或函数。如果是函数该函数应该以 ToolException 作为参数并返回一个值。 请注意仅仅抛出 ToolException 是不会生效的。您需要首先设置工具的 handle_tool_error因为其默认值是 False。fromlangchain_core.toolsimportToolExceptiondefget_weather(city:str)-int:获取给定城市的天气。raiseToolException(f错误没有名为{city}的城市。)# 示例tools_exception.pyget_weather_toolStructuredTool.from_function(funcget_weather,handle_tool_errorTrue,)get_weather_tool.invoke({city:foobar})#结果错误没有名为foobar的城市。可以将handle_tool_error设置为一个始终返回的字符串。# 示例tools_exception_handle.pyget_weather_toolStructuredTool.from_function(funcget_weather,handle_tool_error没找到这个城市,)get_weather_tool.invoke({city:foobar})#结果没找到这个城市使用函数处理错误# 示例tools_exception_handle_error.pydef_handle_error(error:ToolException)-str:returnf工具执行期间发生以下错误{error.args[0]}get_weather_toolStructuredTool.from_function(funcget_weather,handle_tool_error_handle_error,)get_weather_tool.invoke({city:foobar})#结果工具执行期间发生以下错误错误没有名为foobar的城市。10.4 调用内置工具包和拓展工具使用维基百科工具包# 示例tools_wikipedia.pyfromlangchain_community.toolsimportWikipediaQueryRunfromlangchain_community.utilitiesimportWikipediaAPIWrapper api_wrapperWikipediaAPIWrapper(top_k_results1,doc_content_chars_max100)toolWikipediaQueryRun(api_wrapperapi_wrapper)print(tool.invoke({query:langchain}))#结果Page:LangChain Summary:LangChainisa framework designed to simplify the creation of applicationsprint(fName:{tool.name})print(fDescription:{tool.description})print(fargs schema:{tool.args})print(freturns directly?:{tool.return_direct})#结果Name:wikipedia Description:A wrapper around Wikipedia.Usefulforwhen you need to answer general questions about people,places,companies,facts,historical events,orother subjects.Input should be a search query.args schema:{query:{title:Query,description:query to look up on wikipedia,type:string}}returns directly?:False10.5 自定义默认工具我们还可以修改内置工具的名称、描述和参数的 JSON 模式。在定义参数的 JSON 模式时重要的是输入保持与函数相同因此您不应更改它。但您可以轻松为每个输入定义自定义描述。#示例tools_custom.pyfromlangchain_community.toolsimportWikipediaQueryRunfromlangchain_community.utilitiesimportWikipediaAPIWrapperfrompydanticimportBaseModel,FieldclassWikiInputs(BaseModel):维基百科工具的输入。query:strField(descriptionquery to look up in Wikipedia, should be 3 or less words)toolWikipediaQueryRun(namewiki-tool,descriptionlook up things in wikipedia,args_schemaWikiInputs,api_wrapperapi_wrapper,return_directTrue,)print(tool.run(langchain))#结果Page:LangChain Summary:LangChainisa framework designed to simplify the creation of applicationsprint(fName:{tool.name})print(fDescription:{tool.description})print(fargs schema:{tool.args})print(freturns directly?:{tool.return_direct})#结果Name:wiki-tool Description:look up thingsinwikipedia args schema:{query:{title:Query,description:query to look up in Wikipedia, should be 3 or less words,type:string}}returns directly?:True10.6 如何使用内置工具包工具包是一组旨在一起使用以执行特定任务的工具。它们具有便捷的加载方法。要获取可用的现成工具包完整列表请访问集成。所有工具包都公开了一个get_tools方法该方法返回一个工具列表。# 初始化一个工具包toolkitExampleTookit(...)# 获取工具列表toolstoolkit.get_tools()使用SQLDatabase toolkit 读取 langchain.db 数据库表结构fromlangchain_community.agent_toolkits.sql.toolkitimportSQLDatabaseToolkitfromlangchain_community.utilitiesimportSQLDatabasefromlangchain_openaiimportChatOpenAIfromlangchain_community.agent_toolkits.sql.baseimportcreate_sql_agentfromlangchain.agents.agent_typesimportAgentType dbSQLDatabase.from_uri(sqlite:///langchain.db)toolkitSQLDatabaseToolkit(dbdb,llmChatOpenAI(temperature0))print(toolkit.get_tools())#结果[QuerySQLDataBaseTool(descriptionInput to this tool is a detailed and correct SQL query, output is a result from the database. If the query is not correct, an error message will be returned. If an error is returned, rewrite the query, check the query, and try again. If you encounter an issue with Unknown column xxxx in field list, use sql_db_schema to query the correct table fields.,dblangchain_community.utilities.sql_database.SQLDatabaseobjectat0x000001D15C9749B0),InfoSQLDatabaseTool(descriptionInput to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables. Be sure that the tables actually exist by calling sql_db_list_tables first! Example Input: table1, table2, table3,dblangchain_community.utilities.sql_database.SQLDatabaseobjectat0x000001D15C9749B0),ListSQLDatabaseTool(dblangchain_community.utilities.sql_database.SQLDatabaseobjectat0x000001D15C9749B0),QuerySQLCheckerTool(descriptionUse this tool to double check if your query is correct before executing it. Always use this tool before executing a query with sql_db_query!,dblangchain_community.utilities.sql_database.SQLDatabaseobjectat0x000001D15C9749B0,llmChatOpenAI(clientopenai.resources.chat.completions.Completionsobjectat0x000001D17B4453D0,async_clientopenai.resources.chat.completions.AsyncCompletionsobjectat0x000001D17B446D80,temperature0.0,openai_api_keySecretStr(**********),openai_proxy),llm_chainLLMChain(promptPromptTemplate(input_variables[dialect,query],template\n{query}\nDouble check the {dialect} query above for common mistakes, including:\n- Using NOT IN with NULL values\n- Using UNION when UNION ALL should have been used\n- Using BETWEEN for exclusive ranges\n- Data type mismatch in predicates\n- Properly quoting identifiers\n- Using the correct number of arguments for functions\n- Casting to the correct data type\n- Using the proper columns for joins\n\nIf there are any of the above mistakes, rewrite the query. If there are no mistakes, just reproduce the original query.\n\nOutput the final SQL query only.\n\nSQL Query: ),llmChatOpenAI(clientopenai.resources.chat.completions.Completionsobjectat0x000001D17B4453D0,async_clientopenai.resources.chat.completions.AsyncCompletionsobjectat0x000001D17B446D80,temperature0.0,openai_api_keySecretStr(**********),openai_proxy)))]agent_executorcreate_sql_agent(llmChatOpenAI(temperature0,modelgpt-4),toolkittoolkit,verboseTrue,agent_typeAgentType.OPENAI_FUNCTIONS)# %%agent_executor.invoke(Describe the full_llm_cache table)#结果Entering new SQL Agent Executor chain...Invoking:sql_db_schemawith{table_names:full_llm_cache} CREATE TABLE full_llm_cache(prompt VARCHAR NOT NULL,llm VARCHAR NOT NULL,idx INTEGER NOT NULL,response VARCHAR,PRIMARY KEY(prompt,llm,idx))/*3rowsfromfull_llm_cache table:prompt llm idx response[{lc:1,type:constructor,id:[langchain,schema,messages,HumanMessage],kwargs {id: [langchain, chat_models, openai, ChatOpenAI], kwargs: {max_retries: 2, model_nam0{lc:1,type:constructor,id:[langchain,schema,output,ChatGeneration],kwargs*/The full_llm_cache table has the following structure:-prompt:A VARCHAR field thatispart of the primary key.It cannot be NULL.-llm:A VARCHAR field thatisalso part of the primary key.It cannot be NULL.-idx:An INTEGER field thatispart of the primary keyaswell.It cannot be NULL.-response:A VARCHAR field that can contain NULL values.Here are some sample rowsfromthe full_llm_cache table:|prompt|llm|idx|response||--------|-----|-----|----------||[{lc:1,type:constructor,id:[langchain,schema,messages,HumanMessage],kwargs | {id: [langchain, chat_models, openai, ChatOpenAI], kwargs: {max_retries: 2, model_nam|0|{lc:1,type:constructor,id:[langchain,schema,output,ChatGeneration],kwargs|Finished chain.