PyPriompt: Python Library for Priority-Based Prompt Design

This repository profile is provided by osrepos.com, an open source repository discovery platform.

PyPriompt: Python Library for Priority-Based Prompt Design

Summary

PyPriompt is a Python library for designing prompts, inspired by web design libraries like React and FastHTML. It intelligently manages context windows by using priorities to decide what information to include in the prompt, ensuring efficient use of token limits. This tool helps developers create dynamic and adaptable prompts for large language models.

Repository Information

Analyzed by OSRepos on November 27, 2025

Topics

Click on any tag to explore related repositories

Use at your own risk

OSRepos shares public repositories for knowledge and discovery only. Any installation, execution, configuration, or use of code from these repositories is the user's own responsibility. Always review the repository, source code, dependencies, licenses, and security implications before running or installing anything. OSRepos is not responsible for issues, damages, or losses resulting from third-party repositories.

Introduction

PyPriompt (Python + priority + prompt) is a Python port of the Priompt library, remixed with FastHTML. It introduces a structured approach to prompt design, allowing developers to manage the context window of large language models (LLMs) by assigning priorities to different parts of the prompt. This ensures that the most critical information is always included, even when facing token limits. The library draws inspiration from web design frameworks, aiming to bring similar component-based development principles to prompt engineering. You can read more about the motivation behind this approach in the Prompt Design article.

Installation

PyPriompt can be easily installed using various Python package managers:

uv add priompt
rye add priompt
poetry add priompt
pip install priompt

Examples

Prompts in PyPriompt are rendered from Python components, allowing for dynamic and flexible prompt construction. Here's an example demonstrating a simple chat component that manages message history with priorities:

from priompt import (
  component, # Decorator for custom components
  # Standard components
  SystemMessage, # For system messages
  AssistantMessage, # For assistant messages
  UserMessage, # For user messages
  # Priompt components
  Empty, # For reserving empty space
  Scope, # For setting priorities
  # For rendering prompts to OpenAI chat messages or a string
  render,
  O200KTokenizer, # For GPT-4o, GPT-4o-mini
)

@component
def chat(name: str, message: str, history: list[dict[str, str]]):
    capitalized_name = name[0].upper() + name[1:]

    return [
        SystemMessage(f"The user's name is {capitalized_name}. Please respond to them kindly."),
        *[
            Scope(
                UserMessage(m["message"]) if m["role"] == "user" else AssistantMessage(m["message"]),
                prel=i,
            )
            for i, m in enumerate(history)
        ],
        UserMessage(message),
        Empty(1000),
    ]

messages = render(
    chat(
        name="cyrus",
        message="What is the answer to life, the universe, and everything?",
        history=[
            {"role": "user", "message": "Hello!"},
            {"role": "assistant", "message": "Hello! How can I help you today?"},
        ],
    ),
    {
        "token_limit": 8192, # However many tokens you want to limit to
        "tokenizer": O200KTokenizer,
    }
)

openai.chat.completions.create(
    ...
    messages=messages,
)

In this example, the chat component defines a prompt structure. The SystemMessage and the latest UserMessage are always included. Historical messages are wrapped in Scope with prel=i, meaning later messages (higher i) are prioritized over earlier ones. The render function then processes this component, respecting the token_limit and including as many high-priority items as possible.

Why Use PyPriompt

PyPriompt offers a powerful way to manage LLM prompts, especially when dealing with dynamic content and strict token limits. Its core principles revolve around component-based design and priority-driven content inclusion.

Key Principles:

  • Component-Based Prompt Design: Just like in web frameworks, you can create reusable Python components to build complex prompts, making them modular and maintainable.
  • Priority System: Each child within a component can be assigned an absolute (p) or relative (prel) priority. Higher priority items are favored for inclusion when token limits are approached.
  • Token Limit Optimization: The renderer guarantees that it will find the minimum priority cutoff such that the prompt's total token count stays within the specified limit, maximizing the included relevant information.

Building Blocks:

PyPriompt provides several specialized components to control prompt structure and content:

  • Scope: Sets priorities for its children.
  • First: Includes the first child with sufficiently high priority, useful for fallbacks.
  • Empty: Reserves a specified number of tokens, useful for ensuring space for model generation.
  • Capture: Captures and parses output directly within the prompt.
  • Isolate: Isolates a section with its own token limit, useful for caching or guaranteeing specific content.
  • Br: Forces a token break, useful for precise tokenization control.
  • Config: Specifies common configuration properties like stop tokens or maxResponseTokens.

Built-in Components for LLMs:

  • UserMessage, AssistantMessage, SystemMessage: For constructing standard chat-based prompts.
  • Image: For incorporating images into multimodal prompts.
  • Tools: For defining tools that the AI can call using a JSON schema.

Advanced Features:

  • Callbacks (on_eject, on_include): Execute custom logic when a scope is either excluded or included in the final prompt, allowing for adaptive prompt behavior.
  • Sourcemaps: When enabled, the renderer can compute a map between prompt characters and their originating JSX tree parts, aiding in debugging and caching strategies.

Important Considerations (Caveats):

While powerful, it's important to be aware of certain aspects:

  • Overusing priorities can sometimes be an anti-pattern, potentially making prompts harder to cache.
  • The current version supports around 10K scopes reasonably fast, which is sufficient for most use cases.
  • For latency-critical prompts, monitoring performance in a preview dashboard is recommended.
  • The renderer's token limit optimization is generally accurate but may have slight inaccuracies in specific edge cases involving First components.

Links

Related repositories

Similar repositories that may be relevant next.

PromptBench: A Unified Framework for LLM Evaluation and Robustness

PromptBench: A Unified Framework for LLM Evaluation and Robustness

July 1, 2026

PromptBench is a comprehensive Python library designed for the evaluation and understanding of Large Language Models (LLMs). It provides a unified framework for assessing model performance, exploring various prompt engineering techniques, and evaluating robustness against adversarial attacks. This tool empowers researchers to conduct in-depth analyses of LLMs across diverse datasets and models.

large-language-modelsLLM Evaluationprompt-engineering
LangTest: A Comprehensive Library for Safe & Effective Language Models

LangTest: A Comprehensive Library for Safe & Effective Language Models

June 30, 2026

LangTest is an open-source Python library dedicated to ensuring the safety and effectiveness of language models. It offers a comprehensive framework for testing model quality, covering robustness, bias, fairness, and accuracy across various NLP tasks and LLM providers. With LangTest, developers can generate and execute over 60 distinct test types with just one line of code, promoting responsible AI development.

ai-safetyai-testinglarge-language-models
EvalPlus: Rigorous Evaluation for LLM-Synthesized Code

EvalPlus: Rigorous Evaluation for LLM-Synthesized Code

June 30, 2026

EvalPlus is a robust framework designed for the rigorous evaluation of code generated by Large Language Models (LLMs). It extends standard benchmarks like HumanEval and MBPP with significantly more tests, offering precise assessment of code correctness and efficiency. This tool is crucial for developers and researchers aiming to thoroughly validate LLM-synthesized code.

benchmarklarge-language-modelsprogram-synthesis
AgentEvals: Robust Evaluation Tools for LLM Agent Trajectories

AgentEvals: Robust Evaluation Tools for LLM Agent Trajectories

June 30, 2026

AgentEvals is a powerful open-source package from LangChain designed to simplify the evaluation of agentic applications. It provides a collection of ready-made evaluators and utilities, with a particular focus on analyzing agent trajectories, the intermediate steps an agent takes to solve problems. This helps developers understand and improve the reliability and performance of their LLM agents.

PythonLLMAgents

Source repository

Open the original repository on GitHub.

View on GitHub
OS
OSRepos

Analysis and discovery of open source repositories. Find interesting projects and follow their updates.

Monitor your website with YourWebsiteScore

OSRepos shares public repositories for knowledge and discovery only. Any installation, execution, configuration, or use of third-party repository code is at your own risk. Always review source code, dependencies, licenses, and security implications before running anything.

© 2025 OSRepos. Built with Nuxt 3 and lots of ❤️