@nebutra/agents 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +40 -0
- package/.turbo/turbo-test.log +18 -0
- package/.turbo/turbo-typecheck.log +4 -0
- package/CHANGELOG.md +26 -0
- package/dist/agent-CahnMASx.d.ts +32 -0
- package/dist/chunk-5JZJ5KMC.js +37 -0
- package/dist/chunk-5LX742GP.js +224 -0
- package/dist/chunk-B7XWL35G.js +60 -0
- package/dist/chunk-NPQECBXL.js +82 -0
- package/dist/chunk-NVPE5EDI.js +42 -0
- package/dist/chunk-RDOFKRI6.js +166 -0
- package/dist/chunk-RLWM437Q.js +61 -0
- package/dist/chunk-UVL2UVVM.js +56 -0
- package/dist/index.d.ts +476 -0
- package/dist/index.js +533 -0
- package/dist/providers/langchain.d.ts +18 -0
- package/dist/providers/langchain.js +23 -0
- package/dist/providers/vercel-ai.d.ts +16 -0
- package/dist/providers/vercel-ai.js +83 -0
- package/dist/sdk/config.d.ts +48 -0
- package/dist/sdk/config.js +10 -0
- package/dist/sdk/index.d.ts +94 -0
- package/dist/sdk/index.js +33 -0
- package/dist/sdk/models.d.ts +40 -0
- package/dist/sdk/models.js +8 -0
- package/dist/sdk/provider.d.ts +21 -0
- package/dist/sdk/provider.js +10 -0
- package/dist/tools.d.ts +20 -0
- package/dist/tools.js +12 -0
- package/dist/types-NtgB3pch.d.ts +92 -0
- package/package.json +4 -3
- package/src/__tests__/generation.test.ts +111 -0
- package/src/generation/index.ts +157 -0
- package/src/generation/mock-provider.ts +123 -0
- package/src/generation/types.ts +87 -0
- package/src/index.ts +18 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
import { B as BaseAgent } from './agent-CahnMASx.js';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { EmbeddingModel, LanguageModel } from 'ai';
|
|
4
|
+
export { GenerateTextResult, ModelMessage, StreamTextResult } from 'ai';
|
|
5
|
+
import { A as AgentMessage, O as OrchestratorConfig, a as AgentContext, b as AgentResponse, P as PipelineStep, R as RouterConfig, c as AgentConfig } from './types-NtgB3pch.js';
|
|
6
|
+
export { d as AgentTool, e as AgentUsageEvent, M as MemoryConfig, T as TokenUsage, f as ToolCallResult } from './types-NtgB3pch.js';
|
|
7
|
+
export { EmbedOptions, GenerateOptions, configure, embed, embedMany, generateText, getConfig, streamText } from './sdk/index.js';
|
|
8
|
+
export { BUILT_IN_TOOLS, databaseQueryTool, knowledgeBaseTool, webSearchTool } from './tools.js';
|
|
9
|
+
export { ModelPreset, models, resolveModel } from './sdk/models.js';
|
|
10
|
+
export { NebutraAIConfig, NebutraAIConfigSchema, ProviderType, ResolvedNebutraAIConfig } from './sdk/config.js';
|
|
11
|
+
export { createEmbeddingModel, createModel } from './sdk/provider.js';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* User context primitives — Memory-as-context layer for AI conversations.
|
|
15
|
+
*
|
|
16
|
+
* Inspired by Perplexity / ChatGPT "custom instructions" pattern but
|
|
17
|
+
* implemented as pure helpers: this package does **not** read the database
|
|
18
|
+
* (keeps `@nebutra/agents` data-layer-agnostic). The caller fetches the
|
|
19
|
+
* profile and passes the structured object in.
|
|
20
|
+
*
|
|
21
|
+
* Usage pattern from a Next.js route:
|
|
22
|
+
*
|
|
23
|
+
* ```ts
|
|
24
|
+
* const profile = await db.userProfile.findUnique({ where: { userId } });
|
|
25
|
+
* const system = buildPersonalizedSystemPrompt(BASE_PROMPT, profile);
|
|
26
|
+
* const result = await streamText(messages, { system, model: "fast" });
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
interface UserContext {
|
|
30
|
+
/** What the assistant should call the user. */
|
|
31
|
+
nickname?: string | null;
|
|
32
|
+
/** Job title / role — gives the model audience context. */
|
|
33
|
+
occupation?: string | null;
|
|
34
|
+
/** Free-form bio (interests, location, work focus, etc.). */
|
|
35
|
+
bio?: string | null;
|
|
36
|
+
/** Verbatim instructions that override default tone/format. */
|
|
37
|
+
customInstructions?: string | null;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Renders a `UserContext` as a compact block to inject into a system prompt.
|
|
41
|
+
*
|
|
42
|
+
* Output is null when no field is set, so callers can skip the entire
|
|
43
|
+
* "About the user" preamble and avoid wasted tokens.
|
|
44
|
+
*/
|
|
45
|
+
declare function renderUserContextBlock(context: UserContext | null | undefined): string | null;
|
|
46
|
+
/**
|
|
47
|
+
* Builds the final system prompt by prepending a personalization block to the
|
|
48
|
+
* base prompt. Pure — no side effects, safe to call per-request.
|
|
49
|
+
*
|
|
50
|
+
* @param basePrompt - the assistant's role-defining base prompt
|
|
51
|
+
* @param context - structured user context (null/undefined disables personalization)
|
|
52
|
+
*/
|
|
53
|
+
declare function buildPersonalizedSystemPrompt(basePrompt: string, context: UserContext | null | undefined): string;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Environment validation for `@nebutra/agents`.
|
|
57
|
+
*
|
|
58
|
+
* All variables are OPTIONAL — the package must work with zero new env config.
|
|
59
|
+
* Provider keys (OPENROUTER_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)
|
|
60
|
+
* are validated lazily by the provider resolver, not here.
|
|
61
|
+
*/
|
|
62
|
+
|
|
63
|
+
/** Comma-separated provider chain. Order = priority. */
|
|
64
|
+
declare const FallbackProviderName: z.ZodEnum<{
|
|
65
|
+
openrouter: "openrouter";
|
|
66
|
+
anthropic: "anthropic";
|
|
67
|
+
openai: "openai";
|
|
68
|
+
}>;
|
|
69
|
+
type FallbackProviderName = z.infer<typeof FallbackProviderName>;
|
|
70
|
+
declare const AgentsEnvSchema: z.ZodObject<{
|
|
71
|
+
ANTHROPIC_API_KEY: z.ZodOptional<z.ZodString>;
|
|
72
|
+
LANGFUSE_PUBLIC_KEY: z.ZodOptional<z.ZodString>;
|
|
73
|
+
LANGFUSE_SECRET_KEY: z.ZodOptional<z.ZodString>;
|
|
74
|
+
LANGFUSE_HOST: z.ZodDefault<z.ZodString>;
|
|
75
|
+
LLM_FALLBACK_CHAIN: z.ZodDefault<z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string[], string>>, z.ZodArray<z.ZodEnum<{
|
|
76
|
+
openrouter: "openrouter";
|
|
77
|
+
anthropic: "anthropic";
|
|
78
|
+
openai: "openai";
|
|
79
|
+
}>>>>;
|
|
80
|
+
LLM_EMBEDDING_FALLBACK_CHAIN: z.ZodDefault<z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string[], string>>, z.ZodArray<z.ZodEnum<{
|
|
81
|
+
openrouter: "openrouter";
|
|
82
|
+
anthropic: "anthropic";
|
|
83
|
+
openai: "openai";
|
|
84
|
+
}>>>>;
|
|
85
|
+
}, z.core.$strip>;
|
|
86
|
+
type AgentsEnv = z.infer<typeof AgentsEnvSchema>;
|
|
87
|
+
/** Returns the validated env (cached). Safe to call from any runtime. */
|
|
88
|
+
declare function getAgentsEnv(): AgentsEnv;
|
|
89
|
+
/** True iff Langfuse credentials are present. */
|
|
90
|
+
declare function isLangfuseConfigured(): boolean;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Multi-provider fallback chain + prompt-caching helpers.
|
|
94
|
+
*
|
|
95
|
+
* Cost & reliability primitives for production LLM workloads:
|
|
96
|
+
*
|
|
97
|
+
* 1. `createFallbackModel()` — picks a primary model and returns a callable
|
|
98
|
+
* that retries on retryable errors (429 / 5xx / network) by swapping to
|
|
99
|
+
* the next provider in `LLM_FALLBACK_CHAIN`.
|
|
100
|
+
*
|
|
101
|
+
* 2. `withCacheControl()` — annotates the system message with Anthropic
|
|
102
|
+
* `cacheControl: { type: 'ephemeral' }` for a 90% discount on cached
|
|
103
|
+
* prefix tokens. OpenAI auto-caches when the prefix is stable and ≥1024
|
|
104
|
+
* tokens — see comment in `generateWithFallback()`.
|
|
105
|
+
*
|
|
106
|
+
* Reference: https://sdk.vercel.ai/docs/ai-sdk-providers/anthropic#cache-control
|
|
107
|
+
*/
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Filter a chain to providers whose API key is present in env.
|
|
111
|
+
* Returns the original chain unchanged if NO providers have keys (so callers
|
|
112
|
+
* still see a meaningful error rather than an empty-chain throw).
|
|
113
|
+
*/
|
|
114
|
+
declare function filterAvailableProviders(chain: readonly FallbackProviderName[]): readonly FallbackProviderName[];
|
|
115
|
+
declare function isRetryableError(error: unknown): boolean;
|
|
116
|
+
interface FallbackResult<T> {
|
|
117
|
+
result: T;
|
|
118
|
+
provider: FallbackProviderName;
|
|
119
|
+
attempts: number;
|
|
120
|
+
}
|
|
121
|
+
interface CreateFallbackModelOptions {
|
|
122
|
+
/** Override the default chain from env. */
|
|
123
|
+
chain?: readonly FallbackProviderName[];
|
|
124
|
+
/** Model preset / id passed to each provider in the chain. */
|
|
125
|
+
model?: string;
|
|
126
|
+
/**
|
|
127
|
+
* If true (default), filter the chain to providers whose API key is present
|
|
128
|
+
* in env. Set false to keep the original chain (caller wants to surface
|
|
129
|
+
* "missing key" errors as fallback steps — useful for tests).
|
|
130
|
+
*/
|
|
131
|
+
filterAvailable?: boolean;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Run an AI SDK call against the configured fallback chain.
|
|
135
|
+
*
|
|
136
|
+
* The caller provides an `invoke(model)` function — usually a closure over
|
|
137
|
+
* `streamText` or `generateText` — and `runWithFallback` walks the chain,
|
|
138
|
+
* trying each provider in order until one succeeds or the chain is exhausted.
|
|
139
|
+
*/
|
|
140
|
+
declare function runWithFallback<T>(invoke: (model: LanguageModel) => Promise<T>, options?: CreateFallbackModelOptions): Promise<FallbackResult<T>>;
|
|
141
|
+
/**
|
|
142
|
+
* Build `providerOptions` that enable prompt caching across providers.
|
|
143
|
+
*
|
|
144
|
+
* - Anthropic: explicit `cacheControl: { type: 'ephemeral' }` on the system
|
|
145
|
+
* message — 90% cost reduction on cached prefix tokens.
|
|
146
|
+
* - OpenAI: prompt caching is AUTOMATIC for prompts ≥1024 tokens with a
|
|
147
|
+
* stable prefix. No flag needed — but callers MUST keep the system prompt
|
|
148
|
+
* + tools FIRST and dynamic user content LAST, otherwise the cache is
|
|
149
|
+
* invalidated on every call.
|
|
150
|
+
* - OpenRouter: passes provider options through transparently.
|
|
151
|
+
*/
|
|
152
|
+
declare function withAnthropicCacheControl(): {
|
|
153
|
+
anthropic: {
|
|
154
|
+
cacheControl: {
|
|
155
|
+
type: "ephemeral";
|
|
156
|
+
};
|
|
157
|
+
};
|
|
158
|
+
};
|
|
159
|
+
/**
|
|
160
|
+
* Wraps the system message in a structured cache-control hint.
|
|
161
|
+
* Returns the messages array unchanged if no system text is provided.
|
|
162
|
+
*
|
|
163
|
+
* IMPORTANT: keep stable content (system prompt + tool defs) FIRST,
|
|
164
|
+
* dynamic content (user query) LAST — required for both Anthropic explicit
|
|
165
|
+
* caching AND OpenAI automatic caching to hit.
|
|
166
|
+
*/
|
|
167
|
+
declare function buildSystemWithCache(systemPrompt: string): {
|
|
168
|
+
role: "system";
|
|
169
|
+
content: string;
|
|
170
|
+
providerOptions: ReturnType<typeof withAnthropicCacheControl>;
|
|
171
|
+
};
|
|
172
|
+
interface EmbeddingFallbackOptions {
|
|
173
|
+
chain?: readonly FallbackProviderName[];
|
|
174
|
+
model?: string;
|
|
175
|
+
filterAvailable?: boolean;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Run an AI SDK embedding call against the configured embedding fallback chain.
|
|
179
|
+
*
|
|
180
|
+
* The caller provides an `invoke(model)` function — usually a closure over
|
|
181
|
+
* `embed` or `embedMany` from the `ai` package — and this helper walks the
|
|
182
|
+
* embedding-capable chain, trying each provider until one succeeds.
|
|
183
|
+
*/
|
|
184
|
+
declare function runEmbedWithFallback<T>(invoke: (model: EmbeddingModel) => Promise<T>, options?: EmbeddingFallbackOptions): Promise<FallbackResult<T>>;
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Image / video generation modality for `@nebutra/agents`.
|
|
188
|
+
*
|
|
189
|
+
* The text + embedding modalities wrap the Vercel AI SDK. Image / video
|
|
190
|
+
* generation is a *new modality on the same provider layer*: providers are
|
|
191
|
+
* env-key gated exactly like the LLM fallback chain (see `fallback.ts`), so
|
|
192
|
+
* single-provider — or zero-provider (mock) — deploys just work.
|
|
193
|
+
*
|
|
194
|
+
* Generation is tenant-scoped: every call carries a {@link GenerationContext}
|
|
195
|
+
* so downstream metering / audit can attribute units to an organization.
|
|
196
|
+
*/
|
|
197
|
+
/** What a provider can produce. */
|
|
198
|
+
type GenerationModality = "image" | "video";
|
|
199
|
+
/** Tenant-scoped attribution for a generation call (mirrors AgentContext). */
|
|
200
|
+
interface GenerationContext {
|
|
201
|
+
readonly tenantId: string;
|
|
202
|
+
readonly userId: string;
|
|
203
|
+
/** Optional logical grouping (e.g. a canvas / conversation id). */
|
|
204
|
+
readonly conversationId?: string;
|
|
205
|
+
}
|
|
206
|
+
interface ImageGenerationRequest {
|
|
207
|
+
readonly prompt: string;
|
|
208
|
+
/** Pixel width — defaults to 1024. */
|
|
209
|
+
readonly width?: number;
|
|
210
|
+
/** Pixel height — defaults to 1024. */
|
|
211
|
+
readonly height?: number;
|
|
212
|
+
/** Optional model id / preset; provider-specific passthrough. */
|
|
213
|
+
readonly model?: string;
|
|
214
|
+
/** Reference images (data: URI or URL) for edit / variation flows. */
|
|
215
|
+
readonly inputImages?: readonly string[];
|
|
216
|
+
}
|
|
217
|
+
interface VideoGenerationRequest {
|
|
218
|
+
readonly prompt: string;
|
|
219
|
+
/** Clip length in seconds — defaults to 5. */
|
|
220
|
+
readonly durationSeconds?: number;
|
|
221
|
+
readonly width?: number;
|
|
222
|
+
readonly height?: number;
|
|
223
|
+
readonly model?: string;
|
|
224
|
+
/** Optional first-frame image (data: URI or URL). */
|
|
225
|
+
readonly inputImage?: string;
|
|
226
|
+
}
|
|
227
|
+
interface GenerationResult {
|
|
228
|
+
readonly modality: GenerationModality;
|
|
229
|
+
/** e.g. "image/svg+xml", "image/png", "video/mp4". */
|
|
230
|
+
readonly mimeType: string;
|
|
231
|
+
/** `data:` URI (mock / inline) or a remote URL the caller can fetch. */
|
|
232
|
+
readonly url: string;
|
|
233
|
+
readonly width: number;
|
|
234
|
+
readonly height: number;
|
|
235
|
+
/** Provider that actually produced the asset. */
|
|
236
|
+
readonly providerName: string;
|
|
237
|
+
/** Model id reported by the provider. */
|
|
238
|
+
readonly model: string;
|
|
239
|
+
/**
|
|
240
|
+
* Best-effort billable units for `@nebutra/metering` (e.g. 1 image,
|
|
241
|
+
* N seconds of video). Callers decide the meter mapping.
|
|
242
|
+
*/
|
|
243
|
+
readonly usage: {
|
|
244
|
+
readonly units: number;
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* A generation backend. `envKey` mirrors the LLM provider gating: when the
|
|
249
|
+
* variable is absent the provider is filtered out of the chain. `null` means
|
|
250
|
+
* "always available" — reserved for the deterministic mock provider so CI and
|
|
251
|
+
* flag-gated demos never need a paid secret.
|
|
252
|
+
*/
|
|
253
|
+
interface GenerationProvider {
|
|
254
|
+
readonly name: string;
|
|
255
|
+
readonly envKey: string | null;
|
|
256
|
+
readonly capabilities: readonly GenerationModality[];
|
|
257
|
+
generateImage?(req: ImageGenerationRequest, ctx: GenerationContext): Promise<GenerationResult>;
|
|
258
|
+
generateVideo?(req: VideoGenerationRequest, ctx: GenerationContext): Promise<GenerationResult>;
|
|
259
|
+
}
|
|
260
|
+
interface GenerationCallOptions {
|
|
261
|
+
/**
|
|
262
|
+
* Ordered provider-name preference. Unknown / unavailable names are skipped.
|
|
263
|
+
* Defaults to `GENERATION_FALLBACK_CHAIN` env (comma-separated) then registry
|
|
264
|
+
* order, always ending at `mock` so a result is guaranteed.
|
|
265
|
+
*/
|
|
266
|
+
readonly chain?: readonly string[];
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Deterministic mock generation provider.
|
|
271
|
+
*
|
|
272
|
+
* Always available (`envKey: null`) so CI and flag-gated demos never need a
|
|
273
|
+
* paid secret. Output is a stable, content-addressed SVG `data:` URI: the same
|
|
274
|
+
* prompt + size always yields byte-identical bytes, which makes canvas
|
|
275
|
+
* placement and websocket-sync tests deterministic.
|
|
276
|
+
*
|
|
277
|
+
* Wiring a real provider (Replicate / OpenAI images / Volces) later is purely
|
|
278
|
+
* additive — register it with a non-null `envKey` and it takes priority over
|
|
279
|
+
* `mock` in the fallback chain whenever its key is present.
|
|
280
|
+
*/
|
|
281
|
+
|
|
282
|
+
declare const mockGenerationProvider: GenerationProvider;
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Image / video generation modality — public surface.
|
|
286
|
+
*
|
|
287
|
+
* Mirrors the LLM fallback design (`fallback.ts`): an ordered provider chain,
|
|
288
|
+
* filtered to providers whose `envKey` is present, with `mock` as the
|
|
289
|
+
* guaranteed terminal so a result is always produced. Retryable failures
|
|
290
|
+
* (429 / 5xx / network) rotate to the next provider via `isRetryableError`.
|
|
291
|
+
*/
|
|
292
|
+
|
|
293
|
+
declare function registerGenerationProvider(provider: GenerationProvider): void;
|
|
294
|
+
/** Test helper — restores the registry to just the mock provider. */
|
|
295
|
+
declare function _resetGenerationRegistry(): void;
|
|
296
|
+
/** Provider names available for a modality, in resolved priority order. */
|
|
297
|
+
declare function listGenerationProviders(modality: GenerationModality, options?: GenerationCallOptions): string[];
|
|
298
|
+
/**
|
|
299
|
+
* Generate an image. Always resolves (falls back to the deterministic mock).
|
|
300
|
+
*/
|
|
301
|
+
declare function generateImage(req: ImageGenerationRequest, ctx: GenerationContext, options?: GenerationCallOptions): Promise<GenerationResult>;
|
|
302
|
+
/**
|
|
303
|
+
* Generate a video (or, in mock mode, a deterministic poster frame).
|
|
304
|
+
*/
|
|
305
|
+
declare function generateVideo(req: VideoGenerationRequest, ctx: GenerationContext, options?: GenerationCallOptions): Promise<GenerationResult>;
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Agent memory — Redis-backed per-tenant conversation persistence.
|
|
309
|
+
*
|
|
310
|
+
* Key format: `agent:memory:{tenantId}:{conversationId}`
|
|
311
|
+
* TTL: 7 days (configurable via AGENT_MEMORY_TTL_SECONDS env var).
|
|
312
|
+
*
|
|
313
|
+
* Graceful degradation: if Redis is unavailable, functions return
|
|
314
|
+
* empty arrays / silently skip writes so agents still work in
|
|
315
|
+
* in-memory-only mode.
|
|
316
|
+
*/
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Load conversation history from Redis.
|
|
320
|
+
* Returns an empty array when Redis is unavailable.
|
|
321
|
+
*/
|
|
322
|
+
declare function getMemory(tenantId: string, conversationId: string): Promise<AgentMessage[]>;
|
|
323
|
+
/**
|
|
324
|
+
* Persist messages to Redis with TTL.
|
|
325
|
+
* Silently skips when Redis is unavailable.
|
|
326
|
+
*/
|
|
327
|
+
declare function saveMemory(tenantId: string, conversationId: string, messages: readonly AgentMessage[]): Promise<void>;
|
|
328
|
+
/**
|
|
329
|
+
* Clear conversation memory for a tenant/conversation pair.
|
|
330
|
+
*/
|
|
331
|
+
declare function clearMemory(tenantId: string, conversationId: string): Promise<void>;
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* LLM observability via Langfuse.
|
|
335
|
+
*
|
|
336
|
+
* - No-op when env vars are missing — the package works with zero config.
|
|
337
|
+
* - Exposes `experimental_telemetry` settings ready to plug into Vercel AI SDK.
|
|
338
|
+
* - Use `LangfuseExporter` from `langfuse-vercel` in your OTEL NodeSDK setup
|
|
339
|
+
* for full trace export (see README).
|
|
340
|
+
*/
|
|
341
|
+
type LangfuseClient = {
|
|
342
|
+
trace: (input: unknown) => unknown;
|
|
343
|
+
flushAsync: () => Promise<void>;
|
|
344
|
+
shutdownAsync: () => Promise<void>;
|
|
345
|
+
};
|
|
346
|
+
/**
|
|
347
|
+
* Returns a configured `Langfuse` client, or `null` when env is missing.
|
|
348
|
+
*
|
|
349
|
+
* Telemetry is OPTIONAL. If LANGFUSE_PUBLIC_KEY / LANGFUSE_SECRET_KEY are
|
|
350
|
+
* not set, this returns null (no error). Callers must handle the null case.
|
|
351
|
+
*/
|
|
352
|
+
declare function initLangfuse(): Promise<LangfuseClient | null>;
|
|
353
|
+
interface TelemetryMetadata {
|
|
354
|
+
tenantId?: string | undefined;
|
|
355
|
+
userId?: string | undefined;
|
|
356
|
+
sessionId?: string | undefined;
|
|
357
|
+
agentId?: string | undefined;
|
|
358
|
+
[key: string]: unknown;
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Build the `experimental_telemetry` option for AI SDK calls.
|
|
362
|
+
* Returns `{ isEnabled: false }` (a safe no-op) when Langfuse is not configured,
|
|
363
|
+
* which avoids any OTEL span creation cost.
|
|
364
|
+
*/
|
|
365
|
+
declare function buildTelemetryConfig(args: {
|
|
366
|
+
functionId: string;
|
|
367
|
+
metadata?: TelemetryMetadata;
|
|
368
|
+
}): {
|
|
369
|
+
isEnabled: boolean;
|
|
370
|
+
functionId?: string;
|
|
371
|
+
metadata?: Record<string, unknown>;
|
|
372
|
+
};
|
|
373
|
+
/** Flush pending telemetry before process exit. Safe to call when disabled. */
|
|
374
|
+
declare function flushTelemetry(): Promise<void>;
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* AgentOrchestrator — multi-agent coordination engine.
|
|
378
|
+
*
|
|
379
|
+
* Supports three execution modes:
|
|
380
|
+
* - chat(): route a single message to the best agent
|
|
381
|
+
* - pipeline(): chain agents sequentially (output → next input)
|
|
382
|
+
* - broadcast(): fan-out to all agents and collect results
|
|
383
|
+
*/
|
|
384
|
+
|
|
385
|
+
declare class AgentOrchestrator {
|
|
386
|
+
private readonly agents;
|
|
387
|
+
private readonly router;
|
|
388
|
+
private readonly defaultAgentId;
|
|
389
|
+
constructor(config: OrchestratorConfig);
|
|
390
|
+
/**
|
|
391
|
+
* Register a pre-built agent instance (e.g. VercelAIAgent).
|
|
392
|
+
* Overwrites any agent with the same ID.
|
|
393
|
+
*/
|
|
394
|
+
registerAgent(agent: BaseAgent): void;
|
|
395
|
+
/**
|
|
396
|
+
* Get a registered agent by ID.
|
|
397
|
+
*/
|
|
398
|
+
getAgent(agentId: string): BaseAgent | undefined;
|
|
399
|
+
/**
|
|
400
|
+
* Route a message to the best agent and execute.
|
|
401
|
+
*/
|
|
402
|
+
chat(message: string, context: AgentContext): Promise<AgentResponse>;
|
|
403
|
+
/**
|
|
404
|
+
* Execute a multi-agent pipeline where each step's output feeds the next.
|
|
405
|
+
* @experimental — API may change. Use `chat()` for production workloads.
|
|
406
|
+
*/
|
|
407
|
+
pipeline(steps: readonly PipelineStep[], input: string, context: AgentContext): Promise<AgentResponse>;
|
|
408
|
+
/**
|
|
409
|
+
* Broadcast a message to ALL registered agents in parallel.
|
|
410
|
+
* Returns an array of responses (one per agent).
|
|
411
|
+
* @experimental — API may change. Use `chat()` for production workloads.
|
|
412
|
+
*/
|
|
413
|
+
broadcast(message: string, context: AgentContext): Promise<readonly AgentResponse[]>;
|
|
414
|
+
/**
|
|
415
|
+
* Check tenant quota before execution.
|
|
416
|
+
*/
|
|
417
|
+
private assertQuota;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* AgentRouter — routes incoming messages to the appropriate agent.
|
|
422
|
+
*
|
|
423
|
+
* Strategies:
|
|
424
|
+
* - keyword: fast, pattern-based matching against agent descriptions
|
|
425
|
+
* - llm: uses a small model to classify intent (requires AI SDK)
|
|
426
|
+
* - custom: user-supplied routing function
|
|
427
|
+
*/
|
|
428
|
+
|
|
429
|
+
declare class AgentRouter {
|
|
430
|
+
private readonly config;
|
|
431
|
+
constructor(config: RouterConfig);
|
|
432
|
+
/**
|
|
433
|
+
* Route a message to the best-matching agent.
|
|
434
|
+
* Returns the agent ID.
|
|
435
|
+
*/
|
|
436
|
+
route(message: string, agents: readonly AgentConfig[], context: AgentContext, defaultAgentId?: string): Promise<string>;
|
|
437
|
+
/**
|
|
438
|
+
* Keyword-based routing: score each agent by how many words from
|
|
439
|
+
* its name + description appear in the user message.
|
|
440
|
+
*/
|
|
441
|
+
private routeByKeyword;
|
|
442
|
+
/**
|
|
443
|
+
* LLM-based routing: uses a small model to classify the user's intent
|
|
444
|
+
* and select the best agent. Falls back to keyword if AI SDK unavailable.
|
|
445
|
+
*/
|
|
446
|
+
private routeByLLM;
|
|
447
|
+
/**
|
|
448
|
+
* Custom routing via user-supplied function.
|
|
449
|
+
*/
|
|
450
|
+
private routeByCustom;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Tenant-scoped agent execution context.
|
|
455
|
+
*
|
|
456
|
+
* Ensures every agent operation carries tenantId for RLS,
|
|
457
|
+
* billing, and audit trail purposes.
|
|
458
|
+
*/
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* Create a fully-populated AgentContext.
|
|
462
|
+
* Generates a random conversationId when none is provided.
|
|
463
|
+
*/
|
|
464
|
+
declare function createAgentContext(tenantId: string, userId: string, conversationId?: string, metadata?: Record<string, unknown>): AgentContext;
|
|
465
|
+
/**
|
|
466
|
+
* Validate that a tenant has remaining quota for agent execution.
|
|
467
|
+
*
|
|
468
|
+
* Returns `{ allowed: true, remaining: -1 }` (unlimited) by default.
|
|
469
|
+
* Integrate with @nebutra/billing entitlements for production usage.
|
|
470
|
+
*/
|
|
471
|
+
declare function checkAgentQuota(tenantId: string): Promise<{
|
|
472
|
+
allowed: boolean;
|
|
473
|
+
remaining: number;
|
|
474
|
+
}>;
|
|
475
|
+
|
|
476
|
+
export { AgentConfig, AgentContext, AgentMessage, AgentOrchestrator, AgentResponse, AgentRouter, type AgentsEnv, AgentsEnvSchema, BaseAgent, type CreateFallbackModelOptions, type EmbeddingFallbackOptions, FallbackProviderName, type FallbackResult, type GenerationCallOptions, type GenerationContext, type GenerationModality, type GenerationProvider, type GenerationResult, type ImageGenerationRequest, OrchestratorConfig, PipelineStep, RouterConfig, type TelemetryMetadata, type UserContext, type VideoGenerationRequest, _resetGenerationRegistry, buildPersonalizedSystemPrompt, buildSystemWithCache, buildTelemetryConfig, checkAgentQuota, clearMemory, createAgentContext, filterAvailableProviders, flushTelemetry, generateImage, generateVideo, getAgentsEnv, getMemory, initLangfuse, isLangfuseConfigured, isRetryableError, listGenerationProviders, mockGenerationProvider, registerGenerationProvider, renderUserContextBlock, runEmbedWithFallback, runWithFallback, saveMemory, withAnthropicCacheControl };
|