Skip to main content
Open In ColabOpen on GitHub

GPT4All

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

此示例介绍了如何使用 LangChain 与 GPT4All 模型进行交互。

%pip install --upgrade --quiet langchain-community gpt4all

导入GPT4All

from langchain_community.llms import GPT4All
from langchain_core.prompts import PromptTemplate
API 参考:GPT4All | PromptTemplate

设置问题以传递给大型语言模型

template = """Question: {question}

Answer: Let's think step by step."""

prompt = PromptTemplate.from_template(template)

指定模型

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

gpt4all 页面 有一个有用的 Model Explorer 部分:

  • 选择一个感兴趣的模型
  • 通过用户界面下载并移动 .binlocal_path(如下所示)

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


此集成目前还不支持通过 .stream() 方法以分块形式进行流式传输。下面的示例使用了带有 streaming=True 的回调处理器:

local_path = (
"./models/Meta-Llama-3-8B-Instruct.Q4_0.gguf" # replace with your local file path
)
from langchain_core.callbacks import BaseCallbackHandler

count = 0


class MyCustomHandler(BaseCallbackHandler):
def on_llm_new_token(self, token: str, **kwargs) -> None:
global count
if count < 10:
print(f"Token: {token}")
count += 1


# Verbose is required to pass to the callback manager
llm = GPT4All(model=local_path, callbacks=[MyCustomHandler()], streaming=True)

# If you want to use a custom model add the backend parameter
# Check https://docs.gpt4all.io/gpt4all_python.html for supported backends
# llm = GPT4All(model=local_path, backend="gptj", callbacks=callbacks, streaming=True)

chain = prompt | llm

question = "What NFL team won the Super Bowl in the year Justin Bieber was born?"

# Streamed tokens will be logged/aggregated via the passed callback
res = chain.invoke({"question": question})
API 参考:BaseCallbackHandler
Token:  Justin
Token: Bieber
Token: was
Token: born
Token: on
Token: March
Token:
Token: 1
Token: ,
Token: