如何使用 Ollama、LangChain 在 Python 中本地运行 Llama-3.1🦙

2025-05-27

如何使用 Ollama、LangChain 在 Python 中本地运行 Llama-3.1🦙

在本文中,我们将学习如何使用 Python 中的 Ollama 和 LangChain 在 PC 上本地运行 Llama-3.1 模型

大纲

  • 安装 Ollama
  • 拉动模型
  • 服务模型
  • 创建一个新文件夹,用代码编辑器打开它
  • 创建并激活虚拟环境
  • 安装 langchain-ollama
  • 使用 Python 模型运行 Ollama
  • 结论

安装 Ollama

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

https://github.com/ollama/ollama
Enter fullscreen mode Exit fullscreen mode

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

curl -fsSL https://ollama.com/install.sh | sh
Enter fullscreen mode Exit fullscreen mode

拉动模型

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

ollama pull llama3.1
Enter fullscreen mode Exit fullscreen mode

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

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

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

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

服务模型

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

ollama serve
Enter fullscreen mode Exit fullscreen mode

所有模型均自动在 localhost:11434 上提供服务

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

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

创建并激活虚拟环境

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

python3 -m venv .venv
Enter fullscreen mode Exit fullscreen mode
source .venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

安装 langchain-ollama

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

pip install -U langchain-ollama
Enter fullscreen mode Exit fullscreen mode

上述命令将在 Python 中安装或升级 LangChain Ollama 包。该包允许用户在 LangChain 框架内集成并与 Ollama 模型(开源大型语言模型)交互。如果已安装该包,则 -U 标志可确保将其升级到最新版本。

使用 Python 模型运行 Ollama

创建一个Python文件例如:main.py并添加以下代码:

from langchain_ollama import OllamaLLM

llm = OllamaLLM(model="llama3.1")

response = llm.invoke("The first man on the moon was ...")
print(response)
Enter fullscreen mode Exit fullscreen mode

上述代码从 LangChain 库导入了 OllamaLLM 类,并初始化了语言模型“llama3.1”的一个实例。我们输入一个关于月球上第一个人的提示,并将生成的响应存储在变量“response”中。运行上述代码后,我们会从模型中获得以下响应:

...Neil Armstrong!

On July 20, 1969, Neil Armstrong became the first person to set foot on the lunar surface during the Apollo 11 mission. As he stepped off the lunar module Eagle and onto the moon's surface, he famously declared: "That's one small step for man, one giant leap for mankind."
Enter fullscreen mode Exit fullscreen mode

结论

感谢阅读。
您可以查看Ollama 文档了解更多命令。

文章来源:https://dev.to/emmakodes_/how-to-run-llama-31-locally-in-python-using-ollama-langchain-k8k
PREV
Encore.ts — 比 Express.js 快 9 倍,比 Bun + Zod 快 3 倍
NEXT
在技​​术会议上发言