在本文中,我们将学习如何使用在 PC 上本地运行的开源 llm (llama3.1) 创建自定义代理。我们还将使用 Ollama 和 LangChain。
大纲
- 安装 Ollama
- 安装 langchain langchain-ollama
- 使用 Python 中的开源模型构建自定义代理
安装 Ollama
安装 Ollama:
https://github.com/ollama/ollama
我在基于 Linux 的 PC 上,因此我将在终端中运行以下命令:
curl -fsSL https://ollama.com/install.sh | sh
拉取模型
通过以下命令获取可用的 LLM 模型:
ollama pull llama3.1
这将下载模型的默认标记版本。通常,默认值指向最新的、最小尺寸参数模型。在本例中,它将是 llama3.1:8b 模型。
启动模型服务
运行以下命令启动 ollama,而无需运行桌面应用程序。
ollama serve
安装 langchain langchain-ollama
运行以下命令安装 langchain 和 langchain-ollama:
pip install -U langchain langchain-ollama
使用 Python 中的开源模型构建自定义代理
创建一个Python文件例如:main.py并添加以下代码:
from langchain_ollama import ChatOllama
from langchain.agents import tool
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.agents.format_scratchpad.openai_tools import (
format_to_openai_tool_messages,
)
from langchain.agents import AgentExecutor
from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParser
llm = ChatOllama(
model="llama3.1",
temperature=0,
verbose=True
)
@tool
def get_word_length(word: str) -> int:
"""Returns the length of a word."""
return len(word)
tools = [get_word_length]
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are very powerful assistant",
),
("user", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
]
)
llm_with_tools = llm.bind_tools(tools)
agent = (
{
"input": lambda x: x["input"],
"agent_scratchpad": lambda x: format_to_openai_tool_messages(
x["intermediate_steps"]
),
}
| prompt
| llm_with_tools
| OpenAIToolsAgentOutputParser()
)
# Create an agent executor by passing in the agent and tools
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
result = agent_executor.invoke({"input": "How many letters in the word educa"})
if result:
print(f"[Output] --> {result['output']}")
else:
print('There are no result..')
上述代码片段使用 ChatOllama 模型 (llama3.1) 设置了一个 LangChain 代理来处理用户输入并利用一个计算单词长度的自定义工具。它为代理定义了一个提示模板,将该工具绑定到语言模型,并构建了一个处理输入和格式化中间步骤的代理。最后,它创建一个 AgentExecutor 来使用特定输入调用代理。我们传递一个简单的问题来询问“How many letters in the word educa”,然后我们打印输出或指示是否未找到结果。
运行后,我们得到以下结果:
> Entering new AgentExecutor chain...
Invoking: `get_word_length` with `{'word': 'educa'}`
The word "educa" has 5 letters.
> Finished chain.
[Output] --> The word "educa" has 5 letters.
您会看到代理使用模型(llama3.1)正确调用工具来获取单词中的字母数。