Skip to main content

banks

PyPI - Version PyPI - Python Version Coverage Status

PyPI Release test docs

Hatch project Ruff Checked with mypy License - MIT

Banks is the linguist professor who will help you generate meaningful LLM prompts using a template language that makes sense. If you're still using f-strings for the job, keep reading.

Docs are available here.

Banks Logo


Table of Contents

Installation

pip install banks

# install optional deps; litellm, redis
pip install "banks[all]"

Features

Prompts are instrumental for the success of any LLM application, and Banks focuses around specific areas of their lifecycle:

  • :orange_book: Templating: Banks provides tools and functions to build prompts text and chat messages from generic blueprints.
  • :tickets: Versioning and metadata: Banks supports attaching metadata to prompts to ease their management, and versioning is first-class citizen.
  • :file_cabinet: Management: Banks provides ways to store prompts on disk along with their metadata.

Cookbook

Examples

For a more extensive set of code examples, see the documentation page.

:point_right: Render a prompt template as chat messages

You'll find yourself feeding an LLM a list of chat messages instead of plain text more often than not. Banks will help you remove the boilerplate by defining the messages already at the prompt level.

from banks import Prompt


prompt_template = """
{% chat role="system" %}
You are a {{ persona }}.
{% endchat %}

{% chat role="user" %}
Hello, how are you?
{% endchat %}
"""

p = Prompt(prompt_template)
print(p.chat_messages({"persona": "helpful assistant"}))

# Output:
# [
#   ChatMessage(role='system', content=[
#      ContentBlock(type=<ContentBlockType.text: 'text'>, cache_control=None, text='You are a helpful assistant.',
#                  image_url=None, input_audio=None, input_video=None, input_document=None)
#   ], tool_call_id=None, name=None),
#   ChatMessage(role='user', content=[
#      ContentBlock(type=<ContentBlockType.text: 'text'>, cache_control=None, text='Hello, how are you?',
#                  image_url=None, input_audio=None, input_video=None, input_document=None)
#   ], tool_call_id=None, name=None)
# ]

:point_right: Add images to the prompt for vision models

If you're working with a multimodal model, you can include images directly in the prompt, and Banks will do the job needed to upload them when rendering the chat messages:

import litellm

from banks import Prompt

prompt_template = """
{% chat role="user" %}
Guess where is this place.
{{ picture | image }}
{%- endchat %}
"""

pic_url = (
    "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4d/CorcianoMar302024_01.jpg/1079px-CorcianoMar302024_01.jpg"
)
# Alternatively, load the image from disk
# pic_url = "/Users/massi/Downloads/CorcianoMar302024_01.jpg"

p = Prompt(prompt_template)
as_dict = [msg.model_dump(exclude_none=True) for msg in p.chat_messages({"picture": pic_url})]
r = litellm.completion(model="gpt-4-vision-preview", messages=as_dict)

print(r.choices[0].message.content)

:point_right: Use a LLM to generate a text while rendering a prompt

Sometimes it might be useful to ask another LLM to generate examples for you in a few-shots prompt. Provided you have a valid OpenAI API key stored in an env var called OPENAI_API_KEY you can ask Banks to do something like this (note we can annotate the prompt using comments - anything within {# ... #} will be removed from the final prompt):

from banks import Prompt


prompt_template = """
{% set examples %}
{% completion model="gpt-3.5-turbo-0125" %}
  {% chat role="system" %}You are a helpful assistant{% endchat %}
  {% chat role="user" %}Generate a bullet list of 3 tweets with a positive sentiment.{% endchat %}
{% endcompletion %}
{% endset %}

{# output the response content #}
Generate a tweet about the topic {{ topic }} with a positive sentiment.
Examples:
{{ examples }}
"""

p = Prompt(prompt_template)
print(p.text({"topic": "climate change"}))

The output would be something similar to the following:

Generate a tweet about the topic climate change with a positive sentiment.
Examples:
- "Feeling grateful for the sunshine today! 🌞 #thankful #blessed"
- "Just had a great workout and feeling so energized! 💪 #fitness #healthyliving"
- "Spent the day with loved ones and my heart is so full. 💕 #familytime #grateful"

[!IMPORTANT] The completion extension uses LiteLLM under the hood, and provided you have the proper environment variables set, you can use any model from the supported model providers.

[!NOTE] Banks uses a cache to avoid generating text again for the same template with the same context. By default the cache is in-memory but it can be customized.

:point_right: Function calling directly from the prompt

Banks provides a filter tool that can be used to convert a callable passed to a prompt into an LLM function call. Docstrings are used to describe the tool and its arguments, and during prompt rendering Banks will perform all the LLM roundtrips needed in case the model wants to use a tool within a {% completion %} block. For example:

import platform

from banks import Prompt


def get_laptop_info():
    """Get information about the user laptop.

    For example, it returns the operating system and version, along with hardware and network specs."""
    return str(platform.uname())


p = Prompt("""
{% set response %}
{% completion model="gpt-3.5-turbo-0125" %}
    {% chat role="user" %}{{ query }}{% endchat %}
    {{ get_laptop_info | tool }}
{% endcompletion %}
{% endset %}

{# the variable 'response' contains the result #}

{{ response }}
""")

print(p.text({"query": "Can you guess the name of my laptop?", "get_laptop_info": get_laptop_info}))
# Output:
# Based on the information provided, the name of your laptop is likely "MacGiver."

:point_right: Use prompt caching from Anthropic

Several inference providers support prompt caching to save time and costs, and Anthropic in particular offers fine-grained control over the parts of the prompt that we want to cache. With Banks this is as simple as using a template filter:

prompt_template = """
{% chat role="user" %}
Analyze this book:

{# Only this part of the chat message (the book content) will be cached #}
{{ book | cache_control("ephemeral") }}

What is the title of this book? Only output the title.
{% endchat %}
"""

p = Prompt(prompt_template)
print(p.chat_messages({"book": "This is a short book!"}))

# Output:
# [
#   ChatMessage(role='user', content=[
#      ContentBlock(type='text', text='Analyze this book:\n\n'),
#      ContentBlock(type='text', cache_control=CacheControl(type='ephemeral'), text='This is a short book!'),
#      ContentBlock(type='text', text='\n\nWhat is the title of this book? Only output the title.\n')
#   ])
# ]

The output of p.chat_messages() can be fed to the Anthropic client directly.

Reuse templates from registries

We can get the same result as the previous example loading the prompt template from a registry instead of hardcoding it into the Python code. For convenience, Banks comes with a few registry types you can use to store your templates. For example, the DirectoryTemplateRegistry can load templates from a directory in the file system. Suppose you have a folder called templates in the current path, and the folder contains a file called blog.jinja. You can load the prompt template like this:

from banks import Prompt
from banks.registries import DirectoryTemplateRegistry

registry = DirectoryTemplateRegistry(populated_dir)
prompt = registry.get(name="blog")

print(prompt.text({"topic": "retrogame computing"}))

Async support

To run banks within an asyncio loop you have to do two things:

  1. set the environment variable BANKS_ASYNC_ENABLED=true.
  2. use the AsyncPrompt class that has an awaitable run method.

Example:

from banks import AsyncPrompt


async def main():
    p = AsyncPrompt("Write a blog article about the topic {{ topic }}")
    result = await p.text({"topic": "AI frameworks"})
    print(result)


asyncio.run(main())

Contributing

Contributions are very welcome, the CONTRIBUTING.md file contains all the details about how to do it.

License

banks is distributed under the terms of the MIT license.

Metadata

Release files for banks 2.5.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for banks 2.5.1
File Size Uploaded Provenance Actions
banks-2.5.1.tar.gz 196.4 kB Without provenance Details for banks-2.5.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for banks 2.5.1
File Interpreter ABI Platform Actions
banks-2.5.1-py3-none-any.whl Python 3 none any Details for banks-2.5.1-py3-none-any.whl

Total release size: 235.9 kB

Release files / banks-2.5.1.tar.gz

Download URL banks-2.5.1.tar.gz
Size 196.4 kB
Tags Source
SHA-256 checksum
How to use checksums
a7ca5c250b605ae90cfd6e4ca5dd6ce2ee377d5d59021b6feba44e345910026d
BLAKE2b-256 checksum
How to use checksums
f0920449c32e718c10e4af40a3e040c830a77cdaeec6e9066622ee60e4c93e6e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via Hatch/1.18.0 {"ci":true,"cpu":"x86_64","distro":{"id":"noble","libc":{"lib":"glibc","version":"2.39"},"name":"Ubuntu","version":"24.04"},"implementation":{"name":"CPython","version":"3.12.3"},"installer":{"name":"hatch","version":"1.18.0"},"openssl_version":"OpenSSL 3.0.13 30 Jan 2024","python":"3.12.3","system":{"name":"Linux","release":"6.17.0-1022-azure"}} HTTPX2/2.12.0

Release files / banks-2.5.1-py3-none-any.whl

Download URL banks-2.5.1-py3-none-any.whl
Size 39.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b7c91365626bab4b46197d24ce04cd69540730ed669a50a399f240318ba3dcfb
BLAKE2b-256 checksum
How to use checksums
3f6f06c0824ee2611de47a0fc731fa57f6042d3f573025d9f504adfd65e50d51
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via Hatch/1.18.0 {"ci":true,"cpu":"x86_64","distro":{"id":"noble","libc":{"lib":"glibc","version":"2.39"},"name":"Ubuntu","version":"24.04"},"implementation":{"name":"CPython","version":"3.12.3"},"installer":{"name":"hatch","version":"1.18.0"},"openssl_version":"OpenSSL 3.0.13 30 Jan 2024","python":"3.12.3","system":{"name":"Linux","release":"6.17.0-1022-azure"}} HTTPX2/2.12.0

Security for banks 2.5.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.5.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page