import { z } from 'zod'; type MessageRole = 'system' | 'user' | 'assistant' | 'tool'; interface ToolCall { id: string; type: 'function'; function: { name: string; arguments: string; }; } interface ToolDefinition { type: 'function'; function: { name: string; description?: string; parameters?: Record; }; } interface Tool extends ToolDefinition { execute: (args: T) => Promise; } interface GenerateTextResult { text: string; toolCalls: Array; toolResults: Array<{ id: string; result: unknown; }>; finishReason: 'stop' | 'length' | 'tool_calls' | 'error' | 'unknown'; usage: { promptTokens: number; completionTokens: number; totalTokens: number; }; warnings?: Array; } interface TextContentPart { type: 'text'; text: string; } interface ImageContentPart { type: 'image_url'; image_url: { url: string; detail?: 'auto' | 'low' | 'high'; }; } type ContentPart = TextContentPart | ImageContentPart; interface Message { role: MessageRole; content: string | Array | null; thinking?: string; toolCalls?: Array; toolCallId?: string; name?: string; } interface ImageGenerationOptions { prompt: string; model?: string; n?: number; size?: string; quality?: string; style?: string; response_format?: 'url' | 'b64_json'; user?: string; } interface ImageEditOptions extends ImageGenerationOptions { image: string | Blob | Buffer; mask?: string | Blob | Buffer; } interface ImageContent { url?: string; b64_json?: string; revised_prompt?: string; } interface ImageResult { created: number; data: ImageContent[]; } interface ImageAnalysisOptions { image: string | Blob | Buffer; prompt?: string; model: string; messages?: Array; } interface ImageAnalysisResult { content: string; usage?: { inputTokens?: number; outputTokens?: number; totalTokens?: number; }; } interface SpeechGenerationOptions { input: string; model?: string; voice: string; response_format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm'; speed?: number; } interface SpeechResult { buffer: ArrayBuffer; headers?: Record; } interface VideoGenerationOptions { prompt: string; model?: string; aspect_ratio?: string; duration_seconds?: number; } interface VideoContent { url?: string; b64_json?: string; } interface VideoResult { data: VideoContent[]; } interface VideoAnalysisOptions { video: string | Blob | Buffer; prompt?: string; model: string; messages?: Array; } interface VideoAnalysisResult { content: string; usage?: { inputTokens?: number; outputTokens?: number; totalTokens?: number; }; } interface ChatOptions { model: string; messages: Array; tools?: Array; temperature?: number; maxTokens?: number; stream?: boolean; think?: boolean; signal?: AbortSignal; /** Force a specific response format. 'json_object' enables JSON mode. */ responseFormat?: { type: 'json_object' | 'text'; }; } interface ChatResult { message: Message; usage?: { promptTokens: number; completionTokens: number; totalTokens: number; }; } interface StreamChunk { delta: string; thinking?: string; toolCallDelta?: { index: number; id?: string; type?: 'function'; function?: { name?: string; arguments?: string; }; }; usage?: { promptTokens: number; completionTokens: number; totalTokens: number; }; } interface TranscriptionOptions { file: File | Blob | Buffer; model?: string; language?: string; prompt?: string; response_format?: 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt'; temperature?: number; } interface TranscriptionResult { text: string; language?: string; duration?: number; segments?: Array<{ start: number; end: number; text: string; }>; } interface EmbeddingOptions { /** The text(s) to embed. Pass a string for a single embedding or an array for batch. */ input: string | string[]; /** The embedding model to use (e.g., 'text-embedding-3-small'). */ model?: string; /** Number of dimensions for the output embedding (supported by some models). */ dimensions?: number; } interface EmbeddingResult { /** Array of embedding vectors — one per input string. */ embeddings: number[][]; /** Model used for the embeddings. */ model: string; usage?: { promptTokens: number; totalTokens: number; }; } interface ModelLimit { /** Maximum context window size in tokens */ context: number; /** Maximum output tokens */ output: number; } interface ModelModalities { input: Array<'text' | 'image' | 'audio' | 'video' | 'file'>; output: Array<'text' | 'image' | 'audio' | 'video'>; } interface ModelCost { /** Cost per 1M input tokens (USD) */ input?: number; /** Cost per 1M output tokens (USD) */ output?: number; /** Cost per 1M cached input tokens (USD) */ cache_read?: number; } /** * OpenResponses-compliant reasoning configuration. * Maps from `models.dev` boolean `reasoning` flag into * the official `ReasoningEffortEnum` from openresponses/openresponses. */ interface OpenResponsesReasoningConfig { effort?: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'; summary?: 'none' | 'terse' | 'verbose' | 'detailed'; } /** * A standardized model definition that fuses the `models.dev` catalog * with the `openresponses.org` specification. * * This type is returned by providers that support catalog introspection * (e.g., fetching from `https://models.dev/api.json`). */ interface ModelDefinition { /** Unique model identifier (e.g. "gpt-4o", "glm-4.6") */ id: string; /** Human-readable display name */ name: string; /** Model architecture family (e.g. "gpt", "glm", "deepseek") */ family?: string; /** Provider name (e.g. "OpenAI", "Ollama Cloud") */ provider?: string; /** Whether the model supports file/image/audio attachments in input */ attachment: boolean; /** Whether the model supports function/tool calling */ tool_call: boolean; /** Whether the model supports structured JSON output */ structured_output?: boolean; /** * Reasoning capability. * - `false`: No reasoning support. * - `true`: Reasoning supported (default effort = "medium"). * - `OpenResponsesReasoningConfig`: Fine-grained reasoning control * per the official openresponses.org ReasoningEffortEnum. */ reasoning: boolean | OpenResponsesReasoningConfig; /** Supported input/output modalities */ modalities: ModelModalities; /** Token limits */ limit: ModelLimit; /** Pricing per 1M tokens */ cost?: ModelCost; } interface PluginContext { model: string; messages: Array; timestamp: number; requestOptions?: Record; } interface TekimaxPlugin { name: string; /** Triggered when the Tekimax client is instantiated */ onInit?: (client: any) => void; /** Triggered before a chat or stream request is sent. Can mutate the context. */ beforeRequest?: (context: PluginContext) => Promise; /** Triggered after a fully completed standard chat response */ afterResponse?: (context: PluginContext, result: ChatResult) => Promise; /** Triggered on every chunk during a streaming response */ onStreamChunk?: (context: PluginContext, chunk: StreamChunk) => void; /** Triggered before a tool is executed */ beforeToolExecute?: (toolName: string, args: unknown) => Promise; /** Triggered after a tool is executed */ afterToolExecute?: (toolName: string, result: unknown) => Promise; } interface AIProvider { name: string; /** * Send a chat completion request. */ chat: (options: ChatOptions) => Promise; /** * Stream a chat completion. */ chatStream: (options: ChatOptions) => AsyncIterable; /** * Optional: Fetch the catalog of available models from this provider. * Returns OpenResponses-compliant ModelDefinition objects fused with * models.dev metadata (modalities, limits, reasoning flags). */ getModels?: () => Promise; } interface ImageGenerationCapability { /** * Generate an image. */ generateImage: (options: ImageGenerationOptions) => Promise; } interface ImageEditCapability { /** * Edit an image. */ editImage: (options: ImageEditOptions) => Promise; } interface VisionCapability { /** * Analyze an image (Vision). */ analyzeImage: (options: ImageAnalysisOptions) => Promise; } interface SpeechGenerationCapability { /** * Generate speech from text (TTS). */ generateSpeech: (options: SpeechGenerationOptions) => Promise; } interface TranscriptionCapability { /** * Transcribe audio to text (STT). */ transcribeAudio: (options: TranscriptionOptions) => Promise; } interface VideoGenerationCapability { /** * Generate a video. */ generateVideo: (options: VideoGenerationOptions) => Promise; } interface VideoAnalysisCapability { /** * Analyze a video (Video-to-Text). */ analyzeVideo: (options: VideoAnalysisOptions) => Promise; } interface EmbeddingCapability { /** * Generate embeddings for text input(s). */ embed: (options: EmbeddingOptions) => Promise; } /** * Auto-generated API types placeholder. * * To generate from the OpenAPI spec, run: * npx kubb generate * * This stub file exists so TypeScript doesn't error on * `export * as ApiTypes from './gen/types'` in the SDK index. */ interface UserMessageItemParam { role: 'user'; content: string | Array>; [key: string]: any; } interface AssistantMessageItemParam { role: 'assistant'; content: string | Array>; [key: string]: any; } interface CreateResponseBody { model?: string; input?: any; instructions?: string; [key: string]: any; } interface ResponseResource { id: string; object: string; output: Array>; usage?: Record; [key: string]: any; } type types_AssistantMessageItemParam = AssistantMessageItemParam; type types_CreateResponseBody = CreateResponseBody; type types_ResponseResource = ResponseResource; type types_UserMessageItemParam = UserMessageItemParam; declare namespace types { export type { types_AssistantMessageItemParam as AssistantMessageItemParam, types_CreateResponseBody as CreateResponseBody, types_ResponseResource as ResponseResource, types_UserMessageItemParam as UserMessageItemParam }; } /** * A wrapper around the raw API response that provides helper methods * for common tasks like extracting text content. */ declare class TekimaxResponse { private readonly _raw; constructor(_raw: ResponseResource); /** * Access the raw response object returned by the API. */ get raw(): ResponseResource; /** * Automatically extracts the text content from the response. * It looks for the first "output_text" item in the response content. */ get text(): string | undefined; /** * The ID of the response. */ get id(): string | undefined; /** * The model used to generate the response. */ get model(): string | undefined; } /** * Options for sending a message or creating a session. */ type MessageOptions = Omit & { signal?: AbortSignal; }; /** * The main client for interacting with the Tekimax API. */ declare class TekimaxClient { private baseUrl; private headers; /** * Creates a new TekimaxClient. * * @param options - Configuration options for the client. * @param options.baseUrl - The base URL of the API (default: "https://api.tekimax.com"). * @param options.apiKey - Your Tekimax API key. * * @example * const client = new TekimaxClient({ apiKey: "tm_..." }); */ constructor(options?: { baseUrl?: string; apiKey?: string; }); private request; private requestStream; /** * Creates a new session and sends the initial message. * * @param message - The initial message text or array of message items to start the session. * @param options - Additional configuration options (model, temperature, etc.). * * @example * const response = await client.createSession("Hello, world!", { model: "gpt-4" }); * console.log(response.text); */ createSession(message: string | any[], options?: MessageOptions): Promise; /** * Sends a message to an existing session or starts a new one if no previous_response_id is provided. * * @param message - The message text or history array to send. * @param options - Additional configuration options. * * @example * const response = await client.sendMessage("What is the weather?", { * previous_response_id: "resp_123" * }); * console.log(response.text); */ sendMessage(message: string | any[], options?: MessageOptions): Promise; /** * Sends a message and returns an asynchronous iterable of streaming events. */ sendMessageStream(message: string | any[], options?: MessageOptions): AsyncIterable; } declare class TekimaxProvider implements AIProvider { name: string; private client; constructor(options?: { baseUrl?: string; apiKey?: string; }); chat(options: ChatOptions): Promise; chatStream(options: ChatOptions): AsyncIterable; private mapMessages; } /** * Helper to define a tool with type inference. * * @example * const weatherTool = tool({ * name: 'weather', * description: 'Get weather', * parameters: { type: 'object', properties: { location: { type: 'string' } } }, * execute: async ({ location }) => { ... } * }) */ declare function tool(def: Tool): Tool; interface GenerateTextOptions { model: string; messages: Array; tools?: Record; maxSteps?: number; temperature?: number; maxTokens?: number; signal?: AbortSignal; plugins?: TekimaxPlugin[]; } declare function generateText({ adapter, plugins, ...options }: GenerateTextOptions & { adapter: AIProvider; }): Promise; declare const fileToBase64: (file: File) => Promise; declare const parseThinking: (content: string) => { think: null; rest: string; } | { think: string; rest: string; }; declare class AnthropicProvider implements AIProvider, VisionCapability { name: string; private client; constructor(options: { apiKey: string; }); analyzeImage(options: ImageAnalysisOptions): Promise; chat(options: ChatOptions): Promise; chatStream(options: ChatOptions): AsyncIterable; private mapMessages; private mapTool; } declare class GeminiProvider implements AIProvider, VisionCapability, VideoAnalysisCapability, EmbeddingCapability { name: string; private client; constructor(options: { apiKey: string; }); private convertContent; analyzeVideo(options: VideoAnalysisOptions): Promise; analyzeImage(options: ImageAnalysisOptions): Promise; chat(options: ChatOptions): Promise; chatStream(options: ChatOptions): AsyncIterable; private mapHistory; private mapTool; embed(options: EmbeddingOptions): Promise; } declare class OllamaProvider implements AIProvider { name: string; private client; constructor(options?: { host?: string; apiKey?: string; }); chat(options: ChatOptions): Promise; chatStream(options: ChatOptions): AsyncIterable; private mapMessages; private mapTool; } declare class OpenAIProvider implements AIProvider, SpeechGenerationCapability, ImageGenerationCapability, ImageEditCapability, VisionCapability, TranscriptionCapability, EmbeddingCapability { name: string; private client; constructor(options: { apiKey: string; baseURL?: string; }); generateSpeech(options: SpeechGenerationOptions): Promise; generateImage(options: ImageGenerationOptions): Promise; analyzeImage(options: ImageAnalysisOptions): Promise; chat(options: ChatOptions): Promise; chatStream(options: ChatOptions): AsyncIterable; private mapMessages; private mapTool; private mapResponseMessage; transcribeAudio(options: TranscriptionOptions): Promise; embed(options: EmbeddingOptions): Promise; editImage(options: ImageEditOptions): Promise; } declare class GrokProvider implements AIProvider { name: string; private client; constructor(options: { apiKey: string; }); chat(options: ChatOptions): Promise; chatStream(options: ChatOptions): AsyncIterable; private mapMessages; private mapTool; private mapResponseMessage; } declare class OpenRouterProvider implements AIProvider { name: string; private client; constructor(options: { apiKey: string; }); chat(options: ChatOptions): Promise; chatStream(options: ChatOptions): AsyncIterable; private mapMessages; private mapTool; private mapResponseMessage; } interface GenerateObjectOptions { adapter: AIProvider; model: string; schema: T; messages: Array; temperature?: number; maxTokens?: number; signal?: AbortSignal; /** * Maximum number of validation retries. * When the model returns JSON that doesn't match the schema, * the SDK appends the Zod error and re-prompts. * @default 1 */ maxRetries?: number; } interface GenerateObjectResult { object: T; usage?: ChatResult['usage']; } /** * Generate a typed, schema-validated object from an LLM. * * Injects a system instruction asking for JSON, parses the response * with the provided Zod schema, and retries on validation failure. * * @example * ```ts * const result = await generateObject({ * adapter: provider, * model: 'gpt-4o', * schema: z.object({ name: z.string(), age: z.number() }), * messages: [{ role: 'user', content: 'Extract: John is 30 years old' }], * }) * console.log(result.object) // { name: "John", age: 30 } * ``` */ declare function generateObject(options: GenerateObjectOptions): Promise>>; /** * Cost estimation for LLM API calls. * * Prices are per 1M tokens in USD (as of Feb 2026). * Returns null for unknown models — this is intentionally not an error. */ interface CostEstimate { inputCost: number; outputCost: number; totalCost: number; currency: 'USD'; } interface TokenUsage { promptTokens: number; completionTokens: number; totalTokens: number; } /** * Estimate the cost of an API call based on token usage. * * @returns CostEstimate or null if the model is not in the price table. * * @example * ```ts * const result = await client.text.generate({ model: 'gpt-4o', ... }) * const cost = estimateCost(result.usage, 'gpt-4o') * if (cost) console.log(`$${cost.totalCost.toFixed(4)}`) * ``` */ declare function estimateCost(usage: TokenUsage | undefined | null, model: string): CostEstimate | null; /** * Get all models in the price table. */ declare function getSupportedCostModels(): string[]; /** * Register a custom model price (or override an existing one). * * @example * ```ts * registerModelPrice('my-custom-model', { inputPerMillion: 1.0, outputPerMillion: 2.0 }) * ``` */ declare function registerModelPrice(model: string, pricing: { inputPerMillion: number; outputPerMillion: number; }): void; interface RetryOptions { /** * Maximum number of retries (not counting the initial attempt). * @default 3 */ maxRetries?: number; /** * Initial delay in milliseconds before the first retry. * @default 1000 */ initialDelayMs?: number; /** * Multiplier applied to the delay after each retry. * @default 2 */ backoffMultiplier?: number; /** * Maximum delay cap in milliseconds. * @default 30000 */ maxDelayMs?: number; /** * Whether to add random jitter (±25%) to the delay. * Prevents thundering herd when multiple clients retry simultaneously. * @default true */ jitter?: boolean; /** * Custom predicate to determine if an error should trigger a retry. * Default: retries on rate limits (429), server errors (5xx), and network errors. */ shouldRetry?: (error: Error, attempt: number) => boolean; /** * AbortSignal — cancels all pending retries immediately. */ signal?: AbortSignal; } /** * Execute an async function with retry and exponential backoff. * * @example * ```ts * const result = await withRetry( * () => client.text.generate({ model: 'gpt-4o', messages }), * { maxRetries: 3, initialDelayMs: 1000 } * ) * ``` */ declare function withRetry(fn: () => Promise, options?: RetryOptions): Promise; /** * Wrap an AIProvider with automatic retry on all chat/chatStream calls. * * @example * ```ts * const resilientProvider = createRetryProvider(openaiProvider, { maxRetries: 3 }) * const client = new Tekimax({ provider: resilientProvider }) * // All calls through this client now auto-retry on failures * ``` */ declare function createRetryProvider(provider: TProvider, options?: RetryOptions): TProvider; /** * Middleware interface for intercepting provider calls. * * - `beforeChat`: Runs before each chat/chatStream call. Can modify options. * - `afterChat`: Runs after each chat call completes. Can modify the result. * - `onError`: Runs when a chat call throws. Can recover, re-throw, or log. * * All hooks are optional. Middleware runs in array order for `before` hooks * and reverse order for `after` hooks (onion model). */ interface Middleware { name?: string; /** * Intercept before a chat request is sent. * Return modified options to alter the request, or return as-is to pass through. */ beforeChat?: (options: ChatOptions) => Promise | ChatOptions; /** * Intercept after a chat response is received. * Return modified result to alter the response, or return as-is to pass through. */ afterChat?: (result: ChatResult, options: ChatOptions) => Promise | ChatResult; /** * Handle errors from chat calls. * Throw to propagate, return a ChatResult to recover. */ onError?: (error: Error, options: ChatOptions) => Promise | ChatResult | void; /** * Intercept each streaming chunk. * Return modified chunk, or return as-is to pass through. */ onStreamChunk?: (chunk: StreamChunk, options: ChatOptions) => StreamChunk; } /** * Wrap a provider with middleware interceptors. * * Middleware runs in the order provided for `beforeChat` and `onStreamChunk`, * and in reverse order for `afterChat` (onion/pipeline model). * * @example * ```ts * const logger: Middleware = { * name: 'logger', * beforeChat: async (options) => { * console.log('→', options.model) * return options * }, * afterChat: async (result) => { * console.log('←', result.usage?.totalTokens, 'tokens') * return result * }, * } * * const provider = wrapProvider(openaiProvider, [logger]) * const client = new Tekimax({ provider }) * ``` */ declare function wrapProvider(provider: TProvider, middlewares: Middleware[]): TProvider; /** * Logging middleware — logs model, token usage, and latency to console. * * @example * ```ts * const provider = wrapProvider(openaiProvider, [loggingMiddleware()]) * ``` */ declare function loggingMiddleware(options?: { prefix?: string; }): Middleware; interface FallbackProviderOptions { /** * Custom predicate to determine if an error should trigger a fallback. * Default: falls back on any error. */ shouldFallback?: (error: Error, providerName: string) => boolean; /** * Called when a provider fails and the SDK falls back to the next one. * Useful for logging or monitoring. */ onFallback?: (error: Error, failedProvider: string, nextProvider: string) => void; } /** * A provider that tries multiple providers in order, falling back on failure. * * If the first provider throws, it tries the second, then the third, etc. * If all providers fail, the last error is thrown. * * @example * ```ts * const provider = new FallbackProvider([ * new OpenAIProvider({ apiKey: process.env.OPENAI_API_KEY! }), * new AnthropicProvider({ apiKey: process.env.ANTHROPIC_API_KEY! }), * new GeminiProvider({ apiKey: process.env.GEMINI_API_KEY! }), * ]) * * const client = new Tekimax({ provider }) * // If OpenAI is down, it automatically tries Anthropic, then Gemini * ``` */ declare class FallbackProvider implements AIProvider { name: string; private providers; private options; constructor(providers: AIProvider[], options?: FallbackProviderOptions); chat(options: ChatOptions): Promise; chatStream(options: ChatOptions): AsyncIterable; get generateImage(): any; get editImage(): any; get analyzeImage(): any; get generateSpeech(): any; get transcribeAudio(): any; get generateVideo(): any; get analyzeVideo(): any; get embed(): any; /** * Try each provider in order. On failure, fall back to the next. */ private tryProviders; } /** * Minimal Redis client interface. * Compatible with `ioredis`, `@upstash/redis`, `redis` (node-redis), etc. */ interface RedisClient { get(key: string): Promise; set(key: string, value: string, ...args: any[]): Promise; del(key: string | string[]): Promise; incrby(key: string, increment: number): Promise; expire(key: string, seconds: number): Promise; incr(key: string): Promise; ttl(key: string): Promise; keys?(pattern: string): Promise; } interface CacheOptions { /** TTL in seconds for cached responses. Default: 3600 (1 hour) */ ttl?: number; /** Key prefix for all cache entries. Default: 'tekimax:' */ prefix?: string; /** Custom key generation function. Default: SHA-256 of model+messages */ keyFn?: (model: string, messages: any[]) => string; } interface RateLimitOptions { /** Maximum requests per window. Default: 60 */ maxRequests: number; /** Window size in seconds. Default: 60 */ windowSeconds?: number; /** Key prefix. Default: 'tekimax:ratelimit:' */ prefix?: string; } interface TokenBudgetOptions { /** Maximum tokens allowed in the budget period */ maxTokens: number; /** Budget period in seconds. Default: 86400 (24 hours) */ periodSeconds?: number; /** Key prefix. Default: 'tekimax:budget:' */ prefix?: string; } interface SessionOptions { /** TTL for session data in seconds. Default: 1800 (30 minutes) */ ttl?: number; /** Key prefix. Default: 'tekimax:session:' */ prefix?: string; } interface RateLimitResult { allowed: boolean; remaining: number; resetInSeconds: number; } interface TokenBudgetResult { allowed: boolean; used: number; remaining: number; resetInSeconds: number; } /** * Cache AI responses in Redis. Identical requests return cached results * without hitting the provider API — saving cost and latency. * * @example * ```ts * import { ResponseCache } from 'tekimax-ts' * import Redis from 'ioredis' * * const cache = new ResponseCache(new Redis(), { ttl: 3600 }) * * // Check cache before calling provider * const cached = await cache.get('gpt-4o', messages) * if (cached) return cached * * const result = await ai.chat('gpt-4o', messages) * await cache.set('gpt-4o', messages, result) * ``` */ declare class ResponseCache { private redis; private ttl; private prefix; private keyFn; constructor(redis: RedisClient, options?: CacheOptions); get(model: string, messages: any[]): Promise; set(model: string, messages: any[], response: any): Promise; invalidate(model: string, messages: any[]): Promise; private defaultKeyFn; } /** * Track per-provider request rates with sliding windows. * Prevents 429 errors by checking limits before making API calls. * * @example * ```ts * const limiter = new RateLimiter(redis, { maxRequests: 60, windowSeconds: 60 }) * * const { allowed, remaining } = await limiter.check('openai') * if (!allowed) throw new Error('Rate limit exceeded') * * await limiter.record('openai') * ``` */ declare class RateLimiter { private redis; private maxRequests; private windowSeconds; private prefix; constructor(redis: RedisClient, options: RateLimitOptions); check(provider: string): Promise; record(provider: string): Promise; } /** * Track daily/monthly token usage per API key. * Prevent surprise bills by enforcing token budgets. * * @example * ```ts * const budget = new TokenBudget(redis, { maxTokens: 100_000, periodSeconds: 86400 }) * * // Check before making a call * const { allowed, used } = await budget.check('openai-prod') * if (!allowed) throw new Error(`Token budget exhausted (${used} used)`) * * // Record usage after call * await budget.record('openai-prod', result.usage.totalTokens) * ``` */ declare class TokenBudget { private redis; private maxTokens; private periodSeconds; private prefix; constructor(redis: RedisClient, options: TokenBudgetOptions); check(bucket: string): Promise; record(bucket: string, tokensUsed: number): Promise; } /** * Lightweight conversation session storage for serverless/edge deployments. * Store and retrieve message history with automatic TTL expiry. * * @example * ```ts * const sessions = new SessionStore(redis, { ttl: 1800 }) * * // Save conversation state * await sessions.save('user-123', { * messages: [...], * metadata: { model: 'gpt-4o', startedAt: Date.now() } * }) * * // Restore on next request * const session = await sessions.load('user-123') * ``` */ declare class SessionStore { private redis; private ttl; private prefix; constructor(redis: RedisClient, options?: SessionOptions); save(sessionId: string, data: any): Promise; load(sessionId: string): Promise; destroy(sessionId: string): Promise; touch(sessionId: string): Promise; } declare class TextNamespace { private provider; private plugins; constructor(provider: TProvider, plugins?: TekimaxPlugin[]); private runBeforeRequest; /** * Generate text from a prompt (Chat Completion). */ generate(options: ChatOptions): Promise; /** * Stream text generation. */ generateStream(options: ChatOptions): AsyncGenerator; /** * Generate embeddings for text input(s). Only available if the provider supports embeddings. */ embed(options: TProvider extends EmbeddingCapability ? EmbeddingOptions : never): Promise; get chat(): { completions: { create: (options: ChatOptions) => Promise; createStream: (options: ChatOptions) => AsyncGenerator; }; }; } declare class ImagesNamespace { private provider; constructor(provider: TProvider); /** * Generate images from a prompt. Only available if the provider supports image generation. */ generate(options: TProvider extends ImageGenerationCapability ? ImageGenerationOptions : never): Promise; /** * Edit an image with a prompt. Only available if the provider supports image editing. */ edit(options: TProvider extends ImageEditCapability ? ImageEditOptions : never): Promise; /** * Analyze an image (Vision). Only available if the provider supports vision analytics. */ analyze(options: TProvider extends VisionCapability ? ImageAnalysisOptions : never): Promise; } declare class AudioNamespace { private provider; constructor(provider: TProvider); /** * Convert text to speech. Only available if the provider supports TTS. */ speak(options: TProvider extends SpeechGenerationCapability ? SpeechGenerationOptions : never): Promise; /** * Transcribe audio to text. Only available if the provider supports STT. */ transcribe(options: TProvider extends TranscriptionCapability ? TranscriptionOptions : never): Promise; } declare class VideosNamespace { private provider; constructor(provider: TProvider); /** * Generate a video from a prompt. Only available if the provider supports video generation. */ generate(options: TProvider extends VideoGenerationCapability ? VideoGenerationOptions : never): Promise; /** * Analyze a video (Video-to-Text). Only available if the provider supports video analysis. */ analyze(options: TProvider extends VideoAnalysisCapability ? VideoAnalysisOptions : never): Promise; } interface TekimaxOptions { provider: TProvider; plugins?: TekimaxPlugin[]; } declare class Tekimax { private provider; plugins: TekimaxPlugin[]; text: TextNamespace; images: ImagesNamespace; audio: AudioNamespace; videos: VideosNamespace; constructor(options: TekimaxOptions); /** * @deprecated Use client.text.chat instead. Kept for backward compatibility. */ get chat(): { completions: { create: (options: ChatOptions) => Promise; createStream: (options: ChatOptions) => AsyncGenerator; }; }; } /** * Telemetry: basic Logger Plugin * Logs payloads, streaming chunks, and tool execution boundaries. */ declare class LoggerPlugin implements TekimaxPlugin { name: string; onInit(): void; beforeRequest(context: PluginContext): Promise; afterResponse(context: PluginContext, result: ChatResult): Promise; onStreamChunk(context: PluginContext, chunk: StreamChunk): void; beforeToolExecute(toolName: string, args: unknown): Promise; afterToolExecute(toolName: string, result: unknown): Promise; } /** * Security: PII Filter Plugin * Redacts sensitive standard patterns (like emails and SSNs) from messages * before they are sent to the provider. */ declare class PIIFilterPlugin implements TekimaxPlugin { name: string; private patterns; beforeRequest(context: PluginContext): Promise; } /** * Scalability: Max Context Overflow Plugin * Prevents token overflow in long-running loops by aggressively * shifting out the oldest messages (excluding the system prompt) * when the message array exceeds the configured limit. */ declare class MaxContextOverflowPlugin implements TekimaxPlugin { private maxMessages; name: string; constructor(maxMessages?: number); beforeRequest(context: PluginContext): Promise; } interface ProvisionConfig { /** Base URL of the API to connect to */ apiUrl: string; /** API key for authentication (sent as X-API-Key header) */ apiKey?: string; /** Deployment or tenant identifier */ deploymentId?: string; /** Rate limit: max requests per window (default: 60) */ rateLimit?: number; /** Rate limit window in ms (default: 60_000 = 1 minute) */ rateLimitWindow?: number; /** Custom headers to include in every request */ headers?: Record; /** Request timeout in ms (default: 15_000) */ timeout?: number; /** Auth header name (default: 'X-API-Key') */ authHeader?: string; } interface ApiEndpoint { /** HTTP method */ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; /** Path template (supports :param and {param} patterns) */ path: string; /** Description for documentation / logging */ description?: string; } interface ApiResponse { ok: boolean; status: number; data: T; headers: Record; /** Time taken in ms */ latency: number; } /** * A namespace that groups related API endpoints together. * Register named endpoints, then call them by name with params and body. * * @example * ```ts * const users = provision.api('/api/users'); * users.register('search', { method: 'GET', path: '/search?q=:query' }); * users.register('create', { method: 'POST', path: '/' }); * users.register('getById', { method: 'GET', path: '/{id}' }); * * const result = await users.call('search', { query: 'john' }); * const user = await users.call('getById', { id: '123' }); * const created = await users.call('create', {}, { name: 'Jane' }); * ``` */ declare class ApiNamespace { private requestFn; private basePath; private endpoints; constructor(requestFn: (method: string, path: string, body?: unknown) => Promise>, basePath?: string); /** Register a named endpoint */ register(name: string, endpoint: ApiEndpoint): this; /** Register multiple endpoints at once */ registerAll(endpoints: Record): this; /** Call a registered endpoint by name */ call(name: string, params?: Record, body?: unknown): Promise>; /** List all registered endpoint names */ list(): string[]; get(path: string): Promise>; post(path: string, body?: unknown): Promise>; put(path: string, body?: unknown): Promise>; patch(path: string, body?: unknown): Promise>; del(path: string): Promise>; } /** * ProvisionPlugin — A generic, endpoint-agnostic API client plugin for * the Tekimax SDK. Provides authenticated, rate-limited access to any * REST API with a clean namespace pattern. * * Features: * - **Auth injection**: API key sent via configurable header (`X-API-Key` default) * - **Rate limiting**: Token-bucket limiter to prevent API abuse * - **Timeout handling**: Configurable request timeouts via AbortController * - **Namespace pattern**: Group related endpoints with `api()` method * - **Type-safe responses**: Generic `ApiResponse` with latency tracking * * @example * ```ts * import { ProvisionPlugin } from 'tekimax-ts'; * * const provision = new ProvisionPlugin({ * apiUrl: 'https://api.example.com', * apiKey: 'sk_live_...', * }); * * // Create namespaces for different API areas * const users = provision.api('/api/users'); * users.registerAll({ * list: { method: 'GET', path: '/' }, * get: { method: 'GET', path: '/{id}' }, * create: { method: 'POST', path: '/' }, * delete: { method: 'DELETE', path: '/{id}' }, * }); * * // Type-safe calls * const result = await users.call('list'); * const user = await users.call('get', { id: '123' }); * * // Direct HTTP for one-off requests * const health = await provision.request('GET', '/api/health'); * ``` */ declare class ProvisionPlugin implements TekimaxPlugin { name: string; private config; private rateLimiter; private _apis; constructor(config: ProvisionConfig); onInit(client: any): void; beforeRequest(context: PluginContext): Promise; /** * Get or create a namespaced API client. Namespaces are cached by * basePath for reuse across your application. * * @param basePath - Base path prefix for all endpoints in this namespace */ api(basePath?: string): ApiNamespace; /** * Make an authenticated, rate-limited request to the API. * Used by all namespaces and also available for direct calls. */ request(method: string, path: string, body?: unknown): Promise>; } export { type AIProvider, AnthropicProvider, type ApiEndpoint, ApiNamespace, type ApiResponse, types as ApiTypes, type CacheOptions, type ChatOptions, type ChatResult, type ContentPart, type CostEstimate, type EmbeddingCapability, type EmbeddingOptions, type EmbeddingResult, FallbackProvider, type FallbackProviderOptions, GeminiProvider, type GenerateObjectOptions, type GenerateObjectResult, type GenerateTextOptions, type GenerateTextResult, GrokProvider, type ImageAnalysisOptions, type ImageAnalysisResult, type ImageContent, type ImageContentPart, type ImageEditCapability, type ImageEditOptions, type ImageGenerationCapability, type ImageGenerationOptions, type ImageResult, LoggerPlugin, MaxContextOverflowPlugin, type Message, type MessageRole, type Middleware, type ModelCost, type ModelDefinition, type ModelLimit, type ModelModalities, OllamaProvider, OpenAIProvider, type OpenResponsesReasoningConfig, OpenRouterProvider, PIIFilterPlugin, type PluginContext, type ProvisionConfig, ProvisionPlugin, type RateLimitOptions, type RateLimitResult, RateLimiter, type RedisClient, ResponseCache, type RetryOptions, type SessionOptions, SessionStore, type SpeechGenerationCapability, type SpeechGenerationOptions, type SpeechResult, type StreamChunk, Tekimax, TekimaxClient, type TekimaxOptions, type TekimaxPlugin, TekimaxProvider, type TextContentPart, TokenBudget, type TokenBudgetOptions, type TokenBudgetResult, type TokenUsage, type Tool, type ToolCall, type ToolDefinition, type TranscriptionCapability, type TranscriptionOptions, type TranscriptionResult, type VideoAnalysisCapability, type VideoAnalysisOptions, type VideoAnalysisResult, type VideoContent, type VideoGenerationCapability, type VideoGenerationOptions, type VideoResult, type VisionCapability, createRetryProvider, estimateCost, fileToBase64, generateObject, generateText, getSupportedCostModels, loggingMiddleware, parseThinking, registerModelPrice, tool, withRetry, wrapProvider };