> ## 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.

# Criar um agente com armazenamentos de memória

> Monte memória durável no ambiente de shell gerenciado de um agente salvo e mantenha-a atualizada entre execuções.

Use armazenamentos de memória quando precisar de contexto durável, utilizável entre usuários, sessões e agentes, e acessível por aplicações externas.
Os armazenamentos de memória são úteis para guardar anotações de contas, manuais de suporte, relatórios de bugs ou qualquer conteúdo que você queira reutilizar em várias execuções de agentes.

Referência da API:

* [Endpoints de Memory Stores](/pt/api-reference/memory-stores/create-memory-store)
* [Endpoints de entradas de Memory Store](/pt/api-reference/memory-stores/create-memory-entry)
* [Endpoints de coleção e execução de agentes](/pt/api-reference/agents/create-an-agent)

## 1. Crie o armazenamento de memória

Crie um armazenamento para um corpo de conhecimento durável.
Use `instructions` para descrever como as entradas devem ser escritas e mantidas.

<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>", // optional — attribute the request to one of your end users
    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);
  ```

  ```ts fetch theme={null}
  const storeResponse = await fetch("https://apigw.mka1.com/api/v1/llm/memory_stores", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer <mka1-api-key>",
      "X-On-Behalf-Of": "<end-user-id>",
    },
    body: JSON.stringify({
      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",
      },
    }),
  });

  const store = await storeResponse.json();
  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>

A resposta inclui um ID de armazenamento de memória, como `mem_store_...`.

A `visibility` determina se esse armazenamento de memória pode ser usado somente para um `X-On-Behalf-Of` específico (`private`) ou se qualquer usuário, independentemente de `X-On-Behalf-Of`, pode acessá-lo (`workspace`).

Consulte a [referência da API Create memory store](/pt/api-reference/memory-stores/create-memory-store) para ver o esquema completo.

## 2. Adicione entradas de memória

As entradas são endereçáveis por `path`.
Use caminhos previsíveis para que o agente possa encontrar arquivos no armazenamento 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);
  ```

  ```ts fetch theme={null}
  const entryResponse = await fetch(
    "https://apigw.mka1.com/api/v1/llm/memory_stores/mem_store_123/entries",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer <mka1-api-key>",
        "X-On-Behalf-Of": "<end-user-id>",
      },
      body: JSON.stringify({
        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",
        },
      }),
    },
  );

  const entry = await entryResponse.json();
  console.log(entry.id, entry.content_hash);
  ```

  ```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>

A resposta da entrada inclui um ID de entrada e um hash de conteúdo.
Salve ambos quando sua aplicação puder atualizar a entrada posteriormente.

## 3. Crie o agente salvo

Crie um agente com uma ferramenta `shell` e monte o armazenamento de memória no ambiente de shell.
O objeto de montagem usa:

* `store_id`: o ID do armazenamento de memória a montar
* `label`: o nome do diretório em `/mnt/memory`
* `access`: `read_only` ou `read_write`
* `description` e `instructions`: contexto opcional sobre como o agente deve usar o armazenamento montado

Use `read_only` para materiais de referência.
Use `read_write` somente quando o agente deve ter permissão para atualizar a memória pelo sistema de arquivos montado.
Quando o agente grava, edita ou exclui arquivos dentro de uma montagem `read_write`, o sandbox sincroniza essas alterações de volta ao armazenamento de memória após a conclusão do comando de shell.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 agents create --body '{
    "name": "account-support-agent",
    "description": "Answers support questions with durable account context.",
    "model": "meetkai:functionary-pt",
    "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: "meetkai:functionary-pt",
      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);
  ```

  ```ts fetch theme={null}
  const agentResponse = await fetch("https://apigw.mka1.com/api/v1/agents", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer <mka1-api-key>",
      "X-On-Behalf-Of": "<end-user-id>",
    },
    body: JSON.stringify({
      name: "account-support-agent",
      description: "Answers support questions with durable account context.",
      model: "meetkai:functionary-pt",
      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",
      },
    }),
  });

  const agent = await agentResponse.json();
  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": "meetkai:functionary-pt",
      "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>

Consulte a [referência da API Create an agent](/pt/api-reference/agents/create-an-agent) para ver a estrutura completa da solicitação de agente salvo.

## 4. Execute o agente e atualize a memória

Execute o agente salvo com a entrada específica da tarefa.
O agente pode inspecionar os arquivos de memória montados pela ferramenta de shell quando precisar de contexto durável.
Se o armazenamento montado for `read_write`, o agente também poderá atualizar a memória gravando arquivos em `/mnt/memory/<label>`.
O sandbox restaura os arquivos montados antes da execução do comando de shell, cria um instantâneo deles e sincroniza os arquivos alterados de volta ao armazenamento após a conclusão do comando.

<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);
  ```

  ```ts fetch theme={null}
  const runResponse = await fetch("https://apigw.mka1.com/api/v1/agents/agt_123/runs", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer <mka1-api-key>",
      "X-On-Behalf-Of": "<end-user-id>",
    },
    body: JSON.stringify({
      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",
      },
    }),
  });

  const run = await runResponse.json();
  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>

Use [Retrieve an agent run](/pt/api-reference/agent-runs/retrieve-an-agent-run) para consultar o status.
Use [Stream agent run events](/pt/api-reference/agent-runs/stream-agent-run-events) para acompanhar o progresso em tempo real.
O agente deve usar a ferramenta de shell para ler os arquivos montados e gravar atualizações duráveis diretamente na montagem `read_write`.

## 5. Inspecione a memória após a execução

Após a conclusão da execução, use a API Memory Stores para inspecionar o que mudou.
Os mesmos arquivos que o agente grava em `/mnt/memory/acme_support` ficam disponíveis como entradas de memória.

<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));
  ```

  ```ts fetch theme={null}
  const entriesResponse = await fetch(
    "https://apigw.mka1.com/api/v1/llm/memory_stores/mem_store_123/entries?limit=20",
    {
      headers: {
        Authorization: "Bearer <mka1-api-key>",
        "X-On-Behalf-Of": "<end-user-id>",
      },
    },
  );

  const entries = await entriesResponse.json();
  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>

Consulte a [referência da API List memory entries](/pt/api-reference/memory-stores/list-memory-entries) e a [referência da API Retrieve memory entry](/pt/api-reference/memory-stores/retrieve-memory-entry) para detalhes da resposta.

## Observações operacionais

* Use montagens `read_only` para memória de referência e montagens `read_write` para agentes confiáveis para editar memória durável.
* Permita que os agentes atualizem a memória durável gravando arquivos em montagens `read_write` pela ferramenta de shell.
* Use atualizações diretas da API Memory Stores para semeamento, fluxos de revisão, correções administrativas ou importações.
* Mantenha as entradas de memória pequenas o suficiente para que o agente inspecione somente os arquivos relevantes durante uma execução.
* Use valores `path` estáveis para que sua aplicação possa mapear objetos do produto para entradas de memória.
* Armazene IDs de objetos externos em `metadata` quando precisar reconciliar a memória com seu banco de dados.
* Exclua entradas obsoletas com o [endpoint Delete memory entry](/pt/api-reference/memory-stores/delete-memory-entry).
