GPT4All Python Generation API
The GPT4All
python package provides bindings to our C/C++ model backend libraries.
The source code and local build instructions can be found here.
Quickstart
This will:
- Instantiate
GPT4All
, which is the primary public API to your large language model (LLM). - Automatically download the given model to
~/.cache/gpt4all/
if not already present.
Read further to see how to chat with this model.
Chatting with GPT4All
To start chatting with a local LLM, you will need to start a chat session. Within a chat session, the model will be
prompted with the appropriate template, and history will be preserved between successive calls to generate()
.
[
{
'role': 'user',
'content': 'hello'
},
{
'role': 'assistant',
'content': 'What is your name?'
},
{
'role': 'user',
'content': 'write me a short poem'
},
{
'role': 'assistant',
'content': "I would love to help you with that! Here's a short poem I came up with:\nBeneath the autumn leaves,\nThe wind whispers through the trees.\nA gentle breeze, so at ease,\nAs if it were born to play.\nAnd as the sun sets in the sky,\nThe world around us grows still."
},
{
'role': 'user',
'content': 'thank you'
},
{
'role': 'assistant',
'content': "You're welcome! I hope this poem was helpful or inspiring for you. Let me know if there is anything else I can assist you with."
}
]
When using GPT4All models in the chat_session()
context:
- Consecutive chat exchanges are taken into account and not discarded until the session ends; as long as the model has capacity.
- A system prompt is inserted into the beginning of the model's context.
- Each prompt passed to
generate()
is wrapped in the appropriate prompt template. If you passallow_download=False
to GPT4All or are using a model that is not from the official models list, you must pass a prompt template using theprompt_template
parameter ofchat_session()
.
NOTE: If you do not use chat_session()
, calls to generate()
will not be wrapped in a prompt template. This will
cause the model to continue the prompt instead of answering it. When in doubt, use a chat session, as many newer
models are designed to be used exclusively with a prompt template.
Streaming Generations
To interact with GPT4All responses as the model generates, use the streaming=True
flag during generation.
The Generate Method API
generate(prompt, *, max_tokens=200, temp=0.7, top_k=40, top_p=0.4, min_p=0.0, repeat_penalty=1.18, repeat_last_n=64, n_batch=8, n_predict=None, streaming=False, callback=empty_response_callback)
Generate outputs from any GPT4All model.
Parameters:
-
prompt
(str
) –The prompt for the model to complete.
-
max_tokens
(int
, default:200
) –The maximum number of tokens to generate.
-
temp
(float
, default:0.7
) –The model temperature. Larger values increase creativity but decrease factuality.
-
top_k
(int
, default:40
) –Randomly sample from the top_k most likely tokens at each generation step. Set this to 1 for greedy decoding.
-
top_p
(float
, default:0.4
) –Randomly sample at each generation step from the top most likely tokens whose probabilities add up to top_p.
-
min_p
(float
, default:0.0
) –Randomly sample at each generation step from the top most likely tokens whose probabilities are at least min_p.
-
repeat_penalty
(float
, default:1.18
) –Penalize the model for repetition. Higher values result in less repetition.
-
repeat_last_n
(int
, default:64
) –How far in the models generation history to apply the repeat penalty.
-
n_batch
(int
, default:8
) –Number of prompt tokens processed in parallel. Larger values decrease latency but increase resource requirements.
-
n_predict
(int | None
, default:None
) –Equivalent to max_tokens, exists for backwards compatibility.
-
streaming
(bool
, default:False
) –If True, this method will instead return a generator that yields tokens as the model generates them.
-
callback
(ResponseCallbackType
, default:empty_response_callback
) –A function with arguments token_id:int and response:str, which receives the tokens from the model as they are generated and stops the generation by returning False.
Returns:
-
Any
–Either the entire completion or a generator that yields the completion token by token.
Source code in gpt4all/gpt4all.py
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 |
|
Examples & Explanations
Influencing Generation
The three most influential parameters in generation are Temperature (temp
), Top-p (top_p
) and Top-K (top_k
).
In a nutshell, during the process of selecting the next token, not just one or a few are considered, but every single
token in the vocabulary is given a probability. The parameters can change the field of candidate tokens.
-
Temperature makes the process either more or less random. A Temperature above 1 increasingly "levels the playing field", while at a Temperature between 0 and 1 the likelihood of the best token candidates grows even more. A Temperature of 0 results in selecting the best token, making the output deterministic. A Temperature of 1 represents a neutral setting with regard to randomness in the process.
-
Top-p and Top-K both narrow the field:
- Top-K limits candidate tokens to a fixed number after sorting by probability. Setting it higher than the vocabulary size deactivates this limit.
- Top-p selects tokens based on their total probabilities. For example, a value of 0.8 means "include the best tokens, whose accumulated probabilities reach or just surpass 80%". Setting Top-p to 1, which is 100%, effectively disables it.
The recommendation is to keep at least one of Top-K and Top-p active. Other parameters can also influence generation; be sure to review all their descriptions.
Specifying the Model Folder
The model folder can be set with the model_path
parameter when creating a GPT4All
instance. The example below is
is the same as if it weren't provided; that is, ~/.cache/gpt4all/
is the default folder.
from pathlib import Path
from gpt4all import GPT4All
model = GPT4All(model_name='orca-mini-3b-gguf2-q4_0.gguf', model_path=Path.home() / '.cache' / 'gpt4all')
If you want to point it at the chat GUI's default folder, it should be:
Alternatively, you could also change the module's default model directory:
from pathlib import Path
from gpt4all import GPT4All, gpt4all
gpt4all.DEFAULT_MODEL_DIRECTORY = Path.home() / 'my' / 'models-directory'
model = GPT4All('orca-mini-3b-gguf2-q4_0.gguf')
Managing Templates
When using a chat_session()
, you may customize the system prompt, and set the prompt template if necessary:
from gpt4all import GPT4All
model = GPT4All('wizardlm-13b-v1.2.Q4_0.gguf')
system_template = 'A chat between a curious user and an artificial intelligence assistant.\n'
# many models use triple hash '###' for keywords, Vicunas are simpler:
prompt_template = 'USER: {0}\nASSISTANT: '
with model.chat_session(system_template, prompt_template):
response1 = model.generate('why is the grass green?')
print(response1)
print()
response2 = model.generate('why is the sky blue?')
print(response2)
The color of grass can be attributed to its chlorophyll content, which allows it
to absorb light energy from sunlight through photosynthesis. Chlorophyll absorbs
blue and red wavelengths of light while reflecting other colors such as yellow
and green. This is why the leaves appear green to our eyes.
The color of the sky appears blue due to a phenomenon called Rayleigh scattering,
which occurs when sunlight enters Earth's atmosphere and interacts with air
molecules such as nitrogen and oxygen. Blue light has shorter wavelength than
other colors in the visible spectrum, so it is scattered more easily by these
particles, making the sky appear blue to our eyes.
Without Online Connectivity
To prevent GPT4All from accessing online resources, instantiate it with allow_download=False
. When using this flag,
there will be no default system prompt by default, and you must specify the prompt template yourself.
You can retrieve a model's default system prompt and prompt template with an online instance of GPT4All:
Then you can pass them explicitly when creating an offline instance:
from gpt4all import GPT4All
model = GPT4All('orca-mini-3b-gguf2-q4_0.gguf', allow_download=False)
system_prompt = '### System:\nYou are an AI assistant that follows instruction extremely well. Help as much as you can.\n\n'
prompt_template = '### User:\n{0}\n\n### Response:\n'
with model.chat_session(system_prompt=system_prompt, prompt_template=prompt_template):
...
Interrupting Generation
The simplest way to stop generation is to set a fixed upper limit with the max_tokens
parameter.
If you know exactly when a model should stop responding, you can add a custom callback, like so:
from gpt4all import GPT4All
model = GPT4All('orca-mini-3b-gguf2-q4_0.gguf')
def stop_on_token_callback(token_id, token_string):
# one sentence is enough:
if '.' in token_string:
return False
else:
return True
response = model.generate('Blue Whales are the biggest animal to ever inhabit the Earth.',
temp=0, callback=stop_on_token_callback)
print(response)
API Documentation
GPT4All
Python class that handles instantiation, downloading, generation and chat with GPT4All models.
Source code in gpt4all/gpt4all.py
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 |
|
backend: Literal['cpu', 'kompute', 'cuda', 'metal']
property
The name of the llama.cpp backend currently in use. One of "cpu", "kompute", "cuda", or "metal".
device: str | None
property
The name of the GPU device currently in use, or None for backends other than Kompute or CUDA.
__init__(model_name, *, model_path=None, model_type=None, allow_download=True, n_threads=None, device=None, n_ctx=2048, ngl=100, verbose=False)
Constructor
Parameters:
-
model_name
(str
) –Name of GPT4All or custom model. Including ".gguf" file extension is optional but encouraged.
-
model_path
(str | PathLike[str] | None
, default:None
) –Path to directory containing model file or, if file does not exist, where to download model. Default is None, in which case models will be stored in
~/.cache/gpt4all/
. -
model_type
(str | None
, default:None
) –Model architecture. This argument currently does not have any functionality and is just used as descriptive identifier for user. Default is None.
-
allow_download
(bool
, default:True
) –Allow API to download models from gpt4all.io. Default is True.
-
n_threads
(int | None
, default:None
) –number of CPU threads used by GPT4All. Default is None, then the number of threads are determined automatically.
-
device
(str | None
, default:None
) –The processing unit on which the GPT4All model will run. It can be set to: - "cpu": Model will run on the central processing unit. - "gpu": Use Metal on ARM64 macOS, otherwise the same as "kompute". - "kompute": Use the best GPU provided by the Kompute backend. - "cuda": Use the best GPU provided by the CUDA backend. - "amd", "nvidia": Use the best GPU provided by the Kompute backend from this vendor. - A specific device name from the list returned by
GPT4All.list_gpus()
. Default is Metal on ARM64 macOS, "cpu" otherwise.Note: If a selected GPU device does not have sufficient RAM to accommodate the model, an error will be thrown, and the GPT4All instance will be rendered invalid. It's advised to ensure the device has enough memory before initiating the model.
-
n_ctx
(int
, default:2048
) –Maximum size of context window
-
ngl
(int
, default:100
) –Number of GPU layers to use (Vulkan)
-
verbose
(bool
, default:False
) –If True, print debug messages.
Source code in gpt4all/gpt4all.py
chat_session(system_message=None, chat_template=None)
Context manager to hold an inference optimized chat session with a GPT4All model.
Parameters:
-
system_message
(str | Literal[False] | None
, default:None
) –An initial instruction for the model, None to use the model default, or False to disable. Defaults to None.
-
chat_template
(str | None
, default:None
) –Jinja template for the conversation, or None to use the model default. Defaults to None.
Source code in gpt4all/gpt4all.py
close()
download_model(model_filename, model_path, verbose=True, url=None, expected_size=None, expected_md5=None)
staticmethod
Download model from gpt4all.io.
Parameters:
-
model_filename
(str
) –Filename of model (with .gguf extension).
-
model_path
(str | PathLike[str]
) –Path to download model to.
-
verbose
(bool
, default:True
) –If True (default), print debug messages.
-
url
(str | None
, default:None
) –the models remote url (e.g. may be hosted on HF)
-
expected_size
(int | None
, default:None
) –The expected size of the download.
-
expected_md5
(str | None
, default:None
) –The expected MD5 hash of the download.
Returns:
-
str | PathLike[str]
–Model file destination.
Source code in gpt4all/gpt4all.py
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 |
|
generate(prompt, *, max_tokens=200, temp=0.7, top_k=40, top_p=0.4, min_p=0.0, repeat_penalty=1.18, repeat_last_n=64, n_batch=8, n_predict=None, streaming=False, callback=empty_response_callback)
Generate outputs from any GPT4All model.
Parameters:
-
prompt
(str
) –The prompt for the model to complete.
-
max_tokens
(int
, default:200
) –The maximum number of tokens to generate.
-
temp
(float
, default:0.7
) –The model temperature. Larger values increase creativity but decrease factuality.
-
top_k
(int
, default:40
) –Randomly sample from the top_k most likely tokens at each generation step. Set this to 1 for greedy decoding.
-
top_p
(float
, default:0.4
) –Randomly sample at each generation step from the top most likely tokens whose probabilities add up to top_p.
-
min_p
(float
, default:0.0
) –Randomly sample at each generation step from the top most likely tokens whose probabilities are at least min_p.
-
repeat_penalty
(float
, default:1.18
) –Penalize the model for repetition. Higher values result in less repetition.
-
repeat_last_n
(int
, default:64
) –How far in the models generation history to apply the repeat penalty.
-
n_batch
(int
, default:8
) –Number of prompt tokens processed in parallel. Larger values decrease latency but increase resource requirements.
-
n_predict
(int | None
, default:None
) –Equivalent to max_tokens, exists for backwards compatibility.
-
streaming
(bool
, default:False
) –If True, this method will instead return a generator that yields tokens as the model generates them.
-
callback
(ResponseCallbackType
, default:empty_response_callback
) –A function with arguments token_id:int and response:str, which receives the tokens from the model as they are generated and stops the generation by returning False.
Returns:
-
Any
–Either the entire completion or a generator that yields the completion token by token.
Source code in gpt4all/gpt4all.py
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 |
|
list_gpus()
staticmethod
List the names of the available GPU devices.
Returns:
-
list[str]
–A list of strings representing the names of the available GPU devices.
list_models()
staticmethod
Fetch model list from https://gpt4all.io/models/models3.json.
Returns:
-
list[ConfigType]
–Model list in JSON format.
Source code in gpt4all/gpt4all.py
retrieve_model(model_name, model_path=None, allow_download=True, verbose=False)
classmethod
Find model file, and if it doesn't exist, download the model.
Parameters:
-
model_name
(str
) –Name of model.
-
model_path
(str | PathLike[str] | None
, default:None
) –Path to find model. Default is None in which case path is set to ~/.cache/gpt4all/.
-
allow_download
(bool
, default:True
) –Allow API to download model from gpt4all.io. Default is True.
-
verbose
(bool
, default:False
) –If True (default), print debug messages.
Returns:
-
ConfigType
–Model config.