Skip to main content

GPT4All

Github:nomic-ai/gpt4all 是一个开源聊天机器人生态系统,它使用大量的干净助手数据进行训练,包括代码、故事和对话。

这个示例演示了如何使用LangChain与GPT4All模型进行交互。

%pip install gpt4all > /dev/null
    注意:您可能需要重新启动内核以使用更新的软件包。
from langchain import PromptTemplate, LLMChain
from langchain.llms import GPT4All
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
template = """问题:{question}

答案:让我们一步一步地思考。"""

prompt = PromptTemplate(template=template, input_variables=["question"])

指定模型

要在本地运行,请下载一个兼容的ggml格式模型。

下载选项1gpt4all页面有一个有用的模型浏览器部分:

  • 选择一个感兴趣的模型
  • 使用UI下载并将.bin文件移动到local_path(如下所示)

有关更多信息,请访问https://github.com/nomic-ai/gpt4all。


下载选项2:取消下面的代码块以下载模型。

  • 您可能需要将url更新为新版本,可以使用gpt4all页面浏览。
local_path = (
"./models/ggml-gpt4all-l13b-snoozy.bin" # 替换为您想要的本地文件路径
)

# import requests

# from pathlib import Path
# from tqdm import tqdm

# Path(local_path).parent.mkdir(parents=True, exist_ok=True)

# # 示例模型。请查看https://github.com/nomic-ai/gpt4all获取最新模型。
# url = 'http://gpt4all.io/models/ggml-gpt4all-l13b-snoozy.bin'

# # 发送GET请求以下载文件。由于文件很大,所以使用流式传输
# response = requests.get(url, stream=True)

# # 以二进制模式打开文件,并将响应的内容以块的形式写入其中
# # 这是一个大文件,所以请准备等待。
# with open(local_path, 'wb') as f:
# for chunk in tqdm(response.iter_content(chunk_size=8192)):
# if chunk:
# f.write(chunk)
# 回调函数支持逐标记流式处理
callbacks = [StreamingStdOutCallbackHandler()]

# 需要将verbose参数传递给回调管理器
llm = GPT4All(model=local_path, callbacks=callbacks, verbose=True)

# 如果要使用自定义模型,请添加backend参数
# 请查看https://docs.gpt4all.io/gpt4all_python.html获取支持的后端
llm = GPT4All(model=local_path, backend="gptj", callbacks=callbacks, verbose=True)
llm_chain = LLMChain(prompt=prompt, llm=llm)
question = "贾斯汀·比伯出生的那一年,哪支NFL球队赢得了超级碗?"

llm_chain.run(question)