文章目录Tools工具调用简介自定义Tool案例Tools工具调用简介背景虽然大模型具有强大的语言理解和生成能力但它本质上是静态的、不可交互的不具备访问数据库、调用API的能力不能执行代码和文件操作、无法实时访问互联网获取动态数据等。定义通过Tool工具机制可以让大模型具备“调用外部函数的能力”使其能够与外部系统、API或自定义函数交互从而完成仅靠文本生成无法实现的任务重要提示ToolCalling也称为FunctionCalling它允许大模型与一组API或工具进行交互将LLM的智能与外部工具或API无缝连接从而增强LLM的能力。LLM本身不执行函数它只是指示应该调用哪个函数以及如何调用。作用访问实时数据执行某种工具类/辅助类操作一句话Tools是LLM的外部Utils工具类自定义Tooltool装饰器属性类型描述namestr必选在提供给LLM或Agent的工具集中必须是唯一的。descriptionstr可选但建议描述工具的功能。LLM或Agent将使用此描述作为上下文使用它确定工具的使用args_schemaPydanticBaseModel可选但建议可用于提供更多信息例如few-shot示例或验证预期参数。return_directboolean仅对Agent相关。当为True时在调用给定工具后Agent将停止并将结果直接返回给用户。案例importrequestsfromlangchain.chat_modelsimportinit_chat_modelfromlangchain_core.output_parsersimportStrOutputParserfromlangchain_core.promptsimportChatPromptTemplatefromlangchain_core.promptsimportMessagesPlaceholderfromconfigimportOPENAI_API_KEY# 1.定义tool获取所有用户defget_users():try:resrequests.get(http://127.0.0.1:8081/api/users)# 如果响应状态码不是200就会抛出异常res.raise_for_status()# 取出json指定字段的数据returnf所有用户{res.json()[data][users]}exceptrequests.RequestExceptionase:returnf请求失败{e}# 2.llm导入工具promptChatPromptTemplate.from_messages([(system,你是一个 helpful的助手。),MessagesPlaceholder(variable_namehistory),(human,请回答{question}),])llminit_chat_model(modeldeepseek-chat,model_providerdeepseek,api_keyOPENAI_API_KEY,base_urlhttps://api.deepseek.com)llm.bind_tools([get_users])# 3.chainparserStrOutputParser()chainprompt|llm|parserprint(chain.invoke({question:获取所有用户}))