自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

又一突破!跨模型的Function_Calling來了

發(fā)布于 2024-4-19 15:43
瀏覽
0收藏

介紹

大型語言模型(LLM)通過工具調用能夠與外部數(shù)據(jù)源進行交互。這項技術讓開發(fā)者能夠利用LLM來獲取、交互和操作外部資源(比如數(shù)據(jù)庫、文件和API等)。

隨著越來越多的LLM提供商開始提供工具調用功能,我們注意到市場上出現(xiàn)了多種多樣的接口。為了解決這個問題,LangChain推出了一個標準化的接口,這樣用戶就可以輕松地在不同的LLM提供商之間進行切換。

又一突破!跨模型的Function_Calling來了-AI.x社區(qū)

這個標準化接口包括以下幾個方面:

  • ChatModel.bind_tools:這個方法允許您將工具的定義附加到模型的調用過程中。
  • AIMessage.tool_calls?:這是一個新增的屬性,它使得從模型返回的 AIMessage 中獲取工具調用變得更加簡單。
  • create_tool_calling_agent?:這是一個構建代理的函數(shù),適用于任何實現(xiàn)了 bind_tools 并且能夠返回 tool_calls 的模型。

下面,我們將詳細解釋這些組件。

ChatModel.bind_tools

為了讓模型能夠使用工具,我們需要告訴它哪些工具是可以使用的。這可以通過向模型提供一個包含工具定義的列表來實現(xiàn),這些工具定義包括了工具參數(shù)的模式。不同的模型提供商可能需要不同的格式,但是 ChatModel.bind_tools 提供了一個統(tǒng)一的接口,讓您可以指定哪些工具對模型來說是可用的。

這意味著,無論您使用的是哪種工具調用模型,代碼的結構都將非常相似。

from langchain_anthropic import ChatAnthropic
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_core.tools import tool

# ? Pydantic 類
class multiply(BaseModel):
    """返回 'x' 和 'y' 的乘積。"""
    x: float = Field(..., descriptinotallow="第一個因子")
    y: float = Field(..., descriptinotallow="第二個因子")
    
# ? LangChain 工具
@tool
def exponentiate(x: float, y: float) -> float:
    """將 'x' 乘以 'y'。"""
    return x**y
    
# ? 函數(shù)

def subtract(x: float, y: float) -> float:
    """從 'y' 中減去 'x'。"""
    return y-x
    
# ? OpenAI 格式字典
# 還可以傳入一個帶有 "title" 和 "description" 的 JSON 模式
add = {
  "name": "add",
  "description": "將 'x' 和 'y' 相加。",
  "parameters": {
    "type": "object",
    "properties": {
      "x": {"type": "number", "description": "要相加的第一個數(shù)字"},
      "y": {"type": "number", "description": "要相加的第二個數(shù)字"}
    },
    "required": ["x", "y"]
  }
}

llm = ChatAnthropic(model="claude-3-sonnet-20240229", temperature=0)

# 每當我們調用 `llm_with_tool` 時,這三個工具定義
# 都會被傳遞給模型。
llm_with_tools = llm.bind_tools([multiply, exponentiate, add, subtract])

如果我們想使用不同的工具調用模型,我們的代碼看起來會非常相似:

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4-turbo", temperature=0)
llm_with_tools = llm.bind_tools([multiply, exponentiate, add, subtract])

那么調用 llm_with_tools 會是什么樣子呢?這就是 AIMessage.tool_calls 的用武之地。

AIMessage.tool_calls

在過去,當使用工具調用模型時,模型返回的工具調用可能會放在 AIMessage.additional_kwargs 或 AIMessage.content 中,這取決于模型提供商的API,并遵循特定于提供商的格式?,F(xiàn)在,AIMessage.tool_calls 提供了一個標準化的接口來獲取模型的工具調用。這樣,在調用了綁定了工具的模型之后,您將得到一個包含 tool_calls 屬性的輸出,其中列出了所有的工具調用。

在調用了綁定工具的模型之后,您將得到以下形式的輸出:

llm_with_tools.invoke([
 ("system", "你是一個有用的助手"), 
 ("human", "5 的 2.743 次方是多少"),
])

# ?? 注意 tool_calls 屬性 ??

# -> AIMessage(
#    cnotallow=..., 
#    additional_kwargs={...},
#    tool_calls=[{'name': 'exponentiate', 'args': {'y': 2.743, 'x': 5.0}, 'id': '54c166b2-f81a-481a-9289-eea68fc84e4f'}]
#    response_metadata={...}, 
#    id='...'
#   )

其中 AIMessage 有一個 tool_calls: List[ToolCall] 屬性,如果有工具調用,它將被填充,并將遵循工具調用的標準接口:

class ToolCall(TypedDict):
  name: str
  args: Dict[str, Any]
 id: Optional[str]

也就是說,無論您是在調用 Anthropic、OpenAI、Gemini 等,只要有工具調用,它將以 AIMessage.tool_calls 形式作為 ToolCall 出現(xiàn)。

我們還添加了一些其他屬性,用于處理流式工具調用塊和無效工具調用。有關這些的更多信息,請閱讀工具調用文檔 這里。

create_tool_calling_agent

利用LLM的工具調用能力來構建代理是一個非常強大的應用場景。我們已經有了一個 create_openai_tools_agent() 構造函數(shù),它可以方便地構建一個符合OpenAI工具調用API的代理。但是,這個構造函數(shù)并不適用于Anthropic和Gemini等模型?,F(xiàn)在,有了 bind_tools() 和 tool_calls 這兩個新接口,我們推出了 create_tool_calling_agent(),它能夠與任何支持工具調用的模型一起工作。

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import ConfigurableField
from langchain_core.tools import tool
from langchain.agents import create_tool_calling_agent, AgentExecutor

@tool
def multiply(x: float, y: float) -> float:
    """將 'x' 乘以 'y'。"""
    return x * y

@tool
def exponentiate(x: float, y: float) -> float:
    """將 'x' 乘以 'y' 的指數(shù)。"""
    return x**y

@tool
def add(x: float, y: float) -> float:
    """將 'x' 和 'y' 相加。"""
    return x + y

prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一個有用的助手"), 
    ("human", "{input}"), 
    ("placeholder", "{agent_scratchpad}"),
])

tools = [multiply, exponentiate, add]

llm = ChatAnthropic(model="claude-3-sonnet-20240229", temperature=0)

agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

agent_executor.invoke({"input": "3 加上 5 的 2.743 次方是多少。還有 17.24 減去 918.1241 是多少。"})

我們可以使用 VertexAI 替代:

from langchain_google_vertexai import ChatVertexAI

llm = ChatVertexAI(
 model="gemini-pro", 
 temperature=0, 
 convert_system_message_to_human=True
)
agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

agent_executor.invoke({"input": "3 加上 5 的 2.743 次方是多少。還有 17.24 減去 918.1241 是多少。"})

或者 OpenAI:

llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)

agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

agent_executor.invoke({"input": "3 加上 5 的 2.743 次方是多少。還有 17.24 減去 918.1241 是多少。"})

等等。

有關新代理的完整文檔,請查看 https://python.langchain.com/docs/modules/agents/agent_types/tool_calling。

總結

我們預計,將原生工具調用功能引入LLM的趨勢將繼續(xù)下去。我們希望這個標準化的工具調用接口能夠幫助LangChain用戶節(jié)省時間和精力,并使他們能夠更容易地在不同的LLM提供商之間進行切換。

本文轉載自 ??AI小智??,作者: AI小智

收藏
回復
舉報
回復
相關推薦