{"title":"Padrão de início de sessão","slug":"session-start-pattern","category":"llm-cookbook","summary":"A sequência canônica de início de sessão que todo agente LLM deve seguir.","audience":["llm"],"tags":["cookbook","session","pattern","startup"],"difficulty":"beginner","updated":"2026-06-27","word_count":262,"read_minutes":1,"llm_context":"ALWAYS at session start: 1) GET /memory/recall, 2) GET /chat/poll, 3) GET /mind/tasks?status=in_progress\nBuild system prompt from recall output.\nProcess unread chat messages before doing new work.\nResume any in_progress tasks before starting new ones.\nStore new learnings as they happen — don't wait until session end.\n","lang":"pt","translated":true,"requested_lang":"pt","content_markdown":"\n# Padrão de início de sessão\n\nToda sessão de agente LLM deve seguir esta sequência canônica de inicialização.\nPular passos leva a contexto perdido, mensagens perdidas e tarefas esquecidas.\n\n## O padrão\n\n```\n1. Recall all memories\n2. Poll for unread chat messages\n3. Check in-progress tasks\n4. Build context from results\n5. Process pending items before new work\n```\n\n## Implementação\n\n### Passo 1: recupere todas as memórias\n\n> [!CRITICAL]\n> Esta é a chamada mais importante. Sem ela, você não tem memória de sessões\n> passadas.\n\n```bash\ncurl -H \"Authorization: Bearer YOUR_MIND_KEY\" \\\n     https://synapse.schaefer.zone/memory/recall\n```\n\nRetorna um resumo em texto puro de todas as memórias, ordenado por prioridade.\n\n### Passo 2: faça poll por mensagens de chat não lidas\n\n```bash\ncurl -H \"Authorization: Bearer YOUR_MIND_KEY\" \\\n     https://synapse.schaefer.zone/chat/poll\n```\n\nRetorna mensagens não lidas do humano. **Automaticamente as marca como lidas.**\n\n### Passo 3: verifique tarefas em andamento\n\n```bash\ncurl -H \"Authorization: Bearer YOUR_MIND_KEY\" \\\n     \"https://synapse.schaefer.zone/mind/tasks?status=in_progress\"\n```\n\nRetorna tarefas em que você estava trabalhando na última sessão.\n\n### Passo 4: construa o contexto\n\nCombine as três respostas no seu prompt de sistema:\n\n```python\ndef build_context(memories, messages, tasks):\n    context = f\"\"\"# SESSION CONTEXT\n\n## Memories (from previous sessions)\n{memories}\n\n## Unread Messages from Human\n{format_messages(messages)}\n\n## Active Tasks\n{format_tasks(tasks)}\n\n## Instructions\n- Address unread messages first\n- Resume active tasks before starting new work\n- Store new learnings as they happen (POST /memory)\n- Poll for new messages every 30-60 seconds\n\"\"\"\n    return context\n```\n\n### Passo 5: processe itens pendentes\n\n```\nFor each unread message:\n  - Acknowledge receipt (POST /chat/reply)\n  - Address the message content\n  - Store any new commitments as memories\n\nFor each in-progress task:\n  - Recall why you were working on it\n  - Continue from where you left off\n  - Update task status as you progress\n```\n\n## Exemplo completo\n\n```python\nimport os\nimport requests\n\nURL = \"https://synapse.schaefer.zone\"\nKEY = os.environ[\"SYNAPSE_MIND_KEY\"]\n\ndef session_start():\n    \"\"\"Canonical session start sequence.\"\"\"\n    headers = {\"Authorization\": f\"Bearer {KEY}\"}\n    \n    # 1. Recall memories\n    r = requests.get(f\"{URL}/memory/recall\", headers=headers)\n    memories = r.text\n    \n    # 2. Poll chat\n    r = requests.get(f\"{URL}/chat/poll\", headers=headers)\n    messages = r.json().get(\"messages\", [])\n    \n    # 3. Check tasks\n    r = requests.get(f\"{URL}/mind/tasks?status=in_progress\", headers=headers)\n    tasks = r.json().get(\"tasks\", [])\n    \n    # 4. Build context\n    context = f\"\"\"You are a Synapse-enabled AI assistant.\n\nMEMORIES FROM PREVIOUS SESSIONS:\n{memories}\n\nUNREAD MESSAGES FROM HUMAN:\n{chr(10).join(f'- {m[\"content\"]}' for m in messages) or 'None'}\n\nACTIVE TASKS:\n{chr(10).join(f'- [{t[\"id\"]}] {t[\"title\"]}: {t.get(\"description\", \"\")}' for t in tasks) or 'None'}\n\nINSTRUCTIONS:\n1. Acknowledge each unread message\n2. Resume active tasks\n3. Store new learnings via POST /memory\n4. Poll /chat/poll every 30-60 seconds\n\"\"\"\n    return context\n\n# At session start\nsystem_prompt = session_start()\n# Pass to LLM...\n```\n\n## Erros comuns\n\n> [!WARNING]\n> - **Pular o recall** — você começa sem contexto, repete erros passados\n> - **Esquecer de fazer poll no chat** — mensagens do humano ficam sem resposta\n> - **Ignorar tarefas ativas** — trabalho é esquecido no meio da execução\n> - **Não armazenar nada** — a sessão não produz valor persistente\n\n## Variações\n\n### Padrão mínimo (LLMs de contexto baixo)\n\nPara LLMs com janelas de contexto pequenas, pule o recall completo:\n\n```bash\n# Just get stats, not full content\ncurl -H \"Authorization: Bearer $KEY\" .../memory/stats\n```\n\nEntão busque tópicos específicos conforme necessário:\n\n```bash\ncurl -H \"Authorization: Bearer $KEY\" \".../memory/search?q=current+project\"\n```\n\n### Padrão agressivo (agentes de longa duração)\n\nPara agentes que rodam por horas, adicione re-recall periódico:\n\n```python\nwhile working:\n    if time.time() - last_recall > 3600:  # every hour\n        memories = recall()\n        last_recall = time.time()\n    # ... do work ...\n```\n\n## Próximos passos\n\n- [Estratégia de tagueamento de memória](/docs/llm-cookbook/memory-tagging-strategy)\n- [Workflow orientado por tarefas](/docs/llm-cookbook/task-driven-workflow)\n- [Padrão de poll de chat](/docs/llm-cookbook/chat-polling-pattern)\n","content_html":"<h1>Padrão de início de sessão</h1>\n<p>Toda sessão de agente LLM deve seguir esta sequência canônica de inicialização.\nPular passos leva a contexto perdido, mensagens perdidas e tarefas esquecidas.</p>\n<h2>O padrão</h2>\n<pre><code class=\"hljs language-plaintext\">1. Recall all memories\n2. Poll for unread chat messages\n3. Check in-progress tasks\n4. Build context from results\n5. Process pending items before new work</code></pre><h2>Implementação</h2>\n<h3>Passo 1: recupere todas as memórias</h3>\n<div class=\"callout callout-critical\">Esta é a chamada mais importante. Sem ela, você não tem memória de sessões\npassadas.</div><pre><code class=\"hljs language-bash\">curl -H <span class=\"hljs-string\">&quot;Authorization: Bearer YOUR_MIND_KEY&quot;</span> \\\n     https://synapse.schaefer.zone/memory/recall</code></pre><p>Retorna um resumo em texto puro de todas as memórias, ordenado por prioridade.</p>\n<h3>Passo 2: faça poll por mensagens de chat não lidas</h3>\n<pre><code class=\"hljs language-bash\">curl -H <span class=\"hljs-string\">&quot;Authorization: Bearer YOUR_MIND_KEY&quot;</span> \\\n     https://synapse.schaefer.zone/chat/poll</code></pre><p>Retorna mensagens não lidas do humano. <strong>Automaticamente as marca como lidas.</strong></p>\n<h3>Passo 3: verifique tarefas em andamento</h3>\n<pre><code class=\"hljs language-bash\">curl -H <span class=\"hljs-string\">&quot;Authorization: Bearer YOUR_MIND_KEY&quot;</span> \\\n     <span class=\"hljs-string\">&quot;https://synapse.schaefer.zone/mind/tasks?status=in_progress&quot;</span></code></pre><p>Retorna tarefas em que você estava trabalhando na última sessão.</p>\n<h3>Passo 4: construa o contexto</h3>\n<p>Combine as três respostas no seu prompt de sistema:</p>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">build_context</span>(<span class=\"hljs-params\">memories, messages, tasks</span>):\n    context = <span class=\"hljs-string\">f&quot;&quot;&quot;# SESSION CONTEXT\n\n## Memories (from previous sessions)\n<span class=\"hljs-subst\">{memories}</span>\n\n## Unread Messages from Human\n<span class=\"hljs-subst\">{format_messages(messages)}</span>\n\n## Active Tasks\n<span class=\"hljs-subst\">{format_tasks(tasks)}</span>\n\n## Instructions\n- Address unread messages first\n- Resume active tasks before starting new work\n- Store new learnings as they happen (POST /memory)\n- Poll for new messages every 30-60 seconds\n&quot;&quot;&quot;</span>\n    <span class=\"hljs-keyword\">return</span> context</code></pre><h3>Passo 5: processe itens pendentes</h3>\n<pre><code class=\"hljs language-plaintext\">For each unread message:\n  - Acknowledge receipt (POST /chat/reply)\n  - Address the message content\n  - Store any new commitments as memories\n\nFor each in-progress task:\n  - Recall why you were working on it\n  - Continue from where you left off\n  - Update task status as you progress</code></pre><h2>Exemplo completo</h2>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-keyword\">import</span> os\n<span class=\"hljs-keyword\">import</span> requests\n\nURL = <span class=\"hljs-string\">&quot;https://synapse.schaefer.zone&quot;</span>\nKEY = os.environ[<span class=\"hljs-string\">&quot;SYNAPSE_MIND_KEY&quot;</span>]\n\n<span class=\"hljs-keyword\">def</span> <span class=\"hljs-title function_\">session_start</span>():\n    <span class=\"hljs-string\">&quot;&quot;&quot;Canonical session start sequence.&quot;&quot;&quot;</span>\n    headers = {<span class=\"hljs-string\">&quot;Authorization&quot;</span>: <span class=\"hljs-string\">f&quot;Bearer <span class=\"hljs-subst\">{KEY}</span>&quot;</span>}\n    \n    <span class=\"hljs-comment\"># 1. Recall memories</span>\n    r = requests.get(<span class=\"hljs-string\">f&quot;<span class=\"hljs-subst\">{URL}</span>/memory/recall&quot;</span>, headers=headers)\n    memories = r.text\n    \n    <span class=\"hljs-comment\"># 2. Poll chat</span>\n    r = requests.get(<span class=\"hljs-string\">f&quot;<span class=\"hljs-subst\">{URL}</span>/chat/poll&quot;</span>, headers=headers)\n    messages = r.json().get(<span class=\"hljs-string\">&quot;messages&quot;</span>, [])\n    \n    <span class=\"hljs-comment\"># 3. Check tasks</span>\n    r = requests.get(<span class=\"hljs-string\">f&quot;<span class=\"hljs-subst\">{URL}</span>/mind/tasks?status=in_progress&quot;</span>, headers=headers)\n    tasks = r.json().get(<span class=\"hljs-string\">&quot;tasks&quot;</span>, [])\n    \n    <span class=\"hljs-comment\"># 4. Build context</span>\n    context = <span class=\"hljs-string\">f&quot;&quot;&quot;You are a Synapse-enabled AI assistant.\n\nMEMORIES FROM PREVIOUS SESSIONS:\n<span class=\"hljs-subst\">{memories}</span>\n\nUNREAD MESSAGES FROM HUMAN:\n<span class=\"hljs-subst\">{<span class=\"hljs-built_in\">chr</span>(<span class=\"hljs-number\">10</span>).join(<span class=\"hljs-string\">f&#x27;- <span class=\"hljs-subst\">{m[<span class=\"hljs-string\">&quot;content&quot;</span>]}</span>&#x27;</span> <span class=\"hljs-keyword\">for</span> m <span class=\"hljs-keyword\">in</span> messages) <span class=\"hljs-keyword\">or</span> <span class=\"hljs-string\">&#x27;None&#x27;</span>}</span>\n\nACTIVE TASKS:\n<span class=\"hljs-subst\">{<span class=\"hljs-built_in\">chr</span>(<span class=\"hljs-number\">10</span>).join(<span class=\"hljs-string\">f&#x27;- [<span class=\"hljs-subst\">{t[<span class=\"hljs-string\">&quot;id&quot;</span>]}</span>] <span class=\"hljs-subst\">{t[<span class=\"hljs-string\">&quot;title&quot;</span>]}</span>: <span class=\"hljs-subst\">{t.get(<span class=\"hljs-string\">&quot;description&quot;</span>, <span class=\"hljs-string\">&quot;&quot;</span>)}</span>&#x27;</span> <span class=\"hljs-keyword\">for</span> t <span class=\"hljs-keyword\">in</span> tasks) <span class=\"hljs-keyword\">or</span> <span class=\"hljs-string\">&#x27;None&#x27;</span>}</span>\n\nINSTRUCTIONS:\n1. Acknowledge each unread message\n2. Resume active tasks\n3. Store new learnings via POST /memory\n4. Poll /chat/poll every 30-60 seconds\n&quot;&quot;&quot;</span>\n    <span class=\"hljs-keyword\">return</span> context\n\n<span class=\"hljs-comment\"># At session start</span>\nsystem_prompt = session_start()\n<span class=\"hljs-comment\"># Pass to LLM...</span></code></pre><h2>Erros comuns</h2>\n<div class=\"callout callout-warn\"></div><h2>Variações</h2>\n<h3>Padrão mínimo (LLMs de contexto baixo)</h3>\n<p>Para LLMs com janelas de contexto pequenas, pule o recall completo:</p>\n<pre><code class=\"hljs language-bash\"><span class=\"hljs-comment\"># Just get stats, not full content</span>\ncurl -H <span class=\"hljs-string\">&quot;Authorization: Bearer <span class=\"hljs-variable\">$KEY</span>&quot;</span> .../memory/stats</code></pre><p>Então busque tópicos específicos conforme necessário:</p>\n<pre><code class=\"hljs language-bash\">curl -H <span class=\"hljs-string\">&quot;Authorization: Bearer <span class=\"hljs-variable\">$KEY</span>&quot;</span> <span class=\"hljs-string\">&quot;.../memory/search?q=current+project&quot;</span></code></pre><h3>Padrão agressivo (agentes de longa duração)</h3>\n<p>Para agentes que rodam por horas, adicione re-recall periódico:</p>\n<pre><code class=\"hljs language-python\"><span class=\"hljs-keyword\">while</span> working:\n    <span class=\"hljs-keyword\">if</span> time.time() - last_recall &gt; <span class=\"hljs-number\">3600</span>:  <span class=\"hljs-comment\"># every hour</span>\n        memories = recall()\n        last_recall = time.time()\n    <span class=\"hljs-comment\"># ... do work ...</span></code></pre><h2>Próximos passos</h2>\n<ul>\n<li><a href=\"/docs/llm-cookbook/memory-tagging-strategy\">Estratégia de tagueamento de memória</a></li>\n<li><a href=\"/docs/llm-cookbook/task-driven-workflow\">Workflow orientado por tarefas</a></li>\n<li><a href=\"/docs/llm-cookbook/chat-polling-pattern\">Padrão de poll de chat</a></li>\n</ul>\n","urls":{"html":"/docs/llm-cookbook/session-start-pattern","text":"/docs/llm-cookbook/session-start-pattern?format=text","json":"/docs/llm-cookbook/session-start-pattern?format=json","llm":"/docs/llm-cookbook/session-start-pattern?format=llm"},"translations_available":["en","zh","hi","es","fr","ar","pt","ru","ja","de","it","ko","nl","pl","tr","sv","vi","th","id","uk"]}