The AI add-on
Instrumented models, token and cost capture, quota enforcement and usage rollups.
@octabits-io/models/octaflow wires model instrumentation, token/cost capture, quota, and daily usage
rollups into the engine’s lifecycle hooks — the engine stays AI-free. It was octaflow/ai until
0.36; the model layer is now its own package, @octabits-io/models.
import { z } from 'zod';
import { generateText } from 'ai';
import { createWorkflowEngine, createStepHandlerRegistry, createInMemoryWorkflowStore } from 'octaflow';
import { defineAiStep, buildAiWorkflow, createAiWorkflowHooks } from '@octabits-io/models/octaflow';
const summarize = defineAiStep({
type: 'summarize',
workflowInputSchema: z.object({ text: z.string() }),
outputSchema: z.object({ summary: z.string() }),
retry: { maxAttempts: 3 }, // provider 429s
handler: async (ctx) => {
const { text } = await generateText({ model: ctx.context.model, prompt: `Summarize: ${ctx.workflowInput.text}` });
return { summary: text };
},
});
const hooks = createAiWorkflowHooks({
modelResolver: {
resolveModel: () => myModel, // your LanguageModelV4
// resolveHost: (args) => container.scope(args), // optional → ctx.context.host
// resolveKeySource: () => 'platform', // optional → stamped on workflow metadata
},
usageRecorder: { recordStepUsage: async () => {}, incrementWorkflowUsage: async () => {} },
// quotaPolicy: { checkQuota: async () => ({ ok: true, value: undefined }) },
// costEstimator: createCostEstimator({ … }), // defaults to DEFAULT_MODEL_PRICING
});
const store = createInMemoryWorkflowStore();
const registry = createStepHandlerRegistry();
const engine = createWorkflowEngine({ store, dispatcher, registry, partitionKey: 'tenant-1', hooks });
ctx.context.model is an instrumented model — token usage is captured automatically and the
onAfterStep hook turns it into cost via a pluggable pricing table (createCostEstimator).
ctx.context.host is whatever modelResolver.resolveHost returns (a DI scope, domain
services), or undefined if you don’t supply one.
→ examples/01-ai-workflow.ts in @octabits-io/models
Quota enforcement & usage aggregation
Two store-agnostic engines complete the add-on. They own the window math, the enforcement
order, and the rollup shapes; the raw counts and aggregate reads come through narrow store seams
(AiQuotaStore / AiUsageStore) that you implement with your own SQL — flow never touches a
database (and the ai layer never depends on pg). Scoping is generic (partitionKey) and
keySource is a free-form string, so both engines stay tenancy-agnostic.
import { createAiQuotaService, createAiUsageAggregationService, DEFAULT_AI_QUOTA } from '@octabits-io/models/octaflow';
// Quota: limits come from an injected getQuota(partitionKey) callback — return
// null to exempt a scope entirely (e.g. bring-your-own-key), or null on any
// single window to leave it unlimited.
const quota = createAiQuotaService({
store, // your AiQuotaStore (count reads)
getQuota: (partitionKey) => DEFAULT_AI_QUOTA,
});
const gate = await quota.checkQuota('tenant-1'); // Result<void, AiQuotaExceededError>
// wire it into the hooks: quotaPolicy: { checkQuota: () => quota.checkQuota('tenant-1') }
// Usage aggregation: roll completed workflows (and embedding batches) into a
// daily table, then read summaries back.
const usage = createAiUsageAggregationService({ store }); // your AiUsageStore (UPSERT + aggregate reads)
await usage.recordWorkflowCompletion({ partitionKey: 'tenant-1', date, workflowType: 'gen', keySource: 'platform', usage: totals, estimatedCostMicros });
const byDay = await usage.getUsageSummary({ partitionKey: 'tenant-1', startDate, endDate });
checkQuota enforces three windows in order — concurrent → per-day → per-month (UTC) — and the
day/month counts include currently-running (not-yet-aggregated) workflows. AiUsageStore extends
AiQuotaStore, so one implementation backs both engines.
The model layer
Everything above assumes you already have a LanguageModelV4. The ai module also ships the layer that produces one in a bring-your-own-key deployment, moved from a production SaaS where every AI call went through it:
createRefusalAwareModel(model)— a Claude 5 model can decline a request rather than fail it: HTTP 200, empty content,stop_reason: "refusal". The AI SDK maps that to the unified finish reasoncontent-filter, so nothing throws and a caller that does not check the finish reason sees an empty string or an unparseable object several frames from the cause. The wrapper turns it into a thrownAiRefusalErrorondoGenerate(with the provider’s category and explanation when sent), anddefineAiSteptreats it as terminal — retrying a refusal yields the same refusal. Streaming is deliberately untouched: a chat presents a decline as a turn.isAiRefusalErrorfollowscausechains, becausegenerateObjectre-wraps.withJsonRepair(model, options)— lenient JSON at the model boundary. A model asked for JSON (generateObject, orgenerateTextwithOutput.object) answers with JSON most of the time; a local or smaller model wraps it in a Markdown fence, puts a sentence before it, answers one object per image instead of one object, or adds a remark after the closing brace, andJSON.parsefails although the answer was usable. The wrapper reads everydoGeneratethat asked for JSON throughparseModelJsonand rewrites the text as canonical JSON before the SDK parses it, each step only when the previous failed: the fence unwrapped (fence), the outermost{ … }or[ … ]cut out of the prose (prose), an array of objects merged into one whenmergeis set and the schema is not itself an array (array_merge: array fields concatenated in order, the first non-empty scalar kept,nullnever overwriting a value). When nothing helps,retryWithoutJsonModemakes one more request with the provider’s JSON mode off, andconvertWith(truefor the wrapped model, or a cheaperLanguageModelV4) makes one call that is handed the schema and the prose — at most one each, their usage summed into the result so the instrumented model outside counts them. A repaired answer carriesproviderMetadata.octaflow.repairedand is reported toonRepairwith the step and the extra requests, for the step’s span underMODEL_JSON_REPAIRED_ATTRIBUTE(gen_ai.response.repaired, a key the telemetry package’s redaction leaves alone) or a meter. When all fails,ModelJsonErroris thrown (key:model_json_empty,model_json_invalid,model_json_not_object,model_json_schema) with the first 500 characters of the last answer inexcerptand never the answer in its message;isModelJsonErrorfollowscausechains. Two unrelated objects in one answer, an array of scalars and a fence around invalid JSON are refused.doGenerateonly, like the refusal wrapper.parseModelJson(text, { schema?, merge?, excerptLength? })is the same recovery as a function returning aResult, andmodelJsonRepairText({ merge? })is it as the SDK’srepairTexthook for a host that callsgenerateObjectdirectly.explainProviderError(error, { provider?, modelId?, detailLength? })— what a vendor’s refusal means, in plain language. Any thrown value (the SDK’sAPICallError, afetchfailure, a vendor client’s error, a string) becomes{ key, message, hint, fatal, status?, detail }: one ofprovider_auth,provider_billing,provider_model_not_found,provider_rate_limited,provider_unavailable,provider_unreachable,budget_exceededorprovider_error; an English sentence that names the vendor and the status; one actionable hint (the key with the vendor’s console URL, the credit, the model id against the vendor’s list —ollama pull <model>for Ollama —, the base URL and egress for an unreachable host); and the raw text with every key-shaped token masked and the rest cut to 300 characters, safe to log or show. The vendor phrases are data,PROVIDER_ERROR_PHRASES, one list per preset (anthropic,openai,mistral,gemini,openrouter,ollama,openai-compatible) tried before the common one; the status decides when no phrase does.isFatalProviderErroris the subset after which further calls to the same vendor in the same run are pointless: the key, the credit, the model id, an unreachable host, a spent budget — a rate limit and an outage are not.PROVIDER_ERROR_STATUSis the status per key for@octabits-io/server’serrorOverrides(502 for the vendor’s refusal, 503 for an outage, 429 for a rate limit or a spent budget), since its convention would answer 404 forprovider_model_not_foundas if the API consumer’s resource were missing.ProviderErroris the explanation as a thrown error with the original ascause;isProviderErrorfollows chains.withCircuitBreaker(model, { onFatal?, provider? })— one dead vendor, one notice. The first fatal error trips the breaker,onFatalis told once with the explanation, and every further call through it fails at once with the sameProviderErrorand no request; a rate limit or an outage does not trip it and is rethrown as it was, for the step’s retry policy.createCircuitBreaker(options)makes one breaker whosewrap(model)is shared by every model of one run, withtripped()andreset()— per run or per workflow instance, never process-wide: a host makes it inresolveModelper workflow id, so one customer’s revoked key never trips another’s. Order with the disclosure gate: the gate outermost, the breaker inside it,guardLanguageModel(withCircuitBreaker(createRefusalAwareModel(createInstrumentedModel(model, usage))), options), so a denial never reaches the breaker and is never counted as a vendor fault.doGenerateanddoStreamboth; for a stream the breaker sees the error the call itself throws, not one that surfaces while the stream is read.testProvider(providerOrModel, { model?, timeoutMs?, provider? })— one real request that proves a key, a model id and a network path: “answer OK”, 16 output tokens, a 30 s deadline, straight todoGeneratewith no SDK retries.Result<{ modelId, elapsedMs, reply, usage? }, ProviderProbeFailure>, the failure being the explanation plus the model and the time it took — what a settings page shows after a key is saved, and what a host meters under its ownprovider_testlabel from the usage returned.testOllamaModel({ baseUrl, model, fetch? })is the Ollama variant: a read of/api/tags(the/v1of the compatible base URL stripped) that says whether the model is installed,provider_model_not_foundwith theollama pullhint when it is not, and no model call.- Capability switches —
supportsAdaptiveThinking,thinkingSettingsFor(providerId, modelId, { temperature, budgetTokens }),supportsToolSearch. Claude 4.6+ rejects the legacybudget_tokensshape and sampling params with a 400; older models require them. A BYOK deployment lets a customer name any model id, so the request shape has to branch on the resolved id, once, here. - The provider registry —
AI_PROVIDERS,EMBEDDING_PROVIDERS,embeddingDimensionsFor: dependency-free metadata a browser picker can import. Each vendor carries its residency (euorthird-country, legal name, country), the fact a subprocessor annex and a residency badge both need. It is the root of@octabits-io/models, which imports noaiSDK, so a browser bundle imports it as is; a lint keeps it that way. @octabits-io/models/ai-sdk—createLanguageModelProvider({ provider, apiKey, defaultModel?, baseUrl? })andcreateEmbeddingModelProvider(...): a key and a provider id become refusal-aware models, with an optional region-pinned endpoint. The vendor SDKs (@ai-sdk/anthropic,@ai-sdk/mistral,@ai-sdk/openai) are optional peers loaded on first use, so only the vendors you point at need to be installed.- Self-hosted and other OpenAI-compatible endpoints —
createOpenAiCompatibleModelProvider({ baseUrl, residency, defaultModel, apiKey? })andcreateOpenAiCompatibleEmbeddingProvider({ baseUrl, residency, model, dimensions, apiKey? }), in the same subpath, over the optional peer@ai-sdk/openai-compatible: vLLM, Ollama, llama.cpp’s server, TGI, or a hosted vendor with that API. Language models go through Chat Completions, which is what those servers speak, not the Responses API that@ai-sdk/openaidefaults to. Nothing is assumed. The base URL has no default. The residency is declared by the deployment and checked byresolveEndpointResidency:{ region: 'self-hosted' }adds no subprocessor, and a hosted vendor needs its legal name and country. An embedding model’sdimensionsmust be stated, because a guessed width fails at the first insert into avector(N)column. A configuration that cannot work throwsAiProviderConfigError, with akey, before any SDK loads. These factories sit besideAI_PROVIDERSrather than in it, so a picker over the fixed-residency vendors is unchanged. Give each self-hosted model id aZERO_MODEL_PRICINGrow in your cost table, or quota prices it at the dearest vendor row. - A gateway with several models —
createOpenAiCompatibleGatewayProvider({ baseUrl, residency, models, apiKey? }), in the same subpath: LiteLLM or any router that serves several model names behind one OpenAI-compatible endpoint and sends each somewhere else. The residency belongs to the alias, somodelsdeclares one per alias ({ 'approval-confidential': { residency: { region: 'self-hosted' } }, … }); the top-levelresidencyis where the gateway itself runs and decides whether plain http is acceptable.languageModel(alias, { metadata? })refuses an alias the declaration does not name withai_model_undeclared, andmetadatagoes into the request body, where LiteLLM keeps it in its spend log — a workflow id there matches a gateway call to your own record. Ids only: metadata leaves as written. The declaration states what the gateway is configured to do; a fallback the gateway adds on its own breaks it silently, so review the two together.
import { createLanguageModelProvider } from '@octabits-io/models/ai-sdk';
import { thinkingSettingsFor } from '@octabits-io/models';
const models = await createLanguageModelProvider({ provider: 'mistral', apiKey: key.value });
const result = await generateText({
model: models.languageModel(),
...thinkingSettingsFor(models.providerId, models.languageModel().modelId, { temperature: 0.3, budgetTokens: 4000 }),
prompt,
});
// A model server in your own cluster: no key, no subprocessor, a declared width.
const local = await createOpenAiCompatibleModelProvider({
baseUrl: 'http://vllm.ai.svc:8000/v1',
residency: { region: 'self-hosted' },
defaultModel: 'qwen3-32b',
});
const embeddings = await createOpenAiCompatibleEmbeddingProvider({
baseUrl: 'http://tei.ai.svc/v1',
residency: { region: 'self-hosted' },
model: 'bge-m3',
dimensions: 1024, // must match vector(1024)
});
From octaflow@0.44.0 in the platform repository, MIT-licensed.npm