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

# Crear un agente con memory stores

> Monta memoria durable en el entorno shell gestionado de un agente guardado y mantenla actualizada entre ejecuciones.

Usa memory stores cuando necesites contexto durable que pueda usarse entre usuarios, sesiones y agentes, y al que puedan acceder aplicaciones externas.
Los memory stores son útiles para almacenar notas de cuentas, manuales de soporte, informes de errores o cualquier contenido que quieras reutilizar en muchas ejecuciones de agentes.

Referencia de API:

* [Endpoints de Memory Stores](/es/api-reference/memory-stores/create-memory-store)
* [Endpoints de entradas de Memory Store](/es/api-reference/memory-stores/create-memory-entry)
* [Endpoints de agentes y ejecuciones](/es/api-reference/agents/create-an-agent)

## 1. Crea el memory store

Crea un store para un cuerpo durable de conocimiento.
Usa `instructions` para describir cómo deben escribirse y mantenerse las entradas.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm memory-stores create --body '{
    "name": "Acme support memory",
    "description": "Durable support notes for Acme Corp.",
    "instructions": "Keep entries concise. Use one file per durable fact, customer preference, or open issue.",
    "visibility": "workspace",
    "metadata": {
      "account_id": "acct_acme"
    }
  }' \
    -H 'X-On-Behalf-Of: <end-user-id>'
  ```

  ```ts MKA1 SDK theme={null}
  import { SDK } from "@meetkai/mka1";

  const sdk = new SDK({
    bearerAuth: "Bearer <mka1-api-key>",
  });

  const store = await sdk.llm.memoryStores.create({
    xOnBehalfOf: "<end-user-id>",
    createMemoryStoreRequest: {
      name: "Acme support memory",
      description: "Durable support notes for Acme Corp.",
      instructions:
        "Keep entries concise. Use one file per durable fact, customer preference, or open issue.",
      visibility: "workspace",
      metadata: {
        account_id: "acct_acme",
      },
    },
  });

  console.log(store.id);
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/memory_stores \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "name": "Acme support memory",
      "description": "Durable support notes for Acme Corp.",
      "instructions": "Keep entries concise. Use one file per durable fact, customer preference, or open issue.",
      "visibility": "workspace",
      "metadata": {
        "account_id": "acct_acme"
      }
    }'
  ```
</CodeGroup>

La respuesta incluye un ID como `mem_store_...`.

`visibility` determina si este memory store puede usarlo solo un `X-On-Behalf-Of` específico (`private`) o si puede acceder cualquier usuario, sin importar el `X-On-Behalf-Of` (`workspace`).

Consulta la [referencia para crear un memory store](/es/api-reference/memory-stores/create-memory-store).

## 2. Agrega entradas de memoria

Las entradas se direccionan por `path`.
Usa rutas predecibles para que el agente encuentre archivos en el store montado.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm memory-stores create-entry \
    --memory-store-id mem_store_123 \
    --body '{
      "path": "accounts/acme/preferences.md",
      "content": "# Acme preferences\n\n- Prefer concise weekly status summaries.\n- Escalate production incidents to the on-call channel before creating a ticket.",
      "metadata": {
        "kind": "customer-preferences"
      }
    }' \
    -H 'X-On-Behalf-Of: <end-user-id>'
  ```

  ```ts MKA1 SDK theme={null}
  const entry = await sdk.llm.memoryStores.createEntry({
    memoryStoreId: "mem_store_123",
    xOnBehalfOf: "<end-user-id>",
    createMemoryEntryRequest: {
      path: "accounts/acme/preferences.md",
      content:
        "# Acme preferences\n\n- Prefer concise weekly status summaries.\n- Escalate production incidents to the on-call channel before creating a ticket.",
      metadata: {
        kind: "customer-preferences",
      },
    },
  });

  console.log(entry.id, entry.contentHash);
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/memory_stores/mem_store_123/entries \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "path": "accounts/acme/preferences.md",
      "content": "# Acme preferences\n\n- Prefer concise weekly status summaries.\n- Escalate production incidents to the on-call channel before creating a ticket.",
      "metadata": {
        "kind": "customer-preferences"
      }
    }'
  ```
</CodeGroup>

La respuesta incluye un ID de entrada y `content_hash`.

## 3. Crea el agente guardado

Crea un agente con una herramienta `shell` y monta el memory store en el entorno shell.
Usa `read_only` para memoria de referencia.
Usa `read_write` cuando el agente deba actualizar memoria escribiendo archivos en `/mnt/memory/<label>`.
Cuando el agente escribe, edita o elimina archivos dentro de un montaje `read_write`, el sandbox sincroniza esos cambios de vuelta al memory store al terminar el comando shell.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 agents create --body '{
    "name": "account-support-agent",
    "description": "Answers support questions with durable account context.",
    "model": "auto",
    "instructions": "Use the mounted Acme support memory for durable account context. Read files under /mnt/memory/acme_support before answering account-specific questions. When you learn a durable Acme fact, write or update the relevant markdown file under /mnt/memory/acme_support. Do not invent account facts that are not present in memory.",
    "tools": [
      {
        "type": "shell",
        "environment": {
          "type": "container_auto",
          "memory_stores": [
            {
              "store_id": "mem_store_123",
              "label": "acme_support",
              "access": "read_write",
              "description": "Durable support notes for Acme Corp.",
              "instructions": "Use these files as account context. Prefer specific files under accounts/acme/. Write durable account learnings back as concise markdown."
            }
          ]
        }
      }
    ],
    "tool_choice": "auto",
    "metadata": {
      "memory_store_id": "mem_store_123",
      "account_id": "acct_acme"
    }
  }' \
    -H 'X-On-Behalf-Of: <end-user-id>'
  ```

  ```ts MKA1 SDK theme={null}
  const agent = await sdk.agents.createAgent({
    xOnBehalfOf: "<end-user-id>",
    createAgentRequest: {
      name: "account-support-agent",
      description: "Answers support questions with durable account context.",
      model: "auto",
      instructions:
        "Use the mounted Acme support memory for durable account context. Read files under /mnt/memory/acme_support before answering account-specific questions. When you learn a durable Acme fact, write or update the relevant markdown file under /mnt/memory/acme_support. Do not invent account facts that are not present in memory.",
      tools: [
        {
          type: "shell",
          environment: {
            type: "container_auto",
            memoryStores: [
              {
                storeId: "mem_store_123",
                label: "acme_support",
                access: "read_write",
                description: "Durable support notes for Acme Corp.",
                instructions:
                  "Use these files as account context. Prefer specific files under accounts/acme/. Write durable account learnings back as concise markdown.",
              },
            ],
          },
        },
      ],
      toolChoice: "auto",
      metadata: {
        memory_store_id: "mem_store_123",
        account_id: "acct_acme",
      },
    },
  });

  console.log(agent.id);
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/agents \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "name": "account-support-agent",
      "description": "Answers support questions with durable account context.",
      "model": "auto",
      "instructions": "Use the mounted Acme support memory for durable account context. Read files under /mnt/memory/acme_support before answering account-specific questions. When you learn a durable Acme fact, write or update the relevant markdown file under /mnt/memory/acme_support. Do not invent account facts that are not present in memory.",
      "tools": [
        {
          "type": "shell",
          "environment": {
            "type": "container_auto",
            "memory_stores": [
              {
                "store_id": "mem_store_123",
                "label": "acme_support",
                "access": "read_write",
                "description": "Durable support notes for Acme Corp.",
                "instructions": "Use these files as account context. Prefer specific files under accounts/acme/. Write durable account learnings back as concise markdown."
              }
            ]
          }
        }
      ],
      "tool_choice": "auto",
      "metadata": {
        "memory_store_id": "mem_store_123",
        "account_id": "acct_acme"
      }
    }'
  ```
</CodeGroup>

Consulta la [referencia para crear un agente](/es/api-reference/agents/create-an-agent).

## 4. Ejecuta el agente y actualiza memoria

El agente puede leer archivos montados con la herramienta shell.
Si el store montado es `read_write`, también puede actualizar memoria escribiendo archivos bajo `/mnt/memory/<label>`.
El sandbox restaura los archivos montados antes de ejecutar el comando, toma una instantánea y sincroniza los archivos cambiados al terminar.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 agent-runs create \
    --agent-id agt_123 \
    --body '{
      "input": "Draft a support update for Acme about the production incident response plan. Use the mounted Acme memory before answering. Also remember that Acme now wants customer-facing incident summaries by 4 PM Central.",
      "metadata": {
        "memory_store_id": "mem_store_123",
        "source": "docs-recipe"
      }
    }' \
    -H 'X-On-Behalf-Of: <end-user-id>'
  ```

  ```ts MKA1 SDK theme={null}
  const run = await sdk.agentRuns.createAgentRun({
    agentId: "agt_123",
    xOnBehalfOf: "<end-user-id>",
    createAgentRunRequest: {
      input:
        "Draft a support update for Acme about the production incident response plan. Use the mounted Acme memory before answering. Also remember that Acme now wants customer-facing incident summaries by 4 PM Central.",
      metadata: {
        memory_store_id: "mem_store_123",
        source: "docs-recipe",
      },
    },
  });

  console.log(run.id);
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/agents/agt_123/runs \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "input": "Draft a support update for Acme about the production incident response plan. Use the mounted Acme memory before answering. Also remember that Acme now wants customer-facing incident summaries by 4 PM Central.",
      "metadata": {
        "memory_store_id": "mem_store_123",
        "source": "docs-recipe"
      }
    }'
  ```
</CodeGroup>

Usa [recuperar una ejecución de agente](/es/api-reference/agent-runs/retrieve-an-agent-run) para consultar el estado.
Usa [transmitir eventos de ejecución](/es/api-reference/agent-runs/stream-agent-run-events) para mostrar progreso en vivo.

## 5. Inspecciona la memoria después

Después de que termine la ejecución, usa la Memory Stores API para revisar qué cambió.
Los mismos archivos que el agente escribe en `/mnt/memory/acme_support` están disponibles como entradas de memoria.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm memory-stores list-entries \
    --memory-store-id mem_store_123 \
    --limit 20 \
    -H 'X-On-Behalf-Of: <end-user-id>'
  ```

  ```ts MKA1 SDK theme={null}
  const entries = await sdk.llm.memoryStores.listEntries({
    memoryStoreId: "mem_store_123",
    limit: 20,
    xOnBehalfOf: "<end-user-id>",
  });

  console.log(entries.data.map((entry) => entry.path));
  ```

  ```bash bash theme={null}
  curl 'https://apigw.mka1.com/api/v1/llm/memory_stores/mem_store_123/entries?limit=20' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>'
  ```
</CodeGroup>

Consulta la [referencia para listar entradas de memoria](/es/api-reference/memory-stores/list-memory-entries).

## Notas operativas

* Usa montajes `read_only` para memoria de referencia y `read_write` para agentes que puedan editar memoria durable.
* Deja que los agentes actualicen memoria escribiendo archivos en montajes `read_write` con la herramienta shell.
* Usa actualizaciones directas de la Memory Stores API para semillas iniciales, revisiones, correcciones administrativas o importaciones.
* Mantén las entradas pequeñas para que el agente inspeccione solo archivos relevantes durante la ejecución.
