Metadata-Version: 2.4
Name: protoprompt
Version: 0.3.0
Summary: Layered context builder for LLM prompts: RAG + compressed session memory + user profile
Author: EnergoAI Hub
Maintainer: EnergoAI Hub
License-Expression: MIT
Project-URL: Homepage, https://github.com/Idxeed/protoprompt
Project-URL: Documentation, https://idxeed.github.io/protoprompt/
Project-URL: Source, https://github.com/Idxeed/protoprompt
Project-URL: Issues, https://github.com/Idxeed/protoprompt/issues
Project-URL: Changelog, https://github.com/Idxeed/protoprompt/blob/master/CHANGELOG.md
Keywords: llm,rag,prompt,context,embedding
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: chroma
Requires-Dist: chromadb<0.6,>=0.5; extra == "chroma"
Provides-Extra: tiktoken
Requires-Dist: tiktoken>=0.5; extra == "tiktoken"
Provides-Extra: http
Requires-Dist: httpx>=0.27; extra == "http"
Provides-Extra: ollama
Requires-Dist: httpx>=0.27; extra == "ollama"
Provides-Extra: openai
Requires-Dist: openai>=1.40; extra == "openai"
Provides-Extra: qdrant
Requires-Dist: qdrant-client>=1.12; extra == "qdrant"
Provides-Extra: fastembed
Requires-Dist: fastembed>=0.4; extra == "fastembed"
Provides-Extra: local
Requires-Dist: sentence-transformers>=3.0; extra == "local"
Provides-Extra: secrets
Requires-Dist: cryptography>=42; extra == "secrets"
Requires-Dist: keyring>=24; extra == "secrets"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-asyncio>=0.24; extra == "dev"
Requires-Dist: pytest-cov>=5; extra == "dev"
Requires-Dist: mkdocs>=1.5; extra == "dev"
Requires-Dist: mkdocs-material>=9; extra == "dev"
Requires-Dist: mkdocstrings[python]>=0.24; extra == "dev"
Requires-Dist: httpx>=0.27; extra == "dev"
Requires-Dist: openai>=1.40; extra == "dev"
Requires-Dist: cryptography>=42; extra == "dev"
Requires-Dist: keyring>=24; extra == "dev"
Dynamic: license-file

# protoprompt

[![CI](https://github.com/Idxeed/protoprompt/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/Idxeed/protoprompt/actions/workflows/ci.yml)
[![Python 3.11–3.13](https://img.shields.io/badge/python-3.11%E2%80%933.13-blue)](https://www.python.org/)
[![License: MIT](https://img.shields.io/badge/license-MIT-yellow.svg)](LICENSE)

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

[Документация](https://idxeed.github.io/protoprompt/ru/) ·
[English](README.en.md) ·
[Примеры](examples/) ·
[Changelog](CHANGELOG.md)

> Проект находится в 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 и не импортируются, пока не понадобятся.

## Установка

```bash
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]"
```

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

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

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

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

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

```python
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/`](examples/): Ollama RAG,
OpenAI с токен-бюджетом, локальные embeddings, сжатие сессии, профиль и
зашифрованный vault.

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

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

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

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

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

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

```python
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 и подробные руководства:

- [быстрый старт](https://idxeed.github.io/protoprompt/ru/quickstart/);
- [RAG](https://idxeed.github.io/protoprompt/ru/rag/);
- [память и сжатие](https://idxeed.github.io/protoprompt/ru/concepts/compression/);
- [профиль пользователя](https://idxeed.github.io/protoprompt/ru/profile/);
- [секреты](https://idxeed.github.io/protoprompt/ru/secrets/);
- [интеграции](https://idxeed.github.io/protoprompt/ru/integrations/).

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

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

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

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

## Разработка

```bash
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](LICENSE)
