Metadata-Version: 2.5
Name: piyapi-langchain
Version: 0.1.1
Summary: LangChain VectorStore adapter for PiyAPI Memory
Project-URL: Homepage, https://www.negentro.tech
Project-URL: Documentation, https://docs.negentro.tech/integrations/langchain
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: ai,embeddings,langchain,memory,piyapi,vectorstore
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.9
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: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: langchain-core>=0.1.0
Requires-Dist: piyapi-memory>=0.2.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: dev
Requires-Dist: hypothesis>=6.0.0; extra == 'dev'
Requires-Dist: langgraph<2,>=1.2.20; (python_version >= '3.10') and extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Description-Content-Type: text/markdown

# PiyAPI LangChain Adapter

A LangChain VectorStore adapter for PiyAPI Memory, enabling seamless integration with LangChain applications.

> **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)

## Installation

```bash
pip install piyapi-langchain
```

## Quick Start

```python
from piyapi_langchain import PiyAPIVectorStore
from langchain_openai import OpenAIEmbeddings

# Initialize the vector store
vectorstore = PiyAPIVectorStore(
    api_key="your-api-key",
    namespace="my-app",
    embedding=OpenAIEmbeddings()
)

# Add documents
from langchain_core.documents import Document

docs = [
    Document(page_content="PiyAPI Memory is a vector database", metadata={"source": "docs"}),
    Document(page_content="LangChain enables AI applications", metadata={"source": "docs"}),
]
vectorstore.add_documents(docs)

# Search
results = vectorstore.similarity_search("vector database", k=5)
for doc in results:
    print(doc.page_content)

# Search with scores
results_with_scores = vectorstore.similarity_search_with_score("AI applications", k=5)
for doc, score in results_with_scores:
    print(f"{doc.page_content} (score: {score})")
```

## Using as a Retriever

```python
# Create a retriever
retriever = vectorstore.as_retriever(
    search_type="similarity",
    search_kwargs={"k": 5}
)

# Use in a chain
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser

def format_docs(docs):
    # One block, in retrieval order, text only: no scores or metadata that change between calls.
    return "\n\n".join(doc.page_content for doc in docs)

# from_template makes a single human message, so the memories land in the user turn.
template = """Answer based on the context:
{context}

Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
llm = ChatOpenAI()

chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | llm
    | StrOutputParser()
)

answer = chain.invoke("What is PiyAPI Memory?")
```

In a multi-turn chain, keep the system message fixed, put `{context}` in the newest human message
only (after a `MessagesPlaceholder` for the history), and store each earlier human message in the
history exactly as it was sent, context included. Never put the context in the system message.

## Metadata Filtering

```python
# Filter by metadata
results = vectorstore.similarity_search(
    "vector database",
    k=5,
    filter={"source": "docs"}
)
```

## Configuration

| Parameter   | Type       | Required | Description                                                           |
| ----------- | ---------- | -------- | --------------------------------------------------------------------- |
| `api_key`   | str        | Yes      | Your PiyAPI API key                                                   |
| `namespace` | str        | No       | Namespace for organizing memories (default: "default")                |
| `embedding` | Embeddings | No       | LangChain embedding function (uses PiyAPI embeddings if not provided) |
| `base_url`  | str        | No       | Custom API base URL                                                   |

## LangGraph store

`PiyAPIStore` is a LangGraph `BaseStore` (`batch`/`abatch` with Get, Put, Search and ListNamespaces operations).
Each item is one PiyAPI memory file, `/memories/langgraph/<namespace labels>/<key>.json`, holding the value as
JSON: versioned, soft-deleted, and searchable. `search(..., query=...)` uses PiyAPI hybrid search under the
namespace prefix; without a query it lists the items. Filters, `offset`/`limit` and `list_namespaces`
(prefix, suffix, `*`, `max_depth`) behave as in LangGraph's `InMemoryStore`. `index` and `ttl` are accepted and
ignored (every item is searchable; items do not expire). Requires `langgraph` (install it yourself).

```python
from piyapi_memory import PiyAPIClient, AsyncPiyAPIClient
from piyapi_langchain.store import PiyAPIStore

store = PiyAPIStore(PiyAPIClient(), namespace="my-app", async_client=AsyncPiyAPIClient())
graph = builder.compile(store=store)

store.put(("users", "42"), "prefs", {"drink": "tea"})
store.search(("users",), query="what does the user drink?")
```

## License

MIT
