serviceProvider.ts
This file provides the service
helper function, which you use to define how
shared resources or external clients (like an API client, database connection,
or special utility) should be managed by the Daydreams framework. It ensures
these services are set up correctly and are ready to use when your agent needs
them.
How to Use
You typically define a service in its own file using service({...})
and then
include it in an Extension
. Inside the service({...})
call, you can define:
register(container)
: (Optional) A function where you tell the agent's DI Container (agent.container
) how to create this service instance. Often, you'll usecontainer.singleton('serviceName', () => new MyServiceClient(...))
here to ensure only one instance is created.boot(container)
: (Optional) Anasync
function where you perform any necessary initialization after all services have been registered (e.g., connecting to the API using credentials maybe resolved from the container). This runs whenagent.start()
is called.
Benefit
Defining services this way ensures proper setup and teardown, especially for
resources needing asynchronous initialization (boot
). It integrates smoothly
with the DI Container, making services easily accessible via
agent.container.resolve('serviceName')
in your actions or other components,
without them needing to know the setup details. Bundling services in Extensions
makes them reusable.
Anticipated Questions
- "When should I use a
service
vs just putting logic in anaction
?" Use aservice
for shared, reusable components, especially those managing connections to external systems or requiring specific setup/initialization steps (boot
). Actions are better for defining specific tasks the agent can perform, which might use one or more services obtained from the container. - "What's the difference between
register
andboot
?"register
runs first and only tells the container how to create the service.boot
runs later (duringagent.start()
) and performs the actual initialization (like connecting), potentially using other services that were registered earlier. - "Do I need to call
createServiceManager()
?" No, this is handled internally bycreateDreams
. You just define your services using theservice
helper.