搜索
首页后端开发Python教程使用开源模型创建您自己的自定义 LLM 代理 (llama)

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
列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

说明如何将内存分配给Python中的列表与数组。说明如何将内存分配给Python中的列表与数组。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python数组中指定元素的数据类型?您如何在Python数组中指定元素的数据类型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

什么是Numpy,为什么对于Python中的数值计算很重要?什么是Numpy,为什么对于Python中的数值计算很重要?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

讨论'连续内存分配”的概念及其对数组的重要性。讨论'连续内存分配”的概念及其对数组的重要性。May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy阵列上可以执行哪些常见操作?在Numpy阵列上可以执行哪些常见操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的数据分析中如何使用阵列?Python的数据分析中如何使用阵列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),