Metadata-Version: 2.5
Name: piyapi-llamaindex
Version: 0.1.1
Summary: LlamaIndex Memory block backed by PiyAPI (recall with /ask, store with conversation ingest)
Project-URL: Homepage, https://www.negentro.tech
Project-URL: Documentation, https://docs.negentro.tech/integrations/llamaindex
Project-URL: Repository, https://github.com/Negentro-ai/piyapi-sdks
Project-URL: Issues, https://github.com/Negentro-ai/piyapi-sdks/issues
Project-URL: Changelog, https://docs.negentro.tech/release-notes
Author-email: PiyAPI Team <care.piyapi@outlook.com>
License-Expression: MIT
License-File: LICENSE
Keywords: agents,ai,llama-index,llamaindex,memory,piyapi
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.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.28
Requires-Dist: llama-index-core<0.15,>=0.14.25
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Description-Content-Type: text/markdown

# piyapi-llamaindex

A [LlamaIndex](https://www.llamaindex.ai) memory block backed by [PiyAPI](https://piyapi.cloud). Add it to
LlamaIndex's `Memory`: before each turn it recalls what PiyAPI knows that is relevant to the latest user message,
and the turns `Memory` flushes out of its short-term queue are stored in PiyAPI.

> **PiyAPI by Negentro** is the memory layer for AI agents: 84.1% on BEAM-1M, 93.6% on LongMemEval-S and 97% fewer tokens than the full history, with every answer [published](https://github.com/Negentro-ai/piyapi-benchmarks).
> [Start for free](https://piyapi.cloud) · [Docs](https://docs.negentro.tech) · [Benchmarks](https://www.negentro.tech/research)

```bash
pip install piyapi-llamaindex
```

## Quick start

```python
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.core.memory import Memory
from piyapi_llamaindex import PiyAPIMemoryBlock

block = PiyAPIMemoryBlock(namespace="user-123")  # api_key defaults to PIYAPI_API_KEY
memory = Memory.from_defaults(session_id="user-123", token_limit=30000, memory_blocks=[block])

agent = FunctionAgent(tools=[...], llm=llm)
response = await agent.run("Which seat should I book?", memory=memory)
```

`Memory` puts the block's text into the system message (or the latest user message, with
`insert_method=InsertMethod.USER`) as `<memory><PiyAPIMemory>...</PiyAPIMemory></memory>`.

Options: `PiyAPIMemoryBlock(name="PiyAPIMemory", namespace="default", api_key=None, base_url=None, timeout=4.0,
max_context_tokens=None, fail_open=True, low_confidence_note=LOW_CONFIDENCE_NOTE, on_lookup=None, transport=None,
http_client=None, priority=0, accept_short_term_memory=True)`. `base_url` defaults to `PIYAPI_BASE_URL`, else `https://api.piyapi.cloud`; trailing
slashes and a trailing `/api/v1` are removed. Every request sends `Authorization: Bearer <key>`,
`Content-Type: application/json` and `X-PiyAPI-Client: piyapi-llamaindex/<version>`. The API key is left out of `repr`
and `model_dump`.

## What it sends

| Block method     | PiyAPI request                                                                                                                                                                                            |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `aget(messages)` | `POST /api/v1/ask {query, namespace, returnContextOnly: true}` (plus `maxContextTokens` when set); returns the response's `context`, or `""` when `abstained` is true; a weak match adds one line (below) |
| `aput(messages)` | `POST /api/v1/conversations/ingest {messages: [{role, content}], namespace}`; PiyAPI stores overlapping windows of the conversation as memories                                                           |

- The query is the text of the latest user message (its text blocks joined). With no user text, nothing is sent and
  the block returns `""`. A query longer than PiyAPI's 2,000-character limit keeps its last 2,000 characters.
- Roles: `user` -> user; `assistant`, `chatbot`, `model` -> assistant; `system`, `developer` -> system; `tool`,
  `function` -> tool. Messages without text (empty, whitespace, only tool-call or image blocks) are skipped.
- A message over 50,000 characters is sent as several messages with the same role; more than 500 messages are sent
  in parts of 500 (same `conversation_id`, `message_offset` set). When PiyAPI answers 207 with `truncated: true`, the
  block resumes from `next_message_index`, as the API asks.
- `BaseMemoryBlock` has only async methods, so the block has no sync wrappers; `Memory.get()` / `Memory.put()` run
  the async ones for you.

## When the memories may not answer

PiyAPI says whether the memories it found match the question (servers from 2026-11-29): `abstain`, `abstain_reason`
and `relevance` on the `/ask` response. When `abstain_reason` is `"LOW_CONFIDENCE_MATCH"` (the best matches are weak,
by `/search/hybrid`'s rule), the block keeps the context and puts one line after it, `LOW_CONFIDENCE_NOTE`:

```text
These memories may not answer this question (none matched it closely).
```

The signal is advisory: it also flags some answerable questions (1 of 130 held out), so the context is never dropped on
it; only `abstained` (no memory came back) gives `""`. `low_confidence_note="..."` changes the line, and `None` or `""`
leaves it out. To see the signal yourself, pass `on_lookup`: it is called (or awaited, for a coroutine function) with
each lookup's `query`, `namespace`, `context` and `sources`, plus `abstain`, `abstain_reason` and `relevance` when the
server sent them. An error it raises is logged, never raised.

```python
def log_lookup(lookup):
    if lookup.get("abstain_reason") == "LOW_CONFIDENCE_MATCH":
        logger.info("weak recall for %r: %s", lookup["query"], lookup["relevance"])

block = PiyAPIMemoryBlock(namespace="user-123", on_lookup=log_lookup)
```

## Failing open

Memory must not take the agent down. A timeout (default 4 seconds, for the whole request), a network error, an
error status or a non-JSON answer is logged as a warning on the `piyapi_llamaindex` logger; `aget` then returns `""`
and `aput` stores nothing (a multi-part ingest stops at the first failure). Pass `fail_open=False` to raise
`PiyAPIError` (with `status_code` and the server's `code`) instead. Requests are not retried.

A new `httpx.AsyncClient` is opened per call (safe across the event loops `Memory`'s sync methods create). To reuse
connections, pass your own `http_client=httpx.AsyncClient(...)`; the block never closes it.

## Limits

- PiyAPI namespace names: letters, digits, `. _ : -`, starting with a letter or digit, at most 100 characters.
- `/ask` queries: at most 2,000 characters; `maxContextTokens` 500-400,000.
- Ingest: 1-50,000 characters per message, at most 500 messages and 50 stored windows per request (handled as above).
  Each window must fit your plan's per-memory size; PiyAPI splits long windows itself.

## Tests

```bash
cd packages/llamaindex-memory
python -m pytest -q
```

The tests use `httpx.MockTransport` (no network, no model calls) and include runs inside LlamaIndex's own `Memory`
(flush into ingest, context injected into the system message, sync wrappers, PiyAPI down).
