工具绑定与调用

基本步骤:

在Agent当中,当我们需要调用自己写好的工具时,我们需要分三步来构建Message:

  1. HumanMessage(提出问题)
  2. AIMessage(由ai来帮我们选择该调用哪个工具,以及每个工具传什么参数)
  3. ToolMessage (工具调用的结果)

例:

绑定工具:

python 复制代码
@tool
def add(
        a: Annotated[int, Field(description="first number")],
        b: Annotated[int, Field(description="second number")]
)->tuple[str, list[int]]:
    """Add two numbers together."""
    nums = [a, b]
    result = f'{nums}等于{a + b}'
    return result, nums

@tool
def multiply(
        a: Annotated[int, Field(description="first number")],
        b: Annotated[int, Field(description="second number")]
)->tuple[str, list[int]]:
    """Multiply two numbers together."""
    nums = [a, b]
    result = f'{nums}等于{a * b}'
    return result, nums

from langchain_openai import ChatOpenAI
chat = ChatOpenAI(model="deepseek-chat",
                  api_key=os.getenv("DEEPSEEK_API_KEY"),
                  base_url="https://api.deepseek.com")

tools = [add, multiply]
chat_with_tools = chat.bind_tools(tools)

HumanMessage:

python 复制代码
messages = [
    HumanMessage(content="56加5223,6乘以6")
]

AIMessage:

python 复制代码
ai_message=chat_with_tools.invoke(messages)

messages.append(ai_message)

AIMessage是工具调用过程中重要的一环,该环节我们知道调用哪个工具,以及参数,在该例子当中,返回的ai_message中包含的tool_calls是最为关键的,内容如下:

tool_calls=[

{

'name': 'add',

'args': {'a': 56, 'b': 5223},

'id': 'call_00_...'

},

{

'name': 'multiply',

'args': {'a': 6, 'b': 6},

'id': 'call_01_...'

}

]

通过以上参数,让我们下一步能够直接去调用tool并将tool_calls中的内容作为参数传递调用。

ToolMessage:

python 复制代码
for tool_call in ai_message.tool_calls:
    selected_tool = {"add":add, "multiply":multiply}[tool_call["name"].lower()]
    tool_message = selected_tool.invoke(tool_call)
    messages.append(tool_message)
相关推荐
yi0117 分钟前
LeetCode 3. 无重复字符的最长子串|不定长滑动窗口:什么时候更新最大值?
笔记·python·算法·leetcode·双指针·滑动窗口
2601_9628857220 分钟前
如何用 Python 计算索提诺比率和卡玛比率?
开发语言·python
小小张说故事24 分钟前
Python 的描述符到底是个啥?property 和 classmethod 底层都靠它,3 个例子讲透
python
kimnoic34 分钟前
Python操作MySQL数据库的两种方式实例分析【pymysql和pandas】
开发语言·python
外收内放34 分钟前
Python基础语法练习题(64)
python·学习
fanjiu202039 分钟前
flask接收消息
python·flask
外收内放40 分钟前
Python基础语法练习题(65)
开发语言·python
Summer-Bright44 分钟前
深度 | 记忆的锁定账:模型可以随便换,记忆却搬不走
人工智能·agent·记忆
SharpCJ1 小时前
Koog(2) —— Koog Agent 的编程模型
llm·agent
iReachers1 小时前
Termux:把安卓手机变成随身的命令行工具箱
python·安卓·termux·命令行·实用工具