@relayplane/sdk
Version:
RelayPlane SDK with zero-config AI access, intelligent model selection, built-in examples, and contextual error handling. The easiest way to add AI to your app with automatic optimization and fallback.
461 lines • 15 kB
TypeScript
/**
* Core relay function for RelayPlane SDK
*
* This module implements the main relay() function that routes AI model calls
* either locally or through the hosted RelayPlane service.
*/
import { RelayRequest, RelayResponse, EnhancedRelayConfig, SupportedModel, ModelProvider } from '../types';
/**
* Configure the RelayPlane SDK globally with enhanced provider detection and feature analysis
*
* @param config Configuration options
* @returns Promise resolving to detected capabilities, configuration status, and available features
*/
export declare function configure(config: EnhancedRelayConfig): Promise<{
success: boolean;
mode: 'hosted' | 'local';
detectedProviders: Array<{
provider: ModelProvider;
models: SupportedModel[];
status: 'available' | 'invalid_key' | 'quota_exceeded' | 'unavailable';
}>;
recommendations: string[];
features?: {
autoOptimization: boolean;
smartRetry: boolean;
costTracking: boolean;
batchProcessing: boolean;
streamingSupport: boolean;
multiAgentChaining: boolean;
};
plan?: {
name: string;
tier: 'free' | 'startup' | 'growth' | 'enterprise';
modelAccess: SupportedModel[];
rateLimits: {
requestsPerMinute: number;
requestsPerMonth: number;
};
};
}>;
/**
* Get the current global configuration (for internal use by other modules)
*/
export declare function getConfig(): EnhancedRelayConfig;
/**
* Main relay function - routes AI model calls with automatic mode detection
*
* @param request The relay request containing target model and payload
* @param config Optional configuration overrides
* @returns Promise resolving to the relay response
*/
export declare function relay<T = any>(request: RelayRequest, config?: Partial<EnhancedRelayConfig>): Promise<RelayResponse<T>>;
/**
* Zero-config quick start method - the "zero-config win" entry point
*
* This method provides instant AI access with zero configuration required.
* It auto-detects available API keys, selects optimal models, and handles everything automatically.
*
* @param input The question or prompt to send to the AI
* @param options Optional configuration for advanced users
* @returns Promise resolving to the AI response with reasoning
*/
export declare function ask<T = any>(input: string, options?: {
/** Preferred cost strategy */
budget?: 'unlimited' | 'moderate' | 'minimal';
/** Preferred speed vs quality tradeoff */
priority?: 'speed' | 'balanced' | 'quality';
/** Task type hint for better model selection */
taskType?: 'general' | 'coding' | 'creative' | 'analysis' | 'translation';
/** Whether to enable streaming (default: true) */
stream?: boolean;
/** Configuration overrides for advanced users */
config?: Partial<EnhancedRelayConfig>;
}): Promise<{
response: RelayResponse<T>;
reasoning: {
selectedModel: SupportedModel;
rationale: string;
alternatives: Array<{
model: SupportedModel;
reason: string;
estimatedCost?: number;
estimatedLatency?: number;
}>;
detectedCapabilities: string[];
};
}>;
/**
* Built-in examples library - ready-to-use patterns for common tasks
*
* This library provides working functions for the most common AI use cases,
* making it incredibly easy for developers to get started.
*/
export declare const examples: {
/**
* Ready-to-use chatbot pattern
*
* @param message User message
* @param context Optional conversation context
* @param personality Optional personality/system prompt
*/
chatbot(message: string, options?: {
context?: Array<{
role: "user" | "assistant";
content: string;
}>;
personality?: string;
budget?: "minimal" | "moderate" | "unlimited";
}): Promise<{
response: RelayResponse<any>;
reasoning: {
selectedModel: SupportedModel;
rationale: string;
alternatives: Array<{
model: SupportedModel;
reason: string;
estimatedCost?: number;
estimatedLatency?: number;
}>;
detectedCapabilities: string[];
};
}>;
/**
* Intelligent summarization with length control
*
* @param text Text to summarize
* @param length Desired summary length
*/
summarize(text: string, options?: {
length?: "brief" | "moderate" | "detailed";
focus?: string;
budget?: "minimal" | "moderate" | "unlimited";
}): Promise<{
response: RelayResponse<any>;
reasoning: {
selectedModel: SupportedModel;
rationale: string;
alternatives: Array<{
model: SupportedModel;
reason: string;
estimatedCost?: number;
estimatedLatency?: number;
}>;
detectedCapabilities: string[];
};
}>;
/**
* Code review and analysis
*
* @param code Code to review
* @param language Programming language
* @param focus What to focus on in the review
*/
codeReview(code: string, options?: {
language?: string;
focus?: "bugs" | "performance" | "security" | "style" | "all";
includeFixSuggestions?: boolean;
}): Promise<{
response: RelayResponse<any>;
reasoning: {
selectedModel: SupportedModel;
rationale: string;
alternatives: Array<{
model: SupportedModel;
reason: string;
estimatedCost?: number;
estimatedLatency?: number;
}>;
detectedCapabilities: string[];
};
}>;
/**
* Smart translation with context awareness
*
* @param text Text to translate
* @param targetLanguage Target language
* @param sourceLanguage Source language (auto-detected if not provided)
*/
translate(text: string, targetLanguage: string, options?: {
sourceLanguage?: string;
tone?: "formal" | "casual" | "professional";
context?: string;
}): Promise<{
response: RelayResponse<any>;
reasoning: {
selectedModel: SupportedModel;
rationale: string;
alternatives: Array<{
model: SupportedModel;
reason: string;
estimatedCost?: number;
estimatedLatency?: number;
}>;
detectedCapabilities: string[];
};
}>;
/**
* Multi-step research workflow
*
* @param topic Research topic
* @param depth Research depth
*/
research(topic: string, options?: {
depth?: "overview" | "detailed" | "comprehensive";
focus?: string;
includeSourceSuggestions?: boolean;
}): Promise<{
response: RelayResponse<any>;
reasoning: {
selectedModel: SupportedModel;
rationale: string;
alternatives: Array<{
model: SupportedModel;
reason: string;
estimatedCost?: number;
estimatedLatency?: number;
}>;
detectedCapabilities: string[];
};
}>;
/**
* Creative writing assistant
*
* @param prompt Writing prompt or request
* @param type Type of creative writing
*/
creativeWriting(prompt: string, options?: {
type?: "story" | "poem" | "essay" | "blog" | "script" | "general";
tone?: "humorous" | "serious" | "inspiring" | "mysterious" | "casual";
length?: "short" | "medium" | "long";
audience?: string;
}): Promise<{
response: RelayResponse<any>;
reasoning: {
selectedModel: SupportedModel;
rationale: string;
alternatives: Array<{
model: SupportedModel;
reason: string;
estimatedCost?: number;
estimatedLatency?: number;
}>;
detectedCapabilities: string[];
};
}>;
/**
* Data analysis and insights
*
* @param data Data to analyze (can be text description or structured data)
* @param analysisType Type of analysis to perform
*/
dataAnalysis(data: string, options?: {
analysisType?: "descriptive" | "diagnostic" | "predictive" | "prescriptive" | "general";
format?: "summary" | "detailed" | "report";
includeVisualizationSuggestions?: boolean;
}): Promise<{
response: RelayResponse<any>;
reasoning: {
selectedModel: SupportedModel;
rationale: string;
alternatives: Array<{
model: SupportedModel;
reason: string;
estimatedCost?: number;
estimatedLatency?: number;
}>;
detectedCapabilities: string[];
};
}>;
/**
* Learning and explanation assistant
*
* @param topic Topic to explain or teach
* @param level Learning level
*/
explain(topic: string, options?: {
level?: "beginner" | "intermediate" | "advanced" | "expert";
style?: "simple" | "detailed" | "step-by-step" | "examples";
audience?: string;
}): Promise<{
response: RelayResponse<any>;
reasoning: {
selectedModel: SupportedModel;
rationale: string;
alternatives: Array<{
model: SupportedModel;
reason: string;
estimatedCost?: number;
estimatedLatency?: number;
}>;
detectedCapabilities: string[];
};
}>;
/**
* Content optimization and improvement
*
* @param content Content to optimize
* @param optimizationType Type of optimization
*/
optimizeContent(content: string, options?: {
optimizationType?: "clarity" | "engagement" | "seo" | "brevity" | "persuasion" | "all";
targetAudience?: string;
preserveLength?: boolean;
}): Promise<{
response: RelayResponse<any>;
reasoning: {
selectedModel: SupportedModel;
rationale: string;
alternatives: Array<{
model: SupportedModel;
reason: string;
estimatedCost?: number;
estimatedLatency?: number;
}>;
detectedCapabilities: string[];
};
}>;
};
/**
* Streaming optimization configuration
*/
interface StreamingOptimization {
/** Enable intelligent chunk sizing for optimal perceived performance */
intelligentChunking: boolean;
/** Target chunks per second for natural reading speed */
targetChunksPerSecond: number;
/** Minimum chunk size in characters */
minChunkSize: number;
/** Maximum chunk size in characters */
maxChunkSize: number;
/** Enable typing indicators and progress feedback */
enableTypingIndicators: boolean;
/** Buffer size for smooth delivery */
bufferSize: number;
/** Enable cost tracking during streaming */
trackCostInRealTime: boolean;
/** Custom render function for streaming UI */
customRenderer?: (chunk: string, metadata: StreamingMetadata) => void;
}
/**
* Streaming metadata for enhanced UX
*/
interface StreamingMetadata {
chunkIndex: number;
totalChunks?: number;
estimatedProgress: number;
tokensStreamed: number;
estimatedCost: number;
averageChunkLatency: number;
isTyping: boolean;
isComplete: boolean;
originalModel: string;
optimizedForSpeed: boolean;
}
/**
* Enhanced streaming wrapper for relay responses
*/
export declare function optimizeStreaming<T>(streamingResponse: AsyncIterable<string>, model: string, options?: Partial<StreamingOptimization>): AsyncGenerator<{
chunk: string;
metadata: StreamingMetadata;
}, void, unknown>;
/**
* React hook for optimized streaming (if using React)
*
* Note: This hook requires React to be installed. It will throw an error if React is not available.
* Import this function only if you're using React in your project.
*/
export declare function useOptimizedStreaming(): {
content: any;
metadata: any;
isStreaming: any;
startStreaming: any;
};
/**
* Cost tracking during streaming
*/
export declare class StreamingCostTracker {
private totalTokens;
private totalCost;
private model;
private costPerToken;
constructor(model: string, costPerToken?: number);
updateCost(tokens: number): {
totalTokens: number;
totalCost: number;
incrementalCost: number;
};
getFormattedCost(): string;
}
/**
* Get current SDK status, plan information, and quota details
*
* @param config Optional configuration overrides
* @returns Promise resolving to comprehensive status information
*/
export declare function status(config?: Partial<EnhancedRelayConfig>): Promise<{
sdk: {
version: string;
mode: 'hosted' | 'local';
configured: boolean;
};
providers: Array<{
provider: ModelProvider;
status: 'available' | 'invalid_key' | 'quota_exceeded' | 'unavailable';
models: SupportedModel[];
quotaRemaining?: number;
}>;
plan?: {
name: string;
tier: 'free' | 'startup' | 'growth' | 'enterprise';
features: string[];
limits: {
requestsPerMonth: number;
modelsAccess: string[];
supportLevel: string;
};
};
quota?: {
current: {
requests: number;
costUsd: number;
};
limits: {
requests: number;
costUsd: number;
};
remaining: {
requests: number;
costUsd: number;
};
resetDate: string;
};
recommendations: string[];
}>;
/**
* Save a provider API key to RelayPlane for secure storage and management
*
* This function allows you to securely store your AI provider API keys
* with RelayPlane for automatic key management and rotation.
*
* @param provider AI provider (openai, anthropic, google)
* @param apiKey The API key to store
* @param options Additional configuration options
* @returns Promise resolving to the save result
*/
export declare function saveProviderKey(provider: 'openai' | 'anthropic' | 'google', apiKey: string, options?: {
name?: string;
description?: string;
isPrimary?: boolean;
config?: Partial<EnhancedRelayConfig>;
}): Promise<{
success: boolean;
keyId?: string;
message: string;
validation?: {
isValid: boolean;
error?: string;
};
}>;
export {};
//# sourceMappingURL=relay.d.ts.map