Daydreams Logo
Extra reading

context.ts

This file provides the essential context function, which you use to define different "modes" or "workspaces" for your agent. Think of each context definition as a blueprint for a specific task or interaction type, like handling a chat conversation, managing a game, or performing a specific workflow. Each active instance of a context (e.g., a specific chat session) gets its own separate memory and state.

How to Use

You'll typically define your contexts in separate files using the context({...}) function and then pass these definitions to createDreams. Key things you define inside context({...}):

  • type: A unique name for this type of context (e.g., "chat", "projectBoard").
  • schema: (Using Zod) Defines the arguments needed to identify a specific instance of this context (e.g., { sessionId: z.string() } for a chat).
  • create: A function that returns the initial structure and default values for this context's persistent memory (ctx.memory). This runs the first time an instance is accessed.
  • render: (Optional) A function that formats the current state (ctx.memory) of an instance into text (or XML) for the AI model to understand the current situation within that specific workspace.
  • actions, inputs, outputs: (Optional, often added via .setActions(), etc.) Link specific tools (Actions), data sources (Inputs), and response methods (Outputs) directly to this context type.

Benefit

Contexts allow your agent to manage multiple tasks or interactions simultaneously without getting confused. Each context instance has its own dedicated memory (ctx.memory) where it stores relevant information (like chat history or task lists) persistently. The render function ensures the AI model gets only the relevant state for the specific task it's working on at that moment. Associating actions/inputs/outputs keeps your agent's capabilities organized.

Anticipated Questions

  • "What's the difference between context memory (ctx.memory) and working memory?" ctx.memory is the persistent storage for a specific context instance (like chat history saved to a database). Working memory is temporary storage used during a single agent run cycle to track the steps (inputs, thoughts, actions) of that specific interaction.
  • "How do I identify a specific chat session if I have multiple?" You use the schema you define to pass identifying arguments (like a sessionId) when calling agent.run or agent.send. The optional key function in the context definition helps create truly unique IDs if needed (e.g., chat:session-xyz).
  • "How does the AI know what happened in this specific chat?" The render function you define formats the relevant parts of ctx.memory (e.g., recent messages) and includes it in the prompt sent to the AI model for that specific context instance.

On this page