> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hookie.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

> Read and write a project's memories, decisions, documents and context from Python, with adapters for LangChain, LangGraph and CrewAI.

`hookie-ai` is Hookie's Python client for a project's brain: its **memories and
decisions**, **knowledge search** (memories, documents and the knowledge graph in one
call), **documents** and the **project context bundle**. It ships adapters for
**LangChain**, **LangGraph** and **CrewAI**, and it is MIT licensed.

The package is on [PyPI as `hookie-ai`](https://pypi.org/project/hookie-ai/).

## Install

```bash theme={"dark"}
pip install hookie-ai                 # the client (httpx is its one dependency)
pip install "hookie-ai[langchain]"    # + LangChain retriever, chat history and tools
pip install "hookie-ai[langgraph]"    # + LangGraph tool node, context and capture nodes
pip install "hookie-ai[crewai]"       # + CrewAI tools
```

The client needs Python 3.9 or later. The `[crewai]` extra needs Python 3.10 or later,
as CrewAI does. The distribution is `hookie-ai`; the import is `hookie`.

## Your API key

Every call uses **your own** Hookie credential: an admin API key (`hk_…`) from
**Settings → API keys** in the console, or a connected agent's OAuth token. Hookie never
supplies a key for you. The key acts as the member who created it, capped at its role
and, optionally, one project. See [API keys](https://docs.hookie.ai/api-keys.md).

```bash theme={"dark"}
export HOOKIE_API_KEY=hk_...        # never commit it
export HOOKIE_PROJECT=my-project    # optional: id or slug; "default" otherwise
```

The client sends the key only as an `Authorization: Bearer` header to your Hookie
origin (HTTPS, or `http://localhost` for development). It never logs the key, never
puts it in an error, and leaves it out of `repr(client)`.

### Projects by id or slug

Hookie's project routes take a project's id. You can pass an id or a slug. The client
looks a slug up once with `GET /admin/api/projects`; a project-scoped key, which may not
list projects, uses the one project `GET /admin/api/me` names. With no project named,
calls go to `default`, the slug of your workspace's Default project.
`hk.project_id()` returns the id the client resolved.

## The client

```python theme={"dark"}
from hookie import Hookie

with Hookie(project="my-project") as hk:          # api_key= defaults to HOOKIE_API_KEY
    ctx = hk.projects.context()                    # summary, decisions, memories, documents, issues
    hits = hk.knowledge.search("how do we deploy?", top_k=10)
    for m in hits["memories"]:  print(m["title"])
    for p in hits["passages"]:  print(p["document_name"], p["score"])
    print(hits["unavailable"])                     # parts your plan does not search, and why

    saved = hk.memories.save("Deploys", "Merging into main deploys production.", tags=["release"],
                             memory_key="deploys")  # the same key updates the same memory
    hk.memories.record_decision("Use Postgres for billing", "Replaces the D1 table; see ADR-7.")
    for m in hk.memories.iter(kind="decision"):    # every page, 100 at a time
        print(m["title"])
    hk.memories.extract(transcript_text, thread={"id": "session-42", "title": "Billing refactor"})

    doc = hk.documents.upload("adr-007.md", "# ADR 7\n...", kind="adr", source_ref="docs/adr/007.md")
    hk.documents.upload_file("spec.pdf", kind="spec")   # PDF, .docx and HTML become Markdown
    hk.documents.search("rate limits", top_k=5)          # document passages only
    text = hk.documents.content(doc["document"]["id"])
```

`AsyncHookie` has the same methods, awaited, and supports `async for` over `iter`.

| Area | Methods | Route (`/admin/api/projects/{project}`) |
| - | - | - |
| Memories | `save`, `record_decision`, `list`, `search`, `iter`, `get`, `update`, `delete`, `versions`, `restore`, `extract` | `/memories…` |
| Knowledge | `search` | `POST /brain/knowledge` |
| Documents | `upload`, `upload_file`, `list`, `iter`, `get`, `content`, `delete`, `search` | `/brain/documents…`, `POST /brain/search` |
| Projects | `context`, `list` | `GET /brain/context` |
| Workspace Brain | `brain.search` | `POST /admin/api/data-workspace/search` |
| Anything else | `request(method, path, params=, json=)` | any `/admin/api/…` route |

Responses are the API's JSON, unchanged, typed as `TypedDict`s in `hookie.models`. See
[Project context](https://docs.hookie.ai/project-context.md) and [Personal AI memory](https://docs.hookie.ai/ai-memory.md) for what each
field means.

`memories.extract` sends a session to [automatic memory capture](https://docs.hookie.ai/project-context.md#automatic-memory-capture):
Hookie proposes up to 5 memories and decisions from it, redacts credentials before its
model reads the text, and does not store the transcript.

### Retries and idempotency

* Every POST that writes carries an `Idempotency-Key`, so a retried save runs once.
  `request()` sends none on the routes that refuse one (`api-keys` and `invites`).
* Reads (GETs and the search POSTs) are retried on 5xx and burst 429s, twice by default.
  A quota 429 is not retried, and neither is a 429 whose `Retry-After` is longer than
  10 seconds.
* When a retried write meets Hookie's 409 "still in progress" (the first attempt timed
  out but is still running), the client waits for the first attempt's answer, up to
  `timeout`. Past that, the `HookieConflictError` has `reason == "idempotency_in_progress"`:
  ask again with the same `idempotency_key`, never a new one.

### Errors

Every failure is a `HookieError` with `status`, `reason`, `retry_after` and `body`:

| Exception | When |
| - | - |
| `HookieAuthError` | 401 or 403 |
| `HookieValidationError` | 400, 413, 415 or 422 |
| `HookieNotFoundError` | 404, including a project you cannot see |
| `HookieConflictError` | 409: a stale `revision`, a full allowance, capture switched off, or `idempotency_in_progress` |
| `HookieRateLimitError` | 429; `.is_quota` is true when waiting a minute will not help |
| `HookieServerError` | 5xx |
| `HookieNetworkError` | No answer |

## LangChain

Install `hookie-ai[langchain]`.

```python theme={"dark"}
from hookie import Hookie
from hookie.integrations.langchain import HookieRetriever, HookieChatMessageHistory, create_hookie_tools

hk = Hookie(project="my-project")
retriever = HookieRetriever(client=hk, top_k=8)                 # memories + passages + graph nodes
docs_only = HookieRetriever(client=hk, search="documents")       # or "memories", "workspace"
docs = retriever.invoke("how do we deploy?")                     # Documents, metadata["source"] == "hookie"

history = HookieChatMessageHistory("session-42", client=hk, title="Billing refactor")
# ... use it with RunnableWithMessageHistory; then:
history.capture()        # Hookie proposes up to 5 memories from the conversation
history.recall("billing")

tools = create_hookie_tools(hk)   # hookie_search_knowledge, hookie_project_context,
                                  # hookie_save_memory, hookie_record_decision
```

* **Retriever:** `top_k` is 1 to 20 in every mode. The `memories` mode matches the query
  word by word and ranks memories that match more words first.
* **Chat history:** `HookieChatMessageHistory` keeps the messages in your process.
  Hookie keeps memories, not transcripts: `capture()` (and `clear()`, unless
  `capture_on_clear=False`) sends the conversation to automatic memory capture. System
  messages and tool output are left out of what is sent. `recall(query)` matches the
  query word by word.
* **Tools:** `create_hookie_tools(async_client=...)` needs no sync client and no
  `HOOKIE_API_KEY` unless a tool is then called synchronously.

## LangGraph

Install `hookie-ai[langgraph]`.

```python theme={"dark"}
from langgraph.graph import StateGraph, MessagesState, START
from hookie.integrations.langgraph import HookieContextNode, HookieCaptureNode, create_hookie_tool_node

graph = StateGraph(MessagesState)
graph.add_node("context", HookieContextNode(hk))        # the project's context as the first (system) message
graph.add_node("tools", create_hookie_tool_node(hk))     # the four tools above
graph.add_node("capture", HookieCaptureNode(hk, thread_id="session-42"))
```

* **Context node:** keeps its message at the front of the history and replaces it rather
  than repeating it. The messages key must use `add_messages`, as `MessagesState` does, so
  a model or prompt that adds its own system message never gets two apart.
* **Capture node:** sends only what the person and the agent said, not the context, other
  system messages or tool output.

Hookie memories are curated notes rather than a key-value store, so there is no
`BaseStore`. Keep the graph's own state in a LangGraph checkpointer.

## CrewAI

Install `hookie-ai[crewai]` (Python 3.10 or later).

```python theme={"dark"}
from crewai import Agent
from hookie.integrations.crewai import hookie_crewai_tools

agent = Agent(role="Engineer", goal="Ship the billing fix", backstory="...",
              tools=hookie_crewai_tools(hk))   # search knowledge, project context, save memory
```

The tools are `HookieKnowledgeSearchTool`, `HookieProjectContextTool` and
`HookieSaveMemoryTool`, which saves a memory or a decision.

## Read-only agents

Pass `allow_writes=False` to any of the tool factories (`create_hookie_tools`,
`create_hookie_tool_node`, `hookie_crewai_tools`) to leave out the tools that save.
For a read-only key, create one with the viewer role in **Settings → API keys**.

## Content is data, not instructions

Memories, documents and graph nodes are written by people and agents. The framework
tools' text and the context node's message start with a note saying so. Keep that note
when you build your own prompts from search results.

## Related

* [n8n node](https://docs.hookie.ai/integrations/n8n.md): the same memories, knowledge and documents in n8n workflows.
* [Node SDK](https://docs.hookie.ai/sdk.md): send events and verify webhooks from JavaScript.
* [Project context](https://docs.hookie.ai/project-context.md) and [Personal AI memory](https://docs.hookie.ai/ai-memory.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.