Skip to main content

Minimal Python library to connect to LLMs (OpenAI, Anthropic, Google Palm2/Vertex, Mistral, Ollama, AI21, Cohere, Aleph-Alpha, HuggingfaceHub), with a built-in model performance benchmark.

Project description

PyLLMs

Twitter License: MIT

PyLLMs is a minimal Python library to connect to LLMs (OpenAI, Anthropic, Google, AI21, Cohere, Aleph Alpha, HuggingfaceHub) with a built-in model performance benchmark.

It is ideal for fast prototyping and evaluating different models thanks to:

  • Connect to top LLMs in a few lines of code
  • Response meta includes tokens processed, cost and latency standardized across the models
  • Multi-model support: Get completions from different models at the same time
  • LLM benchmark: Evaluate models on quality, speed and cost

Feel free to reuse and expand. Pull requests are welcome.

Installation

Install the package using pip:

pip install pyllms

Usage

import llms

model = llms.init('gpt-4')
result = model.complete("what is 5+5")

print(result.text)

Library will attempt to read the API keys and the default model from environment variables, which you can set like this (for the provider you are using):

export OPENAI_API_KEY="your_api_key_here"
export ANTHROPIC_API_KEY="your_api_key_here"
export AI21_API_KEY="your_api_key_here"
export COHERE_API_KEY="your_api_key_here"
export ALEPHALPHA_API_KEY="your_api_key_here"
export HUGGINFACEHUB_API_KEY="your_api_key_here"
export GOOGLE_API_KEY="your_api_key_here"
export MISTRAL_API_KEY="your_api_key_here"

export LLMS_DEFAULT_MODEL="gpt-3.5-turbo"

Alternatively, you can pass initialization values to the init() method:

model=llms.init(openai_api_key='your_api_key_here', model='gpt-4')

For using Google LLMs through Vertex AI API, see "Using Google AI models" below.

You can also pass optional parameters to the complete method. 'temperature' and 'max_tokens' are standardized across all APIs and get converted to the corresponding API params.

Any other parameters accepted by the original model are supported in their verbatim form.

result = model.complete(
    "what is the capital of country where mozzart was born",
    temperature=0.1,
    max_tokens=200
)

Note: By default, temperature for all models is set to 0, and max_tokens to 300.

The result meta will contain helpful information like tokens used, cost (which is automatically calculated using current pricing), and response latency:

>>> print(result.meta)
{
  'model': 'gpt-3.5-turbo',
  'tokens': 34,
  'tokens_prompt': 20,
  'tokens_completion': 14,
  'cost': '0.00007',
  'latency': 1.4
}

Multi-model usage

You can also initialize multiple models at once! This is very useful for testing and comparing output of different models in parallel.

>>> models=llms.init(model=['gpt-3.5-turbo','claude-instant-v1'])
>>> result=models.complete('what is the capital of country where mozzart was born')
>>> print(result.text)
[
 'The capital of the country where Mozart was born is Vienna, Austria.',
 'Wolfgang Amadeus Mozart was born in Salzburg, Austria.\n\nSo the capital of the country where Mozart was born is Vienna, Austria.'
]

>>> print(result.meta)
[
 {'model': 'gpt-3.5-turbo', 'tokens': 34, 'tokens_prompt': 20, 'tokens_completion': 14, 'cost': 6.8e-05, 'latency': 0.7097790241241455},
 {'model': 'claude-instant-v1', 'tokens': 54, 'tokens_prompt': 20, 'tokens_completion': 34, 'cost': 5.79e-05, 'latency': 0.7291600704193115}
]

Async support

Async completion is supported for compatible models. It is not supported in multi-models mode yet.

result = await model.acomplete("what is the capital of country where mozzart was born")

Streaming support

PyLLMs supports streaming from compatible models. 'complete_stream' method will return generator object and all you have to do is iterate through it:

model= llms.init('claude-v1')
result = model.complete_stream("write an essay on civil war")
for chunk in result.stream:
   if chunk is not None:
      print(chunk, end='')

Current limitations:

  • When streaming, 'meta' is not available
  • Multi-models are not supported for streaming

Tip: if you are testing this in python3 CLI, run it with -u parameter to disable buffering:

python3 -u

Chat history and system message

You can pass the history of conversation in a list using the following format:

history=[]
history.append({"role": "user", "content": user_input})
history.append({"role": "assistant", "content": result.text})

model.complete(prompt=prompt, history=history)

In addition, OpenAI chat models support system message:

model.complete(prompt=prompt, system_message=system, history=history)

Other methods

You can count tokens using the model's tokenizer:

count=model.count_tokens('the quick brown fox jumped over the lazy dog')

Using OpenAI API on Azure (and elsewhere, where compatible)

PyLLMs supports optional params to specify base path for the OpenAI input/output format, for example OpenAI models running on Azure.

import llms
AZURE_API_BASE = "{insert here}"
AZURE_API_KEY = "{insert here}"

model = llms.init('gpt-4')

azure_args = {
    "engine": "gpt-4",  # Azure deployment_id
    "api_base": AZURE_API_BASE,
    "api_type": "azure",
    "api_version": "2023-05-15",
    "api_key": AZURE_API_KEY,
}

openai_result = model.complete("what is 5+5")
azure_result = model.complete("what is 5+5", **azure_args)

model.benchmark(**azure_args)

Model Benchmarks

Models are appearing like mushrooms after rain and everyone is interested in three things:

  1. Quality
  2. Speed
  3. Cost

PyLLMs icludes an automated benchmark system. The quality of models is evaluated using a powerful model (for example gpt-4) on a range of predefined questions, or you can supply your own.

models=llms.init(model=['gpt-3.5-turbo', 'claude-instant-v1'])

gpt4=llms.init('gpt-4') # optional, evaluator can be ommited and in that case only speed and cost will be evaluated

models.benchmark(evaluator=gpt4)

+-------------------------+--------------------+---------------------+----------------------+-------------------------+------------------+
|          Model          |       Tokens       |       Cost ($)      |     Latency (s)      |    Speed (tokens/sec)   |    Evaluation    |
+-------------------------+--------------------+---------------------+----------------------+-------------------------+------------------+
| GoogleProvider('chat-bison') | Total Tokens: 2759 | Total Cost: 0.00689 | Median Latency: 2.83 | Aggregated speed: 36.24 | Accuracy: 19.23% |
| GoogleProvider('text-bison') | Total Tokens: 1155 | Total Cost: 0.00897 | Median Latency: 0.38 | Aggregated speed: 60.60 | Accuracy: 25.64% |
| CohereProvider('command') | Total Tokens: 4033 | Total Cost: 0.08125 | Median Latency: 5.77 | Aggregated speed: 9.44 | Accuracy: 11.54% |
| OpenAIProvider('gpt-3.5-turbo') | Total Tokens: 2116 | Total Cost: 0.00753 | Median Latency: 1.18 | Aggregated speed: 42.62 | Accuracy: 37.04% |
| AnthropicProvider('claude-instant-v1') | Total Tokens: 3437 | Total Cost: 0.02153 | Median Latency: 1.84 | Aggregated speed: 61.64 | Accuracy: 42.31% |
|  AnthropicProvider('claude-3-haiku-20240307') | Total Tokens: 6493 | Total Cost: 0.00855 | Median Latency: 1.64 | Aggregated speed: 127.44 | Accuracy: 51.85% |
|     OpenAIProvider('gpt-4')     | Total Tokens: 2109 | Total Cost: 0.17580 | Median Latency: 2.00 | Aggregated speed: 14.04 | Accuracy: 51.85% |
| AnthropicProvider('claude-3-sonnet-20240229') | Total Tokens: 5569 | Total Cost: 0.08876 | Median Latency: 3.65 | Aggregated speed: 54.67  | Accuracy: 55.56% |
| AnthropicProvider('claude-2') | Total Tokens: 3545 | Total Cost: 0.13337 | Median Latency: 6.83 | Aggregated speed: 19.51 | Accuracy: 69.23% |
| OpenAIProvider('gpt-4-turbo') | Total Tokens: 5538 | Total Cost: 0.18256 | Median Latency: 10.68 | Aggregated speed: 14.45 | Accuracy: 74.07% |
|  AnthropicProvider('claude-3-opus-20240229')  | Total Tokens: 6522 | Total Cost: 0.51525 | Median Latency: 8.56 | Aggregated speed: 26.55  | Accuracy: 74.07% |
|    OpenAIProvider('gpt-4o')   | Total Tokens: 6483 | Total Cost: 0.10539 |  Median Latency: 1.91 | Aggregated speed: 94.01 | Accuracy: 85.19% |
+-------------------------------+--------------------+---------------------+----------------------+-------------------------+------------------+

To evaluate models on your own prompts, simply pass a list of questions and optional answers as tuple. The evaluator will automatically evaluate the responses:

models.benchmark(prompts=[("what is the capital of finland", "helsinki")], evaluator=gpt4)

Supported Models

To get a list of supported models, call list(). Models will be shown in the order of least expensive to most expensive.

>>> model=llms.init()

>>> model.list()

>>> model.list("gpt') # lists only models with 'gpt' in name/provider name

Here is a pretty table of supported models (in alphabetical order).


| Provider            | Name                   | Prompt Cost | Completion Cost | Token Limit |
|---------------------|------------------------|-------------|-----------------|-------------|
| AI21Provider        | j2-grande-instruct     |        10.0 |            10.0 |        8192 |
| AI21Provider        | j2-jumbo-instruct      |        15.0 |            15.0 |        8192 |
| AlephAlphaProvider  | luminous-base          |         6.6 |             7.6 |        2048 |
| AlephAlphaProvider  | luminous-extended      |         9.9 |            10.9 |        2048 |
| AlephAlphaProvider  | luminous-supreme       |        38.5 |            42.5 |        2048 |
| AlephAlphaProvider  | luminous-supreme-control |      48.5 |            53.6 |        2048 |
| AnthropicProvider   | claude-instant-v1      |        1.63 |            5.51 |        9000 |
| AnthropicProvider   | claude-v1              |       11.02 |           32.68 |        9000 |
| CohereProvider      | command                |        25.0 |            25.0 |        8192 |
| CohereProvider      | command-nightly        |        25.0 |            25.0 |        8192 |
| GoogleProvider      | chat-bison             |         0.5 |             0.5 |        2048 |
| HuggingfaceHub      | hf_pythia              |         0.0 |             0.0 |        2048 |
| OpenAIProvider      | gpt-3.5-turbo          |         2.0 |             2.0 |        4000 |
| OpenAIProvider      | gpt-4                  |        30.0 |            60.0 |        8000 |

Useful links:
OpenAI documentation
Anthropic documentation
AI21 documentation
Cohere documentation
Aleph Alpha documentation
Google Generateive AI documentation Google Vertex AI documentation

Using Google Vertex LLM models

  1. (Set up a GCP account and create a project)
  2. Enable Vertex AI APIs in your GCP project - https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com
  3. Install gcloud CLI tool - https://cloud.google.com/sdk/docs/install
  4. Set up Application Default Credentials - https://cloud.google.com/docs/authentication/provide-credentials-adc#how-to
  5. Now you should be able to init Google LLM
model = llms.init('chat-bison')
result = model.complete("hello!")

Using Local Ollama LLM models

PyLLMs supports locally installed Ollama models.

To use your Ollama models:

  1. Ensure Ollama is running (as well as reachable at localhost:11434) and you've pulled the model you would like to use.

  2. Get the name of the LLM you would like to use.

Run:

ollama list

to get a list of installed models.

NAME            	ID   SIZE  	MODIFIED
tinyllama:latest	...  637 MB	...
  1. Initialize PyLLMs as you would any other model:
model = llms.init("tinyllama:latest")
result = model.complete("hello!")

where tinyllama:latest is the model name of an installed model.

License

This project is licensed under the MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyllms-0.5.2.tar.gz (28.4 kB view details)

Uploaded Source

Built Distribution

pyllms-0.5.2-py3-none-any.whl (32.1 kB view details)

Uploaded Python 3

File details

Details for the file pyllms-0.5.2.tar.gz.

File metadata

  • Download URL: pyllms-0.5.2.tar.gz
  • Upload date:
  • Size: 28.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.0

File hashes

Hashes for pyllms-0.5.2.tar.gz
Algorithm Hash digest
SHA256 e9db18f489ece6005d2f6908d541539a6e6d77e7c6175de7d6d744c4fd890a70
MD5 e7be79d4673746950c44f64ef19b7d7f
BLAKE2b-256 522c991d66de166bbbbded2cf2fc243d1da62d4705a4c32c99743fd2c446c6b1

See more details on using hashes here.

File details

Details for the file pyllms-0.5.2-py3-none-any.whl.

File metadata

  • Download URL: pyllms-0.5.2-py3-none-any.whl
  • Upload date:
  • Size: 32.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.0

File hashes

Hashes for pyllms-0.5.2-py3-none-any.whl
Algorithm Hash digest
SHA256 c2c91a8771d9edde47d43cd6ce1d785ffd2a99313183ba9a4f5a3d4c036118ce
MD5 13e5da93e6417fb2e0597ec58699470f
BLAKE2b-256 dbd5659da53c794b85f878e0712389171ebb6e8a374037c88869cd433d328294

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page