LangChain-Agent自定义Tools类 ——输入参数篇(二)

文章展示了如何创建并使用两个自定义工具类,Calculate_Life和Calculate_ObjectVolumn,分别处理单个和多个输入参数。这两个工具在计算生命幸福度和物体体积时发挥作用。此外,还引入了ChatOpenAI对话模型以及对话内存管理机制,用于构建智能对话系统。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给自定义函数传入输入参数,分别有single-input 参数函数案例和multi-input 参数函数案例: 

from langchain.agents import Tool
from langchain.tools import BaseTool
from math import pi
from typing import Union
from math import pi
from typing import Union
from langchain.agents import initialize_agent
from langchain.agents import AgentType
import os
from langchain.chat_models import ChatOpenAI
from langchain.chains.conversation.memory import ConversationBufferWindowMemory
from typing import Optional


class Calculate_Life(BaseTool):#这里的RUL value 我瞎编的
      name = "Calculate Life Tool"
      description = "use this tool when you need to calculate the happiness of life using the RUL value"

      def _run(self, RUL: Union[int, float]):
        return "The happiness of life is {RUL*2}"

      def _arun(self, RUL: int):
        raise NotImplementedError("This tool does not support async")
class Calculate_volumn(BaseTool):#这里的RUL value 我瞎编的
      name = "Calculate Object Volumn"
      description = (
      "use this tool when you need to calculate the the volumn of object,inputs are multi parameters,need multi input variables,like the length,width,and height."
      "To use the tool, you must provide at least three of the following parameters "
      "['length', 'width', 'height']."
      )

      def _run(
          self,
          length: Optional[Union[int, float]] = None,
          width: Optional[Union[int, float]] = None,
          height: Optional[Union[int, float]] = None
      ):
          # check for the values we have been given
          if length and width and height:
              return length*width*height
          else:
              return "Could not calculate the size of universe. Need two or more of `length`, `width`,`height`."
      def _arun(self, query: str):
          raise NotImplementedError("This tool does not support async")
os.environ["OPENAI_API_KEY"] = "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"
llm = ChatOpenAI(
    openai_api_key=os.environ["OPENAI_API_KEY"] ,
    temperature=0,
    model_name='gpt-3.5-turbo'
)
# initialize conversational memory
conversational_memory = ConversationBufferWindowMemory(
        memory_key='chat_history',
        k=5,
        return_messages=True
)

tools = [Calculate_volumn()]
 
# sys_msg = """Assistant is a large language model trained by OpenAI.

# Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.

# Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.

# Unfortunately, Assistant is terrible at maths. When provided with math questions, no matter how simple, assistant always refers to it's trusty tools and absolutely does NOT try to answer math questions by itself

# Overall, Assistant is a powerful system that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.
# """
# sys_msg = "Do not try to figure math question by yourself, you might be blindly confident about your mathematic capacity,please always refers to it's trusty tools and absolutely does NOT try to answer math questions by itself"



# agent = initialize_agent(
#     agent='chat-conversational-react-description',
#     # agent='zero-shot-react-description',
#     tools=tools,
#     llm=llm,
#     verbose=True,
#     max_iterations=3,
#     early_stopping_method='generate',
#     memory=conversational_memory
# )


new_prompt = agent.agent.create_prompt(
    system_message=sys_msg,
    tools=tools
)

agent.agent.llm_chain.prompt = new_prompt
# update the agent tools
agent.tools = tools

# agent("How much is the happiness of life when RUL value is equal to 2")#单个参数提问
agent("Given [length=10000,width=2,height=3],what's the size of this box?")#多个参数提问

运行结果 

后期关注结构化输出,方便作为借口提供给其他下游应用 

相关友情链接:

为 LLM 代理构建自定义工具 |松果 (pinecone.io)

### 使用LangChain创建自定义工具Agent #### 准备工作梳理 为了构建能够执行特定任务(如SQL查询)的自定义Agent,需先安装并导入必要的Python库。这通常涉及`langchain`及其依赖项以及其他可能用于数据处理或API调用的相关模块[^1]。 ```bash pip install langchain sqlalchemy pandas ``` 接着,在编写具体逻辑前,应明确定义目标——即希望此Agent完成的任务是什么?对于本案例而言,则是要实现一个能与SQL数据库对话的功能性组件。 #### 定义自定义Tool 基于上述需求分析,下面展示了一个简单的名为`SqlExecutor`的自定义Tool的设计: ```python from typing import Dict, Any import pandas as pd from sqlalchemy import create_engine class SqlExecutor: """A tool that executes SQL queries against a database.""" def __init__(self, connection_string: str): self.engine = create_engine(connection_string) def run(self, query: str) -> pd.DataFrame: with self.engine.connect() as conn: result = conn.execute(query) columns = result.keys() rows = result.fetchall() return pd.DataFrame(rows, columns=columns) ``` 这里通过继承实现了基本接口方法`run()`,它接受一条SQL语句作为参数,并返回由Pandas DataFrame表示的结果集。此外还初始化了连接到指定数据库所需的引擎对象。 #### 实例化Tools并将其实例加入列表 一旦完成了对各个独立功能单元(即不同型的Tool)的设计之后,就可以按照如下方式将其实例化并收集起来形成集合形式供后续操作使用[^2]: ```python sql_executor = SqlExecutor('sqlite:///example.db') tools = [sql_executor] ``` 此处假设已经存在一个SQLite数据库文件位于当前目录下命名为`example.db`;当然也可以替换为其他支持的数据源路径表达式以适应不同的应用场景。 #### 配置Action Schema 为了让代理更好地理解如何利用这些工具所提供的能力去解决问题,可以通过设置action schema的方式让其知道每个动作应该接收什么样的输入格式以及预期产生的输出结构。例如针对前面提到过的`SqlExecutor.run()`函数来说,就应当告知系统该方法期望获取的是字符串型的SQL命令文本[^3]。 ```json { "type": "object", "properties": { "query": {"type": "string"} }, "required": ["query"] } ``` 最后一步就是将以上准备好的所有要素组合在一起构成完整的Agent解决方案啦!
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值