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

# Cookbook: general AI memory

> Add tenant-scoped long-term memory to a chatbot, copilot, or assistant using the General Engine.

Use this for: AI assistants, productivity tools, coding agents, SaaS personalization, onboarding and support chat that doesn't need the Support schema.

The General Engine stores facts, preferences, goals, procedures, relationships, and expertise per `external_user_id` inside your tenant.

## Flow

```text theme={null}
User message → mem.add() → mem.get() → LLM call with system_prompt_addition
```

<CodeGroup>
  ```python Python theme={null}
  import os
  from memoryos import Memory
  from openai import OpenAI

  BASE_PROMPT = "You are a helpful product assistant."

  def answer_user(external_user_id: str, user_message: str) -> str:
      memory = Memory(api_key=os.environ["MEMORYOS_API_KEY"])
      openai = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

      memory.add(
          messages=[{"role": "user", "content": user_message}],
          external_user_id=external_user_id,
          metadata={"source": "chat"},
      )

      memories = memory.get(query=user_message, external_user_id=external_user_id, limit=5, context_max_tokens=500)

      system_prompt = BASE_PROMPT
      if memories.has_context:
          system_prompt = f"{BASE_PROMPT}\n\n{memories.system_prompt_addition}"

      response = openai.responses.create(
          model="gpt-4.1-mini",
          input=[
              {"role": "system", "content": system_prompt},
              {"role": "user", "content": user_message},
          ],
      )

      memory.close()
      return response.output_text
  ```

  ```ts TypeScript theme={null}
  import OpenAI from "openai";
  import { MemoryOS } from "@memoryos/sdk";

  const BASE_PROMPT = "You are a helpful product assistant.";

  export async function answerUser(externalUserId: string, userMessage: string): Promise<string> {
    const memory = new MemoryOS(process.env.MEMORYOS_API_KEY!);
    const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY! });

    await memory.add([{ role: "user", content: userMessage }], externalUserId, undefined, { source: "chat" });

    const memories = await memory.get({ query: userMessage, externalUserId, limit: 5, contextMaxTokens: 500 });

    const systemPrompt = memories.hasContext
      ? `${BASE_PROMPT}\n\n${memories.systemPromptAddition}`
      : BASE_PROMPT;

    const response = await openai.responses.create({
      model: "gpt-4.1-mini",
      input: [
        { role: "system", content: systemPrompt },
        { role: "user", content: userMessage },
      ],
    });

    return response.output_text;
  }
  ```
</CodeGroup>

## Production handling

Always treat MemoryOS as additive. Your app should answer even when memory is empty, passthrough, or unavailable.

```python theme={null}
memories = memory.get(query=user_message, external_user_id=external_user_id)

prompt_addition = ""
if memories.has_context:
    prompt_addition = memories.system_prompt_addition
```

For writes, check `status` before assuming a memory was stored:

```python theme={null}
result = memory.add(messages=messages, external_user_id=external_user_id)

if result.was_stored:
    pass  # queued for extraction
elif result.nothing_to_extract:
    pass  # valid conversation, nothing durable to store
elif result.status == "passthrough":
    pass  # write skipped by quota mode
```

## What to send to `add()`

Send meaningful turns. The quality gate blocks filler.

**Good:** `"I prefer short technical answers with Python examples."` or `"My main goal is to prepare for the AWS Solutions Architect exam."`

**Poor:** `"hi"`, `"ok"`, empty messages, repeated copies of the same turn.

## Retrieval query design

Use the current task as the query, not a generic term.

```python theme={null}
# Good
memory.get(query="Write a follow-up email for this customer", external_user_id="customer-123")

# Poor
memory.get(query="preferences", external_user_id="customer-123")
```

## Related pages

* [Quickstart](/quickstart)
* [MemoryEngine](/concepts/memory-engine)
* [POST /v1/memories/add](/api-reference/add)
* [POST /v1/memories/retrieve](/api-reference/retrieve)
