工具绑定与调用

基本步骤:

在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)
相关推荐
数据杂坛5 分钟前
【Python程序开发系列】实例方法、类方法(@classmethod)、静态方法(@staticmethod)有什么区别
python·课程设计·python语法
正经教主15 分钟前
【FDE系列】阶段2:Day 31:SQL 基础 — 增删改查一把梭
人工智能·python·fde
leihefeng16 分钟前
PX04-用 Python 读 Excel 画折线图,还能直接插回 Excel 文件
python·excel
Mr.朱鹏21 分钟前
Docker三剑客实战指南:Docker、Dockerfile 和 Docker Compose
python·docker·devops·dockerfile
05664623 分钟前
用大模型构建答疑机器人:从 API 调用到上下文工程
python·学习·agent
haluhalu.33 分钟前
初识 Protobuf:微服务跨语言通信的一份契约
java·c语言·开发语言·c++·python
Liaiyang6634 分钟前
# 自研 AST 容错初筛工具:横向评测 Django、PyTorch、TensorFlow 三大开源 Python 框架异常收容风险
python·测试工具·自动化·开源软件·代码规范·devops·代码复审
空奈qwq37 分钟前
机器学习入门:从核心概念到建模全流程
人工智能·python·机器学习
武子康1 小时前
CLAUDE.md 越写越长,哪些规则该放到子目录?
人工智能·llm·agent
IvanCodes1 小时前
Python 基础语法(六):字典与集合
python