Skip to content

platform-intelligence

Multi-provider AI text generation library supporting OpenAI, Anthropic, Google Generative AI, and Grok. Tool orchestration is delegated to the AI SDK through native and provider-defined tool definitions, toolChoice, activeTools, and stopWhen. Advanced use cases can pass native AI SDK prompts, request-level models, provider options, headers, telemetry, output settings, and step hooks through the platform generator.

Package: @breadstone/archipel-platform-intelligence

npm install @breadstone/archipel-platform-intelligence

Quick Start

typescript
import { Module } from '@nestjs/common';
import { IntelligenceModule, IntelligenceProviderNames } from '@breadstone/archipel-platform-intelligence';
import { loadOpenAILanguageModel } from '@breadstone/archipel-platform-intelligence/providers/openai';

@Module({
  imports: [
    IntelligenceModule.register({
      providerLoaders: {
        [IntelligenceProviderNames.OpenAI]: loadOpenAILanguageModel,
      },
    }),
  ],
})
export class AppModule {}

Provider Subpaths

Import only the providers you need:

ProviderSubpath
OpenAI@breadstone/archipel-platform-intelligence/providers/openai
Anthropic@breadstone/archipel-platform-intelligence/providers/anthropic
Google@breadstone/archipel-platform-intelligence/providers/google
Grok@breadstone/archipel-platform-intelligence/providers/grok

Provider-native tool wrappers are exported through matching /tools subpaths, for example @breadstone/archipel-platform-intelligence/providers/grok/tools.


Tool Registration

Tools can be normal Nest providers or direct IIntelligenceTool instances. Register classes for custom application tools, or register provider-native wrappers from provider subpaths.

typescript
import { Injectable, Module } from '@nestjs/common';
import { tool, type Tool } from 'ai';
import { z } from 'zod';
import { IntelligenceModule, IntelligenceProviderNames, IntelligenceToolBase } from '@breadstone/archipel-platform-intelligence';
import { loadOpenAILanguageModel } from '@breadstone/archipel-platform-intelligence/providers/openai';

interface ICustomerSearchInput {
  readonly query: string;
}

interface ICustomerSearchOutput {
  readonly customers: ReadonlyArray<string>;
}

@Injectable()
export class CustomerSearchTool extends IntelligenceToolBase<ICustomerSearchInput, ICustomerSearchOutput> {
  public override get name(): string {
    return 'searchCustomers';
  }

  public override get tool(): Tool<ICustomerSearchInput, ICustomerSearchOutput> {
    return tool({
      description: 'Searches customers by name, email, or company.',
      inputSchema: z.object({
        query: z.string().describe('Customer search query'),
      }),
      execute: async (input) => ({ customers: [input.query] }),
    });
  }
}

@Module({
  imports: [
    IntelligenceModule.register({
      providerLoaders: {
        [IntelligenceProviderNames.OpenAI]: loadOpenAILanguageModel,
      },
      tools: [CustomerSearchTool],
    }),
  ],
})
export class AppModule {}

Provider-Native Tools

Provider SDKs expose built-in tools such as web search, file search, code execution, and URL context. Archipel exports wrappers from provider subpaths so each tool is compatible with IIntelligenceTool without importing unused provider SDKs from the root entry.

typescript
import { Module } from '@nestjs/common';
import { IntelligenceModule, IntelligenceProviderNames } from '@breadstone/archipel-platform-intelligence';
import { loadOpenAILanguageModel } from '@breadstone/archipel-platform-intelligence/providers/openai';
import { createOpenAIWebSearchTool } from '@breadstone/archipel-platform-intelligence/providers/openai/tools';

@Module({
  imports: [
    IntelligenceModule.register({
      providerLoaders: {
        [IntelligenceProviderNames.OpenAI]: loadOpenAILanguageModel,
      },
      tools: [createOpenAIWebSearchTool({ searchContextSize: 'medium' })],
    }),
  ],
})
export class AppModule {}

Provider-native wrappers cover OpenAI web search, file search, code interpreter, image generation, shell, MCP, and tool search; Google Search, Enterprise Web Search, URL Context, Code Execution, File Search, Maps, and Vertex RAG Store; versioned Anthropic web search, web fetch, code execution, bash, text editor, computer, memory, tool search, and advisor tools; and Grok web search, X search, file search, code execution, MCP, image understanding, and X-video understanding.

The detailed AI text generation guide includes OpenAI recipes for spreadsheet analysis with Code Interpreter, image generation with generated files, deferred tool loading via Tool Search, and grammar-constrained custom tools. In the currently installed OpenAI SDK, customTool() constrains provider output but does not run a local execute callback; use a normal tool() when local execution is required.

Native AI SDK Passthrough

generateText() and streamText() accept native AI SDK Prompt objects directly. The options intentionally extend the native AI SDK call options, so provider-specific features can flow through even when Archipel has no dedicated wrapper for them.

The configured platform model is used by default. For exact AI SDK model factories, pass model per request. When every call provides a native model, set validateOnModuleInit: false to skip startup validation of platform provider configuration.

typescript
import { openai } from '@ai-sdk/openai';
import { Injectable, Module } from '@nestjs/common';
import { IntelligenceModule, IntelligenceTextGenerator } from '@breadstone/archipel-platform-intelligence';

@Module({
  imports: [
    IntelligenceModule.register({
      validateOnModuleInit: false,
    }),
  ],
})
export class RawAiSdkModule {}

@Injectable()
export class RawAiSdkRecipeService {
  public constructor(private readonly _textGenerator: IntelligenceTextGenerator) {}

  public async answerWithNativeOptions(): Promise<string> {
    const completion = await this._textGenerator.generateText(
      {
        system: 'Answer concisely and include assumptions.',
        prompt: 'Compare the operational risks of outdoor work tomorrow.',
      },
      {
        model: openai.responses('gpt-5'),
        headers: { 'x-use-case': 'outdoor-risk' },
        providerOptions: {
          openai: {
            reasoningEffort: 'medium',
          },
        },
        seed: 42,
      },
    );

    return completion.text;
  }
}

Outdoor Order Weather Risk Example

Use a class-based application tool for tenant data and a provider-native web search tool for current weather context. Set INTELLIGENCE_PROVIDER=openai and INTELLIGENCE_MODEL=gpt-5 in configuration when this flow should use GPT-5.

typescript
import { Injectable, Module } from '@nestjs/common';
import { stepCountIs, tool, type Tool } from 'ai';
import { z } from 'zod';
import {
  IntelligenceModule,
  IntelligenceProviderNames,
  IntelligenceTextGenerator,
  IntelligenceToolBase,
  type IIntelligenceTextCompletion,
} from '@breadstone/archipel-platform-intelligence';
import { OpenAIIntelligenceToolNames, loadOpenAILanguageModel } from '@breadstone/archipel-platform-intelligence/providers/openai';
import { createOpenAIWebSearchTool } from '@breadstone/archipel-platform-intelligence/providers/openai/tools';

interface IOutdoorOrderLookupInput {
  readonly date: string;
}

interface IOutdoorOrderLookupOutput {
  readonly date: string;
  readonly orders: ReadonlyArray<{
    readonly id: string;
    readonly location: string;
    readonly scheduledAt: string;
    readonly outdoorWork: boolean;
  }>;
}

@Injectable()
export class OutdoorOrdersTool extends IntelligenceToolBase<IOutdoorOrderLookupInput, IOutdoorOrderLookupOutput> {
  public override get name(): string {
    return 'get_outdoor_orders';
  }

  public override get tool(): Tool<IOutdoorOrderLookupInput, IOutdoorOrderLookupOutput> {
    return tool({
      description: 'Returns outdoor field orders for the current tenant and date.',
      inputSchema: z.object({
        date: z.string().describe('Date in YYYY-MM-DD format'),
      }),
      execute: async (input: IOutdoorOrderLookupInput) => ({
        date: input.date,
        orders: [
          {
            id: 'ord_4711',
            location: 'Berlin',
            scheduledAt: `${input.date}T08:00:00+02:00`,
            outdoorWork: true,
          },
        ],
      }),
    });
  }
}

@Injectable()
export class OutdoorOrderRiskAnalysisService {
  public constructor(private readonly _textGenerator: IntelligenceTextGenerator) {}

  public async analyseOutdoorOrders(date: string): Promise<{ readonly text: string; readonly sources: IIntelligenceTextCompletion['sources'] }> {
    const result = await this._textGenerator.generateText(
      {
        system: 'You assess weather-related risks for tenant outdoor field orders.',
        messages: [{ role: 'user', content: `Review outdoor field orders for ${date} and flag weather-related risks.` }],
      },
      {
        toolChoice: 'auto',
        activeTools: ['get_outdoor_orders', OpenAIIntelligenceToolNames.WebSearch],
        stopWhen: stepCountIs(3),
      },
    );

    return {
      text: result.text,
      sources: result.sources,
    };
  }
}

@Module({
  imports: [
    IntelligenceModule.register({
      providerLoaders: {
        [IntelligenceProviderNames.OpenAI]: loadOpenAILanguageModel,
      },
      tools: [
        OutdoorOrdersTool,
        createOpenAIWebSearchTool({
          externalWebAccess: true,
          searchContextSize: 'medium',
          filters: { allowedDomains: ['dwd.de'] },
        }),
      ],
    }),
  ],
  providers: [OutdoorOrderRiskAnalysisService],
})
export class OutdoorOrderRiskAnalysisModule {}

Text Generation

Inject IntelligenceTextGenerator and call generateText():

typescript
import { Injectable } from '@nestjs/common';
import type { Prompt } from 'ai';
import { IntelligenceTextGenerator } from '@breadstone/archipel-platform-intelligence';

@Injectable()
export class SummaryService {
  constructor(private readonly _textGenerator: IntelligenceTextGenerator) {}

  async summarize(content: string): Promise<string> {
    const prompt: Prompt = {
      system: 'You are a concise summarizer.',
      messages: [{ role: 'user', content }],
    };

    const result = await this._textGenerator.generateText(prompt, {
      temperature: 0.3,
      toolChoice: 'auto',
    });

    return result.text;
  }
}

Streaming

streamText() uses the same registered tools and returns the native AI SDK stream result.

typescript
const stream = await this._textGenerator.streamText(prompt, {
  activeTools: ['searchCustomers'],
  stopWhen: stepCountIs(3),
});

return stream.toUIMessageStreamResponse();

Environment Variables

VariableDescriptionRequired
OPENAI_API_KEYOpenAI API keyIf using OpenAI
ANTHROPIC_API_KEYAnthropic API keyIf using Anthropic
GOOGLE_API_KEYGoogle Generative AI API keyIf using Google
GROK_API_KEYGrok / xAI API keyIf using Grok

Timeout & Retry

All generateText() calls include built-in resilience:

SettingDefaultDescription
timeoutMs30000Abort the provider request after this many milliseconds
Max retries2Retryable errors are retried with exponential backoff
Backoff1s → 4sExponential with a 4-second cap

Override the timeout per call via the options parameter:

typescript
const result = await this._textGenerator.generateText(prompt, {
  timeoutMs: 15_000,
});

All errors are wrapped in IntelligenceProviderError with provider, model, and retryable metadata.


Error Handling

The library provides three domain error classes for different failure scenarios:

Error classCodeWhen thrown
IntelligenceProviderErrorINTELLIGENCE_PROVIDERProvider SDK failures during text generation
IntelligenceValidationErrorINTELLIGENCE_VALIDATIONInvalid generation parameters (temperature, topP, maxOutputTokens)
IntelligenceConfigurationErrorINTELLIGENCE_CONFIGURATIONUnsupported provider, missing API key, or missing provider loader
typescript
import {
  IntelligenceProviderError,
  IntelligenceValidationError,
  IntelligenceConfigurationError,
} from '@breadstone/archipel-platform-intelligence';

Lifecycle

IntelligenceTextGenerator implements OnModuleInit and validates the provider configuration plus registered provider loader eagerly at startup. Missing API keys, unsupported providers, or missing loaders throw IntelligenceConfigurationError before the first request is processed.


Tool Registry Limits

IntelligenceToolRegistry enforces a maximum of 128 registered tools. Attempts to register beyond this limit throw IntelligenceValidationError to prevent unbounded memory growth.


Health Check

The IntelligenceHealthIndicator verifies that provider configuration can be resolved. If no text generator is available, it reports disabled: true. Import it from the /health subpath:

typescript
import { IntelligenceModule, IntelligenceProviderNames } from '@breadstone/archipel-platform-intelligence';
import { IntelligenceHealthIndicator } from '@breadstone/archipel-platform-intelligence/health';
import { loadOpenAILanguageModel } from '@breadstone/archipel-platform-intelligence/providers/openai';
import { HealthModule } from '@breadstone/archipel-platform-health';

@Module({
  imports: [
    IntelligenceModule.register({
      providerLoaders: {
        [IntelligenceProviderNames.OpenAI]: loadOpenAILanguageModel,
      },
    }),
    HealthModule.withIndicators([IntelligenceHealthIndicator]),
  ],
})
export class AppModule {}
KeyCheckDependencies
intelligenceup when provider configuration resolves, else down@Optional() IntelligenceTextGenerator

API Reference

See the full API documentation for all exported types, interfaces, and classes.

Released under the MIT License.