Skip to main content

protoprompt

CI Python 3.11–3.13 License: MIT

Контекстный движок для LLM-приложений: RAG, память диалога, профиль пользователя и строгий токен-бюджет через единый Python API.

Документация · English · Примеры · Changelog

Проект находится в alpha-стадии. Публичный API уже покрыт тестами, но до версии 1.0 возможны изменения контрактов.

Что решает protoprompt

LLM обычно нужна не просто история чата, а несколько разных видов контекста: найденные документы, важные факты из прошлых сессий, профиль пользователя и исходный system prompt. Если собирать всё вручную, логика поиска, приоритетов и обрезки быстро расползается по приложению.

protoprompt собирает эти слои в одном месте и возвращает не только готовый промпт, но и provenance — какие RAG-чанки, блоки памяти и данные профиля были использованы.

Возможность Что входит
RAG чанкинг, индексация, top-k поиск, фильтры, reranking и provenance
Память сессии эвристическое или LLM-сжатие длинных диалогов
Профиль извлечение, merge, optimistic locking и SQLite-хранилище
Токен-бюджет жёсткий лимит, приоритеты слоёв и отчёт об обрезке
Хранилища in-memory, SQLite, ChromaDB и Qdrant
LLM и embeddings OpenAI, Ollama, OpenAI-compatible HTTP и локальные модели
Секреты scoped vault с Fernet-шифрованием, TTL и ротацией ключа

Ядро не имеет обязательных сторонних зависимостей. Интеграции подключаются через extras и не импортируются, пока не понадобятся.

Установка

pip install protoprompt

# Частые варианты
pip install "protoprompt[openai,tiktoken]"
pip install "protoprompt[ollama]"
pip install "protoprompt[chroma]"
pip install "protoprompt[qdrant]"
pip install "protoprompt[local]"       # sentence-transformers
pip install "protoprompt[fastembed]"
pip install "protoprompt[secrets]"

Для работы из текущей ветки:

pip install "protoprompt @ git+https://github.com/Idxeed/protoprompt.git@master"

Требуется Python 3.11 или новее.

Быстрый старт

Пример полностью локальный: сеть, API-ключ и сторонняя векторная БД не нужны.

import asyncio

from protoprompt import ContextBuilder, ContextInput, InMemStore


class DemoLLM:
    async def embed(self, texts, model=""):
        # В приложении замените на OpenAIClient, OllamaClient
        # или локальный embedding-клиент.
        return [[1.0, 0.0] for _ in texts]

    async def chat(self, messages, model="", **options):
        return "demo"


async def main():
    llm = DemoLLM()
    store = InMemStore()
    chunks = [
        "protoprompt объединяет RAG, память сессии и профиль пользователя.",
        "Токеновый бюджет не позволяет итоговому контексту превысить лимит.",
    ]
    store.add("guide", chunks, await llm.embed(chunks))

    builder = ContextBuilder(store, llm)
    messages = await builder.build_messages(
        ContextInput(
            query="Что умеет protoprompt?",
            system_prompt="Отвечай кратко и только по контексту.",
            doc_ids=["guide"],
            include_session=False,
        ),
        user_message="Что умеет protoprompt?",
    )

    print(messages)  # готовый OpenAI-style список system + user


asyncio.run(main())

Более реалистичные рецепты находятся в examples/: Ollama RAG, OpenAI с токен-бюджетом, локальные embeddings, сжатие сессии, профиль и зашифрованный vault.

Как устроена сборка контекста

запрос ─┬─> RAG по документам ───────┐
        ├─> память текущей сессии ───┤
        ├─> профиль пользователя ────┼─> ContextBuilder ─> ContextOutput
        └─> исходный system prompt ──┘          │
                                                └─ provenance + budget report

Основные контракты намеренно небольшие:

  • StoreProtocol / AsyncStoreProtocol — синхронное или асинхронное векторное хранилище;
  • LLMClientProtocol — chat() и embed();
  • StrategyProtocol — стратегия сжатия диалога;
  • TokenCounter — подсчёт токенов для конкретной модели.

Благодаря этому встроенные адаптеры можно заменить своими без переписывания сборщика контекста.

Основные точки входа

from protoprompt import (
    ContextBuilder,
    TokenBudgetedContextBuilder,
    Pipeline,
    ProfileManager,
    InMemStore,
    SqliteStore,
)

from protoprompt.rag import DocumentIndexer, Retriever
from protoprompt.secrets import EncryptedSqliteSecretStore, SecretAccess
from protoprompt.integrations import OpenAIClient, OllamaClient, QdrantStore

Полный API и подробные руководства:

Экспериментальный coding-agent

В монорепозитории есть CLI поверх protoprompt.agent.WorkingMemory:

pip install -e "apps/agent-cli[ollama]"
pp-agent /path/to/project

Он поддерживает сессии, hot/cold memory, план-режим и подтверждение опасных инструментов. Подробнее — в apps/agent-cli/README.md.

Разработка

git clone https://github.com/Idxeed/protoprompt.git
cd protoprompt
python -m venv .venv

# Windows
.venv\Scripts\activate

# Linux / macOS
source .venv/bin/activate

pip install -e ".[chroma,dev]"
pytest
python scripts/build_docs.py --clean

CI проверяет Python 3.11–3.13, интеграционные тесты, CLI, содержимое wheel и обе строгие сборки документации.

Лицензия

MIT

Metadata

Release files for protoprompt 0.3.0

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

Source distribution (sdist)

Source distribution for protoprompt 0.3.0
File Size Uploaded
protoprompt-0.3.0.tar.gz 163.1 kB Details

Built distribution (wheel)

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

Total release size: 252.3 kB

Release files / protoprompt-0.3.0.tar.gz

Download URL protoprompt-0.3.0.tar.gz
Size 163.1 kB
Tags Source
SHA-256 checksum
How to use checksums
84bd630184df8ba3f1ea98c20ab070f8444e8f96d8af21ae91cc56e8fdf0cf24
BLAKE2b-256 checksum
How to use checksums
0136917cd410dde9653a574bc4b7abb1aa848df4dacf10e55eb9c87035d81c4e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 28, 2026.

Transparency log

Release files / protoprompt-0.3.0-py3-none-any.whl

Download URL protoprompt-0.3.0-py3-none-any.whl
Size 89.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
631a09b827b1b7da50ebb6bd5121007c5ae1661e9dae46d6471f5fe2b334da7e
BLAKE2b-256 checksum
How to use checksums
8e133bc3fc766b9272e344d049e56536cc9e2815ba17f61588ec4b8575f43a02
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Aug 28, 2026.

Transparency log

Release history Release notifications | RSS feed

0.20.0

2 release files

0.19.0

2 release files

0.18.0

2 release files

0.17.0

2 release files

0.16.1

2 release files

0.15.0

2 release files

0.14.0

2 release files

0.13.0

2 release files

0.12.0

2 release files

0.11.0

2 release files

0.10.0

2 release files

0.9.0

2 release files

0.8.0

2 release files

0.7.0

2 release files

0.6.1

2 release files

0.6.0

2 release files

This release

0.3.0 This release

2 release files

0.1.0

2 release files

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