使用開源模型建立您自己的自訂 LLM 代理程式 (llama)

PHPz
發布: 2024-08-18 06:04:35
原創
576 人瀏覽過

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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!