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-intelligenceQuick Start
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:
| Provider | Subpath |
|---|---|
| OpenAI | @breadstone/archipel-platform-intelligence/providers/openai |
| Anthropic | @breadstone/archipel-platform-intelligence/providers/anthropic |
@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.
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.
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.
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.
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():
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.
const stream = await this._textGenerator.streamText(prompt, {
activeTools: ['searchCustomers'],
stopWhen: stepCountIs(3),
});
return stream.toUIMessageStreamResponse();Environment Variables
| Variable | Description | Required |
|---|---|---|
OPENAI_API_KEY | OpenAI API key | If using OpenAI |
ANTHROPIC_API_KEY | Anthropic API key | If using Anthropic |
GOOGLE_API_KEY | Google Generative AI API key | If using Google |
GROK_API_KEY | Grok / xAI API key | If using Grok |
Timeout & Retry
All generateText() calls include built-in resilience:
| Setting | Default | Description |
|---|---|---|
timeoutMs | 30000 | Abort the provider request after this many milliseconds |
| Max retries | 2 | Retryable errors are retried with exponential backoff |
| Backoff | 1s → 4s | Exponential with a 4-second cap |
Override the timeout per call via the options parameter:
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 class | Code | When thrown |
|---|---|---|
IntelligenceProviderError | INTELLIGENCE_PROVIDER | Provider SDK failures during text generation |
IntelligenceValidationError | INTELLIGENCE_VALIDATION | Invalid generation parameters (temperature, topP, maxOutputTokens) |
IntelligenceConfigurationError | INTELLIGENCE_CONFIGURATION | Unsupported provider, missing API key, or missing provider loader |
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:
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 {}| Key | Check | Dependencies |
|---|---|---|
intelligence | up when provider configuration resolves, else down | @Optional() IntelligenceTextGenerator |
API Reference
See the full API documentation for all exported types, interfaces, and classes.