如何在鏈中使用工具
在本指南中,我們將介紹創建調用工具的鏈和代理程式的基本方法。工具幾乎可以是任何東西 — API、函數、數據庫等。工具使我們能夠將模型的功能擴展到僅輸出文本/訊息之外。使用帶有工具的模型的關鍵是正確提示模型並解析其回應,以便它選擇正確的工具並為其提供正確的輸入。
設定
本指南需要安裝以下套件
%pip install --upgrade --quiet langchain
如果您想在 LangSmith 中追蹤您的運行,請取消註釋並設定以下環境變量
import getpass
import os
# os.environ["LANGSMITH_TRACING"] = "true"
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass()
創建工具
首先,我們需要創建一個要調用的工具。在本示例中,我們將從一個函數創建一個自訂工具。有關創建自訂工具的更多信息,請參閱本指南。
from langchain_core.tools import tool
@tool
def multiply(first_int: int, second_int: int) -> int:
"""Multiply two integers together."""
return first_int * second_int
print(multiply.name)
print(multiply.description)
print(multiply.args)
multiply
multiply(first_int: int, second_int: int) -> int - Multiply two integers together.
{'first_int': {'title': 'First Int', 'type': 'integer'}, 'second_int': {'title': 'Second Int', 'type': 'integer'}}
multiply.invoke({"first_int": 4, "second_int": 5})
20
鏈
如果我們知道我們只需要固定次數使用工具,我們可以創建一個鏈來執行此操作。讓我們創建一個簡單的鏈,僅用於乘以用戶指定的數字。
工具/函數調用
將工具與 LLM 結合使用的最可靠方法之一是使用工具調用 API(有時也稱為函數調用)。這僅適用於顯式支持工具調用的模型。您可以在此處查看哪些模型支持工具調用,並在本指南中了解有關如何使用工具調用的更多信息。
首先,我們將定義我們的模型和工具。我們將從單個工具 `multiply` 開始。
pip install -qU "langchain[openai]"
import getpass
import os
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")
from langchain.chat_models import init_chat_model
llm = init_chat_model("gpt-4o-mini", model_provider="openai")
我們將使用 `bind_tools` 在每次調用模型時傳遞工具的定義,以便模型可以在適當時調用該工具
llm_with_tools = llm.bind_tools([multiply])
當模型調用工具時,這將顯示在輸出的 `AIMessage.tool_calls` 屬性中
msg = llm_with_tools.invoke("whats 5 times forty two")
msg.tool_calls
[{'name': 'multiply',
'args': {'first_int': 5, 'second_int': 42},
'id': 'call_cCP9oA3tRz7HDrjFn1FdmDaG'}]
在此處查看 LangSmith 追蹤。
調用工具
太好了!我們能夠生成工具調用。但是,如果我們想實際調用該工具怎麼辦?為此,我們需要將生成的工具參數傳遞給我們的工具。作為一個簡單的示例,我們將僅提取第一個 tool_call 的參數
from operator import itemgetter
chain = llm_with_tools | (lambda x: x.tool_calls[0]["args"]) | multiply
chain.invoke("What's four times 23")
92
在此處查看 LangSmith 追蹤。
代理程式
當我們知道任何用戶輸入所需的特定工具使用順序時,鏈非常有用。但是對於某些用例,我們使用工具的次數取決於輸入。在這些情況下,我們希望讓模型本身決定使用工具的次數和順序。代理程式讓我們可以做到這一點。
LangChain 帶有多個內建代理程式,這些代理程式針對不同的用例進行了優化。在此處閱讀有關所有代理程式類型的資訊。
我們將使用工具調用代理程式,它通常是最可靠的類型,也是大多數用例的推薦類型。
from langchain import hub
from langchain.agents import AgentExecutor, create_tool_calling_agent
# Get the prompt to use - can be replaced with any prompt that includes variables "agent_scratchpad" and "input"!
prompt = hub.pull("hwchase17/openai-tools-agent")
prompt.pretty_print()
================================[1m System Message [0m================================
You are a helpful assistant
=============================[1m Messages Placeholder [0m=============================
[33;1m[1;3m{chat_history}[0m
================================[1m Human Message [0m=================================
[33;1m[1;3m{input}[0m
=============================[1m Messages Placeholder [0m=============================
[33;1m[1;3m{agent_scratchpad}[0m
代理程式也很棒,因為它們使使用多個工具變得容易。
@tool
def add(first_int: int, second_int: int) -> int:
"Add two integers."
return first_int + second_int
@tool
def exponentiate(base: int, exponent: int) -> int:
"Exponentiate the base to the exponent power."
return base**exponent
tools = [multiply, add, exponentiate]
# Construct the tool calling agent
agent = create_tool_calling_agent(llm, tools, prompt)
# Create an agent executor by passing in the agent and tools
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
使用代理程式,我們可以提出需要任意多次使用我們工具的問題
agent_executor.invoke(
{
"input": "Take 3 to the fifth power and multiply that by the sum of twelve and three, then square the whole result"
}
)
[1m> Entering new AgentExecutor chain...[0m
[32;1m[1;3m
Invoking: `exponentiate` with `{'base': 3, 'exponent': 5}`
[0m[38;5;200m[1;3m243[0m[32;1m[1;3m
Invoking: `add` with `{'first_int': 12, 'second_int': 3}`
[0m[33;1m[1;3m15[0m[32;1m[1;3m
Invoking: `multiply` with `{'first_int': 243, 'second_int': 15}`
[0m[36;1m[1;3m3645[0m[32;1m[1;3m
Invoking: `exponentiate` with `{'base': 405, 'exponent': 2}`
[0m[38;5;200m[1;3m13286025[0m[32;1m[1;3mThe result of taking 3 to the fifth power is 243.
The sum of twelve and three is 15.
Multiplying 243 by 15 gives 3645.
Finally, squaring 3645 gives 13286025.[0m
[1m> Finished chain.[0m
{'input': 'Take 3 to the fifth power and multiply that by the sum of twelve and three, then square the whole result',
'output': 'The result of taking 3 to the fifth power is 243. \n\nThe sum of twelve and three is 15. \n\nMultiplying 243 by 15 gives 3645. \n\nFinally, squaring 3645 gives 13286025.'}
在此處查看 LangSmith 追蹤。