handlers.ts
This file holds the internal "handlers" that the Daydreams agent uses during its
execution cycle (agent.run
). When the agent receives input, or when the AI
model decides to call an action or send an output, the functions in this file
are responsible for processing those requests correctly. Think of it as the
agent's internal dispatcher and validator.
How it Affects You
You don't call functions from this file directly. It works behind the scenes, but it's where several important things happen based on how you defined your actions, inputs, and outputs:
- Validation: When the AI model provides arguments for your
action
or content/attributes for youroutput
, the code here validates that data against theschema
you defined using Zod. If the validation fails, it prevents yourhandler
code from running with bad data. - Parsing: It parses the arguments/content provided by the AI model (which
might be in JSON or XML format) into a usable JavaScript object/value before
passing it to your
handler
. - Template Resolution: If you use templates like
{{calls[0].someValue}}
in your action arguments (as described in Prompting), theresolveTemplates
function here handles resolving those values before your action'shandler
is called. - Handler Execution: It prepares the necessary context (including the
correct memory scopes like
ctx.memory
orctx.actionMemory
) and then calls the specifichandler
function you wrote in youraction
,input
, oroutput
definition. For actions, it uses theTaskRunner
to queue the execution. - Error Handling: It defines specific errors like
NotFoundError
(if the AI calls a non-existent action/output) andParsingError
(if validation fails).
Benefit
These handlers ensure that the interaction between the AI model's requests and your custom code (in action/output/input handlers) is safe, validated, and correctly contextualized. It bridges the gap between the AI's structured text output and the execution of your JavaScript/TypeScript functions, handling potential errors and data transformations along the way.
Anticipated Questions
- "Is this where my
action
'shandler
function actually runs?" Yes, functions in this file (specificallyhandleActionCall
which usesrunAction
fromtasks/index.ts
) are responsible for preparing the context and ultimately calling thehandler
you defined for your action (via theTaskRunner
). - "What happens if the AI provides arguments that don't match my action's Zod
schema?" The validation logic within
prepareActionCall
in this file will catch the mismatch, throw aParsingError
, and prevent your action'shandler
from being called with invalid data. - "How does the agent know which specific context's memory (
ctx.memory
) to give my action handler?" The logic here (within functions likeprepareActionCall
andhandleOutput
) identifies the correctContextState
based on the current run and makes itsmemory
available in thectx
object passed to your handler.