首页  >  文章  >  后端开发  >  使用开源模型创建您自己的自定义 LLM 代理 (llama)

使用开源模型创建您自己的自定义 LLM 代理 (llama)

PHPz
PHPz原创
2024-08-18 06:04:35569浏览

Create your own Custom LLM Agent Using Open Source Models (llama)

在本文中,我们将学习如何创建一个使用在我们的 PC 上本地运行的开源 llm (llama3.1) 的自定义代理。我们还将使用 Ollama 和 LangChain。

大纲

  • 安装 Ollama
  • 拉模型
  • 服务模型
  • 新建一个文件夹,用代码编辑器打开
  • 创建并激活虚拟环境
  • 安装 langchain langchain-ollama
  • 使用 Python 中的开源模型构建自定义代理
  • 结论

安装奥拉马

按照 GitHub README 中基于您操作系统类型的说明安装 Ollama:

https://github.com/ollama/ollama

我使用的是基于 Linux 的 PC,因此我将在终端中运行以下命令:

curl -fsSL https://ollama.com/install.sh | sh

拉模型

通过以下命令获取可用的LLM模型:

ollama pull llama3.1

这将下载模型的默认标记版本。通常,默认值指向最新、最小尺寸参数模型。在这种情况下,它将是 llama3.1:8b 模型。

要下载模型的其他版本,您可以访问:https://ollama.com/library/llama3.1 并选择要安装的版本,然后使用模型及其版本号运行 ollama pull 命令。示例:llama pull llama3.1:70b

在 Mac 上,模型将下载到 ~/.ollama/models

在 Linux(或 WSL)上,模型将存储在 /usr/share/ollama/.ollama/models

服务模式

运行以下命令启动 ollama,无需运行桌面应用程序。

ollama serve

所有模型都会自动在 localhost:11434

上提供服务

新建一个文件夹,用代码编辑器打开

在计算机上创建一个新文件夹,然后使用 VS Code 等代码编辑器打开它。

创建并激活虚拟环境

打开终端。使用以下命令创建虚拟环境.venv并激活它:

python3 -m venv .venv
source .venv/bin/activate

安装 langchain langchain-ollama

运行以下命令来安装 langchain 和 langchain-ollama:

pip install -U langchain langchain-ollama

上面的命令将安装或升级Python中的LangChain和LangChain-Ollama包。 -U 标志确保安装这些软件包的最新版本,替换可能已经存在的任何旧版本。

在 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 以使用特定输入调用代理。我们传递一个简单的问题来询问“educa 这个词中有多少个字母”,然后我们打印输出或指示是否未找到结果。

当我们运行时,我们得到以下结果:

> Entering new AgentExecutor chain...

Invoking: `get_word_length` with `{'word': 'educa'}`


5The word "educa" has 5 letters.

> Finished chain.
[Output] --> The word "educa" has 5 letters.

您看到代理使用模型 (llama3.1) 正确调用该工具来获取单词中的字母数。

结论

感谢您的阅读。

在此处查看 Ollama 存储库:https://github.com/ollama/ollama

以上是使用开源模型创建您自己的自定义 LLM 代理 (llama)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn