Metadata-Version: 2.5
Name: piyapi-langgraph
Version: 0.1.1
Summary: LangGraph long-term memory store (BaseStore) on PiyAPI memory files
Project-URL: Homepage, https://www.negentro.tech
Project-URL: Documentation, https://docs.negentro.tech/integrations/langgraph
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,langgraph,long-term memory,memory,piyapi,store
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: langgraph<2,>=1.2.20
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-langgraph

A LangGraph long-term memory store (`BaseStore`) on [PiyAPI](https://piyapi.cloud) memory files. Items written by
your graph are stored in one PiyAPI namespace as JSON files under `/memories`, so the same memories are visible in
the PiyAPI dashboard, to Anthropic's memory tool, and to PiyAPI search.

> **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-langgraph
```

## Quick start

```python
from langgraph.graph import StateGraph
from piyapi_langgraph import PiyAPIStore

store = PiyAPIStore(namespace="my-app")  # api_key defaults to PIYAPI_API_KEY

store.put(("users", "u1"), "prefs", {"food": "pizza", "units": "metric"})
store.get(("users", "u1"), "prefs").value  # {'food': 'pizza', 'units': 'metric'}
store.search(("users",), query="what does u1 eat")  # PiyAPI hybrid search, with scores
store.search(("users",), filter={"units": "metric"})
store.list_namespaces(prefix=("users",))  # [('users', 'u1')]

graph = StateGraph(...).compile(store=store)  # nodes receive it as `store`
```

Async graphs use the same object (`aget`, `aput`, `asearch`, `alist_namespaces`, `adelete`); it keeps one
`httpx.Client` and one `httpx.AsyncClient`. Close them with `store.close()` / `await store.aclose()`, or use the store
as a (async) context manager.

Constructor: `PiyAPIStore(api_key=None, base_url=None, namespace="default", timeout=30.0, transport=None,
async_transport=None, http_client=None, async_http_client=None)`. `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-langgraph/<version>`.

## How items map to memory files

An item at LangGraph namespace `("users", "u1")` with key `"prefs"` is the file `/memories/users/u1/prefs.json` in
the PiyAPI namespace you chose; its text is `json.dumps(value)`.

PiyAPI refuses some path characters, so labels and keys are escaped (and decoded again when read back):

| In a label or key                                   | In the path                                                     |
| --------------------------------------------------- | --------------------------------------------------------------- |
| `~` `/` `\` `%`, control characters, U+2028, U+2029 | `~XX` per UTF-8 byte, e.g. `a/b` -> `a~2Fb`, `~` -> `~7E`       |
| whitespace at the start or end                      | `~XX`, e.g. `" x"` -> `~20x`                                    |
| a namespace label `.` or `..`                       | dots as `~2E`                                                   |
| an empty namespace label                            | `~`                                                             |
| a namespace label ending in `.json`                 | that dot as `~2E`, so a directory never has an item's file name |

Everything else (including non-ASCII letters) is kept as written. The functions are exported: `item_path`,
`parse_item_path`, `encode_label`, `encode_namespace_label`, `decode_label`.

Files under `/memories` that do not look like items (not `<key>.json` inside a namespace directory, or not a JSON
object) are skipped by `search` and `list_namespaces`; `get` of such a file raises `PiyAPIError`.

## Operations

| Op                          | PiyAPI request                                                                                                                                                                 |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `get`                       | `GET /api/v1/memory-files/file?path=&namespace=`; a 404 `MEMORY_FILE_NOT_FOUND` returns `None`                                                                                 |
| `put`                       | `POST /api/v1/memory-files/file {path, content, namespace}`                                                                                                                    |
| `put(..., None)` / `delete` | `DELETE /api/v1/memory-files?path=&namespace=`; deleting a missing item is a no-op                                                                                             |
| `search` with `query`       | `GET /api/v1/memory-files/search?q=&namespace=&path_prefix=&limit=`; results keep PiyAPI's order and carry its `score`                                                         |
| `search` without `query`    | `GET /api/v1/memory-files?prefix=&namespace=&include_content=true`; newest first, `score` is `None`                                                                            |
| `list_namespaces`           | `GET /api/v1/memory-files?prefix=&namespace=&include_content=false`, then prefix/suffix (with `*`), `max_depth`, `limit`, `offset` as LangGraph's `InMemoryStore` applies them |

`filter` is applied client-side on the value: equality (nested dicts and lists compared whole) and the `$eq`, `$ne`,
`$gt`, `$gte`, `$lt`, `$lte` operators that `SearchOp` documents. `created_at` / `updated_at` come from the API (now,
if missing). Ops in one `batch` / `abatch` run in order, one request each.

Errors: any status other than the `MEMORY_FILE_NOT_FOUND` 404s above (including a 404 from a wrong base URL or a
proxy) raises `PiyAPIError` with `status_code`, `code` (the server's error code, e.g. `MEMORY_FILE_PARENT_IS_FILE`),
`request_id` and the server's message. No response (connection failure or timeout) raises `PiyAPIConnectionError`.
Requests are not retried.

## No vector `index` config

PiyAPI embeds every file and searches server-side (vector plus keyword), so the store takes no `index` /
embeddings config: `PutOp.index` is ignored (an item written with `index=False` is still searchable), and a `query`
always goes to PiyAPI search. TTLs are not supported (`supports_ttl = False`).

## Limits

From the memory-files API (src/config/memoryFiles.ts, src/routes/memoryFiles.routes.ts):

- a path of at most 512 characters (UTF-16 units, after escaping) and 16 segments below `/memories`: at most 15
  namespace labels plus the key. Longer paths raise `ValueError` before any request;
- a value of at most 100,000 characters of JSON (and your plan's per-memory limit); larger writes fail with 413;
- at most 1,000 files per PiyAPI namespace by default (`MEMORY_FILES_MAX_PER_NAMESPACE`); a listing past that is
  marked truncated and the store logs a warning;
- search returns at most 50 results and takes a query of at most 1,000 characters (longer queries are cut), so
  `offset + limit` beyond 50, or a `filter` that drops most hits, returns fewer items;
- PiyAPI namespace names: letters, digits, `. _ : -`, starting with a letter or digit, at most 100 characters.

LangGraph's own rules still apply: namespace labels cannot be empty or contain `.`.

## Tests

```bash
cd packages/langgraph-store
python -m pytest -q
```

The tests run against an in-memory imitation of the memory-files routes served through `httpx.MockTransport` (no
network), including a differential check that answers match LangGraph's `InMemoryStore` for get, filtered search and
`list_namespaces`.
