Skip to main content

protoprompt

CI Python 3.11–3.13 License: MIT

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

Документация · English · Примеры · Каталог интеграций · Roadmap · Как добавить интеграцию · Changelog

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

Telegram-бот вспоминает старый факт и показывает provenance

Эталонный Telegram-бот сохраняет длинную память в SQLite, работает с OpenAI или Ollama и объясняет каждый recall через /why.

Что решает protoprompt

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

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

Возможность Что входит
RAG чанкинг, индексация, top-k поиск, фильтры, reranking и provenance
Память сессии эвристическое или LLM-сжатие длинных диалогов
Профиль извлечение, merge, optimistic locking и SQLite-хранилище
Токен-бюджет жёсткий лимит, приоритеты слоёв и отчёт об обрезке
Хранилища in-memory, SQLite, ChromaDB, Qdrant, pgvector, Elasticsearch/OpenSearch и Redis services
LLM и embeddings OpenAI, Anthropic, Google GenAI, Bedrock, Ollama и локальные модели
Секреты encrypted SQLite, AWS Secrets Manager и GCP Secret Manager
Connectivity MCP, OpenAI Agents SDK, LangGraph, PydanticAI, LlamaIndex, aiogram 3 и FastAPI
Данные bounded readers для text/source/HTML/PDF/DOCX и framework converters

Ядро не имеет обязательных сторонних зависимостей. Интеграции подключаются через 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[mcp]"
pip install "protoprompt[agents]"
pip install "protoprompt[langgraph]"
pip install "protoprompt[telegram,ollama]"
pip install "protoprompt[anthropic]"
pip install "protoprompt[google]"
pip install "protoprompt[bedrock]"
pip install "protoprompt[pydanticai]"
pip install "protoprompt[llamaindex]"
pip install "protoprompt[postgres,redis,otel]"
pip install "protoprompt[elasticsearch]"  # или opensearch
pip install "protoprompt[documents,fastapi]"
pip install "protoprompt[aws-secrets]"    # или gcp-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,qdrant,dev]"
pytest
python scripts/build_docs.py --clean

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

Лицензия

MIT

Metadata

Release files for protoprompt 0.6.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 protoprompt 0.6.1
File Size Uploaded
protoprompt-0.6.1.tar.gz 4.4 MB Details

Built distribution (wheel)

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

Total release size: 4.6 MB

Release files / protoprompt-0.6.1.tar.gz

Download URL protoprompt-0.6.1.tar.gz
Size 4.4 MB
Tags Source
SHA-256 checksum
How to use checksums
e495dcc6aa394a11980d056b2b09be9394b863ab4dbda3c3a8f8cef9a7d78870
BLAKE2b-256 checksum
How to use checksums
1da9c882645085f4076b5bd9185bdb26f051bae492741a90758cfc45a471586c
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 30, 2026.

Transparency log

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

Download URL protoprompt-0.6.1-py3-none-any.whl
Size 162.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2718334909102b02c9df07ed642bf81c1d4708393b01c791fe1a921d8c2e7188
BLAKE2b-256 checksum
How to use checksums
621ba628ef1bd5a6ffcc100cca0a1350a2a5a7121dda43c3d7e92ce31e1bdfa4
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 30, 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

This release

0.6.1 This release

2 release files

0.6.0

2 release files

0.3.0

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