@breadstone/archipel-platform-intelligence
v0.0.50
Published
Intelligence infrastructure for NestJS – AI SDK text generation, streaming, tools, and tree-shakable provider loaders for OpenAI, Anthropic, Google and Grok.
Maintainers
Readme
@breadstone/archipel-platform-intelligence
Intelligence infrastructure for NestJS — AI SDK text generation, streaming, class-based and provider-native tools, and tree-shakable provider loaders for OpenAI, Anthropic, Google, and Grok.
Features
- Multi-provider — OpenAI, Anthropic, Google (Gemini), and Grok via
@ai-sdk/* - Tool calling — Register class-based tools or provider-native AI SDK tools and expose them as native AI SDK
ToolSetvalues - AI SDK passthrough — Use native AI SDK prompts, per-request models, provider options, headers, telemetry, output settings, and tool options when a use case needs them
- Text generation — Unified
IntelligenceTextGenerator.generateText()with timeout, retry, and backoff - Streaming — Unified
IntelligenceTextGenerator.streamText()backed by AI SDKstreamText() - Configurable validation — Missing API keys or unsupported providers can be caught at module init, or skipped for request-level native model usage
- Tree-shakable — Provider loaders live in separate
providers/*sub-exports so unused SDKs are not imported by the root entry - Health checks —
IntelligenceHealthIndicatorfor readiness probes (separate/healthsubpath)
Environment Variables
| Variable | Required | Default | Description |
| -------------------------------- | -------- | ------- | ----------------------------- |
| INTELLIGENCE_MODEL | no | - | AI model identifier |
| INTELLIGENCE_TEMPERATURE | no | 0.7 | AI model sampling temperature |
| INTELLIGENCE_TOP_P | no | 1 | AI model top-p value |
| INTELLIGENCE_MAX_OUTPUT_TOKENS | no | 1024 | Max generated output tokens |
| OPENAI_API_KEY | no | - | OpenAI API key |
| ANTHROPIC_API_KEY | no | - | Anthropic API key |
| GOOGLE_API_KEY | no | - | Google Gemini API key |
| GEMINI_API_KEY | no | - | Google Gemini API key alias |
| GROK_API_KEY | no | - | Grok / xAI API key |
| XAI_API_KEY | no | - | Grok / xAI API key alias |
Quick 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 {}Registering Tools
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. Import their Archipel wrappers from provider subpaths so the provider SDK remains tree-shakable and the tools match IIntelligenceTool.
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 {}Available provider-native wrappers include 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 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. Options intentionally extend the native AI SDK call options so provider-specific metadata, headers, telemetry, output settings, tool repair hooks, step preparation, and similar advanced fields can flow through without Archipel needing to mirror every provider feature.
The configured platform model is used by default. For use cases that need an exact AI SDK model factory, pass model per request. When an application is fully request-driven and always passes native models, set validateOnModuleInit: false so startup does not require 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 OpenAI web search tool for weather context. Configure INTELLIGENCE_PROVIDER=openai and INTELLIGENCE_MODEL=gpt-5 when this use case should run on 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
const result = await this._textGenerator.generateText(prompt, {
temperature: 0.3,
toolChoice: 'auto',
});Streaming
const stream = await this._textGenerator.streamText(prompt, {
activeTools: ['searchCustomers'],
stopWhen: stepCountIs(3),
});
return stream.toUIMessageStreamResponse();Import Options
// Main import (module, text generator, tool base, tool registry)
import { IntelligenceModule, IntelligenceTextGenerator, IntelligenceToolBase, IntelligenceToolRegistry } from '@breadstone/archipel-platform-intelligence';
// Provider-specific loaders and config entries (tree-shakable subpath exports)
import { OPENAI_CONFIG_ENTRIES, loadOpenAILanguageModel } from '@breadstone/archipel-platform-intelligence/providers/openai';
import { ANTHROPIC_CONFIG_ENTRIES, loadAnthropicLanguageModel } from '@breadstone/archipel-platform-intelligence/providers/anthropic';
import { GOOGLE_CONFIG_ENTRIES, loadGoogleLanguageModel } from '@breadstone/archipel-platform-intelligence/providers/google';
import { GROK_CONFIG_ENTRIES, loadGrokLanguageModel } from '@breadstone/archipel-platform-intelligence/providers/grok';
// Provider-native tools (separate subpath exports)
import { createOpenAIWebSearchTool } from '@breadstone/archipel-platform-intelligence/providers/openai/tools';
import { createAnthropicWebSearch20260209Tool } from '@breadstone/archipel-platform-intelligence/providers/anthropic/tools';
import { createGoogleGoogleSearchTool } from '@breadstone/archipel-platform-intelligence/providers/google/tools';
import { createGrokWebSearchTool } from '@breadstone/archipel-platform-intelligence/providers/grok/tools';
// Health indicator (optional)
import { IntelligenceHealthIndicator } from '@breadstone/archipel-platform-intelligence/health';Error Handling
| 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 |
Resource Limits
| Limit | Value | Description | | ------------------------- | ---------- | ----------------------------------------------------- | | Text generation timeout | 30 seconds | LLM requests aborted after 30s (configurable) | | Max retries | 2 | Failed calls retried with exponential backoff (1s–4s) | | Tool registry cap | 128 | Max registered tools | | Default max output tokens | 1,024 | Maximum generated tokens per request |
Lifecycle
- Startup (
OnModuleInit):IntelligenceTextGeneratorvalidates provider configuration and registered provider loader eagerly. Missing API keys, unsupported providers, or missing loaders are caught before the first request.
Peer Dependencies
| Package | Required | Notes |
| --------------------------------------------- | -------- | ----------------------------- |
| @breadstone/archipel-platform-configuration | Yes | Typed config key support |
| @nestjs/common | Yes | NestJS core |
| ai | Yes | Vercel AI SDK core |
| @ai-sdk/openai | No | Required for OpenAI |
| @ai-sdk/anthropic | No | Required for Anthropic |
| @ai-sdk/google | No | Required for Google Gemini |
| @ai-sdk/xai | No | Required for Grok / xAI |
| @breadstone/archipel-platform-health | No | Required for health indicator |
| @nestjs/terminus | No | Required for health indicator |
Documentation
📖 Package Docs: .docs/packages/platform-intelligence/index.md
Development
# Build
yarn nx build platform-intelligence
# Test
yarn nx test platform-intelligence
# Lint
yarn nx lint platform-intelligence