The AgentB Facade
The AgentB facade is your primary entry point for quickly setting up and using the AgentB framework in common scenarios. It's a static class designed to simplify initialization, tool provider registration, and the creation of HTTP streaming handlers.
While the ApiInteractionManager offers more granular control (covered in a separate guide), the AgentB facade handles many underlying complexities for you.
Key Responsibilities of the AgentB Facade
AgentB FacadeSimplified Initialization (
AgentB.initialize()):Sets up the default LLM client (currently
OpenAIAdapter).Initializes default storage adapters (
MemoryStoragefor threads, messages, and agent runs).Establishes global default configurations for agent runs.
Allows registration of initial
ToolProviderSourceConfigs.
Tool Provider Registration (
AgentB.registerToolProvider()):Manages a list of
ToolProviderSourceConfigobjects. These configurations tell AgentB how to create tool providers (primarilyOpenAPIConnectorinstances).When an agent interaction starts, these configurations are used by an internal
ApiInteractionManager(and itsToolsetOrchestrator) to make tools available to the agent.
Core Interaction Logic (
AgentB.runHttpInteractionStream()):The fundamental method for processing an agent interaction and receiving a stream of events.
It takes a
threadId, the user'sLLMMessage, and optionalAgentRunConfigoverrides.Internally, it ensures an
ApiInteractionManageris initialized, determines the correct agent and tools based on registered providers, and then runs the agent.Returns an
AsyncGenerator<AgentEvent, void, undefined>, making it suitable for various integrations, not just Express.js.
HTTP Handler Generation (
AgentB.getExpressStreamingHttpHandler()):Provides a ready-to-use request handler for Express.js applications.
This handler sets up a Server-Sent Events (SSE) stream.
It uses
runHttpInteractionStreaminternally.Offers callbacks to customize:
getThreadId: How to determine or create athreadIdfrom the HTTP request.getUserMessage: How to extract the user's prompt/message from the request.authorizeRequest: For request-level authorization and providing dynamicPerProviderAuthOverrides.initialAgentRunConfig: To set default run configurations specifically for requests hitting this handler.
How It Works Internally (Simplified View)
When you use the AgentB facade:
AgentB.initialize(options):An
ILLMClientis created (e.g.,OpenAIAdapterusingoptions.llmProviderorOPENAI_API_KEY).IMessageStorage,IThreadStorage,IAgentRunStorageare set up (defaulting toMemoryStorageif not provided inoptions).globalDefaultAgentRunConfigis established.Any
toolProvidersinoptionsare stored asToolProviderSourceConfigs.
AgentB.registerToolProvider(sourceConfig):The
sourceConfigis added to an internal list.This signals that the internal
ApiInteractionManagermight need to be re-initialized or updated before the next interaction.
AgentB.runHttpInteractionStream(threadId, userMessage, runConfigOverride)or whengetExpressStreamingHttpHandlerprocesses a request:It retrieves or creates an internal
ApiInteractionManagerinstance (getOrCreateApiInteractionManager()).Mode Determination: The
ApiInteractionManagerintelligently decides its operational mode (genericOpenApi,hierarchicalPlanner, etc.) based on the number and type of registeredToolProviderSourceConfigs:0 providers: Defaults to a mode with no tools (basic conversational agent).
1 OpenAPI provider: Often defaults to
genericOpenApimode, making tools from that single API spec directly available (including potentially agenericHttpRequesttool).Multiple providers (or complex single provider): Typically defaults to
hierarchicalPlannermode. The main agent will be aPlanningAgentequipped with aDelegateToSpecialistTool. The registered providers are used by aToolsetOrchestratorto createIToolSets (specialists) that the planner can delegate to.
The
ApiInteractionManagerthen ensures it's fully initialized (e.g.,OpenAPIConnectors load their specs,ToolsetOrchestratorcreates toolsets).An
IAgentContextis assembled with all necessary components (LLM client, the appropriate tool provider for the determined mode, storages, etc.) and the finalAgentRunConfig.An agent instance (e.g.,
BaseAgentorPlanningAgent, depending on the mode and AIM's logic) is created.The agent's
run()method is called, yielding the stream ofAgentEvents.
AgentBInitializationOptions
AgentBInitializationOptionsWhen calling AgentB.initialize(options), you can provide:
llmProvider?: AgentBLLMProviderConfig:provider: 'openai' | string: Specifies the LLM provider (currently 'openai').apiKey?: string: API key (overridesOPENAI_API_KEYenv var).model?: string: Default model for this provider (e.g., 'gpt-4o-mini').options?: Record<string, any>: Additional options for the LLM adapter (e.g.,baseURLfor OpenAI).
messageStorage?: IMessageStorage: Custom message storage implementation.agentRunStorage?: IAgentRunStorage: Custom agent run storage.threadStorage?: IThreadStorage: Custom thread storage.defaultAgentRunConfig?: Partial<AgentRunConfig>: Global default settings for all agent runs (e.g., temperature, system prompt).toolProviders?: ToolProviderSourceConfig[]: An initial list of configurations for tool providers.
ToolProviderSourceConfig
ToolProviderSourceConfigThis is how you tell AgentB about your APIs or other tool sources:
id: Crucial for identifying the provider, especially for dynamic authentication overrides.openapiConnectorOptions:specUrl?: string: URL to the OpenAPI spec.spec?: OpenAPISpec: Pre-loaded OpenAPI spec object.authentication?: ConnectorAuthentication: Static auth config for this API.businessContextText?: string: Context for prompts.Note:
sourceIdwithinopenapiConnectorOptionsis automatically set by AgentB using the top-levelid.
AgentBExpressHttpHandlerOptions
AgentBExpressHttpHandlerOptionsWhen using AgentB.getExpressStreamingHttpHandler(handlerOptions):
getThreadId?: (req: any, threadStorage: IThreadStorage) => Promise<string>:Receives the Express request (
req) and the initializedthreadStorage.Should return a
Promise<string>resolving to thethreadId.Default behavior: uses
req.body.threadIdorreq.query.threadId; if not found or invalid, creates a new thread.
getUserMessage?: (req: any) => Promise<string | LLMMessage>:Receives
req.Should return a
Promiseresolving to the user's prompt (string) or a fullLLMMessageobject.Default: expects
req.body.promptas a string.
authorizeRequest?: (req: any, threadId: string) => Promise<boolean | PerProviderAuthOverrides>:Receives
reqand the determinedthreadId.Return
true: Authorized, use static/default tool authentication.Return
false: Forbidden (handler sends 403).Return
PerProviderAuthOverrides: Authorized, use these dynamic auth details for specific tool providers (matched by theiridfromToolProviderSourceConfig).
initialAgentRunConfig?: Partial<AgentRunConfig>:Specific
AgentRunConfigdefaults or overrides for requests handled by this specific Express route. These merge with global defaults.
When to Use the Facade vs. ApiInteractionManager
ApiInteractionManagerUse
AgentBFacade for:Quickly setting up standard agent interaction patterns, especially HTTP streaming servers.
Applications where the default mode determination (based on registered providers) is suitable.
Simpler projects or prototypes.
Use
ApiInteractionManagerdirectly for:Fine-grained control over the operational mode (
genericOpenApi,hierarchicalPlanner).Using multiple, differently configured
ApiInteractionManagerinstances within the same application (e.g., different agents for different API routes).Complex scenarios where you need to directly instantiate and configure
ToolsetOrchestratororOpenAPIConnectors with specific, non-standard tool grouping strategies.Registering custom
IToolProviderinstances directly (asApiInteractionManageroptions can be more flexible here than the facade's currentToolProviderSourceConfig-based registration).Unit testing individual components of the agent system.
The AgentB facade is built on top of ApiInteractionManager and other core components, providing a convenient layer of abstraction. Understanding both gives you the full power of the AgentB framework.
Last updated