跳到主要內容

MLX

這個筆記本展示如何開始使用 MLX LLM 作為聊天模型。

特別是,我們將會

  1. 使用 MLXPipeline
  2. 使用 ChatMLX 類別,使這些 LLM 中的任何一個都能與 LangChain 的 聊天訊息 抽象介面互動。
  3. 示範如何使用開源 LLM 來驅動 ChatAgent 管道
%pip install --upgrade --quiet  mlx-lm transformers huggingface_hub

1. 實例化 LLM

有三個 LLM 選項可供選擇。

from langchain_community.llms.mlx_pipeline import MLXPipeline

llm = MLXPipeline.from_model_id(
"mlx-community/quantized-gemma-2b-it",
pipeline_kwargs={"max_tokens": 10, "temp": 0.1},
)
API 參考文檔:MLXPipeline

2. 實例化 ChatMLX 以應用聊天模板

實例化聊天模型和一些要傳遞的訊息。

from langchain_community.chat_models.mlx import ChatMLX
from langchain_core.messages import HumanMessage

messages = [
HumanMessage(
content="What happens when an unstoppable force meets an immovable object?"
),
]

chat_model = ChatMLX(llm=llm)
API 參考文檔:ChatMLX | HumanMessage

檢查聊天訊息如何格式化以進行 LLM 呼叫。

chat_model._to_chat_prompt(messages)

呼叫模型。

res = chat_model.invoke(messages)
print(res.content)

3. 作為代理程式試用看看!

在這裡,我們將測試 gemma-2b-it 作為零樣本 ReAct 代理程式。以下範例取自此處

注意:要執行此部分,您需要將 SerpAPI Token 儲存為環境變數:SERPAPI_API_KEY

from langchain import hub
from langchain.agents import AgentExecutor, load_tools
from langchain.agents.format_scratchpad import format_log_to_str
from langchain.agents.output_parsers import (
ReActJsonSingleInputOutputParser,
)
from langchain.tools.render import render_text_description
from langchain_community.utilities import SerpAPIWrapper

使用 react-json 風格提示和搜尋引擎及計算機的存取權來配置代理程式。

# setup tools
tools = load_tools(["serpapi", "llm-math"], llm=llm)

# setup ReAct style prompt
prompt = hub.pull("hwchase17/react-json")
prompt = prompt.partial(
tools=render_text_description(tools),
tool_names=", ".join([t.name for t in tools]),
)

# define the agent
chat_model_with_stop = chat_model.bind(stop=["\nObservation"])
agent = (
{
"input": lambda x: x["input"],
"agent_scratchpad": lambda x: format_log_to_str(x["intermediate_steps"]),
}
| prompt
| chat_model_with_stop
| ReActJsonSingleInputOutputParser()
)

# instantiate AgentExecutor
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.invoke(
{
"input": "Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?"
}
)

此頁面是否對您有幫助?