> For the complete documentation index, see [llms.txt](https://docs.gitloom.cloud/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.gitloom.cloud/documentation/python.md).

# Python

```bash
pip install gitloom-sdk   # current: 0.5.0
```

A **drop-in beside the OpenAI and Anthropic SDKs**: wrap the client you already use, your call sites stay exactly as they are — one field richer — and the conversation manages itself.

## Drop-in

```python
import gitloom
from openai import OpenAI

memory = gitloom.Gitloom()               # reads GITLOOM_API_KEY
openai = gitloom.wrap(OpenAI(), memory)  # ← the only setup

res = openai.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "What camera do I own?"}],
    conversation="chat-42",              # ← the only change per call
)
print(res.choices[0].message.content)
```

That's the whole loop — you pass **only the new message, never append anything**. Behind the call: the stored conversation supplies the earlier turns, memory is retrieved and injected as background, both turns are stored with the response's real token usage, compaction runs on cadence (default every 5 exchanges) or window pressure, and every compaction feeds the summarized turns to memory ingestion. Untitled conversations get a title automatically. Anthropic clients (`client.messages.create`) wrap identically. Calls without `conversation=` pass through untouched.

```python
openai = gitloom.wrap(OpenAI(), memory,
                      summarize="server",       # GitLoom's model compacts…
                      # summarize=my_function,  # …or yours, locally
                      compact_every=5,
                      namespace=user_id)
```

## Added features, on the same client

```python
conv = openai.gitloom.conversation("chat-42")

conv.rewind(6)                                                # fork after seq 6
conv.edit(4, {"role": "user", "content": "ask differently"})  # fork at same seq
conv.edit_in_place(4, "[redacted]")                           # destroy the original (PII)
conv.set_title("Camera shopping")
conv.branches()
```

These act on the **same managed conversation** the completions flow through — a rewind here is what the next `create(..., conversation="chat-42")` continues from.

## Recall, filtered and answered

`openai.gitloom` — or a bare `gitloom.Gitloom()` — reaches the memory directly.

```python
memory = openai.gitloom

# Ranked memories, no model call. Milliseconds.
res = memory.recall(
    "what camera do I own",
    tiers=["facts"],            # facts | incidents | rules | skills
    paths=["facts/gear"],       # any directories
    tags=["camera"],
    since="2026-01-01",
    min_score=0.3,
    limit=8,
)
for m in res["memories"]:
    print(round(m["score"], 2), m["path"], m["matched"], m["content"])

# One text answer from a fast model over that retrieval …
print(memory.answer("what camera do I own")["answer"])
# … or let a stronger model search the memory itself with tools.
agentic = memory.answer("which of my trips had the longest flight", agentic=True)
print(agentic["answer"], agentic["trace"])
```

Each entry is **one whole memory**, not a scattering of its sections — `content` is the full body and `sections` names the headings that matched. `score` is a calibrated relevance in `[0, 1]`, comparable across queries, so `min_score` means the same thing whatever was asked. `matched` says which arms produced it; matched only by `graph` is context that rode in beside a real match, and `via` names what pulled it in. Pass `detail="full"` for revision history, the last diff, relation snippets and cues.

Filters apply **inside every retrieval arm** server-side, so confining a query to a directory is a real boundary rather than a cut made after the fact.

`answer` is metered as a chat, not a read, and raises `GitloomError("no_answer")` rather than returning an empty string when the model finds nothing to say.

## Tags and when it happened

```python
memory.remember(
    [{"role": "user", "content": "We shipped the beta to the first ten teams."}],
    tags=["launch", "beta"],          # on every memory drawn from it
    occurred_at="2026-09-30 18:00",   # when it happened, not when you sent it…
    timezone="Asia/Kolkata",          # …read in this zone
)
```

`occurred_at` keeps backfilled history at its real dates. It takes an aware `datetime` (a naive one is read as UTC), a `date` for that calendar day, epoch seconds, or a string: RFC 3339, `YYYY-MM-DD`, or a datetime without an offset, read in `timezone`. `date=` still works and is deprecated.

Tags are trimmed and lowercased, and hold letters, digits, spaces and `- _ . : / # @`, up to 32 tags of 64 characters. A bad one raises `GitloomError` with code `invalid_tag`, naming the field.

Every recalled memory carries `created_at`, `updated_at`, `occurred_at` and `expires_at` as aware UTC datetimes (None when unknown). `occurred_precision` is `day` when only the date is known, held as noon UTC, or `instant`, and `occurred_source` is `user`, `extracted`, `said` or `written`. `user_tags` are the tags you set, lowercased and sorted rather than in the order you sent them; `tags` lists those first, then the inferred ones, also sorted. The `created` and `updated` strings remain, deprecated.

## Listing without a question

```python
from datetime import date

res = memory.recall(tags=["launch"], since=date(2026, 9, 1), time_field="occurred")
for m in res["memories"]:
    print(m["occurred_at"], m["path"], m["user_tags"])
```

Without a query, a filter (`tags`, `tags_all`, `since`, `until`, `tiers` or `paths`) says what to list, and every match comes back newest first by `time_field` (`occurred`, `created`, or `updated` by default), scored 1. With neither, `recall` raises `ValueError` before sending anything. A listing is raw retrieval, so `answer` and `rank` need a query. `since` and `until` take what `occurred_at` takes and narrow a question the same way; a date-only `until` includes that whole day in `tz`.

## Direct memory

`remember` has a model decide what a conversation holds. When you already know what a memory says and where it belongs, such as in a migration or an agent filing its own conclusion, store it as written:

```python
from datetime import date

memory.write([
    {"path": "facts/people/maya.md", "content": "Maya rides a bicycle to work.",
     "tags": ["people"], "occurred_at": date(2026, 7, 19),
     "cues": ["how does Maya get around"]},
])

# Seconds later, once the write has landed:
memory.get("facts/people/maya.md")["content"]   # a file, or file.md#section
memory.tree(path="facts", depth=3)              # tier → topic → file → sections
memory.topics(like="databas")                   # check before inventing a topic
memory.graph(limit=200)                         # nodes, edges, truncated
memory.forget(["facts/people/maya.md"])
```

Paths sit under `facts/`, `incidents/`, `rules/` or `skills/`, and one that does not end in `.md` is refused before anything is sent. `write` and `forget` are asynchronous like `remember`, and `forget` leaves earlier revisions in git history. Send writes in batches: one call is one commit.

## Vocabulary and skills

```python
# Teach abbreviations and domain terms. A recall for "k8s" then also finds
# memories written "kubernetes", and the definition comes back as `defined`.
memory.vocab.learn([
    {"term": "kubernetes", "aliases": ["k8s", "kube"],
     "definition": "Container orchestration."},
])
memory.vocab.lookup("k8s")          # → {"term": "kubernetes", "aliases": [...]}
memory.vocab.list(like="kube")
memory.vocab.forget(["kubernetes"])

# Store how things are done; find the skill that fits a task.
memory.skills.store([
    {"name": "Deploy to production", "topic": "ops",
     "description": "Ship a release.",
     "content": "## Steps\n1. Tag the release.\n2. `make deploy ENV=prod`",
     "triggers": ["how do I ship a release", "deploy to prod"]},
])
skill = memory.skills.find("release the new build")[0]
```

Skills are memories under the `skills/` tier, so `recall(q, tiers=["skills"])` reaches them too.

## Multimodal

```python
# Upload the photo once and hand the model a short-lived URL to it, so the
# stored turn holds a reference rather than the bytes.
gl = openai.gitloom.memory   # the Gitloom client behind the wrapper
with open("photo.png", "rb") as f:
    media_id = gl.upload_media("image/png", f.read())["id"]
url = gl.get_media(media_id)["url"]

openai.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": [
        {"type": "text", "text": "what's in this photo?"},
        {"type": "image_url", "image_url": {"url": url}},
    ]}],
    conversation="chat-42",
)
```

Content parts go to the model exactly as you write them, so they take the provider's own shape. `text_part`, `image_part` and `image_data` build GitLoom's parts for `conv.append()` on a conversation you drive yourself, where `image_data`'s bytes are uploaded on append and stored by reference.

The URL expires after 15 minutes; in a conversation that stays open longer, fetch a fresh one with `gl.get_media(media_id)` before the image is sent again.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.gitloom.cloud/documentation/python.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
