Metadata-Version: 2.4
Name: promptpipe
Version: 0.2.0
Summary: A minimal, from-scratch LLM orchestration framework: pipe-composable runnables, RAG, agents, and streaming — with zero-token testing built in.
Author: Pallav Pradhan
Maintainer: Pallav Pradhan
License: MIT License
        
        Copyright (c) 2026 Pallav Pradhan
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Keywords: llm,langchain-alternative,rag,agents,pipelines
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
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
Requires-Dist: pydantic<3.0,>=2.7
Requires-Dist: jinja2>=3.1
Requires-Dist: python-dotenv>=1.0
Requires-Dist: numpy>=1.26
Provides-Extra: anthropic
Requires-Dist: anthropic>=1.0; extra == "anthropic"
Provides-Extra: openai
Requires-Dist: openai>=3.0; extra == "openai"
Provides-Extra: faiss
Requires-Dist: faiss-cpu>=1.8; extra == "faiss"
Provides-Extra: dev
Requires-Dist: pytest>=8.2; extra == "dev"
Requires-Dist: pytest-cov>=5.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: black>=24.4; extra == "dev"
Requires-Dist: ruff>=0.5; extra == "dev"
Requires-Dist: mypy>=1.10; extra == "dev"
Requires-Dist: anthropic>=1.0; extra == "dev"
Requires-Dist: openai>=3.0; extra == "dev"
Requires-Dist: faiss-cpu>=1.8; extra == "dev"
Dynamic: license-file

# PromptPipe

A minimal, from-scratch LLM orchestration framework written in pure Python — pipe-composable
building blocks for chains, RAG, and agents, with **zero-token testing built
in**. No LangChain imports; every piece is implemented here.

```python
from promptpipe import FakeLLM, PromptTemplate

llm = FakeLLM(response="Why did the duck cross the road? To prove he wasn't chicken!")
chain = PromptTemplate("Tell me a joke about {{ topic }}") | llm | (lambda r: r.content.upper())
print(chain.invoke({"topic": "ducks"}))
```

## Install

Requires Python 3.11+.

```bash
pip install .                      # core — fake mode works out of the box
pip install ".[anthropic,openai]"  # + provider SDKs you actually use
pip install ".[faiss]"             # + FAISS vector-store backend
pip install -e ".[dev]"            # everything needed to run the test suite
```

The provider SDKs are **optional extras** imported only when selected — the
core install has no Anthropic/OpenAI dependency.

## Switching providers without code changes

Provider selection is configuration, resolved by `create_llm()`:

```bash
cp .env.example .env
```

```dotenv
PROMPTPIPE_PROVIDER=fake       # fake | anthropic | openai
ANTHROPIC_API_KEY=sk-ant-...   # needed when provider=anthropic
OPENAI_API_KEY=sk-...          # needed when provider=openai
```

Every example runs against any of the three providers with the same code —
flip `PROMPTPIPE_PROVIDER` in `.env` and rerun. An unknown provider or a
missing key fails loudly with `ConfigurationError`, never silently.

## What's inside

| Area | Module | Highlights |
|---|---|---|
| Composition | `promptpipe.core.runnable` | `Runnable` protocol, `\|` operator, `RunnableSequence`, `RunnableLambda`; `stream()` composes through chains |
| Models | `promptpipe.models` | `FakeLLM`, `AnthropicChatModel`, `OpenAIChatModel`, `create_llm()` factory |
| Prompts | `promptpipe.prompts` | Jinja-templated `PromptTemplate` |
| Parsers | `promptpipe.parsers` | JSON and Pydantic output parsers |
| Memory | `promptpipe.memory` | `ConversationBufferMemory`, bounded `ConversationBufferWindowMemory` |
| Tools/Agents | `promptpipe.tools`, `promptpipe.agents` | `@tool` decorator, safe calculator, ReAct agent loop (`max_iterations`-bounded) |
| RAG | loaders → splitters → embeddings → vectorstores → retrievers | `TextLoader`, `RecursiveCharacterTextSplitter`, deterministic `FakeEmbeddings`, `InMemoryVectorStore` + optional `FaissVectorStore` |
| Observability | `promptpipe.core.usage` | Thread-safe `UsageTracker` with cost estimation, streamed-call accounting, and structured debug logging across pipelines |

### Streaming and async

Both are part of the universal `Runnable` contract:

```python
for chunk in chain.stream("hello"):        # token-level through prompt|llm chains
    print(chunk, end="")

result = await llm.ainvoke("hello")        # native async on both real providers
chunks = [c async for c in chain.astream("hello")]  # async never blocks the loop
```

Upstream steps run once eagerly; the terminal step streams — so
`prompt | llm | parser` streams tokens when the LLM is last and yields one
parsed item when a parser is last. Sync-only components are offloaded to
worker threads automatically, so `await`ing any chain keeps the event loop
responsive.

### Cost tracking

```python
tracker = UsageTracker(prices={
    "gpt-4o-mini": {"input": 0.15, "output": 0.60},   # USD per 1M tokens
})
tracked = tracker.wrap(create_llm())       # drop-in Runnable wrapper
chain = PromptTemplate("Summarize: {{ text }}") | tracked
chain.invoke({"text": "..."})
print(tracker.totals)  # {'prompt_tokens': .., 'completion_tokens': ..,
                       #  'total_tokens': .., 'calls': 1, 'cost_usd': 0.000123}
```

Streamed calls are accounted too: both bundled providers report final usage
after a stream completes (`llm.last_usage`), which the wrapper records.

### Resilience and error policy

Provider wrappers expose SDK-level knobs and map failures onto a retry-aware
exception hierarchy:

```python
from promptpipe import (
    AuthenticationError, ContextLengthExceededError, ProviderUnavailableError,
    RateLimitError, create_llm,
)

llm = create_llm(provider="openai", timeout=30.0, max_retries=3)
try:
    llm.invoke("hi")
except RateLimitError:            ...
except ProviderUnavailableError:  ...  # safe to retry with backoff
except ContextLengthExceededError: ...  # shrink the prompt, don't retry
except AuthenticationError:       ...  # fix credentials, don't retry
```

Prompts fail loud as well: a template variable you forgot to supply raises
`LLMFrameworkError` instead of rendering as an empty string.

### RAG in five lines

```python
from promptpipe import (
    FakeEmbeddings, InMemoryVectorStore, RecursiveCharacterTextSplitter,
    TextLoader, VectorStoreRetriever,
)

docs = TextLoader("guide.txt").load()
chunks = RecursiveCharacterTextSplitter(chunk_size=200).split_documents(docs)
store = InMemoryVectorStore(FakeEmbeddings())      # swap in FaissVectorStore at scale
store.add_documents(chunks)
hits = VectorStoreRetriever(store, k=3).invoke("capital of France?")
store.save("index.json")                   # persist; store.load() restores it
```

Retrievers accept anything implementing the `BaseVectorStore` contract —
bring your own backend without touching pipeline code.

## Testing that costs $0

Unit tests use scripted fakes exclusively — `FakeLLM` returns canned
responses; `FakeEmbeddings` derives stable vectors by hashing tokens, so
retrieval is *actually exercised*, not stubbed out.

```bash
pytest --cov=promptpipe          # unit suite: no network, no keys, no cost
pytest -m integration            # opt-in live-provider tests (costs tokens)
pytest -m integration tests/integration -k anthropic
```

Integration tests are deselected by default and skip themselves when API
keys are absent.

## Development

```bash
pip install -e ".[dev]" -c constraints.txt
ruff check promptpipe/ tests/ examples/    # lint
black --check promptpipe/ tests/ examples/ # format
mypy promptpipe/ tests/ examples/          # types
pytest --cov=promptpipe --cov-fail-under=95  # tests + coverage gate
```

CI runs all four gates on Python 3.11–3.13, plus dependency lower-bound
checks, offline example smoke tests, pip-audit, and CodeQL scanning (see
`.github/workflows/`).

## Examples

| File | Demonstrates |
|---|---|
| `examples/01_simple_chain.py` | prompt \| LLM \| parser piping |
| `examples/02_memory_chatbot.py` | multi-turn conversation memory |
| `examples/03_tool_calling_agent.py` | ReAct agent + calculator tool |
| `examples/04_rag_pipeline.py` | load → split → embed → retrieve → answer |
| `examples/05_streaming_async.py` | streaming + concurrent `ainvoke` |

Each prints which provider class answered (`Provider: FakeLLM` …), so config
swaps are visible at a glance.

## Status & roadmap

PromptPipe is v0.2.0 — production-hardened composition, resilience knobs,
granular provider errors, thread-safe state, cost tracking, and a 95%
coverage gate enforced in CI (see [CHANGELOG.md](CHANGELOG.md) for the full
history). Deliberately **not** yet implemented (design first, then build):

- Distributed tracing / callback system beyond structured logging + usage totals
- Response caching and client-side rate limiting for batch workloads
- Native provider function-calling inside the ReAct loop
- Additional providers and vector-store backends

## License

MIT — see [LICENSE](LICENSE).

## Author

**Pallav Pradhan** — ML & LLM Engineer

>>>>>>> 3474528 (docs+ci: README overhaul, community docs, readiness assessment, CI gates)
