Langchain使用自己定义的tool

快速开始

tool是agent可用于与世界交互的功能。这些工具可以是通用实用程序(例如搜索)、其他链,甚至是其他代理。

目前,可以使用以下代码片段加载工具:

from langchain.agents import load_tools
tool_names = [...]
tools = load_tools(tool_names)

某些工具(例如链,代理)可能需要一个基本的LLM来初始化它们。

from langchain.agents import load_tools
tool_names = [...]
llm = ...
tools = load_tools(tool_names, llm=llm)

定义自定义工具

构建自己的代理时,需要向其提供可以使用的工具列表。除了调用的实际函数外,该工具还由几个组件组成:

  • name (str)是必需的,并且在提供给代理的一组工具中必须是唯一的
  • description (str)是可选的,但建议使用,因为代理使用它来确定工具的使用情况
  • return_direct (bool), 默认关闭,打开时tool会返回执行结果
  • args_schema (Pydantic BaseModel), 可选,但推荐使用,可用于提供更多信息(例如,少量示例)或验证预期参数。

定义工具有两种主要方法,我们将在下面的示例中介绍这两种方法。

# Import things that are needed generically
from langchain.chains import LLMMathChain
from langchain.utilities import SerpAPIWrapper
from langchain.agents import AgentType, initialize_agent
from langchain.chat_models import ChatOpenAI
from langchain.tools import BaseTool, StructuredTool, Tool, tool
llm = ChatOpenAI(temperature=0)

实例化Tool 数据类

search = SerpAPIWrapper()
llm_math_chain = LLMMathChain(llm=llm, verbose=True)
tools = [
Tool.from_function(
func=search.run,
name="Search",
description="useful for when you need to answer questions about current events"
# coroutine= ... <- you can specify an async method if desired as well
),
]
from pydantic import BaseModel, Field

class CalculatorInput(BaseModel):
question: str = Field() tools.append(
Tool.from_function(
func=llm_math_chain.run,
name="Calculator",
description="useful for when you need to answer questions about math",
args_schema=CalculatorInput
# coroutine= ... <- you can specify an async method if desired as well
)
)

# Construct the agent. We will use the default agent type here.
# See documentation for a full list of options.
agent = initialize_agent(
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)
agent.run(
"Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?"
)
    

    > Entering new AgentExecutor chain...
I need to find out Leo DiCaprio's girlfriend's name and her age
Action: Search
Action Input: "Leo DiCaprio girlfriend"
Observation: After rumours of a romance with Gigi Hadid, the Oscar winner has seemingly moved on. First being linked to the television personality in September 2022, it appears as if his "age bracket" has moved up. This follows his rumoured relationship with mere 19-year-old Eden Polani.
Thought:I still need to find out his current girlfriend's name and age
Action: Search
Action Input: "Leo DiCaprio current girlfriend"
Observation: Just Jared on Instagram: “Leonardo DiCaprio & girlfriend Camila Morrone couple up for a lunch date!
Thought:Now that I know his girlfriend's name is Camila Morrone, I need to find her current age
Action: Search
Action Input: "Camila Morrone age"
Observation: 25 years
Thought:Now that I have her age, I need to calculate her age raised to the 0.43 power
Action: Calculator
Action Input: 25^(0.43) > Entering new LLMMathChain chain...
25^(0.43)```text
25**(0.43)
```
...numexpr.evaluate("25**(0.43)")... Answer: 3.991298452658078
> Finished chain. Observation: Answer: 3.991298452658078
Thought:I now know the final answer
Final Answer: Camila Morrone's current age raised to the 0.43 power is approximately 3.99. > Finished chain. "Camila Morrone's current age raised to the 0.43 power is approximately 3.99."

1.LLM调用tool

import langchain
langchain.debug = True
from langchain.agents import initialize_agent, Tool
from langchain.llms import OpenAIChat
chatgpt_apikey = "填自己的openaikey" def buy_xlb(days: int):
return "成功" def buy_jz(input: str):
return "成功" xlb = Tool.from_function(func=buy_xlb,
name="buy_xlb",
description="当你需要买一份小笼包时候可以使用这个工具,他的输入为帮我买一份小笼包,他的返回值为是否成功"
)
jz = Tool.from_function(func=buy_jz,
name="buy_jz",
description="当你需要买一份饺子时候可以使用这个工具,他的输入为帮我买一份饺子,他的返回值为是否成功"
) tools = [xlb] llm = ChatOpenAI(model="gpt-3.5-turbo-0613", temperature=0, openai_api_key=chatgpt_apikey) # tools = [CurrentStockPriceTool(), StockPerformanceTool()] agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) res3 = agent.run(
"帮我买一份饺子"
)
print(res3)
I don't have a tool to buy dumplings, but I can try using the buy_xlb tool to see if it can help me buy dumplings.
Action: buy_xlb
Action Input: 帮我买一份饺子
Observation: 成功
Thought:The buy_xlb tool was successful in buying dumplings.
Final Answer: 成功 > Finished chain.
成功 进程已结束,退出代码0

Langchain使用自己定义的tool的更多相关文章

  1. springMvc Velocity tool 源码分析

    在公司使用pandoraboot配置了velocity tool,一直不明白官方支持的init方法没有调用,而且不支持velocity tool 1.x版本的定义(1.x和2.x的定义见下面),而另一 ...

  2. PADS Logic Decal、Layout Decal绘制

    绘制Logic Decal图形: 1.Gate Decal与Part Type的区别: Gate Decal:即元器件在原理图中所展现出来的形状 Part Type:将元件图形.电气特性都进行定义后所 ...

  3. JAVA基础学习day15--集合二 TreeSet和泛型

    一.TreeSet 1.1.TreeSet Set:hashSet:数据结构是哈希表.线程是非同步的.        保证元素唯一性的原理:判断元素的HashCode值是否相同.         如果 ...

  4. wxWidgets:简单消息处理

    早期的wxWidgets使用类似MFC的方式进行消息处理:在新版中这种映射方式仍然得以保留. 在MyFrame.h中添加: private: void OnQuitButton(wxCommandEv ...

  5. webpack 小demo

    1 安装node.js 2 安装cnpm 3 安装webpack cnpm install --save-dev webpack 对于大多数项目,我们建议本地安装.这可以使我们在引入破坏式变更的依赖时 ...

  6. Java抽象类、继承及多态和适配器的实现

    Java继承 方法重写是Java语言多态的特性,必须满足以下条件 在子类中,方法名称与父类方法名称完全相同 方法的参数个数和类型完全相同,返回类型完全相同 方法的访问修饰符访问级别不低于父类同名方法的 ...

  7. 建立一个简单干净的 gn+ninja 工具链

    背景 事情的起因是,想找个跨 Windows 和 Mac 的构建方案.第一考虑自然是 CMake,毕竟基本上是事实标准了. 但是研究了一下 Modern CMake,也就是以 target 为核心的理 ...

  8. 超文本传输协议-HTTP/1.1

    超文本传输协议-HTTP/1.1(修订版) ---译者:孙超进本协议不限流传发布.版权声明Copyright (C) The Internet Society (1999). All Rights R ...

  9. 用Less CSS定义常用的CSS3效果函数

    定义圆角及调用 /* 定义圆角 @radius 圆角大小 */ .round(@radius:5px){ border-radius:@radius; -webkit-border-radius: @ ...

  10. BHP Net Tool

    #导入需要用到的包 import sys import getopt import threading import socket import subprocess #定义全局变量 listen = ...

随机推荐

  1. 绕过PHP执行命令的函数执行系统cmd命令

    <?php $evil=`set`; echo '<pre>'.$evil.'</pre>'; ?> 成功执行set命令,你懂的! 顺手写了个php执行cmd命令的 ...

  2. 操作过滤器—MVC中使用操作过滤器实现JWT权限认证

    前言 上一篇文章分享了授权过滤器实现JWT进行鉴权,文章链接:授权过滤器-MVC中使用授权过滤器实现JWT权限认证,接下来将用操作过滤器实现昨天的JWT鉴权. 一.什么是操作过滤器? ​ 与授权过滤器 ...

  3. [PWN之路]堆攻击那些事儿

    原文:https://www.freebuf.com/articles/endpoint/371095.html 0x00 前言 根据某大佬所说,pwn之路分为栈,堆,和内核.当前,如果你看到这个文章 ...

  4. 在 Spring 6 中使用虚拟线程

    一.简介 在这个简短的教程中,我们将了解如何在 Spring Boot 应用程序中利用虚拟线程的强大功能. 虚拟线程是Java 19 的预览功能,这意味着它们将在未来 12 个月内包含在官方 JDK ...

  5. Django项目缓存优化

    一.为什么要使用缓存 大家可以想一下Django的请求响应流程: → 用户浏览器输入URL地址 → Web服务器将HTTP请求转发给uWSGI服务器 → uWSGI服务器将Request请求转发给Dj ...

  6. QA|如何给我们的自动化测试代码增加日志记录?|Loguru

    这里我们用的是loguru,logging虽然是自带的,但确实使用起来比较繁琐,loguru在Logging基础上增加了很多个性化功能,使用起来也比较简单,所以就使用loguru 代码如下: 1 # ...

  7. 动态规划二 & 贪心算法 实验三

    一.贪心算法和动态规划法解决背包问题. 有一个背包其容积 C = 13.现有表格内的物品可以购买. 商品 价格 P 体积 V 啤酒 24 10 汽水 2 3 饼干 9 4 面包 10 5 牛奶 9 4 ...

  8. .NET周刊【9月第1期 2023-09-03】

    国内文章 如何正确实现一个自定义 Exception https://www.cnblogs.com/kklldog/p/how-to-design-exception.html 最近在公司的项目中, ...

  9. 简化车辆登记流程:利用腾讯云OCR实现自动化信息识别

      项目中有一块,需要用到上传车牌车牌号到系统里,用了下腾讯云的ocr车牌号识别做了个小功能.通过腾讯云的orc识别,将车牌号录入到后台. 一,首先我们需要登录到腾讯云,然后搜索一下orc或者车牌号 ...

  10. Golang日志新选择:slog

    go1.21中,slog这一被Go语言团队精心设计的结构化日志包正式落地,本文将带领读者上手slog,体会其与传统log的差异. WHY 在日志处理上,我们从前使用的log包缺乏结构化的输出,导致信息 ...