Metadata-Version: 2.4
Name: langchain-harny
Version: 0.1.0
Summary: Long-term memory for LangChain agents: recall what each person said, and when, with Harny.
Author-email: Harny <platform@harny.ai>
License: Apache-2.0
Project-URL: Homepage, https://harny.ai
Project-URL: Documentation, https://harny.ai/docs
Keywords: langchain,harny,memory,retriever,agents,ai-agents
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software 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: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: langchain-core<2,>=1.0.0
Requires-Dist: httpx<1.0.0,>=0.27.2
Provides-Extra: agents
Requires-Dist: langchain<2,>=1.0.0; extra == "agents"
Provides-Extra: test
Requires-Dist: langchain<2,>=1.0.0; extra == "test"
Requires-Dist: langchain-tests<2,>=1.0.0; extra == "test"
Requires-Dist: pytest>=8.3.0; extra == "test"
Requires-Dist: pytest-asyncio>=0.24.0; extra == "test"
Requires-Dist: pytest-socket>=0.7.0; extra == "test"
Dynamic: license-file

# langchain-harny

Long-term memory for LangChain agents. `HarnyRetriever`, two agent tools and a LangChain v1 agent middleware recall what each person told your app, with the date each fact happened, and keep the newest answer on top when a fact changed. Your agent remembers across sessions, restarts and devices.

## Install

```bash
pip install langchain-harny                # retriever and tools
pip install "langchain-harny[agents]"      # adds HarnyMemoryMiddleware for create_agent
```

Python 3.10+. Needs `langchain-core>=1,<2` (tested against 1.7.1; the `agents` extra is tested against `langchain` 1.4.7).

## Start without a key

You do not need an account first. From the project folder:

```bash
pip install harny
harny init --name "<business>" --about "<what the app does>" --customers "<who its customers are>" --preset cost_first
```

That creates the app and saves `HARNY_API_KEY` to `.env` without printing it. Never print, log or commit the key. (Raw API route: `POST https://api.harny.ai/v1/auth/provision` with `{"app_name": "<business>"}`; the key is shown once.)

## One-minute example

```python
from langchain_harny import HarnyRetriever

retriever = HarnyRetriever(user="nadia", k=5)  # reads HARNY_API_KEY; "nadia" is YOUR id for the person
for doc in retriever.invoke("What is the Acme pilot budget?"):
    print(doc.metadata["occurred_at"], doc.page_content)
```

`user` is your own id for the person. The API reads only that person's memory, so one app key can serve every user safely.

## The canonical example, with LangChain

Same facts as every Harny surface (Nadia, the Acme pilot, the budget that moved from 32k to 40k):

```python
from langchain_harny import HarnyMemoryClient, HarnyRetriever

with HarnyMemoryClient(user="nadia") as harny:  # reads HARNY_API_KEY
    harny.ingest(
        "Nadia confirmed the Acme pilot ships March 14. Budget is 32k.",
        id="call-8820", label="Account review call", timestamp="2026-02-03T09:00:00Z",
    )
    receipt = harny.ingest(
        "Nadia raised the Acme pilot budget from 32k to 40k.",
        id="call-8821", label="Budget change", timestamp="2026-03-01T09:00:00Z",
    )
    harny.wait_for_ingestion(receipt["ingestionId"])  # facts are processed in the background

docs = HarnyRetriever(user="nadia", level="medium").invoke("What is the Acme pilot budget?")
for rank, doc in enumerate(docs, start=1):
    print(rank, doc.page_content)  # "Acme pilot budget: currently 40k." comes first
```

## Give an agent memory (three ways)

**1. Middleware: recall before every answer.** LangChain v1 agents (saving conversation messages is off by default; switch it on with `HarnyMemoryMiddleware(user=..., save_user_messages=True)`):

```python
from langchain.agents import create_agent
from langchain_harny import HarnyMemoryMiddleware

agent = create_agent("openai:gpt-5", middleware=[HarnyMemoryMiddleware(user="nadia")])
agent.invoke({"messages": [{"role": "user", "content": "What is the Acme pilot budget?"}]})
```

For many people from one agent, pass a function: `HarnyMemoryMiddleware(user=lambda runtime: runtime.context.user_id)`.

**2. Tools: the agent decides when to look up and when to save.**

```python
from langchain.agents import create_agent
from langchain_harny import HarnyToolkit

tools = HarnyToolkit(user="nadia").get_tools()  # harny_recall and harny_remember
agent = create_agent("openai:gpt-5", tools=tools)
```

**3. Retriever: plug memory into any chain or RAG graph** (see the one-minute example). It is a normal `BaseRetriever`, so `retriever | prompt | model` works.

## Options

| Argument | Default | Meaning |
|---|---|---|
| `user` | required | Your id for the person |
| `api_key` | `HARNY_API_KEY` | App key (`fsa_`) or a person's own key (`fsk_`); text or `SecretStr` |
| `base_url` | `https://api.harny.ai` | `/v1` is added when missing. HTTPS only; `http://localhost` allowed for local runs |
| `level` / `max_tokens` | `medium` | How much evidence to recall (`low`, `medium`, `high`, `extra-high`, or a token budget) |
| `k` (retriever) / `limit` (middleware) | API default | Most facts recalled (1 to 200) |
| `as_of`, `occurred_from`, `occurred_to` (retriever) | none | Recall as of a moment, or only facts from a time window |
| `save_user_messages` (middleware) | `False` | Off by default. `True` saves what the person says after each run |
| `cache_seconds` (middleware) | `30` | Reuse a recall for the same words, so a tool loop does not call the API at every step |
| `http_client` / `async_http_client` | new client | Your own `httpx` client (proxy, test transport); never closed by the package |

## Behaviour an agent should know

- **Saving conversation messages is off by default** (`save_user_messages=True` switches it on). When on, only the person's own messages are saved, never the model's replies or system text. `harny_remember` and `HarnyMemoryClient.ingest` save on request.
- **A saved fact has a stable id** (hash of the person and the words), so saying the same words twice is one fact and costs nothing the second time.
- **A memory problem never fails the run.** If recall or save is refused, the middleware lets the agent answer without memory and logs one warning with the error code (never content, never keys). The tools answer in words ("Memory is unavailable right now (code)") instead of raising.
- **`pending`**: facts saved a moment ago may still be processing. Retriever documents carry it in `metadata["pending"]`; the middleware and the tool tell the model in one line.
- **Errors** are `HarnyAPIError` with `code`, `status`, `debug_message`, `retry_after` (a per-minute rate limit has no body; `code` is `rate-limited`).
- Forget a fact: `HarnyMemoryClient(user="nadia").delete_data_points(["call-8821"])`.
- Everything has an async twin: `ainvoke` on the retriever and tools, `AsyncHarnyMemoryClient`, and the middleware's async hooks.

## The memory API underneath

This package is a thin layer over Harny's public memory API (`/v1/memory`: ingest, status, recall, delete). The same calls from Python with the Harny SDK:

```python
from harny import SyncHarnyClient

with SyncHarnyClient() as harny:  # reads HARNY_API_KEY
    harny.ingest_data_point(
        "Nadia confirmed the Acme pilot ships March 14. Budget is 32k.",
        id="call-8820", label="Account review call", timestamp="2026-02-03T09:00:00Z", user="nadia",
    )
    receipt = harny.ingest_data_point(
        "Nadia raised the Acme pilot budget from 32k to 40k.",
        id="call-8821", label="Budget change", timestamp="2026-03-01T09:00:00Z", user="nadia",
    )
    harny.wait_for_ingestion(receipt.ingestionId, user="nadia")

    recall = harny.recall("What is the Acme pilot budget?", level="medium", user="nadia")
    for result in recall.results:
        print(result.rank, result.content)
```

## Tests and pinned versions

```bash
scripts/ci.sh            # fresh venv, installs the pins in ci-pins.txt, runs the tests (no network, no paid call)
scripts/ci.sh --latest   # the same tests against the newest LangChain release (exit 3 = a LangChain update breaks us)
```

Pinned: `langchain-core==1.7.1`, `langchain==1.4.7`, `langchain-tests==1.1.9`, `httpx==0.28.1`. The tests include LangChain's own standard suites for retrievers and tools.

Apache-2.0. https://harny.ai
