当前位置:   article > 正文

大模型从入门到应用——LangChain:代理(Agents)-[工具(Tools):多输入工具和工具输入模式]_langchain agent多工具

langchain agent多工具

分类目录:《大模型从入门到应用》总目录

LangChain系列文章:

----### 多输入工具
本节演示如何在Agent中使用需要多个输入的工具,推荐的方法是使用StructuredTool类。

import os
os.environ["LANGCHAIN_TRACING"] = "true"
from langchain import OpenAI
from langchain.agents import initialize_agent, AgentType

llm = OpenAI(temperature=0)
from langchain.tools import StructuredTool

def multiplier(a: float, b: float) -> float:
    """Multiply the provided floats."""
    return a * b

tool = StructuredTool.from_function(multiplier)
# Structured tools are compatible with the STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION agent type. 
agent_executor = initialize_agent([tool], llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent_executor.run("What is 3 times 4")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

日志输出

Entering new AgentExecutor chain...

Thought: I need to multiply 3 and 4
Action:
  • 1
  • 2
  • 3
  • 4

{
“action”: “multiplier”,
“action_input”: {“a”: 3, “b”: 4}
}


Observation: 12
Thought: I know what to respond
Action:
  • 1
  • 2
  • 3
  • 4

{
“action”: “Final Answer”,
“action_input”: “3 times 4 is 12”
}


Finished chain.
  • 1
  • 2

输出:

'3 times 4 is 12'
  • 1
使用字符串格式的多输入工具

与结构化工具相比,另一种方法是使用常规的Tool类,并接受单个字符串作为输入。然后,工具必须处理解析逻辑,从文本中提取相关值,这将使工具表示与Agent提示紧密耦合。如果底层语言模型无法可靠地生成结构化模式,这仍然很有用。

让我们以乘法函数为例。为了使用它,我们将告诉Agent生成以逗号分隔的长度为两个的Action Input。然后,我们编写一个简单的包装器,将字符串分割成两部分(以逗号为界),并将两个解析后的值作为整数传递给乘法函数。

from langchain.llms import OpenAI
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
  • 1
  • 2
  • 3

以下是乘法函数及其字符串解析器的示例:

def multiplier(a, b):
    return a * b

def parsing_multiplier(string):
    a, b = string.split(",")
    return multiplier(int(a), int(b))
llm = OpenAI(temperature=0)
tools = [
    Tool(
        name = "Multiplier",
        func=parsing_multiplier,
        description="useful for when you need to multiply two numbers together. The input to this tool should be a comma separated list of numbers of length two, representing the two numbers you want to multiply together. For example, `1,2` would be the input if you wanted to multiply 1 by 2."
    )
]
mrkl = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
mrkl.run("What is 3 times 4")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

日志输出:

Entering new AgentExecutor chain...
 I need to multiply two numbers
Action: Multiplier
Action Input: 3,4
Observation: 12
Thought: I now know the final answer
Final Answer: 3 times 4 is 12

Finished chain.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

输出:

'3 times 4 is 12'
  • 1

工具输入模式

默认情况下,工具通过检查函数签名来推断参数模式。对于更严格的要求,可以指定自定义输入模式,以及自定义的验证逻辑。

from typing import Any, Dict

from langchain.agents import AgentType, initialize_agent
from langchain.llms import OpenAI
from langchain.tools.requests.tool import RequestsGetTool, TextRequestsWrapper
from pydantic import BaseModel, Field, root_validator

llm = OpenAI(temperature=0)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

我们还需安装tldextract

!pip install tldextract > /dev/null
notice A new release of pip is available: 23.0.1 -> 23.1
notice To update, run: pip install --upgrade pip
  • 1
  • 2
  • 3

输入:

import tldextract

_APPROVED_DOMAINS = {
    "langchain",
    "wikipedia",
}

class ToolInputSchema(BaseModel):

    url: str = Field(...)
    
    @root_validator
    def validate_query(cls, values: Dict[str, Any]) -> Dict:
        url = values["url"]
        domain = tldextract.extract(url).domain
        if domain not in _APPROVED_DOMAINS:
            raise ValueError(f"Domain {domain} is not on the approved list:"
                             f" {sorted(_APPROVED_DOMAINS)}")
        return values
    
tool = RequestsGetTool(args_schema=ToolInputSchema, requests_wrapper=TextRequestsWrapper())
agent = initialize_agent([tool], llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=False)
# This will succeed, since there aren't any arguments that will be triggered during validation
answer = agent.run("What's the main title on langchain.com?")
print(answer)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

输出:

The main title of langchain.com is "LANG CHAIN 
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/853673
推荐阅读
相关标签