LangChain-26 Custom Agent 自定义一个Agent并通过@tool绑定对应的工具 同时让大模型自己调用编写的@tools函数

请添加图片描述

安装依赖

pip install -qU langchain-core langchain-openai

编写代码

定义一个工具

# 定义工具
@tool
def get_word_length(word: str) -> int:
    """Returns the length of a word."""
    return len(word)

创建一个Agent

# 创建Agent
agent = (
    {
        "input": lambda x: x["input"],
        "agent_scratchpad": lambda x: format_to_openai_tool_messages(
            x["intermediate_steps"]
        ),
    }
    | prompt
    | llm_with_tools
    | OpenAIToolsAgentOutputParser()
)

推荐使用GPT-4GPT3.5任务表现上并不是很好。
完整的代码如下

from langchain_openai import ChatOpenAI
from langchain.agents import tool
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.agents.format_scratchpad.openai_tools import (
    format_to_openai_tool_messages,
)
from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParser
from langchain.agents import AgentExecutor


llm = ChatOpenAI(model="gpt-4-turbo-preview", temperature=0)
# llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)

# 定义工具
@tool
def get_word_length(word: str) -> int:
    """Returns the length of a word."""
    return len(word)


# print(get_word_length.invoke("abc"))
# 定义一个工具集
tools = [get_word_length]
# 提示词
prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "You are very powerful assistant, but don't know current events",
        ),
        (
            "user",
            "{input}"
        ),
        MessagesPlaceholder(variable_name="agent_scratchpad"),
    ]
)

# 绑定工具集
llm_with_tools = llm.bind_tools(tools)

# 创建Agent
agent = (
    {
        "input": lambda x: x["input"],
        "agent_scratchpad": lambda x: format_to_openai_tool_messages(
            x["intermediate_steps"]
        ),
    }
    | prompt
    | llm_with_tools
    | OpenAIToolsAgentOutputParser()
)
# 执行器
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor_stream = list(agent_executor.stream({"input": "How many letters in the word eudca"}))
print(f"agent_executor_stream: {agent_executor_stream}")

执行结果

➜ python3 test27.py


> Entering new AgentExecutor chain...

Invoking: `get_word_length` with `{'word': 'eudca'}`


5The word "eudca" has 5 letters.

> Finished chain.
agent_executor_stream: [{'actions': [OpenAIToolAgentAction(tool='get_word_length', tool_input={'word': 'eudca'}, log="\nInvoking: `get_word_length` with `{'word': 'eudca'}`\n\n\n", message_log=[AIMessageChunk(content='', additional_kwargs={'tool_calls': [{'index': 0, 'id': 'call_Oo2mhYvyOHkw4YvzaL1Gz0tb', 'function': {'arguments': '{"word":"eudca"}', 'name': 'get_word_length'}, 'type': 'function'}]}, response_metadata={'finish_reason': 'tool_calls'})], tool_call_id='call_Oo2mhYvyOHkw4YvzaL1Gz0tb')], 'messages': [AIMessageChunk(content='', additional_kwargs={'tool_calls': [{'index': 0, 'id': 'call_Oo2mhYvyOHkw4YvzaL1Gz0tb', 'function': {'arguments': '{"word":"eudca"}', 'name': 'get_word_length'}, 'type': 'function'}]}, response_metadata={'finish_reason': 'tool_calls'})]}, {'steps': [AgentStep(action=OpenAIToolAgentAction(tool='get_word_length', tool_input={'word': 'eudca'}, log="\nInvoking: `get_word_length` with `{'word': 'eudca'}`\n\n\n", message_log=[AIMessageChunk(content='', additional_kwargs={'tool_calls': [{'index': 0, 'id': 'call_Oo2mhYvyOHkw4YvzaL1Gz0tb', 'function': {'arguments': '{"word":"eudca"}', 'name': 'get_word_length'}, 'type': 'function'}]}, response_metadata={'finish_reason': 'tool_calls'})], tool_call_id='call_Oo2mhYvyOHkw4YvzaL1Gz0tb'), observation=5)], 'messages': [FunctionMessage(content='5', name='get_word_length')]}, {'output': 'The word "eudca" has 5 letters.', 'messages': [AIMessage(content='The word "eudca" has 5 letters.')]}]

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

武子康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值