在看此篇之前你需要先看前几篇,分别是:
GPT4ALL私有化部署 01 | Python环境
GPT4ALL私有化部署 02 | 初尝试
GPT4ALL私有化部署 03 | 模型列表
GPT4ALL私有化部署 04 | 参数详解
前言
在本章中,会介绍到如何在本地任务栏与模型进行多次轮回的对话,代码已贴在下面,其实原理很简单。
步骤
- 导入依赖库:
from gpt4all import GPT4All
这行代码导入了需要用到的 GPT4All 库
- 初始化 GPT-4 模型:
model = GPT4All(model_name='orca-mini-3b.ggmlv3.q4_0.bin')
这行代码创建了一个 GPT-4 模型对象。我们通过指定模型名称(‘orca-mini-3b.ggmlv3.q4_0.bin’)来初始化模型。请确保已经下载了该模型并在代码的当前目录或指定的路径下,如果你不清楚,那你可以先看看GPT4ALL私有化部署 02 | 初尝试
- 建立会话与模型交互:
with model.chat_session():
while True:
user_input = input("You: ")
response = model.generate(prompt=user_input, top_k=1)
print("Bot:", response)
if user_input.lower() == 'exit':
break
这段代码使用 chat_session()
方法进入了一个上下文管理器。在这个上下文管理器中,我们可以与 GPT-4 模型建立持续的会话。
接下来,进入一个无限循环 while True:
。在每次循环中,代码将等待用户在命令行输入文本。这个输入将作为对话的提示传递给 GPT-4 模型,并通过 generate()
方法生成一个回复。
回复将被打印到控制台,形式为 “Bot: 回复内容”。
如果用户输入 ‘exit’,循环将终止,会话结束,代码退出。
这样,可以通过多次输入内容来与 GPT-4 模型进行对话。
完整代码
from gpt4all import GPT4All
# 初始化 GPT4All 模型
model = GPT4All(model_name='orca-mini-3b.ggmlv3.q4_0.bin')
# 使用 chat_session() 方法与模型建立会话
with model.chat_session():
while True:
# 获取用户输入作为对话的提示
user_input = input("You: ")
# 生成回复
response = model.generate(prompt=user_input, top_k=1)
# 打印回复
print("Bot:", response)
# 当用户输入 'exit' 时退出循环,结束对话
if user_input.lower() == 'exit':
break