跳转到主要内容

一种提示编程语言

项目描述

banks

PyPI - Version PyPI - Python Version Coverage Status

PyPI Release test docs

Hatch project Ruff Checked with mypy License - MIT

Banks是一位语言学家教授,将帮助您使用模板语言生成有意义的LLM提示。如果您仍在使用f-strings来完成这项工作,请继续阅读。

文档可在此处找到。


目录

安装

pip install banks

功能

提示对于任何LLM应用程序的成功至关重要,Banks专注于其生命周期中的特定领域。

  • :blue_book: 模板化:Banks提供了构建提示文本和聊天消息的通用蓝图的工具和函数。
  • :tickets: 版本控制和元数据:Banks支持将元数据附加到提示,以便轻松管理,版本控制是第一公民。
  • :file_cabinet: 管理:Banks提供了将提示及其元数据存储在磁盘上的方法。

示例

创建博客写作提示

给定一个通用模板来指导LLM生成博客文章,我们使用Banks生成实际提示,主题为“复古游戏计算”。

from banks import Prompt


p = Prompt("Write a 500-word blog post on {{ topic }}.\n\nBlog post:")
topic = "retrogame computing"
print(p.text({"topic": topic}))

这将打印以下文本,可以直接粘贴到Chat-GPT中

Write a 500-word blog post on retrogame computing.

Blog post:

相同的提示可以写成聊天消息的形式

prompt_text = """{% chat role="system" %}
I want you to act as a title generator for written pieces.
{% endchat %}

{% chat role="user" %}
Write a 500-word blog post on {{ topic }}.

Blog post:
{% endchat %}"""

p = Prompt(prompt_text)
print(p.chat_messages({"topic":"prompt engineering"}))

这将输出以下内容

[
  ChatMessage(role='system', content='I want you to act as a title generator for written pieces.\n'),
  ChatMessage(role='user', content='Write a 500-word blog post on .\n\nBlog post:\n')
]

创建总结提示

我们可以在提示本身中不硬编码要总结的内容,而是从通用模板中注入它

from banks import Prompt


prompt_template = """
Summarize the following documents:
{% for document in documents %}
{{ document }}
{% endfor %}
Summary:
"""

# In a real-world scenario, these would be loaded as external resources from files or network
documents = [
    "A first paragraph talking about AI",
    "A second paragraph talking about climate change",
    "A third paragraph talking about retrogaming"
]

p = Prompt(prompt_template)
print(p.text({"documents": documents}))

生成的提示

Summarize the following documents:

A first paragraph talking about AI

A second paragraph talking about climate change

A third paragraph talking about retrogaming

Summary:

在处理模板时对文本进行词形还原

银行工具包提供了预定义的过滤器,您可以在生成提示之前使用这些过滤器来处理数据。例如,您想在总结文档之前使用词形还原器,首先您需要安装simplemma

pip install simplemma

然后您可以在模板中使用lemmatize过滤器,如下所示

from banks import Prompt


prompt_template = """
Summarize the following document:
{{ document | lemmatize }}
Summary:
"""

p = Prompt(prompt_template)
print(p.text({"document": "The cats are running"}))

输出结果将是

Summarize the following document:
the cat be run
Summary:

使用LLM在渲染提示的同时生成文本

有时,在少量提示中让另一个LLM为您生成示例可能很有用。如果您在名为OPENAI_API_KEY的环境变量中存储了有效的OpenAI API密钥,您可以要求银行执行类似以下操作(注意:我们可以使用注释来标记提示,{# ... #}中的内容将在最终的提示中删除)

from banks import Prompt


prompt_template = """
Generate a tweet about the topic {{ topic }} with a positive sentiment.

{#
    This is for illustration purposes only, there are better and cheaper ways
    to generate examples for a few-shots prompt.
#}
Examples:
{% for number in range(3) %}
- {% generate "write a tweet with positive sentiment" "gpt-3.5-turbo" %}
{% endfor %}
"""

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

输出结果将类似于以下内容

Generate a tweet about the topic climate change with a positive sentiment.


Examples:

- "Feeling grateful for the amazing capabilities of #GPT3.5Turbo! It's making my work so much easier and efficient. Thank you, technology!" #positivity #innovation

- "Feeling grateful for all the opportunities that come my way! With #GPT3.5Turbo, I am able to accomplish tasks faster and more efficiently. #positivity #productivity"

- "Feeling grateful for all the wonderful opportunities and experiences that life has to offer! #positivity #gratitude #blessed #gpt3.5turbo"

如果您将银行的输出粘贴到ChatGPT中,您将得到类似以下内容

Climate change is a pressing global issue, but together we can create positive change! Let's embrace renewable energy, protect our planet, and build a sustainable future for generations to come. 🌍💚 #ClimateAction #PositiveFuture

[!IMPORTANT] generate扩展在内部使用LiteLLM,并且如果您已经设置了正确的环境变量,您可以使用支持模型提供者中的任何模型。

[!NOTE] 银行使用缓存来避免为具有相同上下文和模板生成重复的文本。默认情况下,缓存是内存中的,但它可以被自定义。

元:创建提示并生成其响应

我们可以利用Jinja的宏系统来生成提示,将结果发送到OpenAI,并获取响应。让我们回顾一下博客写作的例子

from banks import Prompt

prompt_template = """
{% from "banks_macros.jinja" import run_prompt with context %}

{%- call run_prompt() -%}
Write a 500-word blog post on {{ topic }}

Blog post:
{%- endcall -%}
"""

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

上面的代码段不会打印提示,而是会生成提示文本

Write a 500-word blog post on climate change

Blog post:

然后使用generate扩展将其发送到OpenAI,最终返回其响应

Climate change is a phenomenon that has been gaining attention in recent years...
...

元元:处理LLM响应

在从提示模板生成响应时,我们可以进一步处理LLM的响应,将其分配给变量并对其应用过滤器

from banks import Prompt

prompt_template = """
{% from "banks_macros.jinja" import run_prompt with context %}

{%- set prompt_result %}
{%- call run_prompt() -%}
Write a 500-word blog post on {{ topic }}

Blog post:
{%- endcall -%}
{%- endset %}

{# nothing is returned at this point: the variable 'prompt_result' contains the result #}

{# let's use the prompt_result variable now #}
{{ prompt_result | upper }}
"""

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

LLM的最终答案将被打印出来,这次全部是大写。

重用注册表中的模板

我们可以像上一个例子那样从注册表中加载提示模板而不是将其硬编码到Python代码中。为了方便,银行附带了几种您可以使用来存储模板的注册类型。例如,DirectoryTemplateRegistry可以从文件系统中的目录加载模板。假设您当前路径中有一个名为templates的文件夹,并且该文件夹中包含一个名为blog.jinja的文件。您可以像这样加载提示模板

from banks import Prompt
from banks.registries import DirectoryTemplateRegistry

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

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

异步支持

要在asyncio循环中运行银行,您必须做两件事

  1. 设置环境变量BANKS_ASYNC_ENABLED=true
  2. 使用具有可等待的run方法的AsyncPrompt类。

示例

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())

许可证

banks是根据MIT许可证分发的。

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分布

banks-1.0.0.tar.gz (22.9 kB 查看哈希值)

上传时间

构建分布

banks-1.0.0-py3-none-any.whl (20.8 kB 查看哈希值)

上传时间 Python 3

由以下组织支持