基本步骤:
在Agent当中,当我们需要调用自己写好的工具时,我们需要分三步来构建Message:
- HumanMessage(提出问题)
- AIMessage(由ai来帮我们选择该调用哪个工具,以及每个工具传什么参数)
- 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)