@plasius/ai
v1.2.1
Published
Plasius AI functions providing chatbot, text-to-speech, speech-to-text, and AI-generated images and videos
Maintainers
Readme
@plasius/ai
AI capability contracts, completion schemas, and agentic foundation contracts for Plasius applications.
Scope
This package currently provides:
- capability contracts (
AICapability,AIPlatform) - agentic foundation contracts for request envelopes, task kinds, rollout metadata, provider/model catalogs, and metering
- completion model interfaces (
ChatCompletion,ImageCompletion,ModelCompletion, etc.) - schema definitions for completion entities
- adapter contracts/factories for multi-provider routing with developer-supplied API keys
Provider wiring and runtime adapters are documented in docs/providers.md.
Install
npm install @plasius/aiModule formats
This package publishes dual ESM and CJS artifacts.
When CJS output is emitted under dist-cjs/*.js with type: module, dist-cjs/package.json is generated with { "type": "commonjs" } to ensure Node require(...) compatibility.
Usage
import {
AICapability,
type AIPlatform,
completionSchema,
chatCompletionSchema,
} from "@plasius/ai";
const capabilities = [AICapability.Chat, AICapability.Image];
void capabilities;
void completionSchema;
void chatCompletionSchema;
// Host apps provide the concrete runtime implementation.
const platform: AIPlatform = {
chatWithAI: async () => ({
id: crypto.randomUUID(),
partitionKey: "user-1",
type: "chat",
model: "gpt-4.1-mini",
durationMs: 42,
createdAt: new Date().toISOString(),
message: "Hello world",
outputUser: "assistant",
}),
synthesizeSpeech: async () => {
throw new Error("Not implemented");
},
transcribeSpeech: async () => {
throw new Error("Not implemented");
},
generateImage: async () => {
throw new Error("Not implemented");
},
produceVideo: async () => {
throw new Error("Not implemented");
},
generateModel: async () => {
throw new Error("Not implemented");
},
checkBalance: async () => ({
id: crypto.randomUUID(),
partitionKey: "user-1",
type: "balance",
model: "",
durationMs: 0,
createdAt: new Date().toISOString(),
balance: 0,
}),
currentBalance: 0,
};
void platform;API Surface
AICapability: enum describing logical capability routing.AIPlatform: interface your runtime adapter must implement.- Agentic foundation contracts and helpers:
AI_FEATURE_FLAGSAI_AGENTIC_FOUNDATION_ROLLOUTcreateAITaskKindcreateAIRequestEnveloperesolveAIRolloutDecisionAIProviderDescriptorAIModelCatalogEntryAIUsageMetricsAICostEstimateAIConfidenceScore
- Generic multi-capability adapter contracts and helpers:
AICapabilityAdapterAdapterPlatformPropsHttpClientPolicycreateAdapterPlatformcreateOpenAIAdaptercreateGeminiAdaptercreateGrokAdaptercreateMetaAIAdaptercreatePixelverseAdapter
- Generic video-provider adapter contracts and helpers:
VideoProviderAdapterVideoGenerationRequestcreateHttpVideoProviderAdapterVideoProviderPlatformcreateVideoProviderPlatform- Contract key:
platform.repo-hardening-sweep.enabled
- Contract key:
- Pixelverse component translation helpers:
pixelverseEnGbTranslationspixelverseTranslationKeystranslatePixelverseText
Completion+ typed completion variants:ChatCompletionTextCompletionImageCompletionSpeechCompletionVideoCompletionModelCompletionBalanceCompletion
- Schemas:
completionSchemachatCompletionSchematextCompletionSchemaimageCompletionSchemaspeechCompletionSchemavideoCompletionSchemamodelCompletionSchemabalanceCompletionSchema
Completion schemas validate persisted records, including the internal partitionKey used to associate requests with a user or system actor. When returning completion payloads to clients, prefer completionSchema.serialize(...) so internal fields stay out of the default response shape.
Documentation
- Architecture:
docs/architecture.md - API reference:
docs/api-reference.md - Provider guidance:
docs/providers.md
Known Limitations
- The supported package surface is the root module export from
src/index.ts; internalsrc/**files remain implementation details unless they are explicitly re-exported. - Provider-specific runtime adapters are still under stabilization and should be wrapped by host applications.
- The package focuses on contracts/schemas first; runtime behavior is expected to be composed by consumers or downstream
@plasius/ai-*packages.
Multi-Capability Adapter Composition
import {
AICapability,
createAdapterPlatform,
createGeminiAdapter,
createGrokAdapter,
createMetaAIAdapter,
createOpenAIAdapter,
createPixelverseAdapter,
} from "@plasius/ai";
const openAIAdapter = createOpenAIAdapter({
id: "openai",
httpPolicy: {
maxAttempts: 3,
timeoutMs: 30000,
baseDelayMs: 250,
maxDelayMs: 4000,
jitterRatio: 0.2,
},
defaultModels: {
chat: "gpt-4.1-mini",
speech: "gpt-4o-mini-tts",
transcription: "gpt-4o-mini-transcribe",
image: "gpt-image-1",
model: "gpt-4.1-mini",
},
});
const geminiAdapter = createGeminiAdapter({
id: "gemini",
httpPolicy: {
maxAttempts: 3,
timeoutMs: 30000,
},
defaultModels: {
chat: "gemini-2.0-flash",
image: "imagen-3.0-generate-002",
model: "gemini-2.0-flash",
},
});
const grokAdapter = createGrokAdapter();
const metaAdapter = createMetaAIAdapter();
const pixelverseAdapter = createPixelverseAdapter();
const platform = await createAdapterPlatform("user-1", {
adapters: [openAIAdapter, geminiAdapter, grokAdapter, metaAdapter, pixelverseAdapter],
apiKeys: {
openai: process.env.OPENAI_API_KEY ?? "",
gemini: process.env.GEMINI_API_KEY ?? "",
grok: process.env.XAI_API_KEY ?? "",
"meta-ai": process.env.META_AI_API_KEY ?? "",
pixelverse: process.env.PIXELVERSE_API_KEY ?? "",
},
defaultAdapterByCapability: {
[AICapability.Chat]: "grok",
[AICapability.Speech]: "openai",
[AICapability.Image]: "gemini",
[AICapability.Model]: "gemini",
[AICapability.Video]: "pixelverse",
[AICapability.Balance]: "pixelverse",
},
});
void platform;Client-safe completion payloads
import { completionSchema } from "@plasius/ai";
const persistedCompletion = {
id: "completion-1",
type: "chat",
model: "gpt-4.1-mini",
durationMs: 42,
createdAt: new Date().toISOString(),
partitionKey: "user-1",
};
const publicPayload = completionSchema.serialize(persistedCompletion);
// partitionKey is omitted by default.
void publicPayload;Agentic foundation contracts
import {
AI_FEATURE_FLAGS,
createAIRequestEnvelope,
createAITaskKind,
resolveAIRolloutDecision,
} from "@plasius/ai";
const rollout = resolveAIRolloutDecision(
{
featureFlag: AI_FEATURE_FLAGS.agenticFoundation,
evaluator: "remote-flag-service",
defaultEnabled: false,
fallbackMode: "fail-closed",
},
{
[AI_FEATURE_FLAGS.agenticFoundation]: true,
}
);
const envelope = createAIRequestEnvelope({
requestId: "req-1",
taskKind: createAITaskKind({
domain: "routing",
action: "select",
}),
actor: {
actorId: "user-1",
actorType: "user",
},
input: {
prompt: "Choose the cheapest safe model.",
},
});
void rollout;
void envelope;Generic Video Adapter Composition
import {
createHttpVideoProviderAdapter,
createVideoProviderPlatform,
} from "@plasius/ai";
const videoAdapter = createHttpVideoProviderAdapter({
uploadImagePath: "/provider/image/upload",
generateVideoPath: "/provider/video/generate",
getVideoResultPath: (videoId) => `/provider/video/result/${videoId}`,
getBalancePath: "/provider/account/balance",
});
const platform = await createVideoProviderPlatform("user-1", {
apiKey: process.env.PROVIDER_API_KEY ?? "",
adapter: videoAdapter,
});
void platform;Pixelverse UI Translations
Pixelverse editor components keep their display text in the package-owned en-GB
dictionary and resolve defaults through @plasius/translations. Host
applications can pass a translate function to VideoGenerationEditor or
Balance when they need a different locale while preserving the package
fallbacks.
import type { PixelverseTranslate } from "@plasius/ai";
const translate: PixelverseTranslate = (key, args) => i18n.t(key, args);
<VideoGenerationEditor
apiKey={apiKey}
adapter={videoAdapter}
translate={translate}
/>;Development
npm install
npm run build
npm test
npm run test:coverage
npm run demo:runDemo Sanity Check
npm run demo:runPublishing
This package is published via GitHub CD only.
- Bind the npm trusted publisher for
@plasius/aito repositoryPlasius-LTD/ai, workflowcd.yml, and environmentproduction. - Run
.github/workflows/cd.ymlvia Actions -> CD (Publish to npm) -> Run workflow. - Select the version bump (
patch,minor,major, ornone) and optional pre-release id.
Publication uses Node 24.18.0 LTS and npm OIDC trusted publishing. The publish
job does not configure NODE_AUTH_TOKEN or a registry auth line; npm exchanges
the GitHub OIDC identity for a short-lived publish credential. Do not publish
from a local machine or configure a long-lived npm token.
Before publication, CD proves that the prepared commit is still the exact
origin/main head and waits for a successful push-triggered ci.yml run for
that SHA. The publish job also enforces Node 24 with npm 11.5.1 or newer and
refuses to continue unless GitHub Actions exposes the OIDC request context
required by npm trusted publishing.
Public Artifact Integrity
CI rejects the administrative contributor-registry path from both the exact Git
index and the npm dry-run inventory without reading its contents. The integrity
gate runs on same-repository pull requests and trusted main pushes; fork pull
requests never execute repository code on self-hosted runners. CI runs on the
approved self-hosted runner group; package publication runs only through the
GitHub-hosted production CD job.
Build Outputs
- ESM:
dist/ - CJS:
dist-cjs/ - Types:
dist/*.d.ts
License
MIT
