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

# Dream over traces

> Schedule an agent to review a person's traces each night and update their memory.

Dreaming is a scheduled review of an agent's past work. In this example, a nightly schedule runs as each opted-in user, reads their recent traces, and updates their user memory.

> [!NOTE]
>
> Managed Deep Agents is in **public [beta](https://docs.langchain.com/langsmith/release-stages.md)** on [LangSmith Cloud](https://docs.langchain.com/langsmith/cloud.md) and [Bring Your Own Cloud (BYOC)](https://docs.langchain.com/langsmith/byoc.md). Use Managed Deep Agents CLI and SDK v0.10 or later for BYOC.

> [!NOTE]
>
> This Python example requires `managed-deepagents>=0.10.4`, the matching `mda` CLI, and `langsmith>=0.10.15`. Self-hosted LangSmith must be v0.16 or later.

![Mock private assistant chat alongside memory files showing an approved nightly dreaming schedule running at 03:00 UTC, updating /memories/user/AGENTS.md, and writing a skill proposal to dreaming-proposals.md.](https://mintcdn.com/langchain-5e9cc07a/bdTAbHGS6Uo5z-4d/langsmith/images/managed-deep-agents-dreaming-light.png?fit=max\&auto=format\&n=bdTAbHGS6Uo5z-4d\&q=85\&s=a34b5ef5b2eaf0f3ec29cae9d77455b9)

## Before you start

* Configure [identity](https://docs.langchain.com/langsmith/python/managed-deep-agents-identity.md) so each person signs in as themselves. User memory and per-user trace lookups require a signed-in person.
* Route each person's traces to their own LangSmith tracing project.
* Add `DREAM_TRACE_PROJECTS` to `.env` wrapped in single quotes so `mda deploy` preserves the JSON double quotes. Map MDA principal IDs to project IDs, and ensure the deployment's LangSmith credentials have read access to those projects:

```text .env theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
DREAM_TRACE_PROJECTS='{"<principal-id>": "<project-id>"}'
```

## Add personal memory

Declare [user memory](https://docs.langchain.com/langsmith/python/managed-deep-agents-memory.md) at the project root:

```python memory.py theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from managed_deepagents import MemoryLayer, define_memory

memory = define_memory(user=MemoryLayer())
```

Scheduled runs have no channel event, so select user memory in the agent factory when a run has no channel origin (such as scheduled runs and Studio). Omitting `memory` on channel runs keeps MDA's default access rules, which mount user memory in Slack direct messages and keep it off in shared channels. Requiring an interrupt on `schedule_dreaming` prompts for approval before creating a schedule:

```python agent.py theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from managed_deepagents import MemoryLayer, define_deep_agent, define_memory

from tools.dreaming import recent_user_traces, schedule_dreaming


def agent(runtime):
    extra = (
        {"memory": define_memory(user=MemoryLayer())}
        if runtime.thread is None or runtime.thread.origin is None
        else {}
    )
    return define_deep_agent(
        name="private-assistant",
        model="openai:gpt-6.1-sol",
        tools=[recent_user_traces, schedule_dreaming],
        interrupt_on={"schedule_dreaming": True},
        **extra,
    )
```

MDA always mounts the signed-in person's memory, so a prompt cannot read someone else's.

## Add the tools

`recent_user_traces` reads up to 25 of the current person's traces from the last day. `schedule_dreaming` creates a nightly schedule that runs as that person.

Install the model provider package (factory definitions do not auto-install provider packages):

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
uv add langchain-openai
```

```python tools/dreaming.py expandable theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import json
import os
from datetime import datetime, timedelta, timezone

from langchain.tools import tool
from langsmith import Client
from managed_deepagents import ManagedDeepAgentRuntime

DREAM_PROMPT = """Read your recent traces with recent_user_traces. Save useful
preferences and recurring context to /memories/user/AGENTS.md, without secrets.
Write ideas for improving your instructions or skills to
/memories/user/dreaming-proposals.md."""


def trace_project(runtime: ManagedDeepAgentRuntime) -> str | None:
    principal = runtime.server_info.principal if runtime.server_info else None
    if principal is None or principal.kind != "person":
        return None
    return json.loads(os.environ["DREAM_TRACE_PROJECTS"]).get(principal.id)


@tool
async def recent_user_traces(runtime: ManagedDeepAgentRuntime) -> str:
    """Read the current person's traces from the last day."""
    if runtime.thread.origin is not None:
        return "Ask outside Slack or other channels, including DMs."
    project = trace_project(runtime)
    if project is None:
        return "No trace project for this person."
    records = []
    async for run in Client().runs.query(
        project_ids=[project],
        min_start_time=datetime.now(timezone.utc) - timedelta(days=1),
        is_root=True,
        selects=["INPUTS", "OUTPUTS"],
        page_size=25,
    ):
        records.append(json.dumps([run.inputs, run.outputs], default=str)[:6000])
        if len(records) == 25:
            break
    return "\n".join(records) or "No recent traces."


@tool
async def schedule_dreaming(runtime: ManagedDeepAgentRuntime) -> str:
    """Schedule a nightly trace review for the current person."""
    if runtime.thread.origin is not None:
        return "Ask outside Slack or other channels, including DMs."
    if trace_project(runtime) is None:
        return "No trace project for this person."
    item = await runtime.schedules.create(
        owner={"type": "user"},
        cron="0 3 * * *",
        timezone="UTC",
        prompt=DREAM_PROMPT,
    )
    return f"Created nightly dreaming schedule {item['id']}."
```

Trace contents reach the model, so configure [trace masking](https://docs.langchain.com/langsmith/mask-inputs-outputs.md) for anything it should not see.

## Start dreaming

[Deploy the agent](https://docs.langchain.com/langsmith/python/managed-deep-agents-deploy.md), sign in, and ask it to schedule nightly dreaming from a direct conversation outside channels (such as LangSmith Studio or your own signed-in app, not Slack DMs). Approve the `schedule_dreaming` call. Each night at 03:00 UTC, the agent reviews your traces and updates `/memories/user/AGENTS.md`.

Deployed instructions and skills are read-only at runtime. To apply an idea from `/memories/user/dreaming-proposals.md`, edit `instructions.md` or the skill in your project and redeploy. To stop dreaming, [delete the schedule](https://docs.langchain.com/langsmith/python/managed-deep-agents-schedules.md#manage-schedules).

## Extend the pattern

* Review a week of traces instead of a day by changing the cron and the query window.
* Test proposed instruction changes with [evals](https://docs.langchain.com/langsmith/python/managed-deep-agents-evals.md) before deploying.
* Add a [skill](https://docs.langchain.com/langsmith/python/managed-deep-agents-skills.md) defining what is worth remembering so reviews stay consistent.

## See also

* [Schedules](https://docs.langchain.com/langsmith/python/managed-deep-agents-schedules.md): manage recurring user-owned runs.
* [Memory](https://docs.langchain.com/langsmith/python/managed-deep-agents-memory.md): configure durable memory and access policies.
* [Export traces](https://docs.langchain.com/langsmith/export-traces.md): query and paginate trace data.

***

[Connect these docs](https://docs.langchain.com/use-these-docs.md) to your agent of choice via MCP for real-time answers.

[Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/langsmith/managed-deep-agents-dreaming.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
