跳至主要內容

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

設定要傳遞給 LLM 的問題

template = """Question: {question}

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

prompt = PromptTemplate.from_template(template)

指定模型

若要在本機執行,請下載相容的 ggml 格式模型。

gpt4all 頁面 有一個有用的 模型瀏覽器 區段

  • 選擇感興趣的模型
  • 使用 UI 下載,並將 .bin 移至 local_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:

此頁面是否有幫助?