# NeuroLink Documentation (Complete) > Enterprise AI Development Platform - Unified provider access, MCP integration, professional CLI Summary version: https://docs.neurolink.ink/llms.txt Total files: 4614 --- ## Table of Contents ### Introduction - NeuroLink - Page Not Found - NeuroLink Documentation Audit Report - Migration Guide: Breaking Changes - AI Analysis Tools - NeuroLink AI Enhancements - Complete Documentation - ️ AI Development Workflow Tools - Automated Publishing Guide (Semantic Release) - Workflow Engine - High-Level Design - Workflow Engine - Low-Level Design - Business Documentation Hub - Business Value Guide: Analytics & Evaluation Features - Domain Configuration Examples for NeuroLink CLI - CLI Guide - ️ CLI Reference Guide - NeuroLink Dependency Upgrade Report - Lighthouse Unified Integration Guide - npm Trusted Publishing Setup - Proxy logging through OpenTelemetry - NeuroLink Review Fixes Documentation - Step-by-Step Integration Tutorials - Use Cases - Visual Demonstrations ### Getting Started - Getting Started - AI Provider Guides - Quick Start - Installation - Environment Variables Configuration Guide - above.dev Provider Guide - AI21 Labs Provider Guide - ai& Provider Guide - ⚙️ Provider Configuration Guide - Aion Labs Provider Guide - Ambient Provider Guide - Anthropic Provider Guide - Redis Quick Start (5 Minutes) - API Route Provider Guide - Arcee Provider Guide - Atlas Cloud Provider Guide - Avian Provider Guide - AWS Bedrock Provider Guide - Azure OpenAI Provider Guide - Azure Speech Services - Baidu Qianfan Provider Guide - Baseten Provider Guide - Beatoven.ai Provider Guide (music) - Bee by HEOSSI Provider Guide - BytePlus ModelArk Provider Guide - Bytez Provider Guide - Cartesia TTS Provider Guide - Cerebras Provider Guide - Charm Hyper Provider Guide - Chutes Provider Guide - Cloudflare Clef Provider Guide - Cloudflare Workers AI Provider Guide - Cohere Provider Guide - Crusoe Provider Guide - D-ID Provider Guide (avatar) - Alibaba Cloud Model Studio (DashScope) Provider Guide - Deepgram Provider Guide - DeepInfra Provider Guide - DeepSeek Provider Guide - ElevenLabs Music Provider Guide - ElevenLabs Provider Guide - EmpirioLabs AI Provider Guide - Featherless AI Provider Guide - Fireworks AI Provider Guide - Fish Audio TTS Provider Guide - Flatkey Provider Guide - FriendliAI Provider Guide - GMI Cloud Provider Guide - Google AI Studio Provider Guide - Google Vertex AI Provider Guide - GradientAI Provider Guide - Groq Provider Guide - Hetzner Inference Provider Guide - HeyGen Provider Guide (avatar) - Hugging Face Provider Guide - Ideogram Provider Guide (image-gen) - Inception Labs Provider Guide - Inceptron Provider Guide - Inco Provider Guide - Inference.net Provider Guide - io.net Intelligence Provider Guide - Jina AI Provider Guide - Kling AI Provider Guide (video) - KosCompute Provider Guide - Laya Provider Guide - Lemonfox AI Provider Guide - Lilac Provider Guide - LiteLLM Provider Guide - llama.cpp Provider Guide - LLM Tech Provider Guide - LM Studio Provider Guide - Google Lyria Provider Guide (music) - Mancer Provider Guide - Meta Model API Provider Guide - MiniMax Provider Guide - Mistral AI Provider Guide - Moark Provider Guide - ModelScope Provider Guide - Moonshot AI (Kimi) Provider Guide - Morph Provider Guide - MuseTalk Provider Guide (avatar via Replicate) - Nebius Token Factory Provider Guide - Neuralwatt Provider Guide - Novita AI Provider Guide - NVIDIA NIM Provider Guide - Ollama Provider Guide - OpenAI-Compatible Providers Guide - OpenAI Decisions Provider Guide - OpenAI TTS Provider Guide - OpenAI Provider Guide - OpenRouter Provider Guide - OVHcloud AI Endpoints Provider Guide - Parasail Provider Guide - Pareto Inference Provider Guide - Perplexity Decisions Provider Guide - Perplexity Provider Guide - Poolside Provider Guide - Prime Intellect Provider Guide - Recraft Provider Guide (image-gen) - Reka AI Provider Guide - Replicate Provider Guide - Runway Provider Guide (video) - Amazon SageMaker Provider Guide - Sakana AI Provider Guide - SambaNova Provider Guide - Sarvam AI Provider Guide - ScaleDown Provider Guide - Scaleway Provider Guide - SiliconFlow Provider Guide - 60db TTS Provider Guide - Stability AI Provider Guide - STACKIT Provider Guide - StepFun Provider Guide - Subconscious Provider Guide - SubQ Provider Guide - Synthetic Provider Guide - Telnyx Provider Guide - Thinking Machines Provider Guide - Tinfoil Provider Guide - Together AI Provider Guide - TypeSafe (Jev) Provider Guide - Umans AI Provider Guide - Upstage Provider Guide - Venice AI Provider Guide - Vispark Provider Guide - Voyage AI Provider Guide - Vultr Inference Provider Guide - Wafer Provider Guide - W&B Inference Provider Guide - Whistle (Built-in Local STT) - xAI Grok Provider Guide - XOR Provider Guide - Z.AI Provider Guide ### SDK Reference - SDK Reference - API Reference - Advanced SDK Features - SDK Custom Tools Guide - SDK Custom Tools - ️ Framework Integration Guide - NestJS Integration Guide ### CLI - CLI Command Reference - CLI Guide - Advanced CLI Usage - CLI Examples ### Features - Feature Guides - Attachment Security - Audio Input & Transcription Guide - Authentication Providers - Client SDK - Auto Evaluation Engine - AutoResearch - Autonomous AI Experiment Engine - The model catalogue - Model routing with a decision model - Classifier Router - Claude Proxy Architecture - Claude Proxy Configuration Reference - Claude Proxy Observability - Claude Proxy Troubleshooting - Claude Proxy - Claude Subscription Testing Guide - Claude Subscription Support - CLI Loop Sessions - Codex (ChatGPT) Support for NeuroLink Proxy - Per-request context budget - Context Compaction - Redis Conversation History Export - Credential Validation - CSV File Support - The `decide` inference type - Embeddings - Enterprise Human-in-the-Loop System - File Processors Guide - Guardrails AI Integration with Middleware - Guardrails Implementation Guide - Guardrails Middleware - Human-in-the-Loop (HITL) Workflows - Image Generation Streaming Guide - Interactive CLI - Your AI Development Environment - LiveKit Voice Agent — Real-Time Voice over WebRTC - MCP Enhancement Architecture Diagrams - MCP Enhancements - MCP Tools Ecosystem - Built-in Tools + Any MCP Server - Memory Guide - Multimodal Chat Experiences - Multimodal Capabilities Guide - Observability Guide - Office Documents Support - OpenCode Support for NeuroLink Proxy - PDF File Support - Per-Request Credentials - PPT Generation - AI-Powered Presentations - Provider Fallback & Model Chains - Provider Orchestration Brain - `GET /accounts` — one row per account - Onboarding a New AI Coding CLI onto the NeuroLink Proxy - Proxy Peer Sharing - Per-query RAG retrieval planning - RAG Document Processing Guide - Real-time Voice Services - Regional Streaming Controls - Relevance-driven compaction - Skills Guide - Speech-to-Speech Agents: Architecture and Gemini Live Integration Plan - Streaming Guide - Structured Output with Zod Schemas - TaskManager - Scheduled & Self-Running Tasks - Extended Thinking Configuration - Tool / MCP routing by decision model - The transcribe inference type - Text-to-Speech (TTS) Integration Guide - Turn Time Budget - Video Analysis - Video Director Mode – Multi-Clip Generation & Merging - Video Generation with Veo 3.1 - Real-Time Voice Agent - Streaming Voice Loop Design - Workflow Engine Guide ### Examples - Examples & Tutorials - Advanced Examples - Basic Usage Examples - Business Applications - Tool Blocking Feature Example - Use Cases ### Cookbook - NeuroLink Cookbook - AutoResearch Quickstart - Basic Streaming - Batch Processing - Context Window Management - Conversation Summarization - Cost Optimization - Embeddings Basics - Error Recovery Patterns - Multi-Provider Fallback - Multimodal Images - Provider Switching - Rate Limit Handling - Streaming with Retry Logic - Structured Output with JSON Schema - Tool Chaining with MCP ### MCP Integration - MCP Foundation (Model Context Protocol) - MCP Configuration Locations Across AI Development Tools - MCP Concurrency Control Guide - NeuroLink Docs MCP Server - HTTP Transport for MCP Servers - MCP (Model Context Protocol) Integration Guide - NeuroLink MCP Latency Optimization Implementation Guide - MCP Foundation Testing Guide ### Advanced - Advanced Features - Analytics & Evaluation - Authentication Architecture - Built-in Middleware Reference - CLI Guide - Enterprise Features - NeuroLink Factory Patterns - Complete Implementation Guide - Factory Pattern Migration Guide - Memory Integration with Hippocampus - Middleware System Architecture - Streaming Responses - Updated Provider Test Results ### Reference - Reference - Analytics Reference - Error Code Reference - Provider Behavior Guide - Provider Capabilities Audit - AI Provider Comparison Guide - Provider Feature Compatibility Reference - Provider Selection Guide - NeuroLink Troubleshooting Guide - Frequently Asked Questions - Srvr Cofiguratio Rfrc [] ### Tutorials - NeuroLink Tutorials - Build a Complete Chat Application - Build a RAG System - Video Tutorials ### Development - Development - ClientConfigurator Registry Implementation Plan - System Architecture - Changelog Automation & Formatting - CLI Factory Integration Impact Assessment - Factory Pattern Architecture - Factory Pattern Migration Guide - Knowledge Grounding: Initialization and Turn Lifecycle - Design Doc: Large Context Handling via Map-Reduce Summarization - Automated Link Checking - Logging Guidelines - Package Version Overrides Documentation - Provider-Agnostic Testing Framework - January 2025 Snapshot - Proxy context protection and audit closure - Proxy incident reliability verification - Proxy package updates and token budgets - COMPREHENSIVE TESTING & VERIFICATION PLAN - NeuroLink Testing Guide — Providers Validated in CI - Documentation Versioning ### Guides - Enterprise Guides - NeuroLink Guides - Migration Guides - Server Adapters - Hono Adapter - Express Adapter - Fastify Adapter - Koa Adapter - Middleware Reference - Streaming Guide - WebSocket Support - Error Handling - Domain-Specific AI Usage Guide - Audit Trails & Compliance Logging - Production Code Patterns - Express.js Integration Guide - MCP Server Catalog - Migrating from LangChain to NeuroLink - Server Adapters API Reference - Security Best Practices - Deployment Guide - Dynamic Model Configuration System - Compliance & Security Guide - Real-World Use Cases - Fastify Integration Guide - Migrating from Vercel AI SDK to NeuroLink - Cost Optimization Guide - Next.js Integration Guide - GitHub Action Guide - SvelteKit Integration Guide - Load Balancing Strategies - Migration Guide - Monitoring & Observability Guide - Provider Selection Wizard - Multi-Provider Failover & High Availability - Complete Redis Configuration Guide - Multi-Region Deployment Guide - Redis Migration Patterns - Session Management & Persistence Guide - Vector Stores Guide ### Memory - Conversation Memory - Automatic Conversation Summarization ### Observability - Health Monitoring & Auto-Recovery Guide - Provider Status Monitoring and Health Management - Enterprise Telemetry Guide ### Deployment - ⚙️ NeuroLink Configuration Guide - ️ Enterprise Configuration Management Guide - Enterprise & Proxy Setup Guide - Performance Optimization Guide for NeuroLink CLI with Domain Features - Performance Optimization Guide ### Demos - Visual Demos - Interactive Demo - Screenshots Gallery - Video Demonstrations ### About - The Nervous System Model - Pipe Architecture - NeuroLink Vision & Roadmap - Why the NeuroLink Core Stays Thin ### Community - Changelog - Contributor Covenant Code of Conduct - Contributing to NeuroLink ### Workflows - AI-Driven Tool Orchestration Guide - Custom Middleware Development Guide - Error Handling - Middleware System - Advanced AI Model Orchestration ### Visual Content - AI Development Workflow Tools - Visual Proof Documentation - MCP CLI Screenshots - Phase 1.2 Screenshot Summary - Phase 1.2 AI Development Workflow Tools - Visual Content Achievement Report - Phase 1.2 AI Development Workflow Tools - Visual Content Plan ### Agents - Artifact Banking (`bankArtifact` / `readArtifact`) - Async Delegation (`delegate_task` / `collect_results`) - Background Commands (`run_command_bg` / `command_status` / `command_output` / `command_kill`) - Multi-Agent Networks CLI Coverage Report - Multi-Agent Networks Configuration Guide - Task Checklist (`tasks_create` / `tasks_update` / `tasks_list`) - Multi-Agent Networks Testing Guide - Multi-Agent Networks Verification Checklist ### Api - AnthropicSetup - Type Alias: AnthropicSetupArgv - AzureSetup - Type Alias: AzureSetupArgv - BedrockSetup - Type Alias: BedrockSetupArgv - BedrockTypes - Type Alias: BedrockClient - GCPSetup - Type Alias: AuthMethodStatus - GoogleAISetup - Type Alias: GoogleAISetupArgv - HuggingFaceSetup - Type Alias: HuggingFaceSetupArgs - MistralSetup - Type Alias: MistralSetupArgs - MistralTypes - Type Alias: MistralClient - OpenAISetup - Type Alias: OpenAISetupArgv - TelemetryTypes - Type Alias: Counter - NeuroLink API Reference - Class: AIProviderFactory - Enumeration: AIProviderName - Function: assembleContext() - Type Alias: AIModelProviderConfig - Variable: AGENT_ATTRIBUTES - Type Alias: AnthropicSetupConfig - Type Alias: AzureSetupConfig - Type Alias: BedrockSetupOptions - Type Alias: InvokeModelCommand - Type Alias: GCPSetupArgv - Type Alias: GoogleAISetupConfig - Type Alias: OpenAISetupConfig - Type Alias: Histogram - Class: AbortError - Enumeration: BedrockModels - Function: assembleKnowledgeContext() - Type Alias: AIProvider - Variable: AGGRESSIVE_FALLBACK_WORKFLOW - Type Alias: AnthropicSetupOptions - Type Alias: AzureSetupOptions - Type Alias: ConfigData - Type Alias: GCPSetupOptions - Type Alias: GoogleAISetupOptions - Type Alias: OpenAISetupOptions - Type Alias: Meter - Class: Agent - Enumeration: FileErrorCode - Function: assertMcpTransportUrlAllowed() - Type Alias: AISDKModel - Variable: AUDIO_FORMAT_DETAILS - Type Alias: ConfigStatus - Type Alias: Span - Class: AgentCoordinator - Enumeration: OpenAIModels - Function: batchConvertToMCP() - Type Alias: AISDKUsage - Variable: AUTORESEARCH_DEFAULTS - Type Alias: Tracer - Class: AgentExposureManager - Enumeration: SpanStatus - Function: batchConvertToNeuroLink() - Type Alias: APIValidationResult - Variable: AVATAR_ERROR_CODES - Class: AgentNetwork - Enumeration: SpanType - Function: batchRerank() - Type Alias: AWSCredentialConfig - Variable: AgentExecuteRequestSchema - Class: AlreadyRunningError - Enumeration: VertexModels - Function: buildDocument() - Type Alias: AbortSignalMiddlewareOptions - Variable: AuthErrorCodes - Class: AlwaysSampler - Function: buildIndexSnapshot() - Type Alias: AccountAdmissionLease - Variable: AuthErrorFactory - Class: AnswerRelevancyScorer - Function: buildModelCatalog() - Type Alias: AccountAdmissionState - Variable: AuthMiddlewareError - Class: AuthContextHolder - Function: buildRegistryIndex() - Type Alias: AccountAdmissionWaiter - Variable: AuthMiddlewareErrorCodes - Class: AuthProviderFactory - Function: buildRoutingQueryFromHistory() - Type Alias: AccountAllowlist - ~~Variable: AuthProviderError~~ - Class: AuthProviderRegistry - Function: buildSpeakerTurns() - Type Alias: AccountCooldownPlan - Variable: BALANCED_ADAPTIVE_WORKFLOW - Class: AuthenticationError - Function: buildToolRoutingCatalog() - Type Alias: AccountCoolingReason - Variable: CLASSIFIER_CONTEXT_SCOPES - Class: AuthorizationError - Function: calculateCost() - Type Alias: AccountPoolConfig - Variable: CLASSIFIER_DIFFICULTIES - Class: AvatarError - Function: calculateExpiresAt() - Type Alias: AccountQuota - Variable: CODE_GENERATION_PIPELINE - Class: AvatarProcessor - Function: calculateModelMetrics() - Type Alias: AccountQuotaSource - Variable: COMPREHENSIVE_PIPELINE - Class: AzureSTT - Function: canDeliverVideoNatively() - Type Alias: AccountQuotaWindow - Variable: CONSENSUS_3_FAST_WORKFLOW - Class: AzureTTS - Function: chunkText() - Type Alias: AccountSelectionContext - Variable: CONSENSUS_3_WORKFLOW - Abstract Class: BaseAuthProvider - Function: classifyHeuristic() - Type Alias: AccountStats - Variable: CUSTOMER_SUPPORT_PIPELINE - Class: BaseError - Function: classifyJev() - Type Alias: AccountUsageFetchResult - Variable: ClientErrorCode - Abstract Class: BaseFactory\ - Function: classifyMcpTransportAddress() - Type Alias: ActionAWSConfig - Variable: DECISION_PROVIDERS - Abstract Class: BaseLLMScorer - Function: classifyProviderError() - Type Alias: ActionCommentResult - Variable: DEFAULT_ALIAS_BOOST - Abstract Class: BaseRealtimeHandler - Function: clearAnalyticsMetrics() - Type Alias: ActionEvaluation - Variable: DEFAULT_BATCH_CONFIG - Abstract Class: BaseRegistry\ - Function: clearGlobalMiddleware() - Type Alias: ActionExecutionResult - Variable: DEFAULT_CACHE_CONFIG - Abstract Class: BaseRuleScorer - Function: clearWorkflowRegistry() - Type Alias: ActionGoogleCloudConfig - Variable: DEFAULT_CANDIDATE_LIMIT - Abstract Class: BaseScorer - Function: collectStream() - Type Alias: ActionInputValidation - Variable: DEFAULT_COMPACTION_THRESHOLD - Abstract Class: BaseServerAdapter - Function: compareWorkflows() - Type Alias: ActionInputs - Variable: DEFAULT_CONFIG - Class: BatchStrategy - Function: composeMiddleware() - Type Alias: ActionMultimodalInputs - Variable: DEFAULT_DECISION_HOOK_TIMEOUT_MS - Class: BeatovenMusic - Function: composeScorers() - Type Alias: ActionOutput - Variable: DEFAULT_EXACT_BOOST - Class: BiasDetectionScorer - Function: computeToolSignature() - Type Alias: ActionProviderKeys - Variable: DEFAULT_FIELD_WEIGHTS - Class: CSVLoader - Function: conditionalMiddleware() - Type Alias: ActionThinkingConfig - Variable: DEFAULT_HTTP_RETRY_CONFIG - Class: CartesiaTTS - Function: configureGlobalMiddleware() - Type Alias: ActionTokenUsage - Variable: DEFAULT_IMAGE_GEN_CONFIG - Class: CharacterChunker - Function: contextScopeToThreshold() - Type Alias: AdaptiveSemaphoreConfig - Variable: DEFAULT_IMAGE_MAX_SIZE_MB - Class: ChromaVectorStore - Function: contextToErrorContext() - Type Alias: AdaptiveSemaphoreMetrics - Variable: DEFAULT_IMAGE_TIMEOUT_MS - Class: ChunkerRegistry - Function: correctTranscript() - Type Alias: AdditionalMemoryUser - Variable: DEFAULT_INFERENCE_KINDS - Class: CircuitBreakerManager - Function: cosineSimilarity() - Type Alias: AffinityRule - Variable: DEFAULT_LLM_SCORER_CONFIG - Class: CircuitBreakerOpenError - Function: createAIProvider() - Type Alias: AgentCapability - Variable: DEFAULT_MAX_CONTEXT_TOKENS - Class: ClassifierRouter - Function: createAIProviderWithFallback() - Type Alias: AgentDefinition - Variable: DEFAULT_MODEL_ALIASES - Class: ClientAuthenticationError - Function: createAdaptiveWorkflow() - Type Alias: AgentExecuteRequest - Variable: DEFAULT_PROVIDER_CONFIGS - Class: ClientAuthorizationError - Function: createAgentRoutes() - Type Alias: AgentExecuteResponse - Variable: DEFAULT_RATE_LIMIT_CONFIG - Class: ClientConfigurationError - Function: createAgentWebSocketHandler() - Type Alias: AgentExecutionContext - Variable: DEFAULT_REALTIME_CONFIG - Class: ClientConnectionError - Function: createAllRoutes() - Type Alias: AgentExecutionOptions - Variable: DEFAULT_RECENT_TURNS - Class: ClientNetworkError - Function: createAnalyticsMiddleware() - Type Alias: AgentInput - Variable: DEFAULT_RELATION_LIMIT - Class: ClientNeuroLinkError - Function: createAndInitializePipeline() - Type Alias: AgentInstance - Variable: DEFAULT_RESULT_LIMIT - Class: ClientProviderError - Function: createAnnotatedTool() - Type Alias: AgentLegOptions - Variable: DEFAULT_RETRY_CONFIG - Class: ClientRateLimitError - Function: createAnswerRelevancyScorer() - Type Alias: AgentMechanicalDigest - Variable: DEFAULT_ROUTER_CONFIG - Class: ClientTimeoutError - Function: createApiKeyAuthInterceptor() - Type Alias: AgentMessage - Variable: DEFAULT_ROUTER_PROMPT_PREFIX - Class: ClientValidationError - Function: createApiKeyMiddleware() - Type Alias: AgentNetworkConfig - Variable: DEFAULT_RULE_SCORER_CONFIG - Class: CohereRelevanceScorer - Function: createArtifactStore() - Type Alias: AgentPrimitive - Variable: DEFAULT_SAMPLING_CONFIG - Class: ConfigManager - Function: createAsyncStream() - Type Alias: AgentResult - Variable: DEFAULT_SCORE_SCALE - Class: ConfigurationError - Function: createAuthMiddleware() - Type Alias: AgentRoutingDecision - Variable: DEFAULT_STT_OPTIONS - Class: ContentFilterError - Function: createAuthProvider() - Type Alias: AgentRunBudget - Variable: DEFAULT_TEXT_MAX_SIZE_MB - Class: ContextBuilder - Function: createAuthProviderMiddleware() - Type Alias: AgentRunEvent - Variable: DEFAULT_TEXT_TIMEOUT_MS - Class: ContextConverter - Function: createAuthValidatorFromProvider() - Type Alias: AgentRunEventType - Variable: DEFAULT_TIMEOUT_MS - Class: ContextFactory - Function: createAuthWithRetryMiddleware() - Type Alias: AgentRunLegInfo - Variable: EVAL_DEFAULT_SCORE_SCALE - Class: ContextLengthError - Function: createAuthenticatedContext() - Type Alias: AgentRunOptions - Variable: ErrorCategory - Class: ContextPrecisionScorer - Function: createAuthenticatedRateLimitMiddleware() - Type Alias: AgentRunOutcome - Variable: ErrorRecoveryStrategies - Class: ContextRelevancyScorer - Function: createBatchEvaluationError() - Type Alias: AgentRunOverrides - Variable: ErrorSeverity - Class: ConversationMemoryError - Function: createBatchStrategy() - Type Alias: AgentRunStatus - Variable: FAST_FALLBACK_WORKFLOW - Class: ConversationSessionErasedError - Function: createBearerAuthInterceptor() - Type Alias: AgentStatus - Variable: FormatScorerPresets - Class: ConversationWriterEpochError - Function: createBearerTokenMiddleware() - Type Alias: AgentStreamChunk - Variable: GENAI_ATTRIBUTES - Class: CrossEncoderReranker - Function: createBestAIProvider() - Type Alias: AgentStreamChunkType - Variable: HOST_DECISION_NAMESPACE - Class: DIDAvatar - Function: createBiasDetectionScorer() - Type Alias: AgentTextChunk - Variable: LengthScorerPresets - Class: DeepgramSTT - Function: createCacheInterceptor() - Type Alias: AgentToolCallChunk - Variable: MAX_DECISION_HOOK_TIMEOUT_MS - Class: ElevenLabsMusic - Function: createCacheInvalidator() - Type Alias: AgentToolRegistrationOptions - Variable: MAX_SLIDES - Class: ElevenLabsSTT - Function: createCacheMiddleware() - Type Alias: AgentToolResultChunk - Variable: MINIMAL_PIPELINE - Class: ElevenLabsTTS - Function: createChunker() - Type Alias: AgentWasteThresholds - Variable: MIN_SLIDES - Class: ElicitationManager - Function: createClient() - Type Alias: AgenticLoopAdapter\ - Variable: MULTI_JUDGE_3_WORKFLOW - Class: ElicitationProtocolAdapter - Function: createCompressionMiddleware() - Type Alias: AgenticLoopChunk - Variable: MULTI_JUDGE_5_WORKFLOW - Class: EnhancedToolDiscovery - Function: createConditionalScorer() - Type Alias: AgenticLoopOptions - Variable: MUSIC_ERROR_CODES - Class: EvaluationAggregator - Function: createConfigurationError() - Type Alias: AgenticLoopReclaimResult\ - ~~Variable: ModelAliases~~ - Class: EvaluationPipeline - Function: createConfirmationRequest() - Type Alias: AgenticLoopReportMetadata - Variable: ModelConfigSchema - Class: Evaluator - Function: createConsensus3WithPrompt() - Type Alias: AgenticLoopReportStatus - Variable: ModelRegistrySchema - Class: EvaluatorFactory - Function: createConsoleLoggerHook() - Type Alias: AgenticLoopReportType - Variable: NEUROLINK_RESOURCE_ID_KEY - Class: ExporterRegistry - Function: createContentSimilarityScorer() - Type Alias: AgenticLoopResult\ - Variable: NEUROLINK_THREAD_ID_KEY - Class: ExporterSpanProcessor - Function: createContextPrecisionScorer() - Type Alias: AgenticLoopStepRequest - Variable: PROCESSOR_PRIORITIES - Class: ExpressServerAdapter - Function: createContextRelevancyScorer() - Type Alias: AgenticLoopStepResult\ - Variable: PROJECT_MCP_CONFIG_FILENAME - Class: ExternalServerManager - Function: createContextWindow() - Type Alias: AgenticLoopToolCall - Variable: PROVIDER_ALIAS_INDEX - Class: FaithfulnessScorer - Function: createDataStreamResponse() - Type Alias: AgenticLoopToolCallResult - Variable: PROVIDER_DESCRIPTORS - Class: FastifyServerAdapter - Function: createDataStreamWriter() - Type Alias: AgenticLoopToolFailureBreaker - Variable: PROVIDER_DESCRIPTORS_BY_NAME - Class: FileSystemSkillStore - Function: createDefaultRequestRouter() - Type Alias: AgenticLoopUsage - Variable: Pipelines - Class: FileTokenStorage - Function: createDefaultTripwireEvaluator() - Type Alias: AggregatedMetrics - Variable: QUALITY_MAX_WORKFLOW - Class: FishAudioTTS - Function: createDynamicAuthInterceptor() - Type Alias: AggregatedScores - Variable: QUALITY_PIPELINE - Class: GeminiLive - Function: createElicitationCancel() - Type Alias: AggregatedUsage - Variable: RAG_PIPELINE - Class: GoogleSTT - Function: createElicitationContext() - Type Alias: AggregationConfig - Variable: REALTIME_ERROR_CODES - Class: GoogleTTSHandler - Function: createElicitationRequest() - Type Alias: AggregationMethod - Variable: Reports - Class: GraphRAG - Function: createElicitationResponse() - Type Alias: AggregationRequest - Variable: SAFETY_PIPELINE - Class: HITLManager - Function: createErrorFactory() - Type Alias: AggregationResult - Variable: SIZE_TIER_THRESHOLDS - Class: HTMLChunker - Function: createErrorFromNative() - Type Alias: AiAnalysisProvider - Variable: SLIDE_DIMENSIONS - Class: HTMLLoader - Function: createErrorFromResponse() - Type Alias: AiMetricInstruments - Variable: SPEED_FIRST_WORKFLOW - Class: HTTPRateLimiter - Function: createErrorHandlerInterceptor() - Type Alias: AiSdkStreamChunk - Variable: STT_ERROR_CODES - Class: HallucinationScorer - Function: createErrorHandlingMiddleware() - Type Alias: AiSdkToolCall - Variable: STT_PROVIDER_DESCRIPTORS - Class: HandlerError - Function: createErrorResponse() - Type Alias: AlertSeverity - Variable: SUMMARIZATION_PIPELINE - Class: HeyGenAvatar - Function: createEvaluationFailedError() - Type Alias: AlertSummary - Variable: SUPPORTED_IMAGE_MIME_TYPES - Class: HonoServerAdapter - Function: createExporterSpanProcessor() - Type Alias: AllToolsMap - Variable: SamplingStrategies - Class: ImageGenService - Function: createExpressAuthMiddleware() - Type Alias: AllowedCommand - Variable: Scorers - Class: InMemoryBM25Index - Function: createFaithfulnessScorer() - Type Alias: AnalyticsConfig - Variable: ServerAdapterErrorCode - Class: InMemoryCacheStore - Function: createFieldValidator() - Type Alias: AnalyticsData - Variable: ServerNameParamSchema - Class: InMemoryRateLimitStore - Function: createFormRequest() - Type Alias: AnalyticsErrorInfo - Variable: SessionIdParamSchema - Class: InMemorySessionStorage - Function: createFormatScorer() - Type Alias: AnalyticsQualityScore - Variable: TASK_DEFAULTS - Class: InMemorySkillStore - Function: createFunctionScorer() - Type Alias: AnalyticsStorage - Variable: TERMINAL_AGENT_PROMPT_V1 - Class: InMemoryTokenStorage - Function: createHallucinationScorer() - Type Alias: AnalyzeCsvToolArgs - Variable: TERMINAL_AGENT_PROMPT_V2 - Class: InMemoryVectorStore - Function: createHealthRoutes() - Type Alias: AnalyzeUsageParams - Variable: TERMINAL_AGENT_PROMPT_VERSION - Class: InvalidAuthenticationError - Function: createHybridSearch() - Type Alias: AnnotatedToolTarget - Variable: TOOL_COMPATIBILITY - Class: InvalidModelError - Function: createInvertedScorer() - Type Alias: AnthropicAttemptLogger - Variable: TOOL_EVENTS_WRAPPED - Class: JSONLoader - Function: createJsonResource() - Type Alias: AnthropicAuthConfig - Variable: TRUSTED_MCP_CONFIGS_FILENAME - Class: JWTTokenManager - Function: createKeywordCoverageScorer() - Type Alias: AnthropicAuthConfigResult - Variable: TRUST_MCP_CONFIG_ENV - Class: KlingVideoHandler - Function: createKeywordScorer() - Type Alias: AnthropicAuthMethod - Variable: TRUST_MCP_CONFIG_FLAG - Class: KnowledgeGroundingEngine - Function: createLangfuseAdapter() - Type Alias: AnthropicAuthRetryResult - Variable: TTS_ERROR_CODES - Class: KnowledgeLexicalIndex - Function: createLengthScorer() - Type Alias: AnthropicBetaFeatures - Variable: TYPESAFE_MAX_REQUEST_TOKENS - Class: KoaServerAdapter - Function: createLifecycleMiddleware() - Type Alias: AnthropicBetaHeader - Variable: TYPESAFE_MAX_STATE_TOKENS - Class: LLMMetadataExtractor - Function: createLocalUsageReader() - Type Alias: AnthropicEntitlementFailure - Variable: ToolArgumentsSchema - Class: LaTeXChunker - Function: createLoggingInterceptor() - Type Alias: AnthropicGuardBlock - Variable: ToolExecuteRequestSchema - Class: LangfuseExporter - Function: createLoggingMiddleware() - Type Alias: AnthropicGuardMessage - Variable: ToolNameParamSchema - Class: LocalTempArtifactStore - Function: createMCPRoutes() - Type Alias: AnthropicInvalidRequestFailure - Variable: ToolSearchQuerySchema - Class: LyriaMusic - Function: createMCPServer() - Type Alias: AnthropicLoopAdapterConfig\ - Variable: VALID_AUDIO_FORMATS - Class: MCPCircuitBreaker - Function: createMaxRetriesExceededError() - Type Alias: AnthropicLoopState - Variable: VALID_AVATAR_FORMATS - Class: MCPClientFactory - Function: createMemoryRoutes() - Type Alias: AnthropicModelMetadata - Variable: VALID_MUSIC_FORMATS - Class: MCPRegistryClient - Function: createMetricsCollector() - Type Alias: AnthropicNonOkResult - Variable: VALID_TTS_QUALITIES - Abstract Class: MCPServerBase - Function: createMetricsCollectorHook() - Type Alias: AnthropicOAuthConfig - Variable: VERSION - Class: MCPToolRegistry - Function: createMultiAuthMiddleware() - Type Alias: AnthropicPendingToolUse - Variable: VIDEO_ERROR_CODES - Class: MDocument - Function: createMultiJudgeWorkflow() - Type Alias: AnthropicProviderConfig - Variable: VIDEO_PROVIDER_CONFIGS - Class: MarkdownChunker - Function: createNDJSONHeaders() - Type Alias: AnthropicRateLimitInfo - Variable: VOICE_ERROR_CODES - Class: MarkdownLoader - Function: createNeuroLinkModel() - Type Alias: AnthropicResponseMetadata - Variable: WORKFLOW_ENGINE_VERSION - Class: MemoryRateLimitStorage - Function: createNeuroLinkProvider() - Type Alias: AnthropicSamplingParams - Variable: commonTripwires - Class: MemorySessionStorage - Function: createOAuthProviderFromConfig() - Type Alias: AnthropicScopedExhaustion - Variable: confirmationMiddleware - Class: MessageBus - Function: createOpenAPIGenerator() - Type Alias: AnthropicStreamPreflightResult - Variable: dynamicModelProvider - Class: MetricsAggregator - Function: createParseError() - Type Alias: AnthropicSuccessResult - Variable: evaluationErrors - Class: MetricsCollector - Function: createPipeline() - Type Alias: AnthropicTraceBlock - Variable: globalAgentExposureManager - Class: MiddlewareFactory - Function: createPrompt() - Type Alias: AnthropicTraceMessage - Variable: globalAuthContext - Class: MissingDependencyError - Function: createPromptAlignmentScorer() - Type Alias: AnthropicUpstreamBody - Variable: globalCircuitBreakerManager - Class: ModelAccessDeniedError - Function: createProtectedMiddleware() - Type Alias: AnthropicUpstreamBodyBuilder - Variable: globalElicitationManager - Class: ModelAccessError - Function: createProviderError() - Type Alias: AnthropicUpstreamFetchResult - Variable: globalElicitationProtocol - Class: ModelPool - Function: createRAGPipeline() - Type Alias: AnthropicUsageLimit - Variable: globalMCPRegistryClient - Class: MultiServerManager - Function: createRBACMiddleware() - Type Alias: AnthropicUsageResponse - Variable: globalMetricsCollector - Class: MusicError - Function: createRateLimitByUserMiddleware() - Type Alias: AnthropicUsageWindow - Variable: globalMultiServerManager - Class: MusicProcessor - Function: createRateLimitInterceptor() - Type Alias: AnthropicVertexSettings - Variable: globalRateLimiterManager - Class: NetworkError - Function: createRateLimitMiddleware() - Type Alias: AnyFunction\ - Variable: globalToolIntegrationManager - Class: NetworkOrchestrator - Function: createRateLimitStorage() - Type Alias: ApiKeyAuthOptions - Variable: logger - Class: NetworkTopology - Function: createRegexScorer() - Type Alias: ApiResponse\ - Variable: loggingMiddleware - Class: NeuroLink - Function: createReportGenerator() - Type Alias: ArchiveDecompressionResult - Variable: mcpLogger - Class: NeuroLinkAIProvider - Function: createRequestBatcher() - Type Alias: ArchiveEntry - Variable: neuroLinkAIInstance - Class: NeuroLinkApiError - Function: createRequestContext() - Type Alias: ArchiveEntryReadResult - Variable: observabilityHooks - Class: NeuroLinkClient - Function: createRequestIdMiddleware() - Type Alias: ArchiveFormat - Variable: ragCircuitBreakerManager - Class: NeuroLinkFeatureError - Function: createRequestTransformInterceptor() - Type Alias: ArithmeticEvaluation - Variable: validationMiddleware - Class: NeuroLinkLanguageModel - Function: createRequestValidationMiddleware() - Type Alias: ArithmeticToken - Class: NeuroLinkOAuthProvider - Function: createResponseTransformInterceptor() - Type Alias: ArizeExporterConfig - Class: NeverSampler - Function: createRetryInterceptor() - Type Alias: ArtifactMeta - Class: NoOpExporter - Function: createRetryMiddleware() - Type Alias: ArtifactPageRequest - Class: NotFoundError - Function: createRoleMiddleware() - Type Alias: ArtifactRef - Class: NotRunningError - Function: createSSEHeaders() - Type Alias: ArtifactSearchMatch - Class: OAuth2AuthError - Function: createSamplingStrategy() - Type Alias: ArtifactSearchResult - Class: OAuth2Error - Function: createScorerMetadata() - Type Alias: ArtifactStorageConfig - Class: OAuth2TokenManager - Function: createSecurityHeadersMiddleware() - Type Alias: ArtifactStorageType - Class: OAuthCallbackServerError - Function: createSelectRequest() - Type Alias: ArtifactStore - Class: OAuthConfigurationError - Function: createServer() - Type Alias: ArtifactWindow - Class: OAuthError - Function: createSessionMiddleware() - Type Alias: AspectRatio - Class: OAuthTokenExchangeError - Function: createSessionStorage() - Type Alias: AspectRatioOption - Class: OAuthTokenRefreshError - Function: createSimpleLengthScorer() - Type Alias: AssistantContent - Class: OAuthTokenRevocationError - Function: createSkillStore() - Type Alias: AssistantModelMessage - Class: OAuthTokenValidationError - Function: createSkillTools() - Type Alias: AssistantOutput - Class: ObservabilityHooks - Function: createSlidingWindowRateLimitMiddleware() - Type Alias: AssistantReply - Class: OpenAIRealtime - Function: createStrategyNotFoundError() - Type Alias: AssistantToolCall - Class: OpenAISTT - Function: createStreamingClient() - Type Alias: AsyncApiResponse\ - Class: OpenAITTS - Function: createStreamingResponse() - Type Alias: AsyncEventHandler\ - Class: PDFLoader - Function: createSummarizationScorer() - Type Alias: AsyncFunction\ - Class: PgVectorStore - Function: createTextInputRequest() - Type Alias: AsyncResult\ - Class: PineconeVectorStore - Function: createTextResource() - Type Alias: AsyncTransformFunction\ - Class: PipelineBuilder - Function: createTimeoutInterceptor() - Type Alias: AtomicConsumeResult - Class: PromptAlignmentScorer - Function: createTimeoutMiddleware() - Type Alias: AttachmentDownloadOptions - Class: ProviderError - Function: createTimingMiddleware() - Type Alias: AttachmentPolicy - Class: ProviderFactory - Function: createTokenManagerMiddleware() - Type Alias: AttachmentReadOptions - Class: ProviderRegistry - Function: createToneConsistencyScorer() - Type Alias: AttachmentReadResult - Class: RAGASEvaluator - Function: createToolCache() - Type Alias: AttachmentRefusalCode - Class: RAGCircuitBreaker - Function: createToolCallBatcher() - Type Alias: AttachmentsConfig - Class: RAGCircuitBreakerManager - Function: createToolFromFunction() - Type Alias: AudienceOption - Class: RAGJSONChunker - Function: createToolMiddlewareChain() - Type Alias: AudioChunk - Class: RAGPipeline - Function: createToolResultCache() - Type Alias: AudioContent - Class: RAGRetryHandler - Function: createToolRouter() - Type Alias: AudioConversionOptions - Class: RateLimitError - Function: createToolRoutes() - Type Alias: AudioConversionResult - Class: RateLimiterManager - Function: createToxicityScorer() - ~~Type Alias: AudioFormat~~ - Class: RealtimeError - Function: createVectorQueryTool() - Type Alias: AudioFormatDetails - Class: RealtimeProcessor - Function: decideSearchPlan() - Type Alias: AudioInputSpec - Class: RecursiveChunker - Function: decisionBooleanConfidence() - Type Alias: AudioMetadata - Class: RedisArtifactStore - Function: decisionKey() - Type Alias: AudioProcessorOptions - Class: RedisRateLimitStorage - Function: decodeJWTPayload() - Type Alias: AudioProviderConfig - Class: RedisSessionStorage - Function: dedupeTools() - Type Alias: AudioSaveResult - Class: RedisSkillStore - Function: describeSTTProviderKeys() - Type Alias: AudioStreamChunk - Class: ReplicateAvatar - Function: detectAndRedactPII() - Type Alias: AudioTranscriptionOutcome - Class: ReplicateMusic - Function: detectImageMimeType() - Type Alias: AudioTranscriptionProvider - Class: ReplicateVideoHandler - Function: elicitationResponseToProtocol() - Type Alias: AudioTranscriptionSelection - Class: ReportGenerator - Function: enrichCandidate() - Type Alias: Auth0Config - Class: RequestBatcher\ - Function: ensureTelemetry() - Type Alias: Auth0TokenPayload - Class: RequestContext\ - Function: estimateDecisionStateTokens() - Type Alias: AuthCacheConfig - Class: RetryManager - Function: estimateVideoTokens() - Type Alias: AuthCommandArgs - Class: RouteConflictError - Function: evaluateBatch() - Type Alias: AuthErrorCode - Class: RouteNotFoundError - Function: executeMCP() - Type Alias: AuthErrorInfo - Class: RunwayVideoHandler - Function: executeWithCircuitBreaker() - Type Alias: AuthEventData - Class: S3SkillStore - Function: exposeAgentAsTool() - Type Alias: AuthEventHandler - Class: SSEClient - Function: exposeAgentsAsTools() - Type Alias: AuthEventType - Class: STTError - Function: exposeWorkflowAsTool() - Type Alias: AuthEvents - Class: STTProcessor - Function: exposeWorkflowsAsTools() - Type Alias: AuthHealthArgs - Class: SamplingStrategy - Function: extractMetadata() - Type Alias: AuthHealthCheck - Class: ScorerBuilder - Function: extractToken() - Type Alias: AuthJWKSCacheEntry - Class: ScorerRegistry - Function: filterToolsByAnnotations() - Type Alias: AuthLifecycle - Class: SemanticChunker - Function: flushOpenTelemetry() - Type Alias: AuthListDirectQuotaRefreshResult - Class: SentenceChunker - Function: formatContextWithCitations() - Type Alias: AuthListQuotaRefreshAdapter - Class: ServerAdapterError - Function: formatProjectMcpConfigSummary() - Type Alias: AuthListRefreshAccountResult - Class: ServerAdapterFactory - Function: gateDecisionBoolean() - Type Alias: AuthListRefreshOutcome - Class: ServerAuthenticationError - Function: generateOpenAPIFromConfig() - Type Alias: AuthListRefreshResultSetter - Class: ServerAuthorizationError - Function: generateOpenAPISpec() - Type Alias: AuthListRefreshStatus - Class: ServerCapabilitiesManager - Function: generateSummaryStats() - Type Alias: AuthMiddlewareConfig - Class: ServerRateLimitError - ~~Function: generateText()~~ - Type Alias: AuthMiddlewareHandler\ - Class: ServerStartError - Function: getAllWellKnownServers() - Type Alias: AuthMiddlewareOptions - Class: ServerStopError - Function: getAnalyticsMetrics() - Type Alias: AuthMiddlewareResult - Class: ServerTimeoutError - Function: getAnnotationSummary() - Type Alias: AuthProvider - Class: ServerValidationError - Function: getApiKeyFromEnv() - Type Alias: AuthProviderConfig - Class: SessionManager - Function: getAuthContext() - Type Alias: AuthProviderConstructor - Class: SixtyDBTTS - Function: getAvailableProviders() - Type Alias: AuthProviderFactoryFn - Class: SkillsManager - Function: getAvailableStrategies() - Type Alias: AuthProviderHealthCheck - Class: SpanSerializer - Function: getBestProvider() - Type Alias: AuthProviderHealthStatus - Class: StreamAbortedError - Function: getCircuitBreaker() - Type Alias: AuthProviderMetadata - Class: StreamError - Function: getCurrentSession() - Type Alias: AuthProviderRegistration - Class: StreamingError - Function: getCurrentUser() - Type Alias: AuthProviderType - Class: SummarizationScorer - Function: getDefaultChunkerConfig() - Type Alias: AuthProvidersArgs - Class: TTSError - Function: getErrorMessage() - Type Alias: AuthRateLimitConfig - Class: TTSProcessor - Function: getEvaluatorFactory() - Type Alias: AuthRateLimitRedisClient - Class: TaskDistributor - Function: getEvaluatorRegistry() - Type Alias: AuthRequestContext - Class: TextLoader - Function: getJWTExpiry() - Type Alias: AuthRequestHandler - Class: TokenChunker - Function: getLangfuseHealthStatus() - Type Alias: AuthResult - Class: TokenRefreshError - Function: getLocalUsageDescriptors() - Type Alias: AuthSession - Class: TokenStoreError - Function: getMCPStats() - Type Alias: AuthSessionManager - Class: TokenTracker - Function: getMetricsAggregator() - Type Alias: AuthStatus - Class: ToneConsistencyScorer - Function: getPoolStats() - Type Alias: AuthStatusResult - Class: ToolCache\ - Function: getPreset() - Type Alias: AuthStrategy - Class: ToolCallBatcher - Function: getPresetNames() - Type Alias: AuthTokenValidator - Class: ToolEmbeddingIndex - Function: getProjectMcpConfigTrustHook() - Type Alias: AuthUser - Class: ToolIntegrationManager - Function: getProjectMcpConfigTrustStatus() - Type Alias: AuthUserAuthorizer - Class: ToolResultCache - Function: getRecommendedStrategy() - Type Alias: AuthUserManager - Class: ToolRouter - Function: getRegisteredLocalUsageCliIds() - Type Alias: AuthValidateArgs - Class: ToolRoutingCache - Function: getServerInfo() - Type Alias: AuthenticatedContext - Class: TopologyBuilder - Function: getToolSafetyLevel() - Type Alias: AuthenticatedUser - Class: ToxicityScorer - Function: getTrustedMcpConfigStorePath() - Type Alias: AuthenticationState - Class: TranscriptionSession - Function: getVideoProviderConfig() - Type Alias: AuthorizationResult - Class: TripwireEvaluator - Function: getWellKnownServer() - Type Alias: AuthorizationUrlResult - Class: TypedEventEmitter\ - Function: getWorkflow() - Type Alias: AutoEvaluationConfig - Class: UserRateLimiter - Function: hasAllPermissions() - Type Alias: AutoresearchEmitter - Class: VertexVideoHandler - Function: hasAnyRole() - Type Alias: AutoresearchErrorEvent - Class: VideoError - Function: hasPermission() - Type Alias: AutoresearchEventMap - Class: VideoProcessor - Function: hasPricing() - Type Alias: AutoresearchEventName - Class: VoiceError - Function: hasRole() - Type Alias: AutoresearchExperimentCompletedEvent - Class: WebLoader - Function: hashProjectMcpConfig() - Type Alias: AutoresearchExperimentStartedEvent - Class: WebSocketConnectionError - Function: inferAnnotations() - Type Alias: AutoresearchInitArgs - Class: WebSocketConnectionManager - Function: initializeMCPEcosystem() - Type Alias: AutoresearchInitializedEvent - Class: WebSocketError - Function: isAbortError() - Type Alias: AutoresearchMetricImprovedEvent - Class: WebSocketMessageRouter - Function: isAnthropicConfig() - Type Alias: AutoresearchPhaseChangedEvent - Class: WebSocketStreamingClient - Function: isApiError() - Type Alias: AutoresearchResumedEvent - Class: WhistleSTT - Function: isAsyncFunction() - Type Alias: AutoresearchRevertEvent - Class: WorkflowError - Function: isAudioContent() - Type Alias: AutoresearchRevertFailedEvent - Function: isAuthenticated() - Type Alias: AutoresearchStateUpdatedEvent - Function: isCSVContent() - Type Alias: AutoresearchTaskConfig - Function: isCliGenerateResult() - Type Alias: AvailableTool - Function: isCommandResult() - Type Alias: AvatarHandler - Function: isDecisionQuestion() - Type Alias: AvatarOptions - Function: isElicitationProtocolMessage() - Type Alias: AvatarProviderName - Function: isError() - Type Alias: AvatarQuality - Function: isErrorInfo() - Type Alias: AvatarResult - Function: isEvaluationError() - Type Alias: AvatarVideoFormat - Function: isImageContent() - Type Alias: AzureNBest - Function: isJWTExpired() - Type Alias: AzureOutputFormat - Function: isJsonRecord() - Type Alias: AzureRecognitionMode - Function: isModelAccessDeniedMessage() - Type Alias: AzureRecognitionResult - Function: isMultimodalInput() - Type Alias: AzureSTTOptions - Function: isMultimodalMessageContent() - Type Alias: AzureSpeakerRecognitionResult - Function: isNativeVideoMimeType() - Type Alias: AzureTTSOptions - Function: isNeuroLinkError() - Type Alias: AzureVoiceInfo - Function: isOpenTelemetryInitialized() - Type Alias: AzureWord - Function: isPDFContent() - Type Alias: BM25Index - Function: isRetryableError() - Type Alias: BM25Result - Function: isRetryableEvaluationError() - Type Alias: BackgroundColors - Function: isRetryableHTTPError() - Type Alias: BackgroundCommandAllowDecision - Function: isRetryableStatus() - Type Alias: BackgroundCommandCounts - Function: isRetryableStatusCode() - Type Alias: BackgroundCommandCountsSource - Function: isSTTProviderConfigured() - Type Alias: BackgroundCommandHandle - Function: isSTTResult() - Type Alias: BackgroundCommandOptions - Function: isSafeToRetry() - Type Alias: BackgroundCommandOutputPage - Function: isStandardRecord() - Type Alias: BackgroundCommandPageRequest - Function: isStringArray() - Type Alias: BackgroundCommandPolicy - Function: isTTSResult() - Type Alias: BackgroundCommandRefusal - Function: isTextContent() - Type Alias: BackgroundCommandStartToolResult - Function: isTokenExpired() - Type Alias: BackgroundCommandState - Function: isToolDefinition() - Type Alias: BackgroundCommandStatus - Function: isToolResult() - Type Alias: BackgroundCommandStatusToolResult - Function: isTranscriptionSegment() - Type Alias: BackgroundCommandStreamName - Function: isValidHexColor() - Type Alias: BackgroundStyle - Function: isValidProvider() - Type Alias: BackupInfo - Function: isValidRealtimeConfig() - Type Alias: BackupMetadata - Function: isValidSTTOptions() - Type Alias: BadWordsConfig - Function: isValidTTSOptions() - Type Alias: BankArtifactOptions - Function: isVertexVideoConfigured() - Type Alias: BankedArtifactKind - Function: isVideoContent() - Type Alias: BankedArtifactRef - Function: jsonSchema() - Type Alias: BaseAuthProviderConfig - Function: linearCombination() - Type Alias: BaseChunkerConfig - Function: listMCPs() - Type Alias: BaseCommandArgs - Function: listSpeakers() - Type Alias: BaseContext - Function: listWorkflows() - Type Alias: BaseEvaluateArgs - Function: loadDocument() - Type Alias: BaseExtractorConfig - Function: loadDocuments() - Type Alias: BaseToolArgs - Function: loadDotenv() - Type Alias: BashToolResult - Function: loadProcessDotenv() - Type Alias: BasicContext - Function: manifestToSources() - Type Alias: BasicToolsMap - Function: mapStatusToErrorCode() - Type Alias: BatchCommandArgs - Function: mcpProtocolToolToServerTool() - Type Alias: BatchConfig - Function: mcpToolToNeuroLink() - Type Alias: BatchEvaluationConfig - Function: mergeAnnotations() - Type Alias: BatchEvaluationItem - Function: neuroLinkToolToMCP() - Type Alias: BatchEvaluationItemResult - Function: normalizeAndValidate() - Type Alias: BatchEvaluationResult - Function: normalizeHexColor() - Type Alias: BatchExecutor\ - Function: normalizePhrases() - Type Alias: BatchFileProcessingResult - Function: normalizeText() - Type Alias: BatchInferenceConfig - Function: parseAllowedModels() - Type Alias: BatchItemResult - Function: pipeAsyncIterableToDataStream() - Type Alias: BatchOperationResult - Function: pipelineToSpanAttributes() - Type Alias: BatchProcessingSummary\ - Function: prepareRAGTool() - Type Alias: BatchProgress - Function: prepareTextForSpeech() - Type Alias: BatchResult\ - Function: processDocument() - Type Alias: BatcherEvents\ - Function: protocolMessageToElicitation() - Type Alias: BearerAuthOptions - Function: rankCatalogue() - Type Alias: BeatovenComposeResponse - Function: reachableTextProviders() - Type Alias: BeatovenTaskStatus - Function: readAllLocalUsage() - Type Alias: BedrockConfigData - Function: readDecisionBoolean() - Type Alias: BedrockConfigStatus - Function: readDecisionChoice() - Type Alias: BedrockContentBlock - Function: readDecisionScore() - Type Alias: BedrockMessage - Function: readDecisionValue() - Type Alias: BedrockPendingContentBlock - Function: readProjectMcpConfigTrustStore() - Type Alias: BedrockToolResult - Function: reciprocalRankFusion() - Type Alias: BedrockToolUse - Function: recordTrustedProjectMcpConfig() - Type Alias: BenchmarkParams - Function: registerAllRoutes() - Type Alias: BetterAuthConfig - Function: registerDefaultAvatarHandlers() - Type Alias: BiasInstance - Function: registerDefaultMusicHandlers() - Type Alias: BodyParserConfig - Function: registerDefaultRealtimeHandlers() - Type Alias: BooleanRecord - Function: registerDefaultSTTHandlers() - Type Alias: BoundedZipEntry - Function: registerDefaultTTSHandlers() - Type Alias: BracketCountingState - Function: registerDefaultVideoHandlers() - Type Alias: BraintrustExporterConfig - Function: registerLocalUsageReader() - Type Alias: BudgetCheckParams - Function: registerWorkflow() - Type Alias: BudgetCheckResult - Function: renderCandidate() - Type Alias: BudgetFileInput - Function: requireAuth() - Type Alias: BuildContentPlanningPromptOptions - Function: requirePermission() - Type Alias: BuildRealtimeMcpToolsParams - Function: requireRole() - Type Alias: BuiltInMiddlewareType - Function: requireUser() - Type Alias: BuiltInScorerDefinition - Function: requiresConfirmation() - Type Alias: BulletPoint - Function: rerank() - Type Alias: BulletStyle - Function: resetMetricsAggregator() - Type Alias: CLIContext - Function: resolveArtifactStorageType() - Type Alias: CLIMCPServerConfig - Function: resolveDecisionLimitsReading() - Type Alias: CLIProviderConfig - Function: resolveDefaultDecisionProvider() - Type Alias: CLISetupResult - Function: resolveDefaultSTTProvider() - Type Alias: CORSConfig - Function: resolveEntry() - Type Alias: CSVColumnDataType - Function: resolveHistoryBudget() - Type Alias: CSVColumnMetadata - Function: resolveProjectMcpConfigPath() - Type Alias: CSVContent - Function: resolveSpeechSanitizeOptions() - Type Alias: CSVDataQualityWarning - Function: resolveToolRoutingExclusions() - Type Alias: CSVFileOpenOptions - Function: retrieve() - Type Alias: CSVLoaderOptions - Function: runWithAuthContext() - Type Alias: CSVProcessorOptions - Function: runWorkflow() - Type Alias: CSVRow - Function: sanitizeToolName() - Type Alias: CacheConfig - Function: scorerToSpanAttributes() - Type Alias: CacheEntry - Function: selectIrrelevantMessages() - Type Alias: CacheEvents - Function: selectRelevantToolNames() - Type Alias: CacheInterceptorOptions - Function: selectServersByDecision() - Type Alias: CacheOptions - Function: serverToolToMCPProtocol() - Type Alias: CacheStats - Function: servesInferenceKind() - Type Alias: CacheStore - Function: setLangfuseContext() - Type Alias: CacheStrategy - Function: setProjectMcpConfigTrustHook() - Type Alias: CachedImage - Function: shutdownOpenTelemetry() - Type Alias: CachedSession - Function: simpleRerank() - Type Alias: CallRecord - Function: sniffImageMimeType() - Type Alias: CallbackResult - Function: startLangfuseAdapter() - Type Alias: CartesiaMessage - Function: stepCountIs() - Type Alias: CatalogBillingPolicy - Function: streamBatchEvaluation() - Type Alias: CatalogCapabilities - Function: summarizeContext() - Type Alias: CatalogCredentialKey - Function: summarizeProjectMcpConfig() - Type Alias: CatalogEntry - Function: summaryPreservesContext() - Type Alias: CatalogEnvSource - Function: supportsNativeVideo() - Type Alias: CatalogErrorRuleClass - Function: toErrorInfo() - Type Alias: CatalogErrorRuleJson - Function: tokenize() - Type Alias: CatalogEvidence - Function: tool() - Type Alias: CatalogKeySource - Function: validateAnnotations() - Type Alias: CatalogModelSpec - Function: validateCondensationPrompt() - Type Alias: CatalogModelStatus - Function: validateMCPTool() - Type Alias: CatalogPricingPerMTok - Function: validateParams() - Type Alias: CatalogProbeEvidence - Function: validateQuery() - Type Alias: CatalogProviderName - Function: validateRequest() - Type Alias: CatalogQuirks - Function: validateResponse() - Type Alias: CatalogSetup - Function: validateServerTools() - Type Alias: CatalogSetupSource - Function: validateTool() - Type Alias: CatalogTimeouts - Function: validateToolName() - Type Alias: CatalogWire - Function: validateWorkflow() - Type Alias: CategoryMapping - Function: withHTTPRetry() - Type Alias: CellValue - Function: withRetry() - Type Alias: CharacterChunkerConfig - Function: wrapError() - Type Alias: ChartSeries - Function: wrapToolWithElicitation() - Type Alias: ChatMessage - Function: wrapToolsWithElicitation() - Type Alias: ChatMessageMetadata - Type Alias: ChecklistCommandCounts - Type Alias: ChecklistCommandCountsSource - Type Alias: ChecklistCreateInput - Type Alias: ChecklistDelegateCounts - Type Alias: ChecklistDelegateCountsSource - Type Alias: ChecklistItem - Type Alias: ChecklistItemStatus - Type Alias: ChecklistRefusal - Type Alias: ChecklistState - Type Alias: ChecklistToolResult - Type Alias: ChecklistUpdateInput - Type Alias: ChromaClientLike - Type Alias: ChromaCollectionLike - Type Alias: ChromaDeleteParams - Type Alias: ChromaDistanceMetric - Type Alias: ChromaIncludeField - Type Alias: ChromaMetadata - Type Alias: ChromaMetadataValue - Type Alias: ChromaQueryParams - Type Alias: ChromaQueryResponse - Type Alias: ChromaUpsertParams - Type Alias: ChromaVectorStoreOptions - Type Alias: ChromaWhere - Type Alias: Chunk - Type Alias: ChunkMetadata - Type Alias: ChunkParams - Type Alias: Chunker - Type Alias: ChunkerConfig - Type Alias: ChunkerMetadata - Type Alias: ChunkerValidationResult - Type Alias: ChunkingStrategy - Type Alias: CircuitBreakerConfig - Type Alias: CircuitBreakerEvents - Type Alias: CircuitBreakerState - Type Alias: CircuitBreakerStats - Type Alias: CircuitState - Type Alias: CitationFormat - Type Alias: ClaimItem - Type Alias: ClassificationScores - Type Alias: ClassificationStats - Type Alias: ClassificationValidation - Type Alias: ClassifierCandidate - Type Alias: ClassifierCatalogConfig - Type Alias: ClassifierContextScope - Type Alias: ClassifierDecideFn - Type Alias: ClassifierDecision - Type Alias: ClassifierDifficulty - Type Alias: ClassifierGenerateFn - Type Alias: ClassifierGenerateOptions - Type Alias: ClassifierGenerateResult - Type Alias: ClassifierLogger - Type Alias: ClassifierModelMeta - Type Alias: ClassifierModelRef - Type Alias: ClassifierRouterConfig - Type Alias: ClassifierRouterDecision - Type Alias: ClassifierRouterDeps - Type Alias: ClassifierRouterInput - Type Alias: ClassifierRouterPoolMember - Type Alias: ClassifierStrategyKind - Type Alias: ClassifierToolDirective - Type Alias: ClaudeCacheBreakpointOptions - Type Alias: ClaudeCacheControl - Type Alias: ClaudeCodeIdentity - Type Alias: ClaudeContentBlock - Type Alias: ClaudeDisabledThinkingReplacement - Type Alias: ClaudeErrorResponse - Type Alias: ClaudeFinalRequestLogger - Type Alias: ClaudeImageBlock - Type Alias: ClaudeLimitCaptureSlot - Type Alias: ClaudeLimitSnapshot - Type Alias: ClaudeLoggedErrorBuilder - Type Alias: ClaudeMessage - Type Alias: ClaudeMetadata - Type Alias: ClaudeProxyDeps - Type Alias: ClaudeProxyModelTier - Type Alias: ClaudeProxyRouteRuntimeOptions - Type Alias: ClaudeQuotaInfo - Type Alias: ClaudeRequest - Type Alias: ClaudeRequestRuntimeContext - Type Alias: ClaudeResponse - Type Alias: ClaudeSnapshot - Type Alias: ClaudeSnapshotBody - Type Alias: ClaudeSnapshotBodyProbe - Type Alias: ClaudeSubscriptionTier - Type Alias: ClaudeTextBlock - Type Alias: ClaudeThinkingBlock - Type Alias: ClaudeTokenValidationResult - Type Alias: ClaudeTool - Type Alias: ClaudeToolResultBlock - Type Alias: ClaudeToolUseBlock - Type Alias: ClaudeUsage - Type Alias: ClaudeUsageInfo - Type Alias: ClerkConfig - Type Alias: CliAccountUsageTotals - Type Alias: CliAccountsResponse - Type Alias: CliAccountsRow - Type Alias: CliAgentCommandArgs - Type Alias: CliAnalytics - Type Alias: CliAnalyticsDomainAnalyticsConfig - Type Alias: CliAudioPlayerCommand - Type Alias: CliClassifierRouterFlags - Type Alias: CliClientUsageTotals - Type Alias: CliConfigProvider - Type Alias: CliDecideArgs - Type Alias: CliDomainConfig\ - Type Alias: CliEcommerceAnalyticsConfig - Type Alias: CliEvaluation - Type Alias: CliFileProcessingOptions - Type Alias: CliFinanceAnalyticsConfig - Type Alias: CliGeminiSnapshot - Type Alias: CliGenerateResult - Type Alias: CliGrokProxyModelSpec - Type Alias: CliGrokSnapshot - Type Alias: CliHealthcareAnalyticsConfig - Type Alias: CliNetworkCommandArgs - Type Alias: CliNeuroLinkConfig - Type Alias: CliOpenCodeSnapshot - Type Alias: CliProcessingResult - Type Alias: CliProxyClientApplyOptions - Type Alias: CliProxyClientApplyResult - Type Alias: CliProxyClientConfigurator - Type Alias: CliProxyClientRestoreResult - Type Alias: CliProxyConfigDoc - Type Alias: CliProxyRestartError - Type Alias: CliProxyRestartOutput - Type Alias: CliQwenSettings - Type Alias: CliRedisClient - Type Alias: CliResponse - Type Alias: CliServeFlatRoute - Type Alias: CliServeRouteGroup - Type Alias: CliStreamChunk - Type Alias: CliSubtitleCue - Type Alias: CliTokenUsage - Type Alias: CliTomlScanState - Type Alias: CliTomlSection - Type Alias: CliToolRoutingFlags - Type Alias: CliTranscribeArgs - Type Alias: CliTranscribeStreamSink - Type Alias: CliValidatedFileOption - Type Alias: CliVoicesCommandArgs - Type Alias: ClientAgentExecuteOptions - Type Alias: ClientAgentExecuteResult - Type Alias: ClientAgentInfo - Type Alias: ClientApiError - Type Alias: ClientApiResponse\ - Type Alias: ClientAuthConfig - Type Alias: ClientChatMessage - Type Alias: ClientClientWebSocketState - Type Alias: ClientConfig - Type Alias: ClientControlMessage - Type Alias: ClientGenerateRequestOptions - Type Alias: ClientGenerateResponse - Type Alias: ClientInternalConfig - Type Alias: ClientLanguageModel - Type Alias: ClientLanguageModelCallOptions - Type Alias: ClientLanguageModelResponse - Type Alias: ClientLanguageModelStreamResponse - Type Alias: ClientMiddleware - Type Alias: ClientMiddlewareContext - Type Alias: ClientMiddlewareRequest - Type Alias: ClientMiddlewareResponse - Type Alias: ClientModelOptions - Type Alias: ClientOAuth2Config - Type Alias: ClientProviderStatus - Type Alias: ClientReactElement - Type Alias: ClientReactProviderDescriptor - Type Alias: ClientRequestOptions - Type Alias: ClientRetryConfig - Type Alias: ClientSpeechRecognitionResult - Type Alias: ClientSpeechSynthesisOptions - Type Alias: ClientStreamCallbacks - Type Alias: ClientStreamEvent - Type Alias: ClientStreamEventType - Type Alias: ClientStreamRequestOptions - Type Alias: ClientStreamResult - Type Alias: ClientTokenRefreshResult - Type Alias: ClientToolInfo - Type Alias: ClientWebSocketConfig - Type Alias: ClientWebSocketMessage - Type Alias: ClientWebSocketMessageHandler - Type Alias: ClientWebSocketOptions - Type Alias: ClientWebSocketState - Type Alias: ClientWorkflowExecuteOptions - Type Alias: ClientWorkflowExecuteResult - Type Alias: ClientWorkflowInfo - Type Alias: ClipCompletion - Type Alias: ClipGenState - Type Alias: ClipResult - Type Alias: CloakingAccount - Type Alias: CloakingConfig - Type Alias: CloakingContext - Type Alias: CloakingMode - Type Alias: CloakingPlugin - Type Alias: CloakingRequest - Type Alias: CloakingResponse - Type Alias: CloseHandler - Type Alias: CobraInstance - Type Alias: CodeLanguage - Type Alias: CodexAnthropicAffinityKey - Type Alias: CodexAttemptLogExtra - Type Alias: CodexAuthFile - Type Alias: CodexAuthFileTokens - Type Alias: CodexContentPart - Type Alias: CodexFallbackResult - Type Alias: CodexFallbackStream - Type Alias: CodexFallbackTarget - Type Alias: CodexFinalLogExtra - Type Alias: CodexImportedCredential - Type Alias: CodexNativeAdditionalToolsInputItem - Type Alias: CodexNativeCustomToolCallInputItem - Type Alias: CodexNativeCustomToolCallOutputInputItem - Type Alias: CodexNativeCustomToolDeclaration - Type Alias: CodexNativeCustomToolFormat - Type Alias: CodexNativeFunctionCallInputItem - Type Alias: CodexNativeFunctionCallOutputInputItem - Type Alias: CodexNativeFunctionToolDeclaration - Type Alias: CodexNativeInputItem - Type Alias: CodexNativeMessageInputItem - Type Alias: CodexNativeReasoningInputItem - Type Alias: CodexNativeRequest - Type Alias: CodexNativeRole - Type Alias: CodexNativeToolChoice - Type Alias: CodexNativeToolDeclaration - Type Alias: CodexNativeToolKind - Type Alias: CodexNativeToolNamespace - Type Alias: CodexOutboundFailureClass - Type Alias: CodexOutboundFailureInput - Type Alias: CodexOutboundFallbackDecision - Type Alias: CodexOutboundFallbackOutcome - Type Alias: CodexOutboundMessageGroup - Type Alias: CodexOutboundServedAttribution - Type Alias: CodexOutboundToolMappingResult - Type Alias: CodexProxyStatusAccountIdentity - Type Alias: CodexQuotaError - Type Alias: CodexRateLimitWindow - Type Alias: CodexRateLimits - Type Alias: CodexReasoningEffort - Type Alias: CodexRefreshTokenStore - Type Alias: CodexRequestRuntime - Type Alias: CodexRequestState - Type Alias: CodexResponseCustomToolCallItem - Type Alias: CodexResponseEnvelope - Type Alias: CodexResponseFunctionCallItem - Type Alias: CodexResponseItem - Type Alias: CodexResponseItemStatus - Type Alias: CodexResponseMessageItem - Type Alias: CodexResponseOpenItemKind - Type Alias: CodexResponseOutputTextPart - Type Alias: CodexResponseSSEEventType - Type Alias: CodexResponseStream - Type Alias: CodexResponseUsage - Type Alias: CodexResponsesInputItem - Type Alias: CodexResponsesRequest - Type Alias: CodexRotationFailure - Type Alias: CodexRuntimeAccount - Type Alias: CodexStreamEvidence - Type Alias: CodexStreamUsage - Type Alias: CodexTokenRefresher - Type Alias: CodexTokenResponse - Type Alias: CodexTranslationError - Type Alias: CodexUsageFetchResult - Type Alias: CodexUsageResponse - Type Alias: CognitoConfig - Type Alias: CollectedChunkResult - Type Alias: ColorMap - Type Alias: ColumnData - Type Alias: CommandDefinition\ - Type Alias: CommandHandler\ - Type Alias: CommandResult - Type Alias: CompactionConfig - Type Alias: CompactionResult - Type Alias: CompactionStage - Type Alias: CompareProxyReplayOptions - Type Alias: ComparisonColumn - Type Alias: CompatibilityCheckResult - Type Alias: CompleteSlide - Type Alias: CompressionOptions - Type Alias: CompressionResult - Type Alias: CondensationPlaceholder - Type Alias: CondensationPromptValidation - Type Alias: ConditionOptions - Type Alias: ConditionResult - Type Alias: ConditioningConfig - Type Alias: ConfigSource - Type Alias: ConfigUpdateOptions - Type Alias: ConfigValidationResult - Type Alias: ConfirmationElicitation - Type Alias: ConfirmationRequest - Type Alias: ConfirmationRequestEvent - Type Alias: ConfirmationResponseEvent - Type Alias: ConfirmationResult - Type Alias: ConfirmationTimeoutEvent - Type Alias: ConflictDetectionPlugin - Type Alias: ConnectionResult - Type Alias: ConnectivityResult - Type Alias: ConsoleOverride - Type Alias: Content - Type Alias: ContentBlockType - Type Alias: ContentFilteringResult - Type Alias: ContentPlan - Type Alias: ContentSimilarityConfig - Type Alias: Context - Type Alias: ContextAssemblyOptions - Type Alias: ContextCompactRequest - Type Alias: ContextCompactorDeps - Type Alias: ContextConfig - Type Alias: ContextRelevanceOptions - Type Alias: ContextRelevanceResult - Type Alias: ContextScoreItem - Type Alias: ContextWindow - Type Alias: ConversationBase - Type Alias: ConversationChoice - Type Alias: ConversationData - Type Alias: ConversationEntry - Type Alias: ConversationErasureProtocol - Type Alias: ConversationErasureResult - Type Alias: ConversationErasureWriteContext - Type Alias: ConversationErasureWriterStatus - Type Alias: ConversationMemoryConfig - Type Alias: ConversationMemoryEvents - Type Alias: ConversationMemoryStats - Type Alias: ConversationMessage - Type Alias: ConversationModality - Type Alias: ConversationSeedMessage - Type Alias: ConversationSeedOptions - Type Alias: ConversationSummary - Type Alias: ConversationTitleGeneratedEvent - Type Alias: CoordinationContext - Type Alias: CoordinationResult - Type Alias: CoordinationStrategy - Type Alias: CoordinatorConfig - Type Alias: CoreMessage - Type Alias: CostAnalysisOptions - Type Alias: CostAnalysisResult - Type Alias: CostEstimate - Type Alias: CostEstimationParams - Type Alias: CostGroupItem - Type Alias: CreateRoutesOptions - Type Alias: CreateThinkingConfigOptions - Type Alias: CredentialValidationResult - Type Alias: CronSchedule - Type Alias: CustomAuthConfig - Type Alias: CustomSchemaExtractorConfig - Type Alias: DIDTalkResponse - Type Alias: DataContent - Type Alias: DataStreamEvent - Type Alias: DataStreamEventType - Type Alias: DataStreamResponseConfig - Type Alias: DataStreamWriter - Type Alias: DataStreamWriterConfig - Type Alias: DatadogExporterConfig - Type Alias: DebugResult - Type Alias: DecideAmbientKeyCredentialField - Type Alias: DecideAmbientKeyGuard - Type Alias: DecideBaseURLShape - Type Alias: DecideBaseURLTransform - Type Alias: DecideBlock - Type Alias: DecideBodyShape - Type Alias: DecideCapableModel - Type Alias: DecideCatalogJson - Type Alias: DecideDialectName - Type Alias: DecideErrorRule - Type Alias: DecideErrors - Type Alias: DecideFormatterName - Type Alias: DecideMedia - Type Alias: DecideModel - Type Alias: DecisionAfterEvent - Type Alias: DecisionAnswer - Type Alias: DecisionAnswerMap - Type Alias: DecisionAnswerReading - Type Alias: DecisionAudioFormat - Type Alias: DecisionAudioLimits - Type Alias: DecisionBeforeEvent - Type Alias: DecisionBooleanAnswer - Type Alias: DecisionBooleanGate - Type Alias: DecisionBooleanQuestion - Type Alias: DecisionCallerFn - Type Alias: DecisionCallerOptions - Type Alias: DecisionChoiceAnswer - Type Alias: DecisionChoiceQuestion - Type Alias: DecisionChoiceReading - Type Alias: DecisionDialect - Type Alias: DecisionDialectBody - Type Alias: DecisionError - Type Alias: DecisionErrorKind - Type Alias: DecisionHookAnswersContext - Type Alias: DecisionHookContext - Type Alias: DecisionHooks - Type Alias: DecisionImageDimensions - Type Alias: DecisionInput - Type Alias: DecisionLimits - Type Alias: DecisionLimitsQuery - Type Alias: DecisionLimitsReading - Type Alias: DecisionMediaConversion - Type Alias: DecisionMediaFileRead - Type Alias: DecisionMediaKind - Type Alias: DecisionMediaLimits - Type Alias: DecisionMediaResult - Type Alias: DecisionMediaSource - Type Alias: DecisionMediaSourceRead - Type Alias: DecisionModelCard - Type Alias: DecisionOptions - Type Alias: DecisionPreparedAudio - Type Alias: DecisionPreparedMedia - Type Alias: DecisionQuestion - Type Alias: DecisionQuestionMap - Type Alias: DecisionQuestionType - Type Alias: DecisionRequest - Type Alias: DecisionResult - Type Alias: DecisionScoreAnswer - Type Alias: DecisionScoreQuestion - Type Alias: DecisionScoreReading - Type Alias: DecisionSite - Type Alias: DecisionSiteAttributes - Type Alias: DecisionSiteContext - Type Alias: DecisionState - Type Alias: DecisionUsage - Type Alias: DecisionValueAnswer - Type Alias: DecisionValueQuestion - Type Alias: DecisionValueReading - Type Alias: DecodedBuffer - Type Alias: DeduplicationResult - Type Alias: DeepgramAlternative - Type Alias: DeepgramChannel - Type Alias: DeepgramModel - Type Alias: DeepgramResponse - Type Alias: DeepgramResult - Type Alias: DeepgramSTTOptions - Type Alias: DeepgramUtterance - Type Alias: DeepgramWord - Type Alias: DefaultRequestRouterConfig - Type Alias: DeferredClaudeAccountFailure - Type Alias: DeferredToolIndexEntry - Type Alias: DeferredToolResolver - Type Alias: DeferredUsage - Type Alias: DelegateCollectMode - Type Alias: DelegateCollectRequest - Type Alias: DelegateCollectResult - Type Alias: DelegateHandle - Type Alias: DelegateJobPhase - Type Alias: DelegateOutcome - Type Alias: DelegateRefusal - Type Alias: DelegateRegistrationOptions - Type Alias: DelegateRuntimeSettings - Type Alias: DelegateSpawnDefaults - Type Alias: DelegateSpawnOptions - Type Alias: DelegateSpawnToolResult - Type Alias: DelegationCondition - Type Alias: DelegationRule - Type Alias: DeprecatedRouteInfo - Type Alias: DeprecationConfig - Type Alias: DetachableTransferableProxySocket - Type Alias: DetectedPII - Type Alias: DetectionStrategy - Type Alias: DetectionTestConfig - Type Alias: DiagnosticReport - Type Alias: DiagnosticResult - Type Alias: DimensionAnalysis - Type Alias: DirectEvaluateArgs - Type Alias: DirectorModeOptions - Type Alias: DirectorSegment - Type Alias: DiscoveredMcp\ - Type Alias: DistributableTask - Type Alias: DistributionResult - Type Alias: DistributionStrategy - Type Alias: DoGenerateModel - Type Alias: DocsCommandArgs - Type Alias: DocumentLoader - Type Alias: DocumentState - Type Alias: DocumentType - Type Alias: DocumentationResult - Type Alias: DomainConfig - Type Alias: DomainConfigOptions - Type Alias: DomainEvaluationCriteria - Type Alias: DomainTemplate - Type Alias: DomainType - Type Alias: DomainValidationRule - Type Alias: DotenvBootstrapOptions - Type Alias: DotenvBootstrapResult - Type Alias: DynamicArgument\ - Type Alias: DynamicCacheEntry\ - Type Alias: DynamicConfig\ - Type Alias: DynamicModelConfig - Type Alias: DynamicOptions - Type Alias: DynamicResolutionContext - Type Alias: EffectivePPTProviderResult - Type Alias: ElevenLabsModel - Type Alias: ElevenLabsMp3Bitrate - Type Alias: ElevenLabsOpusBitrate - Type Alias: ElevenLabsOutputFormat - Type Alias: ElevenLabsSTTModel - Type Alias: ElevenLabsSTTOptions - Type Alias: ElevenLabsSTTResponse - Type Alias: ElevenLabsSTTWord - Type Alias: ElevenLabsTTSOptions - Type Alias: ElevenLabsVoice - Type Alias: ElevenLabsVoiceSettings - Type Alias: ElevenLabsVoicesResponse - Type Alias: Elicitation - Type Alias: ElicitationCancelMessage - Type Alias: ElicitationCancelParams - Type Alias: ElicitationContext - Type Alias: ElicitationHandler - Type Alias: ElicitationManagerConfig - Type Alias: ElicitationProtocolAdapterConfig - Type Alias: ElicitationProtocolHandler - Type Alias: ElicitationProtocolMessage - Type Alias: ElicitationProtocolMessageType - Type Alias: ElicitationProtocolPayload - Type Alias: ElicitationRequest - Type Alias: ElicitationRequestMessage - Type Alias: ElicitationRequestParams - Type Alias: ElicitationResponse - Type Alias: ElicitationResponseMessage - Type Alias: ElicitationResponseParams - Type Alias: ElicitationType - Type Alias: EmbedInput - Type Alias: EmbedManyRequest - Type Alias: EmbedManyResponse - Type Alias: EmbedRequest - Type Alias: EmbedResponse - Type Alias: EmbeddingModality - Type Alias: EmbeddingModel - Type Alias: EmbeddingModelConfig - Type Alias: EndpointHealth - Type Alias: EndpointMetrics - Type Alias: EnhancedContext - Type Alias: EnhancedConversationTurn - Type Alias: EnhancedEvaluationContext - Type Alias: EnhancedEvaluationResult - Type Alias: EnhancedExecutionContext - Type Alias: EnhancedGenerateResult - Type Alias: EnhancedGroundingMetadata - Type Alias: EnhancedGroundingSource - Type Alias: EnhancedProvider - Type Alias: EnhancedSearchResult - Type Alias: EnhancedStreamProvider - Type Alias: EnhancedToolInfo - Type Alias: EnhancedValidationResult - Type Alias: EnhancementOptions - Type Alias: EnhancementResult - Type Alias: EnhancementType - Type Alias: EnsembleExecutionResult - Type Alias: EnsembleResponse - Type Alias: Entity - Type Alias: EntityId - Type Alias: EnvBackupResult - Type Alias: EnvUpdateResult - Type Alias: EnvVarValidationResult - Type Alias: EphemeralContext - Type Alias: ErrorCategoryType - Type Alias: ErrorCode - Type Alias: ErrorCodeType - Type Alias: ErrorHandlerOptions - Type Alias: ErrorInfo - Type Alias: ErrorResponse - Type Alias: ErrorSeverityType - Type Alias: EscalationResult - Type Alias: EvaluatePresetsArgs - Type Alias: EvaluateReportArgs - Type Alias: EvaluateRunArgs - Type Alias: EvaluateScoreArgs - Type Alias: EvaluateScorersArgs - Type Alias: EvaluationAction - Type Alias: EvaluationActionResult - Type Alias: EvaluationActions - Type Alias: EvaluationConfig - Type Alias: EvaluationContext - Type Alias: EvaluationCriteria - Type Alias: EvaluationData - Type Alias: EvaluationErrorCode - Type Alias: EvaluationErrorContext - Type Alias: EvaluationEvents - Type Alias: EvaluationIssue - Type Alias: EvaluationMode - Type Alias: EvaluationProvider - Type Alias: EvaluationRequest - Type Alias: EvaluationResult - Type Alias: EvaluationSpanAttributes - Type Alias: EvaluationStrategyConfig - Type Alias: EvaluationStrategyFunction - Type Alias: EvaluationStrategyMetadata - Type Alias: EvaluationThresholds - Type Alias: EvaluationTraceContext - Type Alias: EvaluatorPreset - Type Alias: EventHandler\ - Type Alias: EventWrappedTool - Type Alias: ExcelJSCell - Type Alias: ExcelJSCellErrorValue - Type Alias: ExcelJSCellFormulaValue - Type Alias: ExcelJSCellHyperlinkValue - Type Alias: ExcelJSCellRichTextValue - Type Alias: ExcelJSCellSharedFormulaValue - Type Alias: ExcelJSColor - Type Alias: ExcelJSFont - Type Alias: ExcelJSRichText - Type Alias: ExcelJSRow - Type Alias: ExcelJSWorkbook - Type Alias: ExcelJSWorksheet - Type Alias: ExcelWorksheet - Type Alias: ExecuteEnsembleOptions - Type Alias: ExecuteLayerOptions - Type Alias: ExecuteModelOptions - Type Alias: ExecutionConfig - Type Alias: ExecutionContext\ - Type Alias: ExecutionControlDecision - Type Alias: ExecutionControlOptions - Type Alias: ExecutionControlStepContext - Type Alias: ExecutionRequest - Type Alias: ExecutionStrategy - Type Alias: ExifOrientationProbe - Type Alias: ExperimentPhase - Type Alias: ExperimentRecord - Type Alias: ExperimentStats - Type Alias: ExperimentStatus - Type Alias: ExperimentSummary - Type Alias: ExportError - Type Alias: ExportProxyReplayOptions - Type Alias: ExportResult - Type Alias: ExporterConfig - Type Alias: ExporterDeliveryCounts - Type Alias: ExporterHealthStatus - Type Alias: ExporterPlugin - Type Alias: ExporterSpanProcessorOptions - Type Alias: ExporterStatus - Type Alias: ExposableAgent - Type Alias: ExposableWorkflow - Type Alias: ExposureOptions - Type Alias: ExposureResult - Type Alias: ExpressMiddleware - Type Alias: ExtendedObservabilityConfig - Type Alias: ExtendedPropertySchema - Type Alias: ExtendedTool - Type Alias: ExtendedValidationSchema - Type Alias: ExternalMCPConfigValidation - Type Alias: ExternalMCPManagerConfig - Type Alias: ExternalMCPOperationResult\ - Type Alias: ExternalMCPServerConfig - Type Alias: ExternalMCPServerEvents - Type Alias: ExternalMCPServerHealth - Type Alias: ExternalMCPServerInstance - Type Alias: ExternalMCPServerStatus - Type Alias: ExternalMCPToolContext - Type Alias: ExternalMCPToolInfo - Type Alias: ExternalMCPToolResult - Type Alias: ExternalToolExecutionOptions - Type Alias: ExtractChunksOptions - Type Alias: ExtractParams - Type Alias: ExtractionResult - Type Alias: ExtractorType - Type Alias: FactoryEnhancedProvider - Type Alias: FactoryFunction\ - Type Alias: FactoryRegistration\ - Type Alias: FailedFileInfo - Type Alias: FallbackConfig - Type Alias: FallbackEntry - Type Alias: FallbackInfo - Type Alias: FallbackOptions - Type Alias: FastifyRateLimitContext - Type Alias: FeatureConfig - Type Alias: FeatureItem - Type Alias: FfprobeData - Type Alias: FfprobeStream - Type Alias: FileDetectionResult - Type Alias: FileDetectorOptions - Type Alias: FileElicitation - Type Alias: FileExtractionParams - Type Alias: FileExtractionResult - Type Alias: FileForSummarization - Type Alias: FileFormatEntry - Type Alias: FileInfo - Type Alias: FileInput - Type Alias: FileModality - Type Alias: FilePart - Type Alias: FileProcessingError - Type Alias: FileProcessingOptions - Type Alias: FileProcessingResult - Type Alias: FileProcessingSummary - Type Alias: FileProcessorConfig - Type Alias: FileReadResult - Type Alias: FileReference - Type Alias: FileReferenceStatus - Type Alias: FileRegistrationOptions - Type Alias: FileRegistryOptions - Type Alias: FileSearchMatch - Type Alias: FileSearchResult - Type Alias: FileSource - Type Alias: FileSummarizationCheckParams - Type Alias: FileSummarizationCheckResult - Type Alias: FileSummarizationPlanEntry - Type Alias: FileSummarizationPromptParams - Type Alias: FileSummarizationServiceOptions - Type Alias: FileToolRootPolicy - Type Alias: FileType - Type Alias: FileWarning - Type Alias: FileWithMetadata - Type Alias: FilesystemToolsMap - Type Alias: FinishEvent - Type Alias: FinishReason - Type Alias: FirebaseConfig - Type Alias: FixedWindowRateLimitConfig - Type Alias: FlaggedItem - Type Alias: FlexibleSchema\ - Type Alias: FlexibleValidationResult - Type Alias: FormElicitation - Type Alias: FormField - Type Alias: FormatScorerConfig - Type Alias: FormatType - Type Alias: FormatValidationResult - Type Alias: Frame - Type Alias: FrameworkFieldsConfig - Type Alias: FunctionParameters - Type Alias: GcpAuthMethodStatus - Type Alias: GeminiGuardContent - Type Alias: GeminiLoopAdapterConfig - Type Alias: GeminiLoopAdapterCoreConfig - Type Alias: GeminiMalformedRetryConfig - Type Alias: GeminiMessage - Type Alias: GeminiMultimodalInput - Type Alias: GeminiResponse - Type Alias: GeminiStepRaw - Type Alias: GeminiStepRequest - ~~Type Alias: GeminiToolExecutionGuards~~ - Type Alias: GeminiTurnContent - Type Alias: GenAIClient - Type Alias: GenAIGenerateContentResponse - Type Alias: GenAILiveMedia - Type Alias: GenAILiveSession - Type Alias: GenAIModelsAPI - Type Alias: GenAIStreamChunk - ~~Type Alias: Gender~~ - Type Alias: GenerateCommandArgs - Type Alias: GenerateOptions - Type Alias: GenerateOptionsNormalized - Type Alias: GenerateResult - Type Alias: GenerateStopReason - Type Alias: GenerateTextResult\ - Type Alias: GeneratedReport - Type Alias: GenerationModelConfig - Type Alias: GenerationOperation - Type Alias: GenerationRecord - Type Alias: GetPromptFunction - Type Alias: GitToolLogFormat - Type Alias: GitToolRefusal - Type Alias: GitToolResult - Type Alias: GitToolRuntimeSettings - Type Alias: GitToolsetOptions - Type Alias: GlobalInstallerExecFile - Type Alias: GlobalInstallerKind - Type Alias: GlobalInstallerProbe - Type Alias: GlobalInstallerResolution - Type Alias: GoogleAudioConfig - Type Alias: GoogleAudioEncoding - Type Alias: GoogleFilesAPIUploadResult - Type Alias: GoogleGenAIClass - Type Alias: GoogleGenAIHttpOptions - Type Alias: GoogleListVoicesResponse - Type Alias: GoogleLiveAudioQueueItem - Type Alias: GoogleLongRunningRecognizeResponse - Type Alias: GoogleOperationResponse - Type Alias: GoogleRecognitionAudio - Type Alias: GoogleRecognitionConfig - Type Alias: GoogleRecognizeResponse - Type Alias: GoogleSTTAudioEncoding - Type Alias: GoogleSTTModel - Type Alias: GoogleSTTOptions - Type Alias: GoogleSpeechRecognitionAlternative - Type Alias: GoogleSpeechRecognitionResult - Type Alias: GoogleStreamingAudioEncoding - Type Alias: GoogleSynthesisInput - Type Alias: GoogleSynthesizeRequest - Type Alias: GoogleSynthesizeResponse - Type Alias: GoogleTTSOptions - Type Alias: GoogleVertexProviderSettings - Type Alias: GoogleVoiceInfo - Type Alias: GoogleVoiceSelectionParams - Type Alias: GoogleVoiceType - Type Alias: GoogleWordInfo - Type Alias: GraphChunk - Type Alias: GraphEdge - Type Alias: GraphEmbedding - Type Alias: GraphNode - Type Alias: GraphQueryParams - Type Alias: GraphRAGConfig - Type Alias: GraphStats - Type Alias: GridPosition - Type Alias: GroundingChunk - Type Alias: GroundingSupport - Type Alias: GuardrailsMiddlewareConfig - Type Alias: HITLAuditLog - Type Alias: HITLConfig - Type Alias: HITLExecutionState - Type Alias: HITLRule - Type Alias: HITLStatistics - Type Alias: HTMLChunkerConfig - Type Alias: HTTPRetryConfig - Type Alias: HallucinationItem - Type Alias: HeaderScrubberOptions - Type Alias: HealthMetrics - Type Alias: HealthResponse - Type Alias: HeyGenVideoStatusResponse - Type Alias: HierarchicalExecutionTrace - Type Alias: HierarchicalNetworkConfig - Type Alias: HippocampusAddOptions - Type Alias: HippocampusClientFactory - Type Alias: HippocampusCondenserGenerateOptions - Type Alias: HippocampusCondenserResult - Type Alias: HippocampusConfig - Type Alias: HippocampusLike - Type Alias: HippocampusMemory - Type Alias: HippocampusModule - Type Alias: HippocampusNeurolinkConfig - Type Alias: HippocampusNeurolinkLike - Type Alias: HippocampusStorageConfig - Type Alias: HonoRateLimitEntry - Type Alias: HttpMethod - Type Alias: HybridSearchConfig - Type Alias: HybridSearchOptions - Type Alias: HybridSearchResult - Type Alias: HyperlinkProps - Type Alias: IConversationMemoryManager - Type Alias: IdeogramImageResponse - Type Alias: ImageCacheConfig - Type Alias: ImageCacheStats - Type Alias: ImageChunkMetadata - Type Alias: ImageContent - Type Alias: ImageDocument - Type Alias: ImageGenConfig - Type Alias: ImageGenOptions - Type Alias: ImageGenProvider - Type Alias: ImageGenResult - Type Alias: ImageGenToolContext - Type Alias: ImageGenToolDefinition - Type Alias: ImageGenToolParams - Type Alias: ImageGenToolResponse - Type Alias: ImageLoaderOptions - Type Alias: ImageModel - Type Alias: ImageOrientationNormalization - Type Alias: ImagePart - Type Alias: ImageValidationResult - Type Alias: ImageWithAltText - Type Alias: InMemoryAnalyticsStorageOptions - Type Alias: IncomingRequest - Type Alias: IndexEntry - Type Alias: IndexedKnowledgeDocument - Type Alias: IndividualProviderConfig - Type Alias: InferSchema\ - Type Alias: InferToolInput\ - Type Alias: InferToolOutput\ - Type Alias: InferenceKind - Type Alias: InfraRegistryEntry\ - Type Alias: InfraRetryOptions - Type Alias: IngestOptions - Type Alias: InstalledVersionValidation - Type Alias: InteractiveProviderConfig - Type Alias: InternalResult - Type Alias: InternalStreamEvent - Type Alias: IntervalSchedule - Type Alias: InvokeEndpointParams - Type Alias: InvokeEndpointResponse - Type Alias: IsolatedAgentDefinition - Type Alias: IsolatedAgentExtraction - Type Alias: IssueCategory - Type Alias: IssueSeverity - Type Alias: JSONChunkerConfig - Type Alias: JSONOutput - Type Alias: JWK - Type Alias: JWKS - Type Alias: JWTConfig - Type Alias: JinaEmbeddingsResponse - Type Alias: JinaRerankResponse - Type Alias: JsonArray - Type Alias: JsonCoercionResult - Type Alias: JsonObject - Type Alias: JsonRecord - Type Alias: JsonTypeGuard\ - Type Alias: JsonValue - Type Alias: JudgeConfig - Type Alias: JudgeOutputFormat - Type Alias: JudgeScoreResult - Type Alias: JudgeScores - Type Alias: KeycloakConfig - Type Alias: KeywordCoverageConfig - Type Alias: KeywordCoverageDetails - Type Alias: KeywordExtractorConfig - Type Alias: KlingTaskResponse - Type Alias: KnowledgeAssembledContext - Type Alias: KnowledgeCitation - Type Alias: KnowledgeContextConfig - Type Alias: KnowledgeConversationTurn - Type Alias: KnowledgeEngineStatus - Type Alias: KnowledgeEntryInput - Type Alias: KnowledgeEntryKind - Type Alias: KnowledgeFieldName - Type Alias: KnowledgeFieldWeights - Type Alias: KnowledgeGroundingConfig - Type Alias: KnowledgeGroundingInput - Type Alias: KnowledgeGroundingMetadata - Type Alias: KnowledgeGroundingOutcome - Type Alias: KnowledgeIndexSnapshot - Type Alias: KnowledgeLexicalMatch - Type Alias: KnowledgeLexicalSearcher - Type Alias: KnowledgeManifest - Type Alias: KnowledgeManifestCatalog - Type Alias: KnowledgeNormalizeOptions - Type Alias: KnowledgeNormalizeResult - Type Alias: KnowledgeRequestScope - Type Alias: KnowledgeResolvedRetrieval - Type Alias: KnowledgeRetrievalConfidence - Type Alias: KnowledgeRetrievalConfig - Type Alias: KnowledgeRetrievalMode - Type Alias: KnowledgeRetrievalRequest - Type Alias: KnowledgeRetrievalResult - Type Alias: KnowledgeScoredCandidate - Type Alias: KnowledgeSelection - Type Alias: KnowledgeSource - Type Alias: KnowledgeStatus - Type Alias: KnowledgeValidationIssue - Type Alias: KnowledgeValidationResult - Type Alias: KoaRateLimitEntry - Type Alias: LLMScorer - Type Alias: LLMScorerConfig - Type Alias: LaTeXChunkerConfig - Type Alias: LaminarExporterConfig - Type Alias: LangSmithExporterConfig - Type Alias: LangSmithRun - Type Alias: LangfuseAdapterConfig - Type Alias: LangfuseAttributePolicy - Type Alias: LangfuseClient - Type Alias: LangfuseDeliveryReport - Type Alias: LangfuseExporterConfig - Type Alias: LangfusePostOutcome - Type Alias: LangfuseSpan - Type Alias: LangfuseSpanAttributes - Type Alias: LanguageModel - Type Alias: LanguageModelMiddleware - Type Alias: LanguageModelObject - Type Alias: LanguageModelRequestMetadata - Type Alias: LanguageModelResponseMetadata - Type Alias: LanguageModelUsage - Type Alias: LanguageModelV3 - Type Alias: LanguageModelV3CallOptions - Type Alias: LanguageModelV3Content - Type Alias: LanguageModelV3GenerateResult - Type Alias: LanguageModelV3Message - Type Alias: LanguageModelV3Middleware - Type Alias: LanguageModelV3Prompt - Type Alias: LanguageModelV3Source - Type Alias: LanguageModelV3StreamPart - Type Alias: LanguageModelV3StreamResult - Type Alias: LanguageModelV3ToolCall - Type Alias: LanguageModelV3ToolChoice - Type Alias: LatencyStats - Type Alias: LayerExecutionResult - Type Alias: LegacyReadableSpan - Type Alias: LengthConstraintType - Type Alias: LengthMeasurement - Type Alias: LengthScorerConfig - Type Alias: LengthUnit - Type Alias: LifecycleChunkPayload - Type Alias: LifecycleErrorPayload - Type Alias: LifecycleFinishPayload - Type Alias: LifecycleMiddlewareConfig - Type Alias: ListOptions - Type Alias: LiveConnectCallbacks - Type Alias: LiveConnectConfig - Type Alias: LiveKitBrainConfig - Type Alias: LiveKitBrainDefaults - Type Alias: LiveKitBrainTurn - Type Alias: LiveKitBridgeRoom - Type Alias: LiveKitEventBridgeConfig - Type Alias: LiveKitEventBridgeHandle - Type Alias: LiveKitEventBridgeParams - Type Alias: LiveKitInterruptionConfig - Type Alias: LiveKitMemoryNeuroLink - Type Alias: LiveKitNeuroLinkStreamer - Type Alias: LiveKitRoomCallContext - Type Alias: LiveKitServerConfig - Type Alias: LiveKitServerCredentials - Type Alias: LiveKitSttConfig - Type Alias: LiveKitTokenRequest - Type Alias: LiveKitToolEventFields - Type Alias: LiveKitTtsConfig - Type Alias: LiveKitTurnConfig - Type Alias: LiveKitVadConfig - Type Alias: LiveKitVoiceAgentConfig - Type Alias: LiveKitVoiceAgentMemoryConfig - Type Alias: LiveKitVoiceBrain - Type Alias: LiveKitVoiceControlMessage - Type Alias: LiveKitVoiceDoneEvent - Type Alias: LiveKitVoiceEvent - Type Alias: LiveKitVoiceEventEnvelope - Type Alias: LiveKitVoiceEventType - Type Alias: LiveKitVoiceHitlPromptEvent - Type Alias: LiveKitVoiceMemoryEvent - Type Alias: LiveKitVoiceStatusEvent - Type Alias: LiveKitVoiceTextEvent - Type Alias: LiveKitVoiceToolResultEvent - Type Alias: LiveKitVoiceToolStartEvent - Type Alias: LiveKitVoiceUserTextEvent - Type Alias: LiveKitWorkerLaunchOptions - Type Alias: LiveServerContent - Type Alias: LiveServerMessage - Type Alias: LiveServerMessageModelTurn - Type Alias: LiveServerMessagePartInlineData - Type Alias: LoadBalancingStrategy - Type Alias: LoadProxyConfigOptions - Type Alias: LoadedClaudeAccountContext - Type Alias: LoadedProxyConfig - Type Alias: LoaderOptions - Type Alias: LocalModelAsset - Type Alias: LocalUsageAggregateOptions - Type Alias: LocalUsageAggregateReport - Type Alias: LocalUsageClaudeRawUsage - Type Alias: LocalUsageCliId - Type Alias: LocalUsageCodexSessionRollup - Type Alias: LocalUsageCommandArgs - Type Alias: LocalUsageContextPart - Type Alias: LocalUsageCopilotUsageRow - Type Alias: LocalUsageCostConfidence - Type Alias: LocalUsageDedupStrategy - Type Alias: LocalUsageGeminiCliTokens - Type Alias: LocalUsageGeminiMessageRecord - Type Alias: LocalUsageGrokTurn - Type Alias: LocalUsageGrokTurnUsage - Type Alias: LocalUsageHermesUsageRow - Type Alias: LocalUsageQwenRawUsage - Type Alias: LocalUsageReader - Type Alias: LocalUsageReaderDescriptor - Type Alias: LocalUsageReaderFactoryFn - Type Alias: LocalUsageReaderFailure - Type Alias: LocalUsageReaderRegistration - Type Alias: LocalUsageRequestUnit - Type Alias: LocalUsageScanError - Type Alias: LocalUsageScanOptions - Type Alias: LocalUsageScanResult - Type Alias: LocalUsageSqliteDatabase - Type Alias: LocalUsageSqliteDatabaseCtor - Type Alias: LocalUsageTotals - Type Alias: LocalUsageWireField - Type Alias: LogEntry - Type Alias: LogEventEmitter - Type Alias: LogLevel - Type Alias: Logger - Type Alias: LoggingConfig - Type Alias: LoggingInterceptorOptions - Type Alias: LogoConfig - Type Alias: LogoPosition - Type Alias: LoopGuardEntry - Type Alias: LoopGuardPlan - Type Alias: LoopGuardPolicy - Type Alias: LoopSessionState - Type Alias: LyriaResponse - Type Alias: MCPClientResult - Type Alias: MCPCommandArgs - Type Alias: MCPConnectedServer - Type Alias: MCPDiscoveredServer - Type Alias: MCPDiscoveryResult - Type Alias: MCPEnhancementsConfig - Type Alias: MCPExecutableTool - Type Alias: MCPHTTPTransportOptions - Type Alias: MCPOAuthConfig - Type Alias: MCPPrompt - Type Alias: MCPProtocolTool - Type Alias: MCPRegistryClientConfig - Type Alias: MCPResource - Type Alias: MCPServerBaseConfig - Type Alias: MCPServerCategory - Type Alias: MCPServerConfig - Type Alias: MCPServerConnectionStatus - Type Alias: MCPServerDomainCategory - Type Alias: MCPServerEvents - Type Alias: MCPServerInfo - Type Alias: MCPServerMetadata - Type Alias: MCPServerReadiness - Type Alias: MCPServerRegistryEntry - Type Alias: MCPServerStatus - Type Alias: MCPServerStatusResponse - Type Alias: MCPServerTool - Type Alias: MCPStatus - Type Alias: MCPTool - Type Alias: MCPToolAnnotations - Type Alias: MCPToolInfo - Type Alias: MCPToolMetadata - Type Alias: MCPToolWithServer - Type Alias: MCPTransportType - Type Alias: MDocumentConfig - Type Alias: ManagedLogFile - Type Alias: ManifestFamilyRule - Type Alias: MarkdownChunkerConfig - Type Alias: MarkdownHtmlElementNode - Type Alias: MarkdownHtmlNode - Type Alias: Maybe\ - Type Alias: McpCacheConfig - Type Alias: McpCacheEntry\ - Type Alias: McpMetadata - Type Alias: McpOperationConfig - Type Alias: McpOutputContext - Type Alias: McpOutputNormalizerConfig - Type Alias: McpOutputStrategy - Type Alias: McpRegistry - Type Alias: McpRegistryEntry - Type Alias: McpServerWeight - Type Alias: McpTransportAddressClass - Type Alias: McpTransportUrlPolicyOptions - Type Alias: MediaGenerationOutputs - Type Alias: MediaHandlerDescriptor - Type Alias: MediaHandlerKind - Type Alias: MemoryBeforeStoreHook - Type Alias: MemoryCallOptions - Type Alias: MemoryCustomStorageConfig - Type Alias: MemoryMetricConfig - Type Alias: MemoryRedisStorageConfig - Type Alias: MemoryS3StorageConfig - Type Alias: MemoryShouldWriteHook - Type Alias: MemorySqliteStorageConfig - Type Alias: MemoryToolCallRecord - Type Alias: MemoryToolResultRecord - Type Alias: MemoryTurn - Type Alias: MemoryWriteHooks - Type Alias: MenuChoice - Type Alias: Message - Type Alias: MessageBusConfig - Type Alias: MessageBusSubscription - Type Alias: MessageContent - Type Alias: MessageHandler - Type Alias: MessagePriority - Type Alias: MessageType - Type Alias: MetadataExtractor - Type Alias: MetadataExtractorConfig - Type Alias: MetadataExtractorMetadata - Type Alias: MetadataExtractorType - Type Alias: MetadataFilter - Type Alias: MetricConfig - Type Alias: MetricConnectionType - Type Alias: MetricDirection - Type Alias: MetricsAggregatorConfig - Type Alias: MetricsSummary - Type Alias: MetricsTraceContext - Type Alias: MiddlewareChainConfig - Type Alias: MiddlewareChainStats - Type Alias: MiddlewareConditions - Type Alias: MiddlewareConfig - Type Alias: MiddlewareContext - Type Alias: MiddlewareDefinition - Type Alias: MiddlewareExecutionContext - Type Alias: MiddlewareExecutionResult - Type Alias: MiddlewareFactoryConfig - Type Alias: MiddlewareFactoryOptions - Type Alias: MiddlewareHandler - Type Alias: MiddlewareMetrics - Type Alias: MiddlewarePreset - Type Alias: MiddlewareRegistrationOptions - Type Alias: MiddlewareRegistryEntry - Type Alias: MiddlewareRequestSchema - Type Alias: MiddlewareValidationResult - Type Alias: MinimalChatMessage - Type Alias: ModelAliasConfig - Type Alias: ModelCapabilities - Type Alias: ModelCapability - Type Alias: ModelChoice - Type Alias: ModelComparison - Type Alias: ModelConfig - Type Alias: ModelCostStats - Type Alias: ModelDeploymentConfig - Type Alias: ModelDetectionResult - Type Alias: ModelFilter - Type Alias: ModelFilterConfig - Type Alias: ModelGroup - Type Alias: ModelInfo - Type Alias: ModelLimits - Type Alias: ModelMapping - Type Alias: ModelMessage - Type Alias: ModelPerformance - Type Alias: ModelPoolConfig - Type Alias: ModelPoolMember - Type Alias: ModelPoolStrategy - Type Alias: ModelPricing - Type Alias: ModelPricingInfo - Type Alias: ModelPricingRates - Type Alias: ModelRecommendation - Type Alias: ModelRegistry - Type Alias: ModelResolutionContext - Type Alias: ModelRoute - Type Alias: ModelRouterInterface - Type Alias: ModelRoutingOptions - Type Alias: ModelSearchFilters - Type Alias: ModelSearchResult - Type Alias: ModelStats - Type Alias: ModelTier - Type Alias: ModelTierEntry - Type Alias: ModelTokenStats - Type Alias: ModelUseCase - Type Alias: ModelsCommandArgs - Type Alias: ModelsResponse - Type Alias: MultiJudgeScores - Type Alias: MultiModalChunk - Type Alias: MultiModalEmbeddingConfig - Type Alias: MultiModalMatchType - Type Alias: MultiModalQuery - Type Alias: MultiModalRAGConfig - Type Alias: MultiModalSearchResult - Type Alias: MultiSelectElicitation - Type Alias: MultiServerManagerConfig - Type Alias: MultimodalAudioEntry - Type Alias: MultimodalChatMessage - Type Alias: MultimodalInput - Type Alias: MultimodalMessage - Type Alias: MultimodalPdfEntry - Type Alias: MultimodalVideoEntry - Type Alias: MusicAudioFormat - Type Alias: MusicGenre - Type Alias: MusicHandler - Type Alias: MusicMood - Type Alias: MusicOptions - Type Alias: MusicProviderName - Type Alias: MusicResult - Type Alias: NamedZipEntry - Type Alias: NativeAnthropicToolDeclaration - Type Alias: NativeFunctionCall - Type Alias: NativeFunctionDeclaration - Type Alias: NativeFunctionResponse - Type Alias: NativeGenerateGuardConfig - Type Alias: NativeGenerateLoopArgs - Type Alias: NativeGenerateLoopResult - Type Alias: NativeLoopPrepareStep - Type Alias: NativeMediaAttachments - Type Alias: NativeThinkingConfig - Type Alias: NativeToolDeclarationsResult - Type Alias: NativeToolFormat - Type Alias: NativeToolsConfig - Type Alias: NetworkCompleteChunk - Type Alias: NetworkDefaults - Type Alias: NetworkErrorChunk - Type Alias: NetworkExecutionInput - Type Alias: NetworkExecutionOptions - Type Alias: NetworkExecutionResult - Type Alias: NetworkExecutionStatus - Type Alias: NetworkExecutionStep - Type Alias: NetworkExecutionTrace - Type Alias: NetworkInfo - Type Alias: NetworkMemoryConfig - Type Alias: NetworkPrimitive - Type Alias: NetworkPrimitiveType - Type Alias: NetworkStartChunk - Type Alias: NetworkState - Type Alias: NetworkStreamChunk - Type Alias: NetworkStreamChunkBase - Type Alias: NetworkStreamChunkType - Type Alias: NetworkTokenUsage - Type Alias: NetworkToolInfo - Type Alias: NetworkTransportResult - Type Alias: NetworkWorkflow - Type Alias: NetworkWorkflowDefinition - Type Alias: NeuroLinkAuthConfig - Type Alias: NeuroLinkAuthOptions - Type Alias: NeuroLinkConfig - Type Alias: NeuroLinkEvents - Type Alias: NeuroLinkExecutable - Type Alias: NeuroLinkExecutionContext - Type Alias: NeuroLinkInstance - Type Alias: NeuroLinkMCPServer - Type Alias: NeuroLinkMCPTool - Type Alias: NeuroLinkMiddleware - Type Alias: NeuroLinkMiddlewareMetadata - Type Alias: NeuroLinkProviderOptions - Type Alias: NeuroLinkProviderProps - Type Alias: NeuroLinkTool - Type Alias: NeurolinkConstructorConfig - Type Alias: NeurolinkCredentials - Type Alias: NeurolinkLangfuseConfig - Type Alias: NeurolinkOptions - Type Alias: NeurolinkTraceContext - Type Alias: NextFunction - Type Alias: NonEmptyString - Type Alias: NormalizedKnowledgeEntry - Type Alias: NormalizedMcpOutput - Type Alias: Nullable\ - Type Alias: NumberArray - Type Alias: NumberRecord - Type Alias: NvidiaNimExtraBody - Type Alias: OAuth2Config - Type Alias: OAuthClientInformation - Type Alias: OAuthConfig - Type Alias: OAuthFlowTokens - Type Alias: OAuthToken - Type Alias: OAuthTokenResponse - Type Alias: OAuthTokens - Type Alias: ObservabilityCircuitBreakerConfig - Type Alias: ObservabilityCircuitBreakerState - Type Alias: ObservabilityCommandArgs - Type Alias: ObservabilityConfig - Type Alias: ObservabilityCostsArgs - Type Alias: ObservabilityMetricsArgs - Type Alias: ObservabilityModelPricing - Type Alias: ObservabilityStatusArgs - Type Alias: ObservationAttributes - Type Alias: ObservationLevel - Type Alias: ObservationToolCall - Type Alias: ObservationType - Type Alias: OfficeDocumentType - Type Alias: OfficeProcessorOptions - Type Alias: OllamaCommandArgs - Type Alias: OllamaDiagnosticContext - Type Alias: OllamaDiagnosticGate - Type Alias: OllamaDiagnosticOutcome - Type Alias: OllamaDiagnosticPermit - Type Alias: OllamaDiagnosticSnapshot - Type Alias: OllamaDiagnosticState - Type Alias: OllamaHttpError - Type Alias: OnChunkCallback - Type Alias: OnErrorCallback - Type Alias: OnFinishCallback - Type Alias: OnceSchedule - Type Alias: OpenAIAssistantMessage - Type Alias: OpenAIAudioDelta - Type Alias: OpenAICompatBuildBodyArgs - Type Alias: OpenAICompatCatalogEntry - Type Alias: OpenAICompatChatChoice - Type Alias: OpenAICompatChatChoiceMessage - Type Alias: OpenAICompatChatMessage - Type Alias: OpenAICompatChatRequest - Type Alias: OpenAICompatChatResponse - Type Alias: OpenAICompatChatRole - Type Alias: OpenAICompatChatStreamChunk - Type Alias: OpenAICompatChatTool - Type Alias: OpenAICompatConfig - Type Alias: OpenAICompatConfigInput - Type Alias: OpenAICompatCredentials - Type Alias: OpenAICompatErrorBody - Type Alias: OpenAICompatErrorMessage - Type Alias: OpenAICompatImageURLContent - Type Alias: OpenAICompatMessage - Type Alias: OpenAICompatMessageContent - Type Alias: OpenAICompatResponseFormat - Type Alias: OpenAICompatSSEResult - Type Alias: OpenAICompatStreamChunk - Type Alias: OpenAICompatStreamChunkChoice - Type Alias: OpenAICompatStreamDelta - Type Alias: OpenAICompatStreamLifecycleListeners - Type Alias: OpenAICompatTextContent - Type Alias: OpenAICompatToolCallWire - Type Alias: OpenAICompatToolChoiceWire - Type Alias: OpenAICompatToolWarning - Type Alias: OpenAICompatUsage - Type Alias: OpenAICompatUserOrAssistantPart - Type Alias: OpenAICompatV3CallToolChoice - Type Alias: OpenAICompatV3CallTools - Type Alias: OpenAICompatV3Content - Type Alias: OpenAICompatV3FinishReason - Type Alias: OpenAICompatV3StreamPart - Type Alias: OpenAICompatV3Usage - Type Alias: OpenAICompletionRequest - Type Alias: OpenAICompletionResponse - Type Alias: OpenAIContentPart - Type Alias: OpenAIContentPartImage - Type Alias: OpenAIContentPartText - Type Alias: OpenAIErrorResponse - Type Alias: OpenAIMessage - Type Alias: OpenAIRealtimeEvent - Type Alias: OpenAISessionCreated - Type Alias: OpenAIStreamChunk - Type Alias: OpenAISystemMessage - Type Alias: OpenAITTSModel - Type Alias: OpenAITTSOptions - Type Alias: OpenAIToolCall - Type Alias: OpenAIToolChoice - Type Alias: OpenAIToolDef - Type Alias: OpenAIToolMessage - Type Alias: OpenAITranscriptDelta - Type Alias: OpenAIUsage - Type Alias: OpenAIUserMessage - Type Alias: OpenAIVoice - Type Alias: OpenAPIGeneratorConfig - Type Alias: OpenAPISpec - Type Alias: OpenRouterModelInfo - Type Alias: OpenRouterModelsResponse - Type Alias: OpenRouterProviderCache - Type Alias: OperationResult\ - Type Alias: OptimizeParametersParams - Type Alias: OptionSchema - Type Alias: Optional\ - Type Alias: OptionalJsonRecord - Type Alias: OptionalRecordArray - Type Alias: OptionalStandardRecord - Type Alias: OptionalStringArray - Type Alias: OptionalStringRecord - Type Alias: OptionalValidationSchema - Type Alias: OptionsWithLifecycleMiddleware - Type Alias: OrchestrationMode - Type Alias: OrchestrationResult - Type Alias: OrchestrationState - Type Alias: OrchestratorConfig - Type Alias: OtelExporterConfig - Type Alias: OtelProtocol - Type Alias: OtelSpan - Type Alias: OtlpAnyValue - Type Alias: OtlpConnections - Type Alias: OtlpEncodedSpan - Type Alias: OtlpKeyValue - Type Alias: OtlpLink - Type Alias: OtlpScopeSpans - Type Alias: OtlpSpan - Type Alias: OtlpTraceRequest - Type Alias: OutgoingResponse - Type Alias: OutlineSection - Type Alias: OutputFormatOption - Type Alias: OutputOptions - Type Alias: PCMEncoding - Type Alias: PDFAPIType - Type Alias: PDFContent - Type Alias: PDFImageConversionOptions - Type Alias: PDFImageConversionProgress - Type Alias: PDFImageConversionResult - Type Alias: PDFImagePage - Type Alias: PDFLoaderOptions - Type Alias: PDFProcessorOptions - Type Alias: PDFProviderConfig - Type Alias: PDFRenderDocument - Type Alias: PKCEChallenge - Type Alias: PKCEParams - Type Alias: PPTGenerationContext - Type Alias: PPTGenerationResult - Type Alias: PPTModelInfo - Type Alias: PPTOutputOptions - Type Alias: PaginatedResponse\ - Type Alias: ParallelDetectionConfig - Type Alias: ParsedClaudeError - Type Alias: ParsedClaudeRequest - Type Alias: ParsedGeminiRequest - Type Alias: ParsedJudgeResponse - Type Alias: ParsedOpenAIRequest - Type Alias: ParsedOutputTag - Type Alias: ParsedProxyConfig - Type Alias: ParsedSSEBuffer - Type Alias: ParsedSSEEvent - Type Alias: PathSandboxResult - Type Alias: PendingRequest\ - Type Alias: PendingToolExecution - Type Alias: PerformanceConfig - Type Alias: PerformanceMetrics - Type Alias: PerformancePriority - Type Alias: PerformanceProfile - Type Alias: PerformanceThresholds - Type Alias: PermissionDefinition - Type Alias: PersistedAccountCooldown - Type Alias: PersistedProxyStatsSnapshot - Type Alias: PersistedProxyTerminalErrorSnapshot - Type Alias: PgClientLike - Type Alias: PgQueryResult\ - Type Alias: PgVectorStoreOptions - Type Alias: PgVectorStoreRow - Type Alias: PhaseToolPolicy - Type Alias: PiiDetectionConfig - Type Alias: PiiDetectionResult - Type Alias: PiiType - Type Alias: PineconeIndexLike - Type Alias: PineconeMatch - Type Alias: PineconeQueryRequest - Type Alias: PineconeQueryResponse - Type Alias: PineconeUpsertRecord - Type Alias: PinnedAddress - Type Alias: PipelineConfig - Type Alias: PipelineExecutionOptions - Type Alias: PipelineMetrics - Type Alias: PipelineResult - Type Alias: PipelineStats - Type Alias: PositiveNumber - Type Alias: PostHogExporterConfig - Type Alias: PptxBackgroundOptions - Type Alias: PptxChartData - Type Alias: PptxChartName - Type Alias: PptxChartOptions - Type Alias: PptxImageOptions - Type Alias: PptxPresentation - Type Alias: PptxRichTextProps - Type Alias: PptxShapeOptions - Type Alias: PptxSlide - Type Alias: PptxTableOptions - Type Alias: PptxTableRow - Type Alias: PptxTextOptions - Type Alias: PptxTextProps - Type Alias: PptxTextRun - Type Alias: PrecallEvaluationConfig - Type Alias: PrecallEvaluationResult - Type Alias: PrepareStepFunction\ - Type Alias: PrepareStepResult\ - Type Alias: PreparedAnthropicAccountAttempt - Type Alias: PresentationGenerationOptions - Type Alias: PresentationTheme - Type Alias: Primitive - Type Alias: PrimitiveEndChunk - Type Alias: PrimitiveExecutionResult - Type Alias: PrimitiveRecord - Type Alias: PrimitiveStartChunk - Type Alias: ProcessOptions - Type Alias: ProcessResult - Type Alias: ProcessStep - Type Alias: ProcessedArchive - Type Alias: ProcessedAudio - Type Alias: ProcessedConfig - Type Alias: ProcessedExcel - Type Alias: ProcessedFileBase - Type Alias: ProcessedFileInfo - Type Alias: ProcessedHtml - Type Alias: ProcessedImage - Type Alias: ProcessedJson - Type Alias: ProcessedMarkdown - Type Alias: ProcessedOpenDocument - Type Alias: ProcessedProxyBodyCapture - Type Alias: ProcessedRtf - Type Alias: ProcessedSourceCode - Type Alias: ProcessedSvg - Type Alias: ProcessedText - Type Alias: ProcessedVideo - Type Alias: ProcessedWord - Type Alias: ProcessedXml - Type Alias: ProcessedYaml - Type Alias: ProcessorErrorMessageTemplate - Type Alias: ProcessorFileProcessingResult\ - Type Alias: ProcessorFluentFfmpegModule - Type Alias: ProcessorInfo - Type Alias: ProcessorMatch\<\_T\> - Type Alias: ProcessorOperationResult\ - ~~Type Alias: ProcessorPipelineConfig~~ - Type Alias: ProcessorPriorityKey - Type Alias: ProcessorPriorityValue - Type Alias: ProcessorRegistration\ - Type Alias: ProcessorRetryConfig - Type Alias: ProgressCallback - Type Alias: ProjectMcpConfigPathResolution - Type Alias: ProjectMcpConfigServerSummary - Type Alias: ProjectMcpConfigSource - Type Alias: ProjectMcpConfigSummary - Type Alias: ProjectMcpConfigTrustEntry - Type Alias: ProjectMcpConfigTrustHook - Type Alias: ProjectMcpConfigTrustStatus - Type Alias: ProjectMcpConfigTrustStore - Type Alias: PromptGenerator - Type Alias: PromptMessage - Type Alias: PromptRedactionOptions - Type Alias: PromptResult - Type Alias: PromptTier - Type Alias: PropertySchema - Type Alias: ProtocolState - Type Alias: ProviderAttempt - Type Alias: ProviderAvailabilityStatus - Type Alias: ProviderCapabilities - Type Alias: ProviderCapability - Type Alias: ProviderCatalogJson - Type Alias: ProviderConfigOptions - Type Alias: ProviderConfiguration - Type Alias: ProviderConstructor - Type Alias: ProviderCostStats - Type Alias: ProviderCreationError - Type Alias: ProviderDescriptor - Type Alias: ProviderDetails - Type Alias: ProviderErrorClass - Type Alias: ProviderErrorContext - Type Alias: ProviderErrorLike - Type Alias: ProviderErrorRule - Type Alias: ProviderFallbackCallback - Type Alias: ProviderHealthCheckOptions - Type Alias: ProviderHealthStatus - Type Alias: ProviderHealthStatusOptions - Type Alias: ProviderImageFormat - Type Alias: ProviderInfo - Type Alias: ProviderKeyMap - Type Alias: ProviderKeyMapping - Type Alias: ProviderMetadata - Type Alias: ProviderMetricItem - Type Alias: ProviderMetricsOptions - Type Alias: ProviderMetricsResult - Type Alias: ProviderModelConfig - Type Alias: ProviderModelManifest - Type Alias: ProviderModelManifestEntry - Type Alias: ProviderMultimodalPayload - Type Alias: ProviderName - Type Alias: ProviderOperationConfig - Type Alias: ProviderPairResult\ - Type Alias: ProviderPerformanceAnalytics - Type Alias: ProviderPerformanceData - Type Alias: ProviderPerformanceMetrics - Type Alias: ProviderPerformanceSample - Type Alias: ProviderRegistration - Type Alias: ProviderRegistryOptions - Type Alias: ProviderRuntimeConfig - Type Alias: ProviderRuntimeProbeOutcome - Type Alias: ProviderScoringResult - Type Alias: ProviderSelectionCriteria - Type Alias: ProviderSetupArgv - Type Alias: ProviderSetupConfig - Type Alias: ProviderSetupOptions - Type Alias: ProviderStatus - Type Alias: ProviderStatusArgs - Type Alias: ProviderStreamChunk - Type Alias: ProviderTokenStats - Type Alias: ProxyAccount - Type Alias: ProxyAccountConfig - Type Alias: ProxyAccountDirectoryOverride - Type Alias: ProxyAccountPrecedenceReason - Type Alias: ProxyAccountProvider - Type Alias: ProxyAccountRankingPolicy - Type Alias: ProxyAccountRoutingAffinityEvidence - Type Alias: ProxyAccountRoutingAffinitySkipReason - Type Alias: ProxyAccountRoutingCandidate - Type Alias: ProxyAccountRoutingDecision - Type Alias: ProxyAccountRoutingMode - Type Alias: ProxyAccountRoutingReason - Type Alias: ProxyAccountRoutingSpillEvidence - Type Alias: ProxyAccountRoutingStrategy - Type Alias: ProxyAccountSortMetrics - Type Alias: ProxyAccountSpillMove - Type Alias: ProxyAccountType - Type Alias: ProxyActivitySnapshot - Type Alias: ProxyAffinityPrecedenceSkipReason - Type Alias: ProxyAnalysisAccount - Type Alias: ProxyAnalysisAttemptRecord - Type Alias: ProxyAnalysisFinalRequestRecord - Type Alias: ProxyAnalysisOptions - Type Alias: ProxyAnalysisReport - Type Alias: ProxyAnalysisRoutingRecord - Type Alias: ProxyAnalysisStreamName - Type Alias: ProxyAnalyzeArgs - Type Alias: ProxyBindPolicyDecision - Type Alias: ProxyBindPolicyInput - Type Alias: ProxyBodyCaptureAdmission - Type Alias: ProxyBodyCaptureEntry - Type Alias: ProxyBodyCaptureInput - Type Alias: ProxyBodyCaptureLogger - Type Alias: ProxyBodyCapturePolicyOptions - Type Alias: ProxyBodyCapturePolicySnapshot - Type Alias: ProxyBodyCapturePublication - Type Alias: ProxyBodyCaptureReference - Type Alias: ProxyBodyCaptureWorkerSnapshot - Type Alias: ProxyBodyChunkEmitter - Type Alias: ProxyBodyDeduplicationEntry - Type Alias: ProxyBodyDeliveryResult - Type Alias: ProxyBodyPublicationProgress - Type Alias: ProxyCancellableTransformer\ - Type Alias: ProxyClosableServer - Type Alias: ProxyConfig - Type Alias: ProxyConfigFile - Type Alias: ProxyContextEvidence - Type Alias: ProxyContextPolicy - Type Alias: ProxyEnvLoadResult - Type Alias: ProxyEnvOptions - Type Alias: ProxyEnvResolution - Type Alias: ProxyEnvSource - Type Alias: ProxyEnvironmentSnapshot - Type Alias: ProxyExposeArgs - Type Alias: ProxyFormat - Type Alias: ProxyGateProbe - Type Alias: ProxyGeminiContent - Type Alias: ProxyGeminiPart - Type Alias: ProxyGuardArgs - Type Alias: ProxyHealthProbe - Type Alias: ProxyHealthResponse - Type Alias: ProxyHistoryEstimate - Type Alias: ProxyHistoryField - Type Alias: ProxyHistoryTruncationResult\ - Type Alias: ProxyIRCacheHint - Type Alias: ProxyIRContentPart - Type Alias: ProxyIRCustomGrammarToolDeclaration - Type Alias: ProxyIRFunctionToolDeclaration - Type Alias: ProxyIRImagePart - Type Alias: ProxyIRMessage - Type Alias: ProxyIROutputItem - Type Alias: ProxyIRProviderError - Type Alias: ProxyIRReasoning - Type Alias: ProxyIRRequest - Type Alias: ProxyIRRequestBuilder\ - Type Alias: ProxyIRRequestParser\ - Type Alias: ProxyIRRequestTargetOptions - Type Alias: ProxyIRResponse - Type Alias: ProxyIRResponseEvent - Type Alias: ProxyIRResponseParser - Type Alias: ProxyIRResponseRenderer - Type Alias: ProxyIRRole - Type Alias: ProxyIRTerminalOutcome - Type Alias: ProxyIRTextPart - Type Alias: ProxyIRThinkingPart - Type Alias: ProxyIRToolCallPart - Type Alias: ProxyIRToolChoice - Type Alias: ProxyIRToolDeclaration - Type Alias: ProxyIRToolResultPart - Type Alias: ProxyIRUnmappableValue - Type Alias: ProxyIRUnmappedPart - Type Alias: ProxyIRWireFormat - Type Alias: ProxyInboundAuthOptions - Type Alias: ProxyLatencySummary - Type Alias: ProxyLedgerEntry - Type Alias: ProxyLedgerFileCursor - Type Alias: ProxyLifecycleEventInput - Type Alias: ProxyLifecycleEventName - Type Alias: ProxyLifecycleLoggerOptions - Type Alias: ProxyLifecycleLoggerSnapshot - Type Alias: ProxyLifecycleTerminalOutcome - Type Alias: ProxyLimitsAccountResult - Type Alias: ProxyLimitsRefreshResponse - Type Alias: ProxyLogCleanupScheduler - Type Alias: ProxyLogCleanupWorkerData - Type Alias: ProxyLogTraceContext - Type Alias: ProxyMetrics - Type Alias: ProxyMode - Type Alias: ProxyModelRouterConfig - Type Alias: ProxyNetworkTransportScope - Type Alias: ProxyNeurolinkRuntime - Type Alias: ProxyOtelExportFailure - Type Alias: ProxyOtlpLogTransport - Type Alias: ProxyOveragePolicy - Type Alias: ProxyPackageBaseline - Type Alias: ProxyPackagePolyfillReport - Type Alias: ProxyPackagePruneOptions - Type Alias: ProxyPackagePruneResult - Type Alias: ProxyPackagePruneRetention - Type Alias: ProxyPackageSelection - Type Alias: ProxyPackageSelectionState - Type Alias: ProxyPackageUpgradeOptions - Type Alias: ProxyPassthroughAccount - Type Alias: ProxyPaths - Type Alias: ProxyPeer - Type Alias: ProxyPeerArgs - Type Alias: ProxyPeerAttempt - Type Alias: ProxyPeerAuthOutcome - Type Alias: ProxyPeerCooldownReason - Type Alias: ProxyPeerFile - Type Alias: ProxyPeerInput - Type Alias: ProxyPeerLimitsSnapshot - Type Alias: ProxyPeerObservation - Type Alias: ProxyPeerPendingProvision - Type Alias: ProxyPolyfillArgs - Type Alias: ProxyPoolHeadroom - Type Alias: ProxyPreparedContext\ - Type Alias: ProxyProcessTelemetrySnapshot - Type Alias: ProxyProviderTransportPermit - Type Alias: ProxyProviderTransportProbeOutcome - Type Alias: ProxyQuotaCooldownUpdate - Type Alias: ProxyQuotaFreshness - Type Alias: ProxyQuotaHeaderContext - Type Alias: ProxyQuotaRefreshMetrics - Type Alias: ProxyQuotaRefreshReason - Type Alias: ProxyQuotaRefreshRunResult - Type Alias: ProxyQuotaRefreshRuntimeState - Type Alias: ProxyQuotaSaturationKind - Type Alias: ProxyQuotaSource - Type Alias: ProxyReadinessState - Type Alias: ProxyReplayArgs - Type Alias: ProxyReplayBundle - Type Alias: ProxyReplayCapture - Type Alias: ProxyReplayComparison - Type Alias: ProxyReplayJsonRecord - Type Alias: ProxyRequestContext - Type Alias: ProxyRequestLogSinkSnapshot - Type Alias: ProxyRequestLoggerSnapshot - Type Alias: ProxyRequestOrigin - Type Alias: ProxyRequestRoutingSnapshot - Type Alias: ProxyResidentGrant - Type Alias: ProxyResidentGrantFile - Type Alias: ProxyResponseTerminalOutcome - Type Alias: ProxyResponseTrackingObserver - Type Alias: ProxyRestartArgs - Type Alias: ProxyRestartControlIdentity - Type Alias: ProxyRestartControlOptions - Type Alias: ProxyRestartResult - Type Alias: ProxyRestartSupervisorState - Type Alias: ProxyRollingState - Type Alias: ProxyRoutingConfig - Type Alias: ProxyRoutingPolicySnapshot - Type Alias: ProxyRuntimeActivity - Type Alias: ProxyRuntimeConfigListener - Type Alias: ProxyRuntimeConfigProvider - Type Alias: ProxyRuntimeConfigReloadListener - Type Alias: ProxyRuntimeConfigReloadResult - Type Alias: ProxyRuntimeConfigReloadSource - Type Alias: ProxyRuntimeConfigSnapshot - Type Alias: ProxyRuntimeConfigStatus - Type Alias: ProxyRuntimeConfigStoreOptions - Type Alias: ProxyRuntimeSample - Type Alias: ProxyServiceInstallSettings - Type Alias: ProxyServingWorkerIdentity - Type Alias: ProxyShareAccountExclusion - Type Alias: ProxyShareAccountFilterResult - Type Alias: ProxyShareAccountView - Type Alias: ProxyShareAdmission - Type Alias: ProxyShareAdmissionInput - Type Alias: ProxyShareArgs - Type Alias: ProxyShareAuditFile - Type Alias: ProxyShareAuditObservation - Type Alias: ProxyShareAuditRecord - Type Alias: ProxyShareCliAction - Type Alias: ProxyShareDriftVerdict - Type Alias: ProxyShareEntitlement - Type Alias: ProxyShareGateOutcome - Type Alias: ProxyShareGates - Type Alias: ProxyShareGrant - Type Alias: ProxyShareGrantCounters - Type Alias: ProxyShareGrantFile - Type Alias: ProxyShareGrantInput - Type Alias: ProxyShareGrantPatch - Type Alias: ProxyShareGrantState - Type Alias: ProxyShareGrantUsageSummary - Type Alias: ProxyShareHeartbeatRenewal - Type Alias: ProxyShareHeartbeatRequest - Type Alias: ProxyShareHeartbeatResponse - Type Alias: ProxyShareHeartbeatStop - Type Alias: ProxyShareHold - Type Alias: ProxyShareIssuedGrant - Type Alias: ProxyShareLease - Type Alias: ProxyShareLeaseRefusal - Type Alias: ProxyShareLeaseVerdict - Type Alias: ProxyShareLedgerBucket - Type Alias: ProxyShareLedgerFile - Type Alias: ProxyShareLedgerMode - Type Alias: ProxyShareLevel - Type Alias: ProxyShareListenerHandle - Type Alias: ProxyShareNettingClaim - Type Alias: ProxyShareNettingResult - Type Alias: ProxyShareNote - Type Alias: ProxyShareNoteFile - Type Alias: ProxyShareNoteRecord - Type Alias: ProxyShareNoteStatus - Type Alias: ProxySharePoolUsage - Type Alias: ProxySharePresetName - Type Alias: ProxyShareProvisionClaim - Type Alias: ProxyShareProvisionFile - Type Alias: ProxyShareProvisionOutcome - Type Alias: ProxyShareProvisionRequest - Type Alias: ProxyShareProvisionStatus - Type Alias: ProxyShareProvisioningBundle - Type Alias: ProxyShareRate - Type Alias: ProxyShareReceipt - Type Alias: ProxyShareReceiptFile - Type Alias: ProxyShareRefillPeriod - Type Alias: ProxyShareRefusalReason - Type Alias: ProxyShareRefusalResponse - Type Alias: ProxyShareRefusedAdmission - Type Alias: ProxyShareRequestContext - Type Alias: ProxyShareRuntimeCounters - Type Alias: ProxyShareSchedule - Type Alias: ProxyShareSettlement - Type Alias: ProxyShareSpilloverGate - Type Alias: ProxyShareStatement - Type Alias: ProxyShareUsage - Type Alias: ProxyShareWindowObservation - Type Alias: ProxyShareWindowSlice - Type Alias: ProxySpinner - Type Alias: ProxyStagedInstallOptions - Type Alias: ProxyStartApp - Type Alias: ProxyStartArgs - Type Alias: ProxyStartStrategy - Type Alias: ProxyState - Type Alias: ProxyStats - Type Alias: ProxyStatsLockOwner - Type Alias: ProxyStatsPersistenceStatus - Type Alias: ProxyStatusArgs - Type Alias: ProxyStatusPrimaryAccount - Type Alias: ProxySupervisorState - Type Alias: ProxySupervisorTelemetry - Type Alias: ProxyTelemetryAction - Type Alias: ProxyTelemetryArgs - Type Alias: ProxyTelemetryBackend - Type Alias: ProxyTelemetryCheck - Type Alias: ProxyTelemetryDoctorOptions - Type Alias: ProxyTelemetryFieldCoverage - Type Alias: ProxyTelemetryNativeConfig - Type Alias: ProxyTelemetryQueryBudget - Type Alias: ProxyTelemetryQueryOptions - Type Alias: ProxyTelemetryStoredRecord - Type Alias: ProxyTerminalErrorCategory - Type Alias: ProxyTerminalErrorDetails - Type Alias: ProxyTerminalErrorJournal - Type Alias: ProxyTerminalErrorSummary - Type Alias: ProxyTimeouts - Type Alias: ProxyTokenBudgetBucket - Type Alias: ProxyTokenBudgetLease - Type Alias: ProxyTokenBudgetPolicy - Type Alias: ProxyTokenBudgetRecord - Type Alias: ProxyTokenBudgetReservation - Type Alias: ProxyTokenBudgetRpcPending - Type Alias: ProxyTokenBudgetRpcRequest - Type Alias: ProxyTokenBudgetRpcResponse - Type Alias: ProxyTokenBudgetSnapshot - Type Alias: ProxyTranslationAttempt - Type Alias: ProxyTranslationPlan - Type Alias: ProxyTransportScope - Type Alias: ProxyUpdateWindowOptions - Type Alias: ProxyUpdateWindowResult - Type Alias: ProxyUsageAttributionOptions - Type Alias: ProxyUsageStatsSnapshot - Type Alias: ProxyUsageStatsStoreOptions - Type Alias: ProxyWorkerControlMessage - Type Alias: ProxyWorkerIpcMessage - Type Alias: ProxyWorkerSocketMessage - Type Alias: ProxyWorkerStatusMessage - Type Alias: PruneConfig - Type Alias: PruneResult - Type Alias: QualityErrorDetails - Type Alias: QueryIntentAnalysis - Type Alias: QueryOptions - Type Alias: QuestionExtractorConfig - Type Alias: QueuedAccountAdmission - Type Alias: QueuedProxyLifecycleEvent - Type Alias: QuietStatus - Type Alias: QuotaCheckResult - Type Alias: RAGCircuitBreakerConfig - Type Alias: RAGCircuitBreakerEvents - Type Alias: RAGCircuitBreakerStats - Type Alias: RAGCommandArgs - Type Alias: RAGConfig - Type Alias: RAGErrorCode - Type Alias: RAGPipelineConfig - Type Alias: RAGPreparedTool - Type Alias: RAGResponse - Type Alias: RAGRetryConfig - Type Alias: RBACConfig - Type Alias: RBACMiddlewareConfig - Type Alias: RagChunkArgs - Type Alias: RagIndexArgs - Type Alias: RagQueryArgs - Type Alias: RankedNode - Type Alias: RateLimitConfig - Type Alias: RateLimitCoolingReason - Type Alias: RateLimitEntry - Type Alias: RateLimitMiddlewareConfig - Type Alias: RateLimitMiddlewareResult - Type Alias: RateLimitResult - Type Alias: RateLimitStorage - Type Alias: RateLimitStore - Type Alias: RateLimiterConfig - Type Alias: RateLimiterOptions - Type Alias: RateLimiterPendingRequest - Type Alias: RateLimiterStats - Type Alias: RawFileInput - Type Alias: RawGroundingMetadata - Type Alias: RawStreamCapture - Type Alias: RawStreamCaptureResult - Type Alias: RawUsageObject - Type Alias: ReadyResponse - Type Alias: RealtimeAudioChunk - Type Alias: RealtimeCallMemory - Type Alias: RealtimeConfig - Type Alias: RealtimeConfirmationRequester - Type Alias: RealtimeEventBridgeHandle - Type Alias: RealtimeEventBridgeParams - Type Alias: RealtimeEventHandlers - Type Alias: RealtimeEventPublisher - Type Alias: RealtimeHandler - Type Alias: RealtimeLlm - Type Alias: RealtimeMessage - Type Alias: RealtimeMessageType - Type Alias: RealtimeSession - Type Alias: RealtimeSessionState - Type Alias: RealtimeTool - Type Alias: RealtimeTracedCall - Type Alias: RealtimeVoiceAgentConfig - Type Alias: RealtimeVoiceBackend - Type Alias: RealtimeVoiceConfig - Type Alias: RealtimeVoiceLogContext - Type Alias: RealtimeVoiceLogEntry - Type Alias: RealtimeVoiceMemoryConfig - Type Alias: RealtimeVoiceProvider - Type Alias: RecommendationContext - Type Alias: RecordArray - Type Alias: RecordConversationTurnOptions - Type Alias: RecordConversationTurnResult - Type Alias: RecraftImageResponse - Type Alias: RecursiveChunkerConfig - Type Alias: RedactionConfig - Type Alias: RedisArtifactRecord - Type Alias: RedisClient - Type Alias: RedisConversationObject - Type Alias: RedisStorageConfig - Type Alias: RefactoringResult - Type Alias: RefreshResult - Type Alias: RefreshableAccount - Type Alias: RegexPatternVerdict - Type Alias: RegisterOptions - Type Alias: RegisterResult - Type Alias: RegisteredPrompt - Type Alias: RegisteredResource - Type Alias: RegistryConfig - Type Alias: RegistryEntry - Type Alias: RegistryOptions - Type Alias: RegistryProcessResult\ - Type Alias: RegistrySearchOptions - Type Alias: RegistrySearchResult - Type Alias: RegistrySourceType - Type Alias: RegistryStats - Type Alias: RemoteRegistryInput - Type Alias: RemoteRegistryPackage - Type Alias: RemoteRegistryPage - Type Alias: RemoteRegistryRecord - Type Alias: RemoteRegistryServer - Type Alias: RemoteRegistryTarget - Type Alias: RemoteRegistryTransport - Type Alias: RenderContentSlideOptions - Type Alias: RepairResult - Type Alias: RepairToolBatch - Type Alias: ReplicateAuth - Type Alias: ReplicateCreatePredictionInput - Type Alias: ReplicatePollOptions - Type Alias: ReplicatePrediction - Type Alias: ReplicatePredictionStatus - Type Alias: ReportConfig - Type Alias: ReportData - Type Alias: ReportFormat - Type Alias: RequestAttemptLogEntry - Type Alias: RequestKind - Type Alias: RequestKindInput - Type Alias: RequestKindTTSInput - Type Alias: RequestLogEntry - Type Alias: RequestRouter - Type Alias: RequestRouterDecision - Type Alias: RequiredBodyParserConfig - Type Alias: RequiredCORSConfig - Type Alias: RequiredLoggingConfig - Type Alias: RequiredRateLimitConfig - Type Alias: RequiredRedactionConfig - Type Alias: RequiredServerAdapterConfig - Type Alias: RequiredShutdownConfig - Type Alias: Requirement - Type Alias: RerankResult - Type Alias: Reranker - Type Alias: RerankerConfig - Type Alias: RerankerMetadata - Type Alias: RerankerOptions - Type Alias: RerankerType - Type Alias: ResearchConfig - Type Alias: ResearchState - Type Alias: ResearchToolsDeps - Type Alias: ResearchWorkerConfig - Type Alias: ResolutionOptions - Type Alias: ResolutionResult\ - Type Alias: ResolveGlobalInstallerOptions - Type Alias: ResolvedConfig\ - Type Alias: ResolvedSpeechSanitizeOptions - Type Alias: ResolvedToolPolicy - Type Alias: ResourceContent - Type Alias: ResourceReader - Type Alias: ResourceSubscriptionCallback - Type Alias: ResponseCacheEntry\ - Type Alias: ResponseInfoContext - Type Alias: ResponseMetadata - Type Alias: ResponseValidationConfig - Type Alias: ResponseValidationResult - Type Alias: RestorationToolContext - Type Alias: Result\ - Type Alias: RetryConfig - Type Alias: RetryContext - Type Alias: RetryDecision - Type Alias: RetryInterceptorOptions - Type Alias: RetryOptions - Type Alias: RetryPolicy - Type Alias: RetryStrategy - Type Alias: ReviewDecision - Type Alias: RollingCandidateWorker - Type Alias: RollingManagedWorker - Type Alias: RollingProxyServer - Type Alias: RollingProxyServerOptions - Type Alias: RollingQueuedSocket - Type Alias: RollingSocketAdmission - Type Alias: RollingWorkerFailureDetails - Type Alias: RollingWorkerHandle - Type Alias: RollingWorkerSupervisorEvent - Type Alias: RollingWorkerSupervisorOptions - Type Alias: RollingWorkerSupervisorSnapshot - Type Alias: RouteDefinition - Type Alias: RouteDeprecation - Type Alias: RouteGroup - Type Alias: RouteHandler\ - Type Alias: RouteResult - Type Alias: RoutedClaudeRequestRuntimeContext - Type Alias: RouterConfig - Type Alias: RouterInputContext - Type Alias: RoutingContext - Type Alias: RoutingDecision - Type Alias: RoutingDecisionChunk - Type Alias: RoutingPromptOptions - Type Alias: RoutingStrategy - Type Alias: RuleResult - Type Alias: RuleScorer - Type Alias: RuleScorerConfig - Type Alias: RunPipelineArgs - Type Alias: RunWorkflowOptions - Type Alias: RuntimeAccountState - Type Alias: RuntimeMCPServerInfo - Type Alias: RuntimeRequestMetadata - Type Alias: RunwayTaskResponse - Type Alias: SDKToolContext - Type Alias: SSEConfig - Type Alias: SSEConnectionOptions - Type Alias: SSEConnectionState - Type Alias: SSEContentBlock - Type Alias: SSEContentBlockDelta - Type Alias: SSEContentBlockDescriptor - Type Alias: SSEContentBlockStart - Type Alias: SSEContentBlockStop - Type Alias: SSEDeltaDescriptor - Type Alias: SSEEvent - Type Alias: SSEEventHandlers - Type Alias: SSEEventOptions - Type Alias: SSEInterceptorOptions - Type Alias: SSEInterceptorResult - Type Alias: SSEMessageDelta - Type Alias: SSEMessageStart - Type Alias: SSEMessageStop - Type Alias: SSEPing - Type Alias: SSERequestOptions - Type Alias: SSEState - Type Alias: SSETelemetry - Type Alias: SSEWriteOptions - Type Alias: STTChunkedPassOptions - Type Alias: STTChunkedRun - Type Alias: STTChunkedStreamOptions - Type Alias: STTCodeMixAnalysis - Type Alias: STTConfidenceSource - Type Alias: STTCorrectionDeps - Type Alias: STTCorrectionInput - Type Alias: STTCorrectionOptions - Type Alias: STTCorrectionOutput - Type Alias: STTCredentials - Type Alias: STTCredentialsCarrier - Type Alias: STTDecisionRecord - Type Alias: STTDictionaryCandidate - Type Alias: STTDictionaryEntry - Type Alias: STTEndpointConfig - Type Alias: STTEndpointerConfig - Type Alias: STTEndpointerEvent - Type Alias: STTEndpointerPreBlock - Type Alias: STTEndpointerSpeechConfig - Type Alias: STTEndpointerUtterance - Type Alias: STTEngineInfo - Type Alias: STTFallbackOptions - Type Alias: STTHandler - Type Alias: STTLanguage - Type Alias: STTLanguageScore - Type Alias: STTLocalAgreementState - Type Alias: STTLocalAgreementUpdate - Type Alias: STTOnnxRuntime - Type Alias: STTOnnxSession - Type Alias: STTOnnxTensor - Type Alias: STTOptions - Type Alias: STTOutputBatchOutcome - Type Alias: STTOutputLanguageSource - Type Alias: STTOutputOptions - Type Alias: STTOutputRenderInput - Type Alias: STTOutputRendering - Type Alias: STTOutputStatus - Type Alias: STTProviderCapabilities - Type Alias: STTProviderDescriptor - Type Alias: STTResult - Type Alias: STTRewriteLinesOutcome - Type Alias: STTRewriteOutcome - Type Alias: STTRoutingOptions - Type Alias: STTSpeechDetector - Type Alias: STTStreamEngineRole - Type Alias: STTStreamingOptions - Type Alias: STTVadEngine - Type Alias: STTVadOptions - Type Alias: STTWordPair - Type Alias: SafeDownloadOptions - Type Alias: SafeDownloadResult - Type Alias: SafeParseResult\ - Type Alias: SafetyStatus - Type Alias: SageMakerAsLanguageModel - Type Alias: SageMakerCommandArgs - Type Alias: SageMakerConfig - Type Alias: SageMakerEndpointInfo - Type Alias: SageMakerErrorCode - Type Alias: SageMakerErrorInfo - Type Alias: SageMakerGenerateResult - Type Alias: SageMakerGenerationOptions - Type Alias: SageMakerGenerationResponse - Type Alias: SageMakerModelConfig - Type Alias: SageMakerOpenAIToolCall - Type Alias: SageMakerStreamChunk - Type Alias: SageMakerStreamingToolCall - Type Alias: SageMakerStreamingToolResult - Type Alias: SageMakerStructuredOutput - Type Alias: SageMakerToolCall - Type Alias: SageMakerToolResult - Type Alias: SageMakerUsage - Type Alias: SampleDataFormat - Type Alias: Sampler - Type Alias: SamplerConfig - Type Alias: SamplingConfig - Type Alias: SamplingContext - Type Alias: SamplingDecision - Type Alias: SamplingRule - Type Alias: SanitizeDisplayNameOptions - Type Alias: SanitizeFileNameOptions - Type Alias: ScalarRecoveryDecision - Type Alias: ScheduledEntry - Type Alias: ScheduledTaskType - Type Alias: Schema\ - Type Alias: SchemaConversionContext - Type Alias: SchemaConversionNode - Type Alias: SchemaRegexDrop - Type Alias: ScoreDistribution - Type Alias: ScoreOptions - Type Alias: ScoreResult - Type Alias: ScoreScale - Type Alias: ScoreStatistics - Type Alias: Scorer - Type Alias: ScorerCategory - Type Alias: ScorerConfig - Type Alias: ScorerEvent - Type Alias: ScorerFactory - Type Alias: ScorerFunction - Type Alias: ScorerInput - Type Alias: ScorerMetadata - Type Alias: ScorerMetrics - Type Alias: ScorerRegistryEntry - Type Alias: ScorerRule - Type Alias: ScorerType - Type Alias: ScriptCode - Type Alias: SdkSimpleTool\ - Type Alias: SearchPlanCapabilities - Type Alias: SearchPlanResult - Type Alias: SecretElicitation - Type Alias: SecureConfiguration - Type Alias: SegmentAttribution - Type Alias: SegmentSupport - Type Alias: SelectElicitation - Type Alias: SelectOption - Type Alias: SemVer - Type Alias: SemanticChunkerConfig - Type Alias: SentenceChunkerConfig - Type Alias: SentryExporterConfig - Type Alias: SentryModule - Type Alias: SentryScope - Type Alias: SerializeOptions - Type Alias: SerializedError - Type Alias: ServeCommandArgs - Type Alias: ServeState - Type Alias: ServerAdapterConfig - Type Alias: ServerAdapterErrorCodeType - Type Alias: ServerAdapterErrorContext - Type Alias: ServerAdapterEvents - Type Alias: ServerAdapterFactoryOptions - Type Alias: ServerAgentResolveOptions - Type Alias: ServerAgentResolvedInput - Type Alias: ServerAgentRouteOptions - Type Alias: ServerAuthConfig - Type Alias: ServerBodyParserVerdict - Type Alias: ServerBoundedBodyRead - Type Alias: ServerBufferedRequest - Type Alias: ServerCacheConfig - Type Alias: ServerCapabilitiesConfig - Type Alias: ServerCarriedContext - Type Alias: ServerClientAddressInput - Type Alias: ServerClientFacingError - Type Alias: ServerCommandArgs - Type Alias: ServerConfig - Type Alias: ServerConfigFile - Type Alias: ServerContext - Type Alias: ServerFramework - Type Alias: ServerGroup - Type Alias: ServerInstance - Type Alias: ServerLifecycleState - Type Alias: ServerLoadResult - Type Alias: ServerMemoryActor - Type Alias: ServerMemoryRouteOptions - Type Alias: ServerMetrics - Type Alias: ServerNodeMiddleware - Type Alias: ServerOpenAITranscriptionResponse - Type Alias: ServerOpenAITranscriptionSegment - Type Alias: ServerOpenAITranscriptionWord - Type Alias: ServerParsedNodeRequest - Type Alias: ServerRealtimeItem - Type Alias: ServerRealtimeSessionConfig - Type Alias: ServerRealtimeSocket - Type Alias: ServerResponse\ - Type Alias: ServerSTTEvalAlignment - Type Alias: ServerSTTEvalBatchRequest - Type Alias: ServerSTTEvalBatchResponse - Type Alias: ServerSTTEvalCallRecord - Type Alias: ServerSTTEvalCallSummary - Type Alias: ServerSTTEvalComparison - Type Alias: ServerSTTEvalLangfuseConfig - Type Alias: ServerSTTEvalLangfuseEvent - Type Alias: ServerSTTEvalOptions - Type Alias: ServerSTTEvalReport - Type Alias: ServerSTTEvalSegment - Type Alias: ServerSTTEvalSide - Type Alias: ServerSTTEvalStoredBatch - Type Alias: ServerSTTRealtimeProfile - Type Alias: ServerSensitiveRouteOptions - Type Alias: ServerServeHardeningArgs - Type Alias: ServerServerAuthConfig - Type Alias: ServerSessionConfig - Type Alias: ServerState - Type Alias: ServerStatus - Type Alias: ServerTranscribeCapabilities - Type Alias: ServerTranscribeRequest - Type Alias: ServerTranscribeRouteOptions - Type Alias: ServerTranscribeStreamConfig - Type Alias: ServerTranscribeWebSocketOptions - Type Alias: ServerValidationResult\ - Type Alias: ServerVoiceConnectionCtx - Type Alias: ServerVoiceSessionState - Type Alias: ServerVoiceWebSocketOptions - Type Alias: ServerWeight - Type Alias: ServiceConfig - Type Alias: ServiceConfigOptions - Type Alias: ServiceConnectivityResult - Type Alias: ServiceDefinition\ - Type Alias: ServiceDependencyHealth - Type Alias: ServiceHealth - Type Alias: ServiceMetadata - Type Alias: ServiceRegistryStats - Type Alias: ServiceStatus - Type Alias: SessionConfig - Type Alias: SessionExport - Type Alias: SessionIdentifier - Type Alias: SessionListItem - Type Alias: SessionManagerStorage - Type Alias: SessionMemory - Type Alias: SessionMetadata - Type Alias: SessionRestoreResult - Type Alias: SessionStorage - Type Alias: SessionStorageType - Type Alias: SessionValidationResult - Type Alias: SessionVariableValue - Type Alias: SetupArgs - Type Alias: SetupCommandArgs - Type Alias: SetupHuggingFaceArgs - Type Alias: SetupMistralArgs - Type Alias: SetupProviderInfo - Type Alias: SetupResult - Type Alias: SeverityColors - Type Alias: ShadowProps - Type Alias: SharedRefreshResult - Type Alias: ShutdownConfig - Type Alias: SimilarityDetails - Type Alias: SimilarityMetric - Type Alias: SimpleResult - Type Alias: SimpleTool\ - Type Alias: SingleShotRequest - Type Alias: SingleShotResult - Type Alias: SizeTier - Type Alias: SkillActivationRecord - Type Alias: SkillCallToolsContext - Type Alias: SkillCreateInput - Type Alias: SkillCustomStorageConfig - Type Alias: SkillDefinition - Type Alias: SkillDiscoveryMode - Type Alias: SkillFilesystemStorageConfig - Type Alias: SkillIndexItem - Type Alias: SkillLifecycleStatus - Type Alias: SkillMemoryStorageConfig - Type Alias: SkillMutationAction - Type Alias: SkillMutationDecision - Type Alias: SkillMutationResult - Type Alias: SkillRedisStorageConfig - Type Alias: SkillResourceRef - Type Alias: SkillS3ConditionalGetResult - Type Alias: SkillS3IndexDocument - Type Alias: SkillS3ModuleSurface - Type Alias: SkillS3ObjectOps - Type Alias: SkillS3StorageConfig - Type Alias: SkillScopeKind - Type Alias: SkillSearchQuery - Type Alias: SkillSessionStateLike - Type Alias: SkillStore - Type Alias: SkillToolsOptions - Type Alias: SkillUpdateInput - Type Alias: SkillsCallOptions - Type Alias: SkillsConfig - Type Alias: SkillsManagerLike - Type Alias: SkillsStorageConfig - Type Alias: SkippedFileInfo - Type Alias: SlideContent - Type Alias: SlideFormattingConfig - Type Alias: SlideGenerationBatchResult - Type Alias: SlideGeneratorConfig - Type Alias: SlideLayout - Type Alias: SlideSchema - Type Alias: SlideType - Type Alias: SocketWorkerRuntime - Type Alias: SocketWorkerRuntimeOptions - Type Alias: SonioxMessage - Type Alias: SonioxToken - Type Alias: SpanAttributeValue - Type Alias: SpanAttributes - Type Alias: SpanContent - Type Alias: SpanData - Type Alias: SpanEvent - Type Alias: SpanLink - Type Alias: SpanModelRequest - Type Alias: SpanOptions - Type Alias: SpanProcessor - Type Alias: SpanScope - Type Alias: SpawnProxySocketWorkerOptions - Type Alias: SpeechGrammar - Type Alias: SpeechGrammarList - Type Alias: SpeechRecognitionErrorEventInternal - Type Alias: SpeechRecognitionEventInternal - Type Alias: SpeechRecognitionEventMap - Type Alias: SpeechRecognitionInternal - Type Alias: SpeechSanitizeOptions - Type Alias: SsrfGuardOptions - Type Alias: StabilityImageResponse - Type Alias: StandardError - Type Alias: StandardRecord - Type Alias: Statistic - Type Alias: StatusStats - Type Alias: StepResult\ - Type Alias: StepToolChoiceInput - Type Alias: StepToolResult - Type Alias: StorageConfig - Type Alias: StorageType - Type Alias: StoreConversationTurnOptions - Type Alias: StoredBodyArtifact - Type Alias: StoredCredentials - Type Alias: StoredOAuthTokens - Type Alias: StoredProviderTokens - Type Alias: StreamAnalyticsCollector - Type Alias: StreamAnalyticsData - Type Alias: StreamChannel\ - Type Alias: StreamChunk - Type Alias: StreamCommandArgs - Type Alias: StreamEventSequence - Type Alias: StreamEvents - Type Alias: StreamGenerationEndContext - Type Alias: StreamHandlerConfig - Type Alias: StreamLifecycleState - Type Alias: StreamLoopArgs - Type Alias: StreamNoOutputSentinel - Type Alias: StreamNoOutputSentinelResultLike - Type Alias: StreamOptions - Type Alias: StreamPhase - Type Alias: StreamResult - Type Alias: StreamSerializerAdapter - Type Alias: StreamTerminalOutcome - Type Alias: StreamTerminalOutcomeTracker - Type Alias: StreamTextResult - Type Alias: StreamToolCall - Type Alias: StreamToolResult - Type Alias: StreamingCapability - Type Alias: StreamingClientConfig - Type Alias: StreamingConfig - Type Alias: StreamingEventEmitter - Type Alias: StreamingMetadata - Type Alias: StreamingOptions - Type Alias: StreamingParser - Type Alias: StreamingProgressData - Type Alias: StreamingReaderOptions - Type Alias: StreamingRequestOptions - Type Alias: StringArray - Type Alias: StringRecord - Type Alias: StructuredError - Type Alias: StructuredRecoveryCandidate - Type Alias: StructuredRecoveryResult - Type Alias: StructuredRecoverySource - Type Alias: StylePreset - Type Alias: SubscriptionFeatures - Type Alias: SubscriptionInfo - Type Alias: SubscriptionInfoSummary - Type Alias: SubscriptionOptions - Type Alias: SummarizationPromptOptions - Type Alias: SummarizeConfig - Type Alias: SummarizeResult - Type Alias: SummarizedFile - Type Alias: SummaryExtractorConfig - Type Alias: SummaryStats - Type Alias: SupabaseConfig - Type Alias: SupervisedResult - Type Alias: SupervisionOptions - Type Alias: SupervisionPolicy - Type Alias: SupervisorAgentDefinition - Type Alias: SupportedFileTypeInfo - Type Alias: SupportedFormat - Type Alias: SupportedModelName - Type Alias: SupportedProvider - Type Alias: SuppressedVersion - Type Alias: SvgSanitizationResult - Type Alias: SyncFunction\ - Type Alias: SystemModelMessage - Type Alias: SystemPromptInjectorOptions - Type Alias: TTSAudioFormat - Type Alias: TTSChunk - Type Alias: TTSGender - Type Alias: TTSHandler - Type Alias: TTSHandlerTimeBudget - Type Alias: TTSMetadata - Type Alias: TTSOptions - ~~Type Alias: TTSProvider~~ - Type Alias: TTSProviderName - Type Alias: TTSQuality - Type Alias: TTSResult - ~~Type Alias: TTSStreamChunk~~ - Type Alias: TTSSynthesisMode - Type Alias: TTSVoice - Type Alias: TTSVoiceType - Type Alias: TableBorderOptions - Type Alias: TableCell - Type Alias: TableRow - Type Alias: Task - Type Alias: TaskAnalysis - Type Alias: TaskAssignment - Type Alias: TaskBackend - Type Alias: TaskBackendFactoryFn - Type Alias: TaskBackendName - Type Alias: TaskClassification - Type Alias: TaskCreateArgs - Type Alias: TaskDefinition - Type Alias: TaskDistributorConfig - Type Alias: TaskExecutionMode - Type Alias: TaskExecutorFn - Type Alias: TaskLogsArgs - Type Alias: TaskManagerConfig - Type Alias: TaskPriority - Type Alias: TaskQueueItem - Type Alias: TaskRetentionConfig - Type Alias: TaskRunError - Type Alias: TaskRunResult - Type Alias: TaskSchedule - Type Alias: TaskScheduleType - Type Alias: TaskStatus - Type Alias: TaskStore - Type Alias: TaskType - Type Alias: TaskUpdateArgs - Type Alias: TasksFile - Type Alias: TeamAnalyticsOptions - Type Alias: TeamAnalyticsResult - Type Alias: TeamMember - Type Alias: TelemetryAccumulator - Type Alias: TelemetryCommandArgs - Type Alias: TelemetryFlushArgs - Type Alias: TelemetryNativePrepareArgs - Type Alias: TelemetryNativeValidateArgs - Type Alias: TelemetryRecord - Type Alias: TelemetryStatsArgs - Type Alias: TelemetryStatusArgs - Type Alias: TerminalAgentModeOption - Type Alias: TerminalAgentModeVersion - Type Alias: TestFunction - Type Alias: TestResult - Type Alias: TextContent - Type Alias: TextElicitation - Type Alias: TextGenerationOptions - Type Alias: TextGenerationResult - Type Alias: TextPart - Type Alias: TextSegment - Type Alias: ThemeColors - Type Alias: ThemeFonts - Type Alias: ThemeOption - Type Alias: ThinkingConfig - Type Alias: ThinkingLevel - Type Alias: TierComparisonResult - Type Alias: TimeRangeOption - Type Alias: TimeWindowStats - Type Alias: TimelineItem - Type Alias: TimeoutCategory - Type Alias: TimeoutConfig - Type Alias: TimeoutInterceptorOptions - Type Alias: TimeoutResult\ - Type Alias: Timestamp - Type Alias: TitleExtractorConfig - Type Alias: TlsFingerprintOptions - Type Alias: TokenBucket - Type Alias: TokenBucketRateLimitConfig - Type Alias: TokenChunkerConfig - Type Alias: TokenClaims - Type Alias: TokenExchangeRequest - Type Alias: TokenExtractionConfig - Type Alias: TokenExtractionOptions - Type Alias: TokenExtractionStrategy - Type Alias: TokenPersistTarget - Type Alias: TokenRefreshResult - Type Alias: TokenRefresher - Type Alias: TokenResponse - Type Alias: TokenStorage - Type Alias: TokenStorageData - Type Alias: TokenStoreLockOwner - Type Alias: TokenType - Type Alias: TokenUsage - Type Alias: TokenUsageStats - Type Alias: TokenValidationConfig - Type Alias: TokenValidationResult - Type Alias: TokenValidator - Type Alias: ToneAdjustment - Type Alias: ToneOption - Type Alias: ToneShift - Type Alias: Tool\ - Type Alias: ToolAnnotationInfo - Type Alias: ToolApprovalRequest - Type Alias: ToolApprovalResponse - Type Alias: ToolArgs - Type Alias: ToolCall - Type Alias: ToolCallObject - Type Alias: ToolCallPart - Type Alias: ToolCallRepairFunction\ - Type Alias: ToolCallResult - Type Alias: ToolCallResults - Type Alias: ToolCalls - Type Alias: ToolChoice\ - Type Alias: ToolConfig - Type Alias: ToolContent - Type Alias: ToolContext - Type Alias: ToolConverterOptions - Type Alias: ToolDedupConfig - Type Alias: ToolDedupRemoved - Type Alias: ToolDedupResult\ - Type Alias: ToolDefinition\ - Type Alias: ToolDiscoveryResult - Type Alias: ToolEventPayload - Type Alias: ToolExecuteFunction\ - Type Alias: ToolExecuteRequest - Type Alias: ToolExecuteResponse - Type Alias: ToolExecution - Type Alias: ToolExecutionCaptureOptions - Type Alias: ToolExecutionContext - Type Alias: ToolExecutionEvent - Type Alias: ToolExecutionFunction\ - Type Alias: ToolExecutionGuards - Type Alias: ToolExecutionMetadata - Type Alias: ToolExecutionOptions - Type Alias: ToolExecutionRecord - Type Alias: ToolExecutionResult\ - Type Alias: ToolExecutionSummary - Type Alias: ToolExecutionSummaryInternal - Type Alias: ToolHistoryRow - Type Alias: ToolImplementation - Type Alias: ToolInfo - Type Alias: ToolMetadata - Type Alias: ToolMiddleware - Type Alias: ToolModelMessage - Type Alias: ToolNameResolution - Type Alias: ToolOutputPreviewOptions - Type Alias: ToolOutputPreviewResult - Type Alias: ToolParameterSchema - Type Alias: ToolPolicyResolutionInput - Type Alias: ToolPrimitive - Type Alias: ToolRegistrationOptions - Type Alias: ToolRegistryEntry - Type Alias: ToolRegistryEvents - Type Alias: ToolReplayMode - Type Alias: ToolReplayOutcome - Type Alias: ToolReplayStep - Type Alias: ToolResult\ - Type Alias: ToolResultData - Type Alias: ToolResultMetadata - Type Alias: ToolResultPart - Type Alias: ToolResultUsage - Type Alias: ToolRetrievalItem - Type Alias: ToolRetrievalRankedResult - Type Alias: ToolRetrievalSelectOptions - Type Alias: ToolRetrievalWeights - Type Alias: ToolRouterConfig - Type Alias: ToolRouterEvents - Type Alias: ToolRoutingCacheEntry - Type Alias: ToolRoutingCacheOptions - Type Alias: ToolRoutingCatalogEntry - Type Alias: ToolRoutingConfig - Type Alias: ToolRoutingDecision - Type Alias: ToolRoutingDecisionOutcome - Type Alias: ToolRoutingEmbeddingConfig - Type Alias: ToolRoutingModelConfig - Type Alias: ToolRoutingOutcome - Type Alias: ToolRoutingResolutionParams - Type Alias: ToolRoutingServerDescriptor - Type Alias: ToolRoutingStickiness - Type Alias: ToolSearchCriteria - Type Alias: ToolSearchResult - Type Alias: ToolSet - Type Alias: ToolUtilities - Type Alias: ToolValidationOptions - Type Alias: ToolValidationResult - Type Alias: ToolWithLegacyParams - Type Alias: ToolWrapperOptions - Type Alias: TopologyConfig - Type Alias: TopologyEdge - Type Alias: TopologyNode - Type Alias: TopologyStats - Type Alias: TopologyType - Type Alias: TraceContent - Type Alias: TraceView - Type Alias: TrackedConnection - Type Alias: TranscribeAudioInput - Type Alias: TranscribeDeps - Type Alias: TranscribeOptions - Type Alias: TranscribeResult - Type Alias: TranscribeStreamCorrectedEvent - Type Alias: TranscribeStreamEvent - Type Alias: TranscribeStreamFinalEvent - Type Alias: TranscribeStreamOptions - Type Alias: TranscribeStreamOutputEvent - Type Alias: TranscribeTimings - Type Alias: TranscriptionSegment - Type Alias: TranscriptionSessionEvent - Type Alias: TranscriptionSessionOptions - Type Alias: TranscriptionSubscriberOptions - Type Alias: TranscriptionSubscription - Type Alias: TransferableProxySocket - Type Alias: TransformFunction\ - Type Alias: TransientRateLimitRetryBudget - Type Alias: TransitionResult - Type Alias: TransportResult - Type Alias: TransportWithProcessResult - Type Alias: TrendAnalysis - Type Alias: TripwireAction - Type Alias: TripwireConfig - Type Alias: TripwireData - Type Alias: TripwireResult - ~~Type Alias: TruncateOptions~~ - ~~Type Alias: TruncateResult~~ - Type Alias: TruncationConfig - Type Alias: TruncationResult - Type Alias: TurnMessageIdentity - Type Alias: UnifiedGenerationOptions - Type Alias: UnifiedMCPRegistry - Type Alias: UnifiedTool - Type Alias: Unknown - Type Alias: UnknownArray - Type Alias: UnknownRecord - Type Alias: UnsupportedFileError - Type Alias: UpdateCheckResult - Type Alias: UpdateState - Type Alias: UpdaterWorkerSupervisor - Type Alias: UpdaterWorkerSupervisorOptions - Type Alias: UpsertableVectorStore - Type Alias: UpstreamAttemptContext - Type Alias: UsageContext - Type Alias: UsageQuota - Type Alias: UseAgentOptions - Type Alias: UseAgentReturn - Type Alias: UseCaseSuitability - Type Alias: UseChatOptions - Type Alias: UseChatReturn - Type Alias: UseStreamOptions - Type Alias: UseStreamReturn - Type Alias: UseToolsOptions - Type Alias: UseToolsReturn - Type Alias: UseVoiceOptions - Type Alias: UseVoiceReturn - Type Alias: UseWorkflowOptions - Type Alias: UseWorkflowReturn - Type Alias: UserContent - Type Alias: UserModelMessage - Type Alias: UtilityToolsMap - Type Alias: ValidateInstalledVersionOptions - Type Alias: ValidationConfig - Type Alias: ValidationErrorInfo - Type Alias: ValidationErrorPayload - Type Alias: ValidationFunction\ - Type Alias: ValidationIssue - Type Alias: ValidationIssues - Type Alias: ValidationResult - Type Alias: ValidationSchema - Type Alias: VectorProviderOptions - Type Alias: VectorQueryResponse - Type Alias: VectorQueryResult - Type Alias: VectorQueryToolConfig - Type Alias: VectorStore - Type Alias: VertexAccessTokenProvider - Type Alias: VertexAnthropicAuthClient - Type Alias: VertexAnthropicCacheControl - Type Alias: VertexAnthropicCacheInput - Type Alias: VertexAnthropicCacheOutput - Type Alias: VertexAnthropicContentBlock - Type Alias: VertexAnthropicMessage - Type Alias: VertexAnthropicPassthroughRequest - Type Alias: VertexAnthropicPassthroughTarget - Type Alias: VertexAnthropicSystemBlock - Type Alias: VertexAnthropicTool - Type Alias: VertexGenaiFunctionDeclaration - Type Alias: VertexNativeLoopPart - Type Alias: VertexNativePart - Type Alias: VertexOperationResult - Type Alias: VertexPassthroughTerminal - Type Alias: VertexRegularSegment - Type Alias: VertexSegment - Type Alias: VertexToolStep - Type Alias: VertexUsageCounter - Type Alias: VideoContent - Type Alias: VideoDeliveryDecision - Type Alias: VideoGenerateOptions - Type Alias: VideoGenerationResult - Type Alias: VideoHandler - Type Alias: VideoKeyframe - Type Alias: VideoOutputOptions - Type Alias: VideoProcessorOptions - Type Alias: VideoProviderConfig - Type Alias: VideoProviderName - Type Alias: VideoSaveResult - Type Alias: VideoTransitionOptions - Type Alias: VisionCapability - Type Alias: VisionImageConversion - Type Alias: VisionImageOutputFormat - Type Alias: VisionTranscodeOptions - Type Alias: VoiceCapability - Type Alias: VoiceErrorOptions - Type Alias: VoiceEvent\ - Type Alias: VoiceEventType - Type Alias: VoiceHandler - Type Alias: VoiceMemoryBinding - Type Alias: VoiceMemoryBindingInput - Type Alias: VoiceMemoryBindingRejection - Type Alias: VoiceMemoryBindingVerdict - Type Alias: VoiceMemoryBindingVerifyInput - Type Alias: VoiceProviderConfig - Type Alias: VoiceProviderName - Type Alias: VoiceProviderType - Type Alias: VoiceResult - Type Alias: VoiceServerArgs - Type Alias: VoiceTurn - Type Alias: VoiceTurnClosedExchange - Type Alias: VoiceTurnOpenExchange - Type Alias: VoiceTurnRecord - Type Alias: VoiceTurnRecorder - Type Alias: VoiceTurnRecorderOptions - Type Alias: VoiceTurnRecorderStats - ~~Type Alias: VoiceType~~ - Type Alias: VoyageEmbeddingsResponse - Type Alias: WSClientConfig - Type Alias: WSClientEventHandlers - Type Alias: WSClientMessage - Type Alias: WSClientState - Type Alias: WebLoaderOptions - Type Alias: WebSocketConfig - Type Alias: WebSocketConnection - Type Alias: WebSocketEventHandlers - Type Alias: WebSocketHandler - Type Alias: WebSocketMessage - Type Alias: WebSocketMessageType - Type Alias: WebSocketRequestId - Type Alias: WhisperModel - Type Alias: WhisperSTTOptions - Type Alias: WhisperSimpleResponse - Type Alias: WhisperTranscriptionSegment - Type Alias: WhisperTranscriptionWord - Type Alias: WhisperVerboseResponse - Type Alias: WhistleAsset - Type Alias: WhistleAssetName - Type Alias: WhistleAssetPaths - Type Alias: WhistleEngineOutput - Type Alias: WhistleNeedleFactory - Type Alias: WhistleNeedleModule - Type Alias: WhistleStreamStep - Type Alias: WhistleWord - Type Alias: WhistleWorkerData - Type Alias: WhistleWorkerOutgoing\ - Type Alias: WhistleWorkerRequest - Type Alias: WhistleWorkerResponse - Type Alias: WordTiming - Type Alias: WorkOSConfig - Type Alias: WorkerInstanceOptions - Type Alias: WorkerLogEvent - Type Alias: WorkerState - Type Alias: WorkflowAnalytics - Type Alias: WorkflowComparison - Type Alias: WorkflowConfig - Type Alias: WorkflowErrorDetails - Type Alias: WorkflowEvaluationData - Type Alias: WorkflowExecutionMetrics - Type Alias: WorkflowGenerateOptions - Type Alias: WorkflowInput - Type Alias: WorkflowMetadata - Type Alias: WorkflowModelConfig - Type Alias: WorkflowPrimitive - Type Alias: WorkflowResult - Type Alias: WorkflowStreamChunk - Type Alias: WorkflowTestCase - Type Alias: WorkflowType - Type Alias: WorkflowValidation\ - Type Alias: WorkflowValidationError - Type Alias: WorkflowValidationResult - Type Alias: WorkflowValidationWarning - Type Alias: XaiObservedSession - Type Alias: XaiResponseUsage - Type Alias: YamlModule - Type Alias: Zod4DiscriminatedUnionDefinition - Type Alias: Zod4NativeParams - Type Alias: Zod4NativeTarget - Type Alias: Zod4ObjectDefinition - Type Alias: Zod4OverrideContext - Type Alias: ZodAnySchema - Type Alias: ZodObjectSchema - Type Alias: ZodStringSchema - Type Alias: ZodToJsonSchemaInput - Type Alias: ZodUnknownSchema ### Assets - Proxy dashboard accounting ### Connectors - Connector Catalog - Automatic - Tara - Yama ### Implementation Guides - RAG Document Processing - Implementation Guide ### Playground - Interactive Playground ### Provider Integration - 00 · Native Provider Architecture - ADR-0001: `ProviderDescriptor` is the single source of truth for provider identity - Provider Manifests - Abliteration source pilot - Provider Onboarding Tiers - 01 · Shared Changes (Touch Once for All Four Providers) - ADR-0002: OpenAI-wire-compatible providers default to a catalog row, not a subclass - AIHubMix text and streaming pilot - Tier 1 — Aggregator Passthrough - DeepSeek Native Provider - ADR-0003: Mocked-fetch contract tests are the CI merge gate; live-API suites are not - LongCat text and streaming source pilot - Tier 2 — Catalog Entry - NVIDIA NIM Native Provider - Architecture Decision Records — Provider Onboarding Redesign - NAVER CLOVA Studio source pilot - Tier 3 — Adapter-Based Native - LM Studio Native Provider - RunInfra text and streaming source pilot - Tier 4 — Full Custom - llama.cpp Native Provider - Xiaomi MiMo text and streaming pilot - 06 · Testing Strategy - 07 · Implementation Order & Milestones - 08 · Provider × Feature Support Matrix - 09 · Test Suite Specification - FINAL — After exhaustive 13-iteration debugging - Investigation: 4 Real Sub-Test Failures Drilled - PR Analysis & Commit Plan - Self Code Review (agent rate-limited; reviewed manually) - 14 · Voice / Speech Integration — Implementation Journal - 15 · Adding a New LLM Provider — superseded by the tiered guide - 16 · Adding a New TTS Provider — Exhaustive Guide - 17 · Adding a New STT Provider — Exhaustive Guide - 18 · Adding a New Realtime (Bidirectional Voice) Provider — Exhaustive Guide - 19 · Adding a New Video Provider — Exhaustive Guide - 20 · Adding a New Image-Generation Provider — Exhaustive Guide - 21 · Adding a New Modality (Avatar, Music, etc.) — Exhaustive Guide - 22 · Adding a Multi-Modal Provider (Replicate-style) — Exhaustive Guide - Provider / Modality Integration Checklist - Provider Integration Documentation - Safety Primitives Reference - Credential-free provider acceptance gate - Catalog authoring and admission - Provider Descriptor Migration Ledger - OpenAI-Compatible Provider Catalog ### Rag - RAG Processing - CLI Reference - RAG Processing - Configuration Guide - RAG Processing - Testing Guide - RAG Processing - Manual Verification Checklist ### Research - AI SDK Dependency Upgrade Research - AWS SDK Package Upgrade Research - Codebase Compatibility Analysis for Dependency Upgrades - Core Libraries Upgrade Research - Dev Dependencies Upgrade Research ### Security - Subpackage Dependency Advisories ### Skills - NeuroLink Usage Guide - NeuroLink Advanced Features - NeuroLink CLI Reference - NeuroLink Conversation Memory - NeuroLink Multimodal Support - NeuroLink Provider Configuration - NeuroLink RAG Integration - NeuroLink SDK Quickstart - NeuroLink MCP Tools Integration ### Superpowers - Proxy Cost & Budget dashboard enrichment — design - Fallback Context Truncation Design - Proxy Account Routing Policies Design - Codex Outbound Fallback — Design --- # Introduction ## NeuroLink NeuroLink The Pipe Layer of an AI Nervous System Provider Neurons Across Major AI Vendors | 3 Inference Types (generate · stream · decide) | Voice (TTS/STT/Realtime) | 58+ MCP Servers | HITL Security | Redis Persistence [[Image: npm version]](https://www.npmjs.com/package/@juspay/neurolink) [[Image: npm downloads]](https://www.npmjs.com/package/@juspay/neurolink) [[Image: Build Status]](https://github.com/juspay/neurolink/actions/workflows/ci.yml) [[Image: Coverage Status]](https://coveralls.io/github/juspay/neurolink?branch=main) [[Image: License: MIT]](https://opensource.org/licenses/MIT) [[Image: TypeScript]](https://www.typescriptlang.org/) [[Image: GitHub Stars]](https://github.com/juspay/neurolink/stargazers) NeuroLink is the pipe layer of an AI nervous system: one interface connecting provider neurons — major AI vendors and local runtimes — to the applications that consume them. Built-in tooling and an opinionated factory architecture mean adding a new provider, or a new capability, never touches application code. NeuroLink ships as both a TypeScript SDK and a professional CLI so teams can build, operate, and iterate on AI features quickly. ## What is NeuroLink? **NeuroLink is the pipe layer of an AI nervous system.** Providers — OpenAI, Anthropic, Google, AWS, Azure, DeepSeek, NVIDIA NIM, local runtimes like Ollama and llama.cpp, and dozens more — are the neurons: each generates a different kind of intelligence, at a different cost and latency. NeuroLink is the vascular layer that carries that intelligence, as a stream, to the applications that consume it, across three inference types: `generate` and `stream` produce text, `decide` produces a calibrated `boolean`/`choice`/`score` judgment instead. Extracted from production systems at Juspay, NeuroLink provides a practical, TypeScript-first way to plug any application into that nervous system. Switch which neuron answers a request with a single parameter change — any provider you're building with, or any provider you add. **Why NeuroLink?** Three genuine inference types, not one dressed up three ways — `generate` and `stream` produce text, while **`decide` returns a typed, calibrated judgment** (`boolean` / `choice` / `score`) with no text at all, for the routing and gating decisions the other two were never meant to make. Every neuron plugs into the same pipe. Switch providers with a single parameter change, leverage 64+ built-in tools and MCP servers, deploy with confidence using enterprise features like Redis memory and multi-provider failover, and optimize costs automatically with intelligent routing. Use it via our professional CLI or TypeScript SDK—whichever fits your workflow. **Where we're headed:** We're building for the future of AI—edge-first execution and continuous streaming architectures that make AI practically free and universally available. **[Read our vision →](/docs/about/vision)** **[Get Started in \ [Observability Guide](/docs/features/observability) - **Server Adapters** -- Deploy NeuroLink as an HTTP API server with your framework of choice (Hono, Express, Fastify, Koa). Full CLI support with `serve` and `server` commands for foreground/background modes, route management, and OpenAPI generation. -> [Server Adapters Guide](/docs/guides/server-adapters) - **Title Generation Events** -- Emit real-time events when conversation titles are auto-generated. Listen to `conversation:titleGenerated` for session tracking. -> [Conversation Memory Guide](/docs/memory/conversation) - **Custom Title Prompts** -- Customize conversation title generation with `NEUROLINK_TITLE_PROMPT` environment variable. Use `${userMessage}` placeholder for dynamic prompts. -> [Conversation Memory Guide](/docs/memory/conversation) - **Video Generation** -- Transform images into 8-second videos with synchronized audio using Google Veo 3.1 via Vertex AI. Supports 720p/1080p resolutions, portrait/landscape aspect ratios. -> [Video Generation Guide](/docs/features/video-generation) - **Image Generation** -- Generate images from text prompts using Gemini models via Vertex AI or Google AI Studio. Supports streaming mode with automatic file saving. -> [Image Generation Guide](/docs/features/image-generation) - **HTTP/Streamable HTTP Transport for MCP** -- Connect to remote MCP servers via HTTP with authentication headers, retry logic, and rate limiting. -> [HTTP Transport Guide](/docs/mcp/http-transport) - **Claude Subscription (OAuth) Support** -- Use your Claude Pro/Max/Team subscription with NeuroLink via OAuth authentication, no API key required. -> [Subscription Guide](/docs/features/claude-subscription) - **Gemini 3 Preview Support** - Full support for gemini-3-flash-preview and gemini-3-pro-preview with extended thinking capabilities - **Structured Output with Zod Schemas** -- Type-safe JSON generation with automatic validation using `schema` + `output.format: "json"` in `generate()`. -> [Structured Output Guide](/docs/cookbook/structured-output) - **CSV File Support** -- Attach CSV files to prompts for AI-powered data analysis with auto-detection. -> [CSV Guide](/docs/features/multimodal-chat.md#csv-file-support) - **PDF File Support** -- Process PDF documents with native visual analysis for Vertex AI, Anthropic, Bedrock, AI Studio. -> [PDF Guide](/docs/features/pdf-support) - **50+ File Types** -- Process Excel, Word, RTF, JSON, YAML, XML, HTML, SVG, Markdown, and 50+ code languages with intelligent content extraction. -> [File Processors Guide](/docs/features/file-processors) - **LiteLLM Integration** -- Access 100+ AI models across a broad range of AI providers through unified interface. -> [Setup Guide](/docs/getting-started/providers/litellm) - **SageMaker Integration** -- Deploy and use custom trained models on AWS infrastructure. -> [Setup Guide](/docs/getting-started/providers/sagemaker) - **OpenRouter Integration** -- Access 300+ models from OpenAI, Anthropic, Google, Meta, and more through a single unified API. -> [Setup Guide](/docs/getting-started/providers/openrouter) - **Human-in-the-loop workflows** -- Pause generation for user approval/input before tool execution. -> [HITL Guide](/docs/features/hitl) - **Guardrails middleware** -- Block PII, profanity, and unsafe content with built-in filtering. -> [Guardrails Guide](/docs/features/guardrails) - **Context summarization** -- Automatic conversation compression for long-running sessions. -> [Summarization Guide](/docs/memory/summarization) - **Redis conversation export** -- Export full session history as JSON for analytics and debugging. -> [History Guide](/docs/features/conversation-history) ```typescript // Multi-Model Workflow Engine (v8.42.0) NeuroLink, runWorkflow, CONSENSUS_3_WORKFLOW, } from "@juspay/neurolink"; const neurolink = new NeuroLink(); // Run a consensus workflow with multiple models const result = await runWorkflow(CONSENSUS_3_WORKFLOW, { prompt: "Explain quantum computing", }); console.log(result.content); // Best response selected by judge console.log(result.score); // Quality score (0-100) console.log(result.totalTime); // Total workflow time in ms // Image Generation with Gemini (v8.31.0) const image = await neurolink.generate({ input: { text: "A futuristic cityscape" }, provider: "google-ai", model: "gemini-2.5-flash-image", }); console.log(image.imageOutput?.base64); // Base64-encoded PNG // HTTP Transport for Remote MCP (v8.29.0) await neurolink.addExternalMCPServer("remote-tools", { transport: "http", url: "https://mcp.example.com/v1", headers: { Authorization: "Bearer token" }, retries: 3, timeout: 15000, }); ``` --- Previous Updates (Q4 2025) - **Image Generation** – Generate images from text prompts using Gemini models via Vertex AI or Google AI Studio. → [Guide](/docs/features/image-generation) - **Gemini 3 Preview Support** - Full support for `gemini-3-flash-preview` and `gemini-3-pro-preview` with extended thinking - **Structured Output with Zod Schemas** – Type-safe JSON generation with automatic validation. → [Guide](/docs/cookbook/structured-output) - **CSV & PDF File Support** – Attach CSV/PDF files to prompts with auto-detection. → [CSV](/docs/features/multimodal-chat.md#csv-file-support) | [PDF](/docs/features/pdf-support) - **LiteLLM & SageMaker** – Access 100+ models via LiteLLM, deploy custom models on SageMaker. → [LiteLLM](/docs/getting-started/providers/litellm) | [SageMaker](/docs/getting-started/providers/sagemaker) - **OpenRouter Integration** – Access 300+ models through a single unified API. → [Guide](/docs/getting-started/providers/openrouter) - **HITL & Guardrails** – Human-in-the-loop approval workflows and content filtering middleware. → [HITL](/docs/features/hitl) | [Guardrails](/docs/features/guardrails) - **Redis & Context Management** – Session export, conversation history, and automatic summarization. → [History](/docs/features/conversation-history) ## Enterprise Security: Human-in-the-Loop (HITL) NeuroLink includes a **HITL (Human-in-the-Loop) system** that pauses a tool call until your application approves or rejects it, for high-stakes AI operations: | Capability | Description | Use Case | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | | **Tool Approval Workflows** | Pause tools whose name matches `dangerousActions`, or that a `customRules` condition selects, until your app answers | Financial transactions, data modifications | | **Argument Review** | A response can carry `modifiedArguments` and the tool runs with them. `allowArgumentModification` only tells your UI (`allowModification`); NeuroLink does not enforce it | Correcting a path or amount before it runs | | **Timeout Policy** | Reject when nobody answers (default) or auto-approve, with `autoApproveExclusions` for tools that always need an answer | Unattended and background runs | | **Audit Logging** | `auditLogging: true` writes each request and decision, with the full tool arguments, to the NeuroLink logger; it is a log, not a compliance control | Debugging and your own review records | ```typescript NeuroLink, type ConfirmationRequestEvent, type ConfirmationResponseEvent, } from "@juspay/neurolink"; const neurolink = new NeuroLink({ hitl: { enabled: true, // Case-insensitive substring match against the tool name dangerousActions: ["writeFile", "executeCode", "sendEmail"], timeout: 30000, // Rejects if nobody answers within 30 seconds }, }); // Approval is event-based: NeuroLink emits a request, your app answers it const emitter = neurolink.getEventEmitter(); emitter.on("hitl:confirmation-request", async (event) => { const receivedAt = Date.now(); // The emitter types listener arguments as unknown, so narrow the event const { payload } = event as ConfirmationRequestEvent; const { confirmationId, toolName, arguments: args } = payload; // Integrate with your approval system (UI prompt, Slack, ticketing) const approved = await yourApprovalSystem.requestReview({ toolName, args }); emitter.emit("hitl:confirmation-response", { type: "hitl:confirmation-response", payload: { confirmationId, approved, reason: approved ? undefined : "Rejected by reviewer", metadata: { timestamp: new Date().toISOString(), responseTime: Date.now() - receivedAt, // ms since the request arrived }, }, } satisfies ConfirmationResponseEvent); }); // A tool call to a matching tool pauses until your handler answers const result = await neurolink.generate({ input: { text: "Send quarterly report to stakeholders" }, }); ``` The [Enterprise HITL Guide](/docs/features/enterprise-hitl) also sketches a larger target API (`requireApproval`, `reviewCallback`, `confidenceThreshold`, asynchronous review, escalation policies). None of it is implemented yet, and NeuroLink drops unknown `hitl` keys without an error. See [#752](https://github.com/juspay/neurolink/issues/752). **[Enterprise HITL Guide](/docs/features/enterprise-hitl)** | **[Quick Start](/docs/features/hitl)** ## Get Started in Two Steps ```bash # 1. Run the interactive setup wizard (select providers, validate keys) pnpm dlx @juspay/neurolink setup # 2. Start generating with automatic provider selection npx @juspay/neurolink generate "Write a launch plan for multimodal chat" ``` Need a persistent workspace? Launch loop mode with `npx @juspay/neurolink loop` - [Learn more →](/docs/features/cli-loop-sessions) ## Complete Feature Set NeuroLink is a comprehensive AI development platform. Every feature below is available today and fully documented. ### AI Provider Integration **Provider neurons behind one API** - Switch providers with a single parameter change. | Provider | Models | Free Tier | Tool Support | Status | Documentation | | --------------------- | -------------------------------------------------- | --------------- | ------------ | ------------- | ------------------------------------------------------------------------------------------------------------------- | | **OpenAI** | GPT-4o, GPT-4o-mini, o1 | ❌ | ✅ Full | ✅ Production | [Setup Guide](/docs/getting-started/provider-setup.md#openai) | | **Anthropic** | Claude 4.5 Opus/Sonnet/Haiku, Claude 4 Opus/Sonnet | ❌ | ✅ Full | ✅ Production | [Setup Guide](/docs/getting-started/provider-setup.md#anthropic) \| [Subscription Guide](/docs/features/claude-subscription) | | **Google AI Studio** | Gemini 3 Flash/Pro, Gemini 2.5 Flash/Pro | ✅ Free Tier | ✅ Full | ✅ Production | [Setup Guide](/docs/getting-started/provider-setup.md#google-ai) | | **AWS Bedrock** | Claude, Titan, Llama, Nova | ❌ | ✅ Full | ✅ Production | [Setup Guide](/docs/getting-started/provider-setup.md#bedrock) | | **Google Vertex** | Gemini 3/2.5 (gemini-3-\*-preview) | ❌ | ✅ Full | ✅ Production | [Setup Guide](/docs/getting-started/provider-setup.md#vertex) | | **Azure OpenAI** | GPT-4, GPT-4o, o1 | ❌ | ✅ Full | ✅ Production | [Setup Guide](/docs/getting-started/provider-setup.md#azure) | | **LiteLLM** | 100+ models unified | Varies | ✅ Full | ✅ Production | [Setup Guide](/docs/getting-started/providers/litellm) | | **AWS SageMaker** | Custom deployed models | ❌ | ✅ Full | ✅ Production | [Setup Guide](/docs/getting-started/providers/sagemaker) | | **Mistral AI** | Mistral Large, Small | ✅ Free Tier | ✅ Full | ✅ Production | [Setup Guide](/docs/getting-started/provider-setup.md#mistral) | | **Hugging Face** | 100,000+ models | ✅ Free | ⚠️ Partial | ✅ Production | [Setup Guide](/docs/getting-started/provider-setup.md#huggingface) | | **Ollama** | Local models (Llama, Mistral) | ✅ Free (Local) | ⚠️ Partial | ✅ Production | [Setup Guide](/docs/getting-started/provider-setup.md#ollama) | | **OpenAI Compatible** | Any OpenAI-compatible endpoint | Varies | ✅ Full | ✅ Production | [Setup Guide](/docs/getting-started/provider-setup.md#openai-compatible) | | **OpenRouter** | 200+ Models via OpenRouter | Varies | ✅ Full | ✅ Production | [Setup Guide](/docs/getting-started/providers/openrouter) | This table highlights the most commonly used providers. NeuroLink also ships DeepSeek, NVIDIA NIM, LM Studio, llama.cpp, xAI, Groq, Cerebras, SambaNova, Together AI, Fireworks, Perplexity, Cloudflare, Cohere, Voyage AI, Jina AI, Stability AI, Ideogram, Recraft, Replicate, plus TypeSafe Jev, Laya, XOR, SubQ, Perplexity Decisions, Cloudflare Clef, OpenAI Decisions and ScaleDown (the `decide()`-only providers for typed, calibrated decisions) and the full voice/media roster — see the [Provider Guides index](/docs/) for the full roster. **[ Provider Comparison Guide](/docs/reference/provider-comparison)** - Detailed feature matrix and selection criteria **[ Provider Feature Compatibility](/docs/reference/provider-feature-compatibility)** - Test-based compatibility reference for 19 features (dated snapshot covering a subset of the full provider list) --- ### Built-in Tools & MCP Integration **6 Core Tools** (work across supported providers, zero configuration): | Tool | Purpose | Auto-Available | Documentation | | -------------------- | ------------------------ | ----------------------- | ------------------------------------- | | `getCurrentTime` | Real-time clock access | ✅ | [Tool Reference](/docs/sdk/custom-tools) | | `readFile` | File system reading | ✅ | [Tool Reference](/docs/sdk/custom-tools) | | `writeFile` | File system writing | ✅ | [Tool Reference](/docs/sdk/custom-tools) | | `listDirectory` | Directory listing | ✅ | [Tool Reference](/docs/sdk/custom-tools) | | `calculateMath` | Mathematical operations | ✅ | [Tool Reference](/docs/sdk/custom-tools) | | `websearchGrounding` | Google Vertex web search | ⚠️ Requires credentials | [Tool Reference](/docs/sdk/custom-tools) | **58+ External MCP Servers** supported (GitHub, PostgreSQL, Google Drive, Slack, and more): ```typescript // stdio transport - local MCP servers via command execution await neurolink.addExternalMCPServer("github", { command: "npx", args: ["-y", "@modelcontextprotocol/server-github"], transport: "stdio", env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN }, }); // HTTP transport - remote MCP servers via URL await neurolink.addExternalMCPServer("github-copilot", { transport: "http", url: "https://api.githubcopilot.com/mcp", headers: { Authorization: "Bearer YOUR_COPILOT_TOKEN" }, timeout: 15000, retries: 5, }); // Tools automatically available to AI const result = await neurolink.generate({ input: { text: 'Create a GitHub issue titled "Bug in auth flow"' }, }); ``` **MCP Transport Options:** | Transport | Use Case | Key Features | | ----------- | -------------- | ----------------------------------------------- | | `stdio` | Local servers | Command execution, environment variables | | `http` | Remote servers | URL-based, auth headers, retries, rate limiting | | `sse` | Event streams | Server-Sent Events, real-time updates | | `websocket` | Bi-directional | Full-duplex communication | **[ MCP Integration Guide](/docs/mcp/integration)** - Setup external servers **[ HTTP Transport Guide](/docs/mcp/http-transport)** - Remote MCP server configuration --- ### Developer Experience Features **SDK-First Design** with TypeScript, IntelliSense, and type safety: | Feature | Description | Documentation | | --------------------------- | ------------------------------------------------------------- | ---------------------------------------------------- | | **Auto Provider Selection** | Intelligent provider fallback | [SDK Guide](/docs/sdk/index.md#auto-selection) | | **Streaming Responses** | Real-time token streaming | [Streaming Guide](/docs/advanced/streaming) | | **Conversation Memory** | Automatic context management | [Memory Guide](/docs/sdk/index.md#memory) | | **Full Type Safety** | Complete TypeScript types | [Type Reference](/docs/sdk/api-reference) | | **Error Handling** | Graceful provider fallback | [Error Guide](/docs/reference/troubleshooting) | | **Analytics & Evaluation** | Usage tracking, quality scores | [Analytics Guide](/docs/reference/analytics) | | **Middleware System** | Request/response hooks | [Middleware Guide](/docs/workflows/custom-middleware) | | **Framework Integration** | Next.js, SvelteKit, Express | [Framework Guides](/docs/sdk/framework-integration) | | **Extended Thinking** | Native thinking/reasoning mode for Gemini 3 and Claude models | [Thinking Guide](/docs/features/thinking-configuration) | --- ### Multimodal & File Processing **17 file processors across 6 categories** (50+ total file types including code languages) with intelligent content extraction and provider-agnostic processing: | Category | Supported Types | Processing | | ------------- | ---------------------------------------------------------- | ----------------------------------- | | **Documents** | Excel (`.xlsx`, `.xls`), Word (`.docx`), RTF, OpenDocument | Sheet extraction, text extraction | | **Data** | JSON, YAML, XML | Validation, syntax highlighting | | **Markup** | HTML, SVG, Markdown, Text | OWASP-compliant sanitization | | **Code** | 50+ languages (TypeScript, Python, Java, Go, etc.) | Language detection, syntax metadata | | **Config** | `.env`, `.ini`, `.toml`, `.cfg` | Secure parsing | | **Media** | Images (PNG, JPEG, WebP, GIF), PDFs, CSV | Provider-specific formatting | ```typescript // Process any supported file type const result = await neurolink.generate({ input: { text: "Analyze this data and code", files: [ "./data.xlsx", // Excel spreadsheet "./config.yaml", // YAML configuration "./diagram.svg", // SVG (injected as sanitized text) "./main.py", // Python source code ], }, }); // CLI: Use --file for any supported type // neurolink generate "Analyze this" --file ./report.xlsx --file ./config.json ``` **Key Features:** - **ProcessorRegistry** - Priority-based processor selection with fallback - **OWASP Security** - HTML/SVG sanitization prevents XSS attacks - **Auto-detection** - FileDetector identifies file types by extension and content - **Provider-agnostic** - Processors work across supported AI providers **[ File Processors Guide](/docs/features/file-processors)** - Complete reference for all file types --- ### Enterprise & Production Features **Capabilities for regulated industries:** | Feature | Description | Use Case | Documentation | | --------------------------- | ---------------------------------- | ------------------------- | ------------------------------------------------------ | | **Enterprise Proxy** | Corporate proxy support | Behind firewalls | [Proxy Setup](/docs/deployment/enterprise-proxy) | | **Redis Memory** | Distributed conversation state | Multi-instance deployment | [Redis Guide](/docs/getting-started/provider-setup.md#redis) | | **Cost Optimization** | Automatic cheapest model selection | Budget control | [Cost Guide](/docs/) | | **Multi-Provider Failover** | Automatic provider switching | High availability | [Failover Guide](/docs/) | | **Telemetry & Monitoring** | OpenTelemetry integration | Observability | [Telemetry Guide](/docs/observability/telemetry) | | **Security Hardening** | Credential management, auditing | Compliance | [Security Guide](/docs/guides/enterprise) | | **Custom Model Hosting** | SageMaker integration | Private models | [SageMaker Guide](/docs/getting-started/providers/sagemaker) | | **Load Balancing** | LiteLLM proxy integration | Scale & routing | [Load Balancing](/docs/getting-started/providers/litellm) | **Security & Compliance:** - ✅ Deployable within SOC 2 Type II environments — NeuroLink itself is not audited or certified - ✅ Deployable on ISO 27001-certified infrastructure — that certification is your infrastructure's, not NeuroLink's - ✅ GDPR-conscious data handling (EU-region providers selectable; you own compliance) - ✅ Deployable in HIPAA-aligned configurations — you are responsible for a compliant setup - ✅ Hardened OS verified (SELinux, AppArmor) - ✅ Zero credential logging - ✅ Encrypted configuration storage - ✅ Automatic context window management with 5-stage compaction pipeline and 80% budget gate **[ Enterprise Deployment Guide](/docs/guides/enterprise)** - Complete production checklist --- ## Enterprise Persistence: Redis Memory Distributed conversation state for multi-instance deployments: ### Capabilities | Feature | Description | Benefit | | ---------------------- | -------------------------------------------- | --------------------------- | | **Distributed Memory** | Share conversation context across instances | Horizontal scaling | | **Session Export** | Export full history as JSON | Analytics, debugging, audit | | **Auto-Detection** | Automatic Redis discovery from environment | Zero-config in containers | | **Graceful Failover** | Falls back to in-memory if Redis unavailable | High availability | | **TTL Management** | Configurable session expiration | Memory management | ### Quick Setup ```typescript // Auto-detect Redis from REDIS_URL environment variable const neurolink = new NeuroLink({ conversationMemory: { enabled: true, store: "redis", // Automatically uses REDIS_URL ttl: 86400, // 24-hour session expiration }, }); // Or explicit configuration const neurolinkExplicit = new NeuroLink({ conversationMemory: { enabled: true, store: "redis", redis: { host: "redis.example.com", port: 6379, password: process.env.REDIS_PASSWORD, tls: true, // Enable for production }, }, }); // Export conversation for analytics const history = await neurolink.exportAllSessions(undefined, { format: "json", }); await saveToDataWarehouse(history); ``` ### Docker Quick Start ```bash # Start Redis docker run -d --name neurolink-redis -p 6379:6379 redis:7-alpine # Configure NeuroLink export REDIS_URL=redis://localhost:6379 # Start your application node your-app.js ``` **[Redis Setup Guide](/docs/getting-started/redis-quickstart)** | **[Production Configuration](/docs/guides/redis-configuration)** | **[Migration Patterns](/docs/guides/redis-migration)** --- ### Professional CLI **34 commands** for every workflow: | Command | Purpose | Example | Documentation | | ---------------- | ------------------------------------ | -------------------------- | ------------------------------------------- | | `setup` | Interactive provider configuration | `neurolink setup` | [Setup Guide](/docs/) | | `generate` | Text generation | `neurolink gen "Hello"` | [Generate](/docs/cli/commands.md#generate) | | `stream` | Streaming generation | `neurolink stream "Story"` | [Stream](/docs/cli/commands.md#stream) | | `status` | Provider health check | `neurolink status` | [Status](/docs/cli/commands.md#status) | | `loop` | Interactive session | `neurolink loop` | [Loop](/docs/cli/commands.md#loop) | | `mcp` | MCP server management | `neurolink mcp discover` | [MCP CLI](/docs/cli/commands.md#mcp) | | `models` | Model listing | `neurolink models` | [Models](/docs/cli/commands.md#models) | | `eval` | Model evaluation | `neurolink eval` | [Eval](/docs/cli/commands.md#eval) | | `serve` | Start HTTP server in foreground mode | `neurolink serve` | [Serve](/docs/cli/commands.md#serve) | | `server start` | Start HTTP server in background mode | `neurolink server start` | [Server](/docs/cli/commands.md#server-subcommand) | | `server stop` | Stop running background server | `neurolink server stop` | [Server](/docs/cli/commands.md#server-subcommand) | | `server status` | Show server status information | `neurolink server status` | [Server](/docs/cli/commands.md#server-subcommand) | | `server routes` | List all registered API routes | `neurolink server routes` | [Server](/docs/cli/commands.md#server-subcommand) | | `server config` | View or modify server configuration | `neurolink server config` | [Server](/docs/cli/commands.md#server-subcommand) | | `server openapi` | Generate OpenAPI specification | `neurolink server openapi` | [Server](/docs/cli/commands.md#server-subcommand) | **[ Complete CLI Reference](/docs/cli/commands)** - All commands and options --- ### GitHub Action Run AI-powered workflows directly in GitHub Actions with broad provider support and automatic PR/issue commenting. ```yaml - uses: juspay/neurolink@e42b4db89fa87946e2dd766cf2ab43929c689b8b # v13.8.16 with: anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} prompt: "Review this PR for security issues and code quality" post_comment: true ``` | Feature | Description | | ---------------------- | ----------------------------------------------------------------------------------------- | | **Multi-Provider** | Broad provider support behind one unified interface | | **PR/Issue Comments** | Auto-post AI responses with intelligent updates | | **Multimodal Support** | Attach images, PDFs, CSVs, Excel, Word, JSON, YAML, XML, HTML, SVG, code files to prompts | | **Cost Tracking** | Built-in analytics and quality evaluation | | **Extended Thinking** | Deep reasoning with thinking tokens | **[ GitHub Action Guide](/docs/guides/github-action)** - Complete setup and examples --- ## Smart Model Selection NeuroLink features intelligent model selection and cost optimization: ### Cost Optimization Features - ** Automatic Cost Optimization**: Selects cheapest models for simple tasks - ** LiteLLM Model Routing**: Access 100+ models with automatic load balancing - ** Capability-Based Selection**: Find models with specific features (vision, function calling) - **⚡ Intelligent Fallback**: Seamless switching when providers fail ```bash # Cost optimization - automatically use cheapest model npx @juspay/neurolink generate "Hello" --optimize-cost # LiteLLM specific model selection npx @juspay/neurolink generate "Complex analysis" --provider litellm --model "anthropic/claude-sonnet-4-6" # Auto-select best available provider npx @juspay/neurolink generate "Write code" # Automatically chooses optimal provider ``` ## Revolutionary Interactive CLI NeuroLink's CLI goes beyond simple commands - it's a **full AI development environment**: ### Why Interactive Mode Changes Everything | Feature | Traditional CLI | NeuroLink Interactive | | ------------- | ----------------- | ------------------------------ | | Session State | None | Full persistence | | Memory | Per-command | Conversation-aware | | Configuration | Flags per command | `/set` persists across session | | Tool Testing | Manual per tool | Live discovery & testing | | Streaming | Optional | Real-time default | ### Live Demo: Development Session ```bash $ npx @juspay/neurolink loop --enable-conversation-memory neurolink > /set provider vertex ✓ provider set to vertex (Gemini 3 support enabled) neurolink > /set model gemini-3-flash-preview ✓ model set to gemini-3-flash-preview neurolink > Analyze my project architecture and suggest improvements ✓ Analyzing your project structure... [AI provides detailed analysis, remembering context] neurolink > Now implement the first suggestion [AI remembers previous context and implements suggestion] neurolink > /mcp discover ✓ Discovered 58 MCP servers: GitHub: create_issue, list_repos, create_pr... PostgreSQL: query, insert, update... [full list] neurolink > Use the GitHub tool to create an issue for this improvement ✓ Creating issue... (requires HITL approval if configured) neurolink > /export json > session-2026-01-01.json ✓ Exported 15 messages to session-2026-01-01.json neurolink > exit Session saved. Resume with: neurolink loop --session session-2026-01-01.json ``` ### Session Commands Reference | Command | Purpose | | -------------------- | ---------------------------------------------------- | | `/set ` | Persist configuration (provider, model, temperature) | | `/mcp discover` | List all available MCP tools | | `/export json` | Export conversation to JSON | | `/history` | View conversation history | | `/clear` | Clear context while keeping settings | **[Interactive CLI Guide](/docs/cli)** | **[CLI Reference](/docs/cli/commands)** Skip the wizard and configure manually? See [`docs/getting-started/provider-setup.md`](/docs/getting-started/provider-setup). ## CLI & SDK Essentials `neurolink` CLI mirrors the SDK so teams can script experiments and codify them later. ```bash # Discover available providers and models npx @juspay/neurolink status npx @juspay/neurolink models list --provider google-ai # Route to a specific provider/model npx @juspay/neurolink generate "Summarize customer feedback" \ --provider azure --model gpt-4o-mini # Turn on analytics + evaluation for observability npx @juspay/neurolink generate "Draft release notes" \ --enable-analytics --enable-evaluation --format json ``` ```typescript const neurolink = new NeuroLink({ conversationMemory: { enabled: true, store: "redis", }, enableOrchestration: true, }); const result = await neurolink.generate({ input: { text: "Create a comprehensive analysis", files: [ "./sales_data.csv", // Auto-detected as CSV "examples/data/invoice.pdf", // Auto-detected as PDF "./diagrams/architecture.png", // Auto-detected as image "./report.xlsx", // Auto-detected as Excel "./config.json", // Auto-detected as JSON "./diagram.svg", // Auto-detected as SVG (injected as text) "./app.ts", // Auto-detected as TypeScript code ], }, provider: "vertex", // PDF-capable provider (see docs/features/pdf-support.md) enableEvaluation: true, region: "us-east-1", }); console.log(result.content); console.log(result.evaluation?.overallScore); ``` ### Gemini 3 with Extended Thinking ```typescript const neurolink = new NeuroLink(); // Use Gemini 3 with extended thinking for complex reasoning const result = await neurolink.generate({ input: { text: "Solve this step by step: What is the optimal strategy for...", }, provider: "vertex", model: "gemini-3-flash-preview", thinkingLevel: "medium", // Options: "minimal", "low", "medium", "high" }); console.log(result.content); ``` Full command and API breakdown lives in [`docs/cli/commands.md`](/docs/cli/commands) and [`docs/sdk/api-reference.md`](/docs/sdk/api-reference). ## Platform Capabilities at a Glance | Capability | Highlights | | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------- | | **Provider unification** | Provider neurons behind one API, with automatic fallback, cost-aware routing, `providerFallback` policy, `modelChain` config. | | **Multimodal pipeline** | Stream images + CSV data + PDF documents across providers with local/remote assets. Auto-detection for mixed file types. | | **Voice pipeline** | TTS (6 providers) + STT (4 providers) + realtime APIs (OpenAI Realtime, Gemini Live). | | **Quality & governance** | Auto-evaluation engine (14 scorers), guardrails middleware, HITL workflows, audit logging. | | **Memory & context** | Per-user condensed memory (S3/Redis/SQLite), Redis session export, 5-stage context compaction. | | **CLI tooling** | Loop sessions, setup wizard, config validation, Redis auto-detect, JSON output, TTS/STT flags. | | **Enterprise ops** | Claude proxy, OTLP observability, OpenObserve dashboard, regional routing, credential management. | | **Tool ecosystem** | MCP auto discovery, HTTP/stdio/SSE/WebSocket transports, LiteLLM hub access, SageMaker custom deployment, web search. | ## Documentation Map | Area | When to Use | Link | | --------------- | ----------------------------------------------------- | ----------------------------------------------------------- | | Getting started | Install, configure, run first prompt | [`docs/getting-started/index.md`](/docs/) | | Feature guides | Understand new functionality front-to-back | [`docs/features/index.md`](/docs/) | | CLI reference | Command syntax, flags, loop sessions | [`docs/cli/index.md`](/docs/) | | SDK reference | Classes, methods, options | [`docs/sdk/index.md`](/docs/) | | Integrations | LiteLLM, SageMaker, MCP | [`docs/litellm-integration.md`](/docs/getting-started/providers/litellm) | | Advanced | Middleware, architecture, streaming patterns | [`docs/advanced/index.md`](/docs/) | | Cookbook | Practical recipes for common patterns | [`docs/cookbook/index.md`](/docs/) | | Guides | Migration, Redis, troubleshooting, provider selection | [`docs/guides/index.md`](/docs/) | | Operations | Configuration, troubleshooting, provider matrix | [`docs/reference/index.md`](/docs/) | ### New in 2026: Enhanced Documentation **Enterprise Features:** - [Enterprise HITL Guide](/docs/features/enterprise-hitl) - Approval workflows for high-stakes operations - [Interactive CLI Guide](/docs/cli) - AI development environment - [MCP Tools Showcase](/docs/features/mcp-tools-showcase) - 58+ external MCP servers & 6 built-in tools **Provider Intelligence:** - [Provider Capabilities Audit](/docs/reference/provider-capabilities-audit) - Technical capabilities matrix - [Provider Selection Guide](/docs/reference/provider-selection) - Interactive decision wizard - [Provider Comparison](/docs/reference/provider-comparison) - Feature & cost comparison **Middleware System:** - [Middleware Architecture](/docs/advanced/middleware-architecture) - Complete lifecycle & patterns - [Built-in Middleware](/docs/advanced/builtin-middleware) - Analytics, Guardrails, Evaluation - [Custom Middleware Guide](/docs/workflows/custom-middleware) - Build your own **Redis & Persistence:** - [Redis Quick Start](/docs/getting-started/redis-quickstart) - 5-minute setup - [Redis Configuration](/docs/guides/redis-configuration) - Production deployment setup - [Redis Migration](/docs/guides/redis-migration) - Migration patterns **Migration Guides:** - [From LangChain](/docs/guides/migration/from-langchain) - Complete migration guide - [From Vercel AI SDK](/docs/guides/migration/from-vercel-ai-sdk) - Next.js focused **Developer Experience:** - [Cookbook](/docs/) - 15 practical recipes - [Troubleshooting Guide](/docs/reference/troubleshooting) - Common issues & solutions ## Integrations - **LiteLLM 100+ model hub** – Unified access to third-party models via LiteLLM routing. → [`docs/litellm-integration.md`](/docs/getting-started/providers/litellm) - **Amazon SageMaker** – Deploy and call custom endpoints directly from NeuroLink CLI/SDK. → [`docs/sagemaker-integration.md`](/docs/getting-started/providers/sagemaker) - **Enterprise proxy & security** – Configure outbound policies and compliance posture. → [`docs/enterprise-proxy-setup.md`](/docs/deployment/enterprise-proxy) - **Configuration automation** – Manage environments, regions, and credentials safely. → [`docs/configuration-management.md`](/docs/deployment/configuration-management) - **MCP tool ecosystem** – Auto-discover Model Context Protocol tools and extend workflows. → [`docs/advanced/mcp-integration.md`](/docs/mcp/integration) - **Remote MCP via HTTP** – Connect to HTTP-based MCP servers with authentication, retries, and rate limiting. → [`docs/mcp-http-transport.md`](/docs/mcp/http-transport) ## Contributing & Support - Bug reports and feature requests → [GitHub Issues](https://github.com/juspay/neurolink/issues) - Development workflow, testing, and pull request guidelines → [`docs/development/contributing.md`](/docs/community/contributing) - Documentation improvements → open a PR referencing the documentation matrix. --- NeuroLink is built with ❤️ by Juspay. Contributions, questions, and production feedback are always welcome. --- ## Page Not Found # Page Not Found **404 - Page Not Found** — The page you're looking for doesn't exist or has been moved. ## What you can do - **Check the URL** — Make sure the URL is spelled correctly and try again. - **Use Navigation** — Use the navigation menu to find what you're looking for. - **Search** — Use the search function to find specific content. - **Go Home** — Return to the [homepage](/docs/) and start from there. ## Popular Pages - **[Getting Started](/docs/)** — Quick setup and installation guides - **[CLI Guide](/docs/)** — Command-line interface documentation - **[SDK Reference](/docs/)** — API documentation and examples - **[Examples](/docs/)** — Practical usage examples ## 🆘 Need Help? If you think this is an error, please: 1. Check our [Troubleshooting Guide](/docs/reference/troubleshooting) 2. Search our [FAQ](/docs/reference/faq) 3. Report the issue on [GitHub](https://github.com/juspay/neurolink/issues) --- [← Back to Home](/docs/) --- ## NeuroLink Documentation Audit Report # NeuroLink Documentation Audit Report > **⚠️ HISTORICAL DOCUMENT (August 2025)** > > This audit was conducted when NeuroLink shipped 9 providers. At audit time, v9.62.0 (May 2026) shipped 24 providers including DeepSeek, NVIDIA NIM, LM Studio, llama.cpp, plus voice (TTS/STT/realtime). References to "9 providers" or "8/9 working" in this file reflect the state at time of analysis. > > For current capabilities see [README on GitHub](https://github.com/juspay/neurolink/blob/main/README.md) and [Provider Capabilities Audit](https://github.com/juspay/neurolink/blob/main/docs/reference/provider-capabilities-audit.md). > **Snapshot Date:** 2026-03-17 | **Branch:** `fix/documentation` | **Status:** Historical audit record — most items have been resolved. This document is retained for reference. ## Goal Perform a comprehensive audit of the NeuroLink documentation served at **docs.neurolink.ink** to identify every gap, broken element, missing content, incorrect code, navigation issue, and quality problem. This report is the output of **16 parallel investigation agents** that examined the documentation from every angle. This initial audit phase used 16 agents. The full fix cycle across all phases used 77+ agents total. The findings here should be used by a verification agent to confirm each issue and by implementation agents to systematically fix them. ### What Was Investigated 1. **Documentation directory structure** — Complete inventory of all 481 files across 28 directories 2. **Documentation build system** — Docusaurus 3.9.2 config, CI/CD, plugins, search, analytics 3. **SDK API reference** — Every public method on the `NeuroLink` class vs what's documented 4. **CLI documentation** — Every CLI command, flag, and option vs what's documented 5. **Provider documentation** — All 30+ providers vs their dedicated setup guides 6. **Feature documentation** — All 15 major features vs their feature guides 7. **Git commit patterns** — How documentation is typically written, what got missed 8. **Broken links and references** — Every internal link, anchor, and image reference 9. **Code example correctness** — Every code block compared against actual SDK and CLI APIs 10. **Public exports vs documentation** — Every `index.ts` export vs its API reference page 11. **Documentation quality and consistency** — Formatting, frontmatter, heading structure, terminology 12. **Sidebar navigation completeness** — Every sidebar entry verified, orphaned pages identified 13. **TypeScript type documentation** — All 42 type files vs TypeDoc pages and narrative docs 14. **README accuracy** — Every claim in README.md vs actual codebase capabilities 15. **Recently added features** — Features from recent commits vs documentation coverage 16. **Guides, examples, and tutorials** — Getting started path, cookbook, runnable examples quality ### Verified False Positives (5 corrections applied) The following claims from the original 16-agent audit were verified as false positives and have been struck through in-place throughout this document: | Original Claim | Correction | | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Claim 1.7b** — `registerTool` using `parameters` is wrong, should be `inputSchema` | **FALSE POSITIVE.** Runtime compatibility shim handles `parameters` including Zod schemas. The documented code works correctly. | | **Claim 6.2** — `#examples--recipes`, `#use-cases--examples`, `#retry--backoff-strategies` are broken anchors | **FALSE POSITIVE.** These are valid anchors where `&` in headings correctly becomes `--` in generated slugs. 3 of 8 broken anchor claims removed. | | **Claim 7.1** — 351 MkDocs tabbed syntax instances | **OVERSTATED ~7x.** Actual count outside code blocks: ~49. The grep matched `===` inside fenced code blocks (Python comparisons, test assertions). | | **Claim 12.2** — WebSocket Handler not mentioned in README | **FALSE POSITIVE.** WebSocket IS mentioned at 2 locations in README. | | **Claim 2.6** — ToolRouter, ToolCache, RequestBatcher undocumented | **FALSE POSITIVE / CLAUDE.md INACCURACY.** These source files **do not exist in the codebase**. The CLAUDE.md claim is stale or aspirational. Not a doc gap — the code doesn't exist. CLAUDE.md itself needs correction. | ### Verification Criteria For each issue category, a verification agent should: - **Confirm the issue exists** by checking the referenced file path and line number - **Assess current severity** (it may have been partially fixed since audit) - **Flag additional false positives** if further analysis reveals incorrect claims - **Note dependencies** between issues (e.g., fixing MkDocs syntax may fix some broken rendering) --------------- | ----------------------------------------------------------------------------------------------- | | **Framework** | Docusaurus 3.9.2 (React-based static site generator) | | **URL** | https://docs.neurolink.ink | | **Hosting** | GitHub Pages with custom domain (CNAME) | | **Source docs** | `/docs/` directory (synced to `/docs-site/docs/` at build time) | | **Site config** | `/docs-site/docusaurus.config.ts` | | **Sidebar config** | `/docs-site/sidebars.ts` | | **Sync script** | `/docs-site/scripts/sync-docs.ts` (MkDocs → Docusaurus transformation) | | **Search** | Algolia (primary) + MiniSearch (local fallback) | | **Analytics** | PostHog (GDPR-compliant) + Google Analytics | | **Total files** | 481 (410 markdown + 71 media/assets) | | **API docs** | 137 auto-generated TypeDoc pages in `/docs/api/` | | **CI/CD** | `.github/workflows/docs-deploy.yml`, `docs-pr-validation.yml`, `docs-version.yml` | | **Custom plugins** | `docusaurus-plugin-new-docs` (badge detection), `docusaurus-plugin-search-index` (local search) | | **Redirects** | 70+ static redirects in `/docs-site/config/redirects.ts` | | **LLM docs** | `llms.txt` (~50KB summary) and `llms-full.txt` (~3.8MB full) generated at build | --- ## CATEGORY 1: Broken Code Examples ### 1.1 README Hero Example (CRITICAL) **File:** `/README.md`, lines 9-17 **Current broken code:** ```typescript const pipe = new NeuroLink({ defaultProvider: "anthropic" }); for await (const token of pipe.stream({ prompt: "Hello" })) { process.stdout.write(token); } ``` **Why it's broken (3 distinct errors):** 1. `NeurolinkConstructorConfig` has no `defaultProvider` field. Valid fields are: `conversationMemory`, `enableOrchestration`, `hitl`, `toolRegistry`, `observability`, `modelAliasConfig`. 2. `stream()` returns `Promise`, not an async iterable. Must use `result.stream` to get the iterable. 3. Stream chunks are objects (`{ content: string }` or `StreamChunk`), not raw strings. `process.stdout.write(token)` would output `[object Object]`. **Correct code should be:** ```typescript const pipe = new NeuroLink(); const result = await pipe.stream({ input: { text: "Hello" }, provider: "anthropic", }); for await (const chunk of result.stream) { process.stdout.write(chunk.content); } ``` **Verification:** Read `src/lib/types/configTypes.ts` for constructor options, `src/lib/types/streamTypes.ts` for `StreamResult` and `StreamChunk` types. --- ### 1.2 `prompt` vs `input.text` (20+ instances) **The problem:** `GenerateOptions` and `StreamOptions` do NOT have a `prompt` field. The correct field is `input: { text: "..." }`, or you can pass a bare string to `generate("Hello")`. **Affected files (verified instances):** | File | Lines | Pattern | | ------------------------------------- | ----------------------------------------------- | ---------------------------------------------------- | | `README.md` | 586 | `generate({ prompt: "...", rag: {...} })` | | `docs/features/observability.md` | 72, 204, 216, 228, 248, 281, 305, 337, 583, 587 | `generate({ prompt: "Hello" })` | | `docs/features/rag.md` | 921-940 | Both `generate({ prompt })` and `stream({ prompt })` | | `docs/advanced/builtin-middleware.md` | 165, 217, 241, 662, 686, 746 | `generate({ prompt })` and `stream({ prompt })` | | `docs/telemetry-guide.md` | 82 | `generate({ prompt: "Hello" })` | | `docs/sdk/api-reference.md` | 523 | `generate({ prompt: "...", rag: {...} })` | **Verification:** Read `src/lib/types/generateTypes.ts` — search for `prompt` field on `GenerateOptions`. It does not exist. The `generate()` method at `src/lib/neurolink.ts:2857` accepts `GenerateOptions | string`. --- ### 1.3 Streaming Iteration Pattern (10+ instances) **The problem:** `stream()` returns `Promise` where `StreamResult.stream` is the async iterable. Code must use `result.stream`, not iterate the result directly. **Affected files:** | File | Lines | Broken Pattern | | -------------------------------------- | -------------------------- | ----------------------------------- | | `docs/advanced/streaming.md` | 33-36, 51-53, 68-74, 92-94 | `for await (const chunk of stream)` | | `docs/features/rag.md` | 133-150 | `for await (const chunk of stream)` | | `docs/reference/faq.md` | 264 | `for await (const chunk of stream)` | | `docs/mem0-integration.md` | 221 | `for await (const chunk of stream)` | | `docs/reference/provider-selection.md` | 141 | `for await (const chunk of stream)` | | `docs/playground/index.md` | 60 | `for await (const chunk of stream)` | | `docs/cookbook/error-recovery.md` | 301 | `process.stdout.write(chunk)` | | `docs/features/file-processors.md` | 192 | `process.stdout.write(chunk)` | **Verification:** Read `src/lib/types/streamTypes.ts` — `StreamResult` has a `.stream` property that yields `StreamChunk` objects. --- ### 1.4 Invalid Constructor Options (5 instances) **Affected files:** | File | Lines | Invalid Options | | ------------------------------ | ------- | ------------------------------------------------------------ | | `README.md` | 12 | `defaultProvider: "anthropic"` | | `README.md` | 345-368 | `store: "redis"`, `ttl: 86400` | | `docs/sdk/index.md` | 113-117 | `defaultProvider`, `timeout`, `enableAnalytics` | | `docs/sdk/index.md` | 167-172 | `memory: { type: "redis" }` (should be `conversationMemory`) | | `docs/examples/basic-usage.md` | 673-693 | `defaultProvider`, `timeout`, `retryAttempts`, `analytics` | **Verification:** Read `src/lib/types/configTypes.ts` for `NeurolinkConstructorConfig`. --- ### 1.5 Non-Existent Methods Referenced | File | Line | Method | Reality | | ----------- | ---- | ---------------------- | --------------------------------- | | `README.md` | 76 | `generateImage()` | Does not exist on NeuroLink class | | `README.md` | 371 | `exportConversation()` | Does not exist on NeuroLink class | **Verification:** `grep -n "generateImage\|exportConversation" src/lib/neurolink.ts` — returns no results. --- ### 1.6 Tools Passed as Array Instead of Record **File:** `docs/features/rag.md`, lines 124, 139, 245, 320, 349 **Broken:** `tools: [ragTool]` **Correct:** `tools: { [ragTool.name]: ragTool }` **Verification:** `GenerateOptions.tools` type in `src/lib/types/generateTypes.ts` is `Record`, not `Tool[]`. --- ### 1.7 Other Broken Examples | File | Line | Issue | | ---------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `README.md` | 610 | `thinkingLevel` used as top-level `GenerateOptions` field (should be inside `thinkingConfig`) | | `docs/sdk/index.md` | 148-155 | `createProviderWithFallback()` used synchronously (missing `await`) | | `docs/sdk/index.md` | 176-183 | `sessionId` used in `GenerateOptions` (doesn't exist on this type) | | `docs/sdk/index.md` | 224-271 | ~~`registerTool` uses `parameters: z.object(...)`~~ **FALSE POSITIVE** — Runtime compatibility shim handles `parameters` including Zod schemas; this code works correctly | | `docs/features/rag.md` | 691 | `GOOGLE_API_KEY` env var (should be `GOOGLE_AI_API_KEY`) | | `docs/advanced/streaming.md` | 71 | `chunk.type === "tool_use"` (valid types are `"text"` and `"audio"` only) | | `docs/cli/examples.md` | 365, 369 | `--criteria speed` and `--use-case cheapest` flags don't exist | | `docs/cli/advanced.md` | 628 | `neurolink mcp list --server "$name"` — `--server` flag doesn't exist | | `docs/cli/advanced.md` | 138 | `neurolink status --json` — should be `--format json` | --- ## CATEGORY 2: Missing Documentation — Features ### 2.1 Workflow System (CRITICAL — 25 files, ~20K lines, zero user guide) **Source code:** `src/lib/workflow/` — 25 files including: - `core/workflowRunner.ts` — Main execution engine - `core/ensembleExecutor.ts` — Multi-model ensemble execution - `core/judgeScorer.ts` — Judge-based scoring - `workflows/consensusWorkflow.ts`, `fallbackWorkflow.ts`, `adaptiveWorkflow.ts`, `multiJudgeWorkflow.ts` - `utils/workflowValidation.ts`, `workflowMetrics.ts` **What exists in docs:** - `docs/WORKFLOW-ENGINE-HLD.md` (847 lines) — Internal design doc, **NOT in sidebar** - `docs/WORKFLOW-ENGINE-LLD.md` (2,024 lines) — Internal design doc, **NOT in sidebar** - `docs/advanced-orchestration.md` (448 lines) — Maps to sidebar but is generic orchestration, not workflow-engine-specific **What's completely missing:** - User-facing feature guide explaining how to use the workflow engine - Documentation for `runWorkflow()` function - Documentation for 9 pre-built workflow constants: `CONSENSUS_3_WORKFLOW`, `CONSENSUS_3_FAST_WORKFLOW`, `BALANCED_ADAPTIVE_WORKFLOW`, `QUALITY_MAX_WORKFLOW`, `SPEED_FIRST_WORKFLOW`, `AGGRESSIVE_FALLBACK_WORKFLOW`, `FAST_FALLBACK_WORKFLOW`, `MULTI_JUDGE_3_WORKFLOW`, `MULTI_JUDGE_5_WORKFLOW` - Documentation for `WorkflowConfig`, `WorkflowType`, `WorkflowResult` types - CLI `workflow` command documentation (`workflow list`, `workflow info `, `workflow execute `) - Fluent API documentation - Checkpointing documentation - HITL integration with workflows **Verification:** `ls src/lib/workflow/` and `grep -r "workflow" docs-site/sidebars.ts` — the sidebar references `workflows/orchestration` but NOT the workflow engine docs. --- ### 2.2 Observability — 8 of 9 Exporters Undocumented (CRITICAL — ~6,800 lines) **Source code:** `src/lib/observability/` — includes exporters for: | Exporter | Source File | Documented? | | ------------- | --------------------------------- | -------------------------------------- | | Langfuse | `exporters/langfuseExporter.ts` | YES — `docs/features/observability.md` | | LangSmith | `exporters/langsmithExporter.ts` | NO | | Datadog | `exporters/datadogExporter.ts` | NO | | Sentry | `exporters/sentryExporter.ts` | NO | | Braintrust | `exporters/braintrustExporter.ts` | NO | | Arize | `exporters/arizeExporter.ts` | NO | | PostHog | `exporters/posthogExporter.ts` | NO | | Laminar | `exporters/laminarExporter.ts` | NO | | OpenTelemetry | `exporters/otelExporter.ts` | NO | **Also undocumented:** - 9 samplers: AlwaysSampler, NeverSampler, RatioSampler, TraceIdRatioSampler, AttributeBasedSampler, PrioritySampler, ErrorOnlySampler, CompositeSampler, CustomSampler - 7 span processors: PassThrough, AttributeEnrichment, Filter, Redaction, Truncation, Composite, Batch - ExporterRegistry, MetricsAggregator, TokenTracker - 5 retry policies: Exponential, Linear, Fixed, NoRetry, CircuitBreakerAware **The internal status file** `src/lib/observability/FEATURE-STATUS.md` documents all of this but is NOT synced to the docs site. **Verification:** `ls src/lib/observability/exporters/` and `grep -i "langsmith\|datadog\|sentry\|braintrust\|arize\|posthog\|laminar" docs/features/observability.md` — returns 0 matches. --- ### 2.3 Dynamic Arguments (CRITICAL — zero docs, 269 tests) CLAUDE.md states: "Dynamic Arguments: Complete — CLI context flags, runtime resolution, 269 tests" **What's missing:** No documentation file exists. Zero mentions of "dynamic arguments" in any doc. **Verification:** `grep -ri "dynamic.arg" docs/` — returns 0 results. `docs/advanced/dynamic-models.md` is a different feature (dynamic model configuration). --- ### 2.4 Embeddings (HIGH — no dedicated page) **Source code:** - `src/lib/core/baseProvider.ts` — `embed()` and `embedMany()` stubs - Provider implementations in OpenAI, Google AI Studio, Vertex, Bedrock - Server routes: `POST /api/agent/embed`, `POST /api/agent/embed-many` **What exists:** Brief mention in `docs/sdk/api-reference.md` (lines 474-513) — 2 code snippets, provider table. **What's missing:** - No `docs/features/embeddings.md` page - Not in sidebar navigation - No documentation on which providers do NOT support embeddings (and what error they throw) - No batch size limits or chunking behavior for `embedMany` - No usage examples with `InMemoryVectorStore` - Server route documentation not in API reference (only in server adapters guide) --- ### 2.5 Bash Tool (HIGH — zero docs) **Source:** Commit `9a915e6f` added the bash tool as a built-in tool option. **What's missing:** Zero documentation anywhere. The README's "6 Core Tools" table does not list it. **Verification:** `grep -ri "bash.tool\|bashTool\|enableBashTool" docs/` — check results. --- ### ~~2.6 MCP Enhancements — ToolRouter, ToolCache, RequestBatcher~~ > **FALSE POSITIVE / CLAUDE.md INACCURACY:** CLAUDE.md states "ToolRouter, ToolCache, RequestBatcher (1,702 new lines)" but verification confirmed these source files **do not exist in the codebase**. The CLAUDE.md claim is stale or aspirational. This is not a documentation gap — the code itself doesn't exist. However, this means **CLAUDE.md itself needs to be corrected** to remove this false claim. > > The MCP circuit breaker (`mcpCircuitBreaker.ts`) does exist and remains undocumented — that is a real gap. --- ### 2.7 Streaming Architecture — 24 Event Types (MEDIUM) CLAUDE.md claims: "All 4 streaming patterns, 24 event types, backpressure" **What's missing:** - No enumeration of the 24 event types in any doc - No description of the 4 streaming patterns - Backpressure gets a single bullet mention with no guidance - `StreamChunk` discriminated union (text vs audio variants) undocumented --- ## CATEGORY 3: Missing Documentation — Providers ### 3.1 Providers With Zero Documentation | Provider | Source File | Default Model | Key Env Vars | | ------------- | -------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------- | | **OpenAI** | `src/lib/providers/openAI.ts` | `gpt-4o` | `OPENAI_API_KEY`, `OPENAI_MODEL`, `OPENAI_EMBEDDING_MODEL` | | **Ollama** | `src/lib/providers/ollama.ts` | `llama3.1:8b` | `OLLAMA_BASE_URL`, `OLLAMA_MODEL`, `OLLAMA_TIMEOUT`, `OLLAMA_OPENAI_COMPATIBLE` | | **SageMaker** | `src/lib/providers/amazonSagemaker.ts` | Endpoint-based | `SAGEMAKER_REGION`, `SAGEMAKER_DEFAULT_ENDPOINT`, `SAGEMAKER_MODEL`, `SAGEMAKER_MODEL_TYPE` + 10 more | **Critical SageMaker note:** Streaming is explicitly NOT implemented (throws `SageMakerError`) — this is completely undisclosed. **Verification:** `ls docs/getting-started/providers/` — confirm no `openai.md`, no `ollama.md`, no `sagemaker.md`. --- ### 3.2 Providers With Incorrect Documentation **LiteLLM** (`docs/getting-started/providers/litellm.md`): - The entire doc explains how to install and configure the **external LiteLLM proxy server** - It NEVER explains the dedicated NeuroLink `litellm` provider (`--provider litellm`) - Actual env vars `LITELLM_BASE_URL`, `LITELLM_API_KEY`, `LITELLM_MODEL` are undocumented - No model list from `LiteLLMModels` enum **HuggingFace** (`docs/getting-started/providers/huggingface.md`): - Docs use `HUGGINGFACE_DEFAULT_MODEL` but code reads `HUGGINGFACE_MODEL` - Default model documented as `Mistral-7B-Instruct-v0.2` but code defaults to `QWEN_2_5_72B_INSTRUCT` **Verification:** Read `src/lib/factories/providerRegistry.ts` — find the HuggingFace and LiteLLM registration entries to confirm env var names and default models. --- ### 3.3 Provider Documentation Gaps (per provider) | Provider | Missing | | -------------------- | ---------------------------------------------------------------------------------- | | **Google AI Studio** | Embedding support (`GOOGLE_AI_EMBEDDING_MODEL`, `gemini-embedding-001`) | | **Google Vertex** | Embedding support (`VERTEX_EMBEDDING_MODEL`, `text-embedding-004`), TTS support | | **Amazon Bedrock** | `BEDROCK_MODEL` env var, ARN format examples, streaming behavior | | **Azure OpenAI** | Vision/image support for GPT-4o, embedding usage examples, 4 of 5 env var variants | | **Mistral** | Vision models (Pixtral), tool/function calling examples, correct embedding API | | **Anthropic** | `CLAUDE_SONNET_4_6` (registry default) missing from model table | --- ## CATEGORY 4: Missing Documentation — CLI ### 4.1 Entirely Undocumented Commands | Command | Source | Subcommands | Key Flags | | ---------------------------------------- | ----------------------------------- | --------------------------------------------------------- | ---------------------------------------------------- | | `workflow` | `src/cli/commands/workflow.ts` | `list`, `info `, `execute ` | `--provider`, `--model`, `--timeout`, `--verbose` | | `observability` (aliases: `obs`, `otel`) | `src/cli/commands/observability.ts` | `status`, `metrics`, `exporters`, `costs` | — | | `telemetry` (alias: `tel`) | `src/cli/commands/telemetry.ts` | `status`, `configure`, `list-exporters`, `flush`, `stats` | 9 exporters | | `docs` | `src/cli/commands/docs.ts` | — | `--transport` (stdio/http), `--port` | | `rag index` | `src/cli/commands/rag.ts:507` | — | `--index-name`, `--strategy`, `--graph`, `--verbose` | | `rag query` | `src/cli/commands/rag.ts:740` | — | `--index-name`, `--top-k`, `--hybrid`, `--graph` | --- ### 4.2 Incorrect Flag Documentation | Issue | Docs Say | Code Says | | ------------------------------- | ------------------------------------- | ---------------------------------------------- | | `rag chunk --chunk-size` | `--chunk-size` | `--maxSize` (`-m`) | | `rag chunk --chunk-overlap` | `--chunk-overlap` | `--overlap` (`-o`) | | `mcp add --url` and `--headers` | Listed as flags | Not implemented as CLI flags | | `--enable-beta` | Defaults to `true` for OAuth | Code has `default: false` | | `--dry-run` | "Returns mocked analytics/evaluation" | "Test command without making actual API calls" | | `--thinking-budget` | "Gemini 2.5+ models only" | "Anthropic Claude and Gemini 2.5+" | --- ### 4.3 Missing `models` Subcommands (5 of 6 undocumented) Only `models list` is documented. Missing from docs: - `models search [query]` — `--use-case`, `--max-cost`, `--min-context`, `--performance` - `models best` — `--coding`, `--creative`, `--analysis`, `--fast`, `--require-vision`, etc. - `models resolve ` — `--fuzzy` - `models compare ` - `models stats` — `--detailed` --- ### 4.4 PPT Generation Flags (6 flags, all absent) `--ppt-pages`, `--ppt-theme`, `--ppt-audience`, `--ppt-tone`, `--ppt-output`, `--ppt-aspect-ratio`, `--ppt-no-images` — none documented. The `--output-mode` flag doesn't mention `ppt` as a valid choice. **Verification:** Read `src/cli/factories/commandFactory.ts` lines 340-410. --- ## CATEGORY 5: Missing Documentation — SDK API Surface ### 5.1 Undocumented Public Methods on NeuroLink Class Source: `/src/lib/neurolink.ts` (10,249 lines) **Lifecycle (essential for production):** - `shutdown()` — Graceful shutdown (flushes OTEL, closes Redis, shuts down MCP servers). Line 2440. - `dispose()` — Full resource disposal. Line 9954. **Context Compaction API:** - `compactSession(sessionId, config?)` — Manual 4-stage compaction. Line 10120. - `getContextStats(sessionId, provider?, model?)` — Token usage and compaction readiness. Line 10171. - `needsCompaction(sessionId, provider?, model?)` — Boolean check. Line 10213. **Provider Diagnostics (11 methods):** - `getProviderStatus(options?)` — Line 8372 - `testProvider(providerName)` — Line 8558 - `getBestProvider(requestedProvider?)` — Line 8590 - `getAvailableProviders()` — Line 8599 - `isValidProvider(providerName)` — Line 8609 - `hasProviderEnvVars(providerName)` — Line 8748 - `checkProviderHealth(providerName, options?)` — Line 8774 - `checkAllProvidersHealth(options)` — Line 8820 - `getProviderHealthSummary()` — Line 8864 - `clearProviderHealthCache(providerName?)` — Line 8911 - `getToolHealthReport()` — Line 9037 **Observability/Metrics (5 methods):** - `getMetrics()` — Returns `MetricsSummary`. Line 2346. - `getSpans()` — Returns `SpanData[]`. Line 2353. - `getTraces()` — Returns `TraceView[]`. Line 2360. - `resetMetrics()` — Line 2367. - `initializeLangfuseObservability()` — Line 2414. **MCP Management (14 methods):** - `removeExternalMCPServer(serverId, options?)` — Line 9575 - `executeExternalMCPTool(serverId, toolName, args)` — Line 9660 - `testExternalMCPConnection(config)` — Line 9713 - `shutdownExternalMCPServers()` — Line 9753 - `addInMemoryMCPServer(serverId, serverInfo)` — Line 7563 - `getInMemoryServers()` — Line 7607 - `getInMemoryServerInfos()` — Line 7634 - `getAutoDiscoveredServerInfos()` — Line 7650 - `listMCPServers()` — Line 8692 - `testMCPServer(serverId)` — Line 8707 - `getAllAvailableTools()` — Line 8207 - `getCustomTools()` — Line 7434 - `getToolRegistry()` — Line 10112 - `getExternalServerManager()` — Line 10246 **Memory Management (8 methods):** - `getConversationStats()` — Line 9185 - `ensureConversationMemoryInitialized()` — Line 9165 - `storeToolExecutions(sessionId, userId, toolCalls, toolResults)` — Line 9325 - `isToolExecutionStorageAvailable()` — Line 9382 - `getSessionMessages(sessionId, userId?)` — Line 9398 - `setSessionMessages(sessionId, userId, messages)` — Line 9439 - `modifyLastAssistantMessage(sessionId, content)` — Line 9487 - `updateAgenticLoopReport(sessionId, report, userId?)` — Line 7398 **Event System (entire subsystem):** The `NeuroLink` class is a `TypedEventEmitter`. Events defined in `src/lib/types/common.ts` lines 157-210: - `tool:start`, `tool:end` - `stream:start`, `stream:end`, `stream:chunk`, `stream:complete`, `stream:error` - `generation:start`, `generation:end` - `response:start`, `response:end` - `externalMCP:serverConnected`, `externalMCP:serverDisconnected`, `externalMCP:serverFailed`, `externalMCP:toolDiscovered`, `externalMCP:toolRemoved`, `externalMCP:serverAdded`, `externalMCP:serverRemoved` - `tools-register:start` - `hitl:confirmation-request`, `hitl:timeout`, `hitl:confirmation-response` --- ### 5.2 Missing `generate()`/`stream()` Parameters **Parameters present in code but missing from API reference:** | Parameter | Type | Purpose | | ------------------------- | -------------------------- | --------------------------------------------------------- | | `tts` | `TTSOptions` | Text-to-Speech configuration | | `abortSignal` | `AbortSignal` | External cancellation | | `toolFilter` | `string[]` | Whitelist of tools to include | | `excludeTools` | `string[]` | Blacklist of tools to exclude | | `skipToolPromptInjection` | `boolean` | Performance optimization (~30K tokens saved) | | `thinkingConfig` | `object` | Full thinking config (not just `thinkingLevel` shorthand) | | `workflow` | `string` | Predefined workflow ID | | `workflowConfig` | `WorkflowConfig` | Inline workflow configuration | | `maxBudgetUsd` | `number` | Per-session USD budget cap | | `requestId` | `string` | Observability correlation ID | | `csvOptions` | `object` | CSV processing options | | `videoOptions` | `object` | Video processing options | | `factoryConfig` | `object` | Factory configuration override | | `middleware` | `MiddlewareFactoryOptions` | Middleware configuration | | `input.videoFiles` | — | Video file input | | `input.segments` | — | Director Mode segments | | `input.audio` | `AudioInputSpec` | Streaming audio input (stream only) | | `output.director` | — | Director Mode configuration | **Missing `GenerateResult` fields:** `audio` (TTSResult), `workflow.*` (ensemble responses), `retryMetadata` **Missing `StreamResult` fields:** `usage`, `finishReason`, `toolCalls`, `toolResults`, `toolEvents`, `toolExecutions`, `toolsUsed`, `metadata.guardrailsBlocked`, `metadata.thoughtSignature`, `metadata.thoughts` --- ### 5.3 Server Sub-Entry — Zero API Reference The `@juspay/neurolink/server` sub-entry (`src/lib/server/index.ts`) exports ~120 named exports with zero `docs/api/` pages: - Framework adapters (Hono, Express, Fastify, Koa) - All middleware functions (20+ functions) - All error classes - All route factories - OpenAPI generation (`OpenAPIGenerator`, `generateOpenAPISpec`, `createOpenApiRoutes`) - Stream security (`createStreamRedactor`, `redactStreamChunk`) - WebSocket utilities (`WebStreamWriter`, `BaseDataStreamWriter`) - All validation schemas --- ## CATEGORY 6: Broken Links & References ### 6.1 Missing Files Linked from `docs/api/` **Missing `docs/api/interfaces/` directory** (entire directory absent — 6 interface files referenced): - `Chunker.md`, `BM25Index.md`, `VectorStore.md`, `VectorQueryResult.md`, `Reranker.md`, `RerankerMetadata.md` **Missing `docs/api/type-aliases/` files** (20 files): - `BM25Result.md`, `MetadataFilter.md`, `RerankResult.md`, `HybridSearchResult.md` - 9 chunker config types: `CharacterChunkerConfig.md`, `RecursiveChunkerConfig.md`, `SentenceChunkerConfig.md`, `TokenChunkerConfig.md`, `MarkdownChunkerConfig.md`, `HTMLChunkerConfig.md`, `JSONChunkerConfig.md`, `LaTeXChunkerConfig.md`, `SemanticChunkerConfig.md` - 5 metadata extractor configs: `TitleExtractorConfig.md`, `SummaryExtractorConfig.md`, `KeywordExtractorConfig.md`, `QuestionExtractorConfig.md`, `CustomSchemaExtractorConfig.md` - `RAGConfig.md` (listed in `docs/api/README.md` index but file doesn't exist) - `RAGPreparedTool.md` **Missing `docs/api/functions/` files** (7 files): - `prepareRAGTool.md`, `formatContextWithCitations.md`, `summarizeContext.md` - `getRerankerMetadata.md`, `getRerankerDefaultConfig.md`, `getDefaultConfig.md`, `embed.md` ### 6.2 Broken Anchor Links (8 confirmed) | Source File | Broken Link | Issue | | ------------------------------------------- | ------------------------------------------------- | ------------------------------------------------------------------ | | `docs/api/type-aliases/GenerateOptions.md` | `sdk-custom-tools.md#-controlling-tool-execution` | Section doesn't exist | | ~~`docs/features/multimodal.md`~~ | ~~`#examples--recipes`~~ | **FALSE POSITIVE** — `&` in heading correctly becomes `--` in slug | | ~~`docs/features/tts.md`~~ | ~~`#use-cases--examples`~~ | **FALSE POSITIVE** — `&` in heading correctly becomes `--` in slug | | ~~`docs/guides/examples/code-patterns.md`~~ | ~~`#retry--backoff-strategies`~~ | **FALSE POSITIVE** — `&` in heading correctly becomes `--` in slug | | `docs/troubleshooting.md` | `features/ppt-generation.md#error-handling` | Closest: `#error-handling-validation` | | `docs/troubleshooting.md` | `features/ppt-generation.md#file-output` | No close match | | `docs/troubleshooting.md` | `features/ppt-generation.md#ai-image-generation` | Closest: `#disable-ai-image-generation` | ### 6.3 Broken Image References (2) | Source | Path | Likely Correct | | --------------------------- | ---------------------------------------- | ------------------------------------ | | `docs/demos/index.md` | `../assets/images/cli-demo.png` | `../assets/images/cli-help-demo.png` | | `docs/demos/screenshots.md` | `../assets/images/cli-help-overview.png` | `../assets/images/cli-help-demo.png` | ### 6.4 Placeholder Links (7) Links using `(#)` as URL: `docs/tutorials/videos.md` (1), `docs/api/classes/NeuroLink.md` (5), `docs/api/type-aliases/AIProvider.md` (1) ### 6.5 Phantom API Documentation (5 files documenting non-existent code) | File | Phantom Class/API | | ------------------------------------ | ----------------------------------------- | | `docs/health-monitoring-guide.md` | `HealthMonitor` class | | `docs/mcp-testing-guide.md` | `ContextManager` class | | `docs/advanced/mcp-testing-guide.md` | `ContextManager` class (duplicate) | | `docs/ai-orchestration-guide.md` | `DynamicOrchestrator` class | | `docs/mcp-concurrency-guide.md` | `SemaphoreManager` class | | `docs/features/enterprise-hitl.md` | States features "are not yet implemented" | ### 6.6 "Coming Soon" Placeholder Content (40+ instances across 14 files) **Heaviest offenders:** - `docs/tutorials/videos.md` — 15 "Coming Soon" sections with `` markers - `docs/features/audio-input.md` — 10+ "Coming Soon" entries for provider support - `docs/mcp-integration.md` — 3 "Coming Soon" sections - `docs/changelog.md` — 3 "Coming Soon" items (migration guides that never materialized) - `docs/features/index.md` — Video Generation marked "Coming Soon" ### 6.7 Duplicate Documentation Files (16 pairs) | Root File | Duplicate(s) | | -------------------------------- | ------------------------------------------------------------------------------------------------------ | | `docs/api-reference.md` | `docs/advanced/api-reference.md`, `docs/getting-started/api-reference.md`, `docs/sdk/api-reference.md` | | `docs/troubleshooting.md` | `docs/guides/troubleshooting.md`, `docs/reference/troubleshooting.md` | | `docs/configuration.md` | `docs/reference/configuration.md` | | `docs/mcp-integration.md` | `docs/advanced/mcp-integration.md` | | `docs/mcp-testing-guide.md` | `docs/advanced/mcp-testing-guide.md` | | `docs/cli-guide.md` | `docs/advanced/cli-guide.md` | | `docs/contributing.md` | `docs/development/contributing.md` | | `docs/dynamic-models.md` | `docs/advanced/dynamic-models.md` | | `docs/enterprise-proxy-setup.md` | `docs/getting-started/enterprise-proxy-setup.md` | | `docs/framework-integration.md` | `docs/sdk/framework-integration.md` | | `docs/middleware.md` | `docs/guides/server-adapters/middleware.md` | | `docs/provider-comparison.md` | `docs/reference/provider-comparison.md` | | `docs/testing.md` | `docs/development/testing.md` | | `docs/use-cases.md` | `docs/guides/examples/use-cases.md`, `docs/examples/use-cases.md` | | `docs/sdk/custom-tools.md` | `docs/sdk-custom-tools.md` (near-duplicate, 1814 vs 1668 lines) | --- ## CATEGORY 7: Rendering Issues — MkDocs Syntax in Docusaurus ### 7.1 MkDocs Tabbed Syntax (~49 instances, NOT 351) > **Correction:** The original count of 351 was ~7x overstated. The grep included `===` inside fenced code blocks (e.g., Python comparisons, test assertions). Actual MkDocs tab syntax instances outside code blocks: ~49. The `=== "Tab Name"` syntax renders as raw text in Docusaurus. Affected files include: - `docs/getting-started/installation.md` - `docs/sdk/index.md` - `docs/cli/index.md` - `docs/features/rag.md` - `docs/features/guardrails.md` - And additional files **Fix:** Convert to Docusaurus `` component or use the `sync-docs.ts` script transformation (which may already handle some of this but is clearly missing many). ### 7.2 MkDocs Material Icons (11 files) `️`, ``, etc. render as literal text. Files include: - `docs/features/index.md` — all table entries - `docs/guides/index.md` ### 7.3 MkDocs Admonitions (20+ files) `!!!` admonition syntax renders as raw text. Files include: - `docs/features/guardrails.md` - `docs/features/hitl.md` - `docs/features/multimodal-chat.md` ### 7.4 MkDocs Grid Cards (9 files) `` syntax renders as broken HTML. Files include: - `docs/sdk/index.md` --- ## CATEGORY 8: Navigation & Sidebar Issues ### 8.1 Sidebar Structure (from `/docs-site/sidebars.ts`) **16 top-level categories:** Getting Started, SDK, CLI, Features, MCP, Memory, Workflows, Observability, Deployment, Guides, Cookbook, Tutorials, Examples, Reference, Demos, Development, Community **Key problems:** 1. **Features category: 31 flat items** — Needs sub-grouping into: Input/Output (7), Generation (5), Conversation (5), Safety (3), Infrastructure (5), Special (6) 2. **3 duplicate entries:** Migration guides (`from-langchain`, `from-vercel-ai-sdk`, `migration-guide`) appear in BOTH "Getting Started > Migration Guides" AND "Guides > Migration" 3. **8 cross-directory references:** Pages from `advanced/` placed in unrelated categories (e.g., `advanced/streaming` in Features, `advanced/builtin-middleware` in Workflows) 4. **Category overlap:** Cookbook vs Examples vs Tutorials (3 categories for usage patterns). MCP/Memory/Workflows/Observability are features but get separate top-level categories while 31 other features are in a flat list. ### 8.2 Orphaned Pages (70 total — not in sidebar) **High-value orphaned content:** | Page | Lines | Why It Matters | | --------------------------------- | ----- | ------------------------------------ | | `features/context-compaction.md` | 980 | Major feature with comprehensive doc | | `features/video-director-mode.md` | 1,144 | Major feature doc | | `features/video-analysis.md` | 150 | Feature doc with real content | | `WORKFLOW-ENGINE-HLD.md` | 847 | Workflow system design | | `WORKFLOW-ENGINE-LLD.md` | 2,024 | Workflow system detailed design | | `connectors/index.md` | 35 | Connector catalog | | `connectors/tara.md` | — | Connector doc | | `connectors/yama.md` | — | Connector doc | | `playground/index.md` | 133 | Interactive playground | | `about/nervous-system-model.md` | 62 | Architecture concept | | `about/pipe-architecture.md` | 113 | Architecture concept | | `advanced/index.md` | — | Advanced section landing page | | `advanced/factory-patterns.md` | — | Factory pattern guide | | `sdk/custom-tools.md` | 1,814 | Near-duplicate | Other orphans: Internal docs in `plans/`, `phases/`, `tracking/`, `test-reports/`, `analysis/`, `visual-content/`, `rag/` — likely intentionally excluded. --- ## CATEGORY 9: Type Documentation Gaps ### 9.1 Auto-Generated TypeDoc Status **Stale:** All TypeDoc pages are pinned to an old commit (`1be79595b7d7307795c98da4267c1728cb50033d`). Fields added after that commit are missing from all auto-generated pages. **`VERSION` constant:** Hardcoded as `"1.0.0"` in `docs/api/variables/VERSION.md` — actual version is `9.26.1`. ### 9.2 Critical Types With No Documentation | Type | File | Impact | | --------------------------------------- | ------------------ | ----------------------------------------------------------------------- | | `StreamOptions` | `streamTypes.ts` | Primary streaming input type — no TypeDoc page | | `StreamResult` | `streamTypes.ts` | Primary streaming output — no TypeDoc page, narrative omits 60%+ fields | | `StreamChunk` | `streamTypes.ts` | What `stream` yields — no docs, audio variant invisible | | `ChatMessage` | `conversation.ts` | Central message type — no TypeDoc page | | `NeurolinkConstructorConfig` | `configTypes.ts` | `toolRegistry` and `modelAliasConfig` fields missing | | `NeuroLinkConfig` | `configTypes.ts` | Runtime config — no page, no narrative | | `RAGConfig` | `rag/types.ts` | Broken link in API README | | `TTSOptions` / `TTSResult` / `TTSChunk` | `ttsTypes.ts` | Good in-source TSDoc but no TypeDoc pages | | `HITLConfig` | `hitlTypes.ts` | No TypeDoc page | | `WorkflowConfig` / `WorkflowType` | `workflowTypes.ts` | No TypeDoc page | | `TokenUsage` | `analytics.ts` | Used in every response — no page | | `MCPTransportType` | `mcpTypes.ts` | `ws`, `tcp`, `unix` values undocumented | | `ExternalMCPServerConfig` | `externalMcp.ts` | No TypeDoc page | ### 9.3 Missing Model Enumerations Only `AIProviderName`, `BedrockModels`, `OpenAIModels`, `VertexModels` have TypeDoc pages. Missing: - `AnthropicModels`, `GoogleAIModels`, `MistralModels`, `AzureModels`, `OllamaModels`, `LiteLLMModels`, `HuggingFaceModels`, `OpenRouterModels` --- ## CATEGORY 10: Quality & Consistency Issues ### 10.1 Nonsensical Migration Notes 4+ files contain migration notes comparing `generate()` to itself: - `docs/configuration.md` line 12: "Configuration remains identical for both generate() and generate()." - `docs/troubleshooting.md` line 89: "What's the difference between the new generate() and the legacy generate()?" This is leftover from a method rename where a previous name was globally replaced with `generate()`. ### 10.2 Internal Status Banners in User-Facing Docs 7+ files have `IMPLEMENTATION STATUS: COMPLETE (2025-01-07)` banners with checkbox items that read like developer notes, not documentation. Files: `troubleshooting.md`, `configuration.md`, `reference/troubleshooting.md`, `reference/configuration.md`, `advanced/mcp-integration.md`, `mcp-integration.md`, `cli-reference.md` ### 10.3 Frontmatter Inconsistency - ~40% of feature docs lack YAML frontmatter (title, description, keywords) - Keywords format varies: some inline `keywords: rag, chunking`, some YAML array - Only 9 of 31 feature docs have the `> **Since**: vX.X.X | **Status**: Stable` banner ### 10.4 Heading Structure Issues - 3 files start with H2 instead of H1: `video-director-mode.md`, `video-generation.md`, `multimodal-chat.md` - `multimodal-chat.md` has no H1 at all - Emoji usage in headings: present in `getting-started/`, `sdk/`, `cli/`; absent in `features/` ### 10.5 Terminology Inconsistencies | Term | Variations Found | | ----------------- | ------------------------------------------------------------------------ | | Provider count | "9 providers", "12+ providers", "13 Providers", "14+ providers" | | Tool count | "58+ MCP Tools", "64+ built-in tools and MCP servers" | | OpenRouter models | "200+ Models" (table) vs "300+ models" (text) | | Product name | "NeuroLink" (correct) vs "Neurolink" (wrong — in HLD/LLD, some API docs) | | Google AI | "google-ai", "googleAiStudio", "Google AI" used interchangeably | ### 10.6 Other Quality Issues - Contributing guide (`docs/development/contributing.md`) uses `npm` instead of `pnpm`, and references `npm run type-check` (should be `pnpm run check`) - Discord badge in `docs/index.md` uses placeholder `DISCORD_SERVER_ID` - `docs/troubleshooting.md` references v7.47.0 (Sep 2025) — project is at v9.26.1 - `docs/reference/troubleshooting.md` references v1.7.1 (Jan 2025) - `docs/features/multimodal-chat.md` references "NeuroLink 7.47.0" - `docs/sdk/advanced-features.md` is a 55-line stub with placeholder patterns (`generateStream`, `generateBatch`, `cache`) --- ## CATEGORY 11: Missing Guides & Examples ### 11.1 Missing Documentation Pages | Page Needed | Why | | --------------------------------------------- | ----------------------------------------------------------------------------------------- | | `docs/features/embeddings.md` | User-facing embedding feature guide | | `docs/features/workflow-engine.md` | User-facing workflow engine guide | | `docs/features/streaming.md` | Dedicated streaming feature guide (current `advanced/streaming.md` is enterprise-focused) | | `docs/getting-started/providers/openai.md` | Most popular provider | | `docs/getting-started/providers/ollama.md` | Local model execution | | `docs/getting-started/providers/sagemaker.md` | AWS SageMaker | | `docs/guides/migration/from-openai-sdk.md` | Most common migration path | ### 11.2 Missing Quick Start Subsections in Feature Docs 11 feature docs lack a Quick Start section: `auto-evaluation.md`, `structured-output.md`, `thinking-configuration.md`, `mcp-tools-showcase.md`, `provider-orchestration.md`, `regional-streaming.md`, `video-analysis.md`, `file-processors.md`, `cli-loop-sessions.md`, `claude-subscription.md`, `claude-subscription-testing.md` ### 11.3 Missing Runnable Examples No example files exist for: streaming, memory/conversation, embeddings, provider switching, middleware, observability/Langfuse, context compaction, guardrails. ### 11.4 Missing Cookbook Recipes No recipes for: basic streaming, multimodal images, memory persistence, provider switching, embeddings, observability setup. ### 11.5 Missing Migration Guides - No major version migration guide (v7→v8, v8→v9) - No migration from OpenAI SDK directly - No migration from AWS SDK/Bedrock SDK --- ## CATEGORY 12: README Issues ### 12.1 Hero Code Example (see Category 1.1) ### 12.2 Features Missing from README | Feature | Code Size | README Mention | | -------------------------------- | ------------------------------- | -------------------------------------------------------------------- | | Workflow System | 25 files, ~20K lines | Zero | | TTS | TTSProcessor + GoogleTTSHandler | Zero | | Full Observability (9 exporters) | ~6,800 lines | Brief "OpenTelemetry" mention | | Context Compaction | 12 files | Single buried bullet | | Audio/Video/Archive processors | 3 processor classes | Not in file processing table | | GraphRAG | `graphRAG.ts` | Not mentioned | | File Reference Tools (5 tools) | `fileTools.ts` | Not mentioned | | Embeddings API | 4 providers, server routes | Not mentioned | | Claude OAuth/Subscription | Auth command + types | Not mentioned | | ~~WebSocket Handler~~ | ~~`WebSocketHandler.ts`~~ | **FALSE POSITIVE** — WebSocket IS mentioned at 2 locations in README | ### 12.3 README Inconsistencies - OpenRouter: "200+" in table vs "300+" in feature bullets - "64+ built-in tools and MCP servers" conflates two things (6 tools + 58 MCP servers) - Core tools table shows 6 but omits `analyzeCSV` and conditional `bashTool` - "Platform Capabilities" table has stale Q3/Q4 markers for features already shipped --- ## Verification Checklist for Agent (Historical — most items resolved) A verification agent should confirm each category by: 1. **Code examples (Cat 1):** Run `grep -n "prompt:" docs/features/observability.md` and verify `prompt` is used where `input.text` should be 2. **Missing features (Cat 2):** Run `ls docs/features/` and confirm no `embeddings.md`, `workflow-engine.md` exist 3. **Missing providers (Cat 3):** Run `ls docs/getting-started/providers/` and confirm no `openai.md`, `ollama.md`, `sagemaker.md` 4. **CLI commands (Cat 4):** Run `grep -r "workflow\|observability\|telemetry" docs/cli/commands.md` and confirm 0 matches 5. **Undocumented methods (Cat 5):** Run `grep -n "shutdown\|dispose\|compactSession\|getContextStats" docs/sdk/api-reference.md` and confirm 0 matches 6. **Broken links (Cat 6):** Run `ls docs/api/interfaces/` and confirm directory doesn't exist 7. **MkDocs syntax (Cat 7):** Run `grep -c "=== " docs/getting-started/installation.md` and confirm non-zero count 8. **Sidebar (Cat 8):** Read `docs-site/sidebars.ts` and confirm `context-compaction` is absent from the items list 9. **Types (Cat 9):** Run `ls docs/api/type-aliases/StreamOptions.md` and confirm file doesn't exist 10. **Quality (Cat 10):** Read `docs/configuration.md` line 12 and confirm nonsensical migration note 11. **Missing guides (Cat 11):** Run `ls examples/` and confirm no `streaming-basic.ts` or `embeddings.ts` 12. **README (Cat 12):** Read `README.md` lines 9-17 and confirm hero code uses wrong API --- ## Statistics | Metric | Count | | ------------------------------------------- | ------------------------------------------------------------------------ | | Total documentation files | 481 | | Total issues identified | 200+ | | Broken code examples | 32 | | Missing feature documentation pages | 7 | | Missing provider documentation pages | 3 | | Incorrect provider documentation | 2 | | Undocumented CLI commands | 5 | | Undocumented SDK public methods | ~50+ | | Broken internal links | 66 | | Broken anchor links | 5 (3 of original 8 were false positives — valid `&` → `--` slugs) | | Orphaned pages (not in sidebar) | 70 | | Duplicate documentation files | 16 pairs | | MkDocs syntax instances (won't render) | ~49 tabs (corrected from overstated 351), 20+ admonitions, 11 icon files | | "Coming Soon" placeholders | 40+ | | Phantom API docs (non-existent code) | 5 files | | Missing TypeDoc pages for critical types | 17+ | | Missing model enum TypeDoc pages | 8 | | Server sub-entry exports with zero API docs | ~120 | | Feature doc sections missing Quick Start | 11 | | Missing runnable example files | 8 | | Missing cookbook recipes | 6 | --- ## Audit Metadata - **Date:** 2026-03-17 - **Branch:** `fix/documentation` - **Package version:** 9.26.1 - **Agents used:** 16 parallel investigation agents - **Agent types:** Explore (2), feature-dev:code-explorer (4), general-purpose (10) - **Total investigation time:** ~45 minutes wall clock (parallel execution) - **Files examined:** 481 documentation files + ~200 source files --- ## Migration Guide: Breaking Changes # Migration Guide: Breaking Changes This document tracks **breaking changes** shipped in specific NeuroLink releases — changes to public SDK/CLI surface that require an update on the consumer side, as opposed to the additive/backward-compatible changes covered by [`docs/guides/migration-guide.md`](/docs/guides/migration) and the auto-generated changelog (see the [GitHub releases page](https://github.com/juspay/neurolink/releases)). Four breaking changes have shipped (three across 9.94.x–9.95.x, one in 11.0.0), and a fifth is registered below before release. Each is intentional — this document exists so downstream consumers know what changed and how to adapt. ## Policy Per this repository's `CLAUDE.md` (Critical Rule 5), the public SDK API must not break existing callers. The first four breaking changes below (9.94.x–9.95.x and 11.0.0) shipped without an accompanying migration path and are documented here retroactively. Going forward, any breaking change **must** ship its migration path in the same release that introduces it — not documented after the fact. ## 2. `MessageContent` dropped its open index signature (v9.94.6) **What changed:** the exported `MessageContent` type (`src/lib/types/multimodal.ts`, re-exported via `src/lib/types/index.ts` and the package root) no longer has a `[key: string]: unknown` index signature. It's now a closed shape with the concrete fields the pipeline actually reads: `type`, `text`, `image`, `mimeType`, `data`, `name`, `filename`, `toolCallId`, `toolName`, `args`, `result`, `isError`, `providerOptions`. **Why:** the open index signature let any typo or unrelated key through type-checking unchecked (e.g. `{ type: "text", txt: "..." }` compiled fine and silently produced empty content). Closing it catches that class of bug at compile time for everyone building `MessageContent[]` arrays directly. **Before:** ```typescript // Compiled fine even though "customField" isn't a real MessageContent key — // the typo/extra field was silently accepted. const item: MessageContent = { type: "text", text: "hello", customField: "some app-specific metadata", }; ``` **After:** ```typescript // TS2353: Object literal may only specify known properties, and // 'customField' does not exist in type 'MessageContent'. const item: MessageContent = { type: "text", text: "hello", customField: "some app-specific metadata", // ❌ no longer type-checks }; ``` **How to adapt:** - If you were attaching arbitrary metadata to a `MessageContent` item, use the dedicated `providerOptions?: Record` field instead — it's read by `MessageBuilder` when converting to `ModelMessage[]` and is the intended extension point. - If you genuinely need a field NeuroLink doesn't model, open an issue — `MessageContent` intentionally stays a closed, hand-maintained shape rather than reopening a blanket index signature (see the `#325` comment on the type itself). - Runtime behavior is unchanged — this is a compile-time-only break. Plain JavaScript callers, or TypeScript callers that never annotated a literal as `MessageContent` explicitly, are unaffected. --- ## 3. `BatchCommandArgs.file` renamed to `.promptsFile` (v9.95.1) **What changed:** the public CLI argument type `BatchCommandArgs` (`src/lib/types/cli.ts`) renamed its `file?: string` property to `promptsFile?: string`. **Why:** yargs implicitly registers a positional argument's key as a recognized flag name too. Keeping the property named `file` collided with the _unrelated_ common `--file` auto-detect flag that the `batch` command intentionally does not register — `--file` on `batch` would silently pass `strictOptions()` without actually doing anything. Renaming the positional's backing property to `promptsFile` removes that collision. **Before:** ```typescript function handleBatch(argv: BatchCommandArgs) { const promptsListPath = argv.file; // ❌ no longer exists } ``` **After:** ```typescript function handleBatch(argv: BatchCommandArgs) { const promptsListPath = argv.promptsFile; // ✅ } ``` **How to adapt:** - Update any code that constructs or reads a `BatchCommandArgs` object directly (custom CLI wrappers, tests) to use `.promptsFile` instead of `.file`. - The CLI's own `` positional argument and its behavior are unchanged — this is a type-only rename of the property NeuroLink's own `batch` command handler reads internally; end users invoking `neurolink batch ` on the command line see no difference. --- ## 4. Unused provider-option types, `ParameterNormalizer` and `OpenRouterConfig` were removed (v11.0.0) **Who is affected:** code that imports any of the ten names below from `@juspay/neurolink`. Nothing in the SDK or the CLI read these shapes, so code that never imported them is unaffected and no `generate()`/`stream()` behavior changed. **What changed:** the Phase-1 "universal provider options" abstraction (`src/lib/types/universalProviderOptions.ts`) was deleted and `OpenRouterConfig` was removed from `src/lib/types/providers.ts`. The package root re-exports the whole types barrel (`export * from "./types/index.js"` in `src/lib/index.ts`), so all ten names were importable from `@juspay/neurolink` through v10.12.9. They are absent from v11.0.0 and from the current `release` branch. Importing one now fails: TS2305 in TypeScript, a missing named export in native ESM. | Removed export | Kind | What it was | | -------------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `UniversalProviderOptions` | type | Optional `prompt`, `model`, `temperature`, `maxTokens`, `systemPrompt`, `enableAnalytics`, `enableEvaluation`, `context`, `contextConfig`, `metadata`, `extensionOptions`. | | `GenericProviderOptions` | type | `UniversalProviderOptions` without `providerType`. | | `OpenAIProviderOptions` | type | `UniversalProviderOptions` plus `providerType: "openai"`, `organization`, `seed`, `topP`. | | `GoogleAIProviderOptions` | type | `UniversalProviderOptions` plus `providerType: "google-ai"`, `topK`, `candidateCount`, `stopSequences`. | | `AnthropicProviderOptions` | type | `UniversalProviderOptions` plus `providerType: "anthropic"`, `topK`, `stopSequences`. | | `BedrockProviderOptions` | type | `UniversalProviderOptions` plus `providerType: "bedrock"`, `inferenceProfileArn`, `region`. | | `ProviderSpecificOptions` | type | The union of the four provider-specific types above. | | `ProviderFactoryConfig` | type | `{ providerName; modelName?; options?; enableMCP? }`. | | `ParameterNormalizer` | class (runtime value) | Static helpers `normalizeToUniversal`, `extractProviderOptions` and `mergeWithDefaults`. | | `OpenRouterConfig` | type | `{ apiKey: string; referer?: string; appName?: string }`. | **Why:** nothing used them. The abstraction was an abandoned design with no consumer in `src/`, and `OpenRouterConfig` was read only by a dead helper that was deleted with it. The removal landed in a single commit that described it as nominal and deliberately not breaking; its BREAKING CHANGE note was nevertheless parsed as a breaking change, so it shipped in the major release v11.0.0 (see its BREAKING CHANGES entry in `CHANGELOG.md`). Removing exported names is a breaking change whatever the number of consumers. **How to adapt:** - **The nine types.** There is no replacement and no automatic migration: no provider ever accepted these shapes. Delete the import. If your own code still needs one, copy the type alias into your own module. The exact definitions are in `src/lib/types/universalProviderOptions.ts` and, for `OpenRouterConfig`, `src/lib/types/providers.ts` at the `v10.12.9` tag. - **`ParameterNormalizer` is a runtime class, not just a type.** Copying a type alias does not bring it back; if you called it, inline what you used. `normalizeToUniversal(x)` was `typeof x === "string" ? { prompt: x } : x`. `mergeWithDefaults(options, defaults)` spread `defaults` then `options` and merged `context`, `contextConfig` and `metadata` one level deep with the same rule. `extractProviderOptions(options, type)` returned `options` unchanged when its `providerType` equalled `type`, and otherwise `options` without the `providerType` key. Exact source: the same file at `v10.12.9`. - **`OpenRouterConfig`.** The SDK never read it. The OpenRouter provider takes its key from `credentials.openrouter.apiKey` (per call or on the instance) or the `OPENROUTER_API_KEY` environment variable, and its attribution headers from `OPENROUTER_REFERER` and `OPENROUTER_APP_NAME`. Keep your own type if you want one. Other files deleted in the same commit are not importable through the package's `exports` map and are not listed here. --- ## 5. `stream()` synthesizes whenever `tts.enabled` is set (unreleased) **Who is affected:** SDK callers using `stream()` with `tts.enabled: true` without setting `useAiResponse: true`. **What changed:** those callers now receive incremental `tts_audio` chunks and the aggregate `streamResult.audio`. `useAiResponse` continues to choose input versus response synthesis for `generate()`; it no longer gates synthesis for `stream()`. **How to adapt:** disable TTS for a text-only stream by omitting `tts` or setting `tts.enabled: false`. Keep `tts.enabled: true` when streamed response audio is desired; no `useAiResponse` value is required on that path. --- ## AI Analysis Tools # AI Analysis Tools **NeuroLink** features **3 specialized AI Analysis Tools** for AI optimization and workflow enhancement. These tools work seamlessly behind our factory method interface, providing enterprise-grade AI analysis capabilities. ## Production Status **Production Ready: 20/20 Tests Passing (100% Success Rate)** - ✅ **3 AI Analysis Tools Implemented**: Complete AI optimization and analysis capabilities - ✅ **Enterprise Integration**: Professional web interface with full API endpoints - ✅ **Performance Validated**: All tools execute under 1ms individually, 7 seconds total for full suite - ✅ **Production Infrastructure**: Rich context, permissions, error handling, comprehensive validation ## Available Tools ### 1. AI Usage Analysis - `analyzeAIUsage()` Analyze AI usage patterns, token consumption, and cost optimization across your configured providers. ```typescript const analysis = await provider.analyzeAIUsage({ timeframe: "last-24-hours", providers: ["openai", "bedrock", "vertex", "google-ai"], includeOptimizations: true, }); console.log(analysis.tokenUsage); // Token consumption patterns console.log(analysis.costBreakdown); // Cost analysis by provider console.log(analysis.recommendations); // Optimization suggestions ``` **Features:** - **Token Usage Analytics**: Detailed breakdown by provider and time period - **Cost Optimization**: Identify most cost-effective providers for your workload - **Usage Patterns**: Detect peak usage times and optimization opportunities - **Provider Comparison**: Side-by-side cost and performance analysis ### 2. Provider Performance Benchmarking - `benchmarkProviders()` Advanced benchmarking with latency, quality, and cost metrics across configured AI providers. ```typescript const benchmark = await provider.benchmarkProviders({ iterations: 3, testPrompts: ["balanced", "creative", "technical"], includeQualityMetrics: true, }); console.log(benchmark.latencyResults); // Response time comparisons console.log(benchmark.qualityScores); // Content quality analysis console.log(benchmark.costEfficiency); // Cost per token analysis ``` **Features:** - **Latency Testing**: Measure real response times across providers - **Quality Assessment**: Evaluate output quality for different prompt types - **Cost Efficiency**: Calculate cost per token and value metrics - **Provider Rankings**: Automatic ranking by performance criteria ### 3. Prompt Parameter Optimization - `optimizePrompt()` Optimize prompt parameters (temperature, max tokens, style) for better output quality. ```typescript const optimization = await provider.optimizePrompt({ prompt: "Write a professional email explaining AI benefits", style: "balanced", optimizeFor: "quality", includeAlternatives: true, }); console.log(optimization.optimizedParameters); // Temperature, max tokens, etc. console.log(optimization.expectedImprovement); // Quality enhancement predictions console.log(optimization.alternatives); // Alternative parameter sets ``` **Features:** - **Parameter Tuning**: Automatic optimization of temperature, max tokens, style - **Quality Prediction**: Estimate quality improvements from parameter changes - **Alternative Suggestions**: Multiple parameter sets for different use cases - **Style Optimization**: Adjust parameters for specific writing styles ## Business Benefits ### Cost Optimization - **Provider Cost Analysis**: Identify most cost-effective providers for your workload - **Usage Pattern Insights**: Detect opportunities to reduce token consumption - **Budget Planning**: Predict costs based on historical usage patterns ### Performance Enhancement - **Real-time Benchmarking**: Continuous performance monitoring across providers - **Quality Metrics**: Measure and improve output quality over time - **Latency Optimization**: Choose fastest providers for time-sensitive applications ### Parameter Intelligence - **Automated Tuning**: Remove guesswork from prompt parameter selection - **Quality Prediction**: Understand impact of parameter changes before implementation - **Style Adaptation**: Optimize parameters for different content types ## Interactive Web Interface All AI Analysis Tools are available through our unified demo application with professional UI: ```bash cd neurolink-demo && node server.js # Visit http://localhost:9876 to see AI Analysis Tools in action ``` ### Features - ✅ **Real-time Analysis**: Interactive forms for all 3 analysis tools - ✅ **API Endpoints**: Full REST API at `/api/ai/analyze-usage`, `/api/ai/benchmark-performance`, `/api/ai/optimize-parameters` - ✅ **JSON Results**: Comprehensive analysis results with visual feedback - ✅ **Simulation Mode**: Fallback to realistic simulated responses for demonstration ### API Endpoints #### Analyze AI Usage ```bash POST /api/ai/analyze-usage Content-Type: application/json { "timeframe": "last-24-hours", "providers": ["openai", "vertex", "google-ai"], "includeOptimizations": true } ``` #### Benchmark Performance ```bash POST /api/ai/benchmark-performance Content-Type: application/json { "iterations": 3, "testPrompts": ["balanced", "creative"], "includeQualityMetrics": true } ``` #### Optimize Parameters ```bash POST /api/ai/optimize-parameters Content-Type: application/json { "prompt": "Write a technical blog post", "style": "professional", "optimizeFor": "quality" } ``` ## Visual Documentation ### Screenshots - **AI Usage Analysis Interface**: Interactive form with real-time token analysis - **Performance Benchmarking**: Provider comparison with latency and quality metrics - **Parameter Optimization**: Prompt tuning interface with multiple suggestions ### Demo Videos All analysis tools are demonstrated in our comprehensive demo videos: - **[Visual Demos](/docs/)** - Real-time analysis and optimization demonstrations ## Technical Implementation ### MCP Integration AI Analysis Tools are implemented as MCP (Model Context Protocol) tools that work internally behind our factory methods: ```typescript // Internal MCP tool execution (transparent to users) const mcpTools = [ "analyze-ai-usage", "benchmark-provider-performance", "optimize-prompt-parameters", ]; ``` ### Error Handling - **Graceful Fallback**: Tools fall back to simulation mode if AI providers unavailable - **Comprehensive Validation**: Input validation and error reporting - **Production Logging**: Detailed logging for debugging and monitoring ### Performance Metrics - **Tool Execution**: Individual tools execute under 1ms - **Suite Execution**: Complete analysis suite runs in ~7 seconds - **API Response**: REST endpoints respond within 2-5 seconds - **Error Recovery**: Automatic fallback to simulation mode on provider failures ## Getting Started 1. **Install NeuroLink**: `npm install @juspay/neurolink` 2. **Set up providers**: Configure at least one AI provider (see [Provider Configuration](/docs/getting-started/provider-setup)) (now with authentication and model availability checks) 3. **Try the tools**: Use factory methods or visit the demo application 4. **Integrate APIs**: Use REST endpoints for web applications ## Related Documentation - **[Main README](/docs/)** - Project overview and quick start - **[AI Workflow Tools](/docs/ai-workflow-tools)** - Development lifecycle tools - **[MCP Foundation](/docs/mcp/overview)** - Technical architecture details - **[API Reference](/docs/sdk/api-reference)** - Complete TypeScript API - **[Visual Demos](/docs/visual-demos)** - Screenshots and videos --- **Enterprise AI Analysis** - Transform your AI development workflow with data-driven insights and optimization recommendations. --- ## NeuroLink AI Enhancements - Complete Documentation # NeuroLink AI Enhancements - Complete Documentation ## Overview NeuroLink v3.1.0 introduces 6 powerful AI enhancement features that transform it from a basic AI SDK into a comprehensive AI development platform with quality monitoring and analytics capabilities. ## 🆕 New Features ### 1. Response Quality Evaluation ⭐ AI-powered quality scoring using fast, cost-effective models to evaluate response quality on multiple dimensions. **Metrics:** - **Relevance** (1-10): How well the response addresses the prompt - **Accuracy** (1-10): Factual correctness of the information - **Completeness** (1-10): Whether the response fully answers the question - **Overall** (1-10): Combined quality assessment **Configuration:** ```bash # Optional environment variables NEUROLINK_EVALUATION_MODEL=gemini-2.5-flash NEUROLINK_EVALUATION_PROVIDER=google-ai ``` ### 2. Usage Analytics Comprehensive tracking of AI usage patterns, costs, and performance metrics. **Metrics Captured:** - Token usage (input, output, total) - Estimated costs (based on provider pricing) - Response time - Provider and model used - Custom context data - Timestamp **Supported Cost Estimation:** - OpenAI (GPT-4, GPT-4 Turbo, GPT-3.5 Turbo) - Anthropic (Claude 3 Opus, Sonnet, Haiku) - Google AI (Gemini Pro, Gemini 2.5 Flash) ### 3. Generic Context Flow Pass custom context objects through the entire AI request lifecycle for domain-specific tracking and analytics. **Use Cases:** - User identification (`userId`, `sessionId`) - Domain-specific metadata (`department`, `project`) - Request categorization (`priority`, `type`) - Custom business logic data ### 4. Quality Monitoring Analytics and evaluation data returned in response objects for user-controlled alerting and monitoring. **No External Dependencies:** - All data stays within NeuroLink ecosystem - Users control what to do with the data - No forced external endpoints or webhooks ## ️ SDK Usage ### Basic Usage with Analytics ```typescript const sdk = new NeuroLink(); const result = await sdk.generate({ input: { text: "Explain artificial intelligence in simple terms" }, provider: "openai", enableAnalytics: true, // 🆕 NEW: Track usage and costs context: { // 🆕 NEW: Custom context userId: "user-123", department: "engineering", requestType: "explanation", }, }); console.log(result.content); // AI response console.log(result.analytics); // Usage metrics // { // provider: 'openai', // model: 'gpt-4o', // tokens: { input: 15, output: 150, total: 165 }, // cost: 0.00495, // Estimated cost in USD // responseTime: 2340, // timestamp: '2025-01-15T10:30:00.000Z', // context: { userId: 'user-123', department: 'engineering', requestType: 'explanation' } // } ``` ### Usage with Quality Evaluation ```typescript const result = await sdk.generate({ input: { text: "Write a technical explanation of machine learning" }, provider: "google-ai", enableEvaluation: true, // 🆕 NEW: AI quality scoring context: { domain: "technology", audience: "technical", expectedLength: "detailed", }, }); console.log(result.evaluation); // { // relevanceScore: 9, // accuracyScore: 8, // completenessScore: 9, // overallScore: 8.7, // evaluationModel: 'gemini-2.5-flash', // evaluationTime: 1200 // } ``` ### Combined Analytics and Evaluation ```typescript const result = await sdk.generate({ input: { text: "Generate a product description for AI software" }, enableAnalytics: true, // Track usage and costs enableEvaluation: true, // Score response quality context: { productId: "ai-toolkit-v2", userId: "marketing-001", campaign: "product-launch-2025", }, }); // Access all enhancement data const { content, analytics, evaluation } = result; // Custom monitoring logic if (evaluation.overallScore 0.1) { console.warn("High cost request detected"); } // Send to your monitoring system sendToMonitoring({ requestId: analytics.context.productId, quality: evaluation.overallScore, cost: analytics.cost, responseTime: analytics.responseTime, }); ``` ## ️ CLI Usage ### Analytics Tracking ```bash # Enable analytics with debug output npx @juspay/neurolink generate "Explain quantum computing" \ --enable-analytics \ --debug # Output includes: # - AI response text # - Token usage details # - Estimated costs # - Response time # - Provider information ``` ### Quality Evaluation ```bash # Enable response quality scoring npx @juspay/neurolink generate "Write a business proposal" \ --enable-evaluation \ --debug # Output includes: # - AI response text # - Quality scores (relevance, accuracy, completeness, overall) # - Evaluation model used # - Evaluation time ``` ### Custom Context ```bash # Pass custom context data npx @juspay/neurolink generate "Help with customer issue" \ --context '{"userId":"support-001","priority":"high","department":"customer-service"}' \ --enable-analytics \ --debug # Context appears in analytics data for tracking ``` ### All Features Combined ```bash # Use all enhancement features together npx @juspay/neurolink generate "Generate marketing copy for AI product" \ --enable-analytics \ --enable-evaluation \ --context '{"campaign":"q1-2025","target":"developers","budget":"high"}' \ --provider openai \ --temperature 0.8 \ --debug ``` ### 5. Universal Evaluation System Enterprise-grade multi-provider evaluation with intelligent fallback, cost optimization, and performance tuning. **Key Features:** - **Multi-Provider Support**: Google AI, OpenAI, Anthropic, Vertex, Bedrock, Azure, Ollama, Hugging Face, Mistral - **Intelligent Fallback**: Automatic provider selection when primary fails - **Cost Optimization**: Provider-specific cost calculations and budget awareness - **Performance Modes**: Fast, balanced, and quality evaluation options - **Retry Logic**: Robust error handling with exponential backoff **Configuration:** ```bash # Primary evaluation setup NEUROLINK_EVALUATION_PROVIDER=google-ai NEUROLINK_EVALUATION_MODE=fast NEUROLINK_EVALUATION_FALLBACK_ENABLED=true NEUROLINK_EVALUATION_FALLBACK_PROVIDERS=openai,anthropic,vertex # Cost optimization NEUROLINK_EVALUATION_PREFER_CHEAP=true NEUROLINK_EVALUATION_MAX_COST_PER_EVAL=0.01 # Performance tuning NEUROLINK_EVALUATION_TIMEOUT=10000 NEUROLINK_EVALUATION_RETRY_ATTEMPTS=2 ``` **Usage:** ```typescript // Automatic provider selection const result = await sdk.generate({ input: { text: "Explain quantum computing" }, enableEvaluation: true, // Uses configured evaluation system }); // Will try: google-ai → openai → anthropic → vertex (if primary fails) ``` **CLI Usage:** ```bash # Uses Universal Evaluation System automatically npx @juspay/neurolink generate "What is machine learning?" --enable-evaluation # With debug to see provider selection npx @juspay/neurolink generate "Explain AI" --enable-evaluation --debug ``` ### 6. Lighthouse Enhanced Evaluation Domain-aware evaluation with 6-dimensional scoring based on Lighthouse AI platform patterns. **Enhanced Scoring Dimensions:** - **Relevance Score** (1-10): How well response addresses the prompt - **Accuracy Score** (1-10): Factual correctness of information - **Completeness Score** (1-10): Whether response fully answers question - **Domain Alignment** (1-10): Expertise alignment with specified domain - **Terminology Accuracy** (1-10): Proper use of domain-specific terms - **Tool Effectiveness** (1-10): How well MCP tools were utilized **Advanced Features:** - **Context Integration**: Tool usage tracking and conversation history - **Domain Expertise**: Specialized evaluation prompts for specific domains - **Enterprise Telemetry**: Structured logging with OpenTelemetry patterns - **Backward Compatibility**: Full compatibility with Universal Evaluation System **CLI Usage:** ```bash # Basic Lighthouse-style evaluation npx @juspay/neurolink generate "Fix this Python code" \ --lighthouse-style \ --evaluation-domain "Python coding assistant" # Enterprise evaluation with full context npx @juspay/neurolink generate "Analyze sales performance" \ --lighthouse-style \ --evaluation-domain "Business data analyst" \ --tool-usage-context "Used sales-data and analytics MCP tools" \ --context '{"role":"senior_analyst","department":"sales"}' ``` **SDK Usage:** ```typescript performEnhancedEvaluation, createEnhancedContext, } from "@juspay/neurolink"; // Create enhanced evaluation context const enhancedContext = createEnhancedContext( "Write a business proposal for Q1 expansion", result.text, { domain: "Business development", role: "Business proposal assistant", toolsUsed: ["generate", "analytics-helper"], conversationHistory: [ { role: "user", content: "I need help with our Q1 business plan" }, { role: "assistant", content: "I can help you create a comprehensive plan", }, ], }, ); // Perform enhanced evaluation const domainEvaluation = await performEnhancedEvaluation(enhancedContext); console.log(" Enhanced Evaluation:", domainEvaluation); // { // relevanceScore: 9, accuracyScore: 8, completenessScore: 9, // domainAlignment: 9, terminologyAccuracy: 8, toolEffectiveness: 9, // overall: 8.7, alertSeverity: 'none' // } ``` ## Interface Reference ### Enhanced TextGenerationOptions ```typescript type TextGenerationOptions = { // Existing fields (unchanged) input: { text: string }; provider?: string; model?: string; temperature?: number; maxTokens?: number; systemPrompt?: string; timeout?: number | string; disableTools?: boolean; // NEW: AI Enhancement fields enableAnalytics?: boolean; // Default: false enableEvaluation?: boolean; // Default: false context?: Record; // Default: undefined }; ``` ### AnalyticsData Structure ```typescript type AnalyticsData = { provider: string; // AI provider used model: string; // Specific model name tokens: { input: number; // Input tokens output: number; // Output tokens total: number; // Total tokens }; cost?: number; // Estimated cost (USD) responseTime: number; // Response time (ms) timestamp: string; // ISO timestamp context?: Record; // User context }; ``` ### EvaluationData Structure ```typescript type EvaluationData = { relevanceScore: number; // 1-10 scale accuracyScore: number; // 1-10 scale completenessScore: number; // 1-10 scale overallScore: number; // 1-10 scale evaluationModel: string; // Model used for evaluation evaluationTime: number; // Evaluation time (ms) }; ``` ## Configuration ### Environment Variables ```bash # Response Quality Evaluation (optional) NEUROLINK_EVALUATION_MODEL=gemini-2.5-flash NEUROLINK_EVALUATION_PROVIDER=google-ai # Provider API Keys (existing) OPENAI_API_KEY=sk-your-openai-key GOOGLE_AI_API_KEY=AIza-your-google-ai-key AWS_ACCESS_KEY_ID=your-aws-access-key # ... other provider keys ``` ### Cost Estimation Configuration Built-in pricing for major providers (updated regularly): ```typescript const costMap = { openai: { "gpt-4": { input: 0.03, output: 0.06 }, "gpt-4-turbo": { input: 0.01, output: 0.03 }, "gpt-3.5-turbo": { input: 0.0015, output: 0.002 }, }, anthropic: { "claude-3-opus": { input: 0.015, output: 0.075 }, "claude-3-sonnet": { input: 0.003, output: 0.015 }, "claude-3-haiku": { input: 0.00025, output: 0.00125 }, }, "google-ai": { "gemini-pro": { input: 0.00035, output: 0.00105 }, "gemini-2.5-flash": { input: 0.000075, output: 0.0003 }, }, }; ``` ## Performance Considerations ### Performance Impact - **Features Disabled (default)**: Zero overhead - **Analytics Only**: \ r.evaluation.overallScore >= 8, ); ``` ### Cost Monitoring Dashboard ```typescript function createCostDashboard() { const dailyCosts = []; const qualityMetrics = []; // Track all AI requests sdk.getEventEmitter().on("generation:end", (event) => { // A failed generation emits generation:end without a result const result = (event as { result?: GenerateResult }).result; if (!result) { return; } if (result.analytics) { dailyCosts.push({ date: new Date(result.analytics.timestamp), cost: result.analytics.cost, provider: result.analytics.provider, tokens: result.analytics.tokens.total, }); } if (result.evaluation) { qualityMetrics.push({ date: new Date(), quality: result.evaluation.overallScore, prompt: result.analytics?.context?.promptType, }); } }); } ``` ## Best Practices 1. **Enable Analytics by Default**: Track all production usage 2. **Selective Evaluation**: Use for critical or customer-facing content 3. **Meaningful Context**: Include user/session IDs for tracking 4. **Quality Thresholds**: Set minimum quality scores for auto-publish 5. **Cost Alerts**: Monitor spending with custom thresholds 6. **Performance Monitoring**: Track response times and token usage 7. **A/B Testing**: Use context to track different prompt strategies --- _NeuroLink AI Enhancements v3.1.0 - Transform your AI applications with comprehensive quality monitoring and analytics._ --- ## ️ AI Development Workflow Tools # ️ AI Development Workflow Tools **NeuroLink** features **4 specialized AI Development Workflow Tools** for comprehensive AI development lifecycle support. These tools work seamlessly behind our factory method interface, providing enterprise-grade development assistance. ## Production Status **Production Ready: 24/24 Tests Passing (100% Success Rate)** - ✅ **4 AI Workflow Tools Implemented**: Complete development lifecycle support - ✅ **Platform Evolution**: NeuroLink now features 10 specialized tools (3 core + 3 analysis + 4 workflow) - ✅ **Performance Validated**: All tools designed for \ sum + item.price, 0); }", testTypes: ["unit", "integration", "edge-cases"], framework: "jest", }); console.log(testCases.unitTests); // Unit test scenarios console.log(testCases.edgeCases); // Edge case coverage console.log(testCases.integrationTests); // Integration test patterns ``` **Features:** - **Unit Test Generation**: Comprehensive unit test coverage for functions and classes - **Edge Case Detection**: Identify and test boundary conditions and error scenarios - **Integration Testing**: Generate tests for component interactions and API endpoints - **Framework Support**: Jest, Mocha, Vitest, and other popular testing frameworks - **Realistic Data**: Generate meaningful test data and mock scenarios ### 2. Code Refactoring - `refactorCode()` AI-powered code refactoring and optimization with performance and maintainability improvements. ```typescript const refactoring = await provider.refactorCode({ sourceCode: ` function processUsers(users) { var result = []; for (var i = 0; i ; }; issues: Array; recommendations: string[]; correctedOutput?: string; confidence: number; }; ``` ## Interactive Web Interface All AI Development Workflow Tools are available through our unified demo application: ```bash cd neurolink-demo && node server.js # Visit http://localhost:9876 to see all 10 AI tools in action ``` ### Features - ✅ **Complete Tool Suite**: Interactive forms for all 10 specialized tools (3 core + 3 analysis + 4 workflow) - ✅ **Full API Coverage**: REST endpoints for all AI Analysis and Workflow tools - ✅ **Professional Results**: Comprehensive output with structured JSON responses - ✅ **Demonstration Mode**: Realistic examples for immediate evaluation ### API Endpoints #### Generate Test Cases ```bash POST /api/ai/generate-test-cases Content-Type: application/json { "codeFunction": "function add(a, b) { return a + b; }", "testTypes": ["unit", "edge-cases"], "framework": "jest" } ``` #### Refactor Code ```bash POST /api/ai/refactor-code Content-Type: application/json { "sourceCode": "var users = []; // legacy code...", "target": "modern-es6", "focusAreas": ["performance", "readability"] } ``` #### Generate Documentation ```bash POST /api/ai/generate-documentation Content-Type: application/json { "codeBase": "class ApiService { ... }", "outputFormat": "markdown", "includeExamples": true } ``` #### Debug AI Output ```bash POST /api/ai/debug-ai-output Content-Type: application/json { "aiResponse": "{ malformed json... }", "expectedFormat": "json", "issueTypes": ["format", "logic"] } ``` ## Visual Documentation ### Screenshots - **Test Case Generation**: Interactive form showing comprehensive test generation - **Code Refactoring**: Before/after code comparison with optimization suggestions - **Documentation Generator**: Automatic API documentation creation interface - **Debug Assistant**: AI output analysis with issue identification and fixes ### Demo Videos All workflow tools are demonstrated in our comprehensive demo videos: - **[Visual Demos](/docs/)** - Complete workflow demonstrations and technical applications ## Technical Implementation ### MCP Integration AI Workflow Tools are implemented as MCP (Model Context Protocol) tools that work internally behind our factory methods: ```typescript // Internal MCP tool execution (transparent to users) const workflowTools = [ "generate-test-cases", "refactor-code", "generate-documentation", "debug-ai-output", ]; ``` ### Real AI Integration - **Enhanced AI Generation**: All tools now use real AI generation instead of mock data - **NeuroLink Integration**: Tools leverage actual `NeuroLink` class with automatic fallback - **Graceful Fallback**: AI tools fall back to mock data only if AI parsing fails - **Provider Tracking**: Tools report which AI provider was actually used ### Error Handling - **Comprehensive Validation**: Input validation and error reporting for all tools - **Production Logging**: Detailed logging for debugging and monitoring - **Graceful Degradation**: Fallback to simulation mode when AI providers unavailable - **Context Preservation**: Maintain context across tool execution chains ### Performance Metrics - **Tool Execution**: Individual tools designed for \<100ms execution - **API Response**: REST endpoints respond within 2-5 seconds - **Error Recovery**: Automatic fallback mechanisms for reliability - **Resource Management**: Efficient handling of large code bases and outputs ## Getting Started ### Prerequisites 1. **Install NeuroLink**: `npm install @juspay/neurolink` 2. **Configure Providers**: Set up at least one AI provider (see [Provider Configuration](/docs/getting-started/provider-setup)) (now with authentication and model availability checks) 3. **Verify Setup**: Run `npx @juspay/neurolink status` to check connectivity ### Quick Examples #### Generate Tests for Your Code ```typescript const provider = createBestAIProvider(); const tests = await provider.generateTestCases({ codeFunction: "your-function-here", testTypes: ["unit", "edge-cases"], framework: "jest", }); ``` #### Refactor Legacy Code ```typescript const refactored = await provider.refactorCode({ sourceCode: "legacy-code-here", target: "modern-es6", focusAreas: ["performance", "readability"], }); ``` #### Generate Documentation ```typescript const docs = await provider.generateDocumentation({ codeBase: "your-code-here", outputFormat: "markdown", includeExamples: true, }); ``` ### Integration Patterns #### CI/CD Integration ```yaml # GitHub Actions example - name: Generate Tests run: npx @juspay/neurolink generate-test-cases --input src/ --output tests/ ``` #### Development Workflow ```bash # Local development commands neurolink refactor-code --file legacy.js --target modern neurolink generate-docs --input src/ --output docs/ neurolink debug-output --file ai-response.json --format json ``` ## Current Integration Status **Total Workflow Tools**: 4 specialized development tools - **Test Generation**: Comprehensive test case creation for all code types - **Code Refactoring**: AI-powered optimization and modernization - **Documentation**: Automatic generation of API docs and guides - **Debug Assistance**: AI output validation and correction **Platform Achievement**: NeuroLink has successfully evolved into a **Comprehensive AI Development Platform** with complete development lifecycle support. ## Related Documentation - **[Main README](/docs/)** - Project overview and quick start - **[AI Analysis Tools](/docs/ai-analysis-tools)** - AI optimization and analysis tools - **[MCP Foundation](/docs/mcp/overview)** - Technical architecture details - **[API Reference](/docs/sdk/api-reference)** - Complete TypeScript API - **[CLI Guide](/docs/cli)** - Command-line interface documentation - **[Visual Demos](/docs/visual-demos)** - Screenshots and videos --- **AI-Powered Development** - Accelerate your development workflow with intelligent code generation, optimization, and quality assurance tools. --- ## Automated Publishing Guide (Semantic Release) # Automated Publishing Guide (Semantic Release) Complete step-by-step guide to set up **semantic-release** for automated GitHub releases, tags, and NPM publishing for NeuroLink. ## Current Status ✅ **GitHub Workflow** - `.github/workflows/release.yml` configured with semantic-release ✅ **Semantic Release Config** - `.releaserc.json` configured ✅ **Dependencies Added** - All semantic-release packages in package.json ⏳ **NPM Token Setup** - Required for NPM publishing ⏳ **First Release** - Ready to trigger after NPM token ## Step-by-Step Setup ### **Step 1: Create NPM Automation Token** 1. **Login to NPM:** ```bash npm login ``` Use your NPM account credentials 2. **Create Automation Token:** ```bash npm token create --type=automation ``` 3. **Copy the token** (starts with `npm_...`) ### **Step 2: Add NPM Token to GitHub Secrets** 1. Go to: https://github.com/juspay/neurolink/settings/secrets/actions 2. Click **"New repository secret"** 3. **Name:** `NPM_TOKEN` 4. **Value:** Paste your NPM automation token 5. Click **"Add secret"** ### **Step 3: Use Conventional Commits** Semantic-release uses **conventional commits** to determine version bumps: ```bash # PATCH version (1.7.0 → 1.7.1) - Bug fixes git commit -m "fix: resolve CLI authentication issue" git commit -m "perf: improve provider selection speed" # MINOR version (1.7.0 → 1.8.0) - New features git commit -m "feat: add new AI provider support" git commit -m "feat(cli): add batch processing command" # MAJOR version (1.7.0 → 2.0.0) - Breaking changes git commit -m "feat!: remove deprecated API methods" git commit -m "fix!: change provider interface signature" # Alternative major version syntax git commit -m "feat: add new authentication BREAKING CHANGE: Previous auth methods no longer supported" ``` ### **Step 4: Trigger Automatic Release** **Just push to release branch with conventional commits!** ```bash # Make your changes with conventional commits git add . git commit -m "feat: add Google AI Studio integration" # Push to release branch git checkout release git merge your-feature-branch git push origin release # SEMANTIC RELEASE HANDLES EVERYTHING: # ✅ Analyzes commit messages # ✅ Determines version bump (patch/minor/major) # ✅ Generates CHANGELOG.md # ✅ Creates Git tag # ✅ Creates GitHub release with notes # ✅ Publishes to NPM # ✅ Publishes to GitHub Packages # ✅ Commits version changes back to repo ``` ## How Semantic Release Works ### **Commit Analysis:** - **fix:** → Patch release (1.7.0 → 1.7.1) - **feat:** → Minor release (1.7.0 → 1.8.0) - **BREAKING CHANGE** or **!** → Major release (1.7.0 → 2.0.0) - **docs:, style:, refactor:, test:, chore:** → No release ### **Generated Assets:** - ️ **Git Tag:** `v1.8.0` (automatically created) - **CHANGELOG.md** (automatically generated and committed) - **GitHub Release** (with professional release notes) - **NPM Package:** https://www.npmjs.com/package/@juspay/neurolink - **GitHub Package:** https://github.com/juspay/neurolink/packages ### **Automatic Updates:** - ✅ **package.json version** updated and committed - ✅ **CHANGELOG.md** generated and committed - ✅ **Git tags** created automatically - ✅ **Release notes** generated from commits ## Expected Results After pushing conventional commits to release branch: ### **Automatic Process:** 1. **Analyzes commits** since last release 2. **Determines version** based on conventional commits 3. **Generates CHANGELOG.md** from commit messages 4. ️ **Creates Git tag** (e.g., v1.8.0) 5. **Creates GitHub release** with generated notes 6. **Publishes to NPM** registry 7. **Publishes to GitHub Packages** 8. **Commits changes** back to release branch ### **GitHub Repository:** - ✅ **Tags:** Automatically created (v1.8.0) - ✅ **Releases:** Professional release notes from commits - ✅ **Packages:** Available on GitHub Packages - ✅ **CHANGELOG.md:** Auto-generated and updated ### **NPM Registry:** - ✅ **Published Package:** `@juspay/neurolink@1.8.0` - ✅ **Installation:** `npm install @juspay/neurolink` ## Troubleshooting ### **Common Issues:** #### **"No release published"** - **Cause:** No conventional commits since last release - **Solution:** Use proper conventional commit format (`feat:`, `fix:`, etc.) #### **"NPM_TOKEN not found"** - **Solution:** Add NPM token to GitHub repository secrets - **Check:** Repository → Settings → Secrets and variables → Actions #### **"Permission denied to publish"** - **Solution:** Ensure NPM token has publishing permissions - **Fix:** Create new automation token with correct permissions #### **"CHANGELOG.md conflicts"** - **Solution:** Semantic-release handles this automatically - **Info:** Don't manually edit CHANGELOG.md - it's auto-generated ### **Verification Commands:** ```bash # Check if package is published npm view @juspay/neurolink # Check latest release gh release view --web # Check semantic-release dry run (locally) npx semantic-release --dry-run ``` ## Conventional Commit Examples ### **Feature Examples:** ```bash feat: add OpenAI GPT-4o support feat(cli): add --stream flag for real-time output feat(providers): add retry logic for failed requests ``` ### **Bug Fix Examples:** ```bash fix: resolve memory leak in provider selection fix(auth): handle expired API keys gracefully fix(cli): correct typo in help text ``` ### **Breaking Change Examples:** ```bash feat!: change provider interface to async/await fix!: remove deprecated createProvider function # Or with body: feat: redesign authentication system BREAKING CHANGE: All providers now require async initialization ``` ### **Other Types:** ```bash docs: update README with new provider instructions style: fix code formatting in provider files refactor: simplify error handling logic test: add unit tests for new providers chore: update dependencies to latest versions perf: optimize provider selection algorithm ``` ## Future Releases ### **Fully Automated Process:** 1. Write code with conventional commits 2. Push to release branch 3. **That's it!** Semantic-release handles everything else ### **No Manual Steps Required:** - ❌ No manual version bumping - ❌ No manual changelog writing - ❌ No manual tag creation - ❌ No manual release creation - ❌ No manual NPM publishing ### **Professional Results:** - ✅ Consistent versioning with SemVer - ✅ Professional changelogs from commits - ✅ Comprehensive release notes - ✅ Zero human error in releases ## ✅ Next Steps 1. **Complete Step 1-2:** NPM token setup 2. **Use conventional commits:** Follow the format above 3. **Push to release branch:** Automatic release triggered 4. **Verify:** Check all platforms have packages 5. **Celebrate:** You now have industry-standard automation! --- ** Need Help?** - Check the workflow logs in GitHub Actions - Ensure NPM_TOKEN is properly configured - Use conventional commit format - Test with `npx semantic-release --dry-run` locally The semantic-release workflow is the industry standard used by thousands of open-source projects. Once set up, you'll have bulletproof, professional-grade release automation! ## References - [Semantic Release Documentation](https://semantic-release.gitbook.io/) - [Conventional Commits Specification](https://www.conventionalcommits.org/) - [GitHub Actions for Semantic Release](https://github.com/semantic-release/semantic-release/blob/master/docs/usage/github-actions.md) --- ## Workflow Engine - High-Level Design # Neurolink Workflow Engine - High-Level Design (HLD) **Version**: 1.0 **Date**: November 28, 2025 **Status**: Implementation Complete **Author**: Neurolink Team ## Goals & Non-Goals ### Goals (Testing Phase) 1. **Enable Multi-Model Workflows**: Run N models in parallel for the same prompt 2. **Intelligent Evaluation**: Use judge models to score (0-100) and rank responses 3. **Comprehensive Logging**: Detailed metrics for AB testing and evaluation 4. **Original Output**: Return best response unchanged for production safety 5. **Cost Transparency**: Provide clear cost/performance metrics 6. **Seamless Integration**: Work with existing Neurolink provider layer ### Non-Goals (Phase 1 - Testing) - ❌ Response conditioning/modification (deferred until testing validates workflows) - ❌ Streaming workflow execution (deferred to Phase 2) - ❌ Stateful/resumable workflows (deferred to Phase 2) - ❌ DAG-based workflow chaining (deferred to Phase 3) - ❌ Human-in-the-loop approval steps (deferred to Phase 3) - ❌ Workflow versioning/migration (deferred to Phase 3) --- ## ️ Architecture Overview ### System Context ``` ┌─────────────────────────────────────────────────────────────┐ │ Neurolink SDK │ │ │ │ ┌──────────────┐ ┌─────────────────┐ │ │ │ NeuroLink │────────▶│ Workflow Engine │◀─────┐ │ │ │ Class │ └─────────────────┘ │ │ │ └──────────────┘ │ │ │ │ │ ▼ │ │ │ │ ┌──────────────┐ │ │ │ │ │ Workflow │ │ │ │ │ │ Registry │ │ │ │ │ └──────────────┘ │ │ │ │ │ │ │ │ ▼ ▼ │ │ │ ┌──────────────┐ ┌──────────────┐ │ │ │ │ AI Provider │ │ Ensemble │────────┘ │ │ │ Factory │◀────────│ Executor │ │ │ └──────────────┘ └──────────────┘ │ │ │ │ │ │ │ ▼ │ │ │ ┌──────────────┐ │ │ │ │ Judge │ │ │ │ │ Scorer │ │ │ │ └──────────────┘ │ │ │ │ │ │ ▼ ▼ │ │ ┌──────────────────────────────────────┐ │ │ │ BaseProvider Layer │ │ │ │ (OpenAI, Anthropic, Google, etc.) │ │ │ └──────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ ``` ### Component Hierarchy ``` src/lib/types/ └── workflowTypes.ts # All workflow type definitions (centralized) src/lib/workflow/ ├── index.ts # Public API exports ├── types.ts # Re-exports from types/workflowTypes.ts ├── config.ts # Configuration schemas & defaults │ ├── core/ │ ├── workflowRunner.ts # Main orchestrator │ ├── workflowRegistry.ts # Workflow template registry │ ├── ensembleExecutor.ts # Multi-model parallel execution │ ├── judgeScorer.ts # Judge model scoring │ └── responseConditioner.ts # Response post-processing │ ├── workflows/ # Built-in workflow implementations │ ├── consensusWorkflow.ts # 3-5 models + judge │ ├── fallbackWorkflow.ts # Sequential fallback chain │ ├── multiJudgeWorkflow.ts # Multiple judges with voting │ └── adaptiveWorkflow.ts # Dynamic model selection │ └── utils/ ├── workflowValidation.ts # Config validation └── workflowMetrics.ts # Performance tracking ``` --- ## Workflow Execution Flow ### High-Level Process ``` ┌────────────────────────────────────────────────────────────┐ │ 1. USER REQUEST │ │ neuro.generate({ │ │ workflowConfig: { workflowId: 'consensus-3' }, │ │ input: { text: 'Explain quantum computing' } │ │ }) │ └────────────────────────────────────────────────────────────┘ ↓ ┌────────────────────────────────────────────────────────────┐ │ 2. WORKFLOW RESOLUTION │ │ - Load workflow config from registry │ │ - Validate configuration │ │ - Apply runtime overrides (if any) │ └────────────────────────────────────────────────────────────┘ ↓ ┌────────────────────────────────────────────────────────────┐ │ 3. ENSEMBLE EXECUTION (Parallel) │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ Model 1 │ │ Model 2 │ │ Model 3 │ │ │ │ GPT-4o │ │ Claude │ │ Gemini │ │ │ └──────────┘ └──────────┘ └──────────┘ │ │ │ │ │ │ │ └─────────────┴─────────────┘ │ │ ↓ │ │ [Response 1, Response 2, Response 3] │ └────────────────────────────────────────────────────────────┘ ↓ ┌────────────────────────────────────────────────────────────┐ │ 4. JUDGE SCORING (Optional) │ │ - Format responses for judge evaluation │ │ - Call judge model with structured schema │ │ - Parse scores: { resp1: 8.5, resp2: 9.2, resp3: 7.8 } │ │ - Rank/select best response │ └────────────────────────────────────────────────────────────┘ ↓ ┌────────────────────────────────────────────────────────────┐ │ 5. RESPONSE CONDITIONING (Optional) │ │ - Calculate confidence score │ │ - Adjust tone based on confidence │ │ - Add metadata (models used, scores, timing) │ │ - Format final response │ └────────────────────────────────────────────────────────────┘ ↓ ┌────────────────────────────────────────────────────────────┐ │ 6. RETURN WORKFLOW RESULT │ │ { │ │ content: "Quantum computing is...", │ │ confidence: 0.92, │ │ ensembleResponses: [...], │ │ judgeScores: {...}, │ │ totalTime: 3421 │ │ } │ └────────────────────────────────────────────────────────────┘ ``` --- ## Core Components ### 1. Workflow Runner **Purpose**: Main orchestrator that executes workflows end-to-end **Responsibilities**: - Load and validate workflow configurations - Coordinate ensemble → judge → conditioning pipeline - Handle errors and partial failures - Aggregate results with comprehensive metrics **Key Methods**: ```typescript class WorkflowRunner { async execute( config: WorkflowConfig, input: WorkflowInput, ): Promise; async executeWithRetry( config: WorkflowConfig, input: WorkflowInput, retries: number, ): Promise; } ``` --- ### 2. Workflow Registry **Purpose**: Manage workflow templates (built-in + custom) **Responsibilities**: - Store workflow configurations - Provide workflow discovery API - Validate configs before registration - Support workflow CRUD operations **Key Methods**: ```typescript class WorkflowRegistry { register(config: WorkflowConfig): void; get(id: string): WorkflowConfig | undefined; list(): WorkflowConfig[]; validate(config: WorkflowConfig): ValidationResult; } ``` --- ### 3. Ensemble Executor **Purpose**: Execute multiple models in parallel **Responsibilities**: - Create provider instances for each model - Execute requests concurrently via `Promise.all()` - Collect responses with timing/usage data - Handle individual model failures gracefully **Key Methods**: ```typescript class EnsembleExecutor { async execute( models: ModelConfig[], input: string, ): Promise; async executeWithTimeout( models: ModelConfig[], input: string, timeout: number, ): Promise; } ``` **Integration Points**: - Uses `AIProviderFactory.createProvider()` for model instantiation - Calls `BaseProvider.generate()` for each model - Leverages existing analytics from `core/analytics.ts` --- ### 4. Judge Scorer **Purpose**: Evaluate and rank ensemble responses **Responsibilities**: - Format ensemble results for judge evaluation - Call judge model with structured output schema - Parse scores/rankings from judge response - Support multiple scoring strategies (numeric, ranking, best-pick) **Key Methods**: ```typescript class JudgeScorer { async score( responses: EnsembleResponse[], judgeConfig: JudgeConfig, ): Promise; async scoreMultiJudge( responses: EnsembleResponse[], judgeConfigs: JudgeConfig[], ): Promise; } ``` **Scoring Strategies**: 1. **Numeric Scoring**: Return 0-10 scores for each response 2. **Ranking**: Order responses from best to worst 3. **Best Pick**: Select single best response with reasoning 4. **Multi-Judge Voting**: Average scores from multiple judges --- ### 5. Response Conditioner **Purpose**: Post-process responses based on confidence **Responsibilities**: - Calculate overall confidence score - Adjust tone based on confidence level - Add structured metadata - Format final user-facing response **Key Methods**: ```typescript class ResponseConditioner { async condition( response: string, confidence: number, config: ConditioningConfig, ): Promise; calculateConfidence(scores: JudgeScores, consensus: number): number; } ``` **Conditioning Rules**: - **High confidence (>0.8)**: Direct, assertive language - **Medium confidence (0.5-0.8)**: Balanced, qualified language - **Low confidence (\; // Custom metadata }; ``` ### ModelConfig ```typescript type ModelConfig = { provider: AIProviderName; // e.g., 'openai', 'anthropic' model: string; // e.g., 'gpt-4o', 'claude-sonnet-4-6' weight?: number; // Weight for voting (0-1) temperature?: number; // Model temperature maxTokens?: number; // Max response tokens systemPrompt?: string; // Custom system prompt timeout?: number; // Per-model timeout (ms) }; ``` ### JudgeConfig ```typescript type JudgeConfig = { provider: AIProviderName; // Judge model provider model: string; // Judge model name criteria: string[]; // Evaluation criteria outputFormat: JudgeOutputFormat; // 'scores' | 'ranking' | 'best' systemPrompt?: string; // Custom judge prompt blindEvaluation?: boolean; // Hide provider names }; ``` ### WorkflowResult ```typescript type WorkflowResult = { content: string; // Final conditioned response ensembleResponses: EnsembleResponse[]; // All model responses judgeScores?: JudgeScores; // Judge evaluation selectedResponse?: string; // Selected best response confidence: number; // Overall confidence (0-1) totalTime: number; // Total execution time (ms) workflow: string; // Workflow ID used usage?: AggregatedUsage; // Token usage across all models analytics?: WorkflowAnalytics; // Detailed analytics metadata?: Record; // Custom metadata }; ``` --- ## Integration Points ### With Existing Neurolink Infrastructure #### 1. AIProviderFactory ```typescript // Workflow uses existing factory for provider creation const provider = await AIProviderFactory.createProvider( modelConfig.provider, modelConfig.model, ); ``` #### 2. BaseProvider ```typescript // All models use standard generate() method const result = await provider.generate({ input: { text: prompt }, temperature: modelConfig.temperature, systemPrompt: modelConfig.systemPrompt, }); ``` #### 3. Analytics & Evaluation ```typescript // Workflow aggregates existing analytics const analytics = createAnalytics(provider, model, result, time); const evaluation = await evaluateResponse(query, response); ``` #### 4. NeuroLink Class Extension ```typescript // Workflow execution via generate() method export class NeuroLink { async generate( options: GenerateOptions & { workflowConfig?: WorkflowGenerateOptions }, ): Promise { if (options.workflowConfig) { const workflow = workflowRegistry.get(options.workflowConfig.workflowId); return await workflowRunner.execute(workflow, options); } // ... existing generate logic } } // Standalone registry functions registerWorkflow, listWorkflows, getWorkflow, } from "@juspay/neurolink/workflow"; registerWorkflow(config); const workflows = listWorkflows(); const workflow = getWorkflow("consensus-3"); ``` --- ## Built-in Workflows ### 1. Consensus Workflow (consensus-3) **Purpose**: Cross-validate responses across 3 models with judge scoring ```typescript { id: 'consensus-3', name: 'Three Model Consensus', type: 'ensemble', models: [ { provider: 'openai', model: 'gpt-4o' }, { provider: 'anthropic', model: 'claude-sonnet-4-6' }, { provider: 'google-ai', model: 'gemini-3-flash-preview' } ], judge: { provider: 'openai', model: 'gpt-4o', criteria: ['accuracy', 'clarity', 'completeness'], outputFormat: 'best' }, conditioning: { useConfidence: true, toneAdjustment: 'neutral' } } ``` **Use Cases**: High-stakes decisions, factual queries, technical explanations --- ### 2. Fast Fallback Workflow (fast-fallback) **Purpose**: Try fast model first, fallback to powerful model if needed ```typescript { id: 'fast-fallback', name: 'Fast with Quality Fallback', type: 'chain', models: [ { provider: 'google-ai', model: 'gemini-3-flash-preview', timeout: 5000 }, { provider: 'anthropic', model: 'claude-sonnet-4-6', timeout: 10000 } ], conditioning: { useConfidence: true, metadata: { strategy: 'fast-first' } } } ``` **Use Cases**: Cost optimization, performance-sensitive applications --- ### 3. Quality Max Workflow (quality-max) **Purpose**: Maximum quality with dual powerful models ```typescript { id: 'quality-max', name: 'Maximum Quality Ensemble', type: 'ensemble', models: [ { provider: 'openai', model: 'gpt-4o', temperature: 0.3 }, { provider: 'anthropic', model: 'claude-sonnet-4-6', temperature: 0.3 } ], judge: { provider: 'anthropic', model: 'claude-sonnet-4-6', criteria: ['depth', 'reasoning', 'accuracy', 'safety'], outputFormat: 'scores' }, conditioning: { useConfidence: true, toneAdjustment: 'strengthen' } } ``` **Use Cases**: Research, analysis, critical business decisions --- ### 4. Multi-Judge Workflow (multi-judge-5) **Purpose**: Use multiple judges to eliminate bias ```typescript { id: 'multi-judge-5', name: 'Multi-Judge Consensus', type: 'ensemble', models: [ { provider: 'openai', model: 'gpt-4o' }, { provider: 'anthropic', model: 'claude-sonnet-4-6' }, { provider: 'google-ai', model: 'gemini-3-pro-preview' } ], judges: [ // Multiple judges { provider: 'openai', model: 'gpt-4o', criteria: ['accuracy'] }, { provider: 'anthropic', model: 'claude-sonnet-4-6', criteria: ['safety'] } ], conditioning: { useConfidence: true, toneAdjustment: 'neutral' } } ``` **Use Cases**: Bias-sensitive applications, fairness requirements --- ## Performance Characteristics ### Expected Latency | Workflow Type | Models | Judge | Expected Latency | Cost Multiplier | | ------------- | ------ | ----- | ---------------- | --------------- | | Consensus-3 | 3 | 1 | 3-5 seconds | 4x | | Fast-Fallback | 1-2 | 0 | 1-3 seconds | 1-2x | | Quality-Max | 2 | 1 | 3-4 seconds | 3x | | Multi-Judge-5 | 3 | 2 | 4-6 seconds | 5x | ### Optimization Strategies 1. **Parallel Execution**: All ensemble models run concurrently 2. **Timeout Controls**: Per-model timeout prevents hanging 3. **Early Termination**: Optional "first N responses" mode 4. **Model Selection**: Lightweight models for speed, powerful for quality 5. **Concurrency Control**: p-limit for controlled parallel execution --- ## Security & Safety ### Input Validation - Validate workflow configs before execution - Sanitize user inputs before passing to models - Enforce token limits per model - Validate judge output schemas ### Cost Controls - Pre-execution cost estimation - Per-workflow budget limits - Cost tracking and alerting - Rate limiting on workflow execution ### Error Handling - Graceful degradation on partial failures - Retry logic with exponential backoff - Detailed error logging and metrics - Fallback to single-model execution --- ## Observability ### Metrics to Track 1. **Execution Metrics** - Total workflow execution time - Per-model response time - Judge scoring time - Ensemble success rate 2. **Quality Metrics** - Judge scores distribution - Consensus levels - Confidence scores - Response variation 3. **Cost Metrics** - Total tokens used - Cost per workflow - Cost breakdown by model - Budget utilization 4. **Error Metrics** - Model failure rate - Timeout frequency - Validation errors - Retry attempts ### Logging - Structured JSON logs for all workflow executions - Debug mode for detailed execution traces - Performance profiling for optimization - Audit trail for compliance --- ## API Design ### Public API ```typescript // Import from main package registerWorkflow, listWorkflows, getWorkflow, } from "@juspay/neurolink/workflow"; // Initialize const neuro = new NeuroLink(); // Execute built-in workflow (TESTING PHASE) const result = await neuro.generate({ workflowConfig: { workflowId: "consensus-3", timeout: 30000, }, input: { text: "Explain machine learning" }, }); // Result contains original response + evaluation metrics console.log(result.content); // Original best response (unchanged) console.log(result.score); // 87 (out of 100) console.log(result.reasoning); // "Clear and accurate explanation" // Detailed metrics for AB testing console.log(result.ensembleResponses); // All 3 model responses console.log(result.judgeScores); // Individual scores console.log(result.confidence); // 0.87 console.log(result.totalTime); // 3200ms // Register custom workflow using standalone function registerWorkflow({ id: "custom-workflow", name: "My Custom Workflow", type: "ensemble", models: [ { provider: "openai", model: "gpt-4o" }, { provider: "anthropic", model: "claude-sonnet-4-6" }, ], }); // Execute custom workflow const customResult = await neuro.generate({ workflowConfig: { workflowId: "custom-workflow" }, input: { text: "Custom query" }, }); // List available workflows (standalone function) const workflows = listWorkflows(); // Get workflow details (standalone function) const workflowConfig = getWorkflow("consensus-3"); ``` --- ## Success Criteria ### Phase 1 (MVP) - ✅ Support 3+ ensemble models running in parallel - ✅ Implement judge-based scoring with structured output - ✅ Response conditioning with confidence-based tone adjustment - ✅ 3 built-in workflows (consensus, fallback, quality-max) - ✅ Custom workflow registration API - ✅ Comprehensive analytics and metrics - ✅ Full TypeScript type safety - ✅ Integration tests with real providers ### Performance Targets - **Latency**: \95% workflow completion - **Cost Accuracy**: ±5% cost estimation accuracy - **Error Recovery**: Handle 2/3 model failures gracefully ### Documentation - High-Level Design (this document) - Low-Level Design with implementation details - API Reference documentation - Tutorial with 5+ examples - Migration guide for existing users --- ## Future Enhancements (Post-MVP) ### Phase 2: Streaming & Advanced Patterns - **Streaming Workflows**: Progressive results with `streamWorkflow()` - **Workflow State Management**: Persistent workflow state - **Async Workflows**: Background execution with callbacks - **Workflow Chaining**: Connect workflows in pipelines ### Phase 3: Enterprise Features - **DAG-based Workflows**: Complex multi-stage orchestration - **Human-in-the-Loop**: Manual approval/judging steps - **Workflow Versioning**: Manage workflow evolution - **A/B Testing**: Compare workflow performance - **Workflow Marketplace**: Share and discover workflows ### Phase 4: Advanced Intelligence - **Adaptive Workflows**: Auto-select models based on query - **Self-Improving Workflows**: Learn from past executions - **Cost Optimization**: Auto-route to cheapest viable models - **Quality Prediction**: Predict confidence before execution --- ## References ### Internal Documentation - [Factory Pattern Architecture](/docs/development/factory-architecture) - [MCP Foundation](/docs/mcp/overview) - [Configuration Management](/docs/deployment/configuration) - [API Reference](/docs/sdk/api-reference) ### External Resources - [Vercel AI SDK Documentation](https://sdk.vercel.ai/docs) - [Ensemble Methods in ML](https://en.wikipedia.org/wiki/Ensemble_learning) - [LLM Judge Patterns](https://arxiv.org/abs/2306.05685) --- ## Appendix ### Glossary - **Ensemble**: Running multiple models in parallel for the same input - **Judge Model**: AI model that evaluates and scores responses - **Conditioning**: Post-processing response based on metadata/confidence - **Workflow**: Declarative configuration of ensemble + judge + conditioning - **Consensus**: Agreement level between ensemble models - **Confidence**: Calculated metric representing response reliability ### Assumptions 1. All providers support concurrent requests 2. Judge models support structured output (Zod schemas) 3. Sufficient API rate limits for parallel execution 4. Network latency is manageable (\<1s per model) ### Constraints 1. Maximum 10 models per ensemble (performance/cost) 2. Maximum 3 judges per workflow (complexity) 3. Minimum 2 models for meaningful ensemble 4. Judge model must differ from ensemble models (bias prevention) --- **Document Status**: ✅ Approved for Implementation **Next Step**: Low-Level Design (LLD) document --- ## Workflow Engine - Low-Level Design # Neurolink Workflow Engine - Low-Level Design (LLD) **Version**: 1.0 **Date**: November 28, 2025 **Status**: Implementation Complete **Author**: Neurolink Team ## ️ File Structure ```text src/ ├── lib/ │ ├── workflow/ │ │ ├── index.ts # Public API exports (60 lines) │ │ ├── types.ts # Type definitions (250 lines) │ │ ├── config.ts # Configuration schemas (150 lines) │ │ │ │ │ ├── core/ │ │ │ ├── workflowRunner.ts # Main orchestrator (400 lines) │ │ │ ├── workflowRegistry.ts # Workflow management (200 lines) │ │ │ ├── ensembleExecutor.ts # Parallel execution (300 lines) │ │ │ ├── judgeScorer.ts # Judge scoring logic (350 lines) │ │ │ └── responseConditioner.ts # Response conditioning (200 lines) │ │ │ │ │ ├── workflows/ # Built-in workflows (800 lines total) │ │ │ ├── consensusWorkflow.ts # Consensus pattern (200 lines) │ │ │ ├── fallbackWorkflow.ts # Fallback chain (150 lines) │ │ │ ├── multiJudgeWorkflow.ts # Multi-judge voting (250 lines) │ │ │ └── adaptiveWorkflow.ts # Adaptive selection (200 lines) │ │ │ │ │ └── utils/ │ │ ├── workflowValidation.ts # Validation utilities (250 lines) │ │ └── workflowMetrics.ts # Metrics tracking (150 lines) │ │ │ ├── neurolink.ts # MODIFY: Add workflow methods (20 lines) │ └── index.ts # MODIFY: Export workflow types (10 lines) ``` **Total Estimated Lines**: ~3,000 lines --- ## Module Specifications --- ## 1. Types Module (`workflow/types.ts`) ### Core Type Definitions ```typescript /** * workflow/types.ts * Core type definitions for the Workflow Engine */ AIProviderName, AnalyticsData, EvaluationData, } from "../lib/core/types.js"; // ============================================================================ // WORKFLOW CONFIGURATION TYPES // ============================================================================ /** * Workflow type enumeration */ export type WorkflowType = "ensemble" | "chain" | "adaptive" | "custom"; /** * Judge output format */ export type JudgeOutputFormat = "scores" | "ranking" | "best" | "detailed"; /** * Tone adjustment strategy */ export type ToneAdjustment = "soften" | "strengthen" | "neutral"; /** * Complete workflow configuration */ export type WorkflowConfig = { // Identification id: string; name: string; description?: string; version?: string; // Workflow definition type: WorkflowType; models: ModelConfig[]; // Optional components judge?: JudgeConfig; judges?: JudgeConfig[]; // For multi-judge workflows conditioning?: ConditioningConfig; execution?: ExecutionConfig; // Metadata tags?: string[]; metadata?: Record; createdAt?: string; updatedAt?: string; }; /** * Model configuration for ensemble */ export type ModelConfig = { // Required fields provider: AIProviderName; model: string; // Optional tuning weight?: number; // For weighted voting (0-1) temperature?: number; // Model temperature (0-2) maxTokens?: number; // Max output tokens systemPrompt?: string; // Custom system prompt timeout?: number; // Per-model timeout (ms) // Advanced options topP?: number; topK?: number; presencePenalty?: number; frequencyPenalty?: number; // Metadata label?: string; // Human-readable label metadata?: Record; }; /** * Judge model configuration */ export type JudgeConfig = { // Required fields provider: AIProviderName; model: string; criteria: string[]; // Evaluation criteria outputFormat: JudgeOutputFormat; // Optional configuration systemPrompt?: string; // Custom judge prompt temperature?: number; // Judge temperature (usually low) maxTokens?: number; // Max judge output timeout?: number; // Judge timeout (ms) // Advanced options blindEvaluation?: boolean; // Hide provider names includeReasoning: boolean; // REQUIRED: Always include short explanation scoreScale: { // Fixed 0-100 scale for testing phase min: 0; max: 100; }; // Metadata label?: string; metadata?: Record; }; /** * Response conditioning configuration */ export type ConditioningConfig = { // Confidence-based conditioning useConfidence: boolean; confidenceThresholds?: { high: number; // Default: 0.8 medium: number; // Default: 0.5 low: number; // Default: 0.3 }; // Tone adjustment toneAdjustment?: ToneAdjustment; // Metadata injection includeMetadata?: boolean; metadataFields?: string[]; // Which fields to include // Response formatting addConfidenceStatement?: boolean; addModelAttribution?: boolean; addExecutionTime?: boolean; // Custom metadata metadata?: Record; }; /** * Workflow execution configuration */ export type ExecutionConfig = { // Timeout settings timeout?: number; // Total workflow timeout (ms) modelTimeout?: number; // Per-model timeout (ms) judgeTimeout?: number; // Judge timeout (ms) // Retry settings retries?: number; // Max retries on failure retryDelay?: number; // Delay between retries (ms) retryableErrors?: string[]; // Error codes to retry // Optimization parallelism?: number; // Max parallel models earlyTermination?: boolean; // Stop after N responses minResponses?: number; // Minimum required responses // Cost controls maxCost?: number; // Max cost per execution costThreshold?: number; // Warn at cost threshold // Monitoring enableMetrics?: boolean; enableTracing?: boolean; // Metadata metadata?: Record; }; // ============================================================================ // WORKFLOW INPUT/OUTPUT TYPES // ============================================================================ /** * Input for workflow execution */ export type WorkflowInput = { text: string; context?: Record; metadata?: Record; }; /** * Options for workflow execution */ export type WorkflowGenerateOptions = { // Required workflowId: string; input: WorkflowInput; // Optional overrides overrides?: Partial; timeout?: number | string; // Additional options enableAnalytics?: boolean; enableEvaluation?: boolean; context?: Record; }; /** * Complete workflow execution result * NOTE: For testing phase - returns original content unchanged with evaluation metrics */ export type WorkflowResult = { // Primary output (ORIGINAL, UNMODIFIED) content: string; // Evaluation metrics (for AB testing) score: number; // Judge score (0-100) reasoning: string; // Short summary of why this score // Ensemble data ensembleResponses: EnsembleResponse[]; // Judge data (if used) judgeScores?: JudgeScores; selectedResponse?: EnsembleResponse; // Quality metrics confidence: number; // Overall confidence (0-1) consensus?: number; // Agreement level (0-1) // Performance metrics totalTime: number; // Total execution time (ms) ensembleTime: number; // Ensemble phase time (ms) judgeTime?: number; // Judge phase time (ms) conditioningTime?: number; // Conditioning time (ms) // Workflow metadata workflow: string; // Workflow ID workflowName: string; // Workflow name workflowVersion?: string; // Workflow version // Resource usage usage?: AggregatedUsage; cost?: number; // Total estimated cost // Analytics and evaluation analytics?: WorkflowAnalytics; evaluation?: EvaluationData; // Additional metadata metadata?: Record; timestamp: string; }; /** * Single ensemble model response */ export type EnsembleResponse = { // Model identification provider: string; model: string; modelLabel?: string; // Response content content: string; // Performance metrics responseTime: number; // Response time (ms) // Resource usage usage?: { inputTokens: number; outputTokens: number; totalTokens: number; }; // Status status: "success" | "failure" | "timeout" | "partial"; error?: string; // Metadata metadata?: Record; timestamp: string; }; /** * Judge scoring results * NOTE: Scores are 0-100 for standardized evaluation */ export type JudgeScores = { // Judge identification judgeProvider: string; judgeModel: string; // Scoring results (0-100 scale) scores: Record; // { "response-0": 85, "response-1": 92 } ranking?: string[]; // Ordered list of response IDs bestResponse?: string; // ID of best response // Evaluation details criteria: string[]; reasoning?: string; confidenceInJudgment?: number; // Performance judgeTime: number; // Judge execution time (ms) // Metadata metadata?: Record; timestamp: string; }; /** * Multi-judge voting results */ export type MultiJudgeScores = { // Individual judge results judges: JudgeScores[]; // Aggregated results averageScores: Record; aggregatedRanking: string[]; consensusLevel: number; // Agreement between judges (0-1) // Final selection bestResponse: string; confidence: number; // Metadata votingStrategy: "average" | "median" | "majority"; metadata?: Record; }; /** * Aggregated token usage across all models */ export type AggregatedUsage = { totalInputTokens: number; totalOutputTokens: number; totalTokens: number; // Per-model breakdown byModel: Array; // Judge usage (if applicable) judgeUsage?: { inputTokens: number; outputTokens: number; totalTokens: number; cost?: number; }; }; /** * Workflow-specific analytics */ export type WorkflowAnalytics = AnalyticsData & { // Workflow-specific metrics workflowId: string; workflowType: WorkflowType; // Ensemble metrics modelsExecuted: number; modelsSuccessful: number; modelsFailed: number; // Quality metrics averageConfidence: number; consensusLevel?: number; // Performance distribution modelResponseTimes: Record; fastestModel?: string; slowestModel?: string; // Cost breakdown totalCost: number; costByModel: Record; costEfficiency?: number; // Quality per dollar }; // ============================================================================ // VALIDATION & ERROR TYPES // ============================================================================ /** * Workflow validation result */ export type WorkflowValidationResult = { valid: boolean; errors: WorkflowValidationError[]; warnings: WorkflowValidationWarning[]; }; /** * Validation error */ export type WorkflowValidationError = { field: string; message: string; code: string; severity: "error" | "critical"; }; /** * Validation warning */ export type WorkflowValidationWarning = { field: string; message: string; code: string; recommendation?: string; }; /** * Workflow execution error */ export type WorkflowError = Error & { code: string; workflowId: string; phase: "ensemble" | "judge" | "conditioning" | "validation"; details?: Record; retryable: boolean; }; ``` --- ## 2. Configuration Module (`workflow/config.ts`) ### Configuration Schemas & Defaults ```typescript /** * workflow/config.ts * Configuration schemas, validation, and defaults */ WorkflowConfig, ModelConfig, JudgeConfig, ConditioningConfig, ExecutionConfig, } from "./types.js"; // ============================================================================ // ZOD VALIDATION SCHEMAS // ============================================================================ /** * Model configuration schema */ export const ModelConfigSchema = z.object({ provider: z.string().min(1), model: z.string().min(1), weight: z.number().min(0).max(1).optional(), temperature: z.number().min(0).max(2).optional(), maxTokens: z.number().int().positive().optional(), systemPrompt: z.string().optional(), timeout: z.number().int().positive().optional(), topP: z.number().min(0).max(1).optional(), topK: z.number().int().positive().optional(), presencePenalty: z.number().min(-2).max(2).optional(), frequencyPenalty: z.number().min(-2).max(2).optional(), label: z.string().optional(), metadata: z.record(z.unknown()).optional(), }); /** * Judge configuration schema */ export const JudgeConfigSchema = z.object({ provider: z.string().min(1), model: z.string().min(1), criteria: z.array(z.string()).min(1), outputFormat: z.enum(["scores", "ranking", "best", "detailed"]), systemPrompt: z.string().optional(), temperature: z.number().min(0).max(2).optional(), maxTokens: z.number().int().positive().optional(), timeout: z.number().int().positive().optional(), blindEvaluation: z.boolean().optional(), includeReasoning: z.boolean().optional(), scoreScale: z .object({ min: z.number(), max: z.number(), }) .optional(), label: z.string().optional(), metadata: z.record(z.unknown()).optional(), }); /** * Conditioning configuration schema */ export const ConditioningConfigSchema = z.object({ useConfidence: z.boolean(), confidenceThresholds: z .object({ high: z.number().min(0).max(1), medium: z.number().min(0).max(1), low: z.number().min(0).max(1), }) .optional(), toneAdjustment: z.enum(["soften", "strengthen", "neutral"]).optional(), includeMetadata: z.boolean().optional(), metadataFields: z.array(z.string()).optional(), addConfidenceStatement: z.boolean().optional(), addModelAttribution: z.boolean().optional(), addExecutionTime: z.boolean().optional(), metadata: z.record(z.unknown()).optional(), }); /** * Execution configuration schema */ export const ExecutionConfigSchema = z.object({ timeout: z.number().int().positive().optional(), modelTimeout: z.number().int().positive().optional(), judgeTimeout: z.number().int().positive().optional(), retries: z.number().int().min(0).max(5).optional(), retryDelay: z.number().int().positive().optional(), retryableErrors: z.array(z.string()).optional(), parallelism: z.number().int().positive().optional(), earlyTermination: z.boolean().optional(), minResponses: z.number().int().positive().optional(), maxCost: z.number().positive().optional(), costThreshold: z.number().positive().optional(), enableMetrics: z.boolean().optional(), enableTracing: z.boolean().optional(), metadata: z.record(z.unknown()).optional(), }); /** * Complete workflow configuration schema */ export const WorkflowConfigSchema = z .object({ id: z.string().min(1), name: z.string().min(1), description: z.string().optional(), version: z.string().optional(), type: z.enum(["ensemble", "chain", "adaptive", "custom"]), models: z.array(ModelConfigSchema).min(1), judge: JudgeConfigSchema.optional(), judges: z.array(JudgeConfigSchema).optional(), conditioning: ConditioningConfigSchema.optional(), execution: ExecutionConfigSchema.optional(), tags: z.array(z.string()).optional(), metadata: z.record(z.unknown()).optional(), createdAt: z.string().optional(), updatedAt: z.string().optional(), }) .refine( (data) => { // Cannot have both judge and judges if (data.judge && data.judges) { return false; } // Ensemble and adaptive need at least 2 models if ( (data.type === "ensemble" || data.type === "adaptive") && data.models.length & Pick, ): WorkflowConfig { const base: WorkflowConfig = { id: partial.id, name: partial.name, type: partial.type, models: partial.models, ...partial, }; return mergeWithDefaults(base); } ``` --- ## 3. Workflow Runner (`workflow/core/workflowRunner.ts`) ### Main Orchestrator Implementation ```typescript /** * workflow/core/workflowRunner.ts * Main workflow orchestrator - coordinates ensemble, judge, and conditioning */ WorkflowConfig, WorkflowInput, WorkflowResult, WorkflowGenerateOptions, EnsembleResponse, JudgeScores, MultiJudgeScores, AggregatedUsage, WorkflowAnalytics, } from "../types.js"; /** * Main workflow execution orchestrator */ export class WorkflowRunner { private ensembleExecutor: EnsembleExecutor; private judgeScorer: JudgeScorer; private responseConditioner: ResponseConditioner; private metrics: WorkflowMetrics; constructor() { this.ensembleExecutor = new EnsembleExecutor(); this.judgeScorer = new JudgeScorer(); this.responseConditioner = new ResponseConditioner(); this.metrics = new WorkflowMetrics(); } /** * Execute workflow end-to-end */ async execute( config: WorkflowConfig, options: WorkflowGenerateOptions, ): Promise { const functionTag = "WorkflowRunner.execute"; const startTime = Date.now(); logger.info(`[${functionTag}] Starting workflow execution`, { workflowId: config.id, workflowType: config.type, models: config.models.length, }); try { // Phase 1: Execute ensemble const ensembleStart = Date.now(); const ensembleResponses = await this.executeEnsemblePhase( config, options.input, ); const ensembleTime = Date.now() - ensembleStart; logger.debug(`[${functionTag}] Ensemble phase complete`, { responses: ensembleResponses.length, successful: ensembleResponses.filter((r) => r.status === "success") .length, time: ensembleTime, }); // Phase 2: Judge scoring (optional) let judgeScores: JudgeScores | MultiJudgeScores | undefined; let judgeTime = 0; if (config.judge || config.judges) { const judgeStart = Date.now(); judgeScores = await this.executeJudgePhase(config, ensembleResponses); judgeTime = Date.now() - judgeStart; logger.debug(`[${functionTag}] Judge phase complete`, { judgeTime, bestResponse: judgeScores.bestResponse, }); } // Phase 3: Extract score and reasoning (NO CONDITIONING in testing phase) const { score, reasoning } = this.extractScoreAndReasoning(judgeScores); // Use original best response content (UNCHANGED) const selectedResponse = this.selectBestResponse( ensembleResponses, judgeScores, ); const finalContent = selectedResponse.content; // Calculate final metrics const totalTime = Date.now() - startTime; const usage = this.aggregateUsage(ensembleResponses, judgeScores); const analytics = this.createAnalytics( config, ensembleResponses, judgeScores, totalTime, ); // Build complete result (TESTING PHASE: original content + evaluation) const result: WorkflowResult = { content: finalContent, // ORIGINAL, UNMODIFIED score, // 0-100 reasoning, // Short summary ensembleResponses, judgeScores, selectedResponse, confidence: this.calculateConfidence(ensembleResponses, judgeScores), consensus: this.calculateConsensus(ensembleResponses), totalTime, ensembleTime, judgeTime: judgeTime > 0 ? judgeTime : undefined, workflow: config.id, workflowName: config.name, workflowVersion: config.version, usage, cost: this.calculateTotalCost(usage), analytics, metadata: { ...config.metadata, }, timestamp: new Date().toISOString(), }; // Comprehensive logging for AB testing evaluation logger.info(`[${functionTag}] Workflow execution complete`, { workflowId: config.id, workflowType: config.type, totalTime, ensembleTime, judgeTime, score: result.score, reasoning: result.reasoning, confidence: result.confidence, consensus: result.consensus, modelsExecuted: ensembleResponses.length, modelsSuccessful: ensembleResponses.filter( (r) => r.status === "success", ).length, selectedModel: `${selectedResponse.provider}/${selectedResponse.model}`, allScores: judgeScores?.scores, timestamp: result.timestamp, }); // Record metrics this.metrics.recordExecution(config.id, result); return result; } catch (error) { logger.error(`[${functionTag}] Workflow execution failed`, { workflowId: config.id, error: error instanceof Error ? error.message : String(error), }); throw new WorkflowError( `Workflow execution failed: ${error instanceof Error ? error.message : String(error)}`, { code: "WORKFLOW_EXECUTION_FAILED", workflowId: config.id, phase: "execution", retryable: true, }, ); } } /** * Execute ensemble phase */ private async executeEnsemblePhase( config: WorkflowConfig, input: WorkflowInput, ): Promise { const functionTag = "WorkflowRunner.executeEnsemblePhase"; try { const responses = await this.ensembleExecutor.execute( config.models, input, config.execution, ); // Validate minimum responses const successfulResponses = responses.filter( (r) => r.status === "success", ); const minResponses = config.execution?.minResponses || 1; if (successfulResponses.length { const functionTag = "WorkflowRunner.executeJudgePhase"; try { // Filter successful responses only const validResponses = responses.filter((r) => r.status === "success"); if (validResponses.length === 0) { throw new Error("No valid responses to judge"); } // Multi-judge workflow if (config.judges && config.judges.length > 0) { return await this.judgeScorer.scoreMultiJudge( validResponses, config.judges, config.execution, ); } // Single judge workflow if (config.judge) { return await this.judgeScorer.score( validResponses, config.judge, config.execution, ); } throw new Error("No judge configuration provided"); } catch (error) { logger.error(`[${functionTag}] Judge scoring failed`, { error }); throw error; } } /** * Extract score and reasoning from judge results * NOTE: Testing phase - no response modification */ private extractScoreAndReasoning( judgeScores?: JudgeScores | MultiJudgeScores, ): { score: number; reasoning: string } { if (!judgeScores) { return { score: 0, reasoning: "No judge scoring performed" }; } // Get best response score (0-100) const bestResponseId = judgeScores.bestResponse || "response-0"; const score = judgeScores.scores[bestResponseId] || 0; // Get reasoning (keep it short) const reasoning = judgeScores.reasoning ? judgeScores.reasoning.slice(0, 200) // Max 200 chars for summary : "Score assigned by judge"; return { score, reasoning }; } /** * Select best response based on judge scores or fallback */ private selectBestResponse( responses: EnsembleResponse[], judgeScores?: JudgeScores | MultiJudgeScores, ): EnsembleResponse { // Use judge selection if available if (judgeScores?.bestResponse) { const index = parseInt(judgeScores.bestResponse.replace("response-", "")); return responses[index]; } // Fallback: first successful response const successful = responses.find((r) => r.status === "success"); if (successful) { return successful; } // Fallback: first response (even if failed) return responses[0]; } /** * Calculate confidence score */ private calculateConfidence( responses: EnsembleResponse[], judgeScores?: JudgeScores | MultiJudgeScores, ): number { // If judge provided confidence if ( judgeScores && "confidenceInJudgment" in judgeScores && judgeScores.confidenceInJudgment ) { return judgeScores.confidenceInJudgment; } // Calculate from judge scores if (judgeScores && "scores" in judgeScores) { const scores = Object.values(judgeScores.scores); const maxScore = Math.max(...scores); const avgScore = scores.reduce((a, b) => a + b, 0) / scores.length; // Normalize to 0-1 const scoreRange = 10; // Assuming 0-10 scale return (maxScore / scoreRange + avgScore / scoreRange) / 2; } // Fallback: based on success rate const successCount = responses.filter((r) => r.status === "success").length; return successCount / responses.length; } /** * Calculate consensus level */ private calculateConsensus(responses: EnsembleResponse[]): number { const successful = responses.filter((r) => r.status === "success"); if (successful.length r.content.length); const avgLength = lengths.reduce((a, b) => a + b, 0) / lengths.length; const variance = lengths.reduce((sum, len) => sum + Math.pow(len - avgLength, 2), 0) / lengths.length; const stdDev = Math.sqrt(variance); // Normalize to 0-1 (lower std dev = higher consensus) return Math.max(0, 1 - stdDev / avgLength); } /** * Aggregate token usage */ private aggregateUsage( responses: EnsembleResponse[], judgeScores?: JudgeScores | MultiJudgeScores, ): AggregatedUsage { const byModel = responses .filter((r) => r.usage) .map((r) => ({ provider: r.provider, model: r.model, inputTokens: r.usage!.inputTokens, outputTokens: r.usage!.outputTokens, totalTokens: r.usage!.totalTokens, })); const totalInputTokens = byModel.reduce((sum, m) => sum + m.inputTokens, 0); const totalOutputTokens = byModel.reduce( (sum, m) => sum + m.outputTokens, 0, ); return { totalInputTokens, totalOutputTokens, totalTokens: totalInputTokens + totalOutputTokens, byModel, }; } /** * Create workflow analytics */ private createAnalytics( config: WorkflowConfig, responses: EnsembleResponse[], judgeScores: JudgeScores | MultiJudgeScores | undefined, totalTime: number, ): WorkflowAnalytics { const successful = responses.filter((r) => r.status === "success"); const failed = responses.filter((r) => r.status !== "success"); const modelResponseTimes: Record = {}; responses.forEach((r) => { modelResponseTimes[`${r.provider}/${r.model}`] = r.responseTime; }); const sortedByTime = [...responses].sort( (a, b) => a.responseTime - b.responseTime, ); return { workflowId: config.id, workflowType: config.type, modelsExecuted: responses.length, modelsSuccessful: successful.length, modelsFailed: failed.length, averageConfidence: this.calculateConfidence(responses, judgeScores), consensusLevel: this.calculateConsensus(responses), modelResponseTimes, fastestModel: sortedByTime[0] ? `${sortedByTime[0].provider}/${sortedByTime[0].model}` : undefined, slowestModel: sortedByTime[sortedByTime.length - 1] ? `${sortedByTime[sortedByTime.length - 1].provider}/${sortedByTime[sortedByTime.length - 1].model}` : undefined, totalCost: 0, // Calculated separately costByModel: {}, provider: config.models[0].provider, model: config.models[0].model, tokens: { input: 0, output: 0, total: 0, }, responseTime: totalTime, timestamp: new Date().toISOString(), }; } /** * Calculate total cost */ private calculateTotalCost(usage: AggregatedUsage): number { // TODO: Implement actual cost calculation based on provider pricing return usage.totalTokens * 0.00001; // Placeholder } } ``` --- ## 4. Ensemble Executor (`workflow/core/ensembleExecutor.ts`) ### Parallel Model Execution ```typescript /** * workflow/core/ensembleExecutor.ts * Executes multiple models in parallel for ensemble workflows */ ModelConfig, WorkflowInput, EnsembleResponse, ExecutionConfig, } from "../types.js"; /** * Executes ensemble of models in parallel */ export class EnsembleExecutor { /** * Execute all models in parallel */ async execute( models: ModelConfig[], input: WorkflowInput, execution?: ExecutionConfig, ): Promise { const functionTag = "EnsembleExecutor.execute"; logger.debug(`[${functionTag}] Starting ensemble execution`, { models: models.length, parallelism: execution?.parallelism, }); // Set up concurrency limit const limit = pLimit(execution?.parallelism || 10); // Execute all models in parallel const promises = models.map((modelConfig, index) => limit(() => this.executeModel(modelConfig, input, index, execution)), ); const responses = await Promise.all(promises); logger.debug(`[${functionTag}] Ensemble execution complete`, { total: responses.length, successful: responses.filter((r) => r.status === "success").length, }); return responses; } /** * Execute single model */ private async executeModel( modelConfig: ModelConfig, input: WorkflowInput, index: number, execution?: ExecutionConfig, ): Promise { const functionTag = "EnsembleExecutor.executeModel"; const startTime = Date.now(); try { logger.debug(`[${functionTag}] Executing model`, { provider: modelConfig.provider, model: modelConfig.model, index, }); // Create provider instance const provider = await AIProviderFactory.createProvider( modelConfig.provider, modelConfig.model, ); // Execute with timeout const timeout = modelConfig.timeout || execution?.modelTimeout || 15000; const result = await this.executeWithTimeout( provider, modelConfig, input, timeout, ); const responseTime = Date.now() - startTime; // Build successful response const response: EnsembleResponse = { provider: modelConfig.provider, model: modelConfig.model, modelLabel: modelConfig.label, content: result.content, responseTime, usage: result.usage ? { inputTokens: result.usage.promptTokens || 0, outputTokens: result.usage.completionTokens || 0, totalTokens: result.usage.totalTokens || 0, } : undefined, status: "success", metadata: modelConfig.metadata, timestamp: new Date().toISOString(), }; logger.debug(`[${functionTag}] Model execution successful`, { provider: modelConfig.provider, model: modelConfig.model, responseTime, }); return response; } catch (error) { const responseTime = Date.now() - startTime; logger.warn(`[${functionTag}] Model execution failed`, { provider: modelConfig.provider, model: modelConfig.model, error: error instanceof Error ? error.message : String(error), }); // Build error response return { provider: modelConfig.provider, model: modelConfig.model, modelLabel: modelConfig.label, content: "", responseTime, status: error instanceof Error && error.name === "TimeoutError" ? "timeout" : "failure", error: error instanceof Error ? error.message : String(error), metadata: modelConfig.metadata, timestamp: new Date().toISOString(), }; } } /** * Execute provider with timeout */ private async executeWithTimeout( provider: AIProvider, modelConfig: ModelConfig, input: WorkflowInput, timeout: number, ): Promise { return Promise.race([ provider.generate({ input: { text: input.text }, systemPrompt: modelConfig.systemPrompt, temperature: modelConfig.temperature, maxTokens: modelConfig.maxTokens, }), new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), timeout), ), ]); } } ``` --- _Due to length constraints, I'll continue with the remaining modules in a structured format._ --- ## 5. Judge Scorer (`workflow/core/judgeScorer.ts`) - Key Methods ```typescript export class JudgeScorer { async score( responses: EnsembleResponse[], judgeConfig: JudgeConfig, execution?: ExecutionConfig, ): Promise; async scoreMultiJudge( responses: EnsembleResponse[], judgeConfigs: JudgeConfig[], execution?: ExecutionConfig, ): Promise; private async executeJudge( responses: EnsembleResponse[], judgeConfig: JudgeConfig, ): Promise; private formatPromptForJudge( responses: EnsembleResponse[], judgeConfig: JudgeConfig, ): string; private parseJudgeResponse( judgeResponse: string, outputFormat: JudgeOutputFormat, ): JudgeScores; } ``` **Key Algorithm**: Judge Prompt Generation ```typescript private formatPromptForJudge(responses, judgeConfig): string { const responseTexts = responses.map((r, i) => `Response ${i}: ${judgeConfig.blindEvaluation ? '' : `(${r.provider}/${r.model})`}\n${r.content}` ).join('\n\n'); return ` You are an expert judge evaluating AI responses. Criteria: ${judgeConfig.criteria.join(', ')} Responses to evaluate: ${responseTexts} Please score each response on a scale of ${scoreScale.min}-${scoreScale.max} for each criterion. Return your evaluation in JSON format: { "scores": { "response-0": 8.5, "response-1": 9.2 }, "ranking": ["response-1", "response-0"], "bestResponse": "response-1", "reasoning": "Response 1 demonstrates..." } `; } ``` --- ## 6. Response Conditioner (`workflow/core/responseConditioner.ts`) - Key Methods ```typescript export class ResponseConditioner { async condition( content: string, confidence: number, config: ConditioningConfig, context?: ConditioningContext, ): Promise; private adjustTone( content: string, confidence: number, adjustment: ToneAdjustment, ): string; private addMetadata( content: string, config: ConditioningConfig, context: ConditioningContext, ): string; private getConfidenceStatement(confidence: number): string; } ``` **Tone Adjustment Algorithm**: ```typescript private adjustTone(content: string, confidence: number, adjustment: ToneAdjustment): string { const thresholds = config.confidenceThresholds; if (confidence >= thresholds.high) { // High confidence - assertive tone return adjustment === 'strengthen' ? `Definitively, ${content}` : content; } else if (confidence >= thresholds.medium) { // Medium confidence - balanced tone return adjustment === 'soften' ? `Based on the analysis, ${content}` : content; } else { // Low confidence - tentative tone return adjustment === 'soften' ? `It appears that ${content}. However, this conclusion has lower confidence.` : `Note: This response has lower confidence. ${content}`; } } ``` --- ## 7. Workflow Registry (`workflow/core/workflowRegistry.ts`) - Key Methods ```typescript export class WorkflowRegistry { private workflows: Map; register(config: WorkflowConfig): void; unregister(id: string): boolean; get(id: string): WorkflowConfig | undefined; list(filter?: WorkflowFilter): WorkflowConfig[]; validate(config: WorkflowConfig): WorkflowValidationResult; exists(id: string): boolean; update(id: string, updates: Partial): void; } ``` --- ## 8. Integration with NeuroLink Class ### Modifications to `src/lib/neurolink.ts` ```typescript // Add import at top WorkflowConfig, WorkflowGenerateOptions, WorkflowResult, } from "./workflow/types.js"; export class NeuroLink { // Add workflow runner instance private workflowRunner: WorkflowRunner; constructor(options?: NeuroLinkOptions) { // ... existing code ... this.workflowRunner = new WorkflowRunner(); } /** * Execute a workflow with ensemble and judge via generate() * Workflows are accessed through the workflowConfig option */ async generate( options: GenerateOptions & { workflowConfig?: WorkflowConfig }, ): Promise { if (options.workflowConfig) { // Workflow execution path return await this.workflowRunner.execute(options.workflowConfig, options); } // ... existing generate logic } } // Standalone registry functions (not class methods) registerWorkflow, listWorkflows, getWorkflow, } from "@juspay/neurolink/workflow"; // Register custom workflow registerWorkflow(config); // List available workflows const workflows = listWorkflows(); // Get workflow configuration const workflow = getWorkflow("consensus-3"); ``` --- ## 9. Testing Strategy ### Unit Tests ```typescript // test/workflow/ensembleExecutor.test.ts describe("EnsembleExecutor", () => { test("executes multiple models in parallel", async () => { const executor = new EnsembleExecutor(); const responses = await executor.execute([...models], input); expect(responses).toHaveLength(3); expect(responses.filter((r) => r.status === "success")).toHaveLength(3); }); test("handles individual model failures gracefully", async () => { // Mock one model to fail const responses = await executor.execute([...models], input); expect(responses).toHaveLength(3); expect(responses.filter((r) => r.status === "failure")).toHaveLength(1); }); test("respects timeout configuration", async () => { const responses = await executor.execute( [{ ...model, timeout: 100 }], input, ); expect(responses[0].status).toBe("timeout"); }); }); ``` ### Integration Tests ```typescript // test/workflow/integration/workflow.test.ts describe("Workflow Integration", () => { test("executes consensus workflow end-to-end", async () => { const neuro = new NeuroLink(); const workflowConfig = getWorkflow("consensus-3"); const result = await neuro.generate({ workflowConfig, input: { text: "Test query" }, }); expect(result.content).toBeDefined(); expect(result.workflow?.ensembleResponses).toHaveLength(3); expect(result.workflow?.judgeScores).toBeDefined(); }); }); ``` --- ## 10. Error Handling Strategy ### Error Hierarchy ```typescript // workflow/utils/workflowErrors.ts export class WorkflowError extends Error { constructor( message: string, public details: { code: string; workflowId: string; phase: "ensemble" | "judge" | "conditioning" | "validation"; retryable: boolean; originalError?: Error; }, ) { super(message); this.name = "WorkflowError"; } } export class EnsembleExecutionError extends WorkflowError { constructor( workflowId: string, modelErrors: Array, ) { super("Ensemble execution failed", { code: "ENSEMBLE_FAILED", workflowId, phase: "ensemble", retryable: true, }); } } export class JudgeScoringError extends WorkflowError { constructor(workflowId: string, judgeError: Error) { super("Judge scoring failed", { code: "JUDGE_FAILED", workflowId, phase: "judge", retryable: true, originalError: judgeError, }); } } ``` ### Retry Logic ```typescript async executeWithRetry( config: WorkflowConfig, options: WorkflowGenerateOptions ): Promise { const maxRetries = config.execution?.retries || 1; let lastError: Error; for (let attempt = 0; attempt setTimeout(resolve, delay * (attempt + 1))); continue; } throw error; } } throw lastError!; } ``` --- ## 11. Performance Optimizations ### Parallel Execution Optimization ```typescript // Use p-limit for controlled parallelism const limit = pLimit(config.execution?.parallelism || 10); // Batch model execution const batches = chunk(models, limit); const allResponses: EnsembleResponse[] = []; for (const batch of batches) { const batchResponses = await Promise.all( batch.map((model) => limit(() => this.executeModel(model, input))), ); allResponses.push(...batchResponses); } ``` --- ## 12. Observability & Monitoring ### Structured Logging ```typescript logger.info("WorkflowExecution", { workflowId: config.id, workflowType: config.type, phase: "ensemble", models: config.models.length, duration: Date.now() - startTime, success: true, }); ``` ### Metrics Collection ```typescript // workflow/utils/workflowMetrics.ts export class WorkflowMetrics { recordExecution(workflowId: string, result: WorkflowResult): void; recordModelLatency(provider: string, model: string, latency: number): void; recordJudgeLatency(provider: string, model: string, latency: number): void; recordError(workflowId: string, phase: string, error: Error): void; getMetrics(workflowId: string): WorkflowMetricsData; exportPrometheusMetrics(): string; } ``` --- ## 13. Security Considerations ### Input Validation ````typescript // Sanitize all user inputs before passing to models function sanitizeInput(input: string): string { // Remove potential prompt injection attempts return input .replace(/```[^`]*```/g, "") // Remove code blocks .replace(/]*>.*?/gi, "") // Remove scripts .trim(); } ```` ### Cost Controls ```typescript // Pre-execution cost estimation async estimateCost(config: WorkflowConfig, input: WorkflowInput): Promise { const estimatedTokens = estimateTokenCount(input.text); const modelCosts = config.models.map(m => calculateModelCost(m.provider, m.model, estimatedTokens) ); const totalCost = modelCosts.reduce((a, b) => a + b, 0); if (config.execution?.maxCost && totalCost > config.execution.maxCost) { throw new Error(`Estimated cost ${totalCost} exceeds limit ${config.execution.maxCost}`); } return totalCost; } ``` --- ## 14. Built-in Workflow Implementations ### Consensus Workflow ```typescript // workflow/workflows/consensusWorkflow.ts export const CONSENSUS_3_WORKFLOW: WorkflowConfig = { id: "consensus-3", name: "Three Model Consensus", description: "Cross-validate responses across 3 leading models with judge scoring", type: "ensemble", models: [ { provider: "openai", model: "gpt-4o", temperature: 0.3, label: "OpenAI GPT-4o", }, { provider: "anthropic", model: "claude-sonnet-4-6", temperature: 0.3, label: "Anthropic Claude Sonnet 4.6", }, { provider: "google-ai", model: "gemini-3-flash-preview", temperature: 0.3, label: "Google Gemini 3 Flash", }, ], judge: { provider: "openai", model: "gpt-4o", criteria: ["accuracy", "clarity", "completeness", "depth"], outputFormat: "detailed", temperature: 0.1, includeReasoning: true, // REQUIRED for testing scoreScale: { min: 0, max: 100, // Standard 0-100 scale }, }, conditioning: { useConfidence: true, toneAdjustment: "neutral", addConfidenceStatement: true, includeMetadata: false, }, execution: { timeout: 30000, modelTimeout: 15000, judgeTimeout: 10000, minResponses: 2, enableMetrics: true, }, }; ``` --- ## 15. API Usage Examples ### Basic Usage ```typescript const neuro = new NeuroLink(); // Use built-in workflow (TESTING PHASE) const workflowConfig = getWorkflow("consensus-3"); const result = await neuro.generate({ workflowConfig, input: { text: "Explain quantum entanglement" }, }); // Original response (unchanged) console.log(result.content); // Original AI response // Workflow metadata (when using workflowConfig) console.log(result.workflow?.selectedModel); // Selected best model console.log(result.workflow?.metrics?.totalTime); // Execution time console.log(result.workflow?.ensembleResponses?.length); // 3 ``` ### Custom Workflow ```typescript // Register custom workflow using standalone function registerWorkflow({ id: "custom-medical", name: "Medical Query Workflow", type: "ensemble", models: [ { provider: "openai", model: "gpt-4o", systemPrompt: "You are a medical expert...", }, { provider: "anthropic", model: "claude-sonnet-4-6", systemPrompt: "You are a medical expert...", }, ], judge: { provider: "openai", model: "gpt-4o", criteria: ["medical_accuracy", "safety", "clarity"], outputFormat: "scores", }, }); // Execute custom workflow const customWorkflow = getWorkflow("custom-medical"); const result = await neuro.generate({ workflowConfig: customWorkflow, input: { text: "What are the symptoms of type 2 diabetes?" }, }); ``` --- ## 16. Migration Path for Existing Users ### Backward Compatibility ```typescript // Existing code continues to work const result = await neuro.generate({ input: { text: "Hello" }, }); // Workflow feature is enabled via workflowConfig option const workflowConfig = getWorkflow("consensus-3"); const workflowResult = await neuro.generate({ workflowConfig, input: { text: "Hello" }, }); ``` ### Gradual Adoption 1. **Phase 1**: Users can try workflows alongside existing methods 2. **Phase 2**: Workflows become recommended for high-stakes queries 3. **Phase 3**: Workflows are default with single-model as fallback --- ## 17. Performance Benchmarks (Expected) | Workflow | Models | Judge | Latency (p50) | Latency (p95) | Cost Multiplier | | ------------- | ------ | ----- | ------------- | ------------- | --------------- | | consensus-3 | 3 | 1 | 3.2s | 5.1s | 4.2x | | fast-fallback | 1-2 | 0 | 1.1s | 2.8s | 1.3x | | quality-max | 2 | 1 | 3.5s | 4.9s | 3.1x | | multi-judge-5 | 3 | 2 | 4.8s | 6.7s | 5.3x | --- ## 18. Future Enhancements ### Phase 2: Streaming Support ```typescript async streamWorkflow( options: WorkflowGenerateOptions ): AsyncIterable { // Stream ensemble responses as they arrive // Update judge scores progressively // Condition final response } ``` ### Phase 3: Workflow Chaining Planned: `createWorkflowPipeline()` is not in the current release. ```typescript planned const pipeline = neuro.createWorkflowPipeline([ "quality-check", // First workflow "fact-verification", // Second workflow "final-polish", // Third workflow ]); const result = await pipeline.execute({ input: { text: "Complex query" }, }); ``` --- ## Implementation Checklist - [ ] Create `src/workflow/` directory structure - [ ] Implement `types.ts` with all interfaces - [ ] Implement `config.ts` with Zod schemas - [ ] Implement `ensembleExecutor.ts` - [ ] Implement `judgeScorer.ts` - [ ] Implement `responseConditioner.ts` - [ ] Implement `workflowRegistry.ts` - [ ] Implement `workflowRunner.ts` - [ ] Create built-in workflows (consensus, fallback, quality-max) - [ ] Add methods to `NeuroLink` class - [ ] Export types from `src/lib/index.ts` - [ ] Write unit tests (80% coverage target) - [ ] Write integration tests - [ ] Add JSDoc documentation - [ ] Create user guide with examples - [ ] Add CLI support (optional Phase 2) --- **Document Status**: ✅ Ready for Implementation **Next Step**: Code generation upon approval --- ## Business Documentation Hub # Business Documentation Hub > **Transform your AI operations with NeuroLink's enterprise analytics and quality evaluation features** This hub provides comprehensive business-focused documentation for implementing NeuroLink's analytics and evaluation features in production environments. ## Documentation Overview ### [Business Value Guide](/docs/business-value) **ROI-focused guide with real cost savings and quality improvements** - **Cost Optimization**: 35-40% reduction in AI spending - **Quality Improvement**: 85-95% consistency in AI responses - **Performance Monitoring**: Real-time business intelligence - **Industry Examples**: E-commerce, healthcare, finance, SaaS - **ROI Calculator**: Measure 300-1000% return on investment ### [Industry Use Cases](/docs/use-cases) **Real-world applications across 8+ industries** - **E-commerce**: Product descriptions with cost optimization - **Healthcare**: Patient education with 100% compliance - **Financial Services**: Investment reports with regulatory compliance - **SaaS**: Customer support automation (88% satisfaction) - **Education**: Course content creation (8x faster) - **Manufacturing**: Safety documentation (OSHA compliant) - **Hospitality**: Marketing content (18% booking increase) - **Mobile Apps**: App store optimization ### Integration Tutorials **Step-by-step implementation guides** - **Quick Start**: 15-minute setup guide - **Web Application**: Express.js + frontend integration - **Batch Processing**: CSV data processing at scale - **Real-Time Monitoring**: Analytics dashboard creation - **Cost Optimization**: Automatic model selection - **Industry Examples**: Production-ready implementations ### [Technical Implementation](/docs/ai-enhancements) **Technical feature specifications** - **Analytics System**: Usage tracking and cost analysis - **Evaluation System**: AI-powered quality scoring - **Context Flow**: Custom data through request chains - **Configuration**: Environment setup and model selection ### [Testing & Validation](/docs/development/testing) **Comprehensive testing and validation guides** - **Feature Testing**: Analytics and evaluation validation - **Integration Testing**: End-to-end workflow verification - **Performance Testing**: Load and stress testing - **Quality Assurance**: Testing methodology and best practices ## Quick Navigation by Role ### **Business Decision Makers** **Start Here**: [Business Value Guide](/docs/business-value) - See immediate ROI potential (300-1000% returns) - Review cost optimization examples (35-40% savings) - Understand quality improvement metrics (85-95% consistency) - Compare industry success stories ### ‍ **Product Managers** **Start Here**: [Industry Use Cases](/docs/use-cases) - Find your industry's specific implementation - See real-world success metrics - Understand quality gates and business rules - Review customer satisfaction improvements ### ‍ **Developers & Engineers** **Start Here**: Integration Tutorials - Follow step-by-step implementation guides - Review code examples and best practices - Set up monitoring and analytics dashboards - Implement cost optimization strategies ### **QA & Testing Teams** **Start Here**: [Testing & Validation](/docs/development/testing) - Comprehensive testing methodologies - Quality assurance frameworks - Performance benchmarking - Validation scripts and tools ## Implementation Roadmap ### Week 1: Foundation 1. **Read**: [Business Value Guide](/docs/business-value) - Understand ROI potential 2. **Review**: [Industry Use Cases](/docs/use-cases) - Find relevant examples 3. **Setup**: Basic analytics tracking 4. **Measure**: Baseline costs and quality ### Week 2: Implementation 1. **Follow**: [Quick Start Tutorial](/docs/tutorials/step-by-step#quick-start-15-minutes) 2. **Enable**: Analytics and evaluation features 3. **Configure**: Quality gates and cost monitoring 4. **Test**: Validation using [Testing Guide](/docs/development/testing) ### Week 3: Optimization 1. **Implement**: Cost optimization strategies 2. **Setup**: Real-time monitoring dashboard 3. **Configure**: Department-level tracking 4. **Measure**: Quality improvement metrics ### Week 4: Scale 1. **Deploy**: Production implementation 2. **Monitor**: ROI and performance metrics 3. **Optimize**: Based on analytics data 4. **Expand**: Roll out to additional teams ## Expected Business Outcomes ### Cost Optimization - **Month 1**: 15-25% cost reduction through basic optimization - **Month 2**: 25-35% cost reduction through advanced model selection - **Month 3**: 35-45% cost reduction through department-level optimization - **Ongoing**: Continuous optimization based on analytics insights ### ⭐ Quality Improvement - **Week 1**: Baseline quality measurement established - **Week 2**: Quality gates prevent low-quality content - **Month 1**: 20-30% improvement in content consistency - **Month 3**: 85-95% quality consistency achieved ### Productivity Gains - **Immediate**: Real-time cost and quality visibility - **Week 2**: Automated quality control reduces manual review - **Month 1**: 50-75% reduction in content review time - **Month 3**: 10x faster content creation with quality assurance ## Success Stories Summary ### E-commerce Company - **Challenge**: 50,000 product descriptions monthly - **Solution**: Analytics-driven model selection + quality gates - **Results**: 65% cost reduction, 90% quality consistency, 10x faster creation ### Healthcare Organization - **Challenge**: Regulatory compliance for patient education - **Solution**: Strict evaluation thresholds + medical review workflows - **Results**: 100% compliance, 75% faster creation, 40% better comprehension ### SaaS Company - **Challenge**: Scale customer support while maintaining quality - **Solution**: Tiered quality control + response time optimization - **Results**: 88% satisfaction, 60% cost reduction, 10x volume handling ### Financial Services - **Challenge**: Accurate investment reports with regulatory compliance - **Solution**: Compliance frameworks + fact-checking requirements - **Results**: Zero violations, 5x faster reports, 45% better ratings ## Technical Architecture Overview ``` ┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐ │ Application │────│ NeuroLink SDK │────│ AI Providers │ │ (Your Code) │ │ with Analytics │ │ (AI Providers) │ └─────────────────┘ └──────────────────┘ └─────────────────┘ │ │ │ ▼ ▼ ▼ ┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐ │ Quality Gates │ │ Cost Tracking │ │ Performance │ │ & Evaluation │ │ & Analytics │ │ Monitoring │ └─────────────────┘ └──────────────────┘ └─────────────────┘ ``` ### Core Components - **Analytics System**: Real-time usage tracking and cost analysis - **Evaluation System**: AI-powered response quality scoring - **Context Flow**: Custom business data through request chains - **Quality Gates**: Automated quality control and review workflows - **Cost Optimization**: Intelligent provider and model selection ## Support & Resources ### Getting Help - **Technical Issues**: [GitHub Issues](https://github.com/juspay/neurolink/issues) - **Feature Requests**: [GitHub Discussions](https://github.com/juspay/neurolink/discussions) - **Documentation**: [Complete API Reference](/docs/) - **Examples**: [Working Code Examples](/docs/) ### Community - **NPM Package**: [@juspay/neurolink](https://www.npmjs.com/package/@juspay/neurolink) - **GitHub Repository**: [juspay/neurolink](https://github.com/juspay/neurolink) - **License**: MIT (Production-friendly) ## Next Steps 1. **Assess Your Needs**: Review [Industry Use Cases](/docs/use-cases) for your sector 2. **Calculate ROI**: Use examples in [Business Value Guide](/docs/business-value) 3. **Start Implementation**: Follow the Integration Tutorials 4. **Validate Results**: Use [Testing & Validation](/docs/development/testing) 5. **Optimize & Scale**: Monitor analytics and optimize based on data --- **Ready to transform your AI operations?** Start with the [Business Value Guide](/docs/business-value) to understand the ROI potential, then move to [Industry Use Cases](/docs/use-cases) to see how organizations like yours are achieving success. The analytics and evaluation features typically deliver **300-1000% ROI** within 3-6 months through cost optimization, quality improvement, and productivity gains. --- ## Business Value Guide: Analytics & Evaluation Features # Business Value Guide: Analytics & Evaluation Features - [✅ Performance Monitoring Achieved:](#performance-monitoring-achieved) - [ Next Steps](#next-steps) NeuroLink's analytics and evaluation features deliver measurable business value through cost optimization, quality improvement, and performance monitoring. This guide shows real-world examples of business impact and ROI. ## Cost Optimization ### Problem: Uncontrolled AI Spending **Before NeuroLink Analytics:** - No visibility into AI provider costs - Using expensive models for simple tasks - No department-level cost tracking - Estimated monthly spend: **$5,000-$8,000** **After NeuroLink Analytics:** - Real-time cost tracking by provider, model, department - Automatic model selection based on task complexity - Cost optimization alerts and recommendations - Actual monthly spend: **$3,200-$4,500** (35-40% reduction) ### ROI Example: E-commerce Company ```javascript // Before: Using GPT-4 for all product descriptions const expensiveResult = await provider.generate({ input: { text: "Write product description for basic t-shirt" }, model: "gpt-4-turbo", // $30/1M tokens enableAnalytics: true, }); // Cost per description: $0.12 // Monthly cost (10,000 descriptions): $1,200 // After: Using analytics-driven model selection const optimizedResult = await provider.generate({ input: { text: "Write product description for basic t-shirt" }, model: "gpt-3.5-turbo", // $3/1M tokens enableAnalytics: true, }); // Cost per description: $0.015 // Monthly cost (10,000 descriptions): $150 // Monthly savings: $1,050 (87.5% reduction) ``` ### Department-Level Cost Tracking ```javascript // Track costs by department const marketingResult = await provider.generate({ input: { text: "Create social media post" }, enableAnalytics: true, context: { department: "marketing", campaign: "Q1-launch" }, }); const supportResult = await provider.generate({ input: { text: "Generate customer response" }, enableAnalytics: true, context: { department: "support", priority: "high" }, }); // Analytics dashboard shows: // Marketing: $450/month (social posts, ad copy) // Support: $230/month (customer responses) // Sales: $180/month (email templates) // Total visibility enables budget allocation ``` ## ⭐ Quality Improvement ### Problem: Inconsistent AI Response Quality **Before NeuroLink Evaluation:** - No automated quality assessment - Manual review required for all content - Inconsistent response quality (60-75% satisfaction) - High review overhead (2-3 hours daily) **After NeuroLink Evaluation:** - Automated quality scoring (relevance, accuracy, completeness) - Quality gates prevent low-quality content - Consistent high-quality responses (85-95% satisfaction) - Reduced review time (30 minutes daily) ### ROI Example: Customer Support ```javascript // Automated quality control const supportResponse = await provider.generate({ input: { text: "Customer complaining about delayed shipment" }, enableEvaluation: true, enableAnalytics: true, context: { customerTier: "premium", issueType: "shipping", urgency: "high", }, }); // Quality gates if (supportResponse.evaluation.overall = 9) { await publishContent(medicalContent); } else { await medicalProfessionalReview(medicalContent); } // Results: // - 95% accuracy maintained (regulatory compliance) // - 40% faster content creation // - Zero compliance violations ``` ## Performance Monitoring ### Real-Time Business Intelligence ```bash # Daily analytics reporting npx @juspay/neurolink generate "Daily report summary" \ --enable-analytics --enable-evaluation \ --context '{"report_type":"daily","department":"analytics"}' \ --debug # Output includes: # Analytics: Response time: 1,200ms, Cost: $0.08, Tokens: 1,250 # ⭐ Evaluation: Overall: 9/10, Accuracy: 9/10, Completeness: 8/10 ``` ### Performance Optimization Dashboard ```javascript // Track performance trends const performanceData = { dailyStats: await analytics.getDailyUsage(), qualityTrends: await evaluation.getQualityTrends(), costOptimization: await analytics.getCostOptimization(), }; // Key Performance Indicators: // - Average response time: 1.2s (target: <2s) // - Quality score trend: +15% this month // - Cost per task: -25% vs last quarter // - Provider reliability: 99.2% uptime ``` ## Industry-Specific Value ### E-commerce **Use Case:** Product description generation - **Volume:** 50,000 products/month - **Cost Savings:** $2,400/month (optimized model selection) - **Quality Improvement:** 85% consistency (vs 60% manual) - **Time Savings:** 200 hours/month human writing ### Healthcare **Use Case:** Patient education content - **Compliance:** 98% accuracy requirement met - **Review Time:** 75% reduction in medical review - **Patient Satisfaction:** +30% comprehension scores - **Risk Mitigation:** Zero compliance violations ### Financial Services **Use Case:** Investment report generation - **Accuracy:** 95% fact-checking score required - **Compliance:** Automated regulatory review - **Client Satisfaction:** +40% report quality ratings - **Productivity:** 3x faster report generation ### SaaS Companies **Use Case:** Customer communication - **Response Time:** 90% under 30 seconds - **Quality:** 88% customer satisfaction - **Cost:** 60% reduction vs human-only support - **Scalability:** Handle 10x volume with same team ## ROI Calculation Framework ### Cost Savings Calculator ```javascript // Monthly cost analysis const monthlyROI = { // Before NeuroLink aiProviderCosts: 5000, // Unoptimized spending humanReviewHours: 80, // Manual quality review humanHourlyRate: 50, // $50/hour for reviewers qualityIssues: 12, // Monthly quality problems issueResolutionCost: 200, // $200 per quality issue // After NeuroLink optimizedAICosts: 3200, // 36% cost reduction reducedReviewHours: 20, // 75% review time reduction qualityIssuesPrevented: 10, // Quality gates prevent issues // Calculate savings totalMonthlySavings() { const aiSavings = this.aiProviderCosts - this.optimizedAICosts; const laborSavings = (this.humanReviewHours - this.reducedReviewHours) * this.humanHourlyRate; const qualitySavings = this.qualityIssuesPrevented * this.issueResolutionCost; return aiSavings + laborSavings + qualitySavings; // Result: $1,800 + $3,000 + $2,000 = $6,800/month savings }, }; // Annual ROI: $81,600 savings // Implementation cost: ~$5,000 (development time) // ROI: 1,632% (16x return on investment) ``` ### Quality Improvement Metrics ```javascript const qualityMetrics = { beforeNeuroLink: { averageQualityScore: 6.5, // Out of 10 customerSatisfaction: 72, // Percentage manualReviewRequired: 100, // Percentage complianceViolations: 3, // Per month }, afterNeuroLink: { averageQualityScore: 8.7, // +34% improvement customerSatisfaction: 89, // +24% improvement manualReviewRequired: 25, // -75% reduction complianceViolations: 0, // Zero violations }, }; ``` ## Getting Started with Business Value ### Week 1: Baseline Measurement ```bash # Measure current costs without analytics npx @juspay/neurolink generate "Business content" --provider openai # Note: No cost tracking, no quality metrics ``` ### Week 2: Enable Analytics ```bash # Start tracking costs and usage npx @juspay/neurolink generate "Business content" \ --provider openai --enable-analytics --debug # Result: Immediate cost visibility ``` ### Week 3: Add Quality Control ```bash # Add automated quality assessment npx @juspay/neurolink generate "Business content" \ --provider openai --enable-analytics --enable-evaluation --debug # Result: Quality scores + cost tracking ``` ### Week 4: Optimize Based on Data ```bash # Use analytics data to optimize provider/model selection npx @juspay/neurolink generate "Business content" \ --provider google-ai --model gemini-2.5-flash \ --enable-analytics --enable-evaluation --debug # Result: Optimized costs + maintained quality ``` ## Business Value Checklist ### ✅ Cost Optimization Achieved: - [ ] Real-time cost tracking implemented - [ ] Department-level cost allocation setup - [ ] Model optimization based on task complexity - [ ] Monthly cost reduction of 25-40% - [ ] Automated cost alerts configured ### ✅ Quality Improvement Achieved: - [ ] Automated quality scoring implemented - [ ] Quality gates prevent low-quality content - [ ] Customer satisfaction increased 20%+ - [ ] Manual review time reduced 70%+ - [ ] Compliance requirements met consistently ### Performance Monitoring Achieved: - [ ] Real-time performance dashboards - [ ] Quality trend analysis - [ ] Cost optimization recommendations - [ ] Provider reliability monitoring - [ ] Business intelligence reporting ## Next Steps 1. **Implement Analytics**: Start with cost tracking 2. **Add Quality Control**: Implement evaluation scoring 3. **Measure Baseline**: Document current costs/quality 4. **Optimize Based on Data**: Use insights for improvement 5. **Scale Across Organization**: Roll out to all teams The combination of analytics and evaluation features typically delivers **300-1000% ROI** within 3-6 months through cost optimization, quality improvement, and productivity gains. --- ## Domain Configuration Examples for NeuroLink CLI # Domain Configuration Examples for NeuroLink CLI This document provides comprehensive examples of using domain-specific features with the NeuroLink CLI, showcasing the Phase 1 Factory Infrastructure capabilities. ## Table of Contents - [Basic Domain Usage](#basic-domain-usage) - [Healthcare Domain Examples](#healthcare-domain-examples) - [Analytics Domain Examples](#analytics-domain-examples) - [Finance Domain Examples](#finance-domain-examples) - [E-commerce Domain Examples](#e-commerce-domain-examples) - [Context Integration Examples](#context-integration-examples) - [Evaluation and Analytics](#evaluation-and-analytics) - [Provider-Specific Examples](#provider-specific-examples) - [Streaming with Domains](#streaming-with-domains) - [Configuration Management](#configuration-management) - [Advanced Use Cases](#advanced-use-cases) ## Basic Domain Usage ### Simple Domain Generation ```bash # Basic healthcare domain usage neurolink generate "Analyze patient symptoms: fever, headache, fatigue" \ --evaluationDomain healthcare \ --enable-evaluation \ --format json # Basic analytics domain usage neurolink generate "Calculate quarterly revenue growth trends" \ --evaluationDomain analytics \ --enable-evaluation \ --enable-analytics \ --format json ``` ### Domain-Specific Streaming ```bash # Stream with finance domain evaluation neurolink stream "Assess investment portfolio risk for retirement planning" \ --evaluationDomain finance \ --enable-evaluation # Stream with ecommerce domain evaluation neurolink stream "Optimize conversion funnel for online retail store" \ --evaluationDomain ecommerce \ --enable-evaluation ``` ## Healthcare Domain Examples ### Medical Diagnosis Support ```bash # Comprehensive symptom analysis neurolink generate "Patient presents with: chest pain (8/10), shortness of breath, elevated heart rate (110 BPM), diaphoresis. History: hypertension, diabetes. Age 65. Provide differential diagnosis and recommended tests." \ --evaluationDomain healthcare \ --enable-evaluation \ --enable-analytics \ --provider google-ai \ --max-tokens 800 \ --format json ``` ### Treatment Planning ```bash # Treatment recommendation with context neurolink generate "Develop treatment plan for Type 2 diabetes patient" \ --context '{"patientAge":55,"comorbidities":["hypertension","obesity"],"allergies":["penicillin"],"currentMedications":["metformin","lisinopril"]}' \ --evaluationDomain healthcare \ --enable-evaluation \ --format json ``` ### Medical Research Analysis ```bash # Clinical trial data analysis neurolink stream "Analyze clinical trial results for new cardiovascular drug" \ --context '{"studyType":"randomized-controlled","sampleSize":2000,"primaryEndpoint":"MACE reduction","duration":"24-months"}' \ --evaluationDomain healthcare \ --enable-evaluation \ --enable-analytics \ --provider anthropic ``` ## Analytics Domain Examples ### Business Intelligence ```bash # Quarterly business analysis neurolink generate "Analyze Q3 performance metrics and identify growth opportunities" \ --context '{"revenue":"$2.5M","growth":"15%","customerAcquisition":450,"churnRate":"3.2%","marketSegment":"B2B-SaaS"}' \ --evaluationDomain analytics \ --enable-evaluation \ --enable-analytics \ --format json \ --max-tokens 1000 ``` ### Data Science Insights ```bash # Machine learning model performance analysis neurolink generate "Evaluate ML model performance and recommend optimizations" \ --context '{"modelType":"gradient-boosting","accuracy":0.87,"precision":0.83,"recall":0.91,"f1Score":0.87,"trainingData":"50k-samples","features":42}' \ --evaluationDomain analytics \ --enable-evaluation \ --provider openai \ --format json ``` ### Predictive Analytics ```bash # Sales forecasting with streaming neurolink stream "Generate sales forecast for next quarter based on historical trends" \ --context '{"historicalData":"3-years","seasonality":"high","marketTrends":"positive","competitiveAnalysis":"included"}' \ --evaluationDomain analytics \ --enable-evaluation \ --enable-analytics ``` ## Finance Domain Examples ### Investment Analysis ```bash # Portfolio risk assessment neurolink generate "Assess risk profile of diversified investment portfolio" \ --context '{"assetAllocation":{"stocks":0.60,"bonds":0.30,"alternatives":0.10},"totalValue":"$500k","timeHorizon":"10-years","riskTolerance":"moderate"}' \ --evaluationDomain finance \ --enable-evaluation \ --enable-analytics \ --format json ``` ### Financial Planning ```bash # Retirement planning analysis neurolink generate "Create comprehensive retirement savings strategy" \ --context '{"currentAge":35,"retirementAge":65,"currentSavings":"$75k","annualIncome":"$120k","savingsRate":"15%","expectedReturns":"7%"}' \ --evaluationDomain finance \ --enable-evaluation \ --provider vertex \ --max-tokens 1200 ``` ### Market Analysis ```bash # Economic trend analysis with streaming neurolink stream "Analyze current market conditions and economic indicators" \ --context '{"inflationRate":"3.2%","unemploymentRate":"3.8%","fedFundsRate":"5.25%","gdpGrowth":"2.1%","marketVolatility":"elevated"}' \ --evaluationDomain finance \ --enable-evaluation ``` ## E-commerce Domain Examples ### Conversion Optimization ```bash # E-commerce funnel analysis neurolink generate "Optimize checkout process to reduce cart abandonment" \ --context '{"cartAbandonmentRate":"68%","checkoutSteps":4,"averageLoadTime":"3.2s","mobileUsers":"75%","paymentOptions":["card","paypal","apple-pay"]}' \ --evaluationDomain ecommerce \ --enable-evaluation \ --enable-analytics \ --format json ``` ### Customer Experience ```bash # Product recommendation strategy neurolink generate "Develop personalized product recommendation engine" \ --context '{"userBase":"50k-active","purchaseHistory":"available","browsingData":"tracked","categoryCount":25,"averageOrderValue":"$85"}' \ --evaluationDomain ecommerce \ --enable-evaluation \ --provider google-ai ``` ### Marketing Campaign Analysis ```bash # Campaign performance optimization neurolink stream "Analyze digital marketing campaign performance and ROI" \ --context '{"channels":["social","email","ppc","seo"],"budget":"$50k","duration":"3-months","conversions":1250,"cac":"$40","ltv":"$300"}' \ --evaluationDomain ecommerce \ --enable-evaluation \ --enable-analytics ``` ## Context Integration Examples ### Complex Organizational Context ```bash # Enterprise analytics with comprehensive context neurolink generate "Analyze operational efficiency across multiple departments" \ --context '{ "organization": { "id": "acme-corp-2024", "industry": "technology", "size": "mid-market", "locations": ["us-east", "eu-west", "apac-south"] }, "departments": { "engineering": {"headcount": 120, "budget": "$8M", "kpis": ["velocity", "quality", "innovation"]}, "sales": {"headcount": 45, "budget": "$2M", "kpis": ["revenue", "pipeline", "conversion"]}, "marketing": {"headcount": 25, "budget": "$1.5M", "kpis": ["leads", "brand", "engagement"]} }, "timeframe": "Q3-2024", "objectives": ["growth", "efficiency", "scalability"] }' \ --evaluationDomain analytics \ --enable-evaluation \ --enable-analytics \ --format json \ --max-tokens 1500 ``` ### Multi-Domain Context ```bash # Healthcare analytics with regulatory context neurolink generate "Analyze patient outcomes while ensuring HIPAA compliance" \ --context '{ "healthcare": { "facilityType": "hospital", "specialties": ["cardiology", "oncology", "emergency"], "patientVolume": "daily-500" }, "compliance": { "frameworks": ["HIPAA", "SOX", "FDA"], "auditStatus": "current", "dataClassification": "sensitive" }, "analytics": { "metricsTracked": ["readmission-rates", "patient-satisfaction", "treatment-outcomes"], "reportingFrequency": "monthly", "stakeholders": ["medical-staff", "administration", "regulators"] } }' \ --evaluationDomain healthcare \ --enable-evaluation \ --enable-analytics \ --provider anthropic ``` ## Evaluation and Analytics ### Comprehensive Evaluation Setup ```bash # Full evaluation with custom domain neurolink generate "Develop AI strategy for enterprise transformation" \ --evaluationDomain analytics \ --enable-evaluation \ --enable-analytics \ --context '{"industry":"manufacturing","aiMaturity":"beginner","budget":"$2M","timeline":"18-months"}' \ --provider google-ai \ --format json \ --max-tokens 2000 ``` ### Analytics-Only Mode ```bash # Analytics without evaluation neurolink generate "Create quarterly performance report" \ --enable-analytics \ --context '{"quarter":"Q3","metrics":["revenue","growth","efficiency"],"stakeholders":["executives","board","investors"]}' \ --format json ``` ### Evaluation-Only Mode ```bash # Evaluation without analytics neurolink generate "Review software architecture decisions" \ --evaluationDomain analytics \ --enable-evaluation \ --context '{"architecture":"microservices","scale":"enterprise","complexity":"high"}' ``` ## Provider-Specific Examples ### OpenAI with Healthcare Domain ```bash neurolink generate "Analyze drug interaction risks for polypharmacy patient" \ --provider openai \ --model gpt-4 \ --evaluationDomain healthcare \ --enable-evaluation \ --context '{"medications":["warfarin","amiodarone","simvastatin"],"age":78,"kidneyFunction":"moderate-impairment"}' \ --format json ``` ### Anthropic with Finance Domain ```bash neurolink generate "Assess cryptocurrency investment strategy risks" \ --provider anthropic \ --model claude-sonnet-4-6 \ --evaluationDomain finance \ --enable-evaluation \ --enable-analytics \ --context '{"portfolio":"traditional","riskTolerance":"low","cryptoAllocation":"5%","timeHorizon":"long-term"}' \ --format json ``` ### Google AI with Analytics Domain ```bash neurolink stream "Optimize supply chain logistics using AI predictions" \ --provider google-ai \ --model gemini-3-pro-preview \ --evaluationDomain analytics \ --enable-evaluation \ --context '{"supplyChain":"global","products":"electronics","demandVolatility":"high","inventoryTurnover":"quarterly"}' ``` ## Streaming with Domains ### Interactive Healthcare Consultation ```bash # Stream medical case analysis neurolink stream "Walk through differential diagnosis process for complex case" \ --evaluationDomain healthcare \ --enable-evaluation \ --context '{"setting":"emergency-room","urgency":"high","resources":"full-diagnostic"}' \ --provider anthropic ``` ### Real-time Financial Analysis ```bash # Stream market analysis neurolink stream "Provide real-time analysis of market volatility impact" \ --evaluationDomain finance \ --enable-evaluation \ --enable-analytics \ --context '{"marketConditions":"volatile","portfolio":"balanced","clientRisk":"moderate"}' ``` ### Live Business Intelligence ```bash # Stream business insights neurolink stream "Generate actionable insights from real-time business metrics" \ --evaluationDomain analytics \ --enable-evaluation \ --enable-analytics \ --context '{"dataSource":"live-dashboard","updateFrequency":"real-time","stakeholder":"c-suite"}' ``` ## Configuration Management ### Setting Domain Defaults ```bash # Configure default domain settings neurolink config init # Follow prompts to set: # - Default Evaluation Domain: analytics # - Enable Analytics by Default: yes # - Enable Evaluation by Default: yes ``` ### Domain-Specific Configuration ```bash # Show current domain configuration neurolink config show # Export configuration with domain settings neurolink config export --format json > neurolink-domain-config.json # Validate domain configuration neurolink config validate ``` ### Custom Domain Setup ```bash # Initialize with custom domain preferences neurolink config init # Select healthcare as default domain # Configure evaluation criteria: accuracy, safety, compliance, clarity # Enable diagnostic accuracy tracking # Enable treatment outcomes tracking ``` ## Advanced Use Cases ### Multi-Step Analysis Pipeline ```bash # Step 1: Initial analysis neurolink generate "Conduct preliminary market research analysis" \ --evaluationDomain analytics \ --enable-evaluation \ --context '{"market":"fintech","stage":"preliminary","scope":"competitive-landscape"}' \ --output step1-analysis.json \ --format json # Step 2: Deep dive based on initial findings neurolink generate "Deep dive into identified market opportunities" \ --evaluationDomain analytics \ --enable-evaluation \ --enable-analytics \ --context '{"previousAnalysis":"step1-analysis.json","focus":"opportunity-sizing","methodology":"bottom-up"}' \ --format json ``` ### Cross-Domain Analysis ```bash # Healthcare + Analytics combined analysis neurolink generate "Analyze healthcare cost optimization using data analytics" \ --evaluationDomain healthcare \ --enable-evaluation \ --enable-analytics \ --context '{ "healthcare": {"costs":"rising","quality":"maintained","patient-satisfaction":"high"}, "analytics": {"dataAvailable":["claims","outcomes","satisfaction"],"methodology":"predictive-modeling"} }' \ --format json \ --max-tokens 2000 ``` ### Compliance-Aware Generation ```bash # Finance with regulatory compliance neurolink generate "Develop investment strategy complying with fiduciary standards" \ --evaluationDomain finance \ --enable-evaluation \ --context '{ "regulatory": {"framework":"DOL-fiduciary","state":"california","clientType":"retirement-plan"}, "investment": {"universe":"mutual-funds","fees":"low-cost","diversification":"required"} }' \ --format json ``` ### Performance-Optimized Commands ```bash # High-performance analytics processing neurolink generate "Process large dataset for business insights" \ --evaluationDomain analytics \ --enable-analytics \ --provider vertex \ --max-tokens 1000 \ --timeout 180 \ --context '{"dataSize":"100GB","processing":"distributed","latency":"low","accuracy":"high"}' \ --format json ``` ## Best Practices ### 1. Domain Selection Guidelines - **Healthcare**: Medical analysis, diagnosis support, treatment planning, regulatory compliance - **Analytics**: Data analysis, business intelligence, predictive modeling, performance metrics - **Finance**: Investment analysis, risk assessment, financial planning, market analysis - **E-commerce**: Conversion optimization, customer experience, marketing campaigns, sales analytics ### 2. Context Structure Best Practices ```bash # Well-structured context example neurolink generate "Your analysis request" \ --context '{ "domain_specific": { "key_metrics": ["metric1", "metric2"], "constraints": ["constraint1", "constraint2"] }, "organizational": { "size": "enterprise", "industry": "technology" }, "temporal": { "timeframe": "Q3-2024", "urgency": "high" } }' \ --evaluationDomain analytics \ --enable-evaluation ``` ### 3. Output Format Selection - Use `--format json` for structured analysis and integration - Use `--format text` for human-readable reports - Use `--format table` for comparative data presentation ### 4. Performance Optimization - Use `--max-tokens` to control response length - Enable `--enable-analytics` for detailed performance metrics - Use appropriate providers for specific domains - Structure context data efficiently ### 5. Evaluation Best Practices - Always enable evaluation for critical domain applications - Use domain-specific evaluation criteria - Monitor evaluation scores for quality assurance - Combine evaluation with analytics for comprehensive insights ## Troubleshooting ### Common Issues and Solutions 1. **Unknown domain error** ```bash # Ensure domain name is supported neurolink generate "test" --evaluationDomain healthcare # ✓ Correct neurolink generate "test" --evaluationDomain medical # ✗ Incorrect ``` 2. **Context parsing errors** ```bash # Use proper JSON formatting neurolink generate "test" --context '{"key":"value"}' # ✓ Correct neurolink generate "test" --context '{key:value}' # ✗ Incorrect ``` 3. **Performance issues** ```bash # Optimize token limits and context size neurolink generate "test" --max-tokens 500 --context '{"minimal":"data"}' ``` 4. **Provider compatibility** ```bash # Test with different providers if needed neurolink generate "test" --provider google-ai --evaluationDomain healthcare neurolink generate "test" --provider anthropic --evaluationDomain finance ``` ## Additional Resources - [CLI Reference](/docs/cli/commands) - [Configuration Guide](/docs/deployment/configuration) - [Performance Optimization](/docs/deployment/performance-guide) - [API Documentation](/docs/sdk/api-reference) For more examples and advanced usage patterns, visit the [NeuroLink Examples Repository](https://github.com/juspay/neurolink-examples). --- ## CLI Guide This page has moved to [CLI Guide](/docs/). --- ## ️ CLI Reference Guide # ️ CLI Reference Guide ## Complete Command Reference ### Primary Usage (Recommended) ```bash # NEW: Primary command npx @juspay/neurolink generate "Your prompt here" [options] npx @juspay/neurolink gen "Your prompt here" [options] # Short form ``` ### Migration Examples ```bash # ✅ NEW: Recommended usage npx @juspay/neurolink generate "Explain AI" --provider google-ai npx @juspay/neurolink gen "Write code" --provider openai ``` ### Core Options | Flag | Type | Default | Description | | --------------- | ------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `--provider` | string | `auto` | AI provider (`auto`, `openai`, `bedrock`, `vertex`, `anthropic`, `azure`, `google-ai`, `huggingface`, `ollama`, `mistral`) | | `--model` | string | provider default | Specific model (e.g., `gemini-2.5-pro`, `gpt-4o`, `claude-3-sonnet`) | | `--temperature` | number | `0.7` | Creativity level (0.0 = focused, 1.0 = creative) | | `--max-tokens` | number | `1000` | Maximum tokens to generate | | `--system` | string | none | System prompt to guide AI behavior | | `--agent-mode` | boolean | `false` | Run as an autonomous terminal agent: prepend Neurolink's versioned agent instructions to the system prompt. `generate` and `stream` only. | | `--max-steps` | number | `200` | Maximum tool-calling steps before the turn stops (integer 1–500). Some providers cap lower. `generate` and `stream` only. | | `--format` | string | `text` | Output format (`text`, `json`) | | `--timeout` | number | `120` | Maximum execution time in seconds | | `--debug` | boolean | `false` | Enable debug mode with verbose output | ### Enhancement Features | Flag | Type | Default | Description | | --------------------- | ------- | ------- | -------------------------------------------------- | | `--enable-analytics` | boolean | `false` | Enable usage analytics (tokens, cost, performance) | | `--enable-evaluation` | boolean | `false` | Enable AI response quality evaluation | | `--context` | string | none | JSON context object for custom data | ### Universal Evaluation System | Flag | Type | Default | Description | | ---------------------- | ------- | ------- | ------------------------------------------------------------- | | `--evaluation-domain` | string | none | Domain expertise for evaluation (e.g., 'AI coding assistant') | | `--tool-usage-context` | string | none | Tool usage context for evaluation | | `--lighthouse-style` | boolean | `false` | Use Lighthouse-compatible domain-aware evaluation | ### MCP Integration | Flag | Type | Default | Description | | ----------------- | ------- | ------- | ------------------------------------------------------- | | `--disable-tools` | boolean | `false` | Disable MCP tool integration (tools enabled by default) | ### Video Generation (Veo 3.1) | Flag | Type | Default | Description | | ---------------------- | ------- | ------- | ------------------------------------------------------------------------- | | `--outputMode` | string | `text` | Output mode: 'text', 'video', or 'ppt' | | `--image` | string | none | Path to an input image to base the generated video on (e.g., ./input.png) | | `--videoOutput`, `-vo` | string | none | Path to save generated video (e.g., ./output.mp4) | | `--videoResolution` | string | `720p` | Video resolution: '720p' or '1080p' | | `--videoLength` | number | `6` | Video duration in seconds: 4, 6, or 8 | | `--videoAspectRatio` | string | `16:9` | Aspect ratio: '9:16' (portrait) or '16:9' (landscape) | | `--videoAudio` | boolean | `true` | Include synchronized audio | ### PPT Generation (AI Presentations) - `--outputMode` (string, default: `text`) — Output mode: `text`, `video`, or `ppt` - `--pptPages`, `--pages` (number, default: `10`) — Number of slides to generate (5-50) - `--pptTheme` (string, default: AI-selected) — Theme: `modern`, `corporate`, `creative`, `minimal`, or `dark` - `--pptAudience` (string, default: AI-selected) — Audience: `business`, `students`, `technical`, or `general` - `--pptTone` (string, default: AI-selected) — Tone: `professional`, `casual`, `educational`, or `persuasive` - `--pptNoImages` (boolean, default: `false`) — Disable AI image generation (AI images are enabled by default in CLI) - `--pptAspectRatio` (string, default: `16:9`) — Aspect ratio: `16:9` or `4:3` - `--pptOutput`, `--po` (string, default: auto-generated) — Path to save generated presentation ## Usage Examples ### Basic Text Generation ```bash # Simple generation npx @juspay/neurolink generate "Write a haiku about AI" # With specific provider npx @juspay/neurolink generate "Explain quantum computing" --provider openai # With model selection npx @juspay/neurolink generate "Write code" --provider google-ai --model gemini-2.5-pro ``` ### Enhanced Analytics & Evaluation ```bash # Basic analytics npx @juspay/neurolink generate "What is machine learning?" --enable-analytics # Analytics + evaluation npx @juspay/neurolink generate "Explain AI ethics" --enable-analytics --enable-evaluation # With custom context npx @juspay/neurolink generate "Create a proposal" \ --enable-analytics --enable-evaluation \ --context '{"company":"TechCorp","department":"AI"}' ``` ### Domain-Aware Evaluation ```bash # Basic domain evaluation npx @juspay/neurolink generate "Fix this Python code" \ --enable-evaluation --evaluation-domain "Python coding assistant" # Lighthouse-style evaluation npx @juspay/neurolink generate "Create a business plan" \ --lighthouse-style --evaluation-domain "Business consultant" \ --tool-usage-context "Used market-research and financial-analysis tools" # Enterprise evaluation with context npx @juspay/neurolink generate "Analyze sales data" \ --enable-analytics --lighthouse-style \ --evaluation-domain "Data analyst" \ --context '{"role":"senior_analyst","access_level":"full"}' ``` ### Debug & Development ```bash # Debug mode with full output npx @juspay/neurolink generate "Test prompt" --debug # Debug with enhancements npx @juspay/neurolink generate "Test analytics" \ --enable-analytics --enable-evaluation --debug # Disable MCP tools for testing npx @juspay/neurolink generate "Simple test" --disable-tools ``` ### Advanced Examples ```bash # Enterprise AI assistant with full features npx @juspay/neurolink generate "Create quarterly AI strategy" \ --provider openai --model gpt-4o \ --enable-analytics --lighthouse-style \ --evaluation-domain "AI strategy consultant" \ --tool-usage-context "Market research, competitor analysis, financial modeling" \ --context '{"company":"Fortune500","quarter":"Q1-2025","budget":"$5M"}' \ --debug # Cost-optimized evaluation npx @juspay/neurolink generate "Quick code review" \ --provider google-ai --model gemini-2.5-flash \ --enable-evaluation --evaluation-domain "Code reviewer" \ --max-tokens 500 # High-quality content generation npx @juspay/neurolink generate "Write technical documentation" \ --provider anthropic --model claude-3-opus \ --enable-analytics --enable-evaluation \ --evaluation-domain "Technical writer" \ --temperature 0.3 --max-tokens 2000 ``` ## Output Examples ### Basic Output ``` ✨ Generated text: Artificial Intelligence (AI) refers to... ✅ Text generated successfully! ``` ### Enhanced Output (with --enable-analytics --enable-evaluation) ``` ✨ Generated text: Artificial Intelligence (AI) refers to... Analytics: Provider: google-ai Model: gemini-2.5-flash Tokens: 245 (input: 12, output: 233) Cost: $0.0012 Response Time: 3247ms Context: {"domain":"education"} ⭐ Response Quality Evaluation: Relevance: 9/10 ✅ Accuracy: 8/10 Completeness: 9/10 Overall Quality: 9/10 Evaluated by: gemini-2.5-flash (1247ms) ✅ Text generated successfully! ``` ### Debug Output (with --debug) ``` Debug: Provider selection started Debug: Selected provider: google-ai (model: gemini-2.5-flash) Debug: Analytics enabled: true Debug: Evaluation enabled: true Debug: Request started at 2025-01-06T12:00:00.000Z ✨ Generated text: ... Debug: Raw analytics data: { "provider": "google-ai", "tokens": {"input": 12, "output": 233, "total": 245}, "cost": 0.0012, "responseTime": 3247, "context": {"domain": "education"} } Debug: Raw evaluation data: { "relevance": 9, "accuracy": 8, "completeness": 9, "overall": 9, "model": "gemini-2.5-flash", "evaluationTime": 1247 } ✅ Text generated successfully! ``` ## Error Handling ### Common Errors & Solutions **Provider not available:** ``` ❌ Error: Provider 'openai' not available (missing API key) Solution: Set OPENAI_API_KEY in your .env file ``` **Invalid context JSON:** ``` ❌ Error: Invalid JSON in --context parameter Solution: Use proper JSON format: --context '{"key":"value"}' ``` **Model not found:** ``` ❌ Error: Model 'invalid-model' not found for provider 'openai' Solution: Use valid model names (see provider documentation) ``` **Evaluation failed:** ``` ⚠️ Warning: Evaluation failed, continuing without quality scores Reason: Evaluation provider unavailable, set NEUROLINK_EVALUATION_MODEL ``` ## Performance Tips 1. **Fast Evaluation**: Use `--model gemini-2.5-flash` for quick, cost-effective evaluation 2. **Quality Content**: Use `--provider anthropic --model claude-3-opus` for high-quality generation 3. **Cost Optimization**: Set `NEUROLINK_EVALUATION_PREFER_CHEAP=true` for automatic cost optimization 4. **Debug Efficiently**: Use `--debug` only when troubleshooting to avoid verbose output 5. **Context Size**: Keep `--context` objects small to minimize token usage ## Video Generation Examples Generate videos from images using Veo 3.1 via Vertex AI: ```bash # Basic video generation npx @juspay/neurolink generate "Product showcase with smooth camera movement" \ --image ./product.jpg \ --outputMode video \ --videoOutput ./output.mp4 # Full options npx @juspay/neurolink generate "Cinematic reveal with dramatic lighting" \ --image ./hero-image.png \ --provider vertex \ --model veo-3.1 \ --outputMode video \ --videoResolution 1080p \ --videoLength 8 \ --videoAspectRatio 16:9 \ --videoOutput ./cinematic.mp4 # Portrait video for social media npx @juspay/neurolink generate "Vertical scroll animation" \ --image ./mobile-screenshot.jpg \ --outputMode video \ --videoResolution 720p \ --videoAspectRatio 9:16 \ --videoOutput ./story.mp4 ``` > **Note:** Video generation requires Vertex AI credentials. See [Video Generation Guide](/docs/features/video-generation). ## PPT Generation Examples Generate AI-powered PowerPoint presentations: ```bash # Basic PPT generation npx @juspay/neurolink generate "Introduction to Machine Learning" \ --outputMode ppt \ --pptPages 10 \ --pptOutput ./ml-presentation.pptx # With theme and audience customization npx @juspay/neurolink generate "Quarterly Sales Report Q4 2025" \ --provider vertex \ --model gemini-2.5-pro \ --outputMode ppt \ --pptPages 15 \ --pptTheme corporate \ --pptAudience business \ --pptTone professional \ --pptOutput ./q4-report.pptx # Creative presentation with AI-generated images npx @juspay/neurolink generate "Future of Space Tourism" \ --outputMode ppt \ --pptPages 12 \ --pptTheme creative \ --pptOutput ./space-tourism.pptx # Technical documentation with dark theme npx @juspay/neurolink generate "Kubernetes Architecture Deep Dive" \ --provider anthropic \ --model claude-3-5-sonnet \ --outputMode ppt \ --pptPages 20 \ --pptTheme dark \ --pptAudience technical \ --pptTone educational \ --pptOutput ./k8s-architecture.pptx # Disable AI image generation npx @juspay/neurolink generate "Company Brand Guidelines" \ --outputMode ppt \ --pptPages 8 \ --pptTheme minimal \ --pptNoImages \ --pptOutput ./brand-guidelines.pptx ``` > **Note:** PPT generation works with multiple AI providers. See [PPT Generation Guide](/docs/features/ppt-generation). ## Environment Variables See the [Environment Variables](/docs/getting-started/environment-variables) documentation for complete configuration options. ## API Integration For programmatic usage, see the [API Reference](/docs/sdk/api-reference) documentation. --- ## NeuroLink Dependency Upgrade Report # NeuroLink Dependency Upgrade Report > **Describes the pre-removal dependency state.** The Vercel AI SDK sections > below (§4.1–4.7, §4.25) analyse `ai` and `@ai-sdk/*` packages that have since > been removed from this repo — see > `docs/plans/2026-09-03-completing-the-ai-sdk-removal.md`. Kept as a record; > those upgrade recommendations are no longer actionable. **Date:** 2026-02-27 **Version:** 9.12.1 **Branch:** fix/security-fixes ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Security Fixes** | 1 direct fix (download size limits in `@ai-sdk/provider-utils`), 1 dev dependency fix (Fastify CVE-2026-25224), 2 already-patched CVEs in baseline versions | | **Critical Bug Fixes** | Azure streaming tool calls fixed (`@ai-sdk/openai` 3.0.36), duplicate tool part creation fixed (`ai` 6.0.101) | | **New Features** | Anthropic code execution tool, Gemini 3.1 image model, gpt-5.3-codex phase parameter, Google server-side MCP, GenAI telemetry conventions | | **Breaking Changes** | Zero breaking changes in production dependencies; TypeScript 5.9 will surface new type errors | --- ## 2. Upgrade Priority Matrix | # | Package | Current | Latest | Risk | Priority | Category | | --- | ------------------------------------- | -------- | ------- | ------ | ------------ | ----------- | | 1 | `@ai-sdk/openai` | 3.0.34 | 3.0.36 | Low | **Critical** | Bug Fix | | 2 | `@ai-sdk/azure` | 3.0.35 | 3.0.37 | Low | **Critical** | Bug Fix | | 3 | `@ai-sdk/mistral` | 3.0.12 | 3.0.20 | Low | **Critical** | Security | | 4 | `fastify` | 5.7.2 | 5.7.4 | Low | **High** | Security | | 5 | `ai` | 6.0.101 | 6.0.103 | Low | **High** | Bug Fix | | 6 | `@ai-sdk/anthropic` | 3.0.47 | 3.0.48 | Low | **High** | Feature | | 7 | `@ai-sdk/google` | 3.0.31 | 3.0.33 | Low | **High** | Feature | | 8 | `@ai-sdk/google-vertex` | 4.0.63 | 4.0.66 | Low | **High** | Feature | | 9 | `@google/genai` | 1.42.0 | 1.43.0 | Low | **High** | Feature | | 10 | `undici` | >=7.18.2 | 7.22.0 | Low | **Medium** | Maintenance | | 11 | `@opentelemetry/semantic-conventions` | 1.39.0 | 1.40.0 | Low | **Medium** | Feature | | 12 | `hono` | 4.12.2 | 4.12.3 | Low | **Medium** | Maintenance | | 13 | `nanoid` | 5.1.5 | 5.1.6 | Low | **Low** | Maintenance | | 14 | `@aws-sdk/client-bedrock` | 3.998.0 | 3.999.0 | Low | **Low** | Maintenance | | 15 | `@aws-sdk/client-bedrock-runtime` | 3.998.0 | 3.999.0 | Low | **Low** | Maintenance | | 16 | `@aws-sdk/client-sagemaker` | 3.998.0 | 3.999.0 | Low | **Low** | Maintenance | | 17 | `@aws-sdk/client-sagemaker-runtime` | 3.998.0 | 3.999.0 | Low | **Low** | Maintenance | | 18 | `@semantic-release/npm` | 13.1.2 | 13.1.4 | Low | **Low** | Maintenance | | 19 | `@sveltejs/kit` | 2.53.2 | 2.53.3 | Low | **Low** | Maintenance | | 20 | `@types/node` | 25.3.1 | 25.3.2 | Low | **Low** | Maintenance | | 21 | `svelte-check` | 4.4.3 | 4.4.4 | Low | **Low** | Maintenance | | 22 | `@ai-sdk/provider` | 3.0.8 | 3.0.8 | None | **None** | Up to date | | 23 | `tslib` | 2.4.1 | 2.8.1 | Medium | **Medium** | Maintenance | | 24 | `typescript` | 5.0.0 | 5.9.3 | High | **Medium** | Maintenance | | 25 | `@langfuse/otel` | 4.6.1 | latest | Low | **Low** | Maintenance | --- ## 3. Security Fixes ### Direct Security Fix: Download Size Limits (provider-utils 4.0.15) | Field | Value | | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Severity** | Medium (DoS prevention) | | **Package** | `@ai-sdk/provider-utils` 4.0.15 (transitive, pulled in via `@ai-sdk/mistral` 3.0.20) | | **Description** | `download()` and `downloadBlob()` now enforce a **default 2 GiB size limit** on user-provided URLs. Downloads exceeding the limit abort with `DownloadError`. `abortSignal` properly passed to `fetch()`. | | **Are we affected?** | **Yes.** NeuroLink passes user-provided URLs to `generateText()`/`streamText()` (e.g., image URLs). Without this fix, a malicious URL could cause memory exhaustion (DoS). | | **Fix** | Upgrade `@ai-sdk/mistral` to 3.0.20. All other AI SDK packages will transitively receive this fix. | ### Dev Dependency Security Fix: Fastify CVE-2026-25224 | Field | Value | | -------------------- | --------------------------------------------------------------------------------------------------------------------- | | **CVE** | CVE-2026-25224 (GHSA-mrq3-vjjr-p77c) | | **Severity** | Not yet scored | | **Package** | `fastify` 5.7.3+ | | **Description** | Security fix related to `Reply.send()` string serialization. | | **Are we affected?** | Fastify is a devDependency used as a server adapter (`src/lib/server/`). Low production risk, but important to patch. | | **Fix** | Upgrade `fastify` to 5.7.4. | ### Already Patched (in current baseline versions) | CVE | Severity | Package | Description | Status | | -------------- | --------------- | ------- | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | CVE-2025-48985 | Low | AI SDK | Input validation bypass allowing URL-to-data substitution in multimodal prompts | Fixed in versions prior to our baseline (6.0.101+). **Not a concern.** | | CVE-2026-22036 | Low (CVSS 3.7) | undici | Unbounded decompression chain in HTTP `Content-Encoding` causing CPU/memory exhaustion | Fixed in 7.18.2 (our current minimum). **Not a concern.** | | CVE-2026-27700 | High (CVSS 8.2) | hono | Authentication bypass by IP spoofing in AWS Lambda ALB `conninfo` | Fixed in 4.12.2 (our current version). **NeuroLink does not use the affected Lambda adapter.** | --- ## 4. Per-Package Detailed Analysis ### AI SDK Packages (7 packages) #### 4.1 `@ai-sdk/openai` (3.0.34 -> 3.0.36) | Field | Details | | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **What changed** | v3.0.36: Fixed streaming tool call handling for Azure AI Foundry/Mistral (null/undefined `type` fields now treated as `"function"`). v3.0.35: Enhanced reasoning content fallback for Responses API (uses `encrypted_content` when `itemId` absent). v3.0.34: Added `phase` parameter support for gpt-5.3-codex model. | | **Breaking changes** | None | | **New features for NeuroLink** | The streaming fix (3.0.36) resolves existing failures for Azure-deployed Mistral models. The `phase` parameter (3.0.34) is required for correct gpt-5.3-codex behavior -- dropping it causes performance degradation. Consider exposing `phase` in NeuroLink response objects. | | **Codebase impact** | `src/lib/providers/openAI.ts`, `src/lib/providers/huggingFace.ts`, `src/lib/providers/litellm.ts`, `src/lib/providers/openaiCompatible.ts` -- all use `createOpenAI` factory. No code changes required. | | **Risk level** | Low | | **Recommendation** | Upgrade immediately. Fixes active bugs. | #### 4.2 `@ai-sdk/azure` (3.0.35 -> 3.0.37) | Field | Details | | ------------------------------ | ---------------------------------------------------------------------------------------------------------- | | **What changed** | Three dependency-only bumps pulling in `@ai-sdk/openai` 3.0.34-3.0.36. No Azure-specific code changes. | | **Breaking changes** | None | | **New features for NeuroLink** | Inherits all `@ai-sdk/openai` improvements (streaming tool call fix, reasoning fallback, phase parameter). | | **Codebase impact** | `src/lib/providers/azureOpenai.ts` -- uses `createAzure` factory. No code changes required. | | **Risk level** | Low | | **Recommendation** | Upgrade alongside `@ai-sdk/openai`. | #### 4.3 `@ai-sdk/anthropic` (3.0.47 -> 3.0.48) | Field | Details | | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **What changed** | v3.0.48: Added code execution tool support (Anthropic sandbox). v3.0.47 (already current): Improved `cacheControl` placement for prompt caching. | | **Breaking changes** | None | | **New features for NeuroLink** | Code execution tool could be exposed as a built-in tool option for Anthropic users, similar to MCP tool handling. Prompt caching now works more reliably (automatic benefit). | | **Codebase impact** | `src/lib/providers/anthropic.ts`, `src/lib/providers/anthropicBaseProvider.ts` -- both use `createAnthropic` factory. No code changes required. | | **Risk level** | Low | | **Recommendation** | Upgrade. Consider adding code execution tool integration. | #### 4.4 `@ai-sdk/google` (3.0.31 -> 3.0.33) | Field | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **What changed** | v3.0.33: Added image model aspect ratios/sizes. v3.0.32: Added `gemini-3.1-flash-image-preview` model support. v3.0.31: Expanded model ID type definitions. | | **Breaking changes** | None | | **New features for NeuroLink** | Gemini 3.1 Flash Image Preview model for image generation. More granular image output dimensions. Consider adding the model to NeuroLink's model definitions. | | **Codebase impact** | `src/lib/providers/googleAiStudio.ts` -- uses `createGoogleGenerativeAI` factory. No code changes required. | | **Risk level** | Low | | **Recommendation** | Upgrade. Add `gemini-3.1-flash-image-preview` to model definitions. | #### 4.5 `@ai-sdk/google-vertex` (4.0.63 -> 4.0.66) | Field | Details | | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **What changed** | Four dependency-only bumps pulling in updated `@ai-sdk/google` and `@ai-sdk/anthropic`. v4.0.64 added `gemini-3.1-flash-image-preview` model support for Vertex. | | **Breaking changes** | None | | **New features for NeuroLink** | Same Gemini 3.1 image model support through Vertex AI. Anthropic code execution tool via Vertex. | | **Codebase impact** | `src/lib/providers/googleVertex.ts` -- uses `createVertex` and `createVertexAnthropic` factories, including the `/anthropic` sub-path import. No code changes required. | | **Risk level** | Low | | **Recommendation** | Upgrade alongside other AI SDK packages. | #### 4.6 `@ai-sdk/mistral` (3.0.12 -> 3.0.20) | Field | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **What changed** | 8 version bumps, almost entirely dependency updates. Carries the security fix via `@ai-sdk/provider-utils` 4.0.15 (download size limits). Also includes Bun compatibility, better error messages, and video model resolution support from transitive dependencies. | | **Breaking changes** | None | | **New features for NeuroLink** | Download size limit enforcement (2 GiB default) prevents memory exhaustion DoS. Bun fetch errors now retryable. Better type validation error messages. | | **Codebase impact** | `src/lib/providers/mistral.ts` -- uses `createMistral` factory. `src/lib/factories/providerRegistry.ts` -- type-only import. No code changes required. | | **Risk level** | Low | | **Recommendation** | Upgrade immediately for security fix. | #### 4.7 `ai` (6.0.101 -> 6.0.103) | Field | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **What changed** | v6.0.101: Fixed duplicate tool part creation when models invoke non-existent tools. v6.0.102-103: Gateway dependency bumps. | | **Breaking changes** | None | | **New features for NeuroLink** | The duplicate tool part fix improves reliability of the tool execution pipeline, especially with less capable models that may hallucinate tool names. | | **Codebase impact** | Used across 30+ files (`GenerationHandler.ts`, `ToolsManager.ts`, all provider implementations, middleware, message builders, type definitions). No code changes required -- these are bug fixes. | | **Risk level** | Low | | **Recommendation** | Upgrade. Improves tool execution reliability. | --- ### AWS SDK Packages (4 packages) #### 4.8-4.11 AWS SDK Packages (3.998.0 -> 3.999.0) All four AWS SDK packages (`@aws-sdk/client-bedrock`, `@aws-sdk/client-bedrock-runtime`, `@aws-sdk/client-sagemaker`, `@aws-sdk/client-sagemaker-runtime`) received **version-bump-only** updates. No new features, no bug fixes, no breaking changes in any of the Bedrock or SageMaker client packages. | Package | Codebase Impact | Risk | | ----------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---- | | `@aws-sdk/client-bedrock` | `src/lib/providers/amazonBedrock.ts` -- `BedrockClient`, `ListFoundationModelsCommand` | Low | | `@aws-sdk/client-bedrock-runtime` | `src/lib/providers/amazonBedrock.ts` -- `BedrockRuntimeClient`, `ConverseCommand`, `ConverseStreamCommand` | Low | | `@aws-sdk/client-sagemaker` | `src/cli/factories/sagemakerCommandFactory.ts` -- `SageMakerClient`, `ListEndpointsCommand` | Low | | `@aws-sdk/client-sagemaker-runtime` | `src/lib/providers/sagemaker/client.ts` -- `SageMakerRuntimeClient`, `InvokeEndpointCommand` | Low | **SDK-wide change:** `util-user-agent-node` now populates TypeScript version in user-agent headers (non-breaking telemetry improvement). **Recommendation:** Upgrade all 4 together. No code changes required. --- ### Google & Core Libraries (5 packages) #### 4.12 `@google/genai` (1.42.0 -> 1.43.0) | Field | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **What changed** | Added `gemini-3.1-pro-preview` model. Added Image Grounding for GoogleSearch tool. Enabled server-side MCP support. More image sizes/resolutions. Breaking: `interactions` media mime type changed from string to enum (experimental Interactions API only). | | **Breaking changes** | Interactions API mime type enum change -- **does NOT affect NeuroLink** (we use standard generate/stream APIs, not experimental Interactions). | | **New features for NeuroLink** | **Server-side MCP support** is directly relevant -- could enable passing MCP server configs to the Google API rather than handling tool calls client-side. Gemini 3.1 Pro Preview model. Image Grounding for GoogleSearch. | | **Codebase impact** | `src/lib/providers/googleAiStudio.ts`, `src/lib/providers/googleVertex.ts`, `src/lib/adapters/video/videoAnalyzer.ts` -- all use dynamic imports. No code changes required. | | **Risk level** | Low | | **Recommendation** | Upgrade. Explore server-side MCP integration opportunities. | #### 4.13 `undici` (>=7.18.2 -> 7.22.0) | Field | Details | | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **What changed** | 4 minor + 2 patch releases. Key changes: fixed 401 loop in fetch (7.19.1), proper 401 response handling (7.19.2), HTTP/2 flow-control options (7.19.0), preserved fetch stack traces (7.20.0), `pingInterval` keep-alive (7.21.0), proxy agent enhancements (7.22.0), `__filename` bundling fix (7.21.0). | | **Breaking changes** | None within v7.x. | | **New features for NeuroLink** | 401 loop fix and proxy agent enhancements directly benefit `proxyFetch.ts` and `awsProxyIntegration.ts`. HTTP/2 flow-control could benefit Vertex AI streaming. Stack trace preservation improves debugging. | | **Codebase impact** | `src/lib/utils/messageBuilder.ts`, `src/lib/utils/fileDetector.ts` -- `getGlobalDispatcher`, `interceptors`, `request`. `src/lib/proxy/proxyFetch.ts` -- `ProxyAgent`. No code changes required. | | **Risk level** | Low | | **Recommendation** | Upgrade. Many quality-of-life fixes for proxy/fetch infrastructure. | #### 4.14 `@opentelemetry/semantic-conventions` (1.39.0 -> 1.40.0) | Field | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **What changed** | 2 new stable attributes (`ATTR_SERVICE_INSTANCE_ID`, `ATTR_SERVICE_NAMESPACE`). 157 new unstable attributes including GenAI cache tokens, tool call support, MCP protocol, and OpenAI API type. 40 unstable deprecations. | | **Breaking changes** | None affecting NeuroLink. We only use `ATTR_SERVICE_NAME` and `ATTR_SERVICE_VERSION` (stable, unchanged). | | **New features for NeuroLink** | New GenAI semantic convention attributes (`gen_ai.agent.version`, cache token attributes, MCP protocol support) are directly relevant to NeuroLink's telemetry and could enable richer observability. | | **Codebase impact** | `src/lib/telemetry/telemetryService.ts`, `src/lib/services/server/ai/observability/instrumentation.ts` -- only `ATTR_SERVICE_NAME` and `ATTR_SERVICE_VERSION`. No code changes required. | | **Risk level** | Low | | **Recommendation** | Upgrade. Consider adopting GenAI/MCP telemetry attributes in a follow-up. | #### 4.15 `hono` (4.12.2 -> 4.12.3) | Field | Details | | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **What changed** | Bug fixes: form data type diff, safer JWT timestamp handling (`Math.floor` instead of bitwise OR), `JwtVariables` compatibility, removed DOM type dependencies, corrected middleware types, **fixed JWT memory leak**. | | **Breaking changes** | None | | **New features for NeuroLink** | Memory leak fix in JWT operations. Removal of DOM type dependencies improves Node.js-only TypeScript compatibility. | | **Codebase impact** | `src/lib/server/adapters/honoAdapter.ts` -- `Hono`, `cors`, `HTTPException`, `logger`, `secureHeaders`, `streamSSE`, `timeout`. No code changes required. | | **Risk level** | Low | | **Recommendation** | Upgrade. | #### 4.16 `nanoid` (5.1.5 -> 5.1.6) | Field | Details | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | **What changed** | Fixed infinite loop when passing `0` as size to `customAlphabet()`. | | **Breaking changes** | None | | **New features for NeuroLink** | None directly. NeuroLink always calls `nanoid()` without arguments (default 21-char IDs), never `customAlphabet`. | | **Codebase impact** | `src/lib/core/modules/StreamHandler.ts`, `src/lib/core/modules/TelemetryHandler.ts`, `src/lib/session/globalSessionState.ts`. No code changes required. | | **Risk level** | Low | | **Recommendation** | Upgrade. Trivial zero-risk patch. | --- ### Dev Dependencies (8 packages) #### 4.17 `@semantic-release/npm` (13.1.2 -> 13.1.4) | Field | Details | | -------------------- | ------------------------------------------------------------------- | | **What changed** | Internal `@actions/core` updated from v1 to v3 across two releases. | | **Breaking changes** | None | | **Risk level** | Low | | **Recommendation** | Upgrade. No API changes. | #### 4.18 `@sveltejs/kit` (2.53.2 -> 2.53.3) | Field | Details | | -------------------- | -------------------------------------------------------------------- | | **What changed** | Fix to prevent overlapping file metadata in remote functions `form`. | | **Breaking changes** | None | | **Risk level** | Low | | **Recommendation** | Upgrade. Patch-level bug fix. | #### 4.19 `@types/node` (25.3.1 -> 25.3.2) | Field | Details | | -------------------- | -------------------------------------------------------------- | | **What changed** | Incremental type definition refinements for Node.js 25.x APIs. | | **Breaking changes** | None | | **Risk level** | Low | | **Recommendation** | Upgrade. Type-only, no runtime impact. | #### 4.20 `fastify` (5.7.2 -> 5.7.4) | Field | Details | | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | **What changed** | v5.7.3: Security fix for CVE-2026-25224 (GHSA-mrq3-vjjr-p77c) related to `Reply.send()` string serialization. v5.7.4: Follow-up patch. | | **Breaking changes** | None | | **Codebase impact** | Dev dependency used in `src/lib/server/` adapter layer. | | **Risk level** | Low | | **Recommendation** | Upgrade. Security patch. | #### 4.21 `svelte-check` (4.4.3 -> 4.4.4) | Field | Details | | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | **What changed** | More robust `lang="ts"` detection, filename passed to `warningFilter`, Svelte file resolution under path alias in `--incremental/tsgo` mode. | | **Breaking changes** | None | | **Risk level** | Low | | **Recommendation** | Upgrade. Path alias resolution improvement benefits NeuroLink's `$lib` aliases. | #### 4.22 `tslib` (2.4.1 -> 2.8.1) | Field | Details | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **What changed** | Major feature additions over 10 releases: `using`/`await using` helpers (2.6.0), `rewriteRelativeImportExtensions` helper (2.8.0), decorator init hook order reversed (2.5.1), improved `exports` field for `node16`/`bundler` resolution (2.5.1), non-enumerable keys in `__importStar` (2.8.1). | | **Breaking changes** | Decorator `init` hook order reversed in 2.5.1 (matches spec). `exports` field restructured in 2.5.1. | | **Codebase impact** | Dev dependency only. `importHelpers` is NOT enabled in tsconfig, so tslib may not actually be used at runtime. No direct imports found in `src/`. | | **Risk level** | Medium (due to version jump size), but effectively **Low** since it appears unused at runtime. | | **Recommendation** | Upgrade. Run full test suite after. | #### 4.23 `typescript` (5.0.0 -> 5.9.3) | Field | Details | | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **What changed** | 10 minor versions spanning June 2023 to August 2025. Adds `using`/`await using` (5.2), `NoInfer` (5.4), inferred type predicates (5.5), disallowed nullish/truthy checks (5.6), `--rewriteRelativeImportExtensions` (5.7), `--erasableSyntaxOnly` (5.8), `import defer` (5.9), and cumulative performance improvements. | | **Breaking changes** | **Multiple.** Always-truthy/nullish checks now error (5.6). Stricter generic constraint null checks (5.9). Uninitialized variable checks (5.7). Conditional return type checks (5.8). `BuiltinIterator` renamed to `IteratorObject` (5.6). Numerous `lib.d.ts` changes. ArrayBuffer no longer supertype of Buffer (5.9). | | **Codebase impact** | All `.ts` files potentially. TypeScript strict mode is already enabled. `skipLibCheck: true` mitigates `.d.ts` issues. Run `pnpm run check` after upgrade to identify all new errors. | | **Risk level** | **High** | | **Recommendation** | Dedicate a separate effort. See Phase 4 in Recommended Upgrade Plan. | #### 4.24 `@langfuse/otel` (4.6.1 -> latest) | Field | Details | | -------------------- | -------------------------------------------------------------------------------------------------------- | | **What changed** | Ongoing improvements to the Langfuse OpenTelemetry span processor. | | **Breaking changes** | None expected within minor versions. | | **Codebase impact** | `src/lib/services/server/ai/observability/instrumentation.ts` -- `LangfuseSpanProcessor`. Single import. | | **Risk level** | Low | | **Recommendation** | Upgrade alongside OpenTelemetry packages. | #### 4.25 `@ai-sdk/provider` (3.0.8 -- already current) | Field | Details | | ------------------- | ------------------------------------------------------------------------------------ | | **What changed** | N/A -- already at latest. | | **Codebase impact** | `src/lib/types/evaluationTypes.ts` -- `LanguageModelV3CallOptions` type-only import. | | **Risk level** | None | | **Recommendation** | No action needed. | --- ## 5. New Features & Opportunities Sorted by estimated business value to NeuroLink: ### High Value | Feature | Package | Version | Description | | ---------------------------------------- | ------------------------ | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | **Azure streaming tool call fix** | `@ai-sdk/openai` | 3.0.36 | Fixes `InvalidResponseDataError` for Azure AI Foundry/Mistral deployments during streaming tool calls. Resolves existing user-facing failures. | | **Download size limit (DoS prevention)** | `@ai-sdk/provider-utils` | 4.0.15 | 2 GiB default size limit prevents memory exhaustion from malicious URLs. Security hardening for production. | | **gpt-5.3-codex phase parameter** | `@ai-sdk/openai` | 3.0.34 | Required for correct gpt-5.3-codex behavior. Dropping phase causes performance degradation. | | **Google server-side MCP** | `@google/genai` | 1.43.0 | Pass MCP server configs directly to Google API instead of client-side tool handling. Aligns with NeuroLink's MCP architecture. | | **Anthropic code execution tool** | `@ai-sdk/anthropic` | 3.0.48 | Sandbox code execution. Can be exposed as a built-in tool option for Anthropic users. | ### Medium Value | Feature | Package | Version | Description | | ------------------------------------ | ------------------------------------- | --------------- | ----------------------------------------------------------------------------------------------- | | **Gemini 3.1 models** | `@ai-sdk/google`, `@google/genai` | 3.0.32+, 1.43.0 | `gemini-3.1-flash-image-preview` and `gemini-3.1-pro-preview` models. Add to model definitions. | | **Image Grounding for GoogleSearch** | `@google/genai` | 1.43.0 | Multimodal search capabilities via GoogleSearch tool. | | **GenAI telemetry conventions** | `@opentelemetry/semantic-conventions` | 1.40.0 | Cache token attributes, MCP protocol attributes, tool call support for richer observability. | | **Proxy/fetch improvements** | `undici` | 7.19-7.22 | 401 loop fix, proxy agent enhancements, HTTP/2 flow-control, stack trace preservation. | ### Lower Value (Future) | Feature | Package | Version | Description | | ------------------------------ | ------------------ | ------- | -------------------------------------------------------------------------- | | **Inferred type predicates** | `typescript` | 5.5+ | `.filter()` calls now properly narrow types. Catches bugs. | | **`NoInfer`** | `typescript` | 5.4+ | Useful in factory/registry generics. | | **`using`/`await using`** | `typescript` | 5.2+ | Explicit resource management for MCP connections, Redis, etc. | | **`import defer`** | `typescript` | 5.9 | Deferred module evaluation aligns with NeuroLink's dynamic import pattern. | | **Experimental video support** | `@ai-sdk/provider` | 3.0.7+ | `generateVideo` support in provider interface (experimental). | --- ## 6. Recommended Upgrade Plan ### Phase 1: Zero-Risk Patches (Do Immediately) **Estimated effort:** 30 minutes **Strategy:** Batch update, run tests once | Package | From | To | Reason | | ----------------------- | ------- | ------- | -------------------------------- | | `@ai-sdk/openai` | 3.0.34 | 3.0.36 | Fixes Azure streaming failures | | `@ai-sdk/azure` | 3.0.35 | 3.0.37 | Dependency alignment | | `@ai-sdk/anthropic` | 3.0.47 | 3.0.48 | Code execution tool | | `@ai-sdk/google` | 3.0.31 | 3.0.33 | Image model support | | `@ai-sdk/google-vertex` | 4.0.63 | 4.0.66 | Dependency alignment | | `@ai-sdk/mistral` | 3.0.12 | 3.0.20 | **Security fix** | | `ai` | 6.0.101 | 6.0.103 | Bug fix for duplicate tool parts | | `nanoid` | 5.1.5 | 5.1.6 | Trivial patch | | `hono` | 4.12.2 | 4.12.3 | Memory leak fix | **Verification:** ```bash pnpm install pnpm test pnpm run test:providers ``` ### Phase 2: Low-Risk Upgrades (Batch Together) **Estimated effort:** 1 hour **Strategy:** Batch update by group, run targeted tests **Group A -- AWS SDK (upgrade together):** | Package | From | To | | ----------------------------------- | ------- | ------- | | `@aws-sdk/client-bedrock` | 3.998.0 | 3.999.0 | | `@aws-sdk/client-bedrock-runtime` | 3.998.0 | 3.999.0 | | `@aws-sdk/client-sagemaker` | 3.998.0 | 3.999.0 | | `@aws-sdk/client-sagemaker-runtime` | 3.998.0 | 3.999.0 | **Group B -- Core libs & Google:** | Package | From | To | | ------------------------------------- | -------- | ------ | | `@google/genai` | 1.42.0 | 1.43.0 | | `undici` | >=7.18.2 | 7.22.0 | | `@opentelemetry/semantic-conventions` | 1.39.0 | 1.40.0 | **Group C -- Dev dependencies:** | Package | From | To | | ----------------------- | ------ | ------ | | `@semantic-release/npm` | 13.1.2 | 13.1.4 | | `@sveltejs/kit` | 2.53.2 | 2.53.3 | | `@types/node` | 25.3.1 | 25.3.2 | | `fastify` | 5.7.2 | 5.7.4 | | `svelte-check` | 4.4.3 | 4.4.4 | | `@langfuse/otel` | 4.6.1 | latest | **Verification:** ```bash pnpm install pnpm test pnpm run test:providers pnpm run test:cli pnpm run test:integration pnpm run build ``` ### Phase 3: Medium-Risk Upgrades (Test Carefully) **Estimated effort:** 2 hours **Strategy:** Upgrade one at a time, test after each | Package | From | To | Key Concern | | ------- | ----- | ----- | ---------------------------------------------------------------------------------------------------- | | `tslib` | 2.4.1 | 2.8.1 | Decorator hook order, exports field changes. Likely unused at runtime (`importHelpers` not enabled). | **Verification:** ```bash pnpm install pnpm run build:complete pnpm test pnpm run check ``` ### Phase 4: High-Risk Upgrades (Dedicated Effort) **Estimated effort:** 1-2 days **Strategy:** Separate branch, dedicated type error resolution | Package | From | To | Key Concern | | ------------ | ----- | ----- | -------------------------------------------------------------------------------- | | `typescript` | 5.0.0 | 5.9.3 | 10 minor versions with cumulative stricter checks. Will surface new type errors. | **Migration steps:** 1. Create a dedicated branch: `chore/typescript-5.9-upgrade` 2. Update `typescript` to 5.9.3 in `package.json` 3. Run `pnpm install` 4. Run `tsc --noEmit` and catalog all new errors 5. Fix errors in order of severity (type errors first, then new warnings) 6. Pay special attention to: - Always-truthy/nullish checks (TS 5.6) -- likely the most common new errors - Uninitialized variable checks (TS 5.7) - Stricter conditional return types (TS 5.8) - Generic constraint null checks (TS 5.9) - ArrayBuffer/Buffer relationship changes (TS 5.9) 7. Run full test suite: `pnpm test` 8. Run full type check: `pnpm run check` 9. Run full build: `pnpm run build:complete` 10. Consider using `--noCheck` flag (TS 5.6) as a temporary escape hatch if needed during migration --- ## 7. Risk Mitigation ### Testing Strategy | Phase | Test Coverage | Commands | | ------- | ---------------------------------------------------- | --------------------------------------------------------------------------------- | | Phase 1 | Provider unit tests + full test suite | `pnpm test && pnpm run test:providers` | | Phase 2 | Full test suite + CLI + integration + build | `pnpm test && pnpm run test:cli && pnpm run test:integration && pnpm run build` | | Phase 3 | Full test suite + type check + complete build | `pnpm test && pnpm run check && pnpm run build:complete` | | Phase 4 | Type check (first), then full suite + complete build | `pnpm run check && pnpm test && pnpm run build:complete && pnpm run validate:all` | ### Rollback Plan Each phase should be committed separately so rollback is straightforward: 1. **Phase 1-3 rollback:** Revert the commit, run `pnpm install`. These are all backward-compatible changes, so reverting is clean. 2. **Phase 4 rollback (TypeScript):** Since TypeScript 5.9 upgrade involves source code changes (fixing new type errors), keep the upgrade on a separate branch. If issues are discovered post-merge, revert both the `package.json` change and the type fix commits. ### Pre-Upgrade Checklist - [ ] Ensure CI is green on current branch - [ ] Create a snapshot of current `pnpm-lock.yaml` - [ ] Run `pnpm run validate:all` before starting - [ ] After each phase: `pnpm run validate:security` ### Post-Upgrade Validation - [ ] All tests pass (`pnpm test`) - [ ] Type checking passes (`pnpm run check`) - [ ] Build succeeds (`pnpm run build:complete`) - [ ] Security validation passes (`pnpm run validate:security`) - [ ] ESLint within warning budget (300 src, 10 test) - [ ] No new `no-explicit-any` errors in `src/` --- _Generated by automated dependency research pipeline. Research sources: npm registry, GitHub changelogs, CVE databases, and codebase static analysis._ --- ## Lighthouse Unified Integration Guide # Lighthouse Unified Integration Guide ## ✅ **FINAL IMPLEMENTATION: Unified registerTools() API** This document outlines the final implementation of Lighthouse integration through a unified `registerTools()` method that accepts both object and array formats. ## **Overview** **Problem Solved**: Seamless integration of Lighthouse tools without migration or special methods. **Solution**: Enhanced `registerTools()` method that automatically detects and handles both: - **Object format**: `Record` (existing compatibility) - **Array format**: `Array` (Lighthouse compatibility) ## **Core Implementation** ### **Method Signature** ```typescript registerTools(tools: Record | Array): void ``` ### **Automatic Format Detection** ```typescript registerTools(tools: Record | Array): void { if (Array.isArray(tools)) { // Handle array format (Lighthouse compatible) for (const { name, tool } of tools) { this.registerTool(name, tool); } } else { // Handle object format (existing compatibility) for (const [name, tool] of Object.entries(tools)) { this.registerTool(name, tool); } } } ``` ## **Lighthouse Compatibility** ### **Zod Schema Support** NeuroLink already supports Zod schemas in the `SimpleTool` interface: ```typescript type SimpleTool = { description: string; parameters?: ZodSchema; // Zod support already implemented execute: (params: ToolArgs, context?: ExecutionContext) => Promise; }; ``` ### **Example: Lighthouse Tool Integration** ```typescript const neurolink = new NeuroLink(); // Lighthouse tools exported as array with Zod schemas const lighthouseTools = [ { name: "juspay-analytics", tool: { description: "Analyze Juspay merchant payment data", parameters: z.object({ merchantId: z.string().describe("Merchant identifier"), dateRange: z.object({ start: z.string().datetime(), end: z.string().datetime(), }), metrics: z .array(z.enum(["volume", "success_rate", "avg_amount"])) .optional(), }), execute: async ({ merchantId, dateRange, metrics }) => { // Lighthouse tool implementation return { merchantId, period: dateRange, analytics: { totalVolume: 125000, successRate: 0.987, avgAmount: 45.67, }, }; }, }, }, { name: "payment-processor", tool: { description: "Process payment transactions", parameters: z.object({ amount: z.number().positive(), currency: z.string().length(3), paymentMethod: z.enum(["card", "upi", "wallet"]), }), execute: async ({ amount, currency, paymentMethod }) => { return { transactionId: `txn_${Date.now()}`, status: "success", amount, currency, method: paymentMethod, }; }, }, }, ]; // Register Lighthouse tools using unified API neurolink.registerTools(lighthouseTools); // Use in AI generation const result = await neurolink.generate({ input: { text: "Show me payment analytics for merchant MERCH123 for the last week", }, provider: "google-ai", }); ``` ## **Compatibility Matrix** | Format | Type | Lighthouse Compatible | Backward Compatible | Status | | ------ | ------------------------------------------- | ----------------------- | ------------------- | -------- | | Object | `Record` | ⚠️ Requires conversion | ✅ Yes | Existing | | Array | `Array` | ✅ Direct compatibility | ✅ Yes | New | ## **Migration Path** ### **Existing Code** No changes required - object format continues to work: ```typescript // Existing code remains unchanged neurolink.registerTools({ myTool: { description: "...", execute: async () => {...} } }); ``` ### **New Lighthouse Integration** Direct import using array format: ```typescript // Lighthouse tools can be imported directly neurolink.registerTools(lighthouseAnalyticsTools); ``` ## **Benefits** 1. **Unified API**: Single method for all tool registration needs 2. **Zero Migration**: Lighthouse tools work without conversion 3. **Backward Compatibility**: Existing code unchanged 4. **Type Safety**: Full TypeScript support for both formats 5. **Zod Integration**: Native support for Zod parameter validation 6. **API Simplification**: Removes need for separate methods ## **Testing Strategy** ### **Format Detection Tests** ```typescript describe("Unified registerTools()", () => { test("should detect object format", () => { neurolink.registerTools({ tool1: {...}, tool2: {...} }); expect(neurolink.getCustomTools().size).toBe(2); }); test("should detect array format", () => { neurolink.registerTools([ { name: "tool1", tool: {...} }, { name: "tool2", tool: {...} } ]); expect(neurolink.getCustomTools().size).toBe(2); }); test("should support mixed registration", () => { neurolink.registerTools({ objectTool: {...} }); neurolink.registerTools([{ name: "arrayTool", tool: {...} }]); expect(neurolink.getCustomTools().size).toBe(2); }); }); ``` ### **Lighthouse Integration Tests** ```typescript describe("Lighthouse Integration", () => { test("should register Lighthouse tools with Zod schemas", () => { const lighthouseTools = [ { name: "analytics", tool: { description: "Analytics tool", parameters: z.object({ merchantId: z.string() }), execute: async ({ merchantId }) => ({ data: merchantId }), }, }, ]; neurolink.registerTools(lighthouseTools); const result = await neurolink.executeTool("analytics", { merchantId: "test", }); expect(result.data).toBe("test"); }); }); ``` ## **Implementation Checklist** - [x] **Design**: Unified method signature with union types - [x] **Detection**: Automatic format detection using `Array.isArray()` - [x] **Compatibility**: Zod schema support verification - [x] **Documentation**: Updated README and guides - [x] **Implementation**: Modify `registerTools()` method in NeuroLink class - [x] **Cleanup**: Remove redundant `registerToolsFromArray()` method (never existed) - [x] **Testing**: Update tests for unified method - [x] **Validation**: End-to-end integration testing ## **Future Extensibility** The unified approach supports future extensions: ```typescript // Future: Additional format support registerTools(tools: | Record // Object format | Array // Array format | MCPServerConfig // Future: MCP server format | PluginManifest // Future: Plugin format ): void ``` This architecture ensures the API can grow with new tool formats while maintaining compatibility. --- ## npm Trusted Publishing Setup # npm Trusted Publishing Setup This repository is configured to use npm's **Trusted Publishing** feature with GitHub Actions OIDC authentication. This provides secure, token-free publishing with automatic provenance generation. ## What is Trusted Publishing? Trusted Publishing allows GitHub Actions to publish packages to npm without using long-lived NPM_TOKEN secrets. Instead, it uses OpenID Connect (OIDC) to create short-lived tokens that are automatically verified by npm. **Benefits:** - ✅ No need to manage NPM_TOKEN secrets - ✅ Automatic package provenance (cryptographic attestation) - ✅ Enhanced security (no long-lived credentials) - ✅ Verifiable supply chain ## Configuration Status ✅ **GitHub Actions workflow** - Configured with OIDC permissions ✅ **semantic-release** - Configured to publish with provenance ⚠️ **npm Trusted Publisher** - Requires manual setup on npm.org (see below) ## GitHub Actions Configuration (✅ Complete) The following changes have been made to `.github/workflows/release.yml`: 1. **Added `id-token: write` permission:** ```yaml permissions: contents: write packages: write issues: write pull-requests: write id-token: write # Required for npm provenance ``` 2. **Configured semantic-release** in `.releaserc.json`: ```json [ "@semantic-release/npm", { "npmPublish": true, "provenance": true } ] ``` ## npm Website Configuration (⚠️ Required) To complete the setup, you must configure the trusted publisher on npm.org: ### Step 1: Access Package Settings 1. Go to [npmjs.com](https://www.npmjs.com/) and sign in 2. Navigate to your package: `@juspay/neurolink` 3. Click on **Settings** tab ### Step 2: Configure Trusted Publisher 1. Scroll to **Publishing Access** section 2. Click **Add Trusted Publisher** 3. Select **GitHub Actions** as the provider 4. Fill in the following details: - **Repository owner:** `juspay` - **Repository name:** `neurolink` - **Workflow name:** `release.yml` - **Environment (optional):** Leave empty unless you use GitHub environments ### Step 3: Save Configuration 1. Click **Add Trusted Publisher** 2. Verify the configuration appears in the list ## Migration Notes ### During Transition Period You can keep the `NPM_TOKEN` secret configured during the transition: - If trusted publishing is configured, npm will use OIDC authentication - If trusted publishing fails, it will fall back to the token - Once verified working, you can remove the `NPM_TOKEN` secret ### Removing NPM_TOKEN (After Verification) Once you've confirmed trusted publishing works: 1. Go to GitHub repository settings 2. Navigate to **Secrets and variables** → **Actions** 3. Delete the `NPM_TOKEN` secret (optional but recommended) **Note:** The `NPM_TOKEN` in the workflow environment variables doesn't need to be removed - it will simply be unused when OIDC is active. ## Verification After configuring trusted publishing and triggering a release: 1. **Check the workflow logs:** - Go to **Actions** tab in GitHub - Open the latest release workflow run - Look for the semantic-release step logs 2. **Verify provenance on npm:** - Visit your package page: `https://www.npmjs.com/package/@juspay/neurolink` - Look for the **Provenance** badge or section - Click to view the attestation details 3. **Expected output:** - Workflow should complete successfully without NPM_TOKEN errors - Package page should show provenance information - Attestation should link back to the GitHub Actions run ## Troubleshooting ### Error: "This request requires id-token permission" **Cause:** Missing `id-token: write` permission in workflow **Solution:** Verify `.github/workflows/release.yml` has: ```yaml permissions: id-token: write ``` ### Error: "npm publish failed - no trusted publisher configured" **Cause:** Trusted publisher not configured on npm.org **Solution:** Follow the npm website configuration steps above ### Provenance not showing on npm **Possible causes:** 1. Trusted publisher not configured on npm.org 2. `provenance: true` not set in semantic-release config 3. Publishing happened before OIDC configuration **Solution:** 1. Verify all configuration steps 2. Trigger a new release to test ## References - [npm Trusted Publishers Documentation](https://docs.npmjs.com/trusted-publishers) - [GitHub Actions OIDC](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect) - [semantic-release npm plugin](https://github.com/semantic-release/npm#options) ## Support For issues with: - **GitHub Actions OIDC:** Contact GitHub Support - **npm Trusted Publishing:** Contact npm Support - **semantic-release:** Check [semantic-release documentation](https://semantic-release.gitbook.io/) --- ## Proxy logging through OpenTelemetry # Proxy logging through OpenTelemetry The default remains file logging plus the existing OTLP request/body export. To use only OTLP for proxy application logs, set these variables in the proxy environment file before starting the service: ```dotenv NEUROLINK_PROXY_LOG_SINK=otel OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:14318 ``` `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` can override the complete logs URL, including `/v1/logs`. Remote collectors require HTTPS; HTTP is limited to loopback. A missing or invalid endpoint fails initialization; it does not silently switch back to disk. Verify the collector and its backend before switching the service. Changing a running supervisor's sink requires replacing the supervisor. A worker-only reload cannot change the old supervisor's sink. In this mode: - Request finals retain their dashboard attributes and complete structured metadata in the log body. `proxy.record_kind=request_final` identifies them. - Attempts, lifecycle/runtime/supervisor events, stream errors and body indexes have distinct record kinds and do not carry final-request success fields. - Redacted body processing remains in the bounded body worker. It skips gzip, artifact writes and the debug index file, and exports redacted chunks directly. - Request admission submits lifecycle evidence asynchronously. Collector latency, queue overflow and outages do not cause telemetry admission HTTP 503s. - Proxy application console diagnostics go to OTel. Updater/guard file descriptors and the file retention scanner are disabled. A launchd installation created in this mode uses `/dev/null` for stdout/stderr. Existing installations need their plist updated as part of the supervised cutover. Ambient OTel sink, endpoint and exporter header settings are retained in a private launchd plist. - Existing historical logs are preserved. Credentials, quota, accounting and supervisor state are operational persistence and continue to be stored. Metadata has a 2,048-record queue; redacted body chunks have an independent 256-record queue. Bodies use chunks capped at 128 KiB. Outstanding counts include exports in flight. Publication owns up to 64 captures / 32 MiB of redacted payloads concurrently. Captures share export batches of at most 64 records, wait for queue capacity, and settle their own chunks from exporter callbacks. Metadata has its own queue and transport. Transport timeouts are 30 seconds, with a 31-second callback guard. Capture publication has a 20-second deadline covering capacity waits and export settlement. A deadline or failed export produces an explicit unconfirmed or partial result; submitted chunks retain ownership until their callbacks settle. These bounds still permit rejected captures during a prolonged outage. They are payload/queue limits, not total process RSS limits: objects, serialization buffers and the capture worker add overhead. OTel-only body capture submission returns without waiting for the collector, even when an HTTP handler awaits the logging function. Shutdown calls `flushRequestLogs()` before flushing/shutting down the OTel provider so already submitted processing and publication keep their ownership until settled. Each `body_capture_index` includes a unique `captureId`, a SHA-256 digest of the captured redacted text, and `bodyDelivery`. Chunks carry the same identity as `body.capture_id`; reconstruct by capture ID and chunk index, then verify the count and digest. The index is emitted after publication settles: - `transport_acknowledged`: all prepared chunks received validated OTLP JSON acknowledgments reporting no rejected records; this does not prove backend persistence or independently verified per-record acceptance. - `reference`: identical redacted bytes for this request already received a transport acknowledgment. `bodyReference` identifies that exported capture, digest, byte count and export time. Reconstruct its chunks and verify the current index's digest and byte count; references never form chains. A reference alone does not prove the source is retained in backend storage. - `export_unconfirmed`: all chunks were submitted, but at least one export was not acknowledged. Some or all may still be stored in the backend. - `partial`: publication stopped after only part of the capture was submitted, or a chunk was dropped. Inspect `expectedChunks`, `acknowledgedChunks`, `unconfirmedChunks`, `droppedChunks` and `notSubmittedChunks` separately. - `rejected`: the publication queue or deadline rejected the capture. No partial body is deliberately enqueued to make room. - `capture_rejected`: the body worker's admission guard rejected processing; the index includes `captureError`. `captureAdmission` identifies the limiting resource (`entry`, `captures`, `bytes`, or `worker`) and the admission-time pending count/bytes and configured limits. `no_body` means no body was present. The worker admits up to 64 pending captures within a 32 MiB aggregate pool. OTel-only mode permits a single entry to use that pool; file mode retains its 16 MiB per-entry estimate. `captureAdmission.maxEntryBytes` reports the active entry limit, including rejected inputs. Its estimate accounts for UTF-16 strings without serializing on the serving thread. Admission reasons distinguish `body_capture_entry_too_large`, `body_capture_unsupported_value`, `body_capture_traversal_limit`, `body_capture_queue_full` and `body_worker_backoff`; `/status` includes counts by reason. A processing `completed` count alone is not evidence of transport delivery. OTel-only redacted text is capped at **8 MiB per capture**; the default file mode keeps its existing **1 MiB** ceiling. Indexes expose `bodyCaptureLimitBytes`, `originalRedactedBodyBytes` and `bodyTruncated`. Larger or structurally excessive inputs remain bounded and explicitly rejected or truncated. This is a logging policy and does not truncate the request sent to the model. Borrowed traffic still excludes body capture and emits a metadata-only `policy_excluded` index with reason `borrowed_traffic`; it does not expose the borrowed body. OTel-only mode deduplicates identical redacted payloads within one request, including concurrent client/upstream phases. Every phase keeps its own capture index, headers, identity and truncation/redaction metadata. Transformed payloads with different digests and payloads from different requests are exported independently. Partial or unconfirmed exports never become reference sources; a waiting duplicate attempts its own export instead. The metadata-only cache holds at most 1,024 references for five minutes and retains no body strings. Set `NEUROLINK_PROXY_BODY_DEDUPLICATION=false` to disable this optimization. File logging/replay retain their existing independent artifacts. `NEUROLINK_PROXY_BODY_BYTES_PER_MINUTE` optionally limits unique redacted body bytes submitted to OTel using a token bucket with a one-minute burst capacity. Unset means no additional byte-rate policy. A positive safe integer enables the budget; invalid configured values explicitly exclude bodies instead of silently disabling the policy. Each omission retains a phase index with `bodyDelivery.status=policy_excluded` and reason `body_byte_budget_exhausted` or `body_byte_budget_invalid`. Metadata and inference payloads are unaffected. The budget counts attempted unique payload bytes even if export later fails; transport retry and protocol overhead are outside this payload budget. `/status` request logging includes `bodyCapturePolicy` counters for submitted, deduplicated and omitted bytes/captures and the current reference/budget bounds. Doctor treats configured omissions as incomplete retained content, resolves references for sampled body verification, and cannot report backend completeness from transport acknowledgments alone. Backend retention remains a separate operator policy; expiring the source also makes its references unreconstructable. `/status.observability.process` reports the worker's actual lifecycle sink, OTel initialization and stdout/stderr descriptor types. The `supervisor` field queries the current supervisor through its authenticated private control socket; missing support in an older supervisor is explicitly unavailable. Doctor checks both processes. A worker-only restart refuses an incomplete supervisor logging cutover; replacing a worker cannot close the supervisor's inherited log files. The selected sink and per-process export counters remain under request logging observability. `submitted` means admitted to the memory queue; `transportAcknowledged` means the response-aware transport validated the OTLP JSON acknowledgment with no reported rejected records. It does not prove individual record acceptance or backend persistence. `exportUnconfirmed` means an export failed or could not be confirmed; it may have reached the collector before a connection failed. `dropped` counts local queue overflow. Reconcile these with collector counters and queries for correlated request IDs in the backend. Do not claim exactly-once or lossless delivery from HTTP success. Native runtime output emitted outside application console methods is discarded by `/dev/null`; the supervisor still records worker exits. The shipped collector uses a disk-backed 4,096-entry sending queue and unbounded retry with a 30-second maximum backoff. Its `file_storage` directory must be on persistent storage. The local OpenObserve stack defaults to 30 days of retention through `NEUROLINK_OPENOBSERVE_RETENTION_DAYS`; size the volume for the actual capture rate. A collector/backend can still lose telemetry after storage exhaustion or corruption; this mode removes proxy log files, not backend storage. The local `proxy analyze`, `proxy replay` and file-based account ledger commands read historical files. They do not query the collector and cannot describe new OTel-only traffic. Use the telemetry backend for that interval. ## Querying historical metadata within a small backend memory budget Configure `NEUROLINK_OPENOBSERVE_URL`, `NEUROLINK_OPENOBSERVE_ORG`, `NEUROLINK_PROXY_STREAM_HEADER` (the actual log stream), and either `NEUROLINK_OPENOBSERVE_BASIC_AUTH` or the user/password environment variables. Keep credentials in the environment rather than command-line arguments. ```sh neurolink proxy telemetry query \ --since 2026-09-13T12:32:00Z --until 2026-09-13T18:52:00Z \ --kind body_capture_index > body-capture-history.json ``` This queries metadata, not bulk body chunks, in ten-minute windows and 200-record pages. Equal-time records have deterministic secondary ordering. Windows returning partial results are discarded and retried in smaller intervals; persistent partial results fail the command. The default 10,000-row bound, configurable with `--max-rows` up to 100,000, and a 512-query budget fail explicitly instead of silently truncating the answer. A successful result describes query completeness for the specified interval, not whether the proxy instrumented or delivered every possible event. Include the returned query ledger when reporting evidence. ## Built-in telemetry verification ```sh neurolink proxy telemetry doctor --format json neurolink proxy telemetry doctor --since 2026-09-15T00:00:00Z --until 2026-09-15T01:00:00Z neurolink proxy telemetry query --since 2026-09-15T00:00:00Z --kind telemetry_delivery ``` OTLP is the standard for exporting logs, traces and metrics; it has no historical query API. These read-only commands query **stored OTLP data through OpenObserve's search API**, and inspect the proxy/collector diagnostics endpoints. They do not start Docker, restart services, generate model traffic or scan application files. The existing script entry points call the same implementation. New OTel-only traffic must be read through these commands or the backend; archived file-based analyze/replay commands retain their offline meaning. Backend settings come from the OpenObserve environment variables above, or from `~/.neurolink/telemetry-native/config/collector.yaml` when an explicit backend URL is absent. Override the config path with `NEUROLINK_OTEL_COLLECTOR_CONFIG`. Credentials stay internal and redirects are rejected. Use `NEUROLINK_OTEL_COLLECTOR_METRICS_URL` to select the loopback collector metrics endpoint; native discovery defaults to `http://127.0.0.1:14388/metrics`. `--proxy-url` or `NEUROLINK_PROXY_URL` selects the proxy diagnostics endpoint. The doctor defaults to the last fifteen minutes ending thirty seconds ago to allow export/ingestion to settle. It verifies: - Runtime readiness and actual worker/supervisor OTel-only logging, including inherited stdout/stderr file descriptors. - Producer delivery diagnostics and capture admission failures for the selected interval. Worker-lifetime counters remain in evidence with an explicit scope, but an older incident does not make every later interval warn. - Stored logs, traces and request metrics with a latest timestamp no more than 120 seconds behind the **selected window end**. Historical windows therefore measure historical freshness, not current service health. - Unique final IDs, trace/duration/outcome fields and explained first-output timing, grouped by model. `not_observed` cannot pass timing coverage. - Stored terminal-event/final reconciliation. In-flight admissions and requests spanning the query boundaries are not assumed to have failed. - Client-response capture phase coverage for Claude and direct Codex finals. Capture queries include a two-minute settling margin; delivery checks retain the requested interval. Missing route evidence cannot pass phase coverage. - Capture rejection/truncation/policy status for every queried index, plus count, contiguous chunk indexes, UTF-8 bytes and SHA-256 for up to three largest acknowledged captures (8 MiB per sample). This is explicitly a sample check. - Up to three stored trace correlations, and collector failure/queue counters. Collector counters are cumulative; a historical failure is not a count of proven missing records in the selected interval. All queries share a 512-request budget; history has a configurable 10,000-record limit per kind (maximum 100,000). Invalid ranges, partial backend results and exceeded bounds fail explicitly. Missing data, idle traffic, absent collector series, old versions without required fields and unavailable measurements cannot produce a green report. `pass` exits zero; `fail` or `incomplete` exits nonzero. A successful report proves these checks over the selected records and samples; it cannot prove an event that disappeared before any observable admission. ## Correlation and output timing The shared HTTP tracker creates a W3C-parented OTel SERVER span for `/v1/*`, `/v1beta/*` and `/backend-api/*`. Health, status and administrative polling are excluded to avoid recursive diagnostic traffic. Route traces inherit that span; finals, attempts, lifecycle and body records retain native OTLP trace/span fields through deferred callbacks. Standalone supervisor events are process evidence and do not invent a request trace. Direct Codex requests now use the same tracing and request metrics path, including selected account and requested reasoning effort. Internal child traces do not increment client request metrics. Codex fallback children own their observed token metrics; the parent owns the client request count and retains attributable usage on its span without counting it again. If a later SDK fallback owns the final outcome, the failed Codex attempt retains its usage and the parent does not inherit that earlier provider's usage. Claude JSON, native streams and translated fallbacks record useful-output availability and its source. Populated content starts and completed zero-argument tool calls count as useful output; thinking and whitespace alone do not. Malformed or oversized frames report `not_observed` with a reason rather than implying an empty result. JSON timing measures when the complete parsed body becomes available. Buffered translations use `translated_response.ready` after the full output is validated; upstream text arrival cannot establish output latency visible to the client. Direct Codex routes capture client request, each upstream request/response, and client response, including HTTP errors. Internal fallbacks retain the parent's client phases. Raw stream observers keep at most 1 MiB each and share a 16 MiB retained-byte pool, releasing it on completion, abort or cancellation. The Claude SSE parser retains a separate bounded 1 MiB prefix outside that pool so upstream and client observations remain distinct across cancellation boundaries. UTF-8 prefixes, original wire byte counts and `bodyTruncated` stay explicit. These limits do not alter client bytes or the model context. SSE data is redacted structurally; malformed structured data is replaced with a redaction marker. Plain text and embedded strings use the shared credential-pattern sanitizer without its short diagnostic-text limit. Codex `firstUsefulOutputStatus` is `observed`, `no_useful_output`, or `not_observed`. Timing recognizes non-whitespace text/refusal, populated function and custom-tool calls, content parts and completion-only output. Empty tool shells, reasoning and control events are not useful output. Malformed, oversized or undispatched frames make an absence claim unavailable. These observations never change the relayed bytes, retry policy or context sent to the model. Each OTel log gets a `proxy.event_id`. Per queue, `/status` retains the latest 16 failed exports/admissions, up to 64 record identities per batch, and a `failureHistoryEvicted` counter. These entries contain event/request/capture IDs and sanitized error metadata, not log bodies. After a successful export, `telemetry_delivery` records report queued diagnostics through the same OTel pipeline. Retryable transport failures use bounded retries with unchanged event identities. After export settles as failed, recovery diagnostics do not replay the original uncertain records. Failure diagnostics are bounded, can themselves be lost, and cannot repair an abrupt process exit. The response-aware transport marks partial rejection and malformed acknowledgments unconfirmed without replaying those batches. A valid acknowledgment still does not prove backend persistence. ## Coverage maintained in CI `pnpm run test:proxy-telemetry` exercises recorded upstreams, local collector fixtures and the built CLI in temporary homes. It is wired into required CI. The matrix below describes supported cases, not a universal lossless guarantee. | Case | Observable evidence | Deterministic verification | | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | Anthropic/Codex completion, client cancel, semantic SSE failure, missing terminal | Final outcome, account, attempt, transport and lifecycle records | HTTP route/stream fault fixtures | | W3C context and Codex text, tool, refusal, control-only output | Native OTLP trace IDs, parent spans, timing status/source | Actual local OTLP receiver and in-memory span exporter | | Malformed frames and incomplete measurement | Explicit `not_observed`, preserved relay bytes | Malformed/oversized Codex fixture | | Upstream auth, quota, cooling and network faults | Classified attempt and terminal outcomes | Recorded transport/account/fallback fixtures | | Admission, stream accounting and worker exit | Lifecycle sequence, terminal evidence or explicit unconfirmed state | Durable journal, worker death and socket fixtures | | OTel-only application logs | Finals, attempts, bodies, lifecycle and console records; no application log directory | Local collector plus filesystem assertions | | Export rejection, delayed acknowledgement and shutdown | Unconfirmed/dropped counters, failed record IDs, recovery diagnostics | Reject/recover and slow collector fixtures | | Large body, redaction, truncation and queue pressure | Capture index, admission reason, delivery counts, digest | 7.3 MB request, burst, redaction and rejection fixtures | | Stored query completeness and duplicates | Query ledger, explicit row/page bounds and nonzero failure | Partial/paged backend fixtures and built CLI | | Missing, stale, corrupt or inconsistent stored data | Doctor fail/incomplete with named check | Recorded backend variants including missing final and collector series | Finite memory, policy exclusions, sampling, collector/backend retention and process death remain explicit limits. OTel-only removes proxy application log files; collectors/backends still need storage. Operational account, credential, quota and supervisor state is not application logging and remains persistent. For rollback, restore the previous service environment and launchd configuration, then replace the supervisor with the previous runtime after draining requests. Removing `NEUROLINK_PROXY_LOG_SINK=otel` restores the default file behavior. ## Bounded critical evidence under collector pressure The proxy maintains four independent in-memory log queues, including records currently exporting. `metadata` reserves 2,048 records / 8 MiB for lifecycle, attempt, final, stream-error and supervisor evidence. `indexes` reserves 1,024 records / 8 MiB for body-capture indexes. `diagnostics` reserves 512 records / 2 MiB for console, runtime and delivery diagnostics. `bodies` reserves 256 chunks / 40 MiB. Byte accounting uses UTF-8 payload and attributes plus per-record overhead; these are admission budgets, not an exact process RSS cap. Status exposes outstanding bytes, high-water bytes, byte-limit drops and oldest outstanding age for each queue. Critical metadata remains owned across transient transport failures for a 120-second budget from admission. An active HTTP attempt can finish within its existing 31-second callback deadline. Retries keep the original event IDs, respect Retry-After and use capped backoff. The doctor deduplicates identical backend retries by event identity. Partial acceptance, malformed acknowledgements and permanent rejection are never replayed. Exhausted retention is explicitly unconfirmed; transport acknowledgement is not proof of backend persistence. Status exposes retrying records, retried batches and retention exhaustion. Shutdown ends waiting retries immediately, allows healthy in-flight exports to finish and cancels remaining HTTP work after four seconds, within the service's five-second telemetry cleanup budget. Interrupted exports remain unconfirmed. No application disk spool is introduced. A crash can still lose process memory; durable collector enqueue, bounded storage, backend reconciliation and capacity monitoring remain necessary. Infinite outages cannot be covered by finite queues. --- ## NeuroLink Review Fixes Documentation # NeuroLink Review Fixes Documentation **Branch:** `feat/models-observability-rag-landing-review-fixes` **Date:** 2026-02-28 **Total Files Changed:** 26 **Total Lines Changed:** +2,876 / -1,524 ## 2. P0 Bug Fixes (Critical) ### P0-1: Double Process Spawn in stdio Transport **Issue:** `MCPClientFactory.createClient()` spawned a child process via `spawn()` and then `StdioClientTransport` spawned a second one internally, resulting in orphaned zombie processes. **Root Cause:** The factory manually called `spawn()` before passing the config to `StdioClientTransport`, which also calls `spawn()` internally. This created two child processes for every stdio MCP server. **Fix Applied:** Removed the manual `spawn()` call from `MCPClientFactory`. Now only `StdioClientTransport` spawns the process. The factory accesses the process reference from the transport instance after connection via `transport.stderr` for logging. **Files Changed:** - `src/lib/mcp/mcpClientFactory.ts` (+449/-449 total with OTel changes) **Verification:** PASS --- ### P0-2: Restart Timer Never Cleared **Issue:** When `ExternalServerManager.scheduleRestart()` fired, the `restartTimer` reference was never cleared (`= undefined`), causing the guard `if (instance.restartTimer) return` to permanently block future restarts. **Root Cause:** The `setTimeout` callback did not reset `instance.restartTimer = undefined` at the start of execution. After the timer fires, the reference remains set to the expired timer ID. **Fix Applied:** Added `instance.restartTimer = undefined;` as the first line inside the `setTimeout` callback in `scheduleRestart()`. **Files Changed:** - `src/lib/mcp/externalServerManager.ts` (line ~491 in diff) **Verification:** PASS --- ### P0-3: Inaccurate Cost Estimation (5x Error) **Issue:** Cost estimation used rough multipliers that could be off by 5x or more for some models. There was no per-model pricing table. **Root Cause:** The `estimateCost()` function used generic provider-level multipliers rather than accurate per-model pricing data. **Fix Applied:** Introduced `calculateCost()` from a new `src/lib/utils/pricing.ts` module with per-model pricing tables. Integrated into both `BaseProvider.generate()` and `GenerationHandler` to record accurate `gen_ai.cost_usd` span attributes. **Files Changed:** - `src/lib/core/baseProvider.ts` (lines ~1095-1112) -- `calculateCost()` integration in generate path - `src/lib/core/modules/GenerationHandler.ts` (lines ~444-473) -- `calculateCost()` integration in GenerationHandler **Key Code:** ```typescript // In baseProvider.ts generate() path: if (enhancedResult?.usage) { span.setAttribute( "gen_ai.cost_usd", calculateCost( this.providerName, this.modelName || options.model || "", enhancedResult.usage, ), ); } ``` **Verification:** PASS --- ### P0-4a: tool.input_size/output_size Reporting Truncated Length **Issue:** Tool input/output size OTel attributes were reporting the length of truncated strings rather than actual full size. **Root Cause:** The `tool.result_size` and `tool.args` attributes were recorded after `.substring(0, 4096)` truncation. **Fix Applied:** In `GenerationHandler.ts`, tool result events now capture `tool.result_size` from the full result string length before truncation, and `tool.args` is truncated separately for the attribute value while preserving full size. **Files Changed:** - `src/lib/core/modules/GenerationHandler.ts` (lines ~205-236 in `onStepFinish`) **Key Code:** ```typescript // Record full size, truncate only the preview const resultStr = typeof tr === "string" ? tr : JSON.stringify(tr ?? ""); activeSpan.addEvent("gen_ai.tool.result", { "tool.index": i, "tool.result_preview": resultStr.substring(0, 4096), "tool.result_size": resultStr.length, // Full size, not truncated }); ``` **Verification:** PASS --- ### P0-4b: SSE/WebSocket Headers Silently Ignored **Issue:** When configuring SSE or WebSocket MCP transports, custom headers (e.g., `Authorization: Bearer ...`) were silently ignored, causing authentication failures. **Root Cause:** The `MCPClientFactory.createHTTPTransport()` and related methods did not forward `config.headers` to the underlying SSE/WebSocket transport constructors. **Fix Applied:** Headers are now properly forwarded from the config to all HTTP-based transport types (SSE, WebSocket, Streamable HTTP) in `mcpClientFactory.ts`. **Files Changed:** - `src/lib/mcp/mcpClientFactory.ts` **Verification:** PASS --- ### P0-4c: validateClientConfig Rejecting Valid HTTP Configs **Issue:** The `validateClientConfig()` function required `command` for all transport types, incorrectly rejecting valid HTTP/SSE/WebSocket configs that only have `url`. **Root Cause:** Validation logic checked for `config.command` without considering that HTTP-based transports use `config.url` instead. **Fix Applied:** Updated `validateClientConfig()` to accept configs with either `command` (for stdio) or `url` (for HTTP/SSE/WebSocket) based on the transport type. **Files Changed:** - `src/lib/mcp/mcpClientFactory.ts` **Verification:** PASS --- ## 3. P1 High Priority Fixes ### P1-1: Typed Errors Missing in Azure/Mistral/HuggingFace **Issue:** Azure, Mistral, and HuggingFace providers returned generic `Error` instances from `formatProviderError()`, making it impossible for callers to distinguish authentication errors from rate limits, network failures, or invalid models. **Root Cause:** These three providers did not use the typed error hierarchy (`AuthenticationError`, `RateLimitError`, `NetworkError`, `InvalidModelError`, `ProviderError`) that OpenAI, Anthropic, and other providers already used. **Fix Applied:** Rewrote `formatProviderError()` in all three providers to return typed errors based on HTTP status codes and error message patterns: - `401`/`403` or auth-related messages -> `AuthenticationError` - `429` or rate limit messages -> `RateLimitError` - `ECONNREFUSED`/`ENOTFOUND`/`ETIMEDOUT` -> `NetworkError` - `TimeoutError` -> `NetworkError` - Model not found -> `InvalidModelError` - All others -> `ProviderError` **Files Changed:** - `src/lib/providers/azureOpenai.ts` (+85/-21) -- Full `formatProviderError()` rewrite - `src/lib/providers/mistral.ts` (+62/-21) -- Full `formatProviderError()` rewrite - `src/lib/providers/huggingFace.ts` (+70/-36) -- Full `formatProviderError()` rewrite, removed emoji prefixes **Key Pattern (Azure example):** ```typescript protected formatProviderError(error: unknown): Error { if (error instanceof TimeoutError) { return new NetworkError(error.message, this.providerName); } // ... status code / message checks ... if (statusCode === 401 || statusCode === 403 || message.includes("401")) { return new AuthenticationError( "Invalid Azure OpenAI API key or endpoint.", this.providerName, ); } // ... rate limit, network, model checks ... return new ProviderError(`Azure OpenAI error: ${message}`, this.providerName); } ``` **Verification:** PASS --- ### P1-2: maxRetries:0 Missing from 5 Providers + ENOTFOUND Non-Retryable **Issue:** Five providers (Azure, Google AI Studio, HuggingFace, Mistral, OpenAI Compatible) did not set `maxRetries: 0` in their `streamText()` calls, allowing the Vercel AI SDK to perform invisible internal retries that bypassed NeuroLink's OTel-instrumented retry logic. Additionally, `ENOTFOUND` (DNS failure) was treated as retryable in the HTTP retry handler. **Root Cause:** When these providers were initially implemented, the `maxRetries: 0` convention (established in NL11) was not applied. The HTTP retry handler included `ENOTFOUND` in its retryable error codes list. **Historical note:** this fix targeted the Vercel AI SDK's `streamText()` retry behaviour. That code path no longer exists — every provider now runs a native loop — so the fix is superseded by the SDK removal, not re-broken by it. The `ENOTFOUND` half still applies. **Fix Applied:** 1. Added `maxRetries: 0` to `streamText()` calls in: Azure, Google AI Studio, HuggingFace, Mistral, OpenAI Compatible. 2. Removed `ENOTFOUND` from `isRetryableHTTPError()` in `httpRetryHandler.ts` since DNS failures are permanent (the hostname does not exist). 3. Updated `isRetryableProviderError()` in `providerRetry.ts` to also exclude ENOTFOUND. **Files Changed:** - `src/lib/providers/azureOpenai.ts` (line ~196) -- Added `maxRetries: 0` - `src/lib/providers/googleAiStudio.ts` (line ~594) -- Added `maxRetries: 0` - `src/lib/providers/huggingFace.ts` (line ~191) -- Added `maxRetries: 0` - `src/lib/providers/mistral.ts` (line ~102) -- Added `maxRetries: 0` - `src/lib/providers/openaiCompatible.ts` (line ~249) -- Added `maxRetries: 0` - `src/lib/mcp/httpRetryHandler.ts` -- Removed `ENOTFOUND` from retryable codes, fixed logger to use `mcpLogger` **Verification:** PASS --- ### P1-3: Stream Timeout Composition + Abort Differentiation **Issue:** The stream path in `BaseProvider.stream()` did not compose timeout and user-provided abort signals the way `generate()` did. Abort errors were treated as failures with ERROR status in OTel spans. **Root Cause:** The `stream()` method was missing the `createTimeoutController()` + `composeAbortSignals()` pattern already present in `generate()`. The catch block did not differentiate between abort errors (expected cancellation) and real errors. **Fix Applied:** 1. Added timeout controller creation and signal composition at the top of `BaseProvider.stream()`, mirroring the `generate()` path. 2. In the catch block, added `isAbortError(error)` check: abort errors get `SpanStatusCode.OK` and info-level logging; real errors continue to get `SpanStatusCode.ERROR`. 3. Added `timeoutController?.cleanup()` in the `finally` block. **Files Changed:** - `src/lib/core/baseProvider.ts` (lines ~184-200 for signal composition, lines ~304-317 for abort differentiation) **Key Code:** ```typescript // Compose timeout signal with user-provided abort signal const timeoutController = createTimeoutController(options.timeout, this.providerName, "stream"); const composedSignal = composeAbortSignals(options.abortSignal, timeoutController?.controller.signal); if (composedSignal) { options = { ...options, abortSignal: composedSignal }; } // In catch block: if (isAbortError(error)) { span.setStatus({ code: SpanStatusCode.OK }); logger.info(`Stream aborted for ${this.providerName}`, { ... }); } else { span.setStatus({ code: SpanStatusCode.ERROR, message: ... }); } ``` **Verification:** PASS --- ### P1-4: OTel Stream/Generate Parity **Issue:** The stream path was missing many OTel span attributes and child spans that the generate path had, creating an observability gap. Specifically: middleware count, generation config (temperature/maxTokens/maxSteps), cache tokens, cost estimates, TTFC (Time-To-First-Chunk), chunk metrics, input preview, generate path indicator, mem0 spans, conversation store spans, budget check spans, compaction spans, provider fallback chain recording. **Root Cause:** Stream support was added after the generate path, and OTel instrumentation was not mirrored. **Fix Applied:** Comprehensive OTel additions across multiple files: **BaseProvider (stream):** - Added `gen_ai.middleware.count` attribute - Added `gen_ai.request.temperature`, `gen_ai.request.max_tokens`, `gen_ai.request.max_steps` attributes - Added `gen_ai.cache.input_tokens` and `gen_ai.cache.read_input_tokens` - Added `gen_ai.cost_usd` via `calculateCost()` - Added `wrapStreamWithMetrics()` -- wraps the async generator with a child span (`neurolink.provider.stream.consumption`) that records TTFC, chunk count, total content size, and stream duration - Added `gen_ai.stream.error_recovery` events for fallback scenarios **GenerationHandler:** - Added `gen_ai.message.total_chars`, `gen_ai.messages_preview` with system/user message previews - Added `gen_ai.tool.call` and `gen_ai.tool.result` events in `onStepFinish` - Added cache token attributes and cost calculation in both primary and fallback paths **neurolink.ts:** - Added `gen_ai.input_preview` on generate span - Wrapped mem0 search/store in `neurolink.mem0.search` / `neurolink.mem0.store` spans - Wrapped conversation store in `neurolink.conversation.store` spans (both MCP and direct paths) - Wrapped conversation fetch in `neurolink.conversation.fetch` span - Wrapped budget check in `neurolink.context.budget_check` span with per-component token breakdown (M16) - Wrapped context compaction in `neurolink.context.compact` span - Added `neurolink.generate.path` attribute (`"mcp"` or `"direct"`) - Added provider selection chain: `gen_ai.provider.candidates`, `gen_ai.provider.selected`, `gen_ai.provider.fallback_count`, `gen_ai.provider.fallback` events (H27) **ConversationMemoryManager:** - Added `neurolink.memory.initialize`, `neurolink.memory.storeTurn`, `neurolink.memory.checkAndSummarize`, `neurolink.memory.buildContext`, `neurolink.memory.getSession` spans with full attributes - Removed unused `estimateTokens()` private method **providerRetry:** - Wrapped retry loop in `neurolink.provider.retry` child span (C15) - Added `retry.reason` classification: `rate_limit`, `timeout`, `server_error`, `connection_refused`, `connection_reset`, `unknown` (M17) - Added per-attempt events, backoff tracking, and error recording **MCP modules:** - `externalServerManager.ts`: Added `neurolink.mcp.server.start`, `neurolink.mcp.server.stop`, `neurolink.mcp.server.restart`, `neurolink.mcp.server.healthCheck` spans - `mcpClientFactory.ts`: Wrapped `createClient` in `neurolink.mcp.createClient` span with protocol version, transport type, duration attributes - `mcpCircuitBreaker.ts`: Added `circuit.state_change` and `circuit.half_open_test` OTel events - `toolDiscoveryService.ts`: Added OTel spans for tool discovery operations **Files Changed:** - `src/lib/core/baseProvider.ts` (+178 lines) - `src/lib/core/modules/GenerationHandler.ts` (+130 lines) - `src/lib/neurolink.ts` (+1029/-529 lines) - `src/lib/core/conversationMemoryManager.ts` (+369 lines) - `src/lib/utils/providerRetry.ts` (+214 lines) - `src/lib/mcp/externalServerManager.ts` (+574 lines) - `src/lib/mcp/mcpClientFactory.ts` (+449 lines) - `src/lib/mcp/mcpCircuitBreaker.ts` (+27 lines) - `src/lib/mcp/toolDiscoveryService.ts` (+367 lines) **Verification:** PASS --- ### P1-5: Circuit Breaker Timer Leak + Signal Handler Leak + Debug Artifact **Issue:** Three separate resource leaks / cleanup issues: 1. Circuit breaker cleanup timers were never destroyed during shutdown, leaking `setInterval` timers. 2. Process signal handlers (`SIGINT`, `SIGTERM`, `beforeExit`) were registered as anonymous arrow functions, making them impossible to remove during shutdown. 3. A hardcoded debug filter for `"SuccessRateSRByTime"` / `"juspay-analytics"` tool was left in the `generateTextInternal()` method's logging. **Root Cause:** 1. `globalCircuitBreakerManager.destroyAll()` was never called in `ExternalServerManager.shutdown()`. 2. Anonymous arrow functions passed to `process.on()` cannot be referenced for `process.removeListener()`. 3. Debug artifact from development was not removed before merge. **Fix Applied:** 1. Added `globalCircuitBreakerManager.destroyAll()` call in `ExternalServerManager.shutdown()`. 2. Stored the shutdown handler as a named instance field (`private shutdownHandler = () => { void this.shutdown(); }`), used it for `process.on()` registration, and added matching `process.removeListener()` calls in `shutdown()`. 3. Removed the hardcoded `targetTool` debug filter block from `neurolink.ts`. **Files Changed:** - `src/lib/mcp/externalServerManager.ts`: - Lines ~224-226: Added `shutdownHandler` field - Lines ~262-264: Use `this.shutdownHandler` for signal registration - Lines ~1595-1603: Added `process.removeListener()` calls and `globalCircuitBreakerManager.destroyAll()` - `src/lib/neurolink.ts` (lines ~3752-3765 removed debug artifact) **Verification:** PASS --- ## 4. P2 Medium Priority Fixes ### P2-1: Extract resolveTools() to BaseProvider (Eliminate 14 Copies) **Issue:** Every provider had a duplicated 3-4 line pattern for tool resolution: ```typescript const shouldUseTools = !options.disableTools && this.supportsTools(); const tools = shouldUseTools ? (options.tools as Record) || (await this.getAllTools()) : {}; ``` **Root Cause:** When providers were developed independently, each copied the same tool resolution logic. No shared method existed in `BaseProvider`. **Fix Applied:** Added a `protected resolveTools()` method to `BaseProvider` and replaced the duplicated blocks in all 11 providers that had them. **New Method in BaseProvider:** ```typescript protected async resolveTools( options: StreamOptions | TextGenerationOptions, ): Promise> { const shouldUseTools = !options.disableTools && this.supportsTools(); return shouldUseTools ? (options.tools as Record) || (await this.getAllTools()) : {}; } ``` **Providers Updated (14 occurrences across 11 files):** 1. `src/lib/providers/anthropic.ts` -- Replaced 3-line block with `this.resolveTools(options)` 2. `src/lib/providers/anthropicBaseProvider.ts` -- Same 3. `src/lib/providers/azureOpenai.ts` -- Same 4. `src/lib/providers/googleAiStudio.ts` -- Same (was 4 lines with separate `baseTools` variable) 5. `src/lib/providers/googleVertex.ts` -- Same (was 4 lines) 6. `src/lib/providers/huggingFace.ts` -- Same 7. `src/lib/providers/litellm.ts` -- Same 8. `src/lib/providers/mistral.ts` -- Same 9. `src/lib/providers/openAI.ts` -- Same 10. `src/lib/providers/openRouter.ts` -- Same 11. `src/lib/providers/openaiCompatible.ts` -- Same **Secondary Change:** All providers also updated their `toolChoice` logic from `shouldUseTools ? "auto" : "none"` to `Object.keys(tools).length > 0 ? "auto" : "none"`, which is more correct (checks actual tool availability rather than just the configuration flag). **Files Changed:** - `src/lib/core/baseProvider.ts` (lines ~625-637) -- New `resolveTools()` method - All 11 provider files listed above **Verification:** PASS --- ### P2-2: Misc Cleanups (Tracer Name, Dead Code, Unsafe Casts, Debug Artifacts) **Issue:** Several small code quality issues across the codebase: 1. Logger mismatch in `httpRetryHandler.ts`: Used `logger` (general) instead of `mcpLogger` (MCP-specific). 2. Removed unused `Tool` type import from 6 provider files (cleaned up after `resolveTools()` extraction). 3. Removed unused `TransportWithProcessResult` type import from `mcpClientFactory.ts`. 4. Removed unused `estimateTokens()` private method from `ConversationMemoryManager`. 5. Added unbounded queue protection in `HTTPRateLimiter` (MAX_QUEUE_SIZE = 1000). 6. Updated `httpRetryHandler.ts` documentation to remove `ENOTFOUND` from the retryable list in the JSDoc comment. **Files Changed:** - `src/lib/mcp/httpRetryHandler.ts` -- Switched `logger` to `mcpLogger` (3 occurrences), updated JSDoc - `src/lib/mcp/httpRateLimiter.ts` -- Added queue size limit - `src/lib/mcp/mcpClientFactory.ts` -- Removed unused `spawn` and `TransportWithProcessResult` imports, added `LATEST_PROTOCOL_VERSION` import - `src/lib/providers/anthropic.ts`, `anthropicBaseProvider.ts`, `azureOpenai.ts`, `huggingFace.ts`, `litellm.ts`, `mistral.ts`, `openAI.ts`, `openRouter.ts`, `openaiCompatible.ts` -- Removed unused `type Tool` import - `src/lib/core/conversationMemoryManager.ts` -- Removed unused `estimateTokens()` method - `src/lib/core/modules/TelemetryHandler.ts` -- Minor fix (2 lines) **Verification:** PASS --- ## 5. Impact Analysis Matrix ### Provider Impact | Provider | P1-1 Typed Errors | P1-2 maxRetries:0 | P2-1 resolveTools | Other | | ----------------- | ----------------- | ----------------- | ----------------- | --------------------- | | OpenAI | -- | Already had | Yes | Unused import cleanup | | Anthropic | Already had | Already had | Yes | Unused import cleanup | | AnthropicV2 | Already had | Already had | Yes | Unused import cleanup | | Azure OpenAI | **Added** | **Added** | Yes | -- | | Google AI Studio | -- | **Added** | Yes | -- | | Google Vertex | -- | Already had | Yes | -- | | Mistral | **Added** | **Added** | Yes | Unused import cleanup | | HuggingFace | **Added** | **Added** | Yes | Unused import cleanup | | LiteLLM | -- | Already had | Yes | Unused import cleanup | | OpenRouter | -- | Already had | Yes | Unused import cleanup | | OpenAI Compatible | -- | **Added** | Yes | Unused import cleanup | | Ollama | -- | N/A (local) | -- | -- | ### SDK Path Impact | Fix | generate() | stream() | Both | | ------------------------ | ---------- | ---------------- | -------------------------- | | P0-3 Cost Estimation | Yes | -- | -- | | P1-3 Timeout Composition | -- | Yes | -- | | P1-4 OTel Parity | -- | Yes | Converged | | P2-1 resolveTools | -- | Yes | -- | | P1-1 Typed Errors | -- | -- | Both (formatProviderError) | | P1-2 maxRetries:0 | -- | Yes (streamText) | -- | ### MCP Module Impact | Fix | externalServerManager | mcpClientFactory | mcpCircuitBreaker | toolDiscoveryService | httpRetryHandler | httpRateLimiter | | ------------------ | --------------------- | ---------------- | -------------------- | -------------------- | ---------------- | --------------- | | P0-1 Double Spawn | -- | Yes | -- | -- | -- | -- | | P0-2 Restart Timer | Yes | -- | -- | -- | -- | -- | | P0-4b Headers | -- | Yes | -- | -- | -- | -- | | P0-4c Validation | -- | Yes | -- | -- | -- | -- | | P1-2 ENOTFOUND | -- | -- | -- | -- | Yes | -- | | P1-4 OTel | Yes | Yes | Yes | Yes | -- | -- | | P1-5 Leaks | Yes | -- | Yes (via destroyAll) | -- | -- | -- | | P2-2 Cleanups | -- | Yes | -- | -- | Yes | Yes | --- ## 6. Verification Results Summary | Task ID | Description | Status | | ------- | ---------------------------------------------------------------------- | ------ | | #2 | FIX-P0-1: Double process spawn in stdio transport | PASS | | #3 | FIX-P0-2: Restart timer never cleared | PASS | | #4 | FIX-P0-3: Accurate cost estimation via pricing.ts | PASS | | #5 | FIX-P0-4: Tool I/O size, SSE/WS headers, validateClientConfig | PASS | | #6 | FIX-P1-1: Typed errors in Azure/Mistral/HuggingFace | PASS | | #7 | FIX-P1-2: maxRetries:0 in 5 providers + ENOTFOUND | PASS | | #8 | FIX-P1-3: Stream timeout composition + abort differentiation | PASS | | #9 | FIX-P1-4: OTel stream/generate parity | PASS | | #10 | FIX-P1-5: Circuit breaker timer + signal handler leak + debug artifact | PASS | | #11 | FIX-P2-1: resolveTools() extraction | PASS | | #12 | FIX-P2-2: Misc cleanups | PASS | **All 11 implementation tasks verified PASS by independent verification agents.** --- ## 7. Remaining Gaps / Future Work ### Out-of-Scope Items Identified During Review 1. **Evaluation/Scoring module has 0 test coverage** -- 11 source files (1,822 lines) with no tests. This is a known gap tracked separately. 2. **Stream path cost estimation** -- While `generate()` now has accurate cost via `calculateCost()`, the stream path records cost only on `BaseProvider.generate()` spans. Stream consumption spans do not yet include cost because final token counts are only available after stream completion. A future improvement could add cost calculation to the `wrapStreamWithMetrics()` completion handler. 3. **Redis ConversationMemoryManager OTel parity** -- OTel spans were added to the in-memory `ConversationMemoryManager`, but the Redis implementation should also be checked for equivalent instrumentation. 4. **Provider-specific retry configuration** -- Currently all providers share the same `MAX_PROVIDER_RETRIES = 2` constant. Some providers (e.g., rate-limited free-tier APIs) might benefit from configurable retry counts. 5. **Ollama provider** -- Was not touched by any fixes. Does not have `resolveTools()` because Ollama has a different streaming architecture. Should be reviewed separately. ### Test Coverage Gaps - No unit tests specifically for `resolveTools()` method behavior. - No unit tests for the new `wrapStreamWithMetrics()` stream instrumentation wrapper. - No unit tests for abort error differentiation in the stream catch block. - The OTel span assertions in existing tests may not cover all new span attributes. --- ## 8. Files Changed Summary | File | Lines Added | Lines Removed | Net | | -------------------------------------------- | ----------- | ------------- | ---------- | | `src/lib/neurolink.ts` | +1029 | -529 | +500 | | `src/lib/mcp/externalServerManager.ts` | +574 | -392 | +182 | | `src/lib/core/modules/MessageBuilder.ts` | +501 | -340 | +161 | | `src/lib/mcp/mcpClientFactory.ts` | +449 | -300 | +149 | | `src/lib/core/conversationMemoryManager.ts` | +369 | -180 | +189 | | `src/lib/mcp/toolDiscoveryService.ts` | +367 | -220 | +147 | | `src/lib/utils/providerRetry.ts` | +214 | -86 | +128 | | `src/lib/core/baseProvider.ts` | +178 | -18 | +160 | | `src/lib/core/modules/GenerationHandler.ts` | +130 | -10 | +120 | | `src/lib/providers/azureOpenai.ts` | +85 | -21 | +64 | | `src/lib/core/modules/StreamHandler.ts` | +72 | -36 | +36 | | `src/lib/providers/huggingFace.ts` | +70 | -36 | +34 | | `src/lib/core/modules/ToolsManager.ts` | +168 | -50 | +118 | | `src/lib/providers/mistral.ts` | +62 | -21 | +41 | | `src/lib/mcp/mcpCircuitBreaker.ts` | +27 | -0 | +27 | | `src/lib/providers/googleVertex.ts` | +15 | -16 | -1 | | `src/lib/providers/openAI.ts` | +14 | -14 | 0 | | `src/lib/mcp/httpRetryHandler.ts` | +11 | -7 | +4 | | `src/lib/providers/openRouter.ts` | +11 | -13 | -2 | | `src/lib/providers/litellm.ts` | +11 | -13 | -2 | | `src/lib/providers/openaiCompatible.ts` | +10 | -10 | 0 | | `src/lib/providers/anthropic.ts` | +9 | -9 | 0 | | `src/lib/providers/anthropicBaseProvider.ts` | +9 | -9 | 0 | | `src/lib/providers/googleAiStudio.ts` | +9 | -11 | -2 | | `src/lib/mcp/httpRateLimiter.ts` | +4 | -0 | +4 | | `src/lib/core/modules/TelemetryHandler.ts` | +2 | -2 | 0 | | **Total** | **+2,876** | **-1,524** | **+1,352** | --- ## Step-by-Step Integration Tutorials # Step-by-Step Integration Tutorials ## Quick Start (15 minutes) {#quick-start-15-minutes} ### Step 1: Installation ```bash npm install @juspay/neurolink echo 'GOOGLE_AI_API_KEY="your-key"' > .env npx @juspay/neurolink generate "Hello world" ``` ### Step 2: Enable Analytics ```javascript const { NeuroLink } = require("@juspay/neurolink"); const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Write a professional email" }, enableAnalytics: true, }); console.log(" Analytics:", result.analytics); ``` ### Step 3: Add Quality Evaluation ```javascript const result = await neurolink.generate({ input: { text: "Explain quantum computing" }, enableEvaluation: true, }); console.log("⭐ Quality:", result.evaluation); // Shows: { relevanceScore: 9, accuracyScore: 8, completenessScore: 9, overallScore: 8.7 } ``` ## Video Generation (Veo 3.1) Generate videos from images using Google's Veo 3.1 model via Vertex AI. ### Prerequisites ```bash # Set up Vertex AI credentials export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json" export GOOGLE_VERTEX_PROJECT="your-project-id" export GOOGLE_VERTEX_LOCATION="us-central1" ``` ### SDK Video Generation ```javascript const neurolink = new NeuroLink(); // Generate video from image + text prompt // Note: Image must be PNG, JPEG, or WebP format (max 20MB) const result = await neurolink.generate({ input: { text: "Smooth camera pan with cinematic lighting", images: [await readFile("./product-image.jpg")], }, provider: "vertex", // Optional: auto-switches to vertex when output.mode is "video" model: "veo-3.1", output: { mode: "video", video: { resolution: "1080p", // or "720p" length: 8, // 4, 6, or 8 seconds aspectRatio: "16:9", // or "9:16" for portrait audio: true, // synchronized audio }, }, }); // Save generated video if (result.video) { await writeFile("output.mp4", result.video.data); console.log(`Duration: ${result.video.metadata?.duration}s`); } ``` **Image Requirements:** - **Formats:** PNG, JPEG, or WebP only - **Size limit:** 20MB maximum - **Aspect ratio:** Should be compatible with target video aspect ratio (16:9 or 9:16) ### CLI Video Generation ```bash # Basic video generation npx @juspay/neurolink generate "Product showcase video" \ --image ./product.jpg \ --outputMode video \ --videoOutput ./output.mp4 # Full options (--provider vertex is optional, auto-selected for video mode) npx @juspay/neurolink generate "Cinematic camera movement" \ --image ./input.jpg \ --provider vertex \ --model veo-3.1 \ --outputMode video \ --videoResolution 1080p \ --videoLength 8 \ --videoAspectRatio 16:9 \ --videoOutput ./output.mp4 ``` **Note:** The `--provider vertex` flag is optional for video generation—NeuroLink automatically switches to Vertex AI when `--outputMode video` is specified. For complete documentation, see the [Video Generation Guide](/docs/features/video-generation). ## PPT Generation Tutorial Generate professional PowerPoint presentations using the CLI: ```bash # Basic presentation generation npx @juspay/neurolink generate "Create a 10-slide presentation about AI in healthcare" \ --outputMode ppt \ --pptOutput ./healthcare-ai.pptx # Full options with custom theme and AI images npx @juspay/neurolink generate "Create a sales deck for our SaaS product" \ --provider vertex \ --model gemini-2.5-pro \ --outputMode ppt \ --pptTheme corporate \ --pptPages 12 \ --pptOutput ./sales-deck.pptx ``` **SDK Usage:** ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Create a product launch presentation" }, output: { mode: "ppt", ppt: { theme: "modern", pages: 10, generateAIImages: true, outputPath: "./launch-deck.pptx", }, }, }); console.log(`Generated ${result.ppt?.totalSlides} slides`); ``` For complete documentation, see the [PPT Generation Guide](/docs/features/ppt-generation). ## Web App Integration ### Express.js API ```javascript const express = require("express"); const { NeuroLink } = require("@juspay/neurolink"); const app = express(); app.use(express.json()); const neurolink = new NeuroLink(); app.post("/api/generate", async (req, res) => { const result = await neurolink.generate({ input: { text: req.body.prompt }, enableAnalytics: true, enableEvaluation: true, context: { department: req.body.department, user_id: req.headers["user-id"], }, }); // Quality gate if (result.evaluation.overallScore c.cost = qualityTarget) .sort((a, b) => b.quality - a.quality)[0]; } } ``` ## Batch Processing ```javascript const fs = require("fs"); const csv = require("csv-parser"); const { NeuroLink } = require("@juspay/neurolink"); const neurolink = new NeuroLink(); class BatchProcessor { async processCSV(inputFile) { const items = []; await new Promise((resolve) => { fs.createReadStream(inputFile) .pipe(csv()) .on("data", (row) => items.push(row)) .on("end", resolve); }); for (const item of items) { const result = await neurolink.generate({ input: { text: `Create marketing copy for: ${item.name}` }, enableAnalytics: true, enableEvaluation: true, context: { product_id: item.id, batch: true }, }); console.log( `Processed ${item.name}: Quality ${result.evaluation.overallScore}/10`, ); } } } ``` ## Real-Time Monitoring ### Analytics Dashboard ```javascript // Store analytics in memory (use database in production) const analyticsStore = { requests: [], stats: {} }; app.post("/api/generate", async (req, res) => { const result = await neurolink.generate({ input: { text: req.body.prompt }, ...req.body, enableAnalytics: true, enableEvaluation: true, }); // Store analytics analyticsStore.requests.push({ timestamp: new Date(), ...result.analytics, quality: result.evaluation, }); res.json(result); }); // Dashboard endpoint app.get("/api/dashboard", (req, res) => { const last24h = analyticsStore.requests.filter( (r) => r.timestamp > new Date(Date.now() - 24 * 60 * 60 * 1000), ); res.json({ totalRequests: last24h.length, totalCost: last24h.reduce((sum, r) => sum + (r.cost || 0), 0), avgQuality: last24h.reduce((sum, r) => sum + r.quality.overallScore, 0) / last24h.length, }); }); ``` ## CLI Usage Patterns ### Basic Generation with Analytics ```bash npx @juspay/neurolink generate "Create product description" \ --enable-analytics --debug ``` ### Quality Control ```bash npx @juspay/neurolink generate "Medical advice content" \ --enable-evaluation --debug ``` ### Full Features ```bash npx @juspay/neurolink generate "Business proposal" \ --enable-analytics --enable-evaluation \ --context '{"dept":"sales","priority":"high"}' \ --debug ``` ## Industry Examples ### E-commerce: Product Descriptions ```javascript const productResult = await neurolink.generate({ input: { text: `Product: ${product.name}\nFeatures: ${product.features}` }, enableAnalytics: true, enableEvaluation: true, context: { category: product.category, price_tier: product.priceTier, }, }); // Cost optimization by category if (product.category === "basic" && productResult.analytics?.cost > 0.05) { // Switch to cheaper model for basic products } ``` ### Healthcare: Patient Education ```javascript const medicalContent = await neurolink.generate({ input: { text: "Diabetes management guide for patients" }, enableEvaluation: true, context: { content_type: "medical", accuracy_required: 95, }, }); // Strict medical accuracy requirements if (medicalContent.evaluation.accuracyScore User: ${prompt}`); const result = await neurolink.generate({ input: { text: prompt }, }); console.log(`> Agent: ${result.content}`); } } haveConversation(); ``` ### Expected Output The agent will correctly recall the information provided in earlier prompts, demonstrating its stateful nature. ``` > User: My name is Alex. > Agent: It's nice to meet you, Alex. > User: I live in San Francisco. > Agent: San Francisco is a beautiful city. > User: What is my name and where do I live? > Agent: Your name is Alex and you live in San Francisco. ``` ## Implementation Checklist ### ✅ Basic Setup - [ ] Install NeuroLink SDK - [ ] Configure API keys in .env - [ ] Test basic generation - [ ] Enable analytics tracking - [ ] Add evaluation scoring ### ✅ Production Setup - [ ] Implement quality gates - [ ] Set up cost monitoring - [ ] Create analytics dashboard - [ ] Configure department tracking - [ ] Set up batch processing ### ✅ Optimization - [ ] Model selection strategy - [ ] Cost optimization rules - [ ] Quality improvement process - [ ] Performance monitoring - [ ] ROI measurement ## Next Steps 1. **Start Simple**: Basic analytics and evaluation 2. **Add Quality Gates**: Implement quality thresholds 3. **Monitor Costs**: Track spending by department/usage 4. **Optimize**: Use data to improve cost and quality 5. **Scale**: Implement across organization Each tutorial builds on the previous ones - start with the Quick Start and progress based on your needs. --- ## Use Cases This page has moved to [Real-World Use Cases](/docs/guides/examples/use-cases). --- ## Visual Demonstrations # Visual Demonstrations Experience NeuroLink's capabilities through comprehensive visual documentation. **No installation required!** ## Web Demo Interface ### Interactive Screenshots | Feature | Screenshot | Description | | -------------------------- | --------------------------------------------- | ------------------------------------------------------------ | | **Main Interface** | _[Screenshots available in demo application]_ | Complete web interface showing all features and capabilities | | **AI Generation Results** | _[Screenshots available in demo application]_ | Real AI content generation with OpenAI GPT-4o | | **Business Use Cases** | _[Screenshots available in demo application]_ | Professional business applications and workflows | | **Creative Tools** | _[Screenshots available in demo application]_ | Creative content generation and storytelling | | **Developer Tools** | _[Screenshots available in demo application]_ | Code generation, API documentation, debugging help | | **Analytics & Monitoring** | _[Screenshots available in demo application]_ | Real-time provider analytics and performance metrics | ### Complete Demo Videos **5,681+ tokens of real AI generation captured!** #### **Basic Examples** - _[Demo videos available in live application]_ - Text generation fundamentals - Haiku creation with Claude 3.7 Sonnet - Creative storytelling with OpenAI GPT-4o - **Content Generated**: 529 tokens (robot painting story) #### **Business Use Cases** - _[Demo videos available in live application]_ - Professional email generation - Business analysis and reporting - Executive summaries and insights - **Content Generated**: 1,677 tokens (email + analysis + summaries) #### **Creative Tools** - _[Demo videos available in live application]_ - Story writing and narrative creation - Language translation capabilities - Creative brainstorming and ideation - **Content Generated**: 1,174 tokens (stories + translation + ideas) #### **Developer Tools** - _[Demo videos available in live application]_ - React component generation - API documentation creation - Code debugging and optimization - **Content Generated**: 2,301 tokens (React code + API docs + debugging) #### **Monitoring & Analytics** - _[Demo videos available in live application]_ - Live provider status monitoring - Performance metrics tracking - Usage analytics and insights - **Real-time Demonstrations**: Provider connectivity and response times ### Live Interactive Demo **Express.js Server with Real API Integration** - **All 3 providers functional**: OpenAI, Amazon Bedrock, Google Vertex AI - **15+ use cases demonstrated**: Business, creative, and developer scenarios - **Real-time provider analytics**: Performance metrics and status monitoring - **Working endpoints**: `/api/generate`, `/api/stream`, `/api/status`, `/api/benchmark` **Access**: Run the demo server from the `neurolink-demo/` directory ```bash cd neurolink-demo npm install npm start # Open http://localhost:9876 ``` **Note**: If port 9876 is already in use, the server will automatically find the next available port. Check the terminal output for the actual port number. ## ️ CLI Demonstrations ### Professional CLI Screenshots _(Latest: June 10, 2025)_ | Command | Screenshot | Description | | --------------------------- | --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | **CLI Help Overview** | [Image: CLI Help] | Complete command reference and usage examples | | **Provider Status Check** | [Image: Provider Status] | All provider connectivity verification with response times | | **Text Generation** | [Image: Text Generation] | Real AI haiku generation with JSON output and usage metrics | | **Auto Provider Selection** | [Image: Best Provider] | Automatic provider selection algorithm demonstration | | **Batch Processing** | [Image: Batch Results] | Multi-prompt processing with progress tracking and results | ### CLI Demonstration Videos **Real command execution with live AI generation** #### **CLI Help Overview** - [ MP4](pathname:///docs/visual-content/cli-videos/cli-01-cli-help.mp4) - Complete help system demonstration - Command reference and usage examples - Provider configuration overview - **Size**: 44KB - Professional MP4 with comprehensive command overview #### **Provider Status** - [ MP4](pathname:///docs/visual-content/cli-videos/cli-02-provider-status.mp4) - All provider connectivity verification (now with authentication and model availability checks) - Response time measurements - Authentication status checking - **Size**: 496KB - Professional MP4 showing provider connectivity #### **Text Generation** - [ MP4](pathname:///docs/visual-content/cli-videos/cli-03-text-generation.mp4) - Text generation with different providers - Temperature and token control demonstrations - JSON vs text output formats - **Size**: 100KB - Professional MP4 with real AI generation #### **Auto Provider Selection** - [ MP4](pathname:///docs/visual-content/cli-videos/cli-04-auto-selection.mp4) - Automatic provider selection algorithm - Fallback mechanism demonstration - Performance-based selection - **Size**: Professional MP4 showing selection logic #### **Streaming Generation** - [ MP4](pathname:///docs/visual-content/cli-videos/cli-05-streaming.mp4) - Live AI content streaming demonstration - Real-time text generation as it happens - Provider performance comparison - **Size**: Professional MP4 with live streaming #### **Advanced Features** - [ MP4](pathname:///docs/visual-content/cli-videos/cli-06-advanced-features.mp4) - Verbose diagnostics and debugging - Provider-specific command options - Advanced configuration and customization - **Size**: Professional MP4 with comprehensive advanced features ### CLI Recording Infrastructure **Professional asciinema recordings available:** ```bash # View locally (requires asciinema) asciinema play docs/cli-recordings/latest/01-cli-help.cast asciinema play docs/cli-recordings/latest/02-provider-status.cast asciinema play docs/cli-recordings/latest/03-text-generation.cast asciinema play docs/cli-recordings/latest/04-auto-selection.cast asciinema play docs/cli-recordings/latest/05-streaming.cast asciinema play docs/cli-recordings/latest/06-advanced-features.cast ``` **Features:** - **Web Embeddable**: Upload to asciinema.org with `[![asciicast]` tags - **GIF Convertible**: Use `agg` tool for animated GIF creation - **Professional Quality**: Suitable for documentation, tutorials, marketing - **Real Command Execution**: Actual CLI commands with live AI generation ## MCP (Model Context Protocol) Demonstrations ### MCP CLI Screenshots **Generated January 10, 2025** - Showcasing external server integration capabilities | Command | Screenshot | Description | | ------------------------ | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------- | | **MCP Help Overview** | [Image: MCP Help] | Complete MCP command reference and server management | | **Server Installation** | [Image: Install Server] | Installing external MCP servers (filesystem, github, etc.) | | **Server Status Check** | [Image: Server Status] | MCP server connectivity and status verification | | **Server Testing** | [Image: Test Server] | Testing MCP server connectivity and tool discovery | | **Custom Server Setup** | [Image: Custom Server] | Adding custom MCP server configurations | | **Workflow Integration** | [Image: Workflow Demo] | Complete MCP workflow demonstrations | ### MCP Demo Videos **Real external server integration demonstrations** #### **Server Management** - [ MP4](pathname:///docs/videos/mcp-server-management-demo.mp4) - Installing and configuring MCP servers - Server lifecycle management - Status monitoring and health checks - **Duration**: ~45 seconds of real server management **Note**: Additional MCP demo videos are in development. The server management demo showcases the core MCP integration capabilities. ### MCP CLI Commands Demonstrated ```bash # Server Management neurolink mcp install filesystem neurolink mcp list --status neurolink mcp test filesystem neurolink mcp add custom-python "python /path/to/server.py" neurolink mcp remove server-name # Tool Execution (framework ready) neurolink mcp exec filesystem read-file --path "/path/to/file" neurolink generate "Read README and summarize" --tools filesystem ``` ### MCP Integration Benefits - ✅ **External Server Connectivity**: Connect to filesystem, github, database, and custom servers - ✅ **Tool Discovery**: Automatic discovery of available tools from MCP servers - ✅ **Workflow Integration**: Combine AI generation with external tool execution - ✅ **Extensible Architecture**: Add new capabilities through external servers - ✅ **Standard Protocol**: Compatible with existing MCP server ecosystem ## Visual Content Benefits ### **No Installation Required** See everything in action before installing: - Complete feature demonstrations - Real AI content generation - Provider connectivity validation - Performance metrics and analytics ### **Production Validation** All visual content shows real functionality: - ✅ **Actual AI Generation**: 5,681+ tokens of real content - ✅ **Working Providers**: OpenAI, Bedrock, Vertex AI all functional - ✅ **Real Performance**: Actual response times and metrics - ✅ **Live Demonstrations**: No simulated or mocked content ### **Professional Quality** Suitable for all documentation uses: - **1920x1080 Resolution**: High-definition screenshots and videos - **Professional Styling**: Clean, consistent visual presentation - **Comprehensive Coverage**: Every major feature documented - **Easy Integration**: Ready for embedding in documentation ### **Multiple Formats** Choose the best format for your needs: - **Screenshots**: Quick visual reference and feature overview - **Videos**: Dynamic demonstrations with real interactions - **Asciinema Recordings**: Playable CLI demonstrations - **Live Demo**: Interactive testing environment ## Content Organization ``` neurolink/ ├── neurolink-demo/ # Web interface demonstrations │ ├── screenshots/ # 6 professional web screenshots │ │ ├── 01-overview/ # Main interface overview │ │ ├── 02-basic-examples/ # AI generation results │ │ ├── 03-business-use-cases/ # Business applications │ │ ├── 04-creative-tools/ # Creative content generation │ │ ├── 05-developer-tools/ # Code generation and docs │ │ └── 06-monitoring/ # Analytics and monitoring │ └── videos/ # Complete demo videos (WebM + MP4) │ ├── basic-examples.webm/.mp4 # Text generation fundamentals │ ├── business-use-cases.* # Professional applications │ ├── creative-tools.* # Creative content creation │ ├── developer-tools.* # Code generation and APIs │ ├── monitoring-analytics.* # Real-time analytics │ └── mcp-demos/ # MCP server integration demos ├── docs/visual-content/ # CLI demonstrations │ ├── screenshots/cli-screenshots/ # Professional CLI screenshots │ └── cli-videos/ # CLI demonstration videos │ ├── cli-01-cli-help.mp4 # Help command overview │ ├── cli-02-provider-status.mp4 # Provider connectivity │ ├── cli-03-text-generation.mp4 # AI generation demos │ ├── cli-04-auto-selection.mp4 # Auto provider selection │ ├── cli-05-streaming.mp4 # Real-time streaming │ ├── cli-06-advanced-features.mp4 # Advanced features │ └── cli-advanced-features/ # MCP command demos └── docs/cli-recordings/ # Professional asciinema recordings └── latest/ # 6 .cast files for web embedding ``` ## Getting Started with Visual Content ### Quick Demo Access 1. **Web Interface**: `cd neurolink-demo && npm start` 2. **CLI Testing**: `npx @juspay/neurolink status` 3. **Screenshots**: Browse the visual content directories 4. **Videos**: Open video files in your preferred player ### Recording Your Own Demos 1. **CLI Recording**: Use the provided automation scripts 2. **Web Recording**: Browser automation with Playwright 3. **Screenshot Creation**: Automated capture with consistent styling 4. **Professional Quality**: Follow established visual standards ### Integration in Documentation - **README Files**: Embed screenshots and video links - **API Documentation**: Visual examples alongside code - **Tutorials**: Step-by-step visual guides - **Marketing**: Professional quality content for promotion --- [← Back to Main README](/docs/) | [Next: Error Handling →](/docs/workflows/error-handling) --- # Getting Started ## Getting Started # Getting Started Welcome to NeuroLink! This section will help you get up and running quickly with the Enterprise AI Development Platform. ## What You'll Learn - **[Quick Start](/docs/getting-started/quick-start)** — Get NeuroLink working in under 2 minutes with basic examples for both CLI and SDK usage. - **[Installation](/docs/getting-started/installation)** — Detailed installation instructions for different environments and package managers. - **[Provider Setup](/docs/getting-started/provider-setup)** — Configure API keys and credentials for supported AI providers with step-by-step guides. - **[Environment Variables](/docs/getting-started/environment-variables)** — Complete reference for all environment variables and configuration options. ## Choose Your Path ## Prerequisites - **Node.js 18+** (for SDK usage) - **npm/pnpm/yarn** (package manager) - **API keys** for at least one AI provider :::tip[Free Options Available] You can start with free providers like Google AI Studio, Hugging Face, or local Ollama to test NeuroLink without costs. ::: ## Next Steps 1. **[Quick Start](/docs/getting-started/quick-start)** - Get running in 2 minutes 2. **[Provider Setup](/docs/getting-started/provider-setup)** - Configure your AI providers 3. **[CLI Guide](/docs/)** or **[SDK Reference](/docs/)** - Deep dive into usage 4. **[Examples](/docs/)** - See real-world applications --- ## AI Provider Guides # AI Provider Guides Complete setup guides for all supported AI providers. ## Direct AI Providers Access leading AI models directly from their creators: ### [OpenAI](/docs/getting-started/providers/openai) **GPT-5.4, GPT-5, GPT-4o, and o-series reasoning models** - GPT-5.4 and GPT-5 series flagships with up to 1.05M context - ️ GPT-4o multimodal (vision) and o3 / o3-pro / o4-mini reasoning models - Full tool/function calling and embeddings support - Auth: API Key (`OPENAI_API_KEY`) [Setup Guide →](/docs/getting-started/providers/openai) ### [Anthropic](/docs/getting-started/providers/anthropic) **Claude models with API key or OAuth authentication** - Claude 4.5 Opus/Sonnet/Haiku, Claude 4.0 Opus/Sonnet - API key or OAuth (Pro/Max subscription) - Extended thinking for deep reasoning - 200K context window, multimodal support [Setup Guide →](/docs/getting-started/providers/anthropic) --- ## Enterprise Providers Production-grade providers for enterprise deployments: ### [Azure OpenAI](/docs/getting-started/providers/azure-openai) **Enterprise AI with Microsoft Azure** - SOC2, HIPAA, ISO 27001 compliant - Multi-region deployment (30+ regions) - ️ Private endpoints with VNet - Enterprise SLAs [Setup Guide →](/docs/getting-started/providers/azure-openai) ### [Google Vertex AI](/docs/getting-started/providers/google-vertex) **Google Cloud ML platform** - ☁️ GCP integration - IAM, VPC, service accounts - Global deployment - Gemini, PaLM, Codey models [Setup Guide →](/docs/getting-started/providers/google-vertex) ### [AWS Bedrock](/docs/getting-started/providers/aws-bedrock) **Serverless AI on AWS** - 13 foundation models (Claude, Llama, Mistral) - IAM, VPC integration - Multi-region (us-east-1, eu-west-1, ap-southeast-1) - Pay-per-use pricing [Setup Guide →](/docs/getting-started/providers/aws-bedrock) ### [AWS SageMaker](/docs/getting-started/providers/sagemaker) **Custom model endpoints on AWS SageMaker infrastructure** - Deploy fine-tuned, Hugging Face, or JumpStart models - IAM, VPC, PrivateLink, KMS encryption - ⚠️ `generate()` only — streaming is not implemented - Full control over instance types and autoscaling [Setup Guide →](/docs/getting-started/providers/sagemaker) --- ## Compliance-Focused Providers with specific compliance certifications: ### [Mistral AI](/docs/getting-started/providers/mistral) **European AI with GDPR compliance** - 🇪🇺 EU data residency - ✅ GDPR compliant by default - Open source models - Cost-effective [Setup Guide →](/docs/getting-started/providers/mistral) --- ## ‍ Hosted Inference Providers Access frontier models via hosted cloud inference APIs: ### [DeepSeek](/docs/getting-started/provider-setup.md#deepseek) **deepseek-chat (V3) and deepseek-reasoner (R1)** - deepseek-chat — high-quality general chat at low cost - deepseek-reasoner — R1 chain-of-thought reasoning model - API key from [platform.deepseek.com](https://platform.deepseek.com/api_keys) - Aliases: `ds` [Setup Guide →](/docs/getting-started/provider-setup.md#deepseek) ### [NVIDIA NIM](/docs/getting-started/provider-setup.md#nvidia-nim) **400+ models via NVIDIA's hosted and self-hosted inference platform** - Llama 3.3 70B Instruct (default), Mistral, Nemotron, and 400+ catalog models - NIM-specific extras: top_k, min_p, repetition_penalty, reasoning_budget - API key from [build.nvidia.com](https://build.nvidia.com/settings/api-keys) - ️ Also supports self-hosted NIM endpoints via `NVIDIA_NIM_BASE_URL` - Aliases: `nim`, `nvidia` [Setup Guide →](/docs/getting-started/provider-setup.md#nvidia-nim) ### [xAI Grok](/docs/getting-started/providers/xai) **Grok 3 / 3 Mini / 2 / 2 Vision via api.x.ai** - Grok 3 — flagship reasoning + coding - ⚡ Grok 3 Mini — faster + cheaper - ️ Grok 2 Vision — multimodal text + images - API key from [console.x.ai](https://console.x.ai/) - Aliases: `grok` [Setup Guide →](/docs/getting-started/providers/xai) ### [Groq](/docs/getting-started/providers/groq) **Sub-100ms inference via LPU acceleration** - ⚡ \/v1/decisions` - `XOR_API_KEY` is the key that endpoint accepts; on LiteLLM, the key's team must allow `xor-latest` (and `xor-omni` for media) - Weights and setup: [huggingface.co/juspay/xor](https://huggingface.co/juspay/xor) [Setup Guide →](/docs/getting-started/providers/xor) ### [SubQ](/docs/getting-started/providers/subq) **Hosted decision provider** — the same typed `boolean`/`choice`/`score` answers as Jev, from Subquadratic's `subq-snap-preview` (public preview), at `https://api.subq.ai` - Serves `decide` only (provider id `subq`; the aliases `subquadratic` and `subq-snap` work too); built-in features use it when it is configured and none of TypeSafe, Laya or XOR is — it comes ahead of Perplexity and Cloudflare Clef, because its key is shared with no other provider - `SUBQ_API_KEY` alone configures it (keys come from console.subq.ai, shown once); `SUBQ_MODEL` is optional - ️ No image or video input yet: SubQ's image format is not one the decide catalog can describe, so images are refused before any request - NeuroLink reports an advisory state window (376,000 estimated tokens; SubQ's own 400 response states a maximum model length of 393,216) and enforces none; no question cap is declared - Hosted endpoint, so no base URL is needed; `SUBQ_BASE_URL` (or `credentials.subq.baseURL`) can name another origin [Setup Guide →](/docs/getting-started/providers/subq) ### [Perplexity Decisions](/docs/getting-started/providers/perplexity-decider) **Hosted decision provider** — the same typed `boolean`/`choice`/`score` answers as Jev, from Perplexity's `pplx-decider-v1-27b`, at `https://api.perplexity.ai` - Serves `decide` only (provider id `perplexity-decider`, not the Sonar text provider `perplexity`); built-in features use it when it is configured and no TypeSafe key, no `AI_GATEWAY_API_KEY`, no Laya key and base URL, no XOR key and base URL and no `SUBQ_API_KEY` is - `PERPLEXITY_API_KEY` alone configures it, and it is the same key the Perplexity text provider reads, so a key set for Sonar also lets built-in features use it when none of TypeSafe, Laya, XOR or SubQ is configured; the guide lists what each consumer then sends - ️ Takes up to 8 PNG, JPEG or WebP images with a decision; no video - $0.04 per million input tokens (image tokens included), output free, as Perplexity documents it - Refuses more than about 100,000 estimated tokens of state (NeuroLink's own window; the server's ceiling is 262,144 input tokens), or more than 128 questions in a `decide()` call (`tryDecide()` splits them), before any network call. The 128-question cap, the server's token ceiling and the latency were measured on a real account in October 2026 - Hosted endpoint, so no base URL is needed; `PERPLEXITY_DECIDER_BASE_URL` (or `credentials.perplexityDecider.baseURL`) can name another origin [Setup Guide →](/docs/getting-started/providers/perplexity-decider) ### [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef) **Hosted decision provider on Workers AI** — the same typed `boolean`/`choice`/`score` answers as Jev, from Cloudflare's `clef` (27B) and `clef-flash` (9B), at `https://api.cloudflare.com/client/v4` - Serves `decide` only (provider id `cloudflare-clef`, not the Workers AI text provider `cloudflare`); built-in features use it only when it is configured and none of TypeSafe, Laya, XOR, SubQ or Perplexity is — it comes after those five - `CLOUDFLARE_API_KEY` (Workers AI permission) and `CLOUDFLARE_ACCOUNT_ID` configure it, and they are the same two variables the Cloudflare text provider reads, so a pair set for that provider also lets built-in features use it when none of TypeSafe, Laya, XOR, SubQ or Perplexity is configured - ️ Takes up to 4 PNG, JPEG or WebP images with a decision; no video - $0.24 per million input tokens for `clef`, $0.09 for `clef-flash`; no output price is listed on Cloudflare's pricing page - **The state window changed in October 2026** (hosted service or model: unknown): until 2026-10-04 the endpoint ignored text past about 2,048 tokens without an error, and on 2026-10-07 it read states of at least 190,153 tokens (`clef-flash`) and 52,154 (`clef`); NeuroLink refuses more than 16,000 estimated tokens (digits count a token each, punctuation 0.75, emoji 3), more than 64 questions in a `decide()` call (`tryDecide()` splits them) and a request over 256,000 bytes, base64 image data included, before any network call. The state cut and the request ceiling were measured on a real account in October 2026, with the follow-up text cuts and API limits checked on both models; see the guide for the tested shapes and dates - Hosted endpoint, so no base URL is needed; `CLOUDFLARE_CLEF_BASE_URL` (or `credentials.cloudflareClef.baseURL`) can name another base [Setup Guide →](/docs/getting-started/providers/cloudflare-clef) ### [OpenAI Decisions](/docs/getting-started/providers/openai-decisions) **Hosted decision provider (public beta)** — the same typed `boolean`/`choice`/`score` answers as Jev, from OpenAI's Decisions API (`gpt-6-luna`), at `https://api.openai.com/v1/decisions` - Serves `decide` only (provider id `openai-decisions`, not the OpenAI chat provider `openai`); built-in features use it only when it is configured and none of TypeSafe, Laya, XOR, SubQ, Perplexity or Cloudflare Clef is — it comes seventh, ahead of only ScaleDown - `OPENAI_API_KEY` alone configures it, and it is the same key the OpenAI chat provider reads, so a key set for chat also lets built-in features (and a transcription dictionary's correction check) use it, and make paid decision calls, when none of the six providers ahead of it is configured, unless `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL` names a host other than `https://api.openai.com` (the key is then taken to be a gateway's and is not used by default; a call that names the provider still uses it and sends it to `api.openai.com`); the guide lists what each consumer then sends - ️ Takes up to 8 images as inline data URLs with a decision (NeuroLink's own allowance, not OpenAI's); no video - $0.10 per million input tokens, input only, per [OpenAI's Decisions guide](https://developers.openai.com/api/docs/guides/decisions) as read on 2026-10-07; regional and long-context multipliers are not modelled - Questions per request are capped at 200, the figure in OpenAI's Python SDK, and `tryDecide()` splits a longer set at it; going over 200 was not tried against the live endpoint, and option limits, image formats, rate limits and latency are not established (none measured). NeuroLink reports 922,000 state tokens as an advisory figure and never refuses on it - Hosted endpoint, so no base URL is needed; `OPENAI_DECISIONS_BASE_URL` (or `credentials.openaiDecisions.baseURL`) can name another origin [Setup Guide →](/docs/getting-started/providers/openai-decisions) ### [ScaleDown](/docs/getting-started/providers/scaledown) **Hosted decision provider** — the same typed `boolean`/`choice`/`score` answers as Jev, from ScaleDown's Classify models (`classify-1` by default), at `https://api.scaledown.xyz/v1/scaledown` - Serves `decide` only (provider id `scaledown`; the alias `scaledown-classify` works too); built-in features use it only when it is configured and none of TypeSafe, Laya, XOR, SubQ, Perplexity, Cloudflare Clef or OpenAI Decisions is — it comes last, by choice and not because its key is shared - `SCALEDOWN_API_KEY` alone configures it, and no other provider reads that variable; the key is sent in an `x-api-key` header, never as a Bearer token - ️ Text only: images and video are refused before any request, and the state is always sent as a string (a string unchanged, anything else as its JSON text; a blank string is refused locally) - USD 0.05 per million input tokens, output not charged: a list price reported by the marketing session on 2026-10-15, not measured here. A `choice` question is scored once per option, so input tokens grow with options times state length - Context size, latency, rate limits and the option, question and level maximums are not measured; no state window is declared and nothing is refused on size - Hosted endpoint, so no base URL is needed; `SCALEDOWN_BASE_URL` (or `credentials.scaledown.baseURL`) can name an origin or an origin with a path prefix [Setup Guide →](/docs/getting-started/providers/scaledown) ## Additional Catalog Providers Every provider below is a **Tier-2 catalog entry**. Provider-specific behavioural quirks may apply, so check the provider's catalog file. The whole integration is one JSON file under `src/lib/providers/catalog/`. Each page is generated from that file, which is also what the CI onboarding gate reads. ### [API Route](/docs/getting-started/providers/api-route) **Claude Sonnet 4.6** - 8 models; default `claude-sonnet-4-6` (1M context) - ️ Native tool calling + structured output together - Free tier available - ✅ Roster verified 2026-09-17 (authenticated GET /v1/models) - API key from [api-route.com](https://api-route.com) - Aliases: `apiroute` [Setup Guide →](/docs/getting-started/providers/api-route) ### [Baseten](/docs/getting-started/providers/baseten) **GLM 5.3 Flash** - 16 models; default `zai-org/GLM-5.3-Flash` (1M context) - ️ Native tool calling + structured output together - Free tier available - ✅ Roster verified 2026-09-03 (authenticated GET /v1/models) - API key from [app.baseten.co](https://app.baseten.co/) [Setup Guide →](/docs/getting-started/providers/baseten) ### [Friendli](/docs/getting-started/providers/friendli) **zai-org/GLM-5.3** - 7 models; default `zai-org/GLM-5.3` (1M context) - ️ Native tool calling — not combined with structured output in one request (HTTP 422 if both are set) - Free tier available (rate limits are tight — pace requests 20s+ apart) - ✅ Roster verified 2026-09-06 (authenticated GET /serverless/v1/models) - API key from [suite.friendli.ai](https://suite.friendli.ai/) [Setup Guide →](/docs/getting-started/providers/friendli) ### [GMI Cloud](/docs/getting-started/providers/gmicloud) **MiniMaxAI/MiniMax-M3** - 1 model; default `MiniMaxAI/MiniMax-M3` (1M context) - ️ Native tool calling + structured output together - Free tier available - ✅ Roster verified 2026-09-03 (authenticated GET /v1/models) - API key from [console.gmicloud.ai](https://console.gmicloud.ai) - Aliases: `gmi-cloud` [Setup Guide →](/docs/getting-started/providers/gmicloud) ### [Inception Labs](/docs/getting-started/providers/inception-labs) **Mercury 2, Inception's enterprise diffusion LLM (dLLM)** - 1 model; default `mercury-2` (125K context) - ️ Native tool calling + structured output together - Free tier available - ✅ Roster verified 2026-09-03 (authenticated GET /v1/models) - API key from [platform.inceptionlabs.ai/dashboard/api-keys](https://platform.inceptionlabs.ai/dashboard/api-keys) - Aliases: `inception`, `mercury` [Setup Guide →](/docs/getting-started/providers/inception-labs) ### [io.net Intelligence](/docs/getting-started/providers/io-intelligence) **Meta: Llama 3.3 70B Instruct** - 34 models; default `meta-llama/Llama-3.3-70B-Instruct` (125K context) - ️ Native tool calling + structured output together - Free tier available - ✅ Roster verified 2026-09-03 (authenticated GET /v1/models) - API key from [ai.io.net](https://ai.io.net/) - Aliases: `io-net` [Setup Guide →](/docs/getting-started/providers/io-intelligence) ### [Mancer](/docs/getting-started/providers/mancer) **DeepSeek V4 Flash** - 10 models; default `deepseek-v4-flash` (1M context) - ⚠️ **No tool calling** — text generation and structured output only - Free tier available - ✅ Roster verified 2026-09-03 (authenticated GET /oai/v1/models; full response retained as evidence/mancer-roster-authenticated.json in the campaign scratchpad and every catalog price/limit machine-checked against it (Mancer re-prices — gpt-oss-120b input moved 0.024 → 0.022 within the day)) - API key from [mancer.tech/dashboard](https://mancer.tech/dashboard) - Aliases: `mancer-tech` [Setup Guide →](/docs/getting-started/providers/mancer) ### [Morph](/docs/getting-started/providers/morph) **Morph v3 Large** - 2 models; default `morph-v3-large` (262K context) - ⚠️ **No tool calling** — text generation and structured output only - Free tier requires a card on file (rate-limited to 5 req/min until added) - ✅ Roster verified 2026-09-05 (authenticated GET /v1/models) - API key from [morphllm.com/dashboard](https://morphllm.com/dashboard) - Aliases: `morphllm` [Setup Guide →](/docs/getting-started/providers/morph) ### [Novita AI](/docs/getting-started/providers/novita) **zai-org/GLM-5.3 Flash** - 5 models; default `zai-org/glm-5.3-flash` (128K context) - ️ Native tool calling + structured output together - Free tier available - ✅ Roster verified 2026-09-05 (authenticated GET /openai/v1/models) - API key from [novita.ai/settings/key-management](https://novita.ai/settings/key-management) [Setup Guide →](/docs/getting-started/providers/novita) ### [Upstage](/docs/getting-started/providers/upstage) **Solar Pro 4** - 10 models; default `solar-pro4` (512K context) - ️ Native tool calling + structured output together - Free tier available - ✅ Roster verified 2026-09-03 (authenticated GET /v1/models) - API key from [console.upstage.ai/api-keys](https://console.upstage.ai/api-keys) - Aliases: `solar` [Setup Guide →](/docs/getting-started/providers/upstage) ## ️ Voice Providers {#voice-providers} Synthesize speech, transcribe audio, or run live voice sessions. Voice providers are separate from LLM providers — they handle audio I/O rather than text generation. ### Text-to-Speech (TTS) #### [OpenAI TTS](/docs/getting-started/providers/openai-tts) **Highest-quality text-to-speech** - ️ Voices: alloy, echo, fable, onyx, nova, shimmer - Models: tts-1 (fast) and tts-1-hd (high quality) - Formats: MP3, WAV, OGG, Opus - Auth: API Key (`OPENAI_API_KEY`) [Setup Guide →](/docs/getting-started/providers/openai-tts) #### [ElevenLabs](/docs/getting-started/providers/elevenlabs) **Best multilingual and voice-cloning TTS** - Supports 30+ languages with natural prosody - Custom voice cloning from short audio samples - Formats: MP3, WAV (raw PCM, surfaced as `pcm16`), Opus (Ogg container) - Auth: API Key (`ELEVENLABS_API_KEY`) [Setup Guide →](/docs/getting-started/providers/elevenlabs) #### [Google TTS](/docs/getting-started/provider-setup) **1M characters/month free tier** - Generous free tier for standard voices - 380+ voices across 50+ languages - Formats: MP3, WAV, OGG - Auth: Service Account [Setup Guide →](/docs/getting-started/provider-setup) #### [Azure TTS](/docs/getting-started/providers/azure-speech) **Enterprise TTS with full SSML support** - Fine-grained prosody control via SSML - 400+ neural voices, 140+ languages - Formats: MP3, WAV (PCM), Opus (Ogg container) - Auth: API Key + Region [Setup Guide →](/docs/getting-started/providers/azure-speech) #### [Fish Audio](/docs/getting-started/providers/fish-audio) **Low-cost TTS with 15s voice cloning** - ~80% cheaper than ElevenLabs - 15-second reference audio → custom voice - 14 languages - Formats: MP3, WAV, PCM16 (raw) - Auth: API Key (`FISH_AUDIO_API_KEY`) [Setup Guide →](/docs/getting-started/providers/fish-audio) #### [60db](/docs/getting-started/providers/sixtydb) Workspace voice catalogs and HTTP text-to-speech. - WAV or raw PCM16 output at 24 kHz - Workspace API key and voice UUID - [Setup guide](/docs/getting-started/providers/sixtydb) #### [Cartesia](/docs/getting-started/providers/cartesia) **Low-latency Sonic models — synchronous + streaming** - ⚡ Sub-second turnaround on the synchronous `/tts/bytes` endpoint - Separate WebSocket streaming flow via `CartesiaStream` (voice server) - Voice cloning via dashboard upload - Formats: MP3 (44.1 kHz), WAV (PCM s16le @ 44.1 kHz), PCM16 (raw @ 24 kHz) - Auth: API Key (`CARTESIA_API_KEY`) [Setup Guide →](/docs/getting-started/providers/cartesia) --- ### Speech-to-Text (STT) #### [Whisper (OpenAI)](/docs/getting-started/provider-setup#whisper) **Highest transcription accuracy** - Best-in-class accuracy on diverse audio - Multilingual with automatic language detection - Formats: WAV, MP3, M4A, FLAC, OGG, OPUS, WEBM, MP4, MPEG, MPGA - Auth: API Key (`OPENAI_API_KEY`) [Setup Guide →](/docs/getting-started/provider-setup#whisper) #### [Deepgram](/docs/getting-started/providers/deepgram) **Real-time streaming transcription via WebSocket** - ⚡ Sub-300 ms word-level results over WebSocket - REST batch and WebSocket streaming modes - Formats: WAV, MP3, OGG, FLAC - Auth: API Key (`DEEPGRAM_API_KEY`) [Setup Guide →](/docs/getting-started/providers/deepgram) #### [Google STT](/docs/getting-started/provider-setup) **125+ languages with speaker diarization** - Best fit for existing Google Cloud users - Speaker diarization and multi-channel audio - Formats: WAV, FLAC, MP3, OGG - Auth: API Key (`GOOGLE_AI_API_KEY` / `GEMINI_API_KEY`) **or** Service Account (`GOOGLE_APPLICATION_CREDENTIALS`) [Setup Guide →](/docs/getting-started/provider-setup) #### [Azure STT](/docs/getting-started/providers/azure-speech) **Enterprise STT with custom model training** - Batch transcription and custom model support - Compliance controls for regulated industries - Formats: WAV (PCM), Ogg/Opus — convert MP3 to WAV first - Auth: API Key + Region [Setup Guide →](/docs/getting-started/providers/azure-speech) --- ### Realtime Voice Realtime providers maintain a persistent bidirectional WebSocket connection, enabling low-latency spoken conversation with the AI model. #### [OpenAI Realtime](/docs/getting-started/provider-setup#openai-realtime) **Low-latency bidirectional voice over WebSocket** - ⚡ Full-duplex audio stream with GPT-4o - Voice activity detection (VAD) built-in - Formats: WAV, Opus - Auth: API Key (`OPENAI_API_KEY`) [Setup Guide →](/docs/getting-started/provider-setup#openai-realtime) #### [Gemini Live](/docs/getting-started/provider-setup) **Google's native realtime voice API** - ⚡ Native multimodal realtime session with Gemini - Supports audio + video input simultaneously - Formats: WAV, Opus - Auth: API Key (`GOOGLE_AI_API_KEY` or `GEMINI_API_KEY`) [Setup Guide →](/docs/getting-started/provider-setup) --- ## Video Generation Image-to-video and text-to-video providers (use via `output: { mode: "video" }`): - **Vertex Veo 3.1** (default) — `--videoProvider vertex` - **Kling** (PiAPI) — `--videoProvider kling` ([details](/docs/provider-integration/19-adding-video-provider)) - **Runway** (Gen-3 Alpha / Gen-4 Turbo) — `--videoProvider runway` - **Replicate** — Wan-Alpha + many others — `--videoProvider replicate` ([guide](/docs/getting-started/providers/replicate)) See [Video Generation feature page](/docs/features/video-generation) for the full SDK / CLI surface. --- ## Avatar / Lip-Sync Generation Talking-head video synthesis from a portrait image + audio (use via `output: { mode: "avatar" }`): - **D-ID** — `--avatarProvider d-id` (text-driven via Microsoft voices, or audio-driven) - **HeyGen** — `--avatarProvider heygen` (HeyGen avatar catalog id required) - **Replicate (MuseTalk)** — `--avatarProvider replicate` or `musetalk` ([guide](/docs/getting-started/providers/replicate)) See [`docs/provider-integration/21-adding-new-modality.md`](/docs/provider-integration/21-adding-new-modality) for the architectural pattern. --- ## Music / Sound Generation Music + sound-effect generation (use via `output: { mode: "music" }`): - **Beatoven.ai** — `--musicProvider beatoven` (royalty-free background music) - **ElevenLabs Music** — `--musicProvider elevenlabs-music` (short SFX / loops up to 22s; same `ELEVENLABS_API_KEY` as TTS) - **Lyria 3 Pro** (Google) — `--musicProvider lyria` - **Replicate (MusicGen)** — `--musicProvider replicate` or `musicgen` ([guide](/docs/getting-started/providers/replicate)) --- ## Quick Comparison | Provider | Free Tier | Enterprise | GDPR | Latency | Best For | | ---------------------------------------------------------------- | ---------- | ---------- | ------ | ------- | ------------------------------------- | | [Anthropic](/docs/getting-started/providers/anthropic) | Limited | ✅ | ✅ | Low | Reasoning, coding, Claude | | [Hugging Face](/docs/getting-started/providers/huggingface) | ✅ | ❌ | ✅ | Medium | Open source, experimentation | | [Google AI](/docs/getting-started/providers/google-ai) | ✅ | ✅ | ✅ | Low | Free tier, Gemini | | [Mistral AI](/docs/getting-started/providers/mistral) | ❌ | ✅ | ✅ | Low | EU compliance, cost | | [OpenRouter](/docs/getting-started/providers/openrouter) | ✅ | ✅ | Varies | Low | Multi-model, automatic failover | | [OpenAI Compatible](/docs/getting-started/providers/openai-compatible) | Varies | ✅ | Varies | Varies | Flexibility, local deployment | | [LiteLLM](/docs/getting-started/providers/litellm) | ❌ | ✅ | Varies | Low | Multi-provider, unified API | | [Azure OpenAI](/docs/getting-started/providers/azure-openai) | ❌ | ✅ | ✅ | Low | Enterprise, Microsoft ecosystem | | [Vertex AI](/docs/getting-started/providers/google-vertex) | ❌ | ✅ | ✅ | Low | Enterprise, GCP ecosystem | | [AWS Bedrock](/docs/getting-started/providers/aws-bedrock) | ❌ | ✅ | ✅ | Low | Enterprise, AWS ecosystem | | [DeepSeek](/docs/getting-started/provider-setup.md#deepseek) | ❌ | ✅ | ❌ | Low | Cost-effective reasoning, R1 model | | [NVIDIA NIM](/docs/getting-started/provider-setup.md#nvidia-nim) | ❌ | ✅ | Varies | Low | NVIDIA-hosted or self-hosted LLMs | | [LM Studio](/docs/getting-started/provider-setup.md#lm-studio) | ✅ (Local) | ❌ | ✅ | Varies | Local GUI model management | | [llama.cpp](/docs/getting-started/provider-setup.md#llamacpp) | ✅ (Local) | ❌ | ✅ | Varies | High-performance local GGUF inference | | [OpenAI TTS](/docs/getting-started/providers/openai-tts) | ❌ | ✅ | ✅ | Low | High-quality TTS (tts-1-hd) | | [ElevenLabs](/docs/getting-started/providers/elevenlabs) | ❌ | ✅ | Varies | Low | Multilingual TTS, voice cloning | | [Google TTS](/docs/getting-started/provider-setup) | ✅ | ✅ | ✅ | Low | Cost-effective TTS, 1M chars free | | [Azure TTS](/docs/getting-started/providers/azure-speech) | ❌ | ✅ | ✅ | Low | Enterprise TTS, SSML support | | [Fish Audio](/docs/getting-started/providers/fish-audio) | ❌ | ✅ | Varies | Low | Low-cost TTS, voice cloning, 14 langs | | [Cartesia](/docs/getting-started/providers/cartesia) | ❌ | ✅ | Varies | Low | Low-latency Sonic models | | [Whisper](/docs/getting-started/provider-setup#whisper) | ❌ | ✅ | ✅ | Low | Best STT accuracy | | [Deepgram](/docs/getting-started/providers/deepgram) | ❌ | ✅ | Varies | Low | Real-time STT streaming (WebSocket) | | [Google STT](/docs/getting-started/provider-setup) | ❌ | ✅ | ✅ | Low | STT for GCP users, 125+ languages | | [Azure STT](/docs/getting-started/providers/azure-speech) | ❌ | ✅ | ✅ | Low | Enterprise STT, custom models | | [OpenAI Realtime](/docs/getting-started/provider-setup#openai-realtime) | ❌ | ✅ | ✅ | Low | Realtime bidirectional voice | | [Gemini Live](/docs/getting-started/provider-setup) | ❌ | ✅ | ✅ | Low | Realtime voice + video (Gemini) | --- ## Setup Strategies ### Strategy 1: Free Tier First (Recommended for Development) ```typescript const ai = new NeuroLink({ providers: [ { name: 'google-ai', priority: 1, config: { apiKey: process.env.GOOGLE_AI_KEY }, quotas: { daily: 1500 } }, { name: 'openai', priority: 2, config: { apiKey: process.env.OPENAI_API_KEY } } ], failoverConfig: { enabled: true, fallbackOnQuota: true } }); const result = await ai.generate({ input: { text: "Hello world" } }); ``` ```bash # Set up environment variables export GOOGLE_AI_KEY="your-key" export OPENAI_API_KEY="your-key" # Use with automatic failover npx @juspay/neurolink generate "Hello world" \ --provider google-ai ``` ### Strategy 2: Multi-Region Enterprise ```typescript const ai = new NeuroLink({ providers: [ { name: "azure-us", region: "us-east", config: { /* Azure US */ }, }, { name: "azure-eu", region: "eu-west", config: { /* Azure EU */ }, }, { name: "bedrock-us", region: "us-east", config: { /* Bedrock US */ }, }, ], loadBalancing: "latency-based", }); ``` ### Strategy 3: GDPR Compliance ```typescript const ai = new NeuroLink({ providers: [ { name: "mistral", priority: 1, config: { apiKey: process.env.MISTRAL_API_KEY }, }, { name: "azure-eu", priority: 2, config: { /* Azure EU region */ }, }, ], compliance: { framework: "GDPR", dataResidency: "EU", }, }); ``` --- ## Next Steps 1. **Choose a provider** based on your requirements (free tier, compliance, region) 2. **Follow the setup guide** to get your API key 3. **Configure NeuroLink** with the provider 4. **Test the integration** with a simple request 5. **Add failover** for production reliability --- ## Related Documentation - **[Multi-Provider Failover](/docs/guides/enterprise/multi-provider-failover)** - High availability patterns - **[Cost Optimization](/docs/cookbook/cost-optimization)** - Reduce costs by 80-95% - **[Compliance & Security](/docs/guides/enterprise/compliance)** - GDPR, SOC2, HIPAA - **[Load Balancing](/docs/guides/enterprise/load-balancing)** - Distribution strategies - **[Voice Providers Comparison](/docs/reference/provider-comparison.md#voice-providers)** - TTS, STT, and Realtime capability matrix - **[Voice Provider Selection](/docs/reference/provider-selection.md#text-to-speech-tts)** - Choosing the right voice provider --- ## Quick Start # Quick Start Get NeuroLink running in under 2 minutes with this quick start guide. ## Prerequisites - **Node.js 18+** - **npm/pnpm/yarn** package manager - **API key** for at least one AI provider (we recommend starting with Google AI Studio - it has a free tier) ## ⚡ 1-Minute Setup ### Option 1: CLI Usage (No Installation) ```bash # Set up your API key (Google AI Studio has free tier) export GOOGLE_AI_API_KEY="AIza-your-google-ai-api-key" # Generate text instantly npx @juspay/neurolink generate "Hello, AI" npx @juspay/neurolink gen "Hello, AI" # Shortest form # Check provider status npx @juspay/neurolink status ``` ### Option 2: SDK Installation ```bash # Install for your project npm install @juspay/neurolink ``` ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Write a haiku about programming" }, provider: "google-ai", }); console.log(result.content); console.log(`Used: ${result.provider}`); ``` ### Write Once, Run Anywhere NeuroLink's power is in its provider-agnostic design. Write your code once, and NeuroLink automatically uses the best available provider. If your primary provider fails, it seamlessly falls back to another, ensuring your application remains robust. ```typescript // No provider specified - NeuroLink handles it! const neurolink = new NeuroLink(); // This code works with OpenAI, Google, Anthropic, etc. without any changes. const result = await neurolink.generate({ input: { text: "Explain quantum computing simply." }, }); console.log(result.content); console.log(`AI Provider Used: ${result.provider}`); ``` ## Get API Keys ### Google AI Studio (Free Tier Available) 1. Visit [Google AI Studio](https://aistudio.google.com/) 2. Sign in with your Google account 3. Click "Get API Key" 4. Create a new API key 5. Copy and use: `export GOOGLE_AI_API_KEY="AIza-your-key"` ### Other Providers - **OpenAI**: [platform.openai.com](https://platform.openai.com/) - **Anthropic**: [console.anthropic.com](https://console.anthropic.com/) - **LiteLLM**: Access 100+ models through one proxy server (requires setup) - **Ollama**: Local installation, no API key needed ## ✅ Verify Setup ```bash # Check all configured providers npx @juspay/neurolink status # Test with built-in tools npx @juspay/neurolink generate "What time is it?" --debug # Test without tools (pure text generation) npx @juspay/neurolink generate "Write a poem" --disable-tools ``` ## Next Steps 1. **[Provider Setup](/docs/getting-started/provider-setup)** - Configure multiple AI providers 2. **[CLI Loop Sessions](/docs/features/cli-loop-sessions)** - Try persistent interactive mode with memory 3. **[CLI Commands](/docs/cli/commands)** - Learn all available commands 4. **[SDK Reference](/docs/sdk/api-reference)** - Integrate into your applications 5. **[Examples](/docs/examples/basic-usage)** - See practical implementations **Latest Features:** - [Multimodal Chat](/docs/features/multimodal-chat) - Add images to your prompts - [PPT Generation](/docs/features/ppt-generation) - Generate PowerPoint presentations - [Auto Evaluation](/docs/features/auto-evaluation) - Quality scoring for responses - [Guardrails](/docs/features/guardrails) - Content filtering and safety ## 🆘 Need Help? - **Not working?** Check our [Troubleshooting Guide](/docs/reference/troubleshooting) - **Questions?** See our [FAQ](/docs/reference/faq) - **Issues?** Report on [GitHub](https://github.com/juspay/neurolink/issues) --- ## Installation # Installation Complete installation guide for NeuroLink CLI and SDK across different environments. ## Choose Your Installation Method ```bash # Direct usage (recommended) npx @juspay/neurolink generate "Hello, AI" # Global installation (optional) npm install -g @juspay/neurolink neurolink generate "Hello, AI" ``` ```bash # npm npm install @juspay/neurolink # pnpm pnpm add @juspay/neurolink # yarn yarn add @juspay/neurolink ``` ```bash git clone https://github.com/juspay/neurolink cd neurolink pnpm install npx husky install # Setup git hooks for build rule enforcement pnpm setup:complete # Complete automated setup pnpm run validate:all # Validate build rules and quality ``` ## System Requirements ### Minimum Requirements - **Node.js**: 18.0.0 or higher - **npm**: 8.0.0 or higher - **pnpm**: 8.0.0 or higher (recommended) ### Supported Platforms - **macOS**: 10.15+ (Intel and Apple Silicon) - **Linux**: Ubuntu 18.04+, CentOS 7+, Debian 9+ - **Windows**: 10+ (WSL recommended for best experience) ### Check Your Environment ```bash # Check Node.js version node --version # Should be 18.0.0+ # Check npm version npm --version # Should be 8.0.0+ # Check if TypeScript support is available (optional) npx tsc --version ``` ## Environment Setup ### 1. API Keys Configuration Create a `.env` file in your project root: ```bash # Create .env file touch .env # Add your API keys echo 'GOOGLE_AI_API_KEY="AIza-your-google-ai-key"' >> .env echo 'OPENAI_API_KEY="sk-your-openai-key"' >> .env echo 'ANTHROPIC_API_KEY="sk-ant-your-key"' >> .env ``` ### 2. Verify Installation ```bash # Test CLI installation npx @juspay/neurolink --version # Test provider connectivity npx @juspay/neurolink status # Test basic generation npx @juspay/neurolink generate "Hello, world!" ``` ### 3. TypeScript Setup (Optional) For TypeScript projects, NeuroLink includes full type definitions: ```typescript // tsconfig.json { "compilerOptions": { "target": "ES2020", "module": "ESNext", "moduleResolution": "node", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true } } ``` ```typescript // test.ts const neurolink = new NeuroLink(); // Full TypeScript IntelliSense available ``` ## Framework-Specific Setup ### Next.js ```bash npm install @juspay/neurolink ``` ```typescript // app/api/ai/route.ts export async function POST(request: Request) { const { prompt } = await request.json(); const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: prompt }, }); return Response.json({ content: result.content }); } ``` ### SvelteKit ```bash npm install @juspay/neurolink ``` ```typescript // src/routes/api/ai/+server.ts export const POST: RequestHandler = async ({ request }) => { const { prompt } = await request.json(); const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: prompt }, }); return new Response(JSON.stringify({ content: result.content })); }; ``` ### Express.js ```bash npm install @juspay/neurolink express ``` ```typescript const app = express(); const neurolink = new NeuroLink(); app.post("/api/generate", async (req, res) => { const result = await neurolink.generate({ input: { text: req.body.prompt }, }); res.json({ content: result.content }); }); app.listen(3000); ``` ## Docker Setup ```dockerfile # Dockerfile FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run build EXPOSE 3000 CMD ["npm", "start"] ``` ```yaml # docker-compose.yml version: "3.8" services: neurolink-app: build: . ports: - "3000:3000" environment: - GOOGLE_AI_API_KEY=${GOOGLE_AI_API_KEY} - OPENAI_API_KEY=${OPENAI_API_KEY} volumes: - .env:/app/.env ``` ## Security Considerations ### Environment Variables ```bash # Never commit API keys to version control echo ".env" >> .gitignore # Use environment-specific files cp .env .env.example # Remove actual keys from .env.example ``` ### Production Deployment ```bash # Use secure secret management # AWS: AWS Secrets Manager # Azure: Azure Key Vault # Google Cloud: Secret Manager # Kubernetes: Secrets # Example with environment variables export GOOGLE_AI_API_KEY="$(cat /secrets/google-ai-key)" export OPENAI_API_KEY="$(cat /secrets/openai-key)" ``` ## Troubleshooting ### Common Issues **Node.js version error:** ```bash # Update Node.js to 18+ nvm install 18 nvm use 18 ``` **Permission errors on Linux/macOS:** ```bash # Fix npm permissions sudo chown -R $(whoami) ~/.npm ``` **TypeScript errors:** ```bash # Install type definitions npm install -D @types/node typescript ``` **Import/export errors:** ```bash # Ensure package.json has "type": "module" echo '"type": "module"' >> package.json ``` ### Getting Help 1. **Check our [Troubleshooting Guide](/docs/reference/troubleshooting)** 2. **Review [FAQ](/docs/reference/faq)** 3. **Search [GitHub Issues](https://github.com/juspay/neurolink/issues)** 4. **Create new issue** with: - Node.js version (`node --version`) - Operating system - Error message - Steps to reproduce ## Verification Checklist - [ ] Node.js 18+ installed - [ ] NeuroLink package installed or accessible via npx - [ ] API keys configured in `.env` file - [ ] `neurolink status` shows working providers - [ ] Basic generation command works - [ ] TypeScript support (if needed) - [ ] Framework integration (if applicable) ## Next Steps 1. **[Quick Start](/docs/getting-started/quick-start)** - Test your installation 2. **[Provider Setup](/docs/getting-started/provider-setup)** - Configure AI providers 3. **[CLI Commands](/docs/cli/commands)** - Learn available commands 4. **[Examples](/docs/examples/basic-usage)** - See implementation patterns --- ## Environment Variables Configuration Guide # Environment Variables Configuration Guide This guide provides comprehensive setup instructions for all AI providers supported by NeuroLink. The CLI automatically loads environment variables from `.env` files, making configuration seamless. ## Quick Setup ### Automatic .env Loading The **CLI** loads environment variables from the `.env` file in your current directory (or from the file named by `DOTENV_CONFIG_PATH`) at startup: ```bash # Create .env file (loaded by the CLI) echo 'OPENAI_API_KEY="sk-your-key"' > .env echo 'AWS_ACCESS_KEY_ID="your-key"' >> .env # Test configuration npx @juspay/neurolink status ``` The **SDK does not** read `.env` when it is imported. A library must not pick up files from whatever directory the host process happens to run in — a cloned repository's `.env` could otherwise set `ANTHROPIC_BASE_URL` and send your real key to a host of its choosing. An application that wants the CLI's behaviour opts in explicitly, either way: ```typescript await loadDotenv(); // same rules as the CLI, see below const neurolink = new NeuroLink(); ``` ```bash NEUROLINK_DOTENV=1 node app.js # the SDK loads .env at import ``` **Endpoint overrides need a trustworthy file.** dotenv never overrides a variable that is already set, but it sets every one that is not — including the variables that decide _where_ a request goes: every provider `*_BASE_URL` / `*_ENDPOINT(S)` variable, the `NEUROLINK_*_DIR` directories and `DOTENV_CONFIG_PATH`. For exactly those names the `.env` file must be owned by the current user and must not be group- or world-writable; otherwise they are removed again and named in a stderr line (`Refused 1 endpoint override(s) from … ANTHROPIC_BASE_URL`). When they are kept, a one-line notice lists them (`.env at … set endpoint override(s): ANTHROPIC_BASE_URL`), with a reminder when the file is outside your home directory. Export such a variable in your shell to use it regardless. | Variable | Effect | | -------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | `NEUROLINK_DOTENV=0` | Disable `.env` loading everywhere (CLI included). | | `NEUROLINK_DOTENV=1` | Make the SDK load `.env` when imported. Must be set in the real environment — it cannot come from the file it enables. | | `DOTENV_CONFIG_PATH` | Load this file instead of `./.env`. `DOTENV_CONFIG_PATH=/dev/null` is the documented way to run a test with no `.env` at all. | ### Project MCP configuration (`.mcp-config.json`) A project `.mcp-config.json` names commands to run and URLs to connect to, so it is treated like `.env` — a directory is not a trust boundary: - The **SDK** never loads it from the working directory on its own. Pass `new NeuroLink({ mcp: { configPath: "./.mcp-config.json" } })` to name a file, or `mcp: { trustProjectConfig: true }` for a directory you control. - The **CLI** loads it only after you have trusted that exact content: the file's SHA-256 is recorded in `~/.neurolink/trusted-mcp-configs.json` (mode `0600`). In a terminal you are shown the servers and asked; non-interactively the command refuses with exit status 1 until you decide. | Variable / flag | Effect | | ------------------------------ | ------------------------------------------------------------------------------------- | | `--trust-mcp-config` | Trust the working directory's `.mcp-config.json` as it is now, and remember its hash. | | `NEUROLINK_TRUST_MCP_CONFIG=1` | Same as the flag, for non-interactive runs (CI). | | `NEUROLINK_TRUST_MCP_CONFIG=0` | Run without the project config. | | `NEUROLINK_SKIP_MCP=true` | Skip MCP initialisation entirely (built-in and external servers alike). | See [MCP Integration](/docs/mcp/integration) for what the file may contain and how `${VAR}` references, the stdio environment and transport URLs are checked. ### Manual Export (Also Supported) ```bash export OPENAI_API_KEY="sk-your-key" export AWS_ACCESS_KEY_ID="your-key" npx @juspay/neurolink status ``` ## ️ Enterprise Configuration Management ### **✨ NEW: Automatic Backup System** ```bash # Configure backup settings NEUROLINK_BACKUP_ENABLED=true # Enable automatic backups (default: true) NEUROLINK_BACKUP_RETENTION=30 # Days to keep backups (default: 30) NEUROLINK_BACKUP_DIRECTORY=.neurolink.backups # Backup directory (default: .neurolink.backups) # Config validation settings NEUROLINK_VALIDATION_STRICT=false # Strict validation mode (default: false) NEUROLINK_VALIDATION_WARNINGS=true # Show validation warnings (default: true) # Provider status monitoring NEUROLINK_PROVIDER_STATUS_CHECK=true # Monitor provider availability (default: true) NEUROLINK_PROVIDER_TIMEOUT=30000 # Provider timeout in ms (default: 30000) ``` ### **Interface Configuration** ```bash # MCP Registry settings NEUROLINK_REGISTRY_CACHE_TTL=300 # Cache TTL in seconds (default: 300) NEUROLINK_REGISTRY_AUTO_DISCOVERY=true # Auto-discover MCP servers (default: true) NEUROLINK_REGISTRY_STATS_ENABLED=true # Enable registry statistics (default: true) # Execution context settings NEUROLINK_DEFAULT_TIMEOUT=30000 # Default execution timeout (default: 30000) NEUROLINK_DEFAULT_RETRIES=3 # Default retry count (default: 3) NEUROLINK_CONTEXT_LOGGING=info # Context logging level (default: info) ``` ### **Performance & Optimization** ```bash # Tool execution settings NEUROLINK_TOOL_EXECUTION_TIMEOUT=1000 # Tool execution timeout in ms (default: 1000) NEUROLINK_PIPELINE_TIMEOUT=22000 # Pipeline execution timeout (default: 22000) NEUROLINK_CACHE_ENABLED=true # Enable execution caching (default: true) # Error handling NEUROLINK_AUTO_RESTORE_ENABLED=true # Enable auto-restore on config failures (default: true) NEUROLINK_ERROR_RECOVERY_ATTEMPTS=3 # Error recovery attempts (default: 3) NEUROLINK_GRACEFUL_DEGRADATION=true # Enable graceful degradation (default: true) ``` ## 🆕 AI Enhancement Features ### Basic Enhancement Configuration ```bash # AI response quality evaluation model (optional) NEUROLINK_EVALUATION_MODEL="gemini-2.5-flash" ``` **Description**: Configures the AI model used for response quality evaluation when `--enable-evaluation` flag is used. Uses Google AI's fast Gemini 2.5 Flash model for quick quality assessment. **Supported Models**: - `gemini-2.5-flash` (default) - Fast evaluation processing - `gemini-2.5-pro` - More detailed evaluation (slower) **Usage**: ```bash # Enable evaluation with default model npx @juspay/neurolink generate "prompt" --enable-evaluation # Enable both analytics and evaluation npx @juspay/neurolink generate "prompt" --enable-analytics --enable-evaluation ``` ## Universal Evaluation System (Advanced) ### Primary Configuration ```bash # Primary evaluation provider NEUROLINK_EVALUATION_PROVIDER="google-ai" # Default: google-ai # Evaluation performance mode NEUROLINK_EVALUATION_MODE="fast" # Options: fast, balanced, quality ``` **NEUROLINK_EVALUATION_PROVIDER**: Primary AI provider for evaluation - **Options**: `google-ai`, `openai`, `anthropic`, `vertex`, `bedrock`, `azure`, `ollama`, `huggingface`, `mistral` - **Default**: `google-ai` - **Usage**: Determines which AI provider performs the quality evaluation **NEUROLINK_EVALUATION_MODE**: Performance vs quality trade-off - **Options**: `fast` (cost-effective), `balanced` (optimal), `quality` (highest accuracy) - **Default**: `fast` - **Usage**: Selects appropriate model for the provider (e.g., gemini-2.5-flash vs gemini-2.5-pro) ### Fallback Configuration ```bash # Enable automatic fallback when primary provider fails NEUROLINK_EVALUATION_FALLBACK_ENABLED="true" # Default: true # Fallback provider order (comma-separated) NEUROLINK_EVALUATION_FALLBACK_PROVIDERS="openai,anthropic,vertex,bedrock" ``` **NEUROLINK_EVALUATION_FALLBACK_ENABLED**: Enable intelligent fallback system - **Options**: `true`, `false` - **Default**: `true` - **Usage**: When enabled, automatically tries backup providers if primary fails **NEUROLINK_EVALUATION_FALLBACK_PROVIDERS**: Backup provider order - **Format**: Comma-separated provider names - **Default**: `openai,anthropic,vertex,bedrock` - **Usage**: Defines the order of providers to try if primary fails ### Performance Tuning ```bash # Evaluation timeout (milliseconds) NEUROLINK_EVALUATION_TIMEOUT="10000" # Default: 10000 (10 seconds) # Maximum tokens for evaluation response NEUROLINK_EVALUATION_MAX_TOKENS="500" # Default: 500 # Temperature for consistent evaluation NEUROLINK_EVALUATION_TEMPERATURE="0.1" # Default: 0.1 (low for consistency) # Retry attempts for failed evaluations NEUROLINK_EVALUATION_RETRY_ATTEMPTS="2" # Default: 2 ``` **Performance Variables**: - **TIMEOUT**: Maximum time to wait for evaluation (prevents hanging) - **MAX_TOKENS**: Limits evaluation response length (controls cost) - **TEMPERATURE**: Lower values = more consistent scoring - **RETRY_ATTEMPTS**: Number of retry attempts for transient failures ### Cost Optimization ```bash # Prefer cost-effective models and providers NEUROLINK_EVALUATION_PREFER_CHEAP="true" # Default: true # Maximum cost per evaluation (USD) NEUROLINK_EVALUATION_MAX_COST_PER_EVAL="0.01" # Default: $0.01 ``` **NEUROLINK_EVALUATION_PREFER_CHEAP**: Cost optimization preference - **Options**: `true`, `false` - **Default**: `true` - **Usage**: When enabled, prioritizes cheaper providers and models **NEUROLINK_EVALUATION_MAX_COST_PER_EVAL**: Cost limit per evaluation - **Format**: Decimal number (USD) - **Default**: `0.01` ($0.01) - **Usage**: Prevents expensive evaluations, switches to cheaper providers if needed ### Complete Universal Evaluation Example ```bash # Comprehensive evaluation configuration NEUROLINK_EVALUATION_PROVIDER="google-ai" NEUROLINK_EVALUATION_MODEL="gemini-2.5-flash" NEUROLINK_EVALUATION_MODE="balanced" NEUROLINK_EVALUATION_FALLBACK_ENABLED="true" NEUROLINK_EVALUATION_FALLBACK_PROVIDERS="openai,anthropic,vertex" NEUROLINK_EVALUATION_TIMEOUT="15000" NEUROLINK_EVALUATION_MAX_TOKENS="750" NEUROLINK_EVALUATION_TEMPERATURE="0.2" NEUROLINK_EVALUATION_PREFER_CHEAP="false" NEUROLINK_EVALUATION_MAX_COST_PER_EVAL="0.05" NEUROLINK_EVALUATION_RETRY_ATTEMPTS="3" ``` ### Testing Universal Evaluation ```bash # Test primary provider npx @juspay/neurolink generate "What is AI?" --enable-evaluation --debug # Test with custom domain npx @juspay/neurolink generate "Fix this Python code" --enable-evaluation --evaluation-domain "Python expert" # Test Lighthouse-style evaluation npx @juspay/neurolink generate "Business analysis" --lighthouse-style --evaluation-domain "Business consultant" ``` ---------- | ------------------------------- | ---------------------------------- | | `HTTPS_PROXY` | Proxy server for HTTPS requests | `http://proxy.company.com:8080` | | `HTTP_PROXY` | Proxy server for HTTP requests | `http://proxy.company.com:8080` | | `NO_PROXY` | Domains to bypass proxy | `localhost,127.0.0.1,.company.com` | The shared HTTP proxy fetch accepts comma- or whitespace-separated `NO_PROXY` entries. Entries are case-insensitive: `*` bypasses all; `example.com`, `.example.com` and `*.example.com` cover the host and its subdomains; `example.com:8443` restricts a match to that effective port (HTTP defaults to 80, HTTPS to 443). One trailing dot is normalized for domain names. IPv4/IPv6 literals match exactly, including `[::1]:8080`; IPv4 CIDR entries apply only to literal IPv4 targets, and IPv6 CIDR is unsupported. Dot-only entries (`.` or `..`) match nothing. These rules apply to request paths that use NeuroLink's HTTP proxy fetch. Native AWS handlers, Gemini Live WebSockets and Vertex ADC token requests use separate transports/dependency rules. See [Enterprise & Proxy Setup](/docs/deployment/enterprise-proxy) for those limits. The legacy AWS proxy selector uses a smaller comma-separated matcher; it supports exact hosts, leading-dot subdomain suffixes and `*`, without the full port/wildcard/CIDR syntax. It is not automatically injected into the native Bedrock constructors. ### Authenticated Proxy ```bash # Proxy with username/password authentication HTTPS_PROXY="http://username:password@proxy.company.com:8080" HTTP_PROXY="http://username:password@proxy.company.com:8080" ``` **All NeuroLink providers automatically use proxy settings when configured.** **For detailed proxy setup** → See [Enterprise & Proxy Setup Guide](/docs/deployment/enterprise-proxy) ## Provider Configuration ### 1. OpenAI #### Required Variables ```bash OPENAI_API_KEY="sk-proj-your-openai-api-key" ``` #### Optional Variables ```bash OPENAI_MODEL="gpt-4o-mini" # Default: gpt-4o-mini OPENAI_BASE_URL="https://api.openai.com" # Default: OpenAI API ``` #### How to Get OpenAI API Key 1. Visit [OpenAI Platform](https://platform.openai.com) 2. Sign up or log in to your account 3. Navigate to **API Keys** section 4. Click **Create new secret key** 5. Copy the key (starts with `sk-proj-` or `sk-`) 6. Add billing information if required #### Supported Models Examples, not the full list. The [OpenAI guide](/docs/getting-started/providers/openai) lists every model the SDK names, including the GPT-6 and `gpt-5.4-nano` models. - `gpt-5.4` - GPT-5.4 model - `gpt-5.4-mini` - Faster, cost-effective GPT-5.4 option - `gpt-4o-mini` (default) - Cost-effective, fast - `gpt-4o` - Previous generation multimodal model - `gpt-4-turbo` - High-performance model - `gpt-3.5-turbo` - Legacy cost-effective option With no model set, NeuroLink uses the explicit `model` option, then `OPENAI_MODEL`, then the default in the model configuration (`MODEL_CONFIG_URL`, otherwise the repository's `config/models.json`), then the registry default `gpt-4o-mini`. Constructing `OpenAIProvider` directly with none of these falls back to `gpt-5.4`. --- ### 2. Amazon Bedrock #### Required Variables ```bash AWS_ACCESS_KEY_ID="AKIA..." AWS_SECRET_ACCESS_KEY="your-secret-key" AWS_REGION="us-east-1" ``` #### Model Configuration (⚠️ Critical) ```bash # Use full inference profile ARN for Anthropic models BEDROCK_MODEL="arn:aws:bedrock:us-east-2::inference-profile/us.anthropic.claude-3-7-sonnet-20250219-v1:0" # OR use simple model names for non-Anthropic models BEDROCK_MODEL="amazon.titan-text-express-v1" ``` #### Optional Variables ```bash AWS_SESSION_TOKEN="IQoJb3..." # For temporary credentials ``` #### How to Get AWS Credentials 1. Sign up for [AWS Account](https://aws.amazon.com) 2. Navigate to **IAM Console** 3. Create new user with programmatic access 4. Attach policy: `AmazonBedrockFullAccess` 5. Download access key and secret key 6. **Important**: Request model access in Bedrock console #### Bedrock Model Access Setup 1. Go to [AWS Bedrock Console](https://console.aws.amazon.com/bedrock) 2. Navigate to **Model access** 3. Click **Request model access** 4. Select desired models (Claude, Titan, etc.) 5. Submit request and wait for approval #### Supported Models - **Anthropic Claude**: - `arn:aws:bedrock:::inference-profile/us.anthropic.claude-3-7-sonnet-20250219-v1:0` - `arn:aws:bedrock:::inference-profile/us.anthropic.claude-3-5-sonnet-20241022-v2:0` - **Amazon Titan**: - `amazon.titan-text-express-v1` - `amazon.titan-text-lite-v1` --- ### 3. Google Vertex AI Google Vertex AI supports **three authentication methods**. Choose the one that fits your deployment: #### Method 1: Service Account File (Recommended) ```bash GOOGLE_APPLICATION_CREDENTIALS="/absolute/path/to/service-account.json" GOOGLE_VERTEX_PROJECT="your-gcp-project-id" GOOGLE_VERTEX_LOCATION="us-central1" ``` #### Method 2: Service Account JSON String ```bash GOOGLE_SERVICE_ACCOUNT_KEY='{"type":"service_account","project_id":"your-project",...}' GOOGLE_VERTEX_PROJECT="your-gcp-project-id" GOOGLE_VERTEX_LOCATION="us-central1" ``` #### Method 3: Individual Environment Variables ```bash GOOGLE_AUTH_CLIENT_EMAIL="service-account@your-project.iam.gserviceaccount.com" GOOGLE_AUTH_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0B..." GOOGLE_VERTEX_PROJECT="your-gcp-project-id" GOOGLE_VERTEX_LOCATION="us-central1" ``` #### Optional Variables ```bash VERTEX_MODEL="gemini-2.5-pro" # Default: gemini-2.5-pro ``` #### How to Set Up Google Vertex AI 1. Create [Google Cloud Project](https://console.cloud.google.com) 2. Enable **Vertex AI API** 3. Create **Service Account**: - Go to **IAM & Admin > Service Accounts** - Click **Create Service Account** - Grant **Vertex AI User** role - Generate and download JSON key file 4. Set `GOOGLE_APPLICATION_CREDENTIALS` to the JSON file path #### Supported Models - `gemini-2.5-pro` (default) - Most capable model - `gemini-2.5-flash` - Faster responses - `claude-3-5-sonnet@20241022` - Claude via Vertex AI --- ### 4. Anthropic (Direct) Anthropic supports two authentication methods: **API key** (traditional) and **OAuth token** (for Claude subscription users). #### Method 1: API Key (Traditional) ##### Required Variables ```bash ANTHROPIC_API_KEY="sk-ant-api03-your-anthropic-key" ``` ##### Optional Variables ```bash ANTHROPIC_MODEL="claude-3-5-sonnet-20241022" # Default model ``` ##### How to Get Anthropic API Key 1. Visit [Anthropic Console](https://console.anthropic.com) 2. Sign up or log in 3. Navigate to **API Keys** 4. Click **Create Key** 5. Copy the key (starts with `sk-ant-api03-`) 6. Add billing information for usage #### Method 2: OAuth Token (Claude Subscription) Use OAuth authentication to access Claude models through a Claude Pro, Max, or Team subscription instead of pay-per-token API billing. ##### Required Variables ```bash # Either of these (ANTHROPIC_OAUTH_TOKEN takes precedence) ANTHROPIC_OAUTH_TOKEN="your-oauth-access-token" CLAUDE_OAUTH_TOKEN="your-oauth-access-token" ``` The OAuth token value can be a plain access token string or a JSON object with the following fields: ```json { "accessToken": "your-access-token", "refreshToken": "your-refresh-token", "expiresAt": 1735689600000 } ``` Where `expiresAt` is the token expiry time in Unix milliseconds. ##### Optional Variables ```bash ANTHROPIC_MODEL="claude-3-5-sonnet-20241022" # Default model ANTHROPIC_SUBSCRIPTION_TIER="pro" # Subscription tier override ``` `ANTHROPIC_SUBSCRIPTION_TIER` controls which models and rate limits are available. Valid values: | Tier | Description | | -------- | ----------------------------------------------- | | `free` | Free tier with limited access | | `pro` | Claude Pro subscription (default for OAuth) | | `max` | Claude Max subscription | | `max_5` | Claude Max with 5x usage | | `max_20` | Claude Max with 20x usage | | `api` | Standard API key access (default without OAuth) | If `ANTHROPIC_SUBSCRIPTION_TIER` is not set, the tier is auto-detected: `pro` when using OAuth, `api` when using an API key. #### Environment Variables Reference | Variable | Required | Default | Description | | -------------------------------- | -------- | ---------------------------------- | -------------------------------------------------------------------------- | | `ANTHROPIC_API_KEY` | \* | - | Anthropic API key (required if not using OAuth) | | `ANTHROPIC_OAUTH_TOKEN` | \* | - | OAuth access token, plain string or JSON (required if not using API key) | | `CLAUDE_OAUTH_TOKEN` | \* | - | Alternative OAuth token env var (same format as `ANTHROPIC_OAUTH_TOKEN`) | | `ANTHROPIC_MODEL` | No | `claude-3-5-sonnet-20241022` | Default model to use | | `ANTHROPIC_SUBSCRIPTION_TIER` | No | Auto-detected (`pro` or `api`) | Subscription tier override: `free`, `pro`, `max`, `max_5`, `max_20`, `api` | | `ANTHROPIC_ENABLE_BETA_FEATURES` | No | `true` (OAuth) / `false` (API key) | Enable Anthropic beta headers (OAuth beta, extended thinking) | | `ANTHROPIC_OAUTH_REFRESH_TOKEN` | No | - | OAuth refresh token (used for automatic token renewal) | | `ANTHROPIC_AUTH_METHOD` | No | Auto-detected | Force auth method: `api_key` or `oauth` | \* One of `ANTHROPIC_API_KEY`, `ANTHROPIC_OAUTH_TOKEN`, or `CLAUDE_OAUTH_TOKEN` must be set. #### Supported Models - `claude-3-5-sonnet-20241022` (default) - Latest Claude - `claude-3-haiku-20240307` - Fast, cost-effective - `claude-3-opus-20240229` - Most capable (if available) --- ### 5. Google AI Studio #### Required Variables ```bash GOOGLE_AI_API_KEY="AIza-your-google-ai-api-key" ``` #### Optional Variables ```bash GOOGLE_AI_MODEL="gemini-2.5-pro" # Default model ``` #### How to Get Google AI Studio API Key 1. Visit [Google AI Studio](https://aistudio.google.com) 2. Sign in with your Google account 3. Navigate to **API Keys** section 4. Click **Create API Key** 5. Copy the key (starts with `AIza`) 6. Note: Google AI Studio provides free tier with generous limits #### Supported Models - `gemini-2.5-pro` (default) - Latest Gemini Pro - `gemini-2.0-flash` - Fast, efficient responses --- ### 6. Azure OpenAI #### Required Variables ```bash AZURE_OPENAI_API_KEY="your-azureOpenai-key" AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/" AZURE_OPENAI_DEPLOYMENT_ID="your-deployment-name" ``` #### Optional Variables ```bash AZURE_MODEL="gpt-4o" # Default: gpt-4o AZURE_API_VERSION="2024-02-15-preview" # Default API version ``` #### How to Set Up Azure OpenAI 1. Create [Azure Account](https://azure.microsoft.com) 2. Apply for **Azure OpenAI Service** access 3. Create **Azure OpenAI Resource**: - Go to Azure Portal - Search "OpenAI" - Create new OpenAI resource 4. **Deploy Model**: - Go to Azure OpenAI Studio - Navigate to **Deployments** - Create deployment with desired model 5. Get credentials from **Keys and Endpoint** section #### Supported Models - `gpt-4o` (default) - Latest GPT-4 Optimized - `gpt-4` - Standard GPT-4 - `gpt-35-turbo` - Cost-effective option --- ### 7. Hugging Face #### Required Variables ```bash HUGGINGFACE_API_KEY="hf_your_huggingface_token" ``` #### Optional Variables ```bash HUGGINGFACE_MODEL="Qwen/Qwen2.5-72B-Instruct" # Default model HUGGINGFACE_BASE_URL="https://router.huggingface.co/v1" # Default endpoint ``` #### How to Get Hugging Face API Token 1. Visit [Hugging Face](https://huggingface.co) 2. Sign up or log in 3. Go to Settings → Access Tokens 4. Create new token with "read" scope 5. Copy token (starts with `hf_`) #### Supported Models Requests go to the unified router (`router.huggingface.co/v1`), which serves a curated set of ~140 models — **not** the whole Hub. An id absent from the router answers 400 "not supported by any provider you have enabled", which is why the legacy defaults (DialoGPT, GPT-2, GPT-Neo) no longer work. - `Qwen/Qwen2.5-72B-Instruct` (default) - tool-capable, strong multilingual - `meta-llama/Llama-3.1-8B-Instruct` - fastest of the served set, tool-capable - `meta-llama/Llama-3.3-70B-Instruct` - stronger general reasoning - `deepseek-ai/DeepSeek-V3` - highest quality of the served set - `Qwen/Qwen2.5-Coder-32B-Instruct` - code-focused - Any id listed by `GET https://router.huggingface.co/v1/models` --- ### 8. Ollama (Local AI) #### Required Variables None! Ollama runs locally. #### Optional Variables ```bash OLLAMA_BASE_URL="http://localhost:11434" # Default local server OLLAMA_MODEL="llama2" # Default model ``` #### How to Set Up Ollama 1. **Install Ollama**: - macOS: `brew install ollama` or download from [ollama.ai](https://ollama.ai) - Linux: `curl -fsSL https://ollama.ai/install.sh | sh` - Windows: Download installer from [ollama.ai](https://ollama.ai) 2. **Start Ollama Service**: ```bash ollama serve # Usually auto-starts ``` **Tip: To keep Ollama running in the background:** - macOS: `brew services start ollama` - Linux (user): `systemctl --user enable --now ollama` - Linux (system): `sudo systemctl enable --now ollama` 3. **Pull Models**: ```bash ollama pull llama2 ollama pull codellama ollama pull mistral ``` #### Supported Models - `llama2` (default) - Meta's Llama 2 - `codellama` - Code-specialized Llama - `mistral` - Mistral 7B - `vicuna` - Fine-tuned Llama - Any model from [Ollama Library](https://ollama.ai/library) --- ### 9. Mistral AI #### Required Variables ```bash MISTRAL_API_KEY="your_mistral_api_key" ``` #### Optional Variables ```bash MISTRAL_MODEL="mistral-small" # Default model MISTRAL_ENDPOINT="https://api.mistral.ai" # Default endpoint ``` #### How to Get Mistral AI API Key 1. Visit [Mistral AI Platform](https://mistral.ai) 2. Sign up for an account 3. Navigate to API Keys section 4. Generate new API key 5. Add billing information #### Supported Models - `mistral-tiny` - Fastest, most cost-effective - `mistral-small` (default) - Balanced performance - `mistral-medium` - Enhanced capabilities - `mistral-large` - Most capable model --- ### 10. LiteLLM 🆕 #### Required Variables ```bash LITELLM_BASE_URL="http://localhost:4000" # Local LiteLLM proxy (default) LITELLM_API_KEY="sk-anything" # API key for local proxy (any value works) ``` #### Optional Variables ```bash LITELLM_MODEL="gemini-2.5-pro" # Default model LITELLM_TIMEOUT="60000" # Request timeout (ms) ``` #### How to Use LiteLLM LiteLLM provides access to 100+ AI models through a unified proxy interface: 1. **Local Setup**: Run LiteLLM locally with your API keys (recommended) 2. **Self-Hosted**: Deploy your own LiteLLM proxy server 3. **Cloud Deployment**: Use cloud-hosted LiteLLM instances #### Available Models (Example Configuration) - `openai/gpt-4o` - OpenAI GPT-4 Optimized - `anthropic/claude-3-5-sonnet` - Anthropic Claude Sonnet - `google/gemini-2.0-flash` - Google Gemini Flash - `mistral/mistral-large` - Mistral Large model - Many more via [LiteLLM Providers](https://docs.litellm.ai/docs/providers) #### Benefits - **100+ Models**: Access to a broad range of AI providers through one interface - **Cost Optimization**: Automatic routing to cost-effective models - **Unified API**: OpenAI-compatible API for all models - **Load Balancing**: Automatic failover and load distribution - **Analytics**: Built-in usage tracking and monitoring --- ### 11. Amazon SageMaker 🆕 #### Required Variables ```bash AWS_ACCESS_KEY_ID="AKIA..." AWS_SECRET_ACCESS_KEY="your-aws-secret-key" AWS_REGION="us-east-1" SAGEMAKER_DEFAULT_ENDPOINT="your-endpoint-name" ``` #### Optional Variables ```bash SAGEMAKER_MODEL="custom-model-name" # Model identifier (default: sagemaker-model) SAGEMAKER_TIMEOUT="30000" # Request timeout in ms (default: 30000) SAGEMAKER_MAX_RETRIES="3" # Retry attempts (default: 3) AWS_SESSION_TOKEN="IQoJb3..." # For temporary credentials SAGEMAKER_CONTENT_TYPE="application/json" # Request content type (default: application/json) SAGEMAKER_ACCEPT="application/json" # Response accept type (default: application/json) ``` #### How to Set Up Amazon SageMaker Amazon SageMaker allows you to deploy and use your own custom trained models: 1. **Deploy Your Model to SageMaker**: - Train your model using SageMaker Training Jobs - Deploy model to a SageMaker Real-time Endpoint - Note the endpoint name for configuration 2. **Set Up AWS Credentials**: - Use IAM user with `sagemaker:InvokeEndpoint` permission - Or use IAM role for EC2/Lambda/ECS deployments - Configure AWS CLI: `aws configure` 3. **Configure NeuroLink**: ```bash export AWS_ACCESS_KEY_ID="your-access-key" export AWS_SECRET_ACCESS_KEY="your-secret-key" export AWS_REGION="us-east-1" export SAGEMAKER_DEFAULT_ENDPOINT="my-model-endpoint" ``` 4. **Test Connection**: ```bash npx @juspay/neurolink sagemaker status npx @juspay/neurolink sagemaker test my-endpoint ``` #### How to Get AWS Credentials for SageMaker 1. **Create IAM User**: - Go to [AWS IAM Console](https://console.aws.amazon.com/iam) - Create new user with **Programmatic access** - Attach the following policy: ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["sagemaker:InvokeEndpoint"], "Resource": "arn:aws:sagemaker:*:*:endpoint/*" } ] } ``` 2. **Download Credentials**: - Save Access Key ID and Secret Access Key - Set as environment variables #### Supported Models SageMaker supports **any custom model** you deploy: - **Custom Fine-tuned Models** - Your domain-specific models - **Foundation Model Endpoints** - Large language models deployed via SageMaker - **Multi-model Endpoints** - Multiple models behind single endpoint - **Serverless Endpoints** - Auto-scaling model deployments #### Model Deployment Types - **Real-time Inference** - Low-latency model serving (recommended) - **Batch Transform** - Batch processing (not supported by NeuroLink) - **Serverless Inference** - Pay-per-request model serving - **Multi-model Endpoints** - Host multiple models efficiently #### Benefits - **️ Custom Models** - Deploy and use your own trained models - ** Cost Control** - Pay only for inference usage, auto-scaling available - ** Enterprise Security** - Full control over model infrastructure and data - **⚡ Performance** - Dedicated compute resources with predictable latency - ** Global Deployment** - Available in all major AWS regions - ** Monitoring** - Built-in CloudWatch metrics and logging #### CLI Commands ```bash # Check SageMaker configuration and endpoint status npx @juspay/neurolink sagemaker status # Validate connection to specific endpoint npx @juspay/neurolink sagemaker validate # Test inference with specific endpoint npx @juspay/neurolink sagemaker test my-endpoint # Show current configuration npx @juspay/neurolink sagemaker config # Performance benchmark npx @juspay/neurolink sagemaker benchmark my-endpoint # List available endpoints (requires AWS CLI) npx @juspay/neurolink sagemaker list-endpoints # Interactive setup wizard npx @juspay/neurolink sagemaker setup ``` #### Environment Variables Reference | Variable | Required | Default | Description | | ---------------------------- | -------- | ---------------- | -------------------------------------------- | | `AWS_ACCESS_KEY_ID` | ✅ | - | AWS access key for authentication | | `AWS_SECRET_ACCESS_KEY` | ✅ | - | AWS secret key for authentication | | `AWS_REGION` | ✅ | us-east-1 | AWS region where endpoint is deployed | | `SAGEMAKER_DEFAULT_ENDPOINT` | ✅ | - | SageMaker endpoint name | | `SAGEMAKER_TIMEOUT` | ❌ | 30000 | Request timeout in milliseconds | | `SAGEMAKER_MAX_RETRIES` | ❌ | 3 | Number of retry attempts for failed requests | | `AWS_SESSION_TOKEN` | ❌ | - | Session token for temporary credentials | | `SAGEMAKER_MODEL` | ❌ | sagemaker-model | Model identifier for logging | | `SAGEMAKER_CONTENT_TYPE` | ❌ | application/json | Request content type | | `SAGEMAKER_ACCEPT` | ❌ | application/json | Response accept type | #### Production Considerations - ** Security**: Use IAM roles instead of access keys when possible - ** Monitoring**: Enable CloudWatch logging for your endpoints - ** Cost Optimization**: Use auto-scaling and serverless options - ** Multi-Region**: Deploy endpoints in multiple regions for redundancy - **⚡ Performance**: Choose appropriate instance types for your workload --- ### 12. DeepSeek #### Required Variables ```bash DEEPSEEK_API_KEY="sk-your-deepseek-api-key" ``` #### Optional Variables ```bash DEEPSEEK_MODEL="deepseek-chat" # Default: deepseek-chat (use deepseek-reasoner for R1) DEEPSEEK_BASE_URL="https://api.deepseek.com" # Default: DeepSeek API ``` #### How to Get DeepSeek API Key 1. Visit [DeepSeek Platform](https://platform.deepseek.com/api_keys) 2. Sign up or log in to your account 3. Navigate to **API Keys** section 4. Click **Create API Key** 5. Copy the key #### Supported Models - `deepseek-chat` (default) - DeepSeek V3, high-quality general chat - `deepseek-reasoner` - DeepSeek R1, extended chain-of-thought reasoning --- ### 13. NVIDIA NIM #### Required Variables ```bash NVIDIA_NIM_API_KEY="nvapi-your-nvidia-api-key" ``` #### Optional Variables ```bash NVIDIA_NIM_MODEL="openai/gpt-oss-20b" # Default model NVIDIA_NIM_BASE_URL="https://integrate.api.nvidia.com/v1" # Default: NVIDIA cloud API (override for self-hosted NIM) ``` #### NIM-Specific Extras (rarely needed) ```bash # Sampling extras passed as request body extensions NVIDIA_NIM_TOP_K= # Integer, -1 = disabled (default) NVIDIA_NIM_MIN_P= # Float, 0 = disabled (default) NVIDIA_NIM_REPETITION_PENALTY= # Float, 1.0 = disabled (default) NVIDIA_NIM_MIN_TOKENS= # Integer, 0 = disabled (default) NVIDIA_NIM_CHAT_TEMPLATE= # Override model chat template string (advanced) ``` #### How to Get NVIDIA NIM API Key 1. Visit [NVIDIA Build](https://build.nvidia.com/) 2. Sign in with your NVIDIA developer account 3. Open **Settings → API Keys** 4. Generate a new API key (Bearer token) #### Supported Models - `openai/gpt-oss-20b` (default) - OpenAI gpt-oss 20B, 128K context, tool calling - Any model listed at [build.nvidia.com/models](https://build.nvidia.com/models) --- ### 14. LM Studio (Local) LM Studio is a local provider — no API key is required for standard installations. #### Optional Variables ```bash LM_STUDIO_BASE_URL="http://localhost:1234/v1" # Default: local LM Studio server LM_STUDIO_MODEL="" # Blank = auto-discover from /v1/models # LM_STUDIO_API_KEY= # Only set when running behind an auth-proxying reverse-proxy ``` #### How to Set Up LM Studio 1. Install LM Studio from [lmstudio.ai](https://lmstudio.ai/) 2. Open LM Studio and download a model (e.g., Llama 3.2 3B Instruct) 3. Click **Local Server** → **Start Server** 4. The server starts at `http://localhost:1234/v1` by default 5. NeuroLink auto-discovers the loaded model; no `LM_STUDIO_MODEL` needed **Note:** `LM_STUDIO_API_KEY` is only needed if you run LM Studio behind an authenticating reverse-proxy. Vanilla local installs do not require an API key. --- ### 15. llama.cpp (Local) llama.cpp (llama-server) is a local provider — no API key is required for standard installations. #### Optional Variables ```bash LLAMACPP_BASE_URL="http://localhost:8080/v1" # Default: local llama-server LLAMACPP_MODEL="" # Blank = use whatever model llama-server has loaded # LLAMACPP_API_KEY= # Only set when running behind an auth-proxying reverse-proxy ``` #### How to Set Up llama.cpp 1. Build llama.cpp from source: [github.com/ggerganov/llama.cpp](https://github.com/ggerganov/llama.cpp#build) 2. Download a GGUF model file 3. Start llama-server: ```bash # Basic usage ./llama-server -m model.gguf --port 8080 # With tool/function-call support (required for MCP tools) ./llama-server -m model.gguf --port 8080 --jinja ``` 4. NeuroLink auto-discovers the loaded model; no `LLAMACPP_MODEL` needed **Note:** `LLAMACPP_API_KEY` is only needed if you run llama-server behind an authenticating reverse-proxy. Vanilla local installs do not require an API key. --- ### 16. OpenAI TTS OpenAI TTS uses the same `OPENAI_API_KEY` as the OpenAI LLM provider. No additional credentials are required. #### Required Variables ```bash OPENAI_API_KEY="sk-proj-your-openai-api-key" # Shared with the OpenAI LLM provider ``` #### How to Get the API Key See [OpenAI](#1-openai) above — the same key is used for both LLM and TTS. #### Supported Models - `tts-1` (default) - Optimized for speed - `tts-1-hd` - Optimized for audio quality --- ### 17. ElevenLabs TTS + STT #### Required Variables ```bash ELEVENLABS_API_KEY="your-elevenlabs-api-key" ``` One key serves the `elevenlabs` TTS handler, the `elevenlabs-stt` (Scribe) STT handler and `elevenlabs-music`. #### Optional Variables ```bash # API base URL including the /v1 prefix — for a proxy or a test stub. ELEVENLABS_BASE_URL="https://api.elevenlabs.io/v1" # Base URL for Scribe (speech-to-text) only; wins over ELEVENLABS_BASE_URL # for STT, so transcription can go through a different host than TTS. ELEVENLABS_STT_BASE_URL="https://api.elevenlabs.io/v1" ``` #### How to Get ElevenLabs API Key 1. Visit [ElevenLabs](https://elevenlabs.io) 2. Sign up or log in to your account 3. Navigate to **Profile → API Key** 4. Copy the key #### Supported Models - `eleven_multilingual_v2` (default) - Best quality, 29 languages - `eleven_v3` - Most expressive, 70+ languages, accepts `language` - `eleven_turbo_v2_5` - Low-latency streaming, 32 languages, accepts `language` - `eleven_flash_v2_5` - Fastest, suitable for real-time use, accepts `language` - `eleven_flash_v2`, `eleven_turbo_v2`, `eleven_monolingual_v1` - English variants - STT: `scribe_v2` (default), `scribe_v2_medical`; `scribe_v1` and `scribe_v1_experimental` are deprecated See the [ElevenLabs provider guide](/docs/getting-started/providers/elevenlabs) for formats (Opus 48 kHz for `ogg`/`opus`), speed clamping, retries and the Scribe STT options. --- ### 18. Deepgram STT #### Required Variables ```bash DEEPGRAM_API_KEY="your-deepgram-api-key" ``` #### Optional Variables ```bash # REST base URL (a proxy, a self-hosted Deepgram or a test stub). The live # stream uses the same host on the WebSocket scheme (https → wss). DEEPGRAM_BASE_URL="https://api.deepgram.com/v1" ``` #### How to Get Deepgram API Key 1. Visit [Deepgram Console](https://console.deepgram.com) 2. Sign up or log in to your account 3. Navigate to **API Keys** 4. Click **Create a New API Key** 5. Copy the key #### Supported Models - `nova-2` (default) - High accuracy, broad language support - `nova-3` - Latest, highest accuracy - `base` - Balanced accuracy and speed --- ### 19. Azure Speech Services (TTS + STT) Azure Speech Services provides both text-to-speech and speech-to-text through Microsoft Azure Cognitive Services. #### Required Variables ```bash AZURE_SPEECH_KEY="your-azure-speech-key" AZURE_SPEECH_REGION="eastus" # Azure region where your Speech resource is deployed ``` #### Optional Variables If you also use Google STT or Gemini Live alongside Azure, set the canonical Google credentials: ```bash GOOGLE_AI_API_KEY="AIza-your-google-ai-studio-key" # canonical # GEMINI_API_KEY="AIza-your-key" # alias (also accepted) # GOOGLE_API_KEY="AIza-your-key" # legacy alias (also accepted) # GOOGLE_APPLICATION_CREDENTIALS=/path/to/sa.json # service account (Google STT) ``` #### How to Set Up Azure Speech Services 1. Sign in to [Azure Portal](https://portal.azure.com) 2. Create a **Speech** resource under **Azure AI services** 3. Go to **Keys and Endpoint** in your Speech resource 4. Copy **Key 1** and note the **Location/Region** 5. Set `AZURE_SPEECH_KEY` and `AZURE_SPEECH_REGION` #### Supported Capabilities - **TTS**: Azure Neural TTS with 400+ voices across 140+ languages - **STT**: Azure Speech-to-Text with real-time and batch transcription #### Environment Variables Reference | Variable | Required | Default | Description | | --------------------- | -------- | ------- | --------------------------------------------------- | | `AZURE_SPEECH_KEY` | ✅ | - | Azure Speech Services API key | | `AZURE_SPEECH_REGION` | ✅ | - | Azure region (e.g., `eastus`, `westeurope`) | | `GOOGLE_AI_API_KEY` | ❌ | - | Canonical Google API key (Google STT / Gemini Live) | | `GEMINI_API_KEY` | ❌ | - | Accepted alias for `GOOGLE_AI_API_KEY` | | `GOOGLE_API_KEY` | ❌ | - | Legacy alias for `GOOGLE_AI_API_KEY` | | `ELEVENLABS_API_KEY` | ❌ | - | ElevenLabs key, if using ElevenLabs alongside | | `DEEPGRAM_API_KEY` | ❌ | - | Deepgram key, if using Deepgram alongside | --- ### 20. Speech-to-Text: `transcribe()` and the built-in Whistle engine `neurolink.transcribe()`, `neurolink.transcribeStream()`, the `neurolink transcribe` CLI command, the transcription server routes and audio attached to `generate()` all choose their engine the same way: 1. `NEUROLINK_STT_PROVIDER`, when it names a known STT provider, alias or named endpoint (an unknown name is logged and ignored); 2. otherwise the first **configured** provider in descriptor order — `whisper` (OpenAI-compatible), `deepgram`, `elevenlabs-stt`, `google-stt`, `azure-stt` — configured by the keys in sections 1, 17, 18 and 19 above; 3. otherwise **Whistle**, the built-in local engine, which needs no key. #### Engine selection ```bash # Default STT provider (name or alias: whisper, deepgram, scribe, google-stt, # azure-stt, whistle, or a NEUROLINK_STT_ENDPOINTS name). NEUROLINK_STT_PROVIDER="deepgram" # Model for the provider NEUROLINK_STT_PROVIDER / the default rule picked. # Not applied to a provider named explicitly in a call or with --provider. NEUROLINK_STT_MODEL="nova-3" # Default language code; omit it, or set "auto", to let the engine detect it. NEUROLINK_STT_LANGUAGE="en" ``` #### OpenAI-compatible STT (`whisper`) ```bash # Key for the /audio/transcriptions endpoint. Only the default base URL # (api.openai.com) falls back to OPENAI_API_KEY; a custom OPENAI_STT_BASE_URL # never receives it, and a NEUROLINK_STT_ENDPOINTS entry sends its own # "apiKey" or no key at all. OPENAI_STT_API_KEY="sk-..." # Any OpenAI-compatible /audio/transcriptions server (vLLM, LiteLLM, a # self-hosted Whisper / Qwen3-ASR wrapper). Default: https://api.openai.com/v1 OPENAI_STT_BASE_URL="http://localhost:8004/v1" OPENAI_STT_MODEL="whisper-1" # default model OPENAI_STT_TIMEOUT_MS="120000" # request timeout for long recordings # Several self-hosted engines at once, each a provider of its own (usable as # each other's fallback or second opinion). Keys are the provider names; a # name that collides with a shipped provider is ignored. # Per endpoint: baseURL (required), apiKey, model, timeoutMs, and for a server # that can take a language prior / answer with a language verdict only (the # IndicConformer wrapper): priorLanguageForm ("auto-{lang}") and lidModel. NEUROLINK_STT_ENDPOINTS='{"qwen-asr":{"baseURL":"http://gpu-box:8004/v1","model":"qwen3-asr"},"indic":{"baseURL":"http://gpu-box:8007/v1","model":"indic-conformer","priorLanguageForm":"auto-{lang}","lidModel":"indic-conformer-lid"}}' ``` #### Correction layer ```bash # Text provider and model for the correction rewrite, when a request names # none (a request's correction.rewrite.provider/model still wins). NEUROLINK_STT_REWRITE_PROVIDER="openai" NEUROLINK_STT_REWRITE_MODEL="gpt-4o-mini" # Text provider and model that render transcripts into other languages # (`output.languages`), when a request names none; unset, the rewrite's. NEUROLINK_STT_OUTPUT_PROVIDER="openai" NEUROLINK_STT_OUTPUT_MODEL="gpt-4o" ``` The dictionary guard uses whichever `decide` provider is configured (see the decision providers at the top of this page) and fails open without one. #### Whistle (built-in local engine) Whistle runs on this machine in WebAssembly. Its three files (about 17 MB, pinned Hugging Face revisions verified by SHA-256) ship inside the package under `models/whistle/`, so nothing is downloaded. A download happens only when that copy is missing, into `~/.neurolink/models/whistle`. ```bash # Where Whistle's files live. Precedence: credentials.stt.whistle.modelDir, # then NEUROLINK_WHISTLE_DIR, then $NEUROLINK_MODEL_DIR/whistle, then the # package's own models/whistle, then ~/.neurolink/models/whistle. NEUROLINK_WHISTLE_DIR="/opt/models/whistle" NEUROLINK_MODEL_DIR="/opt/models" # root for local model files # 0 / false / off / no forbids the fallback download (air-gapped hosts, CI). # With no copy anywhere Whistle then reports itself unconfigured. NEUROLINK_WHISTLE_AUTO_DOWNLOAD="0" # 1 / true / on / yes sends the request's vocabulary (dictionary terms # included) to the engine as keywords. Off by default: the engine can loop # on long keyword lists. The model name "whistle-keywords" does the same per # request. NEUROLINK_WHISTLE_KEYWORDS="1" ``` | Variable | Default | Description | | ---------------------------------------- | -------------------------------------- | --------------------------------------------------------------------------------------------- | | `NEUROLINK_STT_PROVIDER` | first configured, else Whistle | Default STT provider, alias or named endpoint | | `NEUROLINK_STT_MODEL` | provider default | Model for the env-chosen provider | | `NEUROLINK_STT_LANGUAGE` | `auto` | Default language; `auto` lets the engine detect | | `NEUROLINK_STT_ENDPOINTS` | - | JSON map of named OpenAI-compatible STT endpoints | | `NEUROLINK_STT_REWRITE_PROVIDER` | instance default | Text provider for the correction rewrite | | `NEUROLINK_STT_REWRITE_MODEL` | provider default | Model for the correction rewrite | | `NEUROLINK_STT_OUTPUT_PROVIDER` | the rewrite's provider | Text provider for output-language renderings | | `NEUROLINK_STT_OUTPUT_MODEL` | the rewrite's model | Model for output-language renderings | | `NEUROLINK_STT_REALTIME_PROFILES` | - | JSON map of profiles an OpenAI-Realtime client selects by `model` on `/v1/realtime` | | `NEUROLINK_STT_EVAL_LANGFUSE_PUBLIC_KEY` | - | With the secret key: export `POST /v1/evals/stt` batches and scores to this Langfuse project | | `NEUROLINK_STT_EVAL_LANGFUSE_SECRET_KEY` | - | Secret key of the evaluation Langfuse project | | `NEUROLINK_STT_EVAL_LANGFUSE_BASE_URL` | `https://cloud.langfuse.com` | Langfuse host for the evaluation export | | `NEUROLINK_STT_EVAL_DIR` | - (memory only) | Directory where `POST /v1/evals/stt` keeps one JSON-lines file per call, replayed on start | | `OPENAI_STT_API_KEY` | `OPENAI_API_KEY` (api.openai.com only) | Key for the OpenAI-compatible STT endpoint; a custom base URL never receives `OPENAI_API_KEY` | | `OPENAI_STT_PRIOR_LANGUAGE_FORM` | - | `language` template (`auto-{lang}`) that carries a language prior to a custom STT server | | `OPENAI_STT_LID_MODEL` | - | Model name the custom STT server runs in language-verdict-only mode (the batch probe) | | `OPENAI_STT_VOCABULARY_PROMPT` | on | Send dictionary terms as a "Names and terms used" prompt; `0` for servers that echo it | | `OPENAI_STT_BASE_URL` | `https://api.openai.com/v1` | OpenAI-compatible `/audio/transcriptions` base URL | | `OPENAI_STT_MODEL` | `whisper-1` | Default model for `whisper` | | `OPENAI_STT_TIMEOUT_MS` | handler default | Request timeout for `whisper` | | `DEEPGRAM_BASE_URL` | `https://api.deepgram.com/v1` | Deepgram REST base URL (stream uses the same host over `wss://`) | | `ELEVENLABS_STT_BASE_URL` | `ELEVENLABS_BASE_URL` | ElevenLabs Scribe base URL | | `NEUROLINK_WHISTLE_DIR` | see precedence above | Directory holding Whistle's files (default: the bundled copy) | | `NEUROLINK_MODEL_DIR` | `~/.neurolink/models` | Root for local model files (`/whistle`) | | `NEUROLINK_WHISTLE_AUTO_DOWNLOAD` | on | `0`/`false`/`off`/`no` forbids the fallback download | | `NEUROLINK_WHISTLE_KEYWORDS` | off | `1`/`true`/`on`/`yes` biases Whistle on the request's vocabulary | See [The transcribe inference type](/docs/features/transcribe) and [Whistle](/docs/getting-started/providers/whistle). --- ## Configuration Examples ### Complete .env File Example ```bash # NeuroLink Environment Configuration - Commonly Used Providers # OpenAI Configuration OPENAI_API_KEY="sk-proj-your-openai-key" OPENAI_MODEL="gpt-4o" # Amazon Bedrock Configuration AWS_ACCESS_KEY_ID="AKIA..." AWS_SECRET_ACCESS_KEY="your-aws-secret" AWS_REGION="us-east-1" BEDROCK_MODEL="arn:aws:bedrock:us-east-1::inference-profile/us.anthropic.claude-3-5-sonnet-20241022-v2:0" # Amazon SageMaker Configuration AWS_ACCESS_KEY_ID="AKIA..." AWS_SECRET_ACCESS_KEY="your-aws-secret" AWS_REGION="us-east-1" SAGEMAKER_DEFAULT_ENDPOINT="my-model-endpoint" SAGEMAKER_TIMEOUT="30000" SAGEMAKER_MAX_RETRIES="3" # Google Vertex AI Configuration GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json" GOOGLE_VERTEX_PROJECT="your-gcp-project" GOOGLE_VERTEX_LOCATION="us-central1" VERTEX_MODEL="gemini-2.5-pro" # Anthropic Configuration (API key or OAuth token) ANTHROPIC_API_KEY="sk-ant-api03-your-key" # ANTHROPIC_OAUTH_TOKEN="your-oauth-token" # Alternative: OAuth token for Claude subscription # ANTHROPIC_SUBSCRIPTION_TIER="pro" # Optional: free, pro, max, max_5, max_20, api # ANTHROPIC_ENABLE_BETA_FEATURES="true" # Optional: enable beta headers (default: true for OAuth) # ANTHROPIC_OAUTH_REFRESH_TOKEN="" # Optional: OAuth refresh token for auto-renewal # ANTHROPIC_AUTH_METHOD="oauth" # Optional: force auth method (api_key or oauth) # Google AI Studio Configuration GOOGLE_AI_API_KEY="AIza-your-google-ai-key" GOOGLE_AI_MODEL="gemini-2.5-pro" # Azure OpenAI Configuration AZURE_OPENAI_API_KEY="your-azure-key" AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/" AZURE_OPENAI_DEPLOYMENT_ID="gpt-4o-deployment" AZURE_MODEL="gpt-4o" # Hugging Face Configuration HUGGINGFACE_API_KEY="hf_your_huggingface_token" HUGGINGFACE_MODEL="Qwen/Qwen2.5-72B-Instruct" # Ollama Configuration (Local AI - No API Key Required) OLLAMA_BASE_URL="http://localhost:11434" OLLAMA_MODEL="llama2" # Mistral AI Configuration MISTRAL_API_KEY="your_mistral_api_key" MISTRAL_MODEL="mistral-small" # LiteLLM Configuration LITELLM_BASE_URL="http://localhost:4000" LITELLM_API_KEY="sk-anything" LITELLM_MODEL="openai/gpt-4o-mini" # DeepSeek Configuration DEEPSEEK_API_KEY="sk-your-deepseek-key" DEEPSEEK_MODEL="deepseek-chat" # DEEPSEEK_BASE_URL=https://api.deepseek.com # NVIDIA NIM Configuration NVIDIA_NIM_API_KEY="nvapi-your-nvidia-key" NVIDIA_NIM_MODEL="openai/gpt-oss-20b" # NVIDIA_NIM_BASE_URL=https://integrate.api.nvidia.com/v1 # LM Studio Configuration (local — no API key required) LM_STUDIO_BASE_URL="http://localhost:1234/v1" # LM_STUDIO_MODEL= # blank = auto-discover # LM_STUDIO_API_KEY= # only for reverse-proxy setups # llama.cpp Configuration (local — no API key required) LLAMACPP_BASE_URL="http://localhost:8080/v1" # LLAMACPP_MODEL= # blank = auto-discover # LLAMACPP_API_KEY= # only for reverse-proxy setups ``` ### Docker/Container Configuration ```bash # Use environment variables in containers docker run -e OPENAI_API_KEY="sk-..." \ -e AWS_ACCESS_KEY_ID="AKIA..." \ -e AWS_SECRET_ACCESS_KEY="..." \ your-app ``` ### CI/CD Configuration ```yaml # GitHub Actions example env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} ``` --- ## Testing Configuration ### Test All Providers ```bash # Check provider status npx @juspay/neurolink status --verbose # Test specific provider npx @juspay/neurolink generate "Hello" --provider openai # Get best available provider npx @juspay/neurolink get-best-provider ``` ### Expected Output ```bash ✅ openai: Working (1245ms) ✅ bedrock: Working (2103ms) ✅ vertex: Working (1876ms) ✅ anthropic: Working (1654ms) ✅ azure: Working (987ms) Summary: 5/5 providers working ``` --- ## Security Best Practices ### Attachment loading (`NEUROLINK_ATTACHMENT_*`) What the SDK may read or fetch when a call names a file path or a URL (`input.files`, `input.images`, `rag.files`, `transcribe({ audio })`). Each variable mirrors a field of the `attachments` constructor option, which wins when both are set. See [Attachment Security](/docs/features/attachment-security). ```bash # Directories a local path may resolve into (":"- or ";"-separated). # Unset: any readable file, with a one-time warning. NEUROLINK_ATTACHMENT_ROOTS=/srv/uploads:/var/lib/app/files # Accept http:// attachment URLs (default: HTTPS only) NEUROLINK_ATTACHMENT_ALLOW_INSECURE_URLS=1 # Fetch loopback / private / link-local / cloud-metadata targets (default: refused) NEUROLINK_ATTACHMENT_ALLOW_PRIVATE_NETWORK=1 # Refuse redirects outright (default: followed, re-checked per hop) NEUROLINK_ATTACHMENT_FOLLOW_REDIRECTS=0 # Cap on any single attachment read or download, in bytes NEUROLINK_ATTACHMENT_MAX_BYTES=67108864 # Accept Redis session/user ids containing ':' '*' '?' '[' with a warning while migrating NEUROLINK_REDIS_ALLOW_LEGACY_IDS=1 ``` ### API Key Management - ✅ **Use .env files** for local development - ✅ **Use environment variables** in production - ✅ **Rotate keys regularly** (every 90 days) - ❌ **Never commit keys** to version control - ❌ **Never hardcode keys** in source code ### .gitignore Configuration ```bash # Add to .gitignore .env .env.local .env.production *.pem service-account*.json ``` ### Production Deployment - Use **secret management systems** (AWS Secrets Manager, Azure Key Vault) - Implement **key rotation** policies - Monitor **API usage** and **rate limits** - Use **least privilege** access policies ### Serving over HTTP (`neurolink serve`) `neurolink serve` listens on `127.0.0.1` unless `--host` says otherwise, and refuses to bind a non-loopback host without an API key. These variables govern the listener; see [/docs/reference/server-configuration](/docs/reference/server-configuration): ```bash NEUROLINK_SERVER_API_KEY=key1,key2 # Required on every route except the health probes NEUROLINK_SERVER_ALLOW_UNAUTHENTICATED=1 # Run open on purpose: non-loopback bind without a key, tool/MCP execution open NEUROLINK_SERVER_ENABLE_BUILTIN_TOOLS=1 # Keep the built-in filesystem tools in the server's registry (off by default) NEUROLINK_SERVER_WS_ALLOW_QUERY_TOKEN=1 # Accept the key as ?token= on the transcription WebSocket (off by default) NEUROLINK_SERVER_TIMEOUT_MS=30000 # Per-request timeout (504 past it) NEUROLINK_STT_EVAL_ENABLED=1 # Mount the STT evaluation collector, /v1/evals/stt (off by default) ``` --- ## Troubleshooting ### Common Issues #### 1. "Missing API Key" Error ```bash # Check if environment is loaded npx @juspay/neurolink status # Verify .env file exists and has correct format cat .env ``` #### 2. AWS Bedrock "Not Authorized" Error - ✅ Verify account has **model access** in Bedrock console - ✅ Use **full inference profile ARN** for Anthropic models - ✅ Check **IAM permissions** include Bedrock access #### 3. Google Vertex AI Import Issues - ✅ Ensure **Vertex AI API** is enabled - ✅ Verify **service account** has correct permissions - ✅ Check **JSON file path** is absolute and accessible #### 4. CLI Not Loading .env - ✅ Ensure `.env` file is in **current directory** - ✅ Check file has **correct format** (no spaces around =) - ✅ Verify CLI version supports **automatic loading** ### Debug Commands ```bash # Verbose status check npx @juspay/neurolink status --verbose # Test specific provider npx @juspay/neurolink generate "test" --provider openai --verbose # Check environment loading node -e "require('dotenv').config(); console.log(process.env.OPENAI_API_KEY)" ``` --- ## Related Documentation - **[Provider Configuration Guide](/docs/getting-started/provider-setup)** - Detailed provider setup - **[CLI Guide](/docs/cli)** - Complete CLI command reference - **[API Reference](/docs/sdk/api-reference)** - Programmatic usage examples - **[Framework Integration](/docs/sdk/framework-integration)** - Next.js, SvelteKit, React --- ## Need Help? - **Check the troubleshooting section** above - **Report issues** in our GitHub repository - **Join our Discord** for community support - **Contact us** for enterprise support **Next Steps**: Once configured, test your setup with `npx @juspay/neurolink status` and start generating AI content! --- ## above.dev Provider Guide # above.dev Provider Guide above.dev is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/above-dev.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status: docs- and roster-verified, not yet live-verified.** > Everything below comes from above.dev's own public docs > (https://above.dev/docs) and an unauthenticated `GET /v1/models` call — no > API key was used or obtained. No `generate()`/`stream()` request has been > made against this provider yet, so chat, streaming, tool calling and > structured output are **not** confirmed to work end-to-end. See > [Verification status](#verification-status) below before relying on this > provider in production. ## Quick Start ### 1. Get an API key 1. Visit: https://above.dev/pricing and purchase credit — API keys are issued only after purchase, there is no free signup 2. Copy the issued key — it starts with `sk-gw-` (the docs give only the prefix, not a full character-set spec) 3. Manage or rotate the key from https://above.dev/dashboard if it is ever compromised — a key grants full access to your credit balance 4. Set `ABOVE_DEV_API_KEY` in your .env file ### 2. Configure ```bash export ABOVE_DEV_API_KEY=your-api-key export ABOVE_DEV_MODEL=deepseek-v4.1-flash # optional — overrides the default model export ABOVE_DEV_BASE_URL=https://api.above.dev/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "above-dev", model: "deepseek-v4.1-flash", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider above-dev ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "above-dev", credentials: { "above-dev": { apiKey: process.env.ABOVE_DEV_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | -------------------------- | ------- | ------ | ---------------------- | ------------------------------------------------------------------------------- | | `deepseek-v4.1-flash` ⭐ | 1M | yes\* | time-of-day (see note) | Default — the id above.dev itself routes to when no model is named. Tier T1. | | `deepseek-v4-pro` | 1M | no | time-of-day (see note) | Tier T2 ("agentic — multi-step, tool-capable" per the vendor's own tier table). | | `glm-5.2` | 1.05M | no | $1.54 / $4.84 | Zhipu GLM 5.2. Tier T2. | | `glm-5.3-flash` | 1.05M | yes\* | $0.165 / $0.55 | Zhipu GLM 5.3 Flash. Tier T1. | | `glm-5.2-fast` | 1.05M | no | $2.31 / $7.26 | Zhipu GLM 5.2 Fast. Tier T3 ("highest capability in the catalog"). | | `qwen3.8-max` | 1M | yes\* | $2.20 / $6.60 | Alibaba Qwen 3.8 Max. Tier T3. | | `mimo-v2.6-pro` | 1M | no | $0.5077 / $1.0154 | MiMo V2.6 Pro. Tier T2. | | `mimo-v2.6-flash` | 1M | no | $0.1692 / $0.3385 | MiMo V2.6 Flash. Tier T1. | | `mimo-v2.6-pro-ultraspeed` | 1M | no | $5.0769 / $10.1538 | MiMo V2.6 Pro UltraSpeed. Tier T3. | \* Vision is `supports_vision: true` as **self-reported by above.dev's own `GET /v1/models`** response (unauthenticated, retrieved 2026-09-28). No image was actually sent to any model — this is vendor-stated metadata, not a live-probed result, so `models.visionModel` is deliberately left unset in the catalog entry. Every model in the current catalog accepts up to **131,072 output tokens** (documented account-wide limit, also reported per-model as `max_completion_tokens` in `GET /v1/models`). **Time-of-day pricing**: `deepseek-v4.1-flash` and `deepseek-v4-pro` bill at different peak/off-peak rates (peak = 01:00–04:00 and 06:00–10:00 UTC on weekdays; everything else, including all of the weekend in Beijing time, is off-peak). Because the catalog schema's `pricingPerMTok` is a single number, not a range, these two models' pricing is **omitted from the catalog entry rather than collapsed into one number** — see above.dev's pricing table (https://above.dev/docs) for the current peak/off-peak figures. Every other model in this roster bills a single flat rate, shown above. **Fallback order** when the default is unavailable: `glm-5.3-flash` → `mimo-v2.6-flash` → `deepseek-v4-pro` → `glm-5.2` → `mimo-v2.6-pro` → `glm-5.2-fast` → `qwen3.8-max` → `mimo-v2.6-pro-ultraspeed`. Two additional model ids, `glm-5.3-flash-modal` and `deepseek-v4.1-flash-modal`, are named in above.dev's docs as "free-tier routes" capped at 16,384 output tokens (they share a fixed concurrency pool). Neither id appears in the current `GET /v1/models` roster, so neither is represented in this catalog — and in any case a purchased key is still required to reach them, so the provider's overall `billingPolicy` remains `no-free-tier`. --- ## Tools & structured output — a documented caveat {#tools-and-structured-output} above.dev's own API reference table describes the `/v1/messages` request parameters differently depending on the field: - `temperature` — "Passed through to the model." - `tool_choice` — "Tool choice control. Passed through to the model." - `tools` — "Tool definitions. **Presence influences routing** toward tool-capable models." - `response_format` — "Structured output format. **Presence scores toward** structured-output models." The docs never state that `tools` or `response_format` are forwarded to, or honoured by, whichever model ends up serving the request — only that sending them nudges above.dev's routing. No example response containing `tool_calls`, a `finish_reason` value, or a `reasoning`/`reasoning_content` field appears anywhere in the docs. `GET /v1/models` does self-report `supports_tool_calls: true` and `supports_structured_output: true` for every model in the roster, but that is unauthenticated, vendor-supplied metadata, not a probed result. Given that ambiguity and that no live request (which would require a paid key) was made: - `capabilities.tools` is set to **`"model-dependent"`** rather than `true`. - `capabilities.structuredOutput` and `capabilities.structuredOutputWithTools` are both **`false`**. - `capabilities.thinking` is **`false`** — `GET /v1/models` reports `supports_reasoning: true` for every model, but the human-readable docs never document a `reasoning`/`thinking` request or response field, so this is not treated as a confirmed NeuroLink-facing capability. A future pass with a real key should re-probe all of this the way `friendli.json`/`novita.json` were probed (see `docs/provider-integration/tiers/tier-2-catalog-entry.md#live-verification`) and tighten these flags with `evidence.liveMatrix` filled in. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for above.dev — **docs- and roster-verified only, not yet live-verified**: | Probe | Result | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://api.above.dev/v1/models` — HTTP 200, 9 models, 2026-09-28. No key used. | | Docs cross-check | `https://above.dev/docs` fetched and re-read 2026-09-28 for auth header shape, endpoints, pricing, limits and error codes. | | Auth rejection probe | **Not performed** — would require sending a request with a credential header, which is out of scope for a credential-free onboarding. | | Live capability sweep | **Not performed** — `evidence.liveMatrix` is `null`. No `generate()`/`stream()` call has been made against `above-dev` yet. | Until a live matrix run fills in `evidence.liveMatrix`, treat `tools`, `structuredOutput`, `structuredOutputWithTools` and `thinking` as unproven — the catalog entry already reflects that by declining to assert them. --- ## Troubleshooting | Symptom | Cause | Fix | | -------------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | | `Invalid or missing above.dev API key` | `ABOVE_DEV_API_KEY` unset, wrong, or inactive (401) | Check the key and get/rotate one at https://above.dev/pricing / https://above.dev/dashboard | | Account balance insufficient (402) | No purchased credit remaining | Top up at https://above.dev/pricing | | Model not enabled for key (403) | The model is plan-restricted or in private beta for this key | Pick another catalog model, or contact above.dev to enable it | | Rate limited (429) | More than 300 requests/minute on the account | Retry after the documented `Retry-After` header | | Upstream timeout (504) | `provider_timeout` — the routed model did not respond in time | Retry the request | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## AI21 Labs Provider Guide # AI21 Labs Provider Guide AI21 Labs is a **Tier-2 catalog provider**: NeuroLink reaches it through its shared chat-completions client, and AI21 documents a chat endpoint at `POST /chat/completions` with Bearer authentication, a `choices` array in the response and server-sent-event streaming ending in `data: [DONE]` ([Chat request](https://docs.ai21.com/reference/jamba-1-6-api-ref), [Chat response](https://docs.ai21.com/reference/jamba-api-response)). No behavioural quirks are declared, so its integration is one JSON file (`src/lib/providers/catalog/ai21.json`) rather than hand-written code. That file is the source of truth for this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** AI21's `GET /studio/v1/models` answers `200` with an empty > `data` array without a key, so the model ids come from AI21's public docs > ([Jamba models page](https://docs.ai21.com/docs/jamba-foundation-models), > retrieved 2026-09-29) and the roster has not been checked. No account was > created and no API key was used to build this entry, and no POST request was > sent. `evidence.liveMatrix` is `null` until someone runs the live capability > matrix with a real key (see [Verification status](#verification-status) > below). ## Quick Start ### 1. Get an API key 1. Visit: https://docs.ai21.com/docs/create-api-key and follow its steps: sign in to AI21 Studio (the page says "You can sign in using your email address, Google account, GitHub account, or SSO."), click Settings in the bottom-left corner of the sidebar, open the API Keys tab, then click Create new key 2. Copy the key when it is shown; the page says "you won’t be able to view it again" 3. Free trial: https://docs.ai21.com/docs/usage-cost says "New accounts are given a $10 credit good for three months on the AI21 platform." and, once the trial is exceeded or expires, "you must provide valid billing information in your account to continue using the AI21 platform". https://www.ai21.com/pricing shows "$10 credits for 7 days." and "No credit card needed" under Free Trial 4. Set `AI21_API_KEY` in your .env file ### 2. Configure ```bash export AI21_API_KEY=your-api-key export AI21_MODEL=jamba-large # optional — overrides the default model export AI21_BASE_URL=https://api.ai21.com/studio/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "ai21", model: "jamba-large", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider ai21 ``` Per-request credentials are passed like this: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "ai21", credentials: { ai21: { apiKey: process.env.AI21_API_KEY } }, }); ``` --- ## Billing AI21's docs and website state different free-trial durations: - [Pricing](https://docs.ai21.com/docs/usage-cost) (docs): "New accounts are given a $10 credit good for three months on the AI21 platform." After the trial is exceeded or expires, "you must provide valid billing information in your account to continue using the AI21 platform." - [Pricing page](https://www.ai21.com/pricing) (website): "Start with a free trial, no credit card required, then pay based on usage." Under Free Trial it lists "$10 credits for 7 days." and "No credit card needed". The entry records `free-tier`. The [Account](https://docs.ai21.com/docs/managing-your-account) page says "You will need to provide billing information when your introductory usage credits expire." --- ## Models | Model | Context | Max output | Vision | $/M in · out | Notes | | ------------------------- | ------- | ---------- | ------ | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | `jamba-large` ⭐ | 256K | 4,096 | no | $2 / $8 | NeuroLink default. The models page: "Our most powerful and advanced model, designed to handle complex tasks at enterprise scale with superior performance." | | `jamba-mini` | 256K | 4,096 | no | $0.2 / $0.4 | NeuroLink fallback. The pricing page: "Efficient & lightweight model for a wide range of tasks". | | `jamba-large-1.7-2025-07` | 256K | 4,096 | no | — | Dated snapshot of Jamba Large (Version 1.7, Snapshot 2025-07); `jamba-large` currently points to it. | | `jamba-mini-2-2026-01` | 256K | 4,096 | no | — | Dated snapshot of Jamba Mini (Version 2, Snapshot 2026-01); `jamba-mini` currently points to it. | | `jamba-large-1.7` | 256K | 4,096 | no | — | Version name; points to `jamba-large-1.7-2025-07`. | | `jamba-mini-2` | 256K | 4,096 | no | — | Version name; points to `jamba-mini-2-2026-01`. | Prices for `jamba-large` and `jamba-mini` come from [AI21's pricing page](https://www.ai21.com/pricing) ("Jamba Large" at $2 / 1M input tokens and $8 / 1M output tokens; "Jamba Mini" at $0.2 / 1M input tokens and $0.4 / 1M output tokens), matched to the ids through the Model Details table on the [Jamba models page](https://docs.ai21.com/docs/jamba-foundation-models) (retrieved 2026-09-29). That page also lists the API Versioning mapping used in the notes above and gives Input Modality: Text, so the catalog records `vision: false` for these models. The same page states "We advise using dated versions of the Jamba API to avoid disruptions from model updates and breaking changes." `models.defaultContextWindow` and the per-model `contextWindow` values (256,000) are a numeric placeholder for the `256K` label printed on the [Jamba models page](https://docs.ai21.com/docs/jamba-foundation-models); no exact token count is taken from a vendor page. `models.defaultMaxOutputTokens` (4,096) is the `max_tokens` limit stated on the [Chat request](https://docs.ai21.com/reference/jamba-1-6-api-ref) page. **Fallback order** when the default is unavailable: `jamba-mini` → `jamba-large-1.7-2025-07` → `jamba-mini-2-2026-01`. The runtime fallback model name is set explicitly to `jamba-mini`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for AI21 Labs — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /studio/v1/models`, HTTP 200, body `{"data":[]}`, 2026-09-29 — no key used; model ids come from the [Jamba models page](https://docs.ai21.com/docs/jamba-foundation-models), not from the API | | Chat endpoint | unauthenticated `GET /studio/v1/chat/completions`, HTTP 405, body `{"detail":"Method Not Allowed"}`, header `allow: POST`, 2026-09-29 | | Billing | [usage-cost](https://docs.ai21.com/docs/usage-cost) and [pricing](https://www.ai21.com/pricing) pages, 2026-09-29 — the two pages state different trial terms, quoted under [Billing](#billing) | | Auth-failure shape | unauthenticated `GET /studio/v1/library/files` (a documented endpoint), HTTP 400, body `{"detail":"Bad request: bad or missing authentication."}`, 2026-09-29. The Chat response page lists 401, 403, 422, 429, 500 and 503. `errorRules` match status 401, status 429, status 503 and the text `bad or missing authentication` | | Tools / structured output | function calling is documented on the [Function Calling](https://docs.ai21.com/docs/function-calling) page and `response_format` with `{ "type": "json_object" }` on the Chat request page. Neither was exercised live. No POST request was sent, so `stream_options` on streaming calls, `tool_choice` on calls with tools and a `json_schema` `response_format`, which NeuroLink's chat-completions client can add, have not been exercised against AI21, and no combined tools + schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. | --- ## Troubleshooting | Symptom | Cause | Fix | | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | HTTP 401 | The Chat response page documents 401 as "Unauthorized (Incorrect API key provided/Invalid Authentication)" | The Authentication page says to use your API key as the Bearer token; NeuroLink reads it from `AI21_API_KEY` | | HTTP 429 | The Chat response page documents 429 as "Too Many Requests (You are sending requests too quickly.)" | The Rate Limits page lists 10 RPS and 200 RPM for Jamba Large and Jamba Mini and says to contact sales@ai21.com if you require a higher limit | | HTTP 503 | The Chat response page documents 503 as "Service Unavailable (The engine is currently overloaded, please try again later)" | The same text says "please try again later" | | Trial credit exceeded or expired | The usage-cost page: "you must provide valid billing information in your account to continue using the AI21 platform" | Add billing information in your account; the page points to Account > Billing & Plans | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## ai& Provider Guide # ai& Provider Guide ai& is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/aiand.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status: docs- and roster-verified, not yet live-verified.** > Every claim on this page comes from ai&'s own public documentation > (`https://docs.aiand.com/`) and an unauthenticated `GET /v1/models` call — > no API key was created or used, and no chat/stream/tool-call request was > ever sent. Treat capability flags as "documented", not "proven against a > live response". See [Verification status](#verification-status) below. ## Quick Start ### 1. Get an API key 1. Visit: https://console.aiand.com/playground and sign in (Google, GitHub, or a magic-link email — https://docs.aiand.com/authentication/) 2. Create an organization API key under Organizations → API Keys (https://docs.aiand.com/organizations/api-keys/) — shown in full only once, and starts with sk- 3. ai& is prepaid only, no free tier: add credits via Stripe Checkout before making requests (https://docs.aiand.com/billing/credits/) — a zero balance returns HTTP 402 until credits are added 4. Set `AIAND_API_KEY` in your .env file ### 2. Configure ```bash export AIAND_API_KEY=your-api-key export AIAND_MODEL=openai/gpt-oss-120b # optional — overrides the default model export AIAND_BASE_URL=https://api.aiand.com/v1 # optional — proxy or regional override ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "aiand", model: "openai/gpt-oss-120b", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider aiand ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "aiand", credentials: { aiand: { apiKey: process.env.AIAND_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out · cached | Notes | | ------------------------------- | ------- | ----------------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `openai/gpt-oss-120b` ⭐ | 131K | no | $0.15 / $0.60 / $0.08 | Default — the model in ai&'s own quickstart example. Cheapest on the roster. `reasoning_effort`: low/medium/high (default medium). | | `zai-org/glm-5.3` | 1M | no | $1.00 / $4.00 / $0.30 | "Flagship GLM model for long-horizon coding, agents, and complex project delivery." `reasoning_effort`: low/high/max (default max). | | `zai-org/glm-5.2` | 1M | no | $1.00 / $4.00 / $0.30 | Prior GLM generation. `reasoning_effort`: none/high/max (default max). | | `deepseek-ai/deepseek-v4-pro` | 1M | no | $1.00 / $2.50 / $0.25 | "Open MoE flagship with million-token context for coding and long agent runs." `reasoning_effort`: none/high/max (default none). | | `deepseek-ai/deepseek-v4-flash` | 1M | no | $0.15 / $0.25 / $0.08 | "Fast DeepSeek V4 lane for economical reasoning, coding, and long-context work." `reasoning_effort`: none/high/max (default none). | | `moonshotai/kimi-k3` | 1M | listed (see note) | $3.00 / $12.50 / $0.50 | "Multimodal Kimi model with 1M context and toggleable max-effort thinking." `reasoning_effort`: low/high/max (default max). | | `moonshotai/kimi-k2.7-code` | 262K | listed (see note) | $0.75 / $3.50 / $0.20 | Coding-focused Kimi model. `reasoning_effort`: high only. | | `qwen/qwen3.8-27b` | 262K | listed (see note) | $0.40 / $3.00 / $0.20 | Dense 27B vision-language model. `reasoning_effort`: none/low/medium/xhigh (default medium). | | `qwen/qwen3.6-27b` | 262K | listed (see note) | $0.32 / $3.20 / $0.20 | Qwen vision-language model. `reasoning_effort`: none/high (default high). | | `motif-technologies/motif-3` | 262K | no | $0.50 / $2.00 / $0.20 | 314B-parameter MoE, 13.2B active per token. `reasoning_effort`: none/high (default high). | | `google/gemma-4-31b-it` | 262K | listed (see note) | $0.20 / $0.50 / $0.05 | Largest Gemma 4 instruction model. `reasoning_effort`: none/high (default none). | **Vision note:** five models list a `vision` capability on `GET /v1/models`, but ai&'s vision docs (`/capabilities/vision/`) describe images and video as uploaded once through the **Files API** and then referenced by `file_id` in the chat request — not the inline base64 `image_url` data-URI shape most other NeuroLink providers use. That flow was not exercised here (no API key was used), so no model is marked `vision: true` (`models.visionModel`) in the catalog entry and this should be treated as **unverified** until a live probe confirms the wire shape NeuroLink sends actually works against it. Context window and pricing are from the unauthenticated `GET /v1/models` response, retrieved 2026-09-28, cross-checked against the docs' Models Catalog page (`/models/catalog/`). ai&'s docs define `context_window` as the combined input+output token budget, with no separately published max-output-tokens figure — hence `defaultMaxOutputTokens` in the catalog equals `defaultContextWindow`. **Fallback order** when the default is unavailable: `zai-org/glm-5.3` → `zai-org/glm-5.2` → `deepseek-ai/deepseek-v4-pro` → `deepseek-ai/deepseek-v4-flash` → `moonshotai/kimi-k3` → `moonshotai/kimi-k2.7-code` → `qwen/qwen3.8-27b` → `qwen/qwen3.6-27b` → `motif-technologies/motif-3` → `google/gemma-4-31b-it`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This entry was built **without credentials**, from ai&'s public documentation and one unauthenticated GET request — no signup, no API key, no POST request to the vendor was made. This is what the catalog records for ai&: | Probe | Result | | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://api.aiand.com/v1/models`, HTTP 200, 2026-09-28 — 11 models, cross-checked against `/models/catalog/` and `/models/pricing/` | | Auth rejection | not probed — sending any request (even with an invalid key) is outside credential-free scope; the 401 `authentication_error` / `invalid_api_key` shape in `errorRules` is transcribed from `https://docs.aiand.com/errors/`, not observed live | | Live capability sweep | **not performed.** `evidence.liveMatrix` is `null`. `capabilities.tools`, `.structuredOutput`, `.streaming` and `.thinking` are set from ai&'s documented request parameters (`tools`, `response_format`, `stream`, `reasoning_effort` — see `https://docs.aiand.com/api/chat-completions/`), not from an executed request. `structuredOutputWithTools` is `false` because the combined `tools` + `response_format` request that would prove it was never sent. | **Before this entry graduates past docs-only status**, someone with a funded account should run the live-verification steps in [Tier-2 onboarding: Live verification](/docs/provider-integration/tiers/tier-2-catalog-entry#live-verification) — an authenticated roster probe, an auth-failure probe, and the capability matrix (`npx tsx test/continuous-test-suite-provider-matrix.ts --provider=aiand`) — and update `evidence.liveMatrix` with the result. --- ## Troubleshooting | Symptom | Cause | Fix | | -------------------------------------------- | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | `Invalid ai& API key` | `AIAND_API_KEY` unset or wrong | Check the key at https://console.aiand.com/playground | | `HTTP 402` / insufficient credits | ai& is prepaid-only with no free tier | Add credits via Stripe Checkout at https://docs.aiand.com/billing/credits/ | | `429` rate limited | Documented per-key/per-org rate limits | Check the `X-RateLimit-Policy` response header and back off | | `tools` request rejected on a non-tool model | The chosen model lacks the `tool_calling` capability | Pick a model whose `GET /v1/models` entry lists `tool_calling` (all 11 catalog models currently do) | | Vision request fails or is ignored | ai& expects images/video via the Files API (`file_id`), not inline `image_url` data URIs | Not yet supported by this integration in the standard NeuroLink flow — treat vision as unverified for now | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## ⚙️ Provider Configuration Guide # ⚙️ Provider Configuration Guide NeuroLink supports multiple AI providers with flexible authentication methods. This guide covers complete setup for all supported providers. ## Supported Providers This guide walks through full environment-variable setup for the providers below; the complete roster — including the newer catalog providers and the embedding/media/decision-only providers — is indexed with setup guides at [Provider Guides](/docs/). ### Providers configured in this guide - **OpenAI** - GPT-4o, GPT-4o-mini, GPT-4-turbo - **Amazon Bedrock** - Claude 3.7 Sonnet, Claude 3.5 Sonnet, Claude 3 Haiku - **Amazon SageMaker** - Custom models deployed on SageMaker endpoints - **Google Vertex AI** - Gemini 3 Flash/Pro (preview), Gemini 2.5 Flash, Claude 4.0 Sonnet - **Google AI Studio** - Gemini 1.5 Pro, Gemini 2.0 Flash, Gemini 1.5 Flash - **Anthropic** - Claude 4.5 Opus/Sonnet/Haiku, Claude 4.0 Opus/Sonnet, Claude 3.7 Sonnet - **Azure OpenAI** - GPT-4, GPT-3.5-Turbo - **LiteLLM** - 100+ models across a broad range of providers via proxy server - **Hugging Face** - open models served by the unified router (Llama 3.x, Qwen 2.5, DeepSeek, Mistral) - **Ollama** - Local AI models including Llama 2, Code Llama, Mistral, Vicuna - **OpenRouter** - 300+ models from every major lab via one aggregator endpoint - **Mistral AI** - Mistral Tiny, Small, Medium, and Large models - **DeepSeek** - deepseek-chat (V3) and deepseek-reasoner (R1) - **NVIDIA NIM** - Llama 3.3 70B and 400+ catalog models via NVIDIA hosted or self-hosted NIM - **LM Studio** - Any model loaded in LM Studio desktop app (local, no API key required) - **llama.cpp** - Any GGUF model served by llama-server (local, no API key required) ### Other providers (setup guides in the Provider Guides index) Onboarded via the zero-quirk OpenAI-wire-compatible catalog (Tier 2) — each has its own setup guide under [`providers/`](providers/): - **[Groq](/docs/getting-started/providers/groq)** - LPU-accelerated inference; default `openai/gpt-oss-120b` - **[Cerebras](/docs/getting-started/providers/cerebras)** - Wafer-scale inference; default `gpt-oss-120b` - **[SambaNova](/docs/getting-started/providers/sambanova)** - default `Meta-Llama-3.3-70B-Instruct` - **[Together AI](/docs/getting-started/providers/together-ai)** - default `meta-llama/Llama-3.3-70B-Instruct-Turbo` - **[Fireworks AI](/docs/getting-started/providers/fireworks)** - default `accounts/fireworks/models/kimi-k3` - **[Perplexity](/docs/getting-started/providers/perplexity)** - search-augmented models; default `sonar` - **[Cloudflare Workers AI](/docs/getting-started/providers/cloudflare)** - edge inference - **[xAI](/docs/getting-started/providers/xai)** - Grok models; default `grok-4.6` - **[Baseten](/docs/getting-started/providers/baseten)** - default `zai-org/GLM-5.3-Flash` (`BASETEN_API_KEY`) - **[GMI Cloud](/docs/getting-started/providers/gmicloud)** - default `MiniMaxAI/MiniMax-M3` (`GMICLOUD_API_KEY`) - **[Inception Labs](/docs/getting-started/providers/inception-labs)** - diffusion LLMs; default `mercury-2` (`INCEPTION_LABS_API_KEY`) - **[io.net Intelligence](/docs/getting-started/providers/io-intelligence)** - decentralized GPU inference; default `meta-llama/Llama-3.3-70B-Instruct` (`IO_INTELLIGENCE_API_KEY`) - **[Mancer](/docs/getting-started/providers/mancer)** - default `deepseek-v4-flash` (`MANCER_API_KEY`); **no tool calling** - **[Upstage](/docs/getting-started/providers/upstage)** - Solar models; default `solar-pro4` (`UPSTAGE_API_KEY`) - **[API Route](/docs/getting-started/providers/api-route)** - OpenAI-compatible passthrough; default `claude-sonnet-4-6` (`API_ROUTE_API_KEY`) - **[DeepInfra](/docs/getting-started/providers/deepinfra)** - default `deepseek-ai/DeepSeek-V4-Flash-0731` (`DEEPINFRA_API_KEY`); docs- and roster-verified, not yet live-verified - **[Featherless AI](/docs/getting-started/providers/featherless-ai)** - default `unsloth/Llama-3.3-70B-Instruct` (`FEATHERLESS_AI_API_KEY`); docs- and roster-verified, not yet live-verified - **[Chutes](/docs/getting-started/providers/chutes)** - default `moonshotai/Kimi-K2.6-TEE` (`CHUTES_API_KEY`); docs- and roster-verified, not yet live-verified - **[OVHcloud AI Endpoints](/docs/getting-started/providers/ovhcloud)** - default `gpt-oss-120b` (`OVH_AI_ENDPOINTS_ACCESS_TOKEN`); docs- and roster-verified, not yet live-verified - **[Sarvam AI](/docs/getting-started/providers/sarvam)** - default `sarvam-105b` (`SARVAM_API_KEY`); docs- and roster-verified, not yet live-verified - **[Synthetic](/docs/getting-started/providers/synthetic)** - default `syn:large:text` (`SYNTHETIC_API_KEY`); docs- and roster-verified, not yet live-verified - **[Ambient](/docs/getting-started/providers/ambient)** - default `ambient/large` (`AMBIENT_API_KEY`); docs- and roster-verified, not yet live-verified - **[Inference.net](/docs/getting-started/providers/inference-net)** - default `glm-5.2` (`INFERENCE_API_KEY`); docs- and roster-verified, not yet live-verified - **[EmpirioLabs AI](/docs/getting-started/providers/empiriolabs)** - default `glm-5-3` (`EMPIRIOLABS_API_KEY`); docs- and roster-verified, not yet live-verified - **[above.dev](/docs/getting-started/providers/above-dev)** - default `deepseek-v4.1-flash` (`ABOVE_DEV_API_KEY`); docs- and roster-verified, not yet live-verified - **[ai&](/docs/getting-started/providers/aiand)** - default `openai/gpt-oss-120b` (`AIAND_API_KEY`); docs- and roster-verified, not yet live-verified - **[Bee by HEOSSI](/docs/getting-started/providers/bee-heossi)** - default `bee-cell` (`BEE_HEOSSI_API_KEY`); docs- and roster-verified, not yet live-verified - **[Charm Hyper](/docs/getting-started/providers/charm-hyper)** - default `deepseek-v4-pro` (`CHARM_HYPER_API_KEY`); docs- and roster-verified, not yet live-verified - **[Inco](/docs/getting-started/providers/inco)** - default `glm-5.3` (`INCO_API_KEY`); **no tool calling**; docs- and roster-verified, not yet live-verified - **[Kosmik Compute](/docs/getting-started/providers/koscompute)** - default `qwen/qwen3.8-27b` (`KOSCOMPUTE_API_KEY`); docs- and roster-verified, not yet live-verified - **[Lilac](/docs/getting-started/providers/lilac)** - default `moonshotai/kimi-k2.6` (`LILAC_API_KEY`); docs- and roster-verified, not yet live-verified - **[LLM Tech](/docs/getting-started/providers/llmtech)** - default `nvidia/Qwen3.8-27B-NVFP4` (`LLMTECH_API_KEY`); docs- and roster-verified, not yet live-verified - **[Moark](/docs/getting-started/providers/moark)** - default `Qwen3-8B` (`MOARK_API_KEY`); docs- and roster-verified, not yet live-verified - **[Neuralwatt](/docs/getting-started/providers/neuralwatt)** - default `glm-5.3` (`NEURALWATT_API_KEY`); docs- and roster-verified, not yet live-verified - **[Pareto Inference](/docs/getting-started/providers/pareto-inference)** - default `z-ai/glm-5.3-flash` (`PARETO_INFERENCE_API_KEY`); docs- and roster-verified, not yet live-verified - **[Aion Labs](/docs/getting-started/providers/aionlabs)** - default `aion-labs/aion-3.5` (`AIONLABS_API_KEY`); docs- and roster-verified, not yet live-verified - **[Atlas Cloud](/docs/getting-started/providers/atlas-cloud)** - default `deepseek-ai/deepseek-v3.2` (`ATLAS_CLOUD_API_KEY`); docs- and roster-verified, not yet live-verified - **[Avian](/docs/getting-started/providers/avian-io)** - default `deepseek/deepseek-v4-pro-0813` (`AVIAN_IO_API_KEY`); docs- and roster-verified, not yet live-verified - **[Prime Intellect](/docs/getting-started/providers/prime-intellect)** - default `openai/gpt-4.1-mini` (`PRIME_INTELLECT_API_KEY`); docs- and roster-verified, not yet live-verified - **[Subconscious](/docs/getting-started/providers/subconscious)** - default `subconscious/glm-5.3-marathon` (`SUBCONSCIOUS_API_KEY`); **no tool calling**; docs- and roster-verified, not yet live-verified - **[Tinfoil](/docs/getting-started/providers/tinfoil)** - default `kimi-k3` (`TINFOIL_API_KEY`); docs- and roster-verified, not yet live-verified - **[Umans AI](/docs/getting-started/providers/umans-ai)** - default `umans-coder` (`UMANS_AI_API_KEY`); docs- and roster-verified, not yet live-verified - **[Vultr Inference](/docs/getting-started/providers/vultr-inference)** - default `glm-5.2` (`VULTR_INFERENCE_API_KEY`); docs- and roster-verified, not yet live-verified - **[Wafer](/docs/getting-started/providers/wafer)** - default `GLM-5.3` (`WAFER_API_KEY`); docs- and roster-verified, not yet live-verified - **[Venice AI](/docs/getting-started/providers/venice-ai)** - default `zai-org-glm-5-2` (`VENICE_AI_API_KEY`); docs- and roster-verified, not yet live-verified - **[AI21 Labs](/docs/getting-started/providers/ai21)** - default `jamba-large` (`AI21_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Nebius Token Factory](/docs/getting-started/providers/nebius)** - default `Qwen/Qwen3-235B-A22B-Instruct-2507` (`NEBIUS_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Moonshot AI (Kimi)](/docs/getting-started/providers/moonshot-ai)** - default `kimi-k3` (`MOONSHOT_AI_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[MiniMax](/docs/getting-started/providers/minimax)** - default `MiniMax-M3` (`MINIMAX_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Z.AI](/docs/getting-started/providers/z-ai)** - default `glm-5.3` (`Z_AI_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[StepFun](/docs/getting-started/providers/stepfun)** - default `step-5-preview` (`STEPFUN_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[SiliconFlow](/docs/getting-started/providers/siliconflow)** - default `deepseek-ai/DeepSeek-V4-Pro` (`SILICONFLOW_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Scaleway](/docs/getting-started/providers/scaleway)** - default `mistral-small-3.2-24b-instruct-2506` (`SCALEWAY_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Crusoe](/docs/getting-started/providers/crusoe)** - default `deepseek-ai/DeepSeek-V4-Flash` (`CRUSOE_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[W&B Inference](/docs/getting-started/providers/wandb-inference)** - default `openai/gpt-oss-120b` (`WANDB_INFERENCE_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Inceptron](/docs/getting-started/providers/inceptron)** - default `zai-org/GLM-5.3` (`INCEPTRON_API_KEY`); docs- and roster-verified, not yet live-verified - **[BytePlus ModelArk](/docs/getting-started/providers/byteplus-modelark)** - default `seed-2-0-pro-260328` (`BYTEPLUS_MODELARK_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[GradientAI (DigitalOcean)](/docs/getting-started/providers/gradientai)** - default `llama-4-maverick` (`GRADIENTAI_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Parasail](/docs/getting-started/providers/parasail)** - default `parasail-llama-33-70b-fp8` (`PARASAIL_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Baidu Qianfan](/docs/getting-started/providers/baidu-qianfan)** - default `ernie-5.1` (`BAIDU_QIANFAN_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Arcee](/docs/getting-started/providers/arcee)** - default `trinity-large-thinking` (`ARCEE_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Telnyx](/docs/getting-started/providers/telnyx)** - default `zai-org/GLM-5.3-Flash` (`TELNYX_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Reka AI](/docs/getting-started/providers/reka)** - default `reka-flash` (`REKA_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Thinking Machines](/docs/getting-started/providers/thinking-machines)** - default `moonshotai/Kimi-K2.6` (`THINKING_MACHINES_API_KEY`); **no tool calling**; docs-verified only (the roster needs a key), not yet live-verified - **[Alibaba Cloud Model Studio (DashScope)](/docs/getting-started/providers/dashscope)** - default `qwen3.8-max` (`DASHSCOPE_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Vispark](/docs/getting-started/providers/vispark)** - default `vispark/vision-large` (`VISPARK_API_KEY`); docs- and roster-verified, not yet live-verified - **[Sakana AI](/docs/getting-started/providers/sakana-ai)** - default `fugu` (`SAKANA_AI_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Poolside](/docs/getting-started/providers/poolside)** - default `poolside/laguna-s-2.1` (`POOLSIDE_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Lemonfox AI](/docs/getting-started/providers/lemonfox-ai)** - default `deepseek-v4-flash` (`LEMONFOX_AI_API_KEY`); **no tool calling**; docs-verified only (the roster needs a key), not yet live-verified - **[ModelScope](/docs/getting-started/providers/modelscope)** - default `Qwen/Qwen3.5-35B-A3B` (`MODELSCOPE_API_KEY`); **no tool calling**; docs- and roster-verified, not yet live-verified - **[Hetzner Inference](/docs/getting-started/providers/hetzner-inference)** - default `Qwen/Qwen3.6-35B-A3B-FP8` (`HETZNER_INFERENCE_API_KEY`); **no tool calling**; docs-verified only (the roster needs a key), not yet live-verified - **[Meta Model API](/docs/getting-started/providers/meta-model-api)** - default `muse-spark-1.3` (`META_MODEL_API_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[STACKIT](/docs/getting-started/providers/stackit)** - default `Qwen/Qwen3-VL-235B-A22B-Instruct-FP8` (`STACKIT_API_KEY`); docs-verified only (the roster needs a key), not yet live-verified - **[Bytez](/docs/getting-started/providers/bytez)** - default `Qwen/Qwen3-4B` (`BYTEZ_API_KEY`); **no tool calling**; docs-verified only (the roster needs a key), not yet live-verified Embedding, media-generation, and decision-only providers — not part of `generate()`/`stream()` provider selection in the same way, but each has a setup guide: - **[Cohere](/docs/getting-started/providers/cohere)** - chat + `embed-english-v3.0` embeddings + reranking - **[Voyage AI](/docs/getting-started/providers/voyage)** - embedding-only; default `voyage-3.5` - **[Jina AI](/docs/getting-started/providers/jina)** - embeddings + reranking; default `jina-embeddings-v3` - **[Replicate](/docs/getting-started/providers/replicate)**, **[Stability AI](/docs/getting-started/providers/stability)**, **[Ideogram](/docs/getting-started/providers/ideogram)**, **[Recraft](/docs/getting-started/providers/recraft)** - direct image generation - **[TypeSafe Jev](/docs/getting-started/providers/typesafe)** - decision-only; serves `decide()`, not `generate()`/`stream()`. Set `TYPESAFE_API_KEY` (or `AI_GATEWAY_API_KEY` for the gateway transport) - **[Laya](/docs/getting-started/providers/laya)** - decision-only, open-weights; serves `decide()` on a Laya server or LiteLLM proxy route you configure. Set `LAYA_API_KEY` + `LAYA_BASE_URL`; used when TypeSafe isn't configured - **[XOR](/docs/getting-started/providers/xor)** - decision-only, open-weights XOR (`xor-latest` for text, `xor-omni` for an image, audio or `value` questions); serves `decide()`. Set `XOR_API_KEY` + `XOR_BASE_URL` (`XOR_MODEL` is optional, default `xor-latest`); used when neither TypeSafe nor Laya is configured - **[SubQ](/docs/getting-started/providers/subq)** - decision-only; serves `decide()` with `subq-snap-preview` (public preview) at `https://api.subq.ai`. Set `SUBQ_API_KEY` alone (`SUBQ_MODEL` and `SUBQ_BASE_URL` are optional); the key comes from console.subq.ai and is shown once. NeuroLink does not send it images or video; used when none of TypeSafe, Laya or XOR is configured, ahead of Perplexity and Cloudflare Clef (its key is shared with no other provider) - **[Perplexity Decisions](/docs/getting-started/providers/perplexity-decider)** - decision-only; serves `decide()` with `pplx-decider-v1-27b` and takes images (no video). Set `PERPLEXITY_API_KEY` alone (`PERPLEXITY_DECIDER_MODEL` and `PERPLEXITY_DECIDER_BASE_URL` are optional); used when none of TypeSafe, Laya, XOR or SubQ is configured. The key is shared with the Perplexity text provider, so a key set for Sonar also configures it - **[Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef)** - decision-only; serves `decide()` with `clef` (27B, the default) or `clef-flash` (9B) and takes up to 4 images (no video). Set `CLOUDFLARE_API_KEY` (Workers AI permission) **and** `CLOUDFLARE_ACCOUNT_ID`, both required (`CLOUDFLARE_CLEF_MODEL` and `CLOUDFLARE_CLEF_BASE_URL` are optional); used when none of TypeSafe, Laya, XOR, SubQ or Perplexity is configured (OpenAI Decisions and ScaleDown come after it). The two variables are shared with the Cloudflare Workers AI text provider, so a token and account id set for it also configure Clef. The Workers AI state window changed in October 2026 (about 2,048 tokens until 2026-10-04, far more on 2026-10-07; hosted service or model: unknown), and NeuroLink refuses a state it estimates over 16,000 tokens - **[OpenAI Decisions](/docs/getting-started/providers/openai-decisions)** - decision-only; serves `decide()` with `gpt-6-luna` (OpenAI's Decisions API, a public beta) and takes up to 8 images (no video). Set `OPENAI_API_KEY` alone (`OPENAI_DECISIONS_MODEL` and `OPENAI_DECISIONS_BASE_URL` are optional); used when none of TypeSafe, Laya, XOR, SubQ, Perplexity or Cloudflare Clef is configured (ScaleDown alone comes after it). The key is shared with the OpenAI chat provider, so a key set for chat also configures it, and built-in features then make paid decision calls, unless `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL` names a host other than `https://api.openai.com` (a gateway's key is not used by default); limits and behaviour of the endpoint are largely not established, see the guide - **[ScaleDown](/docs/getting-started/providers/scaledown)** - decision-only; serves `decide()` with `classify-1` (the default) or `classify` at `https://api.scaledown.xyz`. Set `SCALEDOWN_API_KEY` alone (`SCALEDOWN_MODEL` and `SCALEDOWN_BASE_URL` are optional); the key is sent in an `x-api-key` header and no other provider reads it. Text only (no images or video). Used last, when none of TypeSafe, Laya, XOR, SubQ, Perplexity, Cloudflare Clef or OpenAI Decisions is configured. Its context size, latency and rate limits are not measured, see the guide Voice providers (TTS/STT/Realtime) are configured further down in this guide — see [OpenAI TTS](#openai-tts) onward. ## Model Availability & Cost Considerations **Important Notes:** - **Model Availability**: Specific models may not be available in all regions or require special access - **Cost Variations**: Pricing differs significantly between providers and models (e.g., Claude 3.5 Sonnet vs GPT-4o) - **Rate Limits**: Each provider has different rate limits and quota restrictions - **Local vs Cloud**: Ollama (local) has no per-request cost but requires hardware resources - **Enterprise Tiers**: AWS Bedrock, Google Vertex AI, and Azure typically offer enterprise pricing **Best Practices:** - Use `new NeuroLink()` with automatic provider selection for cost-optimized routing - Monitor usage through built-in analytics to track costs - Consider local models (Ollama) for development and testing - Check provider documentation for current pricing and availability ## Enterprise Proxy Support **Providers support corporate proxy environments automatically.** Simply set environment variables: ```bash export HTTPS_PROXY=http://your-corporate-proxy:port export HTTP_PROXY=http://your-corporate-proxy:port ``` **No code changes required** - NeuroLink automatically detects and uses proxy settings. **For detailed proxy setup** → See [Enterprise & Proxy Setup Guide](/docs/deployment/enterprise-proxy) ## OpenAI Configuration {#openai} ### Basic Setup ```bash export OPENAI_API_KEY="sk-your-openai-api-key" ``` ### Optional Configuration ```bash # Optional: override the default model (default: gpt-4o-mini) export OPENAI_MODEL="gpt-5.4" ``` ### Supported Models Examples, not the full list. The [OpenAI guide](/docs/getting-started/providers/openai) lists every model the SDK names, including the GPT-6 and `gpt-5.4-nano` models. - `gpt-5.4` - GPT-5.4 model - `gpt-5.4-mini` - Cost-effective GPT-5.4 variant - `gpt-4o-mini` (default) - Cost-effective variant - `gpt-4o` - Previous generation multimodal model - `gpt-4-turbo` - High-performance model See the [environment variables guide](/docs/getting-started/environment-variables) for the order in which the model is chosen when none is set. ### Usage Example ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain machine learning" }, provider: "openai", model: "gpt-4o", temperature: 0.7, maxTokens: 500, timeout: "30s", // Optional: Override default 30s timeout }); ``` ### Timeout Configuration - **Default Timeout**: 30 seconds - **Supported Formats**: Milliseconds (`30000`), human-readable (`'30s'`, `'1m'`, `'5m'`) - **Environment Variable**: `OPENAI_TIMEOUT='45s'` (optional) ## Amazon Bedrock Configuration {#bedrock} ### Critical Setup Requirements **⚠️ IMPORTANT: Anthropic Models Require Inference Profile ARN** For Anthropic Claude models in Bedrock, you **MUST** use the full inference profile ARN, not simple model names: ```bash # ✅ CORRECT: Use full inference profile ARN export BEDROCK_MODEL="arn:aws:bedrock:us-east-2::inference-profile/us.anthropic.claude-3-7-sonnet-20250219-v1:0" # ❌ WRONG: Simple model names cause "not authorized to invoke this API" errors # export BEDROCK_MODEL="anthropic.claude-3-sonnet-20240229-v1:0" ``` ### Basic AWS Credentials ```bash export AWS_ACCESS_KEY_ID="your-access-key" export AWS_SECRET_ACCESS_KEY="your-secret-key" export AWS_REGION="us-east-2" ``` ### Session Token Support (Development) For temporary credentials (common in development environments): ```bash export AWS_SESSION_TOKEN="your-session-token" # Required for temporary credentials ``` ### Available Inference Profile ARNs Replace `` with your AWS account ID: ```bash # Claude 3.7 Sonnet (Latest - Recommended) BEDROCK_MODEL="arn:aws:bedrock:us-east-2::inference-profile/us.anthropic.claude-3-7-sonnet-20250219-v1:0" # Claude 3.5 Sonnet BEDROCK_MODEL="arn:aws:bedrock:us-east-2::inference-profile/us.anthropic.claude-3-5-sonnet-20241022-v2:0" # Claude 3 Haiku BEDROCK_MODEL="arn:aws:bedrock:us-east-2::inference-profile/us.anthropic.claude-3-haiku-20240307-v1:0" ``` ### Why Inference Profiles? - **Cross-Region Access**: Faster access across AWS regions - **Better Performance**: Optimized routing and response times - **Higher Availability**: Improved model availability and reliability - **Different Permissions**: Separate permission model from base models ### Complete Bedrock Configuration ```bash # Required AWS credentials export AWS_ACCESS_KEY_ID="your-access-key" export AWS_SECRET_ACCESS_KEY="your-secret-key" export AWS_REGION="us-east-2" # Optional: Session token for temporary credentials export AWS_SESSION_TOKEN="your-session-token" # Required: Inference profile ARN (not simple model name) export BEDROCK_MODEL="arn:aws:bedrock:us-east-2::inference-profile/us.anthropic.claude-3-7-sonnet-20250219-v1:0" # Alternative environment variable names (backward compatibility) export BEDROCK_MODEL_ID="arn:aws:bedrock:us-east-2::inference-profile/us.anthropic.claude-3-7-sonnet-20250219-v1:0" ``` ### Usage Example ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Write a haiku about AI" }, provider: "bedrock", temperature: 0.8, maxTokens: 100, timeout: "45s", // Optional: Override default 45s timeout }); ``` ### Timeout Configuration - **Default Timeout**: 45 seconds (longer due to cold starts) - **Supported Formats**: Milliseconds (`45000`), human-readable (`'45s'`, `'1m'`, `'2m'`) - **Environment Variable**: `BEDROCK_TIMEOUT='1m'` (optional) ### Account Setup Requirements To use AWS Bedrock, ensure your AWS account has: 1. **Bedrock Service Access**: Enable Bedrock in your AWS region 2. **Model Access**: Request access to Anthropic Claude models 3. **IAM Permissions**: Your credentials need `bedrock:InvokeModel` permissions 4. **Inference Profile Access**: Access to the specific inference profiles ### IAM Policy Example ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream" ], "Resource": ["arn:aws:bedrock:*:*:inference-profile/us.anthropic.*"] } ] } ``` ## Amazon SageMaker Configuration **Amazon SageMaker** allows you to use your own custom models deployed on SageMaker endpoints. This provider is perfect for: - **Custom Model Hosting** - Deploy your fine-tuned models - **Enterprise Compliance** - Full control over model infrastructure - **Cost Optimization** - Pay only for inference usage - **Performance** - Dedicated compute resources ### Basic AWS Credentials ```bash export AWS_ACCESS_KEY_ID="your-access-key" export AWS_SECRET_ACCESS_KEY="your-secret-key" export AWS_REGION="us-east-1" # Your SageMaker region ``` ### SageMaker-Specific Configuration ```bash # Required: Your SageMaker endpoint name export SAGEMAKER_DEFAULT_ENDPOINT="your-endpoint-name" # Optional: Timeout and retry settings export SAGEMAKER_TIMEOUT="30000" # 30 seconds (default) export SAGEMAKER_MAX_RETRIES="3" # Retry attempts (default) ``` ### Advanced Model Configuration ```bash # Optional: Model-specific settings export SAGEMAKER_MODEL="custom-model-name" # Model identifier export SAGEMAKER_MODEL_TYPE="custom" # Model type export SAGEMAKER_CONTENT_TYPE="application/json" export SAGEMAKER_ACCEPT="application/json" ``` ### Session Token Support (for IAM Roles) ```bash export AWS_SESSION_TOKEN="your-session-token" # For temporary credentials ``` ### Complete SageMaker Configuration ```bash # AWS Credentials export AWS_ACCESS_KEY_ID="AKIAIOSFODNN7EXAMPLE" export AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" export AWS_REGION="us-east-1" # SageMaker Settings export SAGEMAKER_DEFAULT_ENDPOINT="my-model-endpoint-2024" export SAGEMAKER_TIMEOUT="45000" export SAGEMAKER_MAX_RETRIES="5" ``` ### Usage Example ```bash # Test SageMaker endpoint npx @juspay/neurolink sagemaker test my-endpoint # Generate text with SageMaker npx @juspay/neurolink generate "Analyze this data" --provider sagemaker # Interactive setup npx @juspay/neurolink sagemaker setup ``` ### CLI Commands ```bash # Check SageMaker configuration npx @juspay/neurolink sagemaker status # Validate connection npx @juspay/neurolink sagemaker validate # Show current configuration npx @juspay/neurolink sagemaker config # Performance benchmark npx @juspay/neurolink sagemaker benchmark my-endpoint # List available endpoints (requires AWS CLI) npx @juspay/neurolink sagemaker list-endpoints ``` ### Timeout Configuration Configure request timeouts for SageMaker endpoints: ```bash export SAGEMAKER_TIMEOUT="60000" # 60 seconds for large models ``` ### Prerequisites 1. **SageMaker Endpoint**: Deploy a model to SageMaker and get the endpoint name 2. **AWS IAM Permissions**: Ensure your credentials have `sagemaker:InvokeEndpoint` permission 3. **Endpoint Status**: Endpoint must be in "InService" status ### IAM Policy Example ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["sagemaker:InvokeEndpoint"], "Resource": "arn:aws:sagemaker:*:*:endpoint/*" } ] } ``` ### Environment Variables Reference | Variable | Required | Default | Description | | ---------------------------- | -------- | --------- | ------------------------- | | `AWS_ACCESS_KEY_ID` | ✅ | - | AWS access key | | `AWS_SECRET_ACCESS_KEY` | ✅ | - | AWS secret key | | `AWS_REGION` | ✅ | us-east-1 | AWS region | | `SAGEMAKER_DEFAULT_ENDPOINT` | ✅ | - | SageMaker endpoint name | | `SAGEMAKER_TIMEOUT` | ❌ | 30000 | Request timeout (ms) | | `SAGEMAKER_MAX_RETRIES` | ❌ | 3 | Retry attempts | | `AWS_SESSION_TOKEN` | ❌ | - | For temporary credentials | ### Complete SageMaker Guide For endpoint setup, permissions and production deployment: **[ Amazon SageMaker Provider Guide](/docs/getting-started/providers/sagemaker)** - Includes: - Model endpoint deployment - Environment and client configuration - IAM policies and VPC connectivity - Feature support (streaming, embeddings, tools, structured output) - Troubleshooting ## Google Vertex AI Configuration {#vertex} NeuroLink supports **three authentication methods** for Google Vertex AI to accommodate different deployment environments: ### Method 1: Service Account File (Recommended for Production) Best for production environments where you can store service account files securely. ```bash export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json" export GOOGLE_VERTEX_PROJECT="your-project-id" export GOOGLE_VERTEX_LOCATION="us-central1" ``` **Setup Steps:** 1. Create a service account in Google Cloud Console 2. Download the service account JSON file 3. Set the file path in `GOOGLE_APPLICATION_CREDENTIALS` ### Method 2: Service Account JSON String (Good for Containers/Cloud) Best for containerized environments where file storage is limited. ```bash export GOOGLE_SERVICE_ACCOUNT_KEY='{"type":"service_account","project_id":"your-project",...}' export GOOGLE_VERTEX_PROJECT="your-project-id" export GOOGLE_VERTEX_LOCATION="us-central1" ``` **Setup Steps:** 1. Copy the entire contents of your service account JSON file 2. Set it as a single-line string in `GOOGLE_SERVICE_ACCOUNT_KEY` 3. NeuroLink will automatically create a temporary file for authentication ### Method 3: Individual Environment Variables (Good for CI/CD) Best for CI/CD pipelines where individual secrets are managed separately. ```bash export GOOGLE_AUTH_CLIENT_EMAIL="service-account@project.iam.gserviceaccount.com" export GOOGLE_AUTH_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIE..." export GOOGLE_VERTEX_PROJECT="your-project-id" export GOOGLE_VERTEX_LOCATION="us-central1" ``` **Setup Steps:** 1. Extract `client_email` and `private_key` from your service account JSON 2. Set them as individual environment variables 3. NeuroLink will automatically assemble them into a temporary service account file ### Authentication Detection NeuroLink automatically detects and uses the best available authentication method in this order: 1. **File Path** (`GOOGLE_APPLICATION_CREDENTIALS`) - if file exists 2. **JSON String** (`GOOGLE_SERVICE_ACCOUNT_KEY`) - if provided 3. **Individual Variables** (`GOOGLE_AUTH_CLIENT_EMAIL` + `GOOGLE_AUTH_PRIVATE_KEY`) - if both provided ### Complete Vertex AI Configuration ```bash # Required for all methods export GOOGLE_VERTEX_PROJECT="your-gcp-project-id" # Optional export GOOGLE_VERTEX_LOCATION="us-east5" # Default: us-east5 export VERTEX_MODEL_ID="claude-sonnet-4@20250514" # Default model # Choose ONE authentication method: # Method 1: Service Account File export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json" # Method 2: Service Account JSON String export GOOGLE_SERVICE_ACCOUNT_KEY='{"type":"service_account","project_id":"your-project","private_key_id":"...","private_key":"-----BEGIN PRIVATE KEY-----\n...","client_email":"...","client_id":"...","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_x509_cert_url":"..."}' # Method 3: Individual Environment Variables export GOOGLE_AUTH_CLIENT_EMAIL="service-account@your-project.iam.gserviceaccount.com" export GOOGLE_AUTH_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC...\n-----END PRIVATE KEY-----" ``` ### Usage Example ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain quantum computing" }, provider: "vertex", model: "gemini-2.5-flash", temperature: 0.6, maxTokens: 800, timeout: "1m", // Optional: Override default 60s timeout }); ``` ### Timeout Configuration - **Default Timeout**: 60 seconds (longer due to GCP initialization) - **Supported Formats**: Milliseconds (`60000`), human-readable (`'60s'`, `'1m'`, `'2m'`) - **Environment Variable**: `VERTEX_TIMEOUT='90s'` (optional) ### Supported Models **Gemini 3 (Preview):** - `gemini-3-flash-preview` - Latest Gemini 3 Flash with extended thinking support - `gemini-3-pro-preview` - Latest Gemini 3 Pro with extended thinking support **Gemini 2.x:** - `gemini-2.5-flash` (default) - Fast, efficient model **Anthropic Models:** - `claude-sonnet-4@20250514` - High-quality reasoning (Anthropic via Vertex AI) **Video Generation:** - `veo-3.1` / `veo-3.1-generate-001` - Video generation from image + text prompt (8-second videos with audio) > **Video Generation:** Use `output.mode: "video"` with Veo 3.1 to generate videos. See [Video Generation Guide](/docs/features/video-generation). > **PPT Generation:** Use `output.mode: "ppt"` with supported providers (Vertex AI, Google AI, OpenAI, Anthropic, Azure OpenAI, or Bedrock) and compatible text models to generate PowerPoint presentations. See [PPT Generation Guide](/docs/features/ppt-generation). ### Gemini 3 Extended Thinking Configuration Gemini 3 models support **extended thinking** (also known as "thinking mode"), which allows the model to reason more deeply before providing responses. This is particularly useful for complex reasoning tasks, math problems, and multi-step analysis. #### Environment Variables for Gemini 3 ```bash # Required: Google Vertex AI credentials (same as above) export GOOGLE_VERTEX_PROJECT="your-project-id" export GOOGLE_VERTEX_LOCATION="us-central1" # Gemini 3 model selection export VERTEX_MODEL_ID="gemini-3-flash-preview" # or gemini-3-pro-preview ``` #### Extended Thinking Configuration Configure thinking level to control how much reasoning the model performs: ```typescript const neurolink = new NeuroLink(); // Enable extended thinking with thinkingLevel configuration const result = await neurolink.generate({ input: { text: "Solve this complex math problem step by step: ..." }, provider: "vertex", model: "gemini-3-flash-preview", temperature: 0.7, maxTokens: 4000, // Gemini 3 extended thinking configuration thinkingLevel: "medium", // Options: "minimal", "low", "medium", "high" }); ``` #### Thinking Levels | Level | Description | Best For | | --------- | --------------------------------------- | --------------------------------- | | `minimal` | No extended thinking, fastest responses | Simple queries, quick answers | | `low` | Brief reasoning before responding | Moderate complexity tasks | | `medium` | Balanced reasoning depth (recommended) | Most use cases | | `high` | Deep reasoning, thorough analysis | Complex math, multi-step problems | #### Usage Example with Extended Thinking ```typescript const neurolink = new NeuroLink(); // Complex reasoning task with high thinking level const result = await neurolink.generate({ input: { text: "Analyze the following business scenario and provide strategic recommendations...", }, provider: "vertex", model: "gemini-3-pro-preview", thinkingLevel: "high", maxTokens: 8000, timeout: "2m", // Extended timeout for deep thinking }); console.log(result.content); ``` #### CLI Usage with Gemini 3 ```bash # Generate with Gemini 3 Flash npx @juspay/neurolink generate "Explain quantum computing" --provider vertex --model gemini-3-flash-preview # Stream with Gemini 3 Pro npx @juspay/neurolink stream "Write a detailed analysis" --provider vertex --model gemini-3-pro-preview ``` ### Claude Sonnet 4 via Vertex AI Configuration NeuroLink provides first-class support for Claude Sonnet 4 through Google Vertex AI. This configuration has been thoroughly tested and verified working. #### Working Configuration Example ```bash # ✅ VERIFIED WORKING CONFIGURATION export GOOGLE_VERTEX_PROJECT="your-project-id" export GOOGLE_VERTEX_LOCATION="us-east5" export GOOGLE_AUTH_CLIENT_EMAIL="service-account@your-project.iam.gserviceaccount.com" export GOOGLE_AUTH_PRIVATE_KEY="-----BEGIN PRIVATE KEY----- [Your private key content here] --" ``` #### Performance Metrics (Verified) - **Generation Response**: ~2.6 seconds - **Health Check**: Working status detection - **Streaming**: Fully functional - **Tool Integration**: Ready for MCP tools #### Usage Examples ```bash # Generation test node dist/cli/index.js generate "test" --provider vertex --model claude-sonnet-4@20250514 # Streaming test node dist/cli/index.js stream "Write a short poem" --provider vertex --model claude-sonnet-4@20250514 # Health check node dist/cli/index.js status # Expected: vertex: ✅ Working (2599ms) ``` ### Google Cloud Setup Requirements To use Google Vertex AI, ensure your Google Cloud project has: 1. **Vertex AI API Enabled**: Enable the Vertex AI API in your project 2. **Service Account**: Create a service account with Vertex AI permissions 3. **Model Access**: Ensure access to the models you want to use 4. **Billing Enabled**: Vertex AI requires an active billing account ### Service Account Permissions Your service account needs these IAM roles: - `Vertex AI User` or `Vertex AI Admin` - `Service Account Token Creator` (if using impersonation) ## Google AI Studio Configuration {#google-ai} Google AI Studio provides direct access to Google's Gemini models with a simple API key authentication. ### Basic Setup ```bash export GOOGLE_AI_API_KEY="AIza-your-google-ai-api-key" ``` ### Optional Configuration ```bash export GOOGLE_AI_MODEL="gemini-2.5-pro" # Default model to use ``` ### Supported Models - `gemini-2.5-pro` - Comprehensive, detailed responses for complex tasks - `gemini-2.5-flash` (recommended) - Fast, efficient responses for most tasks ### Usage Example ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain the future of AI" }, provider: "google-ai", model: "gemini-2.5-flash", temperature: 0.7, maxTokens: 1000, timeout: "30s", // Optional: Override default 30s timeout }); ``` ### Timeout Configuration - **Default Timeout**: 30 seconds - **Supported Formats**: Milliseconds (`30000`), human-readable (`'30s'`, `'1m'`, `'5m'`) - **Environment Variable**: `GOOGLE_AI_TIMEOUT='45s'` (optional) ### How to Get Google AI Studio API Key 1. **Visit Google AI Studio**: Go to [aistudio.google.com](https://aistudio.google.com) 2. **Sign In**: Use your Google account credentials 3. **Create API Key**: - Navigate to the **API Keys** section - Click **Create API Key** - Copy the generated key (starts with `AIza`) 4. **Set Environment**: Add to your `.env` file or export directly ### Google AI Studio vs Vertex AI | Feature | Google AI Studio | Google Vertex AI | | ----------------------- | --------------------------- | ---------------------------- | | **Setup Complexity** | Simple (API key only) | Complex (Service account) | | **Authentication** | API key | Service account JSON | | **Free Tier** | ✅ Generous free limits | ❌ Pay-per-use only | | **Enterprise Features** | ❌ Limited | ✅ Full enterprise support | | **Model Selection** | Latest Gemini models | Broader model catalog | | **Best For** | Prototyping, small projects | Production, enterprise apps | ### Complete Google AI Studio Configuration ```bash # Required: API key from Google AI Studio (choose one) export GOOGLE_AI_API_KEY="AIza-your-google-ai-api-key" # OR export GOOGLE_GENERATIVE_AI_API_KEY="AIza-your-google-ai-api-key" # Optional: Default model selection export GOOGLE_AI_MODEL="gemini-2.5-pro" ``` ### Rate Limits and Quotas Google AI Studio includes generous free tier limits: - **Free Tier**: 15 requests per minute, 1,500 requests per day - **Paid Usage**: Higher limits available with billing enabled - **Model-Specific**: Different models may have different rate limits ### Error Handling for Google AI Studio ```typescript const neurolink = new NeuroLink(); try { const result = await neurolink.generate({ input: { text: "Generate a creative story" }, provider: "google-ai", temperature: 0.8, maxTokens: 500, }); console.log(result.content); } catch (error) { if (error.message.includes("API_KEY_INVALID")) { console.error( "Invalid Google AI API key. Check your GOOGLE_AI_API_KEY environment variable.", ); } else if (error.message.includes("QUOTA_EXCEEDED")) { console.error("Rate limit exceeded. Wait before making more requests."); } else { console.error("Google AI Studio error:", error.message); } } ``` ### Security Considerations - **API Key Security**: Treat API keys as sensitive credentials - **Environment Variables**: Never commit API keys to version control - **Rate Limiting**: Implement client-side rate limiting for production apps - **Monitoring**: Monitor usage to avoid unexpected charges ## LiteLLM Configuration LiteLLM provides access to 100+ models through a unified proxy server, allowing you to use supported AI providers through a single interface. ### Prerequisites 1. Install LiteLLM: ```bash pip install litellm ``` 2. Start LiteLLM proxy server: ```bash # Basic usage litellm --port 4000 # With configuration file (recommended) litellm --config litellm_config.yaml --port 4000 ``` ### Basic Setup ```bash export LITELLM_BASE_URL="http://localhost:4000" export LITELLM_API_KEY="sk-anything" # Optional, any value works ``` ### Optional Configuration ```bash export LITELLM_MODEL="openai/gpt-4o-mini" # Default model to use ``` ### Supported Model Formats LiteLLM uses the `provider/model` format: ```bash # OpenAI models openai/gpt-4o openai/gpt-4o-mini openai/gpt-4 # Anthropic models anthropic/claude-3-5-sonnet anthropic/claude-3-haiku # Google models google/gemini-2.0-flash vertex_ai/gemini-pro # Mistral models mistral/mistral-large mistral/mixtral-8x7b # And many more... ``` ### LiteLLM Configuration File (Optional) Create `litellm_config.yaml` for advanced configuration: ```yaml model_list: - model_name: openai/gpt-4o litellm_params: model: gpt-4o api_key: os.environ/OPENAI_API_KEY - model_name: anthropic/claude-3-5-sonnet litellm_params: model: claude-3-5-sonnet-20241022 api_key: os.environ/ANTHROPIC_API_KEY - model_name: google/gemini-2.0-flash litellm_params: model: gemini-2.0-flash api_key: os.environ/GOOGLE_AI_API_KEY ``` ### Usage Example ```typescript const neurolink = new NeuroLink(); // Use LiteLLM provider with specific model const result = await neurolink.generate({ input: { text: "Explain quantum computing" }, provider: "litellm", model: "openai/gpt-4o", temperature: 0.7, }); console.log(result.content); ``` ### Advanced Features - **Cost Tracking**: Built-in usage and cost monitoring - **Load Balancing**: Automatic failover between providers - **Rate Limiting**: Built-in rate limiting and retry logic - **Caching**: Optional response caching for efficiency ### Production Considerations - **Deployment**: Run LiteLLM proxy as a separate service - **Security**: Configure authentication for production environments - **Scaling**: Use Docker/Kubernetes for high-availability deployments - **Monitoring**: Enable logging and metrics collection ## Hugging Face Configuration {#huggingface} ### Basic Setup ```bash export HUGGINGFACE_API_KEY="hf_your_token_here" ``` ### Optional Configuration ```bash export HUGGINGFACE_MODEL="Qwen/Qwen2.5-72B-Instruct" # Default model ``` ### Model Selection Strategy Hugging Face hosts 100,000+ models. Choose based on: - **Task**: text-generation, conversational, code - **Size**: Larger models = better quality but slower - **License**: Check model licenses for commercial use ### Rate Limiting - Free tier: Limited requests - PRO tier: Higher limits - Handle 503 errors (model loading) with retry logic ### Usage Example ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain machine learning" }, provider: "huggingface", model: "gpt2", temperature: 0.8, maxTokens: 200, timeout: "45s", // Optional: Override default 30s timeout }); ``` ### Timeout Configuration - **Default Timeout**: 30 seconds - **Supported Formats**: Milliseconds (`30000`), human-readable (`'30s'`, `'1m'`, `'5m'`) - **Environment Variable**: `HUGGINGFACE_TIMEOUT='45s'` (optional) - **Note**: Model loading may take additional time on first request ### Popular Models - `Qwen/Qwen2.5-72B-Instruct` (default) - tool-capable, strong multilingual - `meta-llama/Llama-3.1-8B-Instruct` - fastest of the served set, tool-capable - `meta-llama/Llama-3.3-70B-Instruct` - stronger general reasoning - `deepseek-ai/DeepSeek-V3` - highest quality of the served set - `Qwen/Qwen2.5-Coder-32B-Instruct` - code-focused - Any id listed by `GET https://router.huggingface.co/v1/models` ### Getting Started with Hugging Face 1. **Create Account**: Visit [huggingface.co](https://huggingface.co) 2. **Generate Token**: Go to Settings → Access Tokens 3. **Create Token**: Click "New token" with "read" scope 4. **Set Environment**: Export token as `HUGGINGFACE_API_KEY` ## Ollama Configuration {#ollama} ### Local Installation Required Ollama must be installed and running locally. ### Installation Steps 1. **macOS**: ```bash brew install ollama # or curl -fsSL https://ollama.ai/install.sh | sh ``` 2. **Linux**: ```bash curl -fsSL https://ollama.ai/install.sh | sh ``` 3. **Windows**: Download from [ollama.ai](https://ollama.ai) ### Model Management ```bash # List models ollama list # Pull new model ollama pull llama2 # Remove model ollama rm llama2 ``` ### Privacy Benefits - **100% Local**: No data leaves your machine - **No API Keys**: No authentication required - **Offline Capable**: Works without internet ### Usage Example ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Write a poem about privacy" }, provider: "ollama", model: "llama2", temperature: 0.7, maxTokens: 300, timeout: "10m", // Optional: Override default 5m timeout }); ``` ### Timeout Configuration - **Default Timeout**: 5 minutes (longer for local model processing) - **Supported Formats**: Milliseconds (`300000`), human-readable (`'5m'`, `'10m'`, `'30m'`) - **Environment Variable**: `OLLAMA_TIMEOUT='10m'` (optional) - **Note**: Local models may need longer timeouts for complex prompts ### Popular Models - `llama2` (default) - Meta's Llama 2 - `codellama` - Code-specialized Llama - `mistral` - Mistral 7B - `vicuna` - Fine-tuned Llama - `phi` - Microsoft's small model ### Environment Variables ```bash # Optional: Custom Ollama server URL export OLLAMA_BASE_URL="http://localhost:11434" # Optional: Default model export OLLAMA_MODEL="llama2" ``` ### Performance Optimization ```bash # Set memory limit OLLAMA_MAX_MEMORY=8GB ollama serve # Use specific GPU OLLAMA_CUDA_DEVICE=0 ollama serve ``` ## OpenRouter Configuration {#openrouter} OpenRouter provides access to 300+ AI models from 60+ providers through a single unified API with automatic failover and cost optimization. ### Basic Setup ```bash export OPENROUTER_API_KEY="sk-or-v1-your-api-key" ``` ### Optional Configuration ```bash # Attribution for OpenRouter dashboard export OPENROUTER_REFERER="https://yourapp.com" export OPENROUTER_APP_NAME="Your App Name" # Default model export OPENROUTER_MODEL="anthropic/claude-3-5-sonnet" ``` ### Supported Models OpenRouter supports 300+ models including: - `anthropic/claude-3-5-sonnet` (default) - Best overall quality - `openai/gpt-4o` - Excellent code generation - `google/gemini-2.0-flash` - Fast and cost-effective - `meta-llama/llama-3.1-70b-instruct` - Best open source ### Usage Example ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain quantum computing" }, provider: "openrouter", model: "anthropic/claude-3-5-sonnet", temperature: 0.7, maxTokens: 500, }); ``` ### Complete Guide For comprehensive OpenRouter setup including model selection, cost optimization, and best practices, see the [OpenRouter Provider Guide](/docs/getting-started/providers/openrouter). ## Mistral AI Configuration {#mistral} ### Basic Setup ```bash export MISTRAL_API_KEY="your_mistral_api_key" ``` ### European Compliance - GDPR compliant - Data processed in Europe - No training on user data ### Model Selection - **mistral-tiny**: Fast responses, basic tasks - **mistral-small**: Balanced choice (default) - **mistral-medium**: Complex reasoning - **mistral-large**: Maximum capability ### Cost Optimization Mistral offers competitive pricing: - Tiny: $0.14 / 1M tokens - Small: $0.6 / 1M tokens - Medium: $2.5 / 1M tokens - Large: $8 / 1M tokens ### Usage Example ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Translate to French: Hello world" }, provider: "mistral", model: "mistral-small", temperature: 0.3, maxTokens: 100, timeout: "30s", // Optional: Override default 30s timeout }); ``` ### Timeout Configuration - **Default Timeout**: 30 seconds - **Supported Formats**: Milliseconds (`30000`), human-readable (`'30s'`, `'1m'`, `'5m'`) - **Environment Variable**: `MISTRAL_TIMEOUT='45s'` (optional) ### Getting Started with Mistral AI 1. **Create Account**: Visit [mistral.ai](https://mistral.ai) 2. **Get API Key**: Navigate to API Keys section 3. **Generate Key**: Create new API key 4. **Add Billing**: Set up payment method ### Environment Variables ```bash # Required: API key export MISTRAL_API_KEY="your_mistral_api_key" # Optional: Default model export MISTRAL_MODEL="mistral-small" # Optional: Custom endpoint export MISTRAL_ENDPOINT="https://api.mistral.ai" ``` ### Multilingual Support Mistral models excel at multilingual tasks: - English, French, Spanish, German, Italian - Code generation in multiple programming languages - Translation between supported languages ## Anthropic Configuration {#anthropic} Direct access to Anthropic's Claude models. Supports both API key and OAuth (Claude subscription) authentication. ### Basic Setup ```bash # Option 1: API key authentication export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here" # Option 2: OAuth authentication (Claude Pro/Max subscribers) neurolink auth login anthropic ``` ### Optional Configuration ```bash export ANTHROPIC_MODEL="claude-3-5-sonnet-20241022" # Default model ``` ### Supported Models - `claude-opus-4-5-20251101` - Claude 4.5 Opus (most capable) - `claude-sonnet-4-5-20250929` - Claude 4.5 Sonnet - `claude-haiku-4-5-20251001` - Claude 4.5 Haiku (fastest) - `claude-opus-4-1-20250805` - Claude 4.1 Opus - `claude-opus-4-20250514` - Claude 4.0 Opus - `claude-sonnet-4-20250514` - Claude 4.0 Sonnet - `claude-3-7-sonnet-20250219` - Claude 3.7 Sonnet ### Usage Example ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain quantum computing" }, provider: "anthropic", model: "claude-3-5-sonnet-20241022", temperature: 0.7, maxTokens: 1000, timeout: "30s", }); ``` ### Timeout Configuration - **Default Timeout**: 30 seconds - **Supported Formats**: Milliseconds (`30000`), human-readable (`'30s'`, `'1m'`, `'5m'`) - **Environment Variable**: `ANTHROPIC_TIMEOUT='45s'` (optional) ### Getting Started with Anthropic 1. **API Key**: Visit [console.anthropic.com](https://console.anthropic.com), navigate to API Keys, and export as `ANTHROPIC_API_KEY` 2. **OAuth (Subscription)**: Run `neurolink auth login anthropic` to authenticate with your Claude Pro/Max subscription ### Complete Guide For comprehensive Anthropic setup including OAuth configuration, subscription tiers, and advanced options, see the [Detailed Anthropic Provider Guide](/docs/getting-started/providers/anthropic) and the [Claude Subscription Guide](/docs/features/claude-subscription). ## Azure OpenAI Configuration {#azure} Azure OpenAI provides enterprise-grade access to OpenAI models through Microsoft Azure. ### Basic Setup ```bash export AZURE_OPENAI_API_KEY="your-azure-openai-key" export AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/" export AZURE_OPENAI_DEPLOYMENT_ID="your-deployment-name" ``` ### Optional Configuration ```bash export AZURE_OPENAI_API_VERSION="2024-02-15-preview" # API version ``` ### Supported Models Azure OpenAI supports deployment of: - `gpt-4o` - Latest multimodal model - `gpt-4` - Advanced reasoning - `gpt-4-turbo` - Optimized performance - `gpt-3.5-turbo` - Cost-effective ### Usage Example ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain machine learning" }, provider: "azure", temperature: 0.7, maxTokens: 500, timeout: "30s", }); ``` ### Timeout Configuration - **Default Timeout**: 30 seconds - **Supported Formats**: Milliseconds (`30000`), human-readable (`'30s'`, `'1m'`, `'5m'`) - **Environment Variable**: `AZURE_TIMEOUT='45s'` (optional) ### Azure Setup Requirements 1. **Azure Subscription**: Active Azure subscription 2. **Azure OpenAI Resource**: Create Azure OpenAI resource in Azure Portal 3. **Model Deployment**: Deploy a model to get deployment ID 4. **API Key**: Get API key from resource's Keys and Endpoint section ### Environment Variables Reference | Variable | Required | Description | | ---------------------------- | -------- | ----------------------------- | | `AZURE_OPENAI_API_KEY` | ✅ | Azure OpenAI API key | | `AZURE_OPENAI_ENDPOINT` | ✅ | Resource endpoint URL | | `AZURE_OPENAI_DEPLOYMENT_ID` | ✅ | Model deployment name | | `AZURE_OPENAI_API_VERSION` | ❌ | API version (default: latest) | ## OpenAI Compatible Configuration {#openai-compatible} Connect to any OpenAI-compatible API endpoint (LocalAI, vLLM, Ollama with OpenAI compatibility, etc.) ### Basic Setup ```bash export OPENAI_COMPATIBLE_BASE_URL="http://localhost:8080/v1" export OPENAI_COMPATIBLE_API_KEY="optional-api-key" # Some servers don't require this ``` ### Optional Configuration ```bash export OPENAI_COMPATIBLE_MODEL="your-model-name" ``` ### Usage Example ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Hello from custom endpoint" }, provider: "openai-compatible", model: "your-model", temperature: 0.7, maxTokens: 500, }); ``` ### Compatible Servers This works with any server implementing the OpenAI API: - **LocalAI** - Local AI server - **vLLM** - High-performance inference server - **Ollama** (with `OLLAMA_OPENAI_COMPAT=1`) - **Text Generation WebUI** - **Custom inference servers** ### Environment Variables ```bash # Required: Base URL of your OpenAI-compatible server export OPENAI_COMPATIBLE_BASE_URL="http://localhost:8080/v1" # Optional: API key (if your server requires one) export OPENAI_COMPATIBLE_API_KEY="your-api-key-if-needed" # Optional: Default model name export OPENAI_COMPATIBLE_MODEL="your-model-name" ``` ## DeepSeek Configuration {#deepseek} DeepSeek provides cost-effective access to its own frontier models: the general-purpose V3 chat model and the R1 reasoning model. ### Basic Setup ```bash export DEEPSEEK_API_KEY="sk-your-deepseek-api-key" ``` ### Optional Configuration ```bash export DEEPSEEK_MODEL="deepseek-chat" # Default: deepseek-chat export DEEPSEEK_BASE_URL="https://api.deepseek.com" # Default base URL (override for compatible proxies) ``` ### Supported Models - `deepseek-chat` (default) - DeepSeek V3, high-quality general chat at low cost - `deepseek-reasoner` - DeepSeek R1, extended chain-of-thought reasoning (thinking mode) ### Usage Example ```typescript const neurolink = new NeuroLink(); // General chat with DeepSeek V3 const result = await neurolink.generate({ input: { text: "Explain transformers in simple terms" }, provider: "deepseek", model: "deepseek-chat", temperature: 0.7, maxTokens: 1000, }); // Extended reasoning with DeepSeek R1 const reasoned = await neurolink.generate({ input: { text: "Solve step by step: ..." }, provider: "deepseek", model: "deepseek-reasoner", thinkingLevel: "high", }); ``` ### CLI Usage ```bash # Use DeepSeek V3 npx @juspay/neurolink generate "Explain quantum computing" --provider deepseek # Use DeepSeek R1 with alias npx @juspay/neurolink generate "Solve this math problem" --provider ds --model deepseek-reasoner ``` ### Getting Started with DeepSeek 1. **Create Account**: Visit [platform.deepseek.com](https://platform.deepseek.com) 2. **Generate Key**: Navigate to **API Keys** and create a new key 3. **Add Billing**: Top up your account balance at [platform.deepseek.com/usage](https://platform.deepseek.com/usage) 4. **Set Environment**: Export `DEEPSEEK_API_KEY` ### Environment Variables Reference | Variable | Required | Default | Description | | ------------------- | -------- | -------------------------- | ------------------------------------------------------- | | `DEEPSEEK_API_KEY` | ✅ | - | DeepSeek API key | | `DEEPSEEK_MODEL` | ❌ | `deepseek-chat` | Model: `deepseek-chat` (V3) or `deepseek-reasoner` (R1) | | `DEEPSEEK_BASE_URL` | ❌ | `https://api.deepseek.com` | Override for proxies or alternative endpoints | ### Provider ID and Aliases - **Provider ID**: `deepseek` - **Aliases**: `ds` --- ## NVIDIA NIM Configuration {#nvidia-nim} NVIDIA NIM provides access to 400+ optimized models through NVIDIA's hosted cloud inference API, and also supports self-hosted NIM deployments. ### Basic Setup ```bash export NVIDIA_NIM_API_KEY="nvapi-your-nvidia-api-key" ``` ### Optional Configuration ```bash export NVIDIA_NIM_MODEL="openai/gpt-oss-20b" # Default model export NVIDIA_NIM_BASE_URL="https://integrate.api.nvidia.com/v1" # Default; override for self-hosted NIM ``` ### NIM-Specific Extras (Advanced) These environment variables pass NIM-specific request body extensions. Leave them unset unless you have a specific need: ```bash export NVIDIA_NIM_TOP_K="" # Integer; -1 or unset = disabled export NVIDIA_NIM_MIN_P="" # Float; 0 or unset = disabled export NVIDIA_NIM_REPETITION_PENALTY="" # Float; 1.0 or unset = disabled export NVIDIA_NIM_MIN_TOKENS="" # Integer; 0 or unset = disabled export NVIDIA_NIM_CHAT_TEMPLATE="" # Override model chat template (advanced) ``` ### Supported Models - `openai/gpt-oss-20b` (default) - OpenAI gpt-oss 20B, 128K context, tool calling - Any model from the [NVIDIA NIM catalog](https://build.nvidia.com/models) ### Usage Example ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain GPU architecture" }, provider: "nvidia-nim", model: "openai/gpt-oss-20b", temperature: 0.7, maxTokens: 1000, }); ``` ### CLI Usage ```bash # Use NVIDIA NIM with default model npx @juspay/neurolink generate "Explain GPU architecture" --provider nvidia-nim # Use nim alias npx @juspay/neurolink generate "Hello" --provider nim --model "mistralai/mistral-7b-instruct-v0.3" ``` ### Self-Hosted NIM Endpoints Override the base URL to point at your own NIM deployment: ```bash export NVIDIA_NIM_BASE_URL="http://your-nim-server:8000/v1" ``` ### Getting Started with NVIDIA NIM 1. **Create Account**: Visit [build.nvidia.com](https://build.nvidia.com/) 2. **Open Settings**: Navigate to **Settings → API Keys** 3. **Generate Key**: Create a new Bearer token API key 4. **Browse Models**: Explore the catalog at [build.nvidia.com/models](https://build.nvidia.com/models) 5. **Set Environment**: Export `NVIDIA_NIM_API_KEY` ### Environment Variables Reference | Variable | Required | Default | Description | | ------------------------------- | -------- | ------------------------------------- | --------------------------------------- | | `NVIDIA_NIM_API_KEY` | ✅ | - | NVIDIA NIM API key (Bearer token) | | `NVIDIA_NIM_MODEL` | ❌ | `openai/gpt-oss-20b` | Default model | | `NVIDIA_NIM_BASE_URL` | ❌ | `https://integrate.api.nvidia.com/v1` | Override for self-hosted NIM | | `NVIDIA_NIM_TOP_K` | ❌ | - | Top-K sampling parameter | | `NVIDIA_NIM_MIN_P` | ❌ | - | Min-P sampling parameter | | `NVIDIA_NIM_REPETITION_PENALTY` | ❌ | - | Repetition penalty | | `NVIDIA_NIM_MIN_TOKENS` | ❌ | - | Minimum tokens to generate | | `NVIDIA_NIM_CHAT_TEMPLATE` | ❌ | - | Override model chat template (advanced) | ### Provider ID and Aliases - **Provider ID**: `nvidia-nim` - **Aliases**: `nim`, `nvidia` --- ## LM Studio Configuration {#lm-studio} LM Studio is a local AI provider — it runs models entirely on your machine with no data sent to any external service. No API key is required for standard (non-proxied) installations. ### Prerequisites 1. Install LM Studio from [lmstudio.ai](https://lmstudio.ai/) 2. Open LM Studio and download a model from the **Discover** tab 3. Go to **Local Server** and click **Start Server** The server starts at `http://localhost:1234/v1` by default. NeuroLink auto-discovers the currently loaded model via `/v1/models` — you do not need to specify a model name. ### Optional Configuration ```bash export LM_STUDIO_BASE_URL="http://localhost:1234/v1" # Default; override if server is on a different host/port export LM_STUDIO_MODEL="" # Blank = auto-discover; set to force a specific model ID # export LM_STUDIO_API_KEY="your-key" # Only needed behind an auth-proxying reverse-proxy ``` ### Usage Example ```typescript const neurolink = new NeuroLink(); // Model is auto-discovered from LM Studio const result = await neurolink.generate({ input: { text: "Explain machine learning" }, provider: "lm-studio", temperature: 0.7, maxTokens: 500, }); // Or specify a model explicitly (must be loaded in LM Studio) const result2 = await neurolink.generate({ input: { text: "Write a poem" }, provider: "lm-studio", model: "lmstudio-community/Meta-Llama-3.1-8B-Instruct-GGUF", }); ``` ### CLI Usage ```bash # Auto-discover loaded model npx @juspay/neurolink generate "Hello from LM Studio" --provider lm-studio # Use alias npx @juspay/neurolink generate "Hello" --provider lmstudio ``` ### Notes - **API key**: Not required for vanilla LM Studio installs. Set `LM_STUDIO_API_KEY` only when running LM Studio behind an authenticating reverse-proxy. - **Model auto-discovery**: If the server is not running or has no model loaded, NeuroLink logs a warning and falls back gracefully. Start LM Studio and load a model, then retry. ### Timeout Configuration - **Default Timeout**: 5 minutes (longer for local CPU/GPU inference) - **Environment Variable**: `LM_STUDIO_TIMEOUT='10m'` (optional) ### Environment Variables Reference | Variable | Required | Default | Description | | -------------------- | -------- | -------------------------- | ----------------------------------------------------- | | `LM_STUDIO_BASE_URL` | ❌ | `http://localhost:1234/v1` | LM Studio server URL | | `LM_STUDIO_MODEL` | ❌ | _(auto-discovered)_ | Force a specific model ID; blank = use loaded model | | `LM_STUDIO_API_KEY` | ❌ | - | API key — only for reverse-proxy authenticated setups | ### Provider ID and Aliases - **Provider ID**: `lm-studio` - **Aliases**: `lmstudio`, `lms` --- ## llama.cpp Configuration {#llamacpp} llama.cpp's `llama-server` is a local AI provider — it runs GGUF models entirely on your machine. No API key is required for standard (non-proxied) installations. ### Prerequisites 1. Build llama.cpp: follow the [build instructions](https://github.com/ggerganov/llama.cpp#build) 2. Download a GGUF model file (e.g., from [Hugging Face](https://huggingface.co/models?library=gguf)) 3. Start the server: ```bash # Basic usage ./llama-server -m model.gguf --port 8080 # With tool/function-call support (required for MCP tools) ./llama-server -m model.gguf --port 8080 --jinja ``` The server starts at `http://localhost:8080/v1` by default. NeuroLink auto-discovers the loaded model via `/v1/models`. ### Optional Configuration ```bash export LLAMACPP_BASE_URL="http://localhost:8080/v1" # Default; override if server is on a different host/port export LLAMACPP_MODEL="" # Blank = auto-discover; set to force a specific model ID # export LLAMACPP_API_KEY="your-key" # Only needed behind an auth-proxying reverse-proxy ``` ### Usage Example ```typescript const neurolink = new NeuroLink(); // Model is auto-discovered from llama-server const result = await neurolink.generate({ input: { text: "Explain machine learning" }, provider: "llamacpp", temperature: 0.7, maxTokens: 500, }); ``` ### CLI Usage ```bash # Auto-discover loaded model npx @juspay/neurolink generate "Hello from llama.cpp" --provider llamacpp # Use alias npx @juspay/neurolink generate "Hello" --provider "llama.cpp" ``` ### Notes - **API key**: Not required for vanilla llama-server installs. Set `LLAMACPP_API_KEY` only when running behind an authenticating reverse-proxy. - **Tool support**: llama-server must be started with the `--jinja` flag to enable tool/function-call support. Without it, tool calls return a 400 error. - **Model auto-discovery**: llama-server hosts one model at a time. NeuroLink reads it from `/v1/models` automatically. - **Health check**: NeuroLink validates connectivity via the `/health` endpoint with up to 3 retries. ### Timeout Configuration - **Default Timeout**: 5 minutes (longer for local CPU/GPU inference) - **Environment Variable**: `LLAMACPP_TIMEOUT='10m'` (optional) ### Environment Variables Reference | Variable | Required | Default | Description | | ------------------- | -------- | -------------------------- | ----------------------------------------------------- | | `LLAMACPP_BASE_URL` | ❌ | `http://localhost:8080/v1` | llama-server URL | | `LLAMACPP_MODEL` | ❌ | _(auto-discovered)_ | Force a specific model ID; blank = use loaded model | | `LLAMACPP_API_KEY` | ❌ | - | API key — only for reverse-proxy authenticated setups | ### Provider ID and Aliases - **Provider ID**: `llamacpp` - **Aliases**: `llama.cpp` --- ## Redis Configuration {#redis} Redis integration for distributed conversation memory and session state. ### Basic Setup ```bash export REDIS_URL="redis://localhost:6379" ``` ### Optional Configuration ```bash export REDIS_PASSWORD="your-redis-password" # If authentication enabled export REDIS_DB="0" # Database number (default: 0) export REDIS_KEY_PREFIX="neurolink:" # Key prefix for namespacing ``` ### Advanced Configuration ```bash # Connection settings export REDIS_HOST="localhost" export REDIS_PORT="6379" export REDIS_TLS="false" # Set to "true" for TLS connections # Pool settings export REDIS_MAX_RETRIES="3" export REDIS_RETRY_DELAY="1000" # milliseconds export REDIS_CONNECTION_TIMEOUT="5000" # milliseconds ``` ### Usage Example ```typescript const neurolink = new NeuroLink({ memory: { type: "redis", url: process.env.REDIS_URL, }, }); const result = await neurolink.generate({ input: { text: "Remember this conversation" }, sessionId: "user-123", // Session stored in Redis }); ``` ### Redis Cloud Setup For managed Redis (Redis Cloud, AWS ElastiCache, etc.): ```bash export REDIS_URL="rediss://username:password@your-redis-host:6380" ``` ### Docker Redis (Development) ```bash # Start Redis in Docker docker run -d -p 6379:6379 redis:latest # Set environment export REDIS_URL="redis://localhost:6379" ``` ### Features Enabled by Redis - **Distributed Memory**: Share conversation state across instances - **Session Persistence**: Conversations survive application restarts - **Export/Import**: Export full session history as JSON - **Multi-tenant**: Isolate conversations by session ID - **Scalability**: Handle thousands of concurrent conversations ### Environment Variables Reference | Variable | Required | Default | Description | | ------------------ | --------------- | ---------- | ------------------------- | | `REDIS_URL` | Recommended | - | Full Redis connection URL | | `REDIS_HOST` | Alternative | localhost | Redis host | | `REDIS_PORT` | Alternative | 6379 | Redis port | | `REDIS_PASSWORD` | If auth enabled | - | Redis password | | `REDIS_DB` | ❌ | 0 | Database number | | `REDIS_KEY_PREFIX` | ❌ | neurolink: | Key prefix | ## Environment File Template Create a `.env` file in your project root: ```bash # NeuroLink Environment Configuration # OpenAI OPENAI_API_KEY=sk-your-openai-key-here OPENAI_MODEL=gpt-4o # Amazon Bedrock AWS_ACCESS_KEY_ID=your-aws-access-key AWS_SECRET_ACCESS_KEY=your-aws-secret-key AWS_REGION=us-east-2 AWS_SESSION_TOKEN=your-session-token # Optional: for temporary credentials BEDROCK_MODEL=arn:aws:bedrock:us-east-2::inference-profile/us.anthropic.claude-3-7-sonnet-20250219-v1:0 # Google Vertex AI (choose one method) # Method 1: File path GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/service-account.json # Method 2: JSON string (uncomment to use) # GOOGLE_SERVICE_ACCOUNT_KEY={"type":"service_account","project_id":"your-project",...} # Method 3: Individual variables (uncomment to use) # GOOGLE_AUTH_CLIENT_EMAIL=service-account@your-project.iam.gserviceaccount.com # GOOGLE_AUTH_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nYOUR_PRIVATE_KEY_HERE\n-----END PRIVATE KEY-----" # Required for all Google Vertex AI methods GOOGLE_VERTEX_PROJECT=your-gcp-project-id GOOGLE_VERTEX_LOCATION=us-east5 VERTEX_MODEL_ID=claude-sonnet-4@20250514 # Alternative: Gemini 3 models with extended thinking support # VERTEX_MODEL_ID=gemini-3-flash-preview # VERTEX_MODEL_ID=gemini-3-pro-preview # Google AI Studio GOOGLE_AI_API_KEY=AIza-your-googleAiStudio-key GOOGLE_AI_MODEL=gemini-2.5-pro # Anthropic ANTHROPIC_API_KEY=sk-ant-api03-your-key # Azure OpenAI AZURE_OPENAI_API_KEY=your-azure-key AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/" AZURE_OPENAI_DEPLOYMENT_ID=your-deployment-name # Hugging Face HUGGINGFACE_API_KEY=hf_your_token_here HUGGINGFACE_MODEL=Qwen/Qwen2.5-72B-Instruct # Optional # Ollama (Local AI) OLLAMA_BASE_URL=http://localhost:11434 # Optional OLLAMA_MODEL=llama2 # Optional # Mistral AI MISTRAL_API_KEY=your_mistral_api_key MISTRAL_MODEL=mistral-small # Optional # DeepSeek DEEPSEEK_API_KEY=sk-your-deepseek-key DEEPSEEK_MODEL=deepseek-chat # Optional (deepseek-chat or deepseek-reasoner) # NVIDIA NIM NVIDIA_NIM_API_KEY=nvapi-your-nvidia-key NVIDIA_NIM_MODEL=openai/gpt-oss-20b # Optional # LM Studio (local — no API key required) LM_STUDIO_BASE_URL=http://localhost:1234/v1 # Optional # llama.cpp (local — no API key required) LLAMACPP_BASE_URL=http://localhost:8080/v1 # Optional # Application Settings DEFAULT_PROVIDER=auto NEUROLINK_DEBUG=false ``` ## Provider Priority and Fallback ### Automatic Provider Selection NeuroLink automatically selects the best available provider when no provider is specified: ```typescript const neurolink = new NeuroLink(); // Automatically selects best available provider const result = await neurolink.generate({ input: { text: "Hello, world!" }, }); ``` ### Provider Priority Order The default priority order (most reliable first): 1. **OpenAI** - Most reliable, fastest setup 2. **Anthropic** - High quality, simple setup 3. **Google AI Studio** - Free tier, easy setup 4. **Azure OpenAI** - Enterprise reliable 5. **Google Vertex AI** - Good performance, multiple auth methods 6. **Mistral AI** - European compliance, competitive pricing 7. **Hugging Face** - Open source variety 8. **Amazon Bedrock** - High quality, requires careful setup 9. **Ollama** - Local only, no fallback ### Specifying Provider and Model ```typescript const neurolink = new NeuroLink(); // Explicitly specify provider and model const result = await neurolink.generate({ input: { text: "Hello" }, provider: "bedrock", model: "anthropic.claude-3-sonnet-20240229-v1:0", }); ``` ### Environment-Based Selection ```typescript const neurolink = new NeuroLink(); // Different providers for different environments const result = await neurolink.generate({ input: { text: "Hello" }, provider: process.env.NODE_ENV === "production" ? "bedrock" : "openai", model: process.env.NODE_ENV === "production" ? undefined : "gpt-4o-mini", }); ``` ## Testing Provider Configuration ### CLI Status Check ```bash # Test all providers npx @juspay/neurolink status --verbose # Expected output: # Checking AI provider status... # ✅ openai: ✅ Working (234ms) # ❌ bedrock: ❌ Invalid credentials - The security token included in the request is expired # ⚪ vertex: ⚪ Not configured - Missing environment variables ``` ### Programmatic Testing ```typescript async function testProviders() { const providers = [ "openai", "bedrock", "vertex", "anthropic", "azure", "google-ai", "huggingface", "ollama", "mistral", ]; const neurolink = new NeuroLink(); for (const providerName of providers) { try { const start = Date.now(); const result = await neurolink.generate({ input: { text: "Test" }, provider: providerName, maxTokens: 10, }); console.log(`✅ ${providerName}: Working (${Date.now() - start}ms)`); } catch (error) { console.log(`❌ ${providerName}: ${error.message}`); } } } testProviders(); ``` ## Common Configuration Issues ### OpenAI Issues ``` Error: Cannot find API key for OpenAI provider ``` **Solution**: Set `OPENAI_API_KEY` environment variable ### Bedrock Issues ``` Your account is not authorized to invoke this API operation ``` **Solutions**: 1. Use full inference profile ARN (not simple model name) 2. Check AWS account has Bedrock access 3. Verify IAM permissions include `bedrock:InvokeModel` 4. Ensure model access is enabled in your AWS region ### Vertex AI Issues ``` Cannot find package '@google-cloud/vertexai' ``` **Solution**: Install peer dependency: `npm install @google-cloud/vertexai` ``` Authentication failed ``` **Solutions**: 1. Verify service account JSON is valid 2. Check project ID is correct 3. Ensure Vertex AI API is enabled 4. Verify service account has proper permissions ## Security Best Practices ### Environment Variables - Never commit API keys to version control - Use different keys for development/staging/production - Rotate keys regularly - Use minimal permissions for service accounts ### AWS Security - Use IAM roles instead of access keys when possible - Enable CloudTrail for audit logging - Use VPC endpoints for additional security - Implement resource-based policies ### Google Cloud Security - Use service account keys with minimal permissions - Enable audit logging - Use VPC Service Controls for additional isolation - Rotate service account keys regularly ### General Security - Use environment-specific configurations - Implement rate limiting in your applications - Monitor usage and costs - Use HTTPS for all API communications --- ## OpenAI TTS Configuration {#openai-tts} OpenAI TTS provides text-to-speech synthesis using the same API key as the OpenAI LLM provider. No additional credentials are required. ### Basic Setup ```bash export OPENAI_API_KEY="sk-your-openai-api-key" ``` **Note:** `OPENAI_API_KEY` is shared with the OpenAI LLM provider. No separate key is needed. ### Supported Models - `tts-1` (default) - Optimized for speed, lower latency - `tts-1-hd` - Optimized for quality, higher fidelity audio ### Supported Voices `alloy`, `echo`, `fable`, `onyx`, `nova`, `shimmer` ### Supported Output Formats `mp3` (default), `opus`, `wav`, `ogg` ### Usage Example ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Hello, world!" }, tts: { enabled: true, provider: "openai-tts", voice: "alloy", format: "mp3", }, }); ``` ### CLI Usage ```bash npx @juspay/neurolink generate "Hello, world!" --tts --tts-provider openai-tts ``` ### Environment Variables Reference | Variable | Required | Default | Description | | ---------------- | -------- | ------- | ----------------------------------- | | `OPENAI_API_KEY` | ✅ | - | Shared with the OpenAI LLM provider | ### Provider ID and Aliases - **Provider ID**: `openai-tts` --- ## ElevenLabs Configuration {#elevenlabs} ElevenLabs provides high-quality, multilingual text-to-speech synthesis with a wide selection of voices and voice cloning support. ### Basic Setup ```bash export ELEVENLABS_API_KEY="your-elevenlabs-api-key" ``` ### How to Get ElevenLabs API Key 1. Visit [ElevenLabs](https://elevenlabs.io) 2. Sign up or log in to your account 3. Navigate to **Profile → API Key** 4. Copy the key ### Supported Models - `eleven_multilingual_v2` (default) - Best quality, 29 languages - `eleven_turbo_v2_5` - Low-latency streaming, 32 languages - `eleven_flash_v2_5` - Fastest, suitable for real-time applications ### Usage Example ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Bonjour le monde!" }, tts: { enabled: true, provider: "elevenlabs", voice: "Rachel", model: "eleven_multilingual_v2", }, }); ``` ### CLI Usage ```bash npx @juspay/neurolink generate "Hello, world!" --tts --tts-provider elevenlabs ``` ### Notes - **Multilingual support**: ElevenLabs models support up to 32 languages with natural prosody - **Voice cloning**: ElevenLabs supports custom voice IDs from your ElevenLabs account ### Environment Variables Reference | Variable | Required | Default | Description | | -------------------- | -------- | ------- | ------------------ | | `ELEVENLABS_API_KEY` | ✅ | - | ElevenLabs API key | ### Provider ID and Aliases - **Provider ID**: `elevenlabs` --- ## Deepgram STT Configuration {#deepgram} Deepgram provides fast, accurate speech-to-text transcription with support for real-time streaming and pre-recorded audio. ### Basic Setup ```bash export DEEPGRAM_API_KEY="your-deepgram-api-key" ``` ### How to Get Deepgram API Key 1. Visit [Deepgram Console](https://console.deepgram.com) 2. Sign up or log in to your account 3. Navigate to **API Keys** 4. Click **Create a New API Key** 5. Copy the key ### Supported Models - `nova-3` (default) - Latest, highest accuracy - `nova-2` - High accuracy, broad language support - `base` - Balanced accuracy and speed ### Usage Example ```typescript const neurolink = new NeuroLink(); const audioBuffer = readFileSync("audio.wav"); const result = await neurolink.generate({ input: { text: "Respond to what was said" }, stt: { enabled: true, provider: "deepgram", audio: audioBuffer, model: "nova-3", language: "en", }, }); ``` ### CLI Usage ```bash npx @juspay/neurolink generate "Respond to this" --stt --stt-provider deepgram --input-audio file.wav ``` ### Notes - **Streaming transcription**: Deepgram supports real-time audio streaming for live transcription - **Language support**: Deepgram nova models support 30+ languages ### Environment Variables Reference | Variable | Required | Default | Description | | ------------------ | -------- | ------- | ---------------- | | `DEEPGRAM_API_KEY` | ✅ | - | Deepgram API key | ### Provider ID and Aliases - **Provider ID**: `deepgram` (STT only — Deepgram's TTS product is not wired today) --- ## Whisper Configuration {#whisper} Whisper is OpenAI's speech-to-text model — registered as the provider id `whisper`. It accepts MP3, WAV, M4A, and FLAC inputs up to 25 MB. ```bash # Required environment variable OPENAI_API_KEY=sk-... ``` Get your API key from: **OpenAI Platform** > **API Keys**. ### Usage ```typescript const result = await neurolink.generate({ input: { text: "Repeat what was said" }, provider: "openai", stt: { enabled: true, provider: "whisper", audio: audioBuffer, format: "mp3", }, }); console.log(result.transcription?.text); ``` ### CLI ```bash neurolink generate "Repeat what was said" \ --provider openai \ --stt --stt-provider whisper --input-audio ./audio.mp3 ``` ### Provider ID - **Provider ID**: `whisper` --- ## Azure Speech Configuration {#azure-speech} Azure Cognitive Services Speech provides both TTS (`azure-tts`) and STT (`azure-stt`). ```bash # Required environment variables AZURE_SPEECH_KEY=your-speech-key AZURE_SPEECH_REGION=eastus ``` Get credentials from: **Azure Portal** > **Cognitive Services** > **Speech** > **Keys and Endpoint**. ### TTS Usage ```typescript const result = await neurolink.generate({ input: { text: "Hello world" }, tts: { enabled: true, provider: "azure-tts", voice: "en-US-JennyNeural", format: "mp3", }, }); ``` ### STT Usage > **MP3 not supported** — Azure's short-audio REST endpoint only decodes WAV > PCM and Ogg/Opus. Passing `format: "mp3"` to `azure-stt` throws > `STT_INVALID_AUDIO_FORMAT` early. Convert with > `ffmpeg -i in.mp3 -ar 16000 -ac 1 out.wav` first. ```typescript const result = await neurolink.generate({ input: { text: "" }, provider: "openai", stt: { enabled: true, provider: "azure-stt", audio: wavBuffer, format: "wav", language: "en-US", }, }); ``` ### Provider IDs - **TTS**: `azure-tts` - **STT**: `azure-stt` --- ## Fish Audio TTS Configuration {#fish-audio} Low-cost TTS provider focused on voice cloning. Wrapped as a TTSHandler so it slots into the same `generate({ tts: { provider: "fish-audio" } })` flow as OpenAI / ElevenLabs / Azure / Google AI TTS. ```bash # Required FISH_AUDIO_API_KEY=your-fish-audio-api-key # Optional: default voice (any reference_id from the Fish library) # FISH_AUDIO_VOICE_ID=... # Optional: base URL override # FISH_AUDIO_BASE_URL=https://api.fish.audio ``` Get an API key from [fish.audio](https://fish.audio/) → dashboard. ### Usage ```typescript const result = await neurolink.generate({ input: { text: "Hello world from Fish Audio" }, provider: "openai", tts: { enabled: true, provider: "fish-audio", format: "mp3", }, }); ``` - **Provider ID**: `fish-audio` - **Default model**: `s1` (override via `tts.model`: `speech-1.5`, `speech-1.6`, `s1`) - **Max text length**: 5000 characters - **Output formats**: `mp3` (default, 44.1 kHz), `wav` (44.1 kHz), `pcm16` (raw, 44.1 kHz) - **Languages**: 14 (English, Mandarin, Cantonese, Japanese, Korean, French, German, Spanish, Italian, Portuguese, Russian, Arabic, Hindi, Indonesian) - **Voice cloning**: 15 s of reference audio → custom `reference_id` Full guide: [Fish Audio TTS Provider](/docs/getting-started/providers/fish-audio). --- ## Cartesia TTS Configuration {#cartesia} Low-latency TTS provider running Cartesia's Sonic models. The synchronous `/tts/bytes` endpoint is wrapped as a TTSHandler; the realtime WebSocket flow is exposed separately as `CartesiaStream` for the voice server. ```bash # Required CARTESIA_API_KEY=sk_car_... # Optional: default voice id (any voice from your Cartesia library) # CARTESIA_VOICE_ID=... # Optional: model override (default sonic-3.6) # CARTESIA_MODEL=sonic-3.6 # Optional: API version header (default 2025-04-16) # CARTESIA_API_VERSION=2025-04-16 # Optional: base URL override # CARTESIA_BASE_URL=https://api.cartesia.ai ``` Get an API key from [play.cartesia.ai/keys](https://play.cartesia.ai/keys). ### Usage ```typescript const result = await neurolink.generate({ input: { text: "Hello world from Cartesia Sonic" }, provider: "openai", tts: { enabled: true, provider: "cartesia", format: "mp3", }, }); ``` - **Provider ID**: `cartesia` - **Default model**: `sonic-3.6` - **Default voice**: `694f9389-aac1-45b6-b726-9d9369183238` ("Bright Female", English) - **Max text length**: 5000 characters - **Output formats**: `mp3` (default, 44.1 kHz), `wav` (PCM s16le @ 44.1 kHz), `pcm16` (raw, 24 kHz) - **Streaming**: synchronous via this handler; WebSocket via `CartesiaStream` adapter Full guide: [Cartesia TTS Provider](/docs/getting-started/providers/cartesia). --- ## Google Speech Configuration {#google-speech} Covers both Google Cloud TTS (`google-tts` / via `google-ai`) and Google Cloud Speech-to-Text (`google-stt`). Both share the same service-account credentials. ```bash # Required environment variable GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json # OR (for TTS only) an API key GOOGLE_API_KEY=AIza... ``` > **Speech-to-Text API must be enabled** in your Google Cloud project for > `google-stt` to work. Enable it at > [console.cloud.google.com/apis/library/speech.googleapis.com](https://console.cloud.google.com/apis/library/speech.googleapis.com). ### TTS Usage ```typescript const result = await neurolink.generate({ input: { text: "Hello world" }, tts: { enabled: true, provider: "google-ai", voice: "en-US-Neural2-A", format: "mp3", }, }); ``` ### STT Usage ```typescript const result = await neurolink.generate({ input: { text: "" }, provider: "openai", stt: { enabled: true, provider: "google-stt", audio: audioBuffer, format: "mp3", }, }); ``` ### Provider IDs - **TTS**: `google-ai` (or `google-tts` alias) - **STT**: `google-stt` --- ## OpenAI Realtime Configuration {#openai-realtime} Real-time voice via the OpenAI Realtime WebSocket API. Provider id `openai-realtime` is registered for future use; the typical pattern is to launch the integrated voice server (`neurolink serve voice`) which wires this through Soniox/Cartesia. ```bash OPENAI_API_KEY=sk-... ``` ### Provider ID - **Provider ID**: `openai-realtime` - **Audio chunk format**: `pcm16` — raw 16-bit PCM at 24 kHz, **NOT** WAV-headered. Do not pass these chunks to a WAV duration parser. --- ## Gemini Live Configuration {#gemini-live} Real-time voice via Google's Gemini Live WebSocket API. Provider id `gemini-live` is registered for future use. ```bash GOOGLE_API_KEY=AIza... # OR GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json ``` ### Provider ID - **Provider ID**: `gemini-live` --- ## Streaming + Voice Patterns {#streaming-voice} ### `stream()` + STT (transcribe before stream) ```typescript const audio = readFileSync("./recording.mp3"); const r = await neurolink.stream({ input: { text: "" }, provider: "openai", stt: { enabled: true, provider: "whisper", audio, format: "mp3" }, }); console.log("transcription:", r.transcription?.text); // available before iterating for await (const chunk of r.stream) { if ("content" in chunk) process.stdout.write(chunk.content); } ``` ### `stream()` + TTS Mode 2 (synthesise the streamed reply) Two ergonomic options — both deliver byte-identical audio: ```typescript const r = await neurolink.stream({ input: { text: "Tell me a fact." }, provider: "openai", tts: { enabled: true, useAiResponse: true, provider: "openai-tts", format: "mp3", }, }); // --- Option A: collect inline while iterating --- const audioBufs: Buffer[] = []; for await (const c of r.stream) { if ("content" in c) process.stdout.write(c.content); else if (c.type === "audio") audioBufs.push(c.audio.data); } writeFileSync("./out.mp3", Buffer.concat(audioBufs)); // --- Option B: ergonomic Promise — read after the stream completes --- const tts = await r.audio; // resolves to TTSResult or undefined if (tts) writeFileSync("./out.mp3", tts.buffer); ``` When `tts.useAiResponse` is `false` (Mode 1) or TTS is not enabled, `r.audio` resolves to `undefined` rather than hanging. --- [← Back to Main README](/docs/) | [Next: API Reference →](/docs/sdk/api-reference) --- ## Aion Labs Provider Guide # Aion Labs Provider Guide Aion Labs is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/aionlabs.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** Every field below comes from Aion Labs' own public > documentation and an unauthenticated `GET /v1/models` call — no account was > created and no API key was used to build it. `evidence.liveMatrix` is `null` > until someone runs the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://www.aionlabs.ai/accounts/signup/ and sign up (GitHub, Google or email) 2. Create an API key from the dashboard's API keys page (https://www.aionlabs.ai/app/api-keys/, sign-in required) and copy it when it is shown 3. Free tier: the pricing page (https://www.aionlabs.ai/pricing/) offers a daily credit allowance with no card required; free-tier limits are 15 requests/min, 20,000 tokens/min and 20,000 tokens/day (https://www.aionlabs.ai/docs/rate-limits/) 4. Set `AIONLABS_API_KEY` in your .env file Whether a brand-new free account can create a key immediately, or waits on manual approval (the site header also carries a "Request Access" button), was not tested — no signup was performed to build this entry. ### 2. Configure ```bash export AIONLABS_API_KEY=your-api-key export AIONLABS_MODEL=aion-labs/aion-3.5 # optional — overrides the default model export AIONLABS_BASE_URL=https://api.aionlabs.ai/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Write the opening paragraph of a lighthouse mystery." }, provider: "aionlabs", model: "aion-labs/aion-3.5", maxTokens: 4096, }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider aionlabs --max-tokens 4096 ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "aionlabs", credentials: { aionlabs: { apiKey: process.env.AIONLABS_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | -------------------------------- | ------- | ------ | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `aion-labs/aion-3.5` ⭐ | 262,144 | no | $3.00 / $6.00 (cached $0.75) | Recommended — the model every request example on Aion Labs' quickstart uses; released 2026-09-23, the latest release date on the roster (shared with 3.5 Mini); GLM-family multi-model system. | | `aion-labs/aion-3.5-mini` | 262,144 | no | $0.70 / $1.40 (cached $0.18) | Released 2026-09-23; GLM-family multi-model system; roster-listed only; fallback. | | `aion-labs/aion-3.0` | 131,072 | no | $3.00 / $6.00 (cached $0.75) | Released 2026-05-05; GLM-family multi-model system; roster-listed only. | | `aion-labs/aion-3.0-mini` | 131,072 | no | $0.70 / $1.40 (cached $0.18) | Released 2026-05-14; DeepSeek-family multi-model system; roster-listed only; fallback. | | `aion-labs/aion-2.0` | 131,072 | no | $0.80 / $1.60 (cached $0.20) | Variant of DeepSeek V3.2 for roleplay and storytelling (2025-12-21); roster-listed only; fallback. | | `aion-labs/aion-rp-llama-3.1-8b` | 32,768 | no | $0.80 / $1.60 | Aion-RP 1.0 (8B), a Llama 3.1 8B variant (2024-11-30); the only non-reasoning model on the roster; roster-listed only. | Every model has a maximum completion of 32,768 tokens. Context comes from the `context_length` field of an unauthenticated `GET https://api.aionlabs.ai/v1/models` call made 2026-09-29 (6 models; the docs models page at https://www.aionlabs.ai/docs/models/ rounds the same values to 128K / 256K / 32K). Prices are the per-million-token figures on that docs models page, retrieved the same day; the roster's per-token `pricing` fields agree with them. `models.defaultContextWindow` (262,144) and `models.defaultMaxOutputTokens` (32,768) are the default model's own figures. The docs pricing page (https://www.aionlabs.ai/docs/pricing/) served the same table as the models page when it was fetched. **Fallback order** when the default is unavailable: `aion-labs/aion-3.5-mini` → `aion-labs/aion-3.0-mini` → `aion-labs/aion-2.0`. `vision` is `false` on every model because the roster reports `text->text` modality for all six; no image-input request was sent. --- ## Reasoning models The five `aion-3.x` and `aion-2.0` models are tagged "Reasoning" on the docs models page and `reasoning: true` on the roster; `aion-rp-llama-3.1-8b` is not. The API reference (https://www.aionlabs.ai/docs/api-reference/) documents two behaviours that matter when you call them through NeuroLink: - **Reasoning shares the `max_tokens` budget.** Reasoning is generated first, so a cap exhausted during reasoning returns `finish_reason=length` with empty `content`. Give these models a generous `maxTokens`; it is a ceiling, not a reservation, and unused budget is not billed. - **`reasoning_effort` differs by generation.** `aion-3.5` and `aion-3.5-mini` accept exactly `low`, `high` (default) or `max` and cannot have reasoning disabled — any other value returns a 400. `aion-2.0`, `aion-3.0` and `aion-3.0-mini` also accept `none` and `medium` (default `medium`). NeuroLink's catalog provider does not send `reasoning_effort`, so the vendor defaults apply. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Aion Labs — **docs- and roster-verified, not live-verified**: | Probe | Result | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /v1/models`, HTTP 200, 6 models, 2026-09-29 — no key used | | Billing | public pricing page states a Free Tier ("A daily credit allowance … No card required."); the rate-limits page lists Free as the default tier on signup, 2026-09-29. No signup was performed, so key issuance for a fresh account is unconfirmed | | Auth-failure shape | not documented — the API reference's error table lists only 400 `invalid_request_error`, 429 `rate_limit_error` and 502 `server_error`, and no credentialed request was made. The only `errorRules` entry is the documented 429; 401s use the default classifier | | Tools / structured output | tools are documented on the API reference but not per model and were not exercised live; no `response_format` parameter is documented, so `structuredOutput` is `false`; no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=aionlabs` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | Empty `content` with `finish_reason=length` | The `max_tokens` cap was used up by reasoning before any visible answer | Raise `maxTokens`; on the 3.5 models reasoning cannot be turned off | | HTTP 429 `rate_limit_error` | Usage limit exceeded — free tier is 15 requests/min, 20,000 tokens/min and 20,000 tokens/day | Wait, or top up credits to reach a higher tier (https://www.aionlabs.ai/docs/rate-limits/) | | HTTP 524 on a long request | Non-streaming responses must complete within 125 seconds; generation still finishes and is billed | Use streaming for large `maxTokens`, reasoning models and very long prompts | | HTTP 400 `invalid_request_error` | Unknown model or malformed request; an unsupported `reasoning_effort` value also returns 400 | Pick a current id from the unauthenticated `GET /v1/models` roster | | HTTP 502 `server_error` | Temporary server-side error | Retry the request | | Structured output ignored with tools attached | `structuredOutputWithTools` is `false` on this entry — untested combination | NeuroLink omits `response_format` automatically whenever tools are present, before sending | | Tool calls not returned | The API reference says the endpoint "Supports streaming and tool calls" but gives no per-model tool support, and none was tested | Unverified per model — check the request against the OpenAI tools format the API reference describes | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Ambient Provider Guide # Ambient Provider Guide Ambient is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/ambient.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status: docs- and roster-verified, not yet live-verified.** > This entry was built entirely from Ambient's public docs pages and an > unauthenticated `GET /v1/models` call — no API key was used or created. > `capabilities.tools` and `capabilities.structuredOutput` come from the live > roster's own self-reported `supported_features` field; the **combined** > capabilities (`structuredOutputWithTools`, `toolsWithStreaming`) are > deliberately left `false` because no live POST request was possible without > credentials. `evidence.liveMatrix` is `null` until someone runs the real > capability sweep with a working key. ## Quick Start ### 1. Get an API key 1. Visit: https://app.ambient.xyz and sign in 2. Click "Get API key" to create a key 3. Ambient has no free tier — the cheapest option is the $1/mo Starter plan (https://ambient.xyz/pricing); confirm current billing terms before use 4. Set `AMBIENT_API_KEY` in your .env file ### 2. Configure ```bash export AMBIENT_API_KEY=your-api-key export AMBIENT_MODEL=ambient/large # optional — overrides the default model export AMBIENT_BASE_URL=https://api.ambient.xyz/v1 # optional — proxy or override ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "ambient", model: "ambient/large", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider ambient ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "ambient", credentials: { ambient: { apiKey: process.env.AMBIENT_API_KEY } }, }); ``` --- ## Models | Model | Context | Max out | Vision | $/M in · out (cached in) | Notes | | ------------------ | ------- | ------- | ------ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ambient/large` ⭐ | 198K | 198K | no | $0.60 / $2.00 ($0.15) | Recommended — the model id used in every example in Ambient's own docs. A vendor-managed alias that today mirrors `z-ai/glm-5.2`; its specs "mirror whatever concrete model it currently points to." | | `z-ai/glm-5.2` | 198K | 198K | no | $0.60 / $2.00 ($0.15) | The concrete model `ambient/large` currently aliases. Docs call it "the supported production model." Fallback pinned to a stable id. | | `qwen/qwen3.6-27b` | 32K | 8K | yes | $0.32 / $3.20 ($0.16) | Natively multimodal (text + image), 27B dense. Docs mark non-GLM-5.2 entries as possible previews with no guarantees. Used as `visionModel`. | | `qwen/qwen3.8-27b` | 32K | 8K | yes | $0.32 / $3.20 ($0.16) | Roster description also claims "video" input, but the live roster's `input_modalities` lists only text/image, so no video support is declared here. Preview. | Context/output/pricing are taken from the unauthenticated `GET https://api.ambient.xyz/v1/models` response (2026-09-28) and cross-checked against Ambient's own docs models page, which shows the same numbers rounded (e.g. "198K" for 202,752 tokens). **Fallback order** when the default is unavailable: `z-ai/glm-5.2` → `qwen/qwen3.6-27b` → `qwen/qwen3.8-27b`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for Ambient — and, just as importantly, what it does **not** yet record: | Probe | Result | | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated GET `/v1/models`, HTTP 200, 4 models, 2026-09-28 — no API key used | | Auth rejection | **not probed** — would require a POST, which is out of scope credential-free | | Live capability sweep | **not run** (`evidence.liveMatrix` is `null`). `tools` and `structuredOutput` are set `true` from the live roster's own `supported_features` field (present on all 4 models today), not from a live request. `structuredOutputWithTools` and `toolsWithStreaming` are both `false` because no combined tools+schema or tools+streaming request was possible without a key. | This entry should be treated as **docs- and roster-verified, not live-verified**. Before relying on it in production, run the live matrix: ```bash npx tsx test/continuous-test-suite-provider-matrix.ts --provider=ambient node dist/cli/index.js generate "hello" --provider ambient ``` and record the outcome in `evidence.liveMatrix`. --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- | | `Invalid Ambient API key` | `AMBIENT_API_KEY` unset or wrong | Check the key at https://app.ambient.xyz | | Model not found (HTTP 400) | Ambient returns `400` "Unknown model" for a bad id, not `404` | Pick a current id from the unauthenticated `GET /v1/models` roster | | `429` with "No workers available" | Ambient's docs describe this as a capacity/upstream issue, not a true rate limit | Retry with short jittered backoff, or switch to another model from `GET /v1/models` | | Empty/cut-off content | `ambient/large` and `z-ai/glm-5.2` are reasoning models; the docs say `max_tokens` "caps reasoning + answer" | Give reasoning prompts a generous `maxTokens` budget | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Anthropic Provider Guide # Anthropic Provider Guide **Direct access to Claude models with flexible authentication options** -------- | -------------------------------------- | ------------------ | | **API Key** | Production, server-side apps | Pay-per-token | | **OAuth** | Personal dev with Pro/Max subscription | Subscription quota | --- ## Quick Start ### 1. Get Your API Key 1. Visit [console.anthropic.com](https://console.anthropic.com) 2. Sign in or create an account 3. Navigate to **API Keys** section 4. Click **Create Key** 5. Copy your new API key (starts with `sk-ant-`) ### 2. Configure Environment Add to your `.env` file: ```bash # Required: Your Anthropic API key ANTHROPIC_API_KEY=sk-ant-api03-your-key-here # Optional: Override default model (defaults to claude-sonnet-4-6) ANTHROPIC_MODEL=claude-sonnet-4-6 ``` ### 3. Test the Setup ```typescript const ai = new NeuroLink(); const result = await ai.generate({ input: { text: "Explain quantum computing in simple terms" }, provider: "anthropic", model: "claude-sonnet-4-6", }); console.log(result.content); ``` ```bash # Quick generation pnpm run cli -- generate "Hello from Claude!" \ --provider anthropic # Use specific model pnpm run cli -- generate "Write a haiku about AI" \ --provider anthropic \ --model "claude-sonnet-4-6" # Interactive loop mode pnpm run cli -- loop \ --provider anthropic \ --model "claude-sonnet-4-6" ``` --- ## Supported Models ### Available Models (from `AnthropicModels` enum) | Enum Key | Model ID | Family | Context | Max Output | Vision | Extended Thinking | Deprecated | | ------------------- | ---------------------------- | ------ | ------- | ---------- | ------ | ----------------- | ---------- | | `CLAUDE_OPUS_5_5` | `claude-opus-5-5` | Opus | 1M | 128,000 | Yes | Yes | No | | `CLAUDE_FABLE_5_1` | `claude-fable-5-1` | Fable | 1M | 128,000 | Yes | Yes | No | | `CLAUDE_OPUS_4_6` | `claude-opus-4-6` | Opus | 1M | 128,000 | Yes | Yes | No | | `CLAUDE_SONNET_4_6` | `claude-sonnet-4-6` | Sonnet | 1M | 64,000 | Yes | Yes | No | | `CLAUDE_OPUS_4_5` | `claude-opus-4-5-20251101` | Opus | 200K | 64,000 | Yes | Yes | No | | `CLAUDE_SONNET_4_5` | `claude-sonnet-4-5-20250929` | Sonnet | 200K | 64,000 | Yes | Yes | No | | `CLAUDE_4_5_HAIKU` | `claude-haiku-4-5-20251001` | Haiku | 200K | 64,000 | Yes | Yes | No | | `CLAUDE_OPUS_4_1` | `claude-opus-4-1-20250805` | Opus | 200K | 32,000 | Yes | Yes | No | | `CLAUDE_OPUS_4_0` | `claude-opus-4-20250514` | Opus | 200K | 64,000 | Yes | Yes | No | | `CLAUDE_SONNET_4_0` | `claude-sonnet-4-20250514` | Sonnet | 200K | 64,000 | Yes | Yes | No | | `CLAUDE_SONNET_3_7` | `claude-3-7-sonnet-20250219` | Sonnet | 200K | 8,192 | Yes | Yes | **Yes** | | `CLAUDE_3_5_SONNET` | `claude-3-5-sonnet-20241022` | Sonnet | 200K | 8,192 | Yes | No | **Yes** | | `CLAUDE_3_5_HAIKU` | `claude-3-5-haiku-20241022` | Haiku | 200K | 8,192 | No | No | **Yes** | | `CLAUDE_3_SONNET` | `claude-3-sonnet-20240229` | Sonnet | 200K | 4,096 | Yes | No | **Yes** | | `CLAUDE_3_OPUS` | `claude-3-opus-20240229` | Opus | 200K | 4,096 | Yes | No | **Yes** | | `CLAUDE_3_HAIKU` | `claude-3-haiku-20240307` | Haiku | 200K | 4,096 | Yes | No | **Yes** | :::note[1M Context Window] Claude 4.6 models (`claude-opus-4-6` and `claude-sonnet-4-6`) support a 1,000,000-token context window at general availability — no beta header is required. ::: The detailed capabilities (context window, max output, vision, etc.) are defined in `MODEL_METADATA` within `src/lib/models/anthropicModels.ts`. ### Default Model The default model when no model is specified is `claude-sonnet-4-6` (set via `AnthropicModels.CLAUDE_SONNET_4_6`). This can be overridden with the `ANTHROPIC_MODEL` environment variable. ### Model Selection by Use Case ```typescript const ai = new NeuroLink(); // Fast, cost-effective responses const quickResult = await ai.generate({ input: { text: "Summarize this text..." }, provider: "anthropic", model: "claude-haiku-4-5-20251001", }); // Balanced performance (recommended default) const balancedResult = await ai.generate({ input: { text: "Analyze this code..." }, provider: "anthropic", model: "claude-sonnet-4-6", }); // Latest Sonnet with extended thinking const sonnet46Result = await ai.generate({ input: { text: "Design a distributed caching system" }, provider: "anthropic", model: "claude-sonnet-4-6", thinkingLevel: "high", }); // Latest flagship for advanced reasoning (1M context) const opusResult = await ai.generate({ input: { text: "Solve this complex problem..." }, provider: "anthropic", model: "claude-opus-4-6", }); ``` --- ## Claude Subscription Tiers Anthropic offers different access tiers, each with varying rate limits and model access: | Tier | Access Method | Models Available | Best For | | -------------------- | ----------------- | ------------------------------------- | ------------------------------- | | **Free** | claude.ai account | Haiku only (3 Haiku, 3.5 Haiku) | Exploration, personal use | | **Pro** ($20/month) | OAuth + claude.ai | Haiku + Sonnet (3.5 Sonnet, Sonnet 4) | Professional use, higher volume | | **Max** ($100/month) | OAuth + claude.ai | All models (including Opus) | Heavy use, all model access | | **Max 5x** | OAuth + claude.ai | All models | 5x usage multiplier | | **Max 20x** | OAuth + claude.ai | All models | 20x usage multiplier | | **API** | API Key | All models | Production, programmatic access | ### Model Access by Tier (`MODEL_TIER_ACCESS`) | Model | Free | Pro | Max / Max 5x / Max 20x | API | | ------------------------------- | ---- | --- | ---------------------- | --- | | `claude-3-haiku-20240307` | Yes | Yes | Yes | Yes | | `claude-3-5-haiku-20241022` | Yes | Yes | Yes | Yes | | `claude-3-5-sonnet-20241022` | No | Yes | Yes | Yes | | `claude-3-5-sonnet-v2-20241022` | No | Yes | Yes | Yes | | `claude-sonnet-4-20250514` | No | Yes | Yes | Yes | | `claude-sonnet-4-6` | No | Yes | Yes | Yes | | `claude-3-opus-20240229` | No | No | Yes | Yes | | `claude-opus-4-20250514` | No | No | Yes | Yes | | `claude-opus-4-6` | No | No | Yes | Yes | ### Default Models by Tier (`DEFAULT_MODELS_BY_TIER`) | Tier | Default Model | | ------- | --------------------------- | | Free | `claude-3-5-haiku-20241022` | | Pro | `claude-sonnet-4-20250514` | | Max | `claude-opus-4-20250514` | | Max 5x | `claude-opus-4-20250514` | | Max 20x | `claude-opus-4-20250514` | | API | `claude-sonnet-4-20250514` | **Note:** The global provider default (when no subscription tier is active) is `claude-sonnet-4-6`. The tier defaults above only apply when a subscription tier is configured. When a requested model is not available for the user's subscription tier, the provider automatically falls back to the recommended default model for that tier and logs a warning. --- ## Authentication Methods ### API Key Authentication (Recommended for Production) The standard method using Anthropic API keys. Best for: - Production deployments - Server-side applications - Predictable billing (pay-per-token) - Full API control #### Environment Variables ```bash # Required ANTHROPIC_API_KEY=sk-ant-api03-your-key-here # Optional: Override default model ANTHROPIC_MODEL=claude-sonnet-4-6 ``` The provider reads the API key via `ANTHROPIC_API_KEY`. The key format is validated against the pattern `sk-ant-*`. #### SDK Configuration ```typescript const ai = new NeuroLink(); const result = await ai.generate({ input: { text: "Analyze this code for bugs" }, provider: "anthropic", model: "claude-sonnet-4-6", temperature: 0.7, maxTokens: 2000, }); ``` #### Direct Provider Configuration The `AnthropicProvider` constructor accepts an optional `AnthropicProviderConfig`: ```typescript // Note: AnthropicProvider is not a top-level package export. // Use relative imports within the codebase or access via the NeuroLink SDK. const provider = new AnthropicProvider( "claude-sonnet-4-6", // modelName undefined, // sdk instance { authMethod: "api_key", apiKey: process.env.ANTHROPIC_API_KEY, enableBetaFeatures: true, }, ); ``` ### OAuth Setup (Claude Pro/Max) OAuth authentication allows you to use your Claude Pro or Max subscription through NeuroLink, leveraging your subscription quota instead of API billing. :::warning[OAuth Limitations] OAuth authentication is designed for personal/development use. For production deployments, use API key authentication for better reliability and SLA guarantees. ::: #### CLI Authentication The `auth` command uses subcommands with the provider as a positional argument: ```bash # Start interactive OAuth authentication (choose method) pnpm run cli -- auth login anthropic # Specify method directly pnpm run cli -- auth login anthropic --method oauth # Create API key via OAuth (recommended for Claude Pro/Max users) pnpm run cli -- auth login anthropic --method create-api-key # Traditional API key authentication pnpm run cli -- auth login anthropic --method api-key ``` The login flow will: 1. Open your default browser to `https://claude.ai/oauth/authorize` 2. Prompt you to sign in to your Claude account 3. Request authorization with scopes: `user:profile`, `user:inference` 4. Exchange the authorization code for tokens using PKCE 5. Store tokens securely in `~/.neurolink/anthropic-credentials.json` #### Token Management ```bash # Check authentication status pnpm run cli -- auth status # Check status for a specific provider pnpm run cli -- auth status anthropic # Refresh tokens manually pnpm run cli -- auth refresh anthropic # Clear credentials (logout) pnpm run cli -- auth logout anthropic ``` #### Token Storage Tokens are stored at `~/.neurolink/anthropic-credentials.json` with `0o600` file permissions (owner read/write only). The file format is: ```json { "type": "oauth", "oauth": { "accessToken": "...", "refreshToken": "...", "expiresAt": 1740000000000, "tokenType": "Bearer" }, "provider": "anthropic", "updatedAt": 1739900000000 } ``` The `expiresAt` field is stored as **Unix milliseconds** (i.e., `Date.now()` scale). The `TokenStore` class (used for multi-provider token storage) stores tokens at `~/.neurolink/tokens.json` with XOR-based obfuscation. #### Token Resolution Priority When the `AnthropicProvider` is initialized, it resolves OAuth tokens in this order: 1. `config.oauthToken` (passed directly to the constructor) 2. Stored credentials file at `~/.neurolink/anthropic-credentials.json` 3. Environment variables: `ANTHROPIC_OAUTH_TOKEN` or `CLAUDE_OAUTH_TOKEN` Environment variable tokens can be either: - A plain access token string - A JSON object with `accessToken`, `refreshToken`, and `expiresAt` fields #### Auto-Refresh Behavior Token refresh happens **automatically on every `generate()` and `stream()` call**. Before each API request, `refreshAuthIfNeeded()` is called, which: 1. Checks if the token has expiry information 2. If the token is expired or will expire within 5 minutes, attempts refresh 3. Sends a refresh request to `https://console.anthropic.com/v1/oauth/token` using the Claude Code client ID 4. Mutates the token object in-place so the fetch wrapper picks up the new access token automatically 5. Persists the refreshed token to `~/.neurolink/anthropic-credentials.json` on disk If the token is expired and no refresh token is available, an `AuthenticationError` is thrown. #### OAuth Environment Variables ```bash # Set an OAuth token directly (plain string or JSON) ANTHROPIC_OAUTH_TOKEN=your-access-token-here # Or use CLAUDE_OAUTH_TOKEN as an alternative CLAUDE_OAUTH_TOKEN=your-access-token-here # Set subscription tier explicitly (auto-detected if not set) ANTHROPIC_SUBSCRIPTION_TIER=pro ``` #### OAuth SDK Configuration ```typescript // Note: AnthropicProvider is not a top-level package export. // Use relative imports within the codebase or access via the NeuroLink SDK. const provider = new AnthropicProvider("claude-sonnet-4-6", undefined, { authMethod: "oauth", oauthToken: { accessToken: "your-access-token", refreshToken: "your-refresh-token", expiresAt: Date.now() + 3600 * 1000, // Unix milliseconds tokenType: "Bearer", }, subscriptionTier: "pro", enableBetaFeatures: true, }); ``` --- ## Extended Thinking All active Claude models (4.0 and above) support extended thinking, allowing the model to reason more deeply before responding. This includes Claude 4.6, 4.5, 4.1, and 4.0 variants. ### Thinking Levels | Level | Description | Use Case | | ----------- | ----------------- | ----------------------------------- | | **minimal** | Basic reasoning | Quick decisions | | **low** | Quick reasoning | Simple analysis | | **medium** | Balanced thinking | Code review, moderate complexity | | **high** | Deep reasoning | Complex proofs, architecture design | ### Configuration ```typescript // Enable extended thinking const result = await ai.generate({ input: { text: "Design a distributed caching system" }, provider: "anthropic", model: "claude-sonnet-4-6", thinkingLevel: "high", }); ``` ### CLI Usage ```bash pnpm run cli -- generate "Solve this logic puzzle..." \ --provider anthropic \ --model "claude-sonnet-4-6" \ --thinking-level high ``` --- ## Beta Features The Anthropic provider supports beta features via the `anthropic-beta` header. The following beta headers are included by default when `enableBetaFeatures` is `true`: - `claude-code-20250219` -- Claude Code specific features - `interleaved-thinking-2025-05-14` -- Interleaved thinking mode - `fine-grained-tool-streaming-2025-05-14` -- Fine-grained tool streaming These correspond to the `AnthropicBetaFeature` enum values in `src/lib/constants/enums.ts`: ```typescript enum AnthropicBetaFeature { CLAUDE_CODE = "claude-code-20250219", INTERLEAVED_THINKING = "interleaved-thinking-2025-05-14", FINE_GRAINED_STREAMING = "fine-grained-tool-streaming-2025-05-14", } ``` For OAuth mode, the beta headers are different: `oauth-2025-04-20` and `interleaved-thinking-2025-05-14` are sent (the `claude-code-20250219` header is only included if it was present in the original request headers, as it can trigger authorization errors with OAuth tokens). --- ## Multimodal Capabilities Claude models with vision support can analyze images. ### Image Analysis ```typescript const result = await ai.generate({ input: { text: "Describe what you see in this image", images: ["data:image/jpeg;base64,..."], }, provider: "anthropic", model: "claude-sonnet-4-6", }); ``` ```bash # From file path (CLI) pnpm run cli -- generate "Describe this image" \ --provider anthropic \ --image ./photo.jpg ``` ### PDF Processing ```typescript const result = await ai.generate({ input: { text: "Summarize the key points in this document", pdfs: ["./document.pdf"], }, provider: "anthropic", model: "claude-sonnet-4-6", }); ``` --- ## Tool Use / Function Calling Claude supports tool use for building agent workflows. All models with `supportsToolUse: true` in `MODEL_METADATA` support this feature. ```typescript const tools = [ { name: "get_weather", description: "Get current weather for a location", parameters: { type: "object", properties: { location: { type: "string", description: "City name" }, }, required: ["location"], }, }, ]; const result = await ai.generate({ input: { text: "What's the weather in Tokyo?" }, provider: "anthropic", model: "claude-sonnet-4-6", tools, }); console.log(result.toolCalls); ``` :::note[OAuth Tool Name Prefixing] When using OAuth authentication, tool names are automatically prefixed with `mcp_` in API requests and the prefix is stripped from responses. This is handled transparently by the OAuth fetch wrapper. ::: --- ## Streaming Responses ```typescript const stream = await ai.stream({ input: { text: "Write a detailed article about AI" }, provider: "anthropic", model: "claude-sonnet-4-6", }); ``` OAuth token refresh also happens automatically before `stream()` calls. --- ## Rate Limit Handling The Anthropic provider tracks rate limit information from API response headers. The following headers are parsed after each request: - `anthropic-ratelimit-requests-limit` / `anthropic-ratelimit-requests-remaining` - `anthropic-ratelimit-tokens-limit` / `anthropic-ratelimit-tokens-remaining` - `anthropic-ratelimit-requests-reset` / `anthropic-ratelimit-tokens-reset` - `retry-after` (on 429 responses) You can access this information programmatically: ```typescript const provider = new AnthropicProvider(); // After making a request... const metadata = provider.getLastResponseMetadata(); console.log(metadata?.rateLimit?.requestsRemaining); console.log(metadata?.rateLimit?.tokensRemaining); // Usage tracking const usage = provider.getUsageInfo(); if (usage) { console.log("Requests made:", usage.requestCount); console.log("Message quota used:", usage.messageQuotaPercent + "%"); console.log("Token quota used:", usage.tokenQuotaPercent + "%"); console.log("Rate limited:", usage.isRateLimited); } ``` Warnings are logged automatically when: - Remaining requests drops to 5 or fewer - Remaining tokens drops below 10% of the limit --- ## Configuration Reference ### Environment Variables | Variable | Description | Default | Required | | ----------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------- | -------- | | `ANTHROPIC_API_KEY` | API key for authentication | - | Yes\* | | `ANTHROPIC_MODEL` | Default model to use | `claude-sonnet-4-6` | No | | `ANTHROPIC_SUBSCRIPTION_TIER` | Subscription tier: `free`, `pro`, `max`, `max_5`, `max_20`, `api` | Auto-detected | No | | `ANTHROPIC_OAUTH_TOKEN` | OAuth token (plain access token string, or JSON `{"accessToken":"...","refreshToken":"...","expiresAt":...}`) | - | No\*\* | | `CLAUDE_OAUTH_TOKEN` | Alternative OAuth token env var (same format as above) | - | No\*\* | \*Required for API key authentication. Not required when using OAuth. \*\*Used when `authMethod` is `oauth` and no stored credentials file exists. The `expiresAt` field uses Unix milliseconds (`Date.now()` scale). ### `AnthropicProviderConfig` Interface ```typescript interface AnthropicProviderConfig { /** Auth method: "api_key" or "oauth". Auto-detected if not set. */ authMethod?: AnthropicAuthMethod; /** Subscription tier. Auto-detected from environment or "api" for API key auth. */ subscriptionTier?: ClaudeSubscriptionTier; /** Whether to enable beta features. Defaults to true. */ enableBetaFeatures?: boolean; /** OAuth token for OAuth authentication. */ oauthToken?: OAuthToken; /** API key for API key authentication. Read from env if not provided. */ apiKey?: string; } ``` ### CLI Provider Options The `--provider` flag accepts `anthropic` (or `anthropic-subscription`, which is automatically mapped to `anthropic` with subscription mode enabled). Additional flags for subscription features: | Flag | Values | Description | | --------------------- | ---------------------------------------------- | ---------------------- | | `--provider` / `-p` | `anthropic` | Use Anthropic provider | | `--auth-method` | `api-key`, `oauth` | Authentication method | | `--subscription-tier` | `free`, `pro`, `max`, `max_5`, `max_20`, `api` | Subscription tier | | `--enable-beta` | (boolean) | Enable beta features | | `--model` / `-m` | model ID string | Specific model to use | Example: ```bash pnpm run cli -- generate "Hello" \ --provider anthropic \ --auth-method oauth \ --subscription-tier pro ``` --- ## Error Handling The Anthropic provider maps errors to specific error types: | Error Type | Condition | | --------------------- | ---------------------------------------------------------- | | `AuthenticationError` | Invalid API key, expired OAuth token, failed token refresh | | `RateLimitError` | Rate limit exceeded (429 responses) | | `NetworkError` | Connection failures, timeouts | | `ProviderError` | Server errors (5xx), other provider-side failures | ### Common Issues #### "Invalid API key" ```bash # Verify key format (should start with sk-ant-) echo $ANTHROPIC_API_KEY | head -c 20 # Expected: sk-ant-api03-xxxx... # Get new key at https://console.anthropic.com ``` #### "OAuth token expired" OAuth tokens are auto-refreshed before each request. If refresh fails: ```bash # Refresh manually pnpm run cli -- auth refresh anthropic # Or re-authenticate pnpm run cli -- auth login anthropic ``` #### "Model access denied" / Model unavailable for tier When a model is not available for your subscription tier, the provider automatically falls back to the recommended model for your tier. To use a specific model, ensure your tier supports it (see [Model Access by Tier](#model-access-by-tier-model_tier_access)). ```typescript // Check model access programmatically const provider = new AnthropicProvider(); if (provider.validateModelAccess("claude-opus-4-20250514")) { // Model is accessible } else { // Falls back to tier default } ``` #### "Rate limit exceeded" (429) 1. For Free tier: Upgrade to Pro or Max 2. For API: Request a rate limit increase 3. Check `provider.getUsageInfo()` for current quota usage --- ## Helper Functions The `src/lib/models/anthropicModels.ts` module exports utility functions for working with models and tiers: ```typescript isModelAvailableForTier, getRecommendedModelForTier, // alias for getDefaultModelForTier getModelCapabilities, // alias for getModelMetadata getAvailableModelsForTier, getMinimumTierForModel, getModelsWithCapability, getModelsByFamily, getLatestModelsByFamily, validateModelAccess, compareTiers, ModelAccessError, } from "@juspay/neurolink"; // Check if a model is available for a tier isModelAvailableForTier("claude-opus-4-20250514", "pro"); // false isModelAvailableForTier("claude-opus-4-20250514", "max"); // true // Get the minimum tier required getMinimumTierForModel("claude-opus-4-20250514"); // "max" // Get all models with extended thinking getModelsWithCapability("supportsExtendedThinking"); // ["claude-sonnet-4-20250514", "claude-opus-4-20250514"] // Get latest non-deprecated model per family getLatestModelsByFamily(); // { haiku: "claude-3-5-haiku-20241022", sonnet: "claude-sonnet-4-20250514", opus: "claude-opus-4-20250514" } ``` --- ## Best Practices ### Security - **Never commit API keys** to version control - Use environment variables or secrets management - Rotate API keys periodically - OAuth tokens are stored with `0o600` permissions (owner read/write only) ```bash # Use .env file (not committed to git) echo "ANTHROPIC_API_KEY=sk-ant-..." >> .env # Add to .gitignore echo ".env" >> .gitignore ``` ### Rate Limiting The provider tracks rate limits automatically and logs warnings when approaching limits. Monitor usage via `getUsageInfo()` and `getLastResponseMetadata()`. --- ## Related Documentation - **[Provider Setup Guide](/docs/getting-started/provider-setup)** - General provider configuration - **[Extended Thinking Configuration](/docs/features/thinking-configuration)** - Thinking modes --- ## Additional Resources - **[Anthropic Console](https://console.anthropic.com)** - Manage API keys - **[Anthropic Documentation](https://docs.anthropic.com)** - Official API docs - **[Claude.ai](https://claude.ai)** - Claude web interface - **[Anthropic Pricing](https://anthropic.com/pricing)** - Pricing details --- ## Redis Quick Start (5 Minutes) # Redis Quick Start (5 Minutes) Get Redis storage up and running with NeuroLink in under 5 minutes. ## Prerequisites - Docker installed **OR** Redis installed locally - NeuroLink SDK installed (`pnpm add @juspay/neurolink`) ## Option 1: Docker (Recommended) The fastest way to get Redis running for development and testing. ### Start Redis Container ```bash # Start Redis with persistence docker run -d \ --name neurolink-redis \ -p 6379:6379 \ -v redis-data:/data \ redis:7-alpine # Verify Redis is running docker ps | grep neurolink-redis ``` ### Test Connection ```bash # Test Redis connectivity docker exec -it neurolink-redis redis-cli ping # Expected output: PONG ``` ## Option 2: Local Install ### macOS ```bash # Install Redis with Homebrew brew install redis # Start Redis service brew services start redis # Verify installation redis-cli ping # Expected output: PONG ``` ### Ubuntu/Debian ```bash # Install Redis sudo apt update sudo apt install redis-server -y # Start Redis service sudo systemctl start redis-server sudo systemctl enable redis-server # Verify installation redis-cli ping # Expected output: PONG ``` ### Windows (WSL2) ```bash # Update packages sudo apt update # Install Redis sudo apt install redis-server -y # Start Redis sudo service redis-server start # Test connection redis-cli ping # Expected output: PONG ``` ## Configure NeuroLink ### 1. Set Environment Variables ```bash # Add to your .env file REDIS_HOST=localhost REDIS_PORT=6379 REDIS_PASSWORD= # Leave empty for local dev REDIS_DB=0 ``` ### 2. Initialize NeuroLink with Redis ```typescript const neurolink = new NeuroLink({ conversationMemory: { enabled: true, store: "redis", redisConfig: { host: "localhost", port: 6379, db: 0, }, }, }); // Use neurolink as normal const result = await neurolink.generate({ input: { text: "Hello! How are you?" }, provider: "openai", }); console.log(result.content); ``` ### 3. Verify Storage ```typescript // Check conversation persistence const stats = await neurolink.conversationMemory?.getStats(); console.log(stats); // { totalSessions: 1, totalTurns: 1 } ``` ## Quick Verification ### Test Data Persistence ```bash # In your Node.js console const neurolink = new NeuroLink({ conversationMemory: { enabled: true, store: "redis", redisConfig: { host: "localhost", port: 6379 } } }); // Generate a conversation await neurolink.generate({ input: { text: "Remember this: my favorite color is blue" }, sessionId: "test-session", userId: "test-user", }); // Stop your app, restart, and verify data persists const history = await neurolink.conversationMemory?.getUserSessionHistory( "test-user", "test-session" ); console.log(history); // Should show your conversation ``` ### Check Redis Data ```bash # Connect to Redis CLI docker exec -it neurolink-redis redis-cli # OR (local install) redis-cli # List all keys 127.0.0.1:6379> KEYS * # Expected: Shows NeuroLink conversation keys # Check a specific session 127.0.0.1:6379> GET neurolink:conversation:test-user:test-session # Shows conversation data in JSON format ``` ## Common Issues ### Connection Refused **Problem:** Cannot connect to Redis ```bash # Check if Redis is running docker ps | grep neurolink-redis # OR sudo systemctl status redis-server # Restart if needed docker restart neurolink-redis # OR sudo systemctl restart redis-server ``` ### Port Already in Use **Problem:** Port 6379 is already taken ```bash # Use a different port for Redis docker run -d --name neurolink-redis -p 6380:6379 redis:7-alpine # Update NeuroLink config redisConfig: { host: "localhost", port: 6380 } ``` ### Permission Denied **Problem:** Cannot access Redis socket (Linux) ```bash # Add your user to the redis group sudo usermod -a -G redis $USER # Restart Redis sudo systemctl restart redis-server ``` ## Next Steps - **[Complete Redis Configuration Guide](/docs/guides/redis-configuration)** - Production setup, clustering, security - **[Redis Migration Patterns](/docs/guides/redis-migration)** - Migrate from in-memory to Redis - **[Conversation Memory Guide](/docs/features/conversation-history)** - Advanced conversation management ## Production Checklist Before going to production, review: - [ ] **Security**: Set `requirepass` in Redis configuration - [ ] **Persistence**: Enable AOF (Append-Only File) for data durability - [ ] **Monitoring**: Set up health checks and alerts - [ ] **Backup**: Configure automated backup schedule - [ ] **Performance**: Tune `maxmemory` and eviction policies See the [Complete Redis Configuration Guide](/docs/guides/redis-configuration) for production best practices. --- **Need Help?** Check our [Troubleshooting Guide](/docs/reference/troubleshooting) or open an issue on [GitHub](https://github.com/juspay/neurolink). --- ## API Route Provider Guide # API Route Provider Guide API Route is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/api-route.json`) rather than hand-written code. That file is the source of truth for everything on this page. ## Quick Start ### 1. Get an API key 1. Visit: https://api-route.com and create an account 2. Generate an API key in your console / dashboard 3. Set `API_ROUTE_API_KEY` in your .env file ### 2. Configure ```bash export API_ROUTE_API_KEY=your-api-key export API_ROUTE_MODEL=claude-sonnet-4-6 # optional — overrides the default model export API_ROUTE_BASE_URL=https://global.api-route.com/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "api-route", model: "claude-sonnet-4-6", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider api-route ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "api-route", credentials: { apiRoute: { apiKey: process.env.API_ROUTE_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ---------------------- | ------- | ------ | ------------ | ------------------------------------------------------------------------------------------ | | `claude-sonnet-4-6` ⭐ | 1M | yes | — | Claude Sonnet 4.6 — flagship model with 1M context, tool calling, and multimodal vision | | `claude-haiku-4-5` | 195K | yes | — | Claude Haiku 4.5 — fast, high-efficiency model with 200K context, tool calling, and vision | | `deepseek-v4-flash` | 1M | no | — | DeepSeek V4 Flash — fast, cost-effective reasoning model with 1M context | | `deepseek-v4-pro` | 1M | no | — | DeepSeek V4 Pro — powerful reasoning model with 1M context | | `gemini-3.8-flash` | 1M | yes | — | Gemini 3.8 Flash — high-speed multimodal model supporting image input and streaming | | `qwen3.8-flash` | 125K | no | — | Qwen 3.8 Flash — versatile, fast model for general instruction and coding tasks | | `kimi-k2.7-code` | 250K | no | — | Kimi K2.7 Code — specialized for coding and multi-step reasoning | | `glm-5.3-flash` | 125K | no | — | GLM 5.3 Flash — lightweight, fast conversational and instruction-following model | **Fallback order** when the default is unavailable: `claude-haiku-4-5` → `deepseek-v4-flash` → `gemini-3.8-flash`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for API Route: | Probe | Result | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | authenticated GET /v1/models, HTTP 200, 2026-09-17 | | Auth rejection | HTTP 401, 2026-09-17 | | Live capability sweep | 2026-09-17 — Verified live against https://global.api-route.com/v1: GET /v1/models returned 70 models. Chat completions, streaming, function calling, streamed function calling, and structured JSON output (json_object and json_schema) | --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------- | ----------------------------------- | ----------------------------------------------------------------- | | `Invalid API Route API key` | `API_ROUTE_API_KEY` unset or wrong | Check the key at https://api-route.com | | Model not found | The roster changed since 2026-09-17 | Pick a current id; catalog providers retire models without notice | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Arcee Provider Guide # Arcee Provider Guide Arcee is a **Tier-2 catalog provider**: OpenAI-wire-compatible, so its entire integration is one JSON file (`src/lib/providers/catalog/arcee.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** The vendor's `GET https://api.arcee.ai/api/v1/models` needs a > key (it answers HTTP 401 without one), so the model ids come from Arcee's > public docs and the roster has not been checked. No account was created and no > API key was used to build this entry. `evidence.liveMatrix` is `null` until > someone runs the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://platform.arcee.ai/api/api-keys — the [Quick Start](https://docs.arcee.ai/get-started/quick-start.md) says to access the Arcee Platform (https://platform.arcee.ai/), "Register or Login.", then to "Create an API Key in the API Keys management page." and "Copy your API Key for use and store in a secure location." 2. Authentication is HTTP Bearer: the Quick Start's curl example sends the header Authorization: Bearer YOUR_API_KEY, and the Chat Completion reference (https://docs.arcee.ai/api-reference/chat-completion.md) gives the key format as "Arcee API key (prefixed with `rcai-`)" 3. Billing as the vendor states it: the Quick Start says to open the Wallet (https://platform.arcee.ai/api/wallet) "to top up if needed"; the Chat Completion reference lists HTTP 402 as "Insufficient Balance" 4. Set `ARCEE_API_KEY` in your .env file ### 2. Configure ```bash export ARCEE_API_KEY=your-api-key export ARCEE_MODEL=trinity-large-thinking # optional — overrides the default model export ARCEE_BASE_URL=https://api.arcee.ai/api/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "arcee", model: "trinity-large-thinking", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider arcee ``` Per-request credentials use the same shape as the other catalog providers: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "arcee", credentials: { arcee: { apiKey: process.env.ARCEE_API_KEY } }, }); ``` --- ## Billing The [Quick Start](https://docs.arcee.ai/get-started/quick-start.md) says to open the Wallet (https://platform.arcee.ai/api/wallet) "to top up if needed". The [Chat Completion reference](https://docs.arcee.ai/api-reference/chat-completion.md) lists HTTP 402 as "Insufficient Balance". The [pricing page](https://docs.arcee.ai/get-started/pricing.md) says "All prices are in USD." and lists prices per 1M tokens. The catalog schema has no unknown billing value, so `billingPolicy` holds `no-free-tier`. It is a schema value, not a vendor statement of signup terms. --- ## Models | Model | Context | Vision | $/M in · out (cached) | Notes | | ----------------------------------- | ------- | ------ | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `trinity-large-thinking` ⭐ | 128,000 | no | $0.25 / $0.80 ($0.06) | NeuroLink default. Strength "Robust generalist model with strong performance across reasoning, coding, math, and complex task decomposition." Context Window "512k tokens (hosted at 128k)". | | `deepseek/deepseek-v4-flash-latest` | — | no | $0.14 / $0.28 ($0.028) | NeuroLink fallback; listed under "Text Models". | | `zai-org/glm-5.3-flash` | — | no | $0.15 / $0.50 ($0.03) | NeuroLink fallback; listed under "Text Models". | | `thinkingmachines/inkling-small` | — | no | $0.50 / $1.20 ($0.10) | NeuroLink fallback; listed under "Text Models". | | `deepseek/deepseek-v4-pro-0813` | — | no | $1.32 / $3.96 ($0.044) | NeuroLink fallback; listed under "Text Models". | | `deepseek/deepseek-v4-pro` | — | no | $1.74 / $3.48 ($0.20) | NeuroLink fallback; listed under "Text Models". | | `zai-org/glm-5.2` | — | no | $1.40 / $4.40 ($0.26) | NeuroLink fallback; listed under "Text Models". | | `zai-org/glm-5.3` | — | no | $1.40 / $4.40 ($0.26) | NeuroLink fallback; listed under "Text Models". | | `moonshotai/kimi-k3` | — | no | $3.00 / $15.00 ($0.30) | NeuroLink fallback; listed under "Text Models". | | `deepseek/deepseek-v4.1-flash` | — | no | $0.22 / $0.66 ($0.007) | NeuroLink fallback; listed under "Text Models". | Model ids and prices are copied from the [pricing page](https://docs.arcee.ai/get-started/pricing.md), retrieved 2026-09-29; the page says "This page provides pricing information for all models on Arcee Platform." and "Prices per 1M Tokens." The default's id, Context Window and Strength come from the [Arcee Model Overview](https://docs.arcee.ai/arcee-language-models/arcee-model-overview.md), retrieved 2026-09-29. A `—` in the Context column means the catalog carries no `contextWindow` for that model, so it uses `models.defaultContextWindow`. On [www.arcee.ai/trinity](https://www.arcee.ai/trinity) the card titled "Trinity Large Thinking (400B, 13B active)" gives "Arcee API — served at 256K context at BF16" after its "Deploy on:" label. The Arcee Model Overview gives "512k tokens (hosted at 128k)" for the same model. The two vendor pages give different hosted context figures; the catalog's `contextWindow` for `trinity-large-thinking` is 128000, the Model Overview figure, the page that lists the API Model Name. The Vision column shows the `vision` value in the JSON, `false` on the ten rows. It is a placeholder for a boolean the catalog schema requires; it is not a vendor statement. Each model's `status` in the JSON is `production`, a placeholder for a value the catalog schema requires; it is not a vendor statement. `models.defaultContextWindow` (128000) and `models.defaultMaxOutputTokens` (8192) apply to model ids outside the catalog and to catalog rows without their own `contextWindow` or `maxOutputTokens` (nine rows have no `contextWindow`; ten rows have no `maxOutputTokens`). They are placeholders the vendor does not publish for those model ids; 128000 is the same number as the "hosted at 128k" figure the Arcee Model Overview gives for `trinity-large-thinking`. **Fallback order** when the default is unavailable follows the row order of the pricing page: `deepseek/deepseek-v4-flash-latest` → `zai-org/glm-5.3-flash` → `thinkingmachines/inkling-small` → `deepseek/deepseek-v4-pro-0813` → `deepseek/deepseek-v4-pro` → `zai-org/glm-5.2` → `zai-org/glm-5.3` → `moonshotai/kimi-k3` → `deepseek/deepseek-v4.1-flash`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `zai-org/glm-5.3-flash`. **Model changes.** The [Deprecation Policy](https://docs.arcee.ai/policies/deprecation-policy.md) says "Cloud models are versioned and may be replaced quickly when new improvements are available." and "Typical notice for standard cloud models: up to 5 business days". --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Arcee — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /api/v1/models` answers HTTP 401 without a key (2026-09-29), so model ids are taken from the pricing page; roster not verified. The [Models reference](https://docs.arcee.ai/api-reference/models.md) documents this endpoint with a 401 response described as "Authentication Fails" | | Auth-failure shape | unauthenticated `GET /models` answered HTTP 401 with header `www-authenticate: Bearer` and body `{"detail":"Missing or invalid Authorization header. Expected: Bearer "}` (2026-09-29); the [Chat Completion reference](https://docs.arcee.ai/api-reference/chat-completion.md) Error schema has one property, `detail`. `errorRules` carry the 401, 402, 403, 429 and 503 rows | | `/chat/completions` GET | unauthenticated `GET /chat/completions` answered HTTP 405 with header `allow: POST` and body `{"error":{"message":"Method Not Allowed","type":"invalid_request_error","param":null,"code":"request.rejected"}}` (2026-09-29). No POST request was sent | | Billing | public pages quoted under [Billing](#billing); no signup performed | | Tools / structured output | documented on the Function Calling and Structured Outputs pages; neither was exercised live, no POST request was sent, and no combined tools+schema request was sent, so `structuredOutputWithTools` stays `false`. The request fields NeuroLink's chat-completions client can add have not been exercised against Arcee | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=arcee` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting The rows below are the statuses the vendor's [Chat Completion reference](https://docs.arcee.ai/api-reference/chat-completion.md) lists; NeuroLink's `errorRules` map 401, 402, 403, 429 and 503 to error classes. | Symptom | What the Chat Completion reference says | | -------- | --------------------------------------- | | HTTP 400 | "Invalid Format" | | HTTP 401 | "Authentication Fails" | | HTTP 402 | "Insufficient Balance" | | HTTP 403 | "Permission Denied" | | HTTP 404 | "Not Found" | | HTTP 422 | "Invalid Parameters" | | HTTP 429 | "Rate Limit Reached" | | HTTP 500 | "Server Error" | | HTTP 503 | "Server Overloaded" | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [Providers index](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Atlas Cloud Provider Guide # Atlas Cloud Provider Guide Atlas Cloud is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/atlas-cloud.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** Every field below comes from Atlas Cloud's own public > documentation and an unauthenticated `GET /v1/models` call — no account was > created and no API key was used to build it. `evidence.liveMatrix` is `null` > until someone runs the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://www.atlascloud.ai/login and sign up or sign in (Google, GitHub, or email and password — one page handles both, see https://www.atlascloud.ai/docs/account/sign-in) 2. Open https://www.atlascloud.ai/console/api-keys, choose Create API Key and copy it immediately — it is shown only once (https://www.atlascloud.ai/docs/api-keys), and Atlas Cloud API keys begin with apikey- (https://www.atlascloud.ai/docs/llm-protocols) 3. Billing is pay-as-you-go from a prepaid balance: the quick start's Step 3 is Add Funds with a $25 minimum top-up (https://www.atlascloud.ai/docs/get-started), and requests are rejected with 402 while the balance is insufficient (https://www.atlascloud.ai/docs/errors). The homepage FAQ also says 'No credit card required to start', but no free-tier terms are documented, so check your balance at https://www.atlascloud.ai/console/billing before relying on it 4. Set `ATLAS_CLOUD_API_KEY` in your .env file (`ATLASCLOUD_API_KEY`, the name used in Atlas Cloud's own docs, is also read) ### 2. Configure ```bash export ATLAS_CLOUD_API_KEY=apikey-your-key export ATLAS_CLOUD_MODEL=deepseek-ai/deepseek-v3.2 # optional — overrides the default model export ATLAS_CLOUD_BASE_URL=https://api.atlascloud.ai/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "atlas-cloud", model: "deepseek-ai/deepseek-v3.2", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider atlas-cloud ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "atlas-cloud", credentials: { atlasCloud: { apiKey: process.env.ATLAS_CLOUD_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ------------------------------------ | ------- | ------ | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `deepseek-ai/deepseek-v3.2` ⭐ | 164K | no | $0.26 / $0.38 (cached $0.13) | Default here because the chat-completions, Anthropic Messages and Responses examples on the LLM API Protocols page use it (the vendor does not recommend it); roster tags `tools`, `structured_outputs`, `reasoning`; model page says 128K context, see below. | | `deepseek-ai/deepseek-v4-flash` | 1M | no | $0.14 / $0.28 (cached $0.028) | First fallback; 393K output ceiling on the roster. | | `zai-org/glm-5.3` | 1M | no | $1.40 / $4.40 (cached $0.26) | Fallback from a second family (GLM is a featured family on the LLM / Chat page); 131K output ceiling. | | `Qwen/Qwen3-235B-A22B-Instruct-2507` | 131K | no | $0.20 / $0.88 (cached $0.20) | Fallback from a third family (Qwen is featured on the LLM / Chat page). | | `deepseek-ai/deepseek-v4-pro` | 1M | no | $1.68 / $3.38 (cached $0.13) | Roster output ceiling 393K. | | `zai-org/glm-5.1` | 203K | no | $1.26 / $3.96 (cached $0.234) | Roster output ceiling equals context (203K), so none recorded separately. | | `minimaxai/minimax-m2.7` | 197K | no | $0.30 / $1.20 (cached $0.06) | MiniMax is a featured family on the LLM / Chat page. | | `moonshotai/kimi-k2.6` | 262K | yes | $0.95 / $4.00 (cached $0.16) | Roster input modalities text, image, video; `models.visionModel`. | | `qwen/qwen3.5-397b-a17b` | 262K | yes | $0.55 / $3.50 (cached $0.55) | Roster input modalities text, image, video; 65K output ceiling. | | `qwen/qwen3.5-27b` | 262K | yes | $0.27 / $2.16 (cached $0.27) | Roster input modalities text, image, video; 65K output ceiling. | Context, pricing, output ceilings and modalities are taken from an unauthenticated `GET https://api.atlascloud.ai/v1/models` call made 2026-09-29 (120 models total; 10 curated into this catalog, all of them text-output models whose roster entry advertises `tools` plus `json_mode` or `structured_outputs`). The roster reports prices per token; the table multiplies by one million. Where a model's `max_output_length` equals its context window, no separate output ceiling is recorded in the catalog. `models.defaultContextWindow` and `models.defaultMaxOutputTokens` (both 163,840) are the default model's own roster figures. **Default model's context window — the vendor's pages disagree.** The model page for `deepseek-ai/deepseek-v3.2` ([models/deepseek-ai/deepseek-v3.2](https://www.atlascloud.ai/models/deepseek-ai/deepseek-v3.2)) says "128K token context length support" and lists "Context Length: 128K tokens" in its spec table. The roster's `context_length` and the same page's machine-readable reference ([llms.txt](https://www.atlascloud.ai/models/deepseek-ai/deepseek-v3.2/llms.txt): "Context length: 163,840 tokens", "Max output tokens: 163,840") both say 163,840. The catalog records 163,840 because the two API-facing sources agree on it; the vendor does not say which figure governs. No request longer than 128K tokens was sent, so treat the range between 128K and 163,840 as vendor-declared and untested; if you need certainty, keep prompts under 128K tokens. **Fallback order** when the default is unavailable: `deepseek-ai/deepseek-v4-flash` → `zai-org/glm-5.3` → `Qwen/Qwen3-235B-A22B-Instruct-2507`. Vision tags (`vision: true`) come from the `image` entry in each model's roster `input_modalities`, not from an image-input probe — no key was used to send a real image request. Image parts use the OpenAI `image_url` content-part shape described on the protocols page. **About `is_ready`.** In the 2026-09-29 roster call the `is_ready` field was `false` on 73 of the 120 entries (by id prefix: `anthropic/` 29, `openai/` 18, `google/` 11, `qwen/` 8, `xai/` 4, `moonshotai/` 2, `zai-org/` 1) and absent on the other 47. The models in this catalog are entries where it is absent. The roster also comes back in a custom `{code, msg, data}` envelope rather than OpenAI's `{object: "list"}` wrapper, but `data` is still an array of `{id, ...}` entries. --- ## Billing The vendor's pages do not agree, and the catalog does not paper over that: - The billing docs ([docs/billing](https://www.atlascloud.ai/docs/billing), [top-up](https://www.atlascloud.ai/docs/billing/topup), [balance & credits](https://www.atlascloud.ai/docs/billing/credits)) and the [quick start](https://www.atlascloud.ai/docs/get-started) describe pay-as-you-go from a prepaid balance with a $25 minimum top-up; a request made with an insufficient balance is rejected with HTTP 402 ([docs/errors](https://www.atlascloud.ai/docs/errors)). Bonus credits exist (promotions, redeem codes, referrals) but are not described as a free tier. - The [homepage](https://www.atlascloud.ai) FAQ says "No credit card required to start" in its answer to "How do I get started"; the phrase "free credits" appears only in the homepage blurbs for the GPT Image 2 and Nano Banana 2 models, with no terms. The [pricing page](https://www.atlascloud.ai/pricing/models) is headed "Pay Per Use, No Subscriptions". No page states what a brand-new, unfunded account can actually call, so `billingPolicy` is set to `no-free-tier` because the schema has no "unknown" value and that is the conservative choice for a setup wizard — not because it was confirmed. Check the balance in the [console](https://www.atlascloud.ai/console/billing) before relying on it. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Atlas Cloud — **docs- and roster-verified, not live-verified**: | Probe | Result | | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /v1/models`, HTTP 200, 120 models, 2026-09-29 — no key used | | Billing | public docs, quick start and homepage read 2026-09-29; prepaid balance and 402 on insufficient balance are documented, the homepage FAQ's "No credit card required to start" is not reconciled with them — see [Billing](#billing) | | Auth-failure shape | documented on docs/errors (`{"code":401,"msg":"unauthorized","request_id":"…","data":null}`; a wrong path also returns 401; 402 is insufficient balance; 404 covers models not available to the account) and **not probed live** — `errorRules` is built from that page alone | | Tools / structured output | documented on docs/llm-protocols for models that advertise them (the page does not say what happens on other models); neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=atlas-cloud` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | HTTP 401 on every request | Key missing, unknown or expired — or a mistyped endpoint path (the gateway authenticates first) | Check `ATLAS_CLOUD_API_KEY`, and confirm the base URL ends in `/v1` | | HTTP 402 | Insufficient balance | Add funds in the [console](https://www.atlascloud.ai/console/billing); service resumes after top-up | | Model not found (404) | Resource not found — the docs say a 404 for a model also covers models that are not available to your account (docs/errors) | Check the model id against the catalog; the unauthenticated `GET https://api.atlascloud.ai/v1/models` roster lists ids | | HTTP 429 with no `Retry-After` | Per-account, per-model rate limit; LLM endpoints send no `X-RateLimit-*` or `Retry-After` headers | Back off client-side with jitter (docs/errors) | | 200 on a stream, but the reply is cut short | Errors after a stream opens arrive as events inside the stream | Handle mid-stream termination; ignore SSE comment lines starting with `:` (keep-alives) | | Tool calls or `response_format` misbehave | The docs cover them for models that advertise `tools` / `json_mode` / `structured_outputs`; behaviour on other models is undocumented | Use a model from the table above (all advertise `tools` and `json_mode` or `structured_outputs`) | | Structured output ignored with tools attached | `structuredOutputWithTools` is `false` on this entry — untested combination | NeuroLink omits `response_format` automatically whenever tools are present, before sending | | Reply contains a system prompt you never sent | The gateway inserts "You are a helpful assistant." when no system prompt is sent | Send your own system message | | Embeddings call fails | Atlas Cloud has no `/v1/embeddings` endpoint | Use a different provider for embeddings | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Avian Provider Guide # Avian Provider Guide Avian is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/avian-io.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** Every field below comes from Avian's own public pages and an > unauthenticated `GET /v1/models` call — no account was created and no API key > was used to build it. `evidence.liveMatrix` is `null` until someone runs the > live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://avian.io/accounts/signup/ and sign up with Google or a work email and password 2. Create an API key from your signed-in account — the public pages only say "Get your API key in under a minute" (https://avian.io/pricing/) and do not name the key page; the docs examples show keys that start with avian- 3. Prepaid credits only: add credits before calling the API (https://avian.io/pricing/ lists $50, $100, $150 and $250 packages); the sign-up buttons say "Get Started Free" but no free credits are stated anywhere, and the docs list HTTP 402 for an insufficient credit balance (https://avian.io/docs/) 4. Set `AVIAN_IO_API_KEY` in your .env file (the vendor's homepage example reads `AVIAN_API_KEY`, which NeuroLink does not) ### 2. Configure ```bash export AVIAN_IO_API_KEY=your-api-key export AVIAN_IO_MODEL=deepseek/deepseek-v4-pro-0813 # optional — overrides the default model export AVIAN_IO_BASE_URL=https://api.avian.io/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "avian-io", model: "deepseek/deepseek-v4-pro-0813", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider avian-io ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "avian-io", credentials: { avianIo: { apiKey: process.env.AVIAN_IO_API_KEY } }, }); ``` --- ## Billing Avian's pricing page (https://avian.io/pricing/) describes "per-token pricing with prepaid credits", "no subscriptions, no commitments", credits that "never expire", and credit packages of $50, $100, $150 and $250. Its docs list HTTP `402 Payment Required` as "Insufficient credit balance" (https://avian.io/docs/). No page states free credits or a free tier, so the entry records `no-free-tier`. The "Get Started Free" button on the public pages is the sign-up call to action; it is not a stated free allowance. --- ## Models | Model | Context | Max output | Vision | $/M in · out (cache read) | Notes | | ---------------------------------- | --------- | ---------- | ------ | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `deepseek/deepseek-v4-pro-0813` ⭐ | 1,000,000 | 393,216 | no | $0.594 / $1.782 ($0.0198) | Default — the model Avian promotes with a "now live" banner on its home, docs, models, pricing and About pages. Reasoning-flagged. | | `deepseek/deepseek-v4-flash` | 1,000,000 | 393,216 | no | $0.0805 / $0.161 ($0.0165) | Fallback; lowest input and output price on the roster. Reasoning-flagged. | | `deepseek/deepseek-v3.2` | 163,840 | 65,536 | no | $0.23 / $0.33 ($0.012) | Fallback; the model in every docs code example, labelled "(Legacy)" by the vendor. Reasoning-flagged. | | `z-ai/glm-5.2` | 1,048,576 | 131,072 | no | $0.495 / $1.733 ($0.124) | Fallback; highest-numbered GLM on the roster. | | `deepseek/deepseek-v4-pro` | 1,000,000 | 393,216 | no | $1.305 / $2.61 ($0.10875) | Undated V4 Pro build; roster-listed only. Reasoning-flagged. | | `minimax/minimax-m2.5` | 196,608 | 131,072 | no | $0.27 / $1.08 ($0.15) | Roster-listed only. | | `z-ai/glm-5` | 204,800 | 131,072 | no | $0.516 / $2.322 ($0.129) | Roster-listed only. | | `z-ai/glm-5.1` | 202,752 | 202,752 | no | $0.743 / $2.971 ($0.186) | Roster-listed only. | | `moonshotai/kimi-k2.5` | 262,144 | 262,144 | no | $0.45 / $2.2 ($0.225) | Roster-listed only. | | `moonshotai/kimi-k2.6` | 262,144 | 262,144 | no | $0.95 / $4 ($0.16) | Roster-listed only. | | `xiaomi/mimo-v2.6-flash` | 1,048,576 | 131,072 | no | $0.2 / $0.4 ($0.05) | Roster-listed only. Reasoning-flagged. | | `xiaomi/mimo-v2.6-pro` | 1,048,576 | 131,072 | no | $0.435 / $0.87 ($0.0036) | Roster-listed only. Reasoning-flagged. | Context, max output and prices come from an unauthenticated `GET https://api.avian.io/v1/models` call made 2026-09-29 (13 models, all chat models; 12 curated into this catalog). The same prices appear on [the docs page](https://avian.io/docs/), [the models page](https://avian.io/models/) and [the pricing page](https://avian.io/pricing/), which also state context and max output in rounded form (for example "1M" and "384K"). "Reasoning-flagged" means the roster's `reasoning` field is `true`; it is not a documented capability. `models.defaultContextWindow` (163,840) and `models.defaultMaxOutputTokens` (65,536) are the smallest context and max-output values on today's roster, so a model id that is not in the catalog gets a figure no roster model falls below. They are not a vendor-stated general cap. **Vision:** every model is `vision: false`. The homepage and About page list "vision analysis" among built-in capabilities "across all models", but no page says which models accept image input in a chat message, so none is declared. **Fallback order** when the default is unavailable: `deepseek/deepseek-v4-flash` → `deepseek/deepseek-v3.2` → `z-ai/glm-5.2`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `deepseek/deepseek-v3.2`, the one model the docs' function-calling and streaming examples use. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Avian — **docs- and roster-verified, not live-verified**: | Probe | Result | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Roster | unauthenticated `GET /v1/models`, HTTP 200, 13 models, 2026-09-29 — no key used | | Billing | public pricing page describes prepaid credits with no subscription and states no free tier or free credits, 2026-09-29 | | Auth-failure shape | the docs list HTTP 401 "Missing or invalid API key" and 402 "Insufficient credit balance" but describe the error body only as "a JSON body with a descriptive message"; the body was not probed, so `errorRules` match the status codes alone (`401`, `402`) | | Tools / structured output | function calling is documented at https://avian.io/docs/; `response_format` is not documented anywhere opened. Neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=avian-io` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------------------------- | -------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | HTTP 402 on every request | No prepaid credit balance — Avian has no free tier | Add credits at https://avian.io/pricing/ (the package amounts are listed there) | | HTTP 401 | Missing or invalid key, or the key was set under the wrong variable name | Set `AVIAN_IO_API_KEY`; the vendor's homepage example uses `AVIAN_API_KEY`, which NeuroLink does not read | | Model not found | The roster changed since 2026-09-29, or a display name was used instead of an id | Use an id exactly as listed by the unauthenticated `GET /v1/models`; the homepage snippet's `DeepSeek-V3.2` is not a roster id, the docs' `deepseek/deepseek-v3.2` is | | Structured output ignored with tools attached | `structuredOutputWithTools` is `false` on this entry — untested combination | NeuroLink omits `response_format` automatically whenever tools are present, before sending | | Tool calls not returned | Tool calling on Avian is `model-dependent` here — only `deepseek/deepseek-v3.2` has a documented example | Try `deepseek/deepseek-v3.2`, then report which models work so the entry can be tightened | | Unexpected HTTP 429 | The pages say "No Rate Limits", yet the docs list 429 "Rate limit exceeded. Retry after a brief delay" | Back off briefly and retry; the vendor's own docs describe 429 as retryable | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## AWS Bedrock Provider Guide # AWS Bedrock Provider Guide **Enterprise AI with Claude, Nova, Llama, Mistral, DeepSeek, Qwen, and 110+ foundation models on AWS infrastructure** ----------- | ------------------------------------------------------------------------ | ---------------------------------------- | | **Anthropic** | Claude 4.6 Opus/Sonnet, 4.5, 4.1, 4, 3.7, 3.5, 3 (12) | Complex reasoning, coding, 1M context | | **Amazon** | Nova Premier/Pro/Lite/Micro, Nova 2, Sonic, Canvas, Reel (11) | AWS-native, multimodal, media generation | | **Meta** | Llama 4 Scout/Maverick, 3.3, 3.2, 3.1, 3 (12) | Open source, long context (10M) | | **Mistral AI** | Large 3, Magistral, Ministral, Pixtral, Voxtral, Devstral (14) | European compliance, coding, multimodal | | **DeepSeek** | R1, V3 (2) | Deep reasoning, cost-effective | | **Qwen** | Qwen 3, Qwen 3 Coder, Qwen 3 VL, Qwen 3 Next (6) | Coding, vision, multilingual | | **Cohere** | Command R/R+, Embed v3/v4, Rerank v3.5 (6) | Enterprise search, RAG, reranking | | **AI21 Labs** | Jamba 1.5 Large/Mini (2) | Long context | | **Google** | Gemma 3 (27B, 12B, 4B) (3) | Lightweight open models | | **Other** | NVIDIA Nemotron, Writer Palmyra, MiniMax, Kimi, OpenAI gpt-oss, Z.AI GLM | Specialized workloads | --- ## Quick Start ### 1. Enable Model Access ```bash # Via AWS CLI aws bedrock list-foundation-models --region us-east-1 # Request model access (one-time) # Go to: https://console.aws.amazon.com/bedrock # → Model access → Manage model access # → Select models → Request access ``` Or via AWS Console: 1. Open [Bedrock Console](https://console.aws.amazon.com/bedrock) 2. Select region (us-east-1 recommended) 3. Click "Model access" 4. Enable desired models (instant for most, approval needed for some) ### 2. Setup IAM Permissions ```bash # Create IAM policy cat > bedrock-policy.json req.userRegion === "us", }, // EU West (GDPR) { name: "bedrock-eu", priority: 1, config: { region: "eu-west-1", credentials: { accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, }, }, condition: (req) => req.userRegion === "eu", }, // Asia Pacific { name: "bedrock-asia", priority: 1, config: { region: "ap-southeast-1", credentials: { accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, }, }, condition: (req) => req.userRegion === "asia", }, ], failoverConfig: { enabled: true }, }); ``` --- ## Model Selection Guide :::warning[Default Model Updated] The SDK default fallback is now `anthropic.claude-sonnet-4-6`. The previous default (`anthropic.claude-3-sonnet-20240229-v1:0`) is deprecated. You can still override the model by setting `BEDROCK_MODEL` in your environment or passing the `model` parameter in code. ::: ### Anthropic Claude Models ```typescript // Claude 4.6 Opus - Latest, most capable (1M context) const opus46 = await ai.generate({ input: { text: "Most difficult reasoning task" }, provider: "bedrock", model: "anthropic.claude-opus-4-6-v1:0", }); // Claude 4.5 Sonnet - Balanced performance (recommended) const sonnet45 = await ai.generate({ input: { text: "Complex analysis task" }, provider: "bedrock", model: "anthropic.claude-sonnet-4-5-20250929-v1:0", }); // Claude 3.5 Haiku - Fast and affordable const haiku35 = await ai.generate({ input: { text: "Quick simple query" }, provider: "bedrock", model: "anthropic.claude-3-5-haiku-20241022-v1:0", }); ``` **Claude Model IDs:** | Model ID | Series | Context | | ------------------------------------------- | ----------------------- | ------- | | `anthropic.claude-opus-4-6-v1:0` | Claude 4.6 Opus | 1M | | `anthropic.claude-sonnet-4-6` | Claude 4.6 Sonnet | 1M | | `anthropic.claude-opus-4-5-20251101-v1:0` | Claude 4.5 Opus | 200K | | `anthropic.claude-sonnet-4-5-20250929-v1:0` | Claude 4.5 Sonnet | 200K | | `anthropic.claude-haiku-4-5-20251001-v1:0` | Claude 4.5 Haiku | 200K | | `anthropic.claude-opus-4-1-20250805-v1:0` | Claude 4.1 Opus | 200K | | `anthropic.claude-sonnet-4-20250514-v1:0` | Claude 4 Sonnet | 200K | | `anthropic.claude-3-7-sonnet-20250219-v1:0` | Claude 3.7 Sonnet | 200K | | `anthropic.claude-3-5-sonnet-20241022-v1:0` | Claude 3.5 Sonnet | 200K | | `anthropic.claude-3-5-haiku-20241022-v1:0` | Claude 3.5 Haiku | 200K | | `anthropic.claude-3-opus-20240229-v1:0` | Claude 3 Opus (legacy) | 200K | | `anthropic.claude-3-haiku-20240307-v1:0` | Claude 3 Haiku (legacy) | 200K | > **Tip:** For Claude 4+ models, AWS recommends cross-region inference profile IDs (e.g., `us.anthropic.claude-sonnet-4-6`) instead of bare model IDs. Cross-region profiles enable automatic routing across regions for better availability. See the [Bedrock cross-region inference docs](https://docs.aws.amazon.com/bedrock/latest/userguide/cross-region-inference.html) for details. ### Amazon Nova Models Amazon Nova is the first-party model family from AWS, spanning text, multimodal, media generation, speech, and embeddings. ```typescript // Nova Pro - Multimodal, balanced (300K context) const novaPro = await ai.generate({ input: { text: "Analyze this data" }, provider: "bedrock", model: "amazon.nova-pro-v1:0", }); // Nova Micro - Text only, fastest (128K context) const novaMicro = await ai.generate({ input: { text: "Quick classification" }, provider: "bedrock", model: "amazon.nova-micro-v1:0", }); // Nova 2 Lite - Next-gen multimodal (1M context) const nova2Lite = await ai.generate({ input: { text: "Long document analysis" }, provider: "bedrock", model: "amazon.nova-2-lite-v1:0", }); ``` **Nova Model IDs:** | Model ID | Type | Context | Notes | | ------------------------------------------ | ----------------- | ------- | ----------------------- | | `amazon.nova-premier-v1:0` | Text + Multimodal | 1M+ | Most capable Nova | | `amazon.nova-pro-v1:0` | Text + Multimodal | 300K | Balanced | | `amazon.nova-lite-v1:0` | Text + Multimodal | 300K | Cost-effective | | `amazon.nova-micro-v1:0` | Text only | 128K | Fastest, cheapest | | `amazon.nova-2-lite-v1:0` | Text + Multimodal | 1M | Gen 2, extended context | | `amazon.nova-2-sonic-v1:0` | Speech-to-speech | -- | Gen 2 voice | | `amazon.nova-sonic-v1:0` | Speech-to-speech | -- | Real-time voice | | `amazon.nova-canvas-v1:0` | Image generation | -- | Text-to-image | | `amazon.nova-reel-v1:0` | Video generation | -- | Text-to-video | | `amazon.nova-reel-v1:1` | Video generation | -- | Improved v1.1 | | `amazon.nova-2-multimodal-embeddings-v1:0` | Embeddings | -- | Multimodal embeddings | ### Meta Llama Models ```typescript // Llama 4 Scout - Massive 10M context window const scout = await ai.generate({ input: { text: "Analyze this very long document" }, provider: "bedrock", model: "meta.llama4-scout-17b-instruct-v1:0", }); // Llama 4 Maverick - 1M context, higher quality const maverick = await ai.generate({ input: { text: "Complex reasoning task" }, provider: "bedrock", model: "meta.llama4-maverick-17b-instruct-v1:0", }); // Llama 3.3 70B - Strong general-purpose const llama33 = await ai.generate({ input: { text: "General task" }, provider: "bedrock", model: "meta.llama3-3-70b-instruct-v1:0", }); ``` **Llama Model IDs:** | Model ID | Series | Context | Notes | | ---------------------------------------- | ---------------- | ------- | --------------------------------- | | `meta.llama4-scout-17b-instruct-v1:0` | Llama 4 Scout | 10M | Largest context window on Bedrock | | `meta.llama4-maverick-17b-instruct-v1:0` | Llama 4 Maverick | 1M | Higher quality | | `meta.llama3-3-70b-instruct-v1:0` | Llama 3.3 | 128K | Strong general-purpose | | `meta.llama3-2-90b-instruct-v1:0` | Llama 3.2 | 128K | Multimodal (vision) | | `meta.llama3-2-11b-instruct-v1:0` | Llama 3.2 | 128K | Multimodal (vision) | | `meta.llama3-2-3b-instruct-v1:0` | Llama 3.2 | 128K | Lightweight | | `meta.llama3-2-1b-instruct-v1:0` | Llama 3.2 | 128K | Edge / mobile | | `meta.llama3-1-405b-instruct-v1:0` | Llama 3.1 | 128K | Largest open model | | `meta.llama3-1-70b-instruct-v1:0` | Llama 3.1 | 128K | Balanced | | `meta.llama3-1-8b-instruct-v1:0` | Llama 3.1 | 128K | Fast, cheap | | `meta.llama3-70b-instruct-v1:0` | Llama 3 (legacy) | 8K | -- | | `meta.llama3-8b-instruct-v1:0` | Llama 3 (legacy) | 8K | -- | ### Mistral AI Models ```typescript // Mistral Large 3 (675B) - Most capable const mistralLarge3 = await ai.generate({ input: { text: "Complex reasoning" }, provider: "bedrock", model: "mistral.mistral-large-3-675b-instruct", }); // Pixtral Large - Vision + text const pixtral = await ai.generate({ input: { text: "Describe this image" }, provider: "bedrock", model: "mistral.pixtral-large-2502-v1:0", }); ``` **Mistral Model IDs:** | Model ID | Type | Notes | | --------------------------------------- | --------------------- | ------------------- | | `mistral.mistral-large-3-675b-instruct` | Large 3 (675B) | Most capable | | `mistral.mistral-large-2407-v1:0` | Large 2 | Previous gen | | `mistral.mistral-large-2402-v1:0` | Large (legacy) | -- | | `mistral.magistral-small-2509` | Magistral Small | Reasoning-focused | | `mistral.ministral-3-14b-instruct` | Ministral 14B | Mid-size | | `mistral.ministral-3-8b-instruct` | Ministral 8B | Lightweight | | `mistral.ministral-3-3b-instruct` | Ministral 3B | Edge / mobile | | `mistral.pixtral-large-2502-v1:0` | Pixtral Large | Vision + text | | `mistral.voxtral-small-24b-2507` | Voxtral Small 24B | Audio + text | | `mistral.voxtral-mini-3b-2507` | Voxtral Mini 3B | Audio (lightweight) | | `mistral.devstral-2-123b` | Devstral 2 (123B) | Coding-focused | | `mistral.mistral-7b-instruct-v0:2` | Mistral 7B (legacy) | -- | | `mistral.mixtral-8x7b-instruct-v0:1` | Mixtral 8x7B (legacy) | -- | ### DeepSeek, Qwen, and Other Models ```typescript // DeepSeek R1 - Deep reasoning const deepseek = await ai.generate({ input: { text: "Solve this step by step" }, provider: "bedrock", model: "deepseek.r1-v1:0", }); // Qwen 3 (235B) - Multilingual, coding const qwen = await ai.generate({ input: { text: "Write a Python function" }, provider: "bedrock", model: "qwen.qwen3-235b-a22b-2507-v1:0", }); ``` **Additional Model IDs:** | Model ID | Provider | Notes | | --------------------------------- | -------------------- | -------------------------------- | | `deepseek.r1-v1:0` | DeepSeek | Deep reasoning (R1) | | `deepseek.v3-v1:0` | DeepSeek | General-purpose (V3) | | `qwen.qwen3-235b-a22b-2507-v1:0` | Qwen | Flagship (235B MoE) | | `qwen.qwen3-coder-480b-a35b-v1:0` | Qwen | Coding (480B MoE) | | `qwen.qwen3-coder-30b-a3b-v1:0` | Qwen | Coding (lightweight) | | `qwen.qwen3-32b-v1:0` | Qwen | Dense 32B | | `qwen.qwen3-next-80b-a3b` | Qwen | Next-gen MoE | | `qwen.qwen3-vl-235b-a22b` | Qwen | Vision-language | | `ai21.jamba-1-5-large-v1:0` | AI21 Labs | Jamba 1.5 Large (256K context) | | `ai21.jamba-1-5-mini-v1:0` | AI21 Labs | Jamba 1.5 Mini | | `google.gemma-3-27b-it` | Google | Gemma 3 27B | | `google.gemma-3-12b-it` | Google | Gemma 3 12B | | `google.gemma-3-4b-it` | Google | Gemma 3 4B | | `nvidia.nemotron-nano-3-30b` | NVIDIA | Nemotron Nano 30B (256K context) | | `writer.palmyra-x5-v1:0` | Writer | Palmyra X5 (1M context) | | `openai.gpt-oss-120b-1:0` | OpenAI (open source) | GPT-OSS 120B | ### Embedding and Reranking Models ```typescript const provider = await ProviderFactory.createProvider("bedrock"); // Nova 2 Multimodal Embeddings (text + image) const novaEmbed = await provider.embedMany( ["Document 1", "Document 2"], "amazon.nova-2-multimodal-embeddings-v1:0", ); // Cohere Embed v4 - Latest embeddings const cohereEmbed = await provider.embedMany( ["Query text"], "cohere.embed-v4:0", ); // Titan Embeddings v2 (legacy) const titanEmbed = await provider.embedMany( ["Document"], "amazon.titan-embed-text-v2:0", ); ``` **Embedding & Reranking Model IDs:** | Model ID | Type | Notes | | ------------------------------------------ | --------- | ------------------------- | | `amazon.nova-2-multimodal-embeddings-v1:0` | Embedding | Multimodal (text + image) | | `cohere.embed-v4:0` | Embedding | Latest Cohere embeddings | | `cohere.embed-english-v3` | Embedding | English-optimized | | `cohere.embed-multilingual-v3` | Embedding | 100+ languages | | `amazon.titan-embed-text-v2:0` | Embedding | 1024 dimensions | | `amazon.titan-embed-text-v1` | Embedding | 1536 dimensions | | `amazon.titan-embed-image-v1` | Embedding | Multimodal (legacy) | | `cohere.rerank-v3-5:0` | Reranking | Relevance scoring for RAG | | `amazon.rerank-v1:0` | Reranking | AWS-native reranking | ### Cohere Generation Models ```typescript // Command R+ - RAG optimized const commandRPlus = await ai.generate({ input: { text: "Search and summarize documents" }, provider: "bedrock", model: "cohere.command-r-plus-v1:0", }); ``` **Cohere Generation Model IDs:** - `cohere.command-r-plus-v1:0` - Command R+ (best for RAG) - `cohere.command-r-v1:0` - Command R (lighter) --- ## IAM Roles & Permissions ### EC2 Instance Role ```bash # Create trust policy cat > trust-policy.json lambda-trust.json { await logMetric(result.usage.totalTokens, result.cost); }, }); ``` ### CloudWatch Logs ```typescript const logs = new CloudWatchLogs({ region: "us-east-1" }); async function logRequest(data: any) { await logs.putLogEvents({ logGroupName: "/aws/bedrock/requests", logStreamName: "production", logEvents: [ { timestamp: Date.now(), message: JSON.stringify(data), }, ], }); } const ai = new NeuroLink({ providers: [{ name: "bedrock", config: { region: "us-east-1" } }], onSuccess: async (result) => { await logRequest({ model: result.model, tokens: result.usage.totalTokens, latency: result.latency, cost: result.cost, }); }, }); ``` --- ## Cost Management ### Pricing Overview Pricing varies by model and changes frequently. Check the [Bedrock pricing page](https://aws.amazon.com/bedrock/pricing/) for current rates. Representative examples: ``` Claude 4.5 Sonnet: - Input: $3.00 per 1M tokens - Output: $15.00 per 1M tokens Claude 3.5 Haiku: - Input: $0.80 per 1M tokens - Output: $4.00 per 1M tokens Nova Pro: - Input: $0.80 per 1M tokens - Output: $3.20 per 1M tokens Nova Micro: - Input: $0.035 per 1M tokens - Output: $0.14 per 1M tokens Llama 4 Scout: - Input: $0.17 per 1M tokens - Output: $0.17 per 1M tokens Llama 3.1 405B: - Input: $2.65 per 1M tokens - Output: $3.50 per 1M tokens Mistral Large 3: - Input: $2.00 per 1M tokens - Output: $6.00 per 1M tokens DeepSeek R1: - Input: $1.35 per 1M tokens - Output: $5.40 per 1M tokens ``` ### Cost Budgets ```bash # Create budget for Bedrock aws budgets create-budget \ --account-id ACCOUNT_ID \ --budget file://budget.json # budget.json cat > budget.json = { "anthropic.claude-sonnet-4-5-20250929-v1:0": { input: 3.0, output: 15.0 }, "anthropic.claude-3-5-haiku-20241022-v1:0": { input: 0.8, output: 4.0 }, "amazon.nova-pro-v1:0": { input: 0.8, output: 3.2 }, "amazon.nova-micro-v1:0": { input: 0.035, output: 0.14 }, "meta.llama4-scout-17b-instruct-v1:0": { input: 0.17, output: 0.17 }, }; const rates = pricing[model] || { input: 1.0, output: 1.0 }; const cost = (inputTokens / 1_000_000) * rates.input + (outputTokens / 1_000_000) * rates.output; this.monthlyCost += cost; return cost; } getMonthlyTotal(): number { return this.monthlyCost; } } ``` --- ## Production Patterns ### Pattern 1: Multi-Model Strategy ```typescript const ai = new NeuroLink({ providers: [ // Cheap for simple tasks (Nova Micro - $0.035/1M input) { name: "bedrock-nova-micro", config: { region: "us-east-1" }, model: "amazon.nova-micro-v1:0", condition: (req) => req.complexity === "low", }, // Balanced for medium tasks { name: "bedrock-sonnet", config: { region: "us-east-1" }, model: "anthropic.claude-sonnet-4-5-20250929-v1:0", condition: (req) => req.complexity === "medium", }, // Premium for complex tasks (1M context) { name: "bedrock-opus", config: { region: "us-east-1" }, model: "anthropic.claude-opus-4-6-v1:0", condition: (req) => req.complexity === "high", }, ], }); ``` ### Pattern 2: Guardrails ```typescript // Enable Bedrock Guardrails const ai = new NeuroLink({ providers: [ { name: "bedrock", config: { region: "us-east-1", guardrailId: "abc123xyz", // Created in Bedrock console guardrailVersion: "1", }, }, ], }); const result = await ai.generate({ input: { text: "Your prompt" }, provider: "bedrock", model: "anthropic.claude-sonnet-4-5-20250929-v1:0", }); // Content filtered by guardrails ``` ### Pattern 3: Knowledge Base Integration ```bash # Create Knowledge Base in Bedrock aws bedrock-agent create-knowledge-base \ --name my-kb \ --role-arn arn:aws:iam::ACCOUNT_ID:role/BedrockKBRole \ --knowledge-base-configuration '{ "type": "VECTOR", "vectorKnowledgeBaseConfiguration": { "embeddingModelArn": "arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-embed-text-v2:0" } }' \ --storage-configuration '{ "type": "OPENSEARCH_SERVERLESS", "opensearchServerlessConfiguration": { "collectionArn": "arn:aws:aoss:us-east-1:ACCOUNT_ID:collection/abc", "vectorIndexName": "my-index", "fieldMapping": { "vectorField": "embedding", "textField": "text", "metadataField": "metadata" } } }' ``` --- ## Best Practices ### 1. ✅ Use IAM Roles Instead of Keys ```typescript // ✅ Good: EC2 instance role (no keys) const ai = new NeuroLink({ providers: [ { name: "bedrock", config: { region: "us-east-1" }, // Credentials from instance metadata }, ], }); ``` ### 2. ✅ Enable VPC Endpoints ```bash # ✅ Good: Private connectivity aws ec2 create-vpc-endpoint \ --service-name com.amazonaws.us-east-1.bedrock-runtime ``` ### 3. ✅ Monitor Costs ```typescript // ✅ Good: Track every request const cost = costTracker.calculateCost(model, inputTokens, outputTokens); ``` ### 4. ✅ Use Appropriate Model for Task ```typescript // ✅ Good: Match model to complexity const model = complexity === "low" ? "claude-haiku" : "claude-sonnet"; ``` ### 5. ✅ Enable CloudWatch Logging ```typescript // ✅ Good: Comprehensive logging await logs.putLogEvents({ /* ... */ }); ``` --- ## Troubleshooting ### Common Issues #### 1. "Model Access Denied" **Problem**: Model not enabled in your account. **Solution**: ```bash # Enable via console # https://console.aws.amazon.com/bedrock → Model access # Or check status aws bedrock list-foundation-models --region us-east-1 ``` #### 2. "Throttling Exception" **Problem**: Exceeded rate limits. **Solution**: ```bash # Request quota increase aws service-quotas request-service-quota-increase \ --service-code bedrock \ --quota-code L-12345678 \ --desired-value 1000 ``` #### 3. "Invalid Model ID" **Problem**: Wrong model identifier. **Solution**: ```bash # List available models aws bedrock list-foundation-models --region us-east-1 # Use exact model ID model: 'anthropic.claude-sonnet-4-5-20250929-v1:0' # ✅ Correct ``` --- ## Related Documentation - **[Provider Setup](/docs/getting-started/provider-setup)** - General configuration - **[Multi-Region](/docs/guides/enterprise/multi-region)** - Geographic distribution - **[Cost Optimization](/docs/cookbook/cost-optimization)** - Reduce costs - **[Compliance](/docs/guides/enterprise/compliance)** - Security --- ## Additional Resources - **[AWS Bedrock Docs](https://docs.aws.amazon.com/bedrock/)** - Official documentation - **[Bedrock Pricing](https://aws.amazon.com/bedrock/pricing/)** - Pricing details - **[Bedrock Console](https://console.aws.amazon.com/bedrock)** - Manage models - **[AWS CLI Reference](https://docs.aws.amazon.com/cli/latest/reference/bedrock/)** - CLI commands --- **Need Help?** Join our [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## Azure OpenAI Provider Guide # Azure OpenAI Provider Guide **Enterprise-grade OpenAI models with Microsoft Azure infrastructure and compliance** ## Quick Start ### 1. Create Azure OpenAI Resource ```bash # Via Azure CLI az cognitiveservices account create \ --name my-openai-resource \ --resource-group my-resource-group \ --location eastus \ --kind OpenAI \ --sku S0 ``` Or use [Azure Portal](https://portal.azure.com/#create/Microsoft.CognitiveServicesOpenAI): 1. Search for "Azure OpenAI" 2. Click "Create" 3. Select subscription and resource group 4. Choose region (eastus, westeurope, etc.) 5. Name your resource 6. Click "Review + Create" ### 2. Deploy a Model ```bash # Deploy GPT-4o model az cognitiveservices account deployment create \ --name my-openai-resource \ --resource-group my-resource-group \ --deployment-name gpt-4o-deployment \ --model-name gpt-4o \ --model-version "2024-08-06" \ --model-format OpenAI \ --sku-capacity 10 \ --sku-name "Standard" ``` Or via Azure Portal: 1. Open your Azure OpenAI resource 2. Go to "Deployments" → "Create new deployment" 3. Select model (gpt-4o, gpt-4, gpt-35-turbo, etc.) 4. Name deployment 5. Set capacity (TPM quota) ### 3. Get Credentials ```bash # Get endpoint az cognitiveservices account show \ --name my-openai-resource \ --resource-group my-resource-group \ --query "properties.endpoint" --output tsv # Get API key az cognitiveservices account keys list \ --name my-openai-resource \ --resource-group my-resource-group \ --query "key1" --output tsv ``` ### 4. Configure NeuroLink ```bash # .env AZURE_OPENAI_API_KEY=your_api_key_here AZURE_OPENAI_ENDPOINT=https://my-resource.openai.azure.com/ AZURE_OPENAI_DEPLOYMENT=gpt-4o-deployment ``` ```typescript const ai = new NeuroLink({ providers: [ { name: "azure-openai", config: { apiKey: process.env.AZURE_OPENAI_API_KEY, endpoint: process.env.AZURE_OPENAI_ENDPOINT, deployment: process.env.AZURE_OPENAI_DEPLOYMENT, }, }, ], }); const result = await ai.generate({ input: { text: "Hello from Azure OpenAI!" }, provider: "azure-openai", }); console.log(result.content); ``` --- ## Regional Deployment ### Available Regions | Region | Location | Models Available | Data Residency | | --------------------- | ------------- | ---------------- | -------------- | | **East US** | Virginia, USA | All models | USA | | **East US 2** | Virginia, USA | All models | USA | | **South Central US** | Texas, USA | All models | USA | | **West Europe** | Netherlands | All models | EU | | **North Europe** | Ireland | All models | EU | | **UK South** | London, UK | All models | UK | | **France Central** | Paris, France | All models | EU | | **Switzerland North** | Zurich | All models | Switzerland | | **Sweden Central** | Stockholm | All models | EU | | **Australia East** | Sydney | All models | Australia | | **Japan East** | Tokyo | All models | Japan | | **Canada East** | Quebec | All models | Canada | ### Multi-Region Setup ```typescript const ai = new NeuroLink({ providers: [ // US deployments { name: "azure-us-east", config: { apiKey: process.env.AZURE_US_EAST_KEY, endpoint: "https://my-us-east.openai.azure.com/", deployment: "gpt-4o-deployment", }, region: "us-east", priority: 1, condition: (req) => req.userRegion === "us", }, // EU deployments { name: "azure-eu-west", config: { apiKey: process.env.AZURE_EU_WEST_KEY, endpoint: "https://my-eu-west.openai.azure.com/", deployment: "gpt-4o-deployment", }, region: "eu-west", priority: 1, condition: (req) => req.userRegion === "eu", }, // Asia deployments { name: "azure-japan", config: { apiKey: process.env.AZURE_JAPAN_KEY, endpoint: "https://my-japan.openai.azure.com/", deployment: "gpt-4o-deployment", }, region: "japan", priority: 1, condition: (req) => req.userRegion === "asia", }, ], failoverConfig: { enabled: true }, }); ``` --- ## Model Deployments ### Available Models | Model | Deployment Name | Context | Vision | Best For | TPM Quota | | -------------------------- | ---------------------- | ------- | ------ | --------------------------- | --------- | | **GPT-6 Astra** _(new)_ | gpt-6-astra | 1,050K | Yes | Current flagship | 10K - 1M | | **GPT-6 Sol** _(new)_ | gpt-6-sol | 1,050K | Yes | Current flagship | 10K - 1M | | **GPT-6 Luna** _(new)_ | gpt-6-luna | 1,050K | Yes | Current flagship | 10K - 1M | | **GPT-5.6 Sol** _(new)_ | gpt-5.6-sol | 1,050K | Yes | Azure-only (retired direct) | 10K - 1M | | **GPT-5.6 Terra** _(new)_ | gpt-5.6-terra | 1,050K | Yes | Azure-only (retired direct) | 10K - 1M | | **GPT-5.6 Luna** _(new)_ | gpt-5.6-luna | 1,050K | Yes | Azure-only (retired direct) | 10K - 1M | | **GPT-5.5** _(new)_ | gpt-5.5 | 1,050K | Yes | Azure-only (retired direct) | 10K - 1M | | **GPT-5.4** | gpt-5.4 | 1,050K | Yes | Flagship (March 2026) | 10K - 1M | | **GPT-5.4 Mini** | gpt-5.4-mini | 400K | Yes | Fast, cost-effective | 10K - 10M | | **GPT-5.4 Nano** | gpt-5.4-nano | 400K | Yes | Ultra-lightweight | 10K - 10M | | **GPT-5** | gpt-5 | 400K | Yes | Advanced reasoning | 10K - 1M | | **GPT-5 Mini** | gpt-5-mini | 400K | Yes | Balanced cost/perf | 10K - 10M | | **GPT-4.1** | gpt-4.1 | 1,047K | Yes | Long-context tasks | 10K - 1M | | **GPT-4.1 Mini** | gpt-4.1-mini | 1,047K | Yes | Long-context, affordable | 10K - 10M | | **GPT-4.1 Nano** | gpt-4.1-nano | 1,047K | Yes | Long-context, lightweight | 10K - 10M | | **o3** | o3 | 200K | Yes | Deep reasoning | 10K - 1M | | **o3-mini** | o3-mini | 200K | No | Reasoning, cost-effective | 10K - 10M | | **o4-mini** | o4-mini | 200K | Yes | Latest reasoning, efficient | 10K - 10M | | **GPT-4o** | gpt-4o | 128K | Yes | Complex reasoning | 10K - 1M | | **GPT-4o-mini** | gpt-4o-mini | 128K | Yes | General tasks | 10K - 10M | | **GPT-4-turbo** | gpt-4-turbo | 128K | Yes | Advanced tasks | 10K - 1M | | **GPT-4** | gpt-4 | 8K | No | Production (legacy) | 10K - 1M | | **GPT-3.5-turbo** | gpt-35-turbo | 16K | No | High-volume | 10K - 10M | | **text-embedding-ada-002** | text-embedding-ada-002 | 8K | — | Vector search | 10K - 10M | | **text-embedding-3-small** | text-embedding-3-small | 8K | — | Efficient search | 10K - 10M | | **text-embedding-3-large** | text-embedding-3-large | 8K | — | Accuracy | 10K - 10M | :::warning[GPT-4o-mini Retirement] GPT-4o-mini is retiring on Azure: **Standard deployments retire March 31, 2026**; **Provisioned and Global deployments retire October 1, 2026**. Migrate to `gpt-4.1-mini` or `gpt-5-mini` as a replacement. ::: ### Deployment Quotas (TPM) ``` Standard Tier Quotas (Tokens Per Minute): - gpt-4o: 10K - 1M TPM - gpt-4o-mini: 10K - 10M TPM - gpt-4-turbo: 10K - 1M TPM - gpt-35-turbo: 10K - 10M TPM - embeddings: 10K - 10M TPM Request quota increase via Azure Portal if needed. ``` ### Multiple Model Deployments ```typescript const ai = new NeuroLink({ providers: [ // GPT-4o for complex tasks { name: "azure-gpt4o", config: { apiKey: process.env.AZURE_API_KEY, endpoint: process.env.AZURE_ENDPOINT, deployment: "gpt-4o-deployment", }, model: "gpt-4o", }, // GPT-4o-mini for general tasks { name: "azure-gpt4o-mini", config: { apiKey: process.env.AZURE_API_KEY, endpoint: process.env.AZURE_ENDPOINT, deployment: "gpt-4o-mini-deployment", }, model: "gpt-4o-mini", }, // GPT-3.5-turbo for high-volume { name: "azure-gpt35", config: { apiKey: process.env.AZURE_API_KEY, endpoint: process.env.AZURE_ENDPOINT, deployment: "gpt-35-turbo-deployment", }, model: "gpt-35-turbo", }, ], }); // Route based on task complexity const complexTask = await ai.generate({ input: { text: "Complex analysis..." }, provider: "azure-gpt4o", }); const simpleTask = await ai.generate({ input: { text: "Simple query..." }, provider: "azure-gpt4o-mini", }); ``` --- ## Azure AD Authentication ### Managed Identity (Recommended) ```typescript const credential = new DefaultAzureCredential(); const ai = new NeuroLink({ providers: [ { name: "azure-openai", config: { credential, // Use Azure AD instead of API key endpoint: process.env.AZURE_OPENAI_ENDPOINT, deployment: process.env.AZURE_OPENAI_DEPLOYMENT, }, }, ], }); ``` ### Service Principal ```typescript const credential = new ClientSecretCredential( process.env.AZURE_TENANT_ID!, process.env.AZURE_CLIENT_ID!, process.env.AZURE_CLIENT_SECRET!, ); const ai = new NeuroLink({ providers: [ { name: "azure-openai", config: { credential, endpoint: process.env.AZURE_OPENAI_ENDPOINT, deployment: process.env.AZURE_OPENAI_DEPLOYMENT, }, }, ], }); ``` ### User-Assigned Managed Identity ```typescript const credential = new ManagedIdentityCredential({ clientId: process.env.AZURE_CLIENT_ID, }); const ai = new NeuroLink({ providers: [ { name: "azure-openai", config: { credential, endpoint: process.env.AZURE_OPENAI_ENDPOINT, deployment: process.env.AZURE_OPENAI_DEPLOYMENT, }, }, ], }); ``` --- ## Private Endpoint & VNet Integration ### Configure Private Endpoint ```bash # Create private endpoint az network private-endpoint create \ --name my-openai-pe \ --resource-group my-resource-group \ --vnet-name my-vnet \ --subnet my-subnet \ --private-connection-resource-id "/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.CognitiveServices/accounts/my-openai" \ --group-id account \ --connection-name my-openai-connection ``` ### Private DNS Zone ```bash # Create private DNS zone az network private-dns zone create \ --resource-group my-resource-group \ --name privatelink.openai.azure.com # Link to VNet az network private-dns link vnet create \ --resource-group my-resource-group \ --zone-name privatelink.openai.azure.com \ --name my-openai-dns-link \ --virtual-network my-vnet \ --registration-enabled false ``` ### VNet Integration in Code ```typescript // No code changes needed - just use private endpoint URL const ai = new NeuroLink({ providers: [ { name: "azure-openai", config: { apiKey: process.env.AZURE_API_KEY, endpoint: "https://my-openai.privatelink.openai.azure.com/", // Private endpoint deployment: "gpt-4o-deployment", }, }, ], }); ``` --- ## Compliance & Security ### Data Residency ```typescript // Ensure EU data stays in EU const ai = new NeuroLink({ providers: [ { name: "azure-eu", config: { apiKey: process.env.AZURE_EU_KEY, endpoint: "https://my-eu-resource.openai.azure.com/", deployment: "gpt-4o-deployment", region: "westeurope", // EU region }, condition: (req) => req.userRegion === "EU", compliance: ["GDPR", "ISO27001", "SOC2"], }, ], }); ``` ### Customer-Managed Keys (CMK) ```bash # Enable CMK with Azure Key Vault az cognitiveservices account update \ --name my-openai-resource \ --resource-group my-resource-group \ --encryption KeyVault \ --encryption-key-name my-key \ --encryption-key-source Microsoft.KeyVault \ --encryption-key-vault https://my-vault.vault.azure.net/ ``` ### Disable Public Network Access ```bash # Restrict to private endpoint only az cognitiveservices account update \ --name my-openai-resource \ --resource-group my-resource-group \ --public-network-access Disabled ``` --- ## Monitoring & Logging ### Azure Monitor Integration ```typescript const appInsights = new ApplicationInsights({ connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING, }); appInsights.start(); const ai = new NeuroLink({ providers: [ { name: "azure-openai", config: { apiKey: process.env.AZURE_API_KEY, endpoint: process.env.AZURE_OPENAI_ENDPOINT, deployment: process.env.AZURE_OPENAI_DEPLOYMENT, }, }, ], onSuccess: (result) => { // Log to Application Insights appInsights.trackEvent({ name: "AI_Generation_Success", properties: { provider: result.provider, model: result.model, tokens: result.usage.totalTokens, cost: result.cost, latency: result.latency, }, }); }, onError: (error, provider) => { // Log errors appInsights.trackException({ exception: error, properties: { provider }, }); }, }); ``` ### Diagnostic Logs ```bash # Enable diagnostic logs az monitor diagnostic-settings create \ --name my-diagnostic-settings \ --resource "/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.CognitiveServices/accounts/my-openai" \ --logs '[{"category":"Audit","enabled":true},{"category":"RequestResponse","enabled":true}]' \ --workspace "/subscriptions/{sub}/resourceGroups/{rg}/providers/microsoft.operationalinsights/workspaces/my-workspace" ``` --- ## Cost Management ### Pricing Model ``` Azure OpenAI Pricing (as of 2025): GPT-4o: - Input: $2.50 per 1M tokens - Output: $10.00 per 1M tokens GPT-4o-mini: - Input: $0.15 per 1M tokens - Output: $0.60 per 1M tokens GPT-4-turbo: - Input: $10.00 per 1M tokens - Output: $30.00 per 1M tokens GPT-3.5-turbo: - Input: $0.50 per 1M tokens - Output: $1.50 per 1M tokens Embeddings (ada-002): - $0.10 per 1M tokens ``` ### Cost Tracking ```typescript class AzureCostTracker { private dailyCost = 0; private monthlyCost = 0; recordUsage(result: any) { const inputTokens = result.usage.promptTokens; const outputTokens = result.usage.completionTokens; // Calculate cost based on model let cost = 0; if (result.model === "gpt-4o") { cost = (inputTokens / 1_000_000) * 2.5 + (outputTokens / 1_000_000) * 10.0; } else if (result.model === "gpt-4o-mini") { cost = (inputTokens / 1_000_000) * 0.15 + (outputTokens / 1_000_000) * 0.6; } this.dailyCost += cost; this.monthlyCost += cost; return cost; } getStats() { return { daily: this.dailyCost, monthly: this.monthlyCost, }; } } const costTracker = new AzureCostTracker(); const result = await ai.generate({ input: { text: "Your prompt" }, provider: "azure-openai", enableAnalytics: true, }); const cost = costTracker.recordUsage(result); console.log(`Request cost: $${cost.toFixed(4)}`); ``` ### Budget Alerts ```bash # Create budget in Azure az consumption budget create \ --budget-name openai-monthly-budget \ --amount 1000 \ --time-grain Monthly \ --start-date 2025-01-01 \ --end-date 2025-12-31 \ --resource-group my-resource-group ``` --- ## Production Patterns ### Pattern 1: High Availability Setup ```typescript const ai = new NeuroLink({ providers: [ // Primary region { name: "azure-primary", priority: 1, config: { apiKey: process.env.AZURE_PRIMARY_KEY, endpoint: process.env.AZURE_PRIMARY_ENDPOINT, deployment: "gpt-4o-deployment", }, }, // Failover region { name: "azure-secondary", priority: 2, config: { apiKey: process.env.AZURE_SECONDARY_KEY, endpoint: process.env.AZURE_SECONDARY_ENDPOINT, deployment: "gpt-4o-deployment", }, }, ], failoverConfig: { enabled: true, maxAttempts: 3, retryDelay: 1000, }, healthCheck: { enabled: true, interval: 60000, }, }); ``` ### Pattern 2: Load Balancing Across Deployments ```typescript const ai = new NeuroLink({ providers: [ { name: "azure-deployment-1", config: { apiKey: process.env.AZURE_API_KEY, endpoint: process.env.AZURE_ENDPOINT, deployment: "gpt-4o-deployment-1", }, weight: 1, }, { name: "azure-deployment-2", config: { apiKey: process.env.AZURE_API_KEY, endpoint: process.env.AZURE_ENDPOINT, deployment: "gpt-4o-deployment-2", }, weight: 1, }, { name: "azure-deployment-3", config: { apiKey: process.env.AZURE_API_KEY, endpoint: process.env.AZURE_ENDPOINT, deployment: "gpt-4o-deployment-3", }, weight: 1, }, ], loadBalancing: "round-robin", }); ``` ### Pattern 3: Quota Management ```typescript class QuotaManager { private tokensThisMinute = 0; private minuteStart = Date.now(); private quotaLimit = 100000; // 100K TPM async checkQuota(estimatedTokens: number): Promise { const now = Date.now(); // Reset if new minute if (now - this.minuteStart > 60000) { this.tokensThisMinute = 0; this.minuteStart = now; } // Check if within quota return this.tokensThisMinute + estimatedTokens <= this.quotaLimit; } recordUsage(tokens: number) { this.tokensThisMinute += tokens; } getRemaining(): number { return Math.max(0, this.quotaLimit - this.tokensThisMinute); } } const quotaManager = new QuotaManager(); async function generateWithQuota(prompt: string) { const estimated = prompt.length / 4; // Rough estimate if (!(await quotaManager.checkQuota(estimated))) { throw new Error("Quota exceeded, please wait"); } const result = await ai.generate({ input: { text: prompt }, provider: "azure-openai", enableAnalytics: true, }); quotaManager.recordUsage(result.usage.totalTokens); return result; } ``` --- ## Troubleshooting ### Common Issues #### 1. "Deployment Not Found" **Problem**: Incorrect deployment name. **Solution**: ```bash # List all deployments az cognitiveservices account deployment list \ --name my-openai-resource \ --resource-group my-resource-group # Use exact deployment name in config AZURE_OPENAI_DEPLOYMENT=gpt-4o-deployment # ✅ Exact name ``` #### 2. "Rate Limit Exceeded (429)" **Problem**: Exceeded TPM quota for deployment. **Solution**: ```bash # Increase quota via Azure Portal: # 1. Go to resource → Deployments # 2. Edit deployment # 3. Increase TPM capacity # Or request quota increase via support ticket ``` #### 3. "Resource Not Found" **Problem**: Incorrect endpoint or resource deleted. **Solution**: ```bash # Verify resource exists az cognitiveservices account show \ --name my-openai-resource \ --resource-group my-resource-group # Check endpoint format AZURE_OPENAI_ENDPOINT=https://my-resource.openai.azure.com/ # ✅ With trailing slash ``` #### 4. "Invalid API Key" **Problem**: API key rotated or incorrect. **Solution**: ```bash # Regenerate key az cognitiveservices account keys regenerate \ --name my-openai-resource \ --resource-group my-resource-group \ --key-name key1 # Update environment variable ``` --- ## Best Practices ### 1. ✅ Use Managed Identity in Azure ```typescript // ✅ Good: Managed identity (no keys to manage) const credential = new DefaultAzureCredential(); const ai = new NeuroLink({ providers: [ { name: "azure-openai", config: { credential, endpoint, deployment }, }, ], }); ``` ### 2. ✅ Deploy Multiple Regions for HA ```typescript // ✅ Good: Multi-region failover providers: [ { name: "azure-us", priority: 1 }, { name: "azure-eu", priority: 2 }, ]; ``` ### 3. ✅ Use Private Endpoints for Security ```bash # ✅ Good: Private endpoint + disable public access az cognitiveservices account update \ --public-network-access Disabled ``` ### 4. ✅ Monitor Costs with Budgets ```bash # ✅ Good: Set budget alerts az consumption budget create \ --amount 1000 \ --time-grain Monthly ``` ### 5. ✅ Enable Diagnostic Logging ```bash # ✅ Good: Enable audit logs az monitor diagnostic-settings create \ --logs '[{"category":"Audit","enabled":true}]' ``` --- ## Related Documentation - **[Provider Setup Guide](/docs/getting-started/provider-setup)** - General provider configuration - **[Multi-Region Deployment](/docs/guides/enterprise/multi-region)** - Geographic distribution - **[Compliance Guide](/docs/guides/enterprise/compliance)** - Security and compliance - **[Cost Optimization](/docs/cookbook/cost-optimization)** - Reduce costs --- ## Additional Resources - **[Azure OpenAI Documentation](https://learn.microsoft.com/azure/cognitive-services/openai/)** - Official docs - **[Azure OpenAI Pricing](https://azure.microsoft.com/pricing/details/cognitive-services/openai-service/)** - Pricing details - **[Azure Portal](https://portal.azure.com/)** - Manage resources - **[Azure CLI Reference](https://learn.microsoft.com/cli/azure/cognitiveservices)** - CLI commands --- **Need Help?** Join our [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## Azure Speech Services # Azure Speech Services Azure Cognitive Services Speech provides both TTS and STT capabilities. ## Setup ```bash # Required environment variables AZURE_SPEECH_KEY=your-speech-key AZURE_SPEECH_REGION=eastus ``` Get credentials from: **Azure Portal** > **Cognitive Services** > **Speech** > **Keys and Endpoint** ## Usage ### Text-to-Speech ```typescript const result = await neurolink.generate({ input: { text: "Summarize this document" }, tts: { enabled: true, provider: "azure-tts", voice: "en-US-JennyNeural", format: "mp3", }, }); // result.audio contains the synthesized speech ``` ### Speech-to-Text ```typescript const result = await neurolink.generate({ input: { text: "" }, stt: { enabled: true, provider: "azure-stt", audio: audioBuffer, language: "en-US", }, }); // result.transcription.text contains the transcribed text ``` ### CLI ```bash # TTS neurolink generate "Hello world" --tts --tts-provider azure-tts # STT neurolink generate --stt --stt-provider azure-stt --input-audio ./recording.wav ``` ## Supported Voices Azure Speech supports 400+ neural voices across 140+ languages. Common voices: | Voice | Language | Style | | -------------------- | ------------ | ------- | | `en-US-JennyNeural` | English (US) | General | | `en-US-GuyNeural` | English (US) | General | | `en-GB-SoniaNeural` | English (UK) | General | | `de-DE-KatjaNeural` | German | General | | `fr-FR-DeniseNeural` | French | General | | `ja-JP-NanamiNeural` | Japanese | General | ## Supported Audio Formats - TTS output: `mp3`, `wav`, `ogg` - STT input: `wav` (16kHz PCM mono recommended), `ogg`, `opus` - Azure's short-audio REST endpoint does not decode MP3 — convert to WAV first or use a different STT provider for MP3 input. ## Limits - TTS: 10,000 characters per request - STT: Batch mode (streaming not yet supported) --- ## Baidu Qianfan Provider Guide # Baidu Qianfan Provider Guide Baidu Qianfan is a **Tier-2 catalog provider**: its integration is one JSON file (`src/lib/providers/catalog/baidu-qianfan.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** An unauthenticated `GET https://qianfan.baidubce.com/v2/models` > on 2026-09-29 answered HTTP 403, so the model ids come from Baidu's public > docs and the roster has not been checked. No account was created and no API > key was used to build this entry. > `evidence.liveMatrix` is `null` until someone runs the live capability matrix > with a real key (see [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://console.bce.baidu.com/qianfan/ (an unauthenticated GET on 2026-09-29 answered HTTP 200 with the page title 百度智能云千帆大模型平台; sign-in was not attempted while building this entry) 2. Create an API key: the API KEY page (https://cloud.baidu.com/doc/qianfan/s/wmh8l6tnf, updated 2026-04-14) says to log in to the 百度千帆 platform, click 系统管理 in the left navigation, open API Key, then click 创建 API Key and enter a name; the quickstart (https://cloud.baidu.com/doc/qianfan/s/rmh4stn9m) links 控制台-安全认证-API Key to https://console.bce.baidu.com/iam/#/iam/apikey/list 3. Authentication is HTTP Bearer: the quickstart (https://cloud.baidu.com/doc/qianfan/s/rmh4stn9m) says the Authorization request header must carry the API key with Bearer in front of it; NeuroLink does not validate the key format 4. Billing as the vendor states it: the new-user free-quota page (https://cloud.baidu.com/doc/qianfan/s/Imi2rpirg, updated 2025-11-17) says that after you visit the platform and agree to the user agreement the system activates it automatically and issues a new-user free token quota; its table has 17 rows under 服务名称, 赠送Tokens量 and 有效期, and the page says the quota applies to online inference calls of preset model services, not batch inference. The billing page (https://cloud.baidu.com/doc/qianfan/s/wmh4sv6ya, updated 2026-09-24) lists text-generation prices under "按量后付费" in 元/千tokens, for example "ERNIE 5.1" (版本名称 "ERNIE-5.1") with 在线推理 "0.004" for 子项 `输入(输入<=32k)` and "0.018" for 子项 `输出(输入<=32k)` 5. Set `BAIDU_QIANFAN_API_KEY` in your .env file ### 2. Configure ```bash export BAIDU_QIANFAN_API_KEY=your-api-key export BAIDU_QIANFAN_MODEL=ernie-5.1 # optional — overrides the default model export BAIDU_QIANFAN_BASE_URL=https://qianfan.baidubce.com/v2 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "baidu-qianfan", model: "ernie-5.1", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider baidu-qianfan ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "baidu-qianfan", credentials: { baiduQianfan: { apiKey: process.env.BAIDU_QIANFAN_API_KEY } }, }); ``` --- ## Billing The [new-user free-quota page](https://cloud.baidu.com/doc/qianfan/s/Imi2rpirg) (updated 2025-11-17) says that from 2025-10-24 00:00, after you visit the platform and agree to the user agreement, the system activates Qianfan automatically and issues a new-user free token quota. Its table has 17 rows, and the 服务名称 column reads: ERNIE-4.5-Turbo-128K, ERNIE-4.5-Turbo-32K, ERNIE-4.5-Turbo-VL, ERNIE-X1-Turbo-32K, DeepSeek-R1, DeepSeek-R1-250528, DeepSeek-V3-250324, DeepSeek-V3.1-250821, DeepSeek-V3.1-Think-250821, Kimi-K2-Instruct, Qwen3-235B-A22B-Instruct-2507, Qwen3-30B-A3B-Instruct-2507, Qwen3-Coder-30B-A3B-Instruct, Qwen3-Coder-480B-A35B-Instruct, bge-large-en, bge-large-zh and qianfan-sug-8k. In rows 1 to 17 the 赠送Tokens量 cell reads "100万" and the 有效期 cell reads "3个月". The page says the quota applies to online inference calls of preset model services, not batch inference. The entry records `free-tier` from that page. The [model-retirement page](https://cloud.baidu.com/doc/qianfan/s/zmh4stou3) (updated 2026-09-24, retrieved 2026-09-29) has rows with 退役模型版本 "DeepSeek-V3.1-250821" (模型退役日期 "2026-06-30"), "Kimi-K2-Instruct" (模型退役日期 "2026-03-26") and "ERNIE-4.5-Turbo-128K" (模型退役日期 "2026-10-29"). The [billing page](https://cloud.baidu.com/doc/qianfan/s/wmh4sv6ya) (updated 2026-09-24) lists text-generation prices under "按量后付费" in 元/千tokens (yuan per thousand tokens). For example, its row with 模型名称 "ERNIE 5.1" and 版本名称 "ERNIE-5.1" has 在线推理 "0.004" for 子项 `输入(输入<=32k)`, "0.018" for `输出(输入<=32k)`, "0.006" for `输入(32k<输入<=128k)` and "0.022" for `输出(32k<输入<=128k)`. The catalog entry carries no `pricingPerMTok`; the billing page states prices in 元/千tokens. --- ## Models | Model | Context | Vision | Max output | Notes | | ------------------------ | ------- | ------ | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ernie-5.1` ⭐ | 128k | no | 65,536 | NeuroLink default. Listed under the "ERNIE系列-旗舰模型" heading; the "推荐模型" table cell begins "ERNIE 5.1是文心系列最新模型". Listed on the function-calling page. | | `ernie-5.0` | 128k | yes | 65,536 | Listed in the vendor's 视觉理解 (vision understanding) ERNIE table and on the function-calling page; described as "文心5.0是原生全模态大模型". The model-retirement page has a row with 退役模型版本 "ERNIE-5.0" and 模型退役日期 "2026-10-29". | | `ernie-4.5-turbo-128k` | 128k | no | not set | Listed under the "ERNIE系列-旗舰模型" heading and in the "推荐模型" table; the page states max output as "16k" in one table and "[2,12288]" in another, so the entry leaves it unset. The model-retirement page has a row with 退役模型版本 "ERNIE-4.5-Turbo-128K" and 模型退役日期 "2026-10-29". | | `ernie-4.5-turbo-32k` | 32k | no | 12,288 | Listed under the "ERNIE系列-旗舰模型" heading. The model-retirement page has a row with 退役模型版本 "ERNIE-4.5-Turbo-32K" and 模型退役日期 "2026-10-29". | | `ernie-4.5-turbo-vl` | 128k | yes | 16,384 | Listed in the vendor's 视觉理解 (vision understanding) ERNIE table; `models.visionModel`. The model-retirement page has a row with 退役模型版本 "ERNIE-4.5-Turbo-VL-128K" and 模型退役日期 "2026-10-29", and a row with 退役模型版本 "ERNIE-4.5-Turbo-VL-32K" and 模型退役日期 "2026-10-29". | | `deepseek-v4-pro` | 1M | no | 393,216 | NeuroLink fallback. The "推荐模型" table cell begins "核心定位:超强通用旗舰大模型,Agent能力大幅提高。"; listed on the structured-outputs page and in the deep-thinking page's `thinking` list. | | `deepseek-v4-pro-0813` | 1M | no | 393,216 | Listed in the DeepSeek tables of the text-generation and deep-thinking sections. | | `deepseek-v4-flash-0731` | 1M | no | 393,216 | Listed in the DeepSeek tables of the text-generation and deep-thinking sections. | | `glm-5.3` | 1M | no | 131,072 | Listed under "其他" in the 深度思考 (deep thinking) section. | | `glm-5.2` | 1M | no | 131,072 | Listed under "其他" in the 深度思考 (deep thinking) section. | | `glm-5.1` | 198k | no | 131,072 | NeuroLink fallback. Listed under "其他" in the 深度思考 section, on the structured-outputs page and in the deep-thinking page's `thinking` list. | | `qwen3.5-397b-a17b` | 256k | no | 65,536 | NeuroLink fallback. Listed under "Qwen系列" in the 深度思考 (deep thinking) section. | The figures are read from the [model-list page](https://cloud.baidu.com/doc/qianfan/s/rmh4stp0j) (updated 2026-09-16, retrieved 2026-09-29). The Context column shows the page's strings ("128k", "1M" and similar); the catalog's `contextWindow` values are NeuroLink's numeric entries for them, converted with k = 1,000 and M = 1,000,000. Max output is the top of the range the page states, for example "[1,65536]". The deep-thinking section's note says "以下最大输出长度为包含思维链输出的总长度" (translation: the max output lengths below are the total including chain-of-thought output), which applies to the `glm-*` and `qwen3.5-*` rows. Vision is `yes` for the models the page lists in its 视觉理解 (vision understanding) section. The vision-understanding page ([docs](https://cloud.baidu.com/doc/qianfan-docs/s/fm8r1ndsm)) documents image input as OpenAI-style `image_url` content parts. `models.defaultContextWindow` (32,000) and `models.defaultMaxOutputTokens` (4,096) are placeholders the vendor does not publish; they apply to a model id that is not in the catalog. Each per-model `contextWindow` is a placeholder too: NeuroLink's conversion of the page's "128k", "1M" style strings. **Fallback order** when the default is unavailable: `deepseek-v4-pro` → `glm-5.1` → `qwen3.5-397b-a17b`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `glm-5.1`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Baidu Qianfan — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://qianfan.baidubce.com/v2/models`, HTTP 403, JSON body with code "AccessDenied" and message "Access denied.", 2026-09-29 — no key used, so the 12 model ids come from the model-list page and the roster has not been checked | | Auth-failure shape | unauthenticated `GET https://qianfan.baidubce.com/v2/chat/completions`, HTTP 401, JSON body with `error.code` "invalid_iam_token", 2026-09-29. The [error-code page](https://cloud.baidu.com/doc/qianfan/s/Qmh4su56e) (updated 2026-04-22) lists 错误码 "invalid_iam_token" as HTTP 401 with 错误信息 "IAM Certification failed" and rows of 类型 "rate_limit_exceeded" as HTTP 429 | | Model retirements | public [model-retirement page](https://cloud.baidu.com/doc/qianfan/s/zmh4stou3) (updated 2026-09-24), read 2026-09-29 — rows with 模型退役日期 "2026-10-29" for ERNIE-5.0, ERNIE-4.5-Turbo-128K, ERNIE-4.5-Turbo-32K, ERNIE-4.5-Turbo-VL-128K and ERNIE-4.5-Turbo-VL-32K | | Billing | public [free-quota page](https://cloud.baidu.com/doc/qianfan/s/Imi2rpirg) (updated 2025-11-17) states a new-user free token quota issued automatically after agreeing to the user agreement, 2026-09-29 | | Tools / structured output | documented on the function-calling and structured-outputs pages respectively; neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=baidu-qianfan` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting | Symptom | Cause | Fix | | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | HTTP 401 with code `invalid_iam_token` | The error-code page says the bearer token is invalid or expired, or the request's Authorization header did not add Bearer | The quickstart says to put Bearer in front of the API key in the Authorization header; NeuroLink reads `BAIDU_QIANFAN_API_KEY` | | HTTP 429 with 类型 `rate_limit_exceeded` | The error-code page lists 错误码 `rpm_rate_limit_exceeded` (错误信息 "Rate limit reached for RPM") and `tpm_rate_limit_exceeded` ("Rate limit reached for TPM") | The same page's 说明 for those rows includes "适当控制请求频率" (translation: control the request frequency appropriately) | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Baseten Provider Guide # Baseten Provider Guide Baseten is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/baseten.json`) rather than hand-written code. That file is the source of truth for everything on this page. ## Quick Start ### 1. Get an API key 1. Visit: https://app.baseten.co/ and sign in or create a workspace 2. Review the current Baseten billing and credit terms in the console before making requests 3. Create a personal API key in the Baseten console 4. Set `BASETEN_API_KEY` in your .env file ### 2. Configure ```bash export BASETEN_API_KEY=your-api-key export BASETEN_MODEL=zai-org/GLM-5.3-Flash # optional — overrides the default model export BASETEN_BASE_URL=https://inference.baseten.co/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "baseten", model: "zai-org/GLM-5.3-Flash", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider baseten ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "baseten", credentials: { baseten: { apiKey: process.env.BASETEN_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ------------------------------------------ | ------- | ------ | ------------- | -------------------------------------------------------------------------------------------------- | | `openai/gpt-oss-120b` | 125K | no | $0.1 / $0.5 | OpenAI GPT-OSS 120B; general-purpose model with controllable reasoning | | `zai-org/GLM-4.7` | 195K | no | $0.6 / $2.2 | GLM 4.7; fast general-purpose model with 200K context and enhanced tool use | | `moonshotai/Kimi-K2.6` | 256K | no | $0.95 / $4 | Kimi K2.6; agentic and coding model for multi-step reasoning and tool use | | `deepseek-ai/DeepSeek-V4-Pro` | 1M | no | $1.74 / $3.48 | DeepSeek V4 Pro; 1M-context mixture-of-experts model for agentic workflows and coding | | `nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B` | 198K | no | $0.6 / $2.4 | NVIDIA Nemotron 3 Ultra; flagship reasoning and non-reasoning model for code and agentic execution | | `zai-org/GLM-5.2` | 1M | no | $1.4 / $4.4 | GLM 5.2; 1M-context reasoning model | | `moonshotai/Kimi-K2.7-Code` | 256K | no | $0.95 / $4 | Kimi K2.7 Code; model for complex coding, code reasoning and long-horizon development | | `deepseek-ai/DeepSeek-V4-Flash-0731` | 1M | no | $0.13 / $0.26 | DeepSeek V4 Flash 0731; fast, low-cost 1M-context mixture-of-experts model | | `thinkingmachines/inkling` | 1M | no | $1 / $4.05 | Thinking Machines Inkling; 1M-context reasoning model | | `zai-org/GLM-5.2-Fast` | 1M | no | $2.1 / $6.6 | GLM 5.2 Fast; 1M-context model | | `moonshotai/Kimi-K3` | 1M | no | $3 / $15 | Kimi K3; 1M-context model | | `thinkingmachines/inkling-small` | 1M | no | $0.5 / $1.2 | Thinking Machines Inkling Small; 1M-context reasoning model | | `deepseek-ai/DeepSeek-V4-Pro-0813` | 1M | no | $1.32 / $3.96 | DeepSeek V4 Pro 0813; dated 1M-context mixture-of-experts model for agentic workflows and coding | | `zai-org/GLM-5.3-Flash` ⭐ | 1M | yes | $0.15 / $0.5 | GLM 5.3 Flash; 1M-context reasoning model with live-verified image input | | `zai-org/GLM-5.3` | 1M | no | $1.4 / $4.4 | GLM 5.3; 1M-context reasoning model | | `zai-org/GLM-5.3-Fast` | 1M | yes | $2.1 / $6.6 | GLM 5.3 Fast; 1M-context reasoning model with image input | **Fallback order** when the default is unavailable: `zai-org/GLM-5.3-Flash` → `zai-org/GLM-5.3` → `zai-org/GLM-5.2`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for Baseten: | Probe | Result | | --------------------- | -------------------------------------------------- | | Roster | authenticated GET /v1/models, HTTP 200, 2026-09-03 | | Auth rejection | HTTP 403, 2026-09-03 | | Live capability sweep | **not run** | > ⚠️ No live capability sweep is recorded for Baseten. The roster and auth > behaviour were verified against the real API on the date above, but the > capability flags come from the catalog declaration rather than from a > measured end-to-end run. Treat them as the provider's stated behaviour. --- ## Troubleshooting | Symptom | Cause | Fix | | ------------------------- | ----------------------------------- | ----------------------------------------------------------------- | | `Invalid Baseten API key` | `BASETEN_API_KEY` unset or wrong | Check the key at https://app.baseten.co/ | | Model not found | The roster changed since 2026-09-03 | Pick a current id; catalog providers retire models without notice | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Beatoven.ai Provider Guide (music) # Beatoven.ai Provider Guide **Royalty-free background / cinematic music via Beatoven.ai** ## Quick Start ### 1. Get an API Key [https://www.beatoven.ai/dashboard](https://www.beatoven.ai/dashboard) ### 2. Configure ```bash BEATOVEN_API_KEY=your-key ``` ### 3. Generate Music ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "vertex", output: { mode: "music", music: { provider: "beatoven", prompt: "Warm corporate background loop, mid-tempo", duration: 60, genre: "corporate", mood: "uplifting", }, }, }); if (result.music?.buffer) { writeFileSync("./beatoven.mp3", result.music.buffer); } ``` --- ## CLI Usage ```bash pnpm run cli generate "Cinematic ambient pad" \ --provider beatoven --musicDuration 90 --musicGenre cinematic \ --musicOutput ./music.mp3 ``` --- ## Configuration Reference | Environment Variable | Required | Description | | -------------------- | -------- | ----------------- | | `BEATOVEN_API_KEY` | Yes | Beatoven API key | | `BEATOVEN_BASE_URL` | No | Base URL override | --- ## See Also - [Lyria Provider](/docs/getting-started/providers/lyria) - [ElevenLabs Music Provider](/docs/getting-started/providers/elevenlabs-music) --- ## Bee by HEOSSI Provider Guide # Bee by HEOSSI Provider Guide Bee by HEOSSI is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/bee-heossi.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs- and roster-verified, but not > yet live-verified**. Every fact below comes from Bee's public docs > (`https://bee.heossi.com/docs/sdks`, `/docs/changelog`, `/pricing`) and an > unauthenticated `GET /bee/models` call, re-run on 2026-09-28 — no API key > was created or used. No authenticated request (chat completion, tool call, > structured-output probe, vision probe) has been made against this vendor. > Capability flags that need a live account to confirm (tool calling, > structured output, combined tools+schema, vision) are therefore > conservative: unset or `false`/`"model-dependent"` rather than assumed. > `evidence.liveMatrix` is `null` until someone runs the live capability > sweep with a real key. ## Quick Start ### 1. Get an API key 1. Visit: https://workspace.bee.heossi.com/account/api-keys and sign in (or create a Bee Workspace account) 2. Create an API key — the free Bee Cell / Bee Pollen tier needs no credit card ("Free hosted access — no card", https://bee.heossi.com/pricing) 3. Higher tiers (Brood/Comb/Buzz/Hive/Swarm) draw from a prepaid wallet billed per token; see https://bee.heossi.com/pricing for current rates 4. Set `BEE_HEOSSI_API_KEY` in your .env file ### 2. Configure ```bash export BEE_HEOSSI_API_KEY=your-api-key export BEE_HEOSSI_MODEL=bee-cell # optional — overrides the default model export BEE_HEOSSI_BASE_URL=https://api.bee.heossi.com/bee # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "bee-heossi", model: "bee-cell", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider bee-heossi ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "bee-heossi", credentials: { beeHeossi: { apiKey: process.env.BEE_HEOSSI_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ------------- | ------- | ------ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `bee-cell` ⭐ | 128K | no | $0.30 / $1.20 | Recommended — free tier, no card; used in every Bee SDK/curl example. Tool calling / JSON mode not documented for this tier. | | `bee-brood` | 256K | no | $0.60 / $2.40 | Second tier; not named among the tool-calling/JSON-mode tiers; fallback. | | `bee-comb` | 256K† | no | $1.25 / $5.00 | Tool calling + JSON-mode structured output documented live (2026-07-11 changelog); fallback. | | `bee-buzz` | 256K† | no | $2.50 / $10.00 | Tool calling + JSON-mode structured output documented live; fallback. | | `bee-hive` | 256K‡ | no | $5.00 / $20.00 | Tool calling + JSON-mode structured output documented live; fallback. | | `bee-swarm` | 1M | no | $25.00 / $150.00 | "1M natively" per the changelog; not named among the tool-calling/JSON-mode tiers; fallback. | † Comb and Buzz also expose a separately routed long-context mode serving up to 1,010,000 tokens (2026-07-11 changelog) — a distinct routed path, not the value shown here. ‡ Hive reaches a 1M-token mode "via Comb" per the pricing page — routing detail, not modeled as this entry's context window. Each named tier also has one or two immutable pinned snapshot ids on the live roster (e.g. `bee-cell-20260710-r1`, `bee-comb-20260710-r1` and `bee-comb-20260827-r1` — Comb's `current_snapshot`). These are in the catalog for completeness but are not separately priced/documented and are not part of `topModels` or the fallback chain. Context window shown is the catalog default of 128,000 tokens (`bee-cell`); no per-request max-output-token ceiling is documented for any tier, so the catalog uses NeuroLink's house default of 4,096. **Fallback order** when the default is unavailable: `bee-brood` → `bee-comb` → `bee-buzz` → `bee-hive` → `bee-swarm`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for Bee by HEOSSI today — **docs- and roster-verified only, not live-verified**: | Probe | Result | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated GET `https://api.bee.heossi.com/bee/models`, HTTP 200, 13 models, 2026-09-28. The endpoint's own OpenAPI entry declares `security: []` (public). | | Docs cross-check | Base URL, request/response shapes and `reasoning_effort` field confirmed against the public OpenAPI 3.1 contract at `https://api.bee.heossi.com/openapi.json` (retrieved 2026-09-28). Pricing/context per tier confirmed against `https://bee.heossi.com/pricing`. Tool-calling/JSON-mode/context-mode facts confirmed against `https://bee.heossi.com/docs/changelog`. | | Auth rejection | Not probed — no authenticated or POST request was made (credential-free onboarding). The OpenAPI contract documents a `401` response ("Missing or invalid API credential") with no literal error-body text, so `errorRules` uses status-only matching. | | Live capability sweep | Not run. `evidence.liveMatrix` is `null`. Tool calling, JSON-mode structured output, combined tools+schema, and vision all need a real key to confirm and are conservatively unset/`false` until then. | --- ## Troubleshooting | Symptom | Cause | Fix | | -------------------------------------------------- | -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | | `Invalid Bee API key` | `BEE_HEOSSI_API_KEY` unset or wrong | Check the key at https://workspace.bee.heossi.com/account/api-keys | | "insufficient funded usage credit" (HTTP 402) | Prepaid wallet is empty (paid tiers only) | Top up at https://bee.heossi.com/pricing | | "model or capability not included" (HTTP 403) | The requested tier/feature isn't in your plan | Upgrade at https://bee.heossi.com/pricing, or switch to a tier your plan includes | | Frequent 429s | Allowance or rate limit reached | Wait and retry; review your plan's usage caps at https://bee.heossi.com/pricing | | Tool calls / `response_format` ignored or rejected | `bee-cell` (the default) is not among the tiers Bee documents tool calling and JSON mode for | Switch to `bee-comb`, `bee-buzz` or `bee-hive`, which the 2026-07-11 changelog names explicitly | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## BytePlus ModelArk Provider Guide # BytePlus ModelArk Provider Guide BytePlus ModelArk is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/byteplus-modelark.json`) rather than hand-written code. That file is the source of truth for the data on this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** The vendor's `GET /models` needs a key (an unauthenticated > GET answers HTTP 401), so the model ids come from the vendor's public > [Model list](https://docs.byteplus.com/en/docs/ModelArk/model-list) page and > the roster has not been checked. No account was created and no API key was > used to build this entry. `evidence.liveMatrix` is `null` until someone runs > the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://console.byteplus.com/auth/signup and register as a BytePlus user — the Inference free trial page (https://docs.byteplus.com/en/docs/ModelArk/free-inference-quota) says "Register and authenticate as a BytePlus user." 2. Activate the models you want to call on the Model activation page (https://ai.byteplus.com/ark/region:ap-southeast-1/openManagement) — the Quick start (https://docs.byteplus.com/en/docs/ModelArk/quick-start) says "Go to the Model activation page to activate the models you need to use." 3. Create an API key at https://ai.byteplus.com/ark/region:ap-southeast-1/apiKey — the Quick start says to "create or obtain a ModelArk API key"; the API key page (https://docs.byteplus.com/en/docs/ModelArk/api-key) says "API Key is isolated by region. Select the appropriate region before creating and using the API Key for authentication." 4. Free trial, as the vendor states it: "ModelArk offers new users a free inference trial quota, allowing them to get started at no cost." (https://docs.byteplus.com/en/docs/ModelArk/free-inference-quota); the Free Tokens Only mode page (https://docs.byteplus.com/en/docs/ModelArk/free-tokens-only-mode) says "In this mode, calls to the inference API consume only the 500k free tokens granted by the platform." 5. Set `BYTEPLUS_MODELARK_API_KEY` in your .env file (the vendor's examples read `ARK_API_KEY`, which NeuroLink does not) ### 2. Configure ```bash export BYTEPLUS_MODELARK_API_KEY=your-api-key export BYTEPLUS_MODELARK_MODEL=seed-2-0-pro-260328 # optional — overrides the default model export BYTEPLUS_MODELARK_BASE_URL=https://ark.ap-southeast.bytepluses.com/api/v3 # optional ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "byteplus-modelark", model: "seed-2-0-pro-260328", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider byteplus-modelark ``` Per-request credentials are passed like this: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "byteplus-modelark", credentials: { byteplusModelark: { apiKey: process.env.BYTEPLUS_MODELARK_API_KEY }, }, }); ``` The Chat API page describes the `model` parameter as the "ID of the called model" and says "For scenarios with multiple applications and fine-grained management, we recommend calling by inference endpoint ID." --- ## Billing The vendor's pages state: - Free trial: "ModelArk offers new users a free inference trial quota, allowing them to get started at no cost." ([Inference free trial](https://docs.byteplus.com/en/docs/ModelArk/free-inference-quota)) - Free Tokens Only mode: "In this mode, calls to the inference API consume only the 500k free tokens granted by the platform." ([Free Tokens Only mode](https://docs.byteplus.com/en/docs/ModelArk/free-tokens-only-mode)) - With Free Tokens Only mode disabled: "When disabled: Online inference calls first consume the free quota. After the free quota is used up, usage is billed based on actual token consumption." (same page) - Pricing: the [Pricing](https://docs.byteplus.com/en/docs/ModelArk/model-pricing) page says "Pay-as-you-go by token." The entry records `free-tier`, the schema value closest to the stated free inference trial quota. --- ## Models | Model | Context | Vision | $/M in · out (cache hit) | Notes | | ------------------------------ | ------- | ------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `seed-2-0-pro-260328` ⭐ | 256K | yes | $0.50 / $3.00 ($0.10) | NeuroLink default. The Model list card that links to its detail page is captioned "Flagship general-purpose agentic model". Tools are listed as "Tool Calling". It is not in the Model list's Structured output (beta) section. | | `dola-seed-2-1-turbo-260628` | 256K | yes | $0.5 / $2.5 ($0.1) | Fallback. Capabilities include Structured output. | | `seed-2-0-lite-260428` | 256K | yes | $0.25 / $2.00 ($0.05) | Fallback. Structured output is listed as "Structured output (Recommended: `json_schema` mode)". | | `seed-2-0-mini-260428` | 256K | yes | $0.10 / $0.40 ($0.02) | Fallback. Structured output is listed with "(Recommended: `json_schema` mode)". | | `seed-2-0-lite-260228` | 256K | yes | $0.25 / $2.00 ($0.05) | Fallback and `models.fallbackModelName`. The id in the vendor's OpenAI-compatibility quickstart, its function-calling streaming example and its chat/completions curl. | | `seed-2-0-mini-260215` | 256K | yes | $0.10 / $0.40 ($0.02) | Catalog entry. | | `seed-2-0-code-preview-260328` | 256K | yes | $0.50 / $3.00 ($0.10) | Catalog entry; status `preview` follows the word in the id. | | `glm-5-3-flash-260828` | 1024K | yes | $0.15 / $0.5 ($0.03) | Catalog entry. | | `glm-5-2-260617` | 1024K | no | $1.4 / $4.4 ($0.26) | Catalog entry; `no` is a schema placeholder, not a vendor statement. | | `deepseek-v4-1-flash-260910` | 1024K | yes | $0.30 / $1.20 ($0.006) | Catalog entry. Structured output is listed as "Structured output (json_object mode only)". Price shown is the "Peak hours" tier. | | `deepseek-v4-pro-ga-260813` | 1024K | no | $1.32 / $3.96 ($0.044) | Fallback; `no` is a schema placeholder, not a vendor statement. | | `deepseek-v4-flash-ga-260731` | 1024K | no | $0.44 / $1.32 ($0.014) | Fallback; `no` is a schema placeholder, not a vendor statement. | Model ids, capabilities and context lengths come from the Text generation table on the [Model list](https://docs.byteplus.com/en/docs/ModelArk/model-list) page (retrieved 2026-09-29); prices come from the "Online inference (standard)" table on the [Pricing](https://docs.byteplus.com/en/docs/ModelArk/model-pricing) page (retrieved 2026-09-29), in USD per million non-audio tokens. - **Tiered prices.** The Pricing page lists two "Prompt length" tiers for the Seed 2.0 rows, `[0, 128]` and `(128, 256]` (K tokens). The catalog stores the `[0, 128]` tier. For `seed-2-0-pro-260328` the `(128, 256]` tier is $1.00 in, $6.00 out and $0.20 cache-hit; the other Seed 2.0 rows' second tiers are in each model's `description` in the JSON. The `dola-seed-2-1-turbo-260628` row has one tier, `[0, 256]`, which is stored; the Pricing page's Model ID cell for that row reads `dola-seed-2-1-turbo`. - **Context.** The Model list writes lengths as `256K` and `1024K`; the catalog stores 256000 and 1024000 (K read as 1,000). `models.defaultContextWindow` (128,000) and `models.defaultMaxOutputTokens` (4,096) are placeholders for model ids outside the catalog; 4,096 is the `max_tokens` default on the Chat API page. No per-model `maxOutputTokens` is set. - **Vision.** `yes` means the Model list's Visual understanding table lists the model. `no`, for `glm-5-2-260617`, `deepseek-v4-pro-ga-260813` and `deepseek-v4-flash-ga-260731`, is a schema placeholder for a boolean the catalog requires; it is not a vendor statement. - **Status.** The `status` field holds `production` (`preview` for the model id containing "preview"); that is a schema placeholder, not a vendor statement. **Fallback order** when the default is unavailable: `seed-2-0-lite-260228` → `seed-2-0-lite-260428` → `seed-2-0-mini-260428` → `dola-seed-2-1-turbo-260628` → `deepseek-v4-pro-ga-260813` → `deepseek-v4-flash-ga-260731`. The runtime fallback model name is set explicitly to `seed-2-0-lite-260228`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for BytePlus ModelArk — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://ark.ap-southeast.bytepluses.com/api/v3/models` answered HTTP 401 on 2026-09-29; model ids are taken from the Model list page and the roster has not been checked | | Auth-failure shape | unauthenticated `GET` of `/models` and of `/chat/completions` each answered HTTP 401 on 2026-09-29 with a JSON body whose `error.code` is `AuthenticationError` and `error.type` is `Unauthorized`; no POST was sent | | Billing | public pages state a free inference trial quota for new users and pay-as-you-go pricing by token, 2026-09-29 — see [Billing](#billing); no signup was performed | | Tools / structured output | documented on the Function call and Structured output (beta) pages; neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=byteplus-modelark` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting The first six rows quote the vendor's [Error codes](https://docs.byteplus.com/en/docs/ModelArk/error-codes) page (rows 1 to 4 and 6) or [Free Tokens Only mode](https://docs.byteplus.com/en/docs/ModelArk/free-tokens-only-mode) page (row 5); the last row describes NeuroLink's own behaviour. | Symptom | Cause | Fix | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | | HTTP 401 `AuthenticationError` | "The API key or AK/SK in the request is missing or invalid." | "Please check the authentication credentials or troubleshoot based on the API document." | | HTTP 404 `ModelNotOpen` | "Your account %s has not activated the model %s." | "Please activate the model service in the Ark Console." | | HTTP 404 `InvalidEndpointOrModel.NotFound` | "The model or inference endpoint %s does not exist or you do not have access to it." | — | | HTTP 429 `QuotaExceeded` | "The account (%s) has exhausted the free trial quota of the model (%s)." | "To continue using the service, go to the ModelArk console and activate the corresponding model service on the Activation page." | | HTTP 429 `SetLimitExceeded` | "Your account [%s] has reached the set inference limit for the [%s] model, and the model service has been paused." | "To continue using this model, please visit the Model Activation page to adjust or close the "Free Tokens Only Mode"." | | HTTP 403 `AccountOverdueError` | "The request failed because your account has an overdue balance." | "To continue using the service, please go to the BytePlus Billing Center to recharge." | | Structured output ignored with tools attached | `structuredOutputWithTools` is `false` on this entry | NeuroLink omits `response_format` automatically when tools are present, before sending | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Bytez Provider Guide # Bytez Provider Guide Bytez is a **Tier-2 catalog provider**: its integration is one JSON file (`src/lib/providers/catalog/bytez.json`) rather than hand-written code. That file is the source of truth for this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** Bytez's `GET /models` needs a key, so the model ids come from > its public docs and the roster has not been checked. The fields below come > from Bytez's own public documentation and unauthenticated `GET` requests — no > account was created and no API key was used to build it. > `evidence.liveMatrix` is `null` until someone runs the live capability matrix > with a real key (see [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Open the API Dashboard at https://bytez.com/api; the Get started page (https://docs.bytez.com/model-api/docs/get-started.md) says "Copy your key from the API Dashboard" 2. Free plan (https://docs.bytez.com/model-api/docs/billing.md): "$0 / month - Get $1 in free credits", with "Run open models up to 7B parameters" and "Credits refresh every 4 weeks"; the Billing Cycle section lists Billing: None for the Free Plan 3. The same page lists a Pay-as-you-go plan with "Run open models up to 120B parameters" and "Add credits anytime" 4. Set `BYTEZ_API_KEY` in your .env file ### 2. Configure ```bash export BYTEZ_API_KEY=your-api-key export BYTEZ_MODEL=Qwen/Qwen3-4B # optional — overrides the default model export BYTEZ_BASE_URL=https://api.bytez.com/models/v2/openai/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "bytez", model: "Qwen/Qwen3-4B", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider bytez ``` Per-request credentials: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "bytez", credentials: { bytez: { apiKey: process.env.BYTEZ_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | Pricing | Notes | | ------------------ | ------- | ------ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `Qwen/Qwen3-4B` ⭐ | not set | no | per second of inference | NeuroLink default. The model in the "Basic usage (Open Source)" and "Streaming (Open Source)" examples of the Chat Completions page and in the Basic usage example of the chat Get started page. | | `Qwen/Qwen3-1.7B` | not set | no | not set | NeuroLink fallback. Named in the API reference's `model` field description: "The ID of the model to run (e.g., `Qwen/Qwen3-1.7B`, `openai/gpt-4`)". | Model ids are copied from these pages, retrieved 2026-09-29: - [Chat Completions page](https://docs.bytez.com/http-reference/examples/openai-compliant/chatCompletionsExample.md) — `Qwen/Qwen3-4B` - [Chat Completions API reference](https://docs.bytez.com/http-reference/oaiCompliant/chatCompletions.md) — `Qwen/Qwen3-1.7B` Open models are billed per second of inference (the "How Credits Work" table on the [Billing & Credits page](https://docs.bytez.com/model-api/docs/billing.md)). That page's "Pricing by Model Size" table lists 7B at $0.000072 per second, 15B at $0.000108, 35B at $0.000144, 70B at $0.000216 and 120B at $0.00036. The catalog stores no per-token price, because `pricingPerMTok` is a per-token figure. `models.defaultContextWindow` (8,192) and `models.defaultMaxOutputTokens` (1,024) are placeholders the vendor does not publish. The per-model context and output figures are left unset. **Vision:** the catalog sets `vision: false` for both models. The Chat Completions API reference types message content as string. **Fallback:** `fallbacks` lists `Qwen/Qwen3-1.7B`, which is the runtime fallback model name the loader derives. **Not in the catalog:** closed-source provider models (for example `openai/gpt-4`) are addressed with a provider prefix, and their curl examples on the Chat Completions page add a `provider-key` header. The catalog schema has no field for an extra request header, so none are listed. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Bytez — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Roster | unauthenticated `GET https://api.bytez.com/models/v2/openai/v1/models` answered HTTP 401 with the body `{"error":"Unauthorized"}`, 2026-09-29 — no key used. The model ids come from the docs pages listed under [Models](#models); the roster has not been checked | | Auth-failure shape | unauthenticated `GET` of both `.../v1/models` and `.../v1/chat/completions` answered 401 with `{"error":"Unauthorized"}`, 2026-09-29. The Models API reference describes 401 as "Auth error - check your api key and how you're sending it." ([page](https://docs.bytez.com/http-reference/list/models.md)). `errorRules` carry 401, 402 and 429 | | Auth header | the curl examples on the Chat Completions page send `Authorization: BYTEZ_KEY`, and its OpenAI-client examples pass the key as `apiKey`. The [Get started page](https://docs.bytez.com/model-api/docs/get-started.md) has the code comment `# add an Authorization header, with value "Key {BYTEZ_KEY}"` above a curl example that sends `-H "Authorization: BYTEZ_KEY"`. NeuroLink's OpenAI-compatible base sends `Authorization: Bearer ` by default. That request was not exercised — it needs a key | | Billing | [Billing & Credits](https://docs.bytez.com/model-api/docs/billing.md) lists a Free plan, "$0 / month - Get $1 in free credits", and its Billing Cycle section lists Billing: None for the Free Plan, 2026-09-29 | | Tools / structured output | declared `false` (see Key Facts for the request fields the API reference lists). Neither was exercised, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. The command is `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=bytez`, and it needs a real key. | This entry is not live-verified until `evidence.liveMatrix` is filled in. --- ## Documented error responses | Status | What the Bytez docs say | | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 401 | The Models API reference describes 401 as "Auth error - check your api key and how you're sending it." ([page](https://docs.bytez.com/http-reference/list/models.md)) | | 402 | The Billing & Credits page shows the response for an account whose credits ran out with auto-reload disabled, with the message "Insufficient credits. Please add credits to continue." ([page](https://docs.bytez.com/model-api/docs/billing.md)) | | 429 | The Models API reference documents 429 as "Too Many Requests – You have hit the rate limit."; the Billing & Credits page says requests over the open model rate limits "are rejected with a rate-limit error" | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Cartesia TTS Provider Guide # Cartesia TTS Provider Guide **Low-latency text-to-speech — Cartesia's `sonic-3.6` model over the synchronous `/tts/bytes` REST endpoint** ## Quick Start ### 1. Get an API Key Sign up at [play.cartesia.ai](https://play.cartesia.ai/), open **Manage → API Keys**, click **Create**, give the key a description, and copy the `sk_car_…` value. ### 2. Configure Environment ```bash # Required CARTESIA_API_KEY=sk_car_... # Optional: override the default voice id (any voice from your Cartesia library) # CARTESIA_VOICE_ID=... # Optional: override the model (default is sonic-3.6) # CARTESIA_MODEL=sonic-3.6 # Optional: override the API version header # CARTESIA_API_VERSION=2025-04-16 # Optional: override the base URL # CARTESIA_BASE_URL=https://api.cartesia.ai ``` ### 3. Synthesize Your First Audio ```typescript const ai = new NeuroLink(); const result = await ai.generate({ // The LLM provider doesn't matter — TTS-only flows skip the LLM call // when `tts.useAiResponse` is false (default). provider: "openai", input: { text: "Hello world from Cartesia Sonic" }, tts: { enabled: true, provider: "cartesia", format: "mp3", }, }); if (result.audio) { writeFileSync("./hello.mp3", result.audio.buffer); } ``` --- ## SDK Usage ### Basic Synthesis (Default Voice) ```typescript const result = await ai.generate({ provider: "openai", input: { text: "The quick brown fox jumps over the lazy dog." }, tts: { enabled: true, provider: "cartesia" }, }); ``` ### Custom Voice Copy a voice id from the **Voice Library** at [play.cartesia.ai](https://play.cartesia.ai/voices): ```typescript const result = await ai.generate({ provider: "openai", input: { text: "..." }, tts: { enabled: true, provider: "cartesia", voice: "your-cartesia-voice-id", format: "mp3", }, }); ``` ### TTS-Augmented LLM Response When `useAiResponse: true`, NeuroLink first calls the LLM, then synthesizes the LLM output through Cartesia: ```typescript const result = await ai.generate({ provider: "openai", // generates the text input: { text: "Tell me a 2-sentence joke" }, tts: { enabled: true, provider: "cartesia", useAiResponse: true, format: "mp3", }, }); console.log(result.content); // joke text writeFileSync("joke.mp3", result.audio.buffer); ``` ### WAV / PCM16 Output ```typescript // WAV (PCM s16le, 44.1 kHz) — complete RIFF/WAV file, plays in any player const wav = await ai.generate({ provider: "openai", input: { text: "..." }, tts: { enabled: true, provider: "cartesia", format: "wav" }, }); // PCM16 — raw 16-bit signed-LE PCM @ 24 kHz, NO RIFF header. // Useful for realtime streaming pipelines that want raw samples. const pcm = await ai.generate({ provider: "openai", input: { text: "..." }, tts: { enabled: true, provider: "cartesia", format: "pcm16" }, }); ``` ### Language Override The handler defaults to English. Pass `language` via the same options bag for other supported languages (see Cartesia docs for the current list): ```typescript const result = await ai.generate({ provider: "openai", input: { text: "Hola mundo" }, tts: { enabled: true, provider: "cartesia", // Provider-specific extension; not in TTSOptions yet — passed through. language: "es", } as unknown as Parameters[0]["tts"], }); ``` --- ## CLI Usage ```bash # Basic — default voice + mp3 pnpm run cli generate "Hello world" \ --tts --tts-provider cartesia \ --output ./hello.mp3 # With a custom voice pnpm run cli generate "Hello world" \ --tts --tts-provider cartesia \ --tts-voice your-cartesia-voice-id \ --output ./hello.mp3 # WAV format pnpm run cli generate "Hello world" \ --tts --tts-provider cartesia \ --tts-format wav --output ./hello.wav ``` --- ## Configuration Reference | Environment Variable | Required | Default | Description | | ---------------------- | -------- | -------------------------------------- | ---------------------------------------------------------- | | `CARTESIA_API_KEY` | Yes | — | Cartesia API key (`sk_car_…`) | | `CARTESIA_VOICE_ID` | No | `694f9389-aac1-45b6-b726-9d9369183238` | Default voice id used when no `voice` is passed per-call | | `CARTESIA_MODEL` | No | `sonic-3.6` | Model id sent as `model_id` | | `CARTESIA_API_VERSION` | No | `2025-04-16` | Value of the `Cartesia-Version` request header | | `CARTESIA_BASE_URL` | No | `https://api.cartesia.ai` | Base URL (override for self-hosted / EU regional gateways) | --- ## Voice Models | Model | Notes | | ----------- | --------------------------------------------------- | | `sonic-3.6` | Default — current best balance of latency + quality | Voices are identified by UUID strings from the Cartesia voice library. Browse and clone voices in your Cartesia dashboard. --- ## Feature Support Matrix | Feature | Cartesia | | ---------------------------------- | ------------------------------------------------ | | Text-to-speech | Yes (synchronous) | | Voice cloning | Yes (via dashboard upload, then voice id) | | Multilingual | Yes (English-first; pass `language` to override) | | MP3 output | Yes (44.1 kHz) | | WAV output | Yes (PCM s16le @ 44.1 kHz) | | PCM16 output | Yes (24 kHz, raw, no RIFF) | | OPUS output | Falls back to MP3 | | Synchronous synthesis | Yes (this handler) | | WebSocket streaming | Separate — `CartesiaStream` adapter | | `getVoices()` programmatic listing | Not implemented (use dashboard) | --- ## Troubleshooting ### `CARTESIA_API_KEY not configured` ```bash echo $CARTESIA_API_KEY export CARTESIA_API_KEY=sk_car_... ``` Get / rotate at [play.cartesia.ai](https://play.cartesia.ai/keys). ### `Cartesia synthesis failed: 401` The API key is invalid or revoked. Regenerate from the dashboard and update your `.env`. ### `Cartesia synthesis failed: 429` Throttled — usually because the account has insufficient credits or the plan's per-minute limit is exhausted. Top up credits or implement client-side backoff. The handler maps 408 / 429 / 5xx to retriable errors so framework-level retry will honor them. ### Audio sounds wrong / wrong voice The `voice` field must be a valid Cartesia voice UUID. If it's missing or invalid, the handler falls back to the env default (`CARTESIA_VOICE_ID`) or the built-in "Bright Female" id. Browse [play.cartesia.ai/voices](https://play.cartesia.ai/voices) to find a voice id, then pass it via `tts.voice` per call or set `CARTESIA_VOICE_ID` to make it the default. ### PCM16 output is unplayable in audio players `pcm16` is RAW samples at 24 kHz, not a WAV file — players need a header. Either write a 44-byte WAV header yourself before the PCM data, or switch to `format: "wav"` which produces a complete RIFF/WAV file already. ### Streaming use cases This handler is synchronous — it waits for the full audio response. For sub-100 ms first-byte latency in voice-agent flows, use `CartesiaStream` in `src/lib/adapters/tts/cartesiaHandler.ts` directly (it's wired into NeuroLink's voice server). The synchronous handler is the right choice for batch generation, file output, and any flow where you process the whole audio buffer at once. --- ## See Also - [TTS Feature Guide](/docs/features/tts) — overall TTS architecture and supported providers - [Fish Audio TTS](/docs/getting-started/providers/fish-audio) — sibling low-cost TTS handler - [ElevenLabs TTS](/docs/getting-started/providers/elevenlabs) — sibling TTS with the largest voice library - [Adding a TTS provider](/docs/provider-integration/16-adding-tts-provider) — internal reference for the integration pattern --- **Need Help?** Open a [GitHub Discussion](https://github.com/juspay/neurolink/discussions) or [issue](https://github.com/juspay/neurolink/issues). --- ## Cerebras Provider Guide # Cerebras Provider Guide **The fastest hosted generation available (~3000 tokens/s on GPT-OSS 120B) via Cerebras' Wafer-Scale Engine — best for throughput-hungry workloads** ## Quick Start ### 1. Get an API Key Sign up at [https://cloud.cerebras.ai](https://cloud.cerebras.ai) (Google OAuth works), claim the $5 free credit under **Billing → Credits** (a payment card must be saved — no charge is made), and create an API key (prefix `csk-`). ### 2. Configure Environment ```bash # Required CEREBRAS_API_KEY=csk-... # Optional: override the default model (default: gpt-oss-120b) CEREBRAS_MODEL=gpt-oss-120b # Optional: override the base URL # CEREBRAS_BASE_URL=https://api.cerebras.ai/v1 ``` ### 3. Generate Your First Response ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "cerebras", input: { text: "What is the Cerebras wafer-scale engine?" }, }); console.log(result.content); ``` --- ## SDK Usage ### Basic Generation ```typescript const result = await ai.generate({ provider: "cerebras", input: { text: "Write a haiku about silicon wafers." }, }); ``` ### Streaming ```typescript const stream = await ai.stream({ provider: "cerebras", input: { text: "Explain how B-trees work, step by step." }, }); for await (const chunk of stream.stream) { if ("content" in chunk && chunk.content) process.stdout.write(chunk.content); } ``` ### Tool Calling ```typescript const ai = new NeuroLink(); ai.registerTool("getTime", { name: "getTime", description: "Returns the current UTC time", inputSchema: { type: "object", properties: {} }, execute: async () => ({ utc: new Date().toISOString() }), }); const result = await ai.generate({ provider: "cerebras", input: { text: "What is the current UTC time? Use the tool." }, enabledToolNames: ["getTime"], }); ``` ### Structured Output ```typescript const result = await ai.generate({ provider: "cerebras", input: { text: "Name three fast chips as JSON." }, schema: z.object({ chips: z.array(z.string()) }), maxTokens: 1000, }); console.log(result.structuredData); // parsed, schema-shaped object ``` Combining `schema` with active tools works, but the schema is enforced post-hoc rather than on the wire (see Key Facts) — expect `structuredData` to be best-effort in that combination, exactly as with Groq. ### Per-Call Credentials ```typescript const result = await ai.generate({ provider: "cerebras", input: { text: "..." }, credentials: { cerebras: { apiKey: "user-key" } }, }); ``` --- ## CLI Usage ```bash # Default model (gpt-oss-120b) pnpm run cli generate "Quick question" --provider cerebras # Explicit model pnpm run cli generate "Hi" --provider cerebras --model gpt-oss-120b # Streaming pnpm run cli stream "Count to ten" --provider cerebras # Loop / chat pnpm run cli loop --provider cerebras ``` --- ## Provider Aliases | Alias | Example | | ---------- | --------------------- | | `cerebras` | `--provider cerebras` | --- ## Configuration Reference | Environment Variable | Required | Default | Description | | -------------------- | -------- | ---------------------------- | ---------------- | | `CEREBRAS_API_KEY` | Yes | — | Cerebras API key | | `CEREBRAS_MODEL` | No | `gpt-oss-120b` | Default model | | `CEREBRAS_BASE_URL` | No | `https://api.cerebras.ai/v1` | Base URL | --- ## Feature Support Matrix | Feature | gpt-oss-120b | | ------------------------- | ------------ | | Text generation | Yes | | Streaming | Yes | | Tool calling | Yes | | Structured output | Yes | | Structured output + tools | Post-hoc | | Vision | No | | Embeddings | No | | Context window | 65K/131K | --- ## Troubleshooting ### "Invalid Cerebras API key" ```bash # Presence check without printing the secret (terminal capture, CI logs # and shell transcripts retain echoed values): test -n "$CEREBRAS_API_KEY" && echo "CEREBRAS_API_KEY is set" || echo "CEREBRAS_API_KEY is missing" export CEREBRAS_API_KEY=csk-... ``` Get / rotate at [https://cloud.cerebras.ai](https://cloud.cerebras.ai). A bad key returns 401 with `"code": "wrong_api_key"`, which NeuroLink maps to this message. ### 402 payment_required on every call The account has no balance. Cerebras has no keyless free tier: open **Billing → Credits → ADD CREDITS** in the console, choose "Start with limited free credits", and save a payment card — the $5 promo credit activates with no charge. Skipping the claim step during onboarding ("SKIP TO CONSOLE") leaves the balance at $0.00. ### Empty content with small `maxTokens` on gpt-oss-120b `gpt-oss-120b` is a reasoning model: it spends its first tokens on a `reasoning` channel before emitting `content`. With a tight budget (e.g. `maxTokens: 50`) the entire budget goes to reasoning, `finish_reason` is `length`, and content is empty. Give reasoning prompts a few hundred tokens of headroom. ### 404 "model not found" for llama/qwen models Those models are retired, and so is `gemma-4-31b`. The catalog carries `gpt-oss-120b` only — verify the live roster with an authenticated `GET https://api.cerebras.ai/v1/models`. --- ## See Also - [Groq Provider](/docs/getting-started/providers/groq) — sibling speed-focused OpenAI-compat provider - [xAI Grok Provider](/docs/getting-started/providers/xai) — sibling OpenAI-compat with Grok 3 - [Tier 2 catalog entry guide](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider is wired internally --- **Need Help?** Open a [GitHub Discussion](https://github.com/juspay/neurolink/discussions) or [issue](https://github.com/juspay/neurolink/issues). --- ## Charm Hyper Provider Guide # Charm Hyper Provider Guide Charm Hyper is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/charm-hyper.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status: docs- and roster-verified, not live-verified.** This > entry was onboarded credential-free — everything below comes from Hyper's > own public documentation and an unauthenticated `GET /v1/models` call. No > API key was ever created, and no authenticated or `POST` request was made > to Hyper — so no chat call, tool call, structured-output call, or error > response was ever actually exercised. Capabilities below reflect what the > docs state or omit, not what a live probe proved. Run the > [Tier-2 live verification steps](/docs/provider-integration/tiers/tier-2-catalog-entry) > (roster probe with a real key, billing check, capability probes, live > matrix) before relying on this entry in production, and fill in > `evidence.liveMatrix` when that happens. ## Quick Start ### 1. Get an API key 1. Visit: https://hyper.charm.land/auth?mode=signup and sign up (Google, GitHub, or email) 2. Copy an API key from the Hyper Dashboard — it starts with `sk-hyper-` 3. Free plan: $0/month, 100 Hypercredits/month; paid subscription ($20/month, 250 Hypercredits/day) and prepaid bundles (never expire) are also available 4. Set `CHARM_HYPER_API_KEY` in your .env file ### 2. Configure ```bash export CHARM_HYPER_API_KEY=sk-hyper-your-api-key export CHARM_HYPER_MODEL=deepseek-v4-pro # optional — overrides the default model export CHARM_HYPER_BASE_URL=https://hyper.charm.land/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "charm-hyper", model: "deepseek-v4-pro", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider charm-hyper ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "charm-hyper", credentials: { "charm-hyper": { apiKey: process.env.CHARM_HYPER_API_KEY } }, }); ``` --- ## Models All 23 entries come from the public, unauthenticated `GET https://hyper.charm.land/v1/models` response (2026-09-28) — context window, max output tokens, vision and pricing are the vendor's own served metadata, not estimates. The one exception is the max output of four models (`kimi-k2-thinking`, `gpt-oss-120b`, `gemma-4-26b-a4b-it`, `minimax-m2.7`), shown as n/a: the roster's figure is a fixed fraction of the context window (a tenth for three of them) and reads like a gateway default, so the catalog records no max output for them and the SDK does not cap `maxTokens` for those models. | Model | Context | Max out | Vision | $/M in · out (cached in) | Notes | | ------------------------ | --------- | ------- | ------ | --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `deepseek-v4-pro` ⭐ | 1M | 384K | no | $2.40 / $4.80 ($0.20) | Default for this entry — Hyper's own Chat Completions reference example. | | `deepseek-v4.1-flash` | 1,048,576 | 32,768 | yes | $0.30 / $1.20 ($0.03) | Newest DeepSeek Flash snapshot; reasoning effort low/high/xhigh. | | `deepseek-v4-flash` | 1M | 384K | no | $0.20 / $0.40 ($0.04) | Homepage quick-start's example model. Hyper's marketing page lists this id under "attachment support", but the live roster reports `vision: false` — a documented inconsistency, not resolved here. | | `deepseek-v4-pro-0813` | 1M | 262,144 | no | $1.437216 / $4.311648 ($0.047907) | Dated pin of the Pro line. | | `deepseek-v4-flash-0731` | 1M | 384K | no | $0.44 / $1.32 ($0.044) | Dated pin of the Flash line. | | `kimi-k3` | 1,048,576 | 16,000 | yes | $3.2664 / $16.332 ($0.32664) | Moonshot Kimi K3. | | `kimi-k2-thinking` | 262,144 | n/a | no | $0.60 / $2.50 ($0.30) | Reasoning-first Kimi variant. | | `kimi-k2.7-code` | 256,000 | 16,000 | yes | $1.03436 / $4.3552 ($0.206872) | Code-focused Kimi variant. | | `glm-5.3` | 1M | 128,000 | no | $1.52432 / $4.79072 ($0.283088) | Zhipu GLM 5.3. | | `glm-5.3-flash` | 1,048,576 | 131,072 | yes | $0.16332 / $0.5444 ($0.031575) | Zhipu GLM 5.3 Flash. | | `glm-5.2` | 1M | 32,768 | no | $1.52432 / $4.79072 ($0.152432) | Prior GLM generation. | | `minimax-m3` | 512,000 | 512,000 | yes | $0.32664 / $1.30656 ($0.064239) | MiniMax M3 — max output equals its context window. | | `minimax-m2.7` | 262,100 | n/a | no | $0.484 / $1.852 ($0.242) | Prior MiniMax generation. | | `inkling` | 1,048,576 | 65,536 | yes | $1.0888 / $4.40964 ($0.185096) | Lineage not stated in the docs read for this entry. | | `qwen3.8-max` | 1M | 65,536 | yes | $2.00 / $6.00 ($0.25) | Alibaba Qwen3.8 Max. | | `qwen3.8-flash` | 1M | 128,000 | yes | $0.15 / $0.47 ($0.016) | Alibaba Qwen3.8 Flash. | | `qwen3.8-27b` | 1M | 128,000 | yes | $0.50 / $3.00 ($0.10) | Alibaba Qwen3.8 27B. | | `qwen3.8-2.4t-a95b` | 1M | 128,000 | no | $2.00 / $6.00 ($0.25) | Large Qwen3.8 MoE variant. | | `qwen3.7-max` | 1M | 64,000 | no | $2.50 / $7.50 ($0.50) | Prior Qwen generation. | | `qwen3.7-plus` | 1M | 64,000 | yes | $1.20 / $4.80 ($0.24) | Prior Qwen generation. | | `qwen3.7-flash` | 1M | 64,000 | yes | $0.20 / $0.80 ($0.04) | Prior Qwen generation. | | `gpt-oss-120b` | 131,072 | n/a | no | $0.178 / $0.68 ($0.089) | OpenAI's open-weight gpt-oss-120b. | | `gemma-4-26b-a4b-it` | 256,000 | n/a | no | $0.098 / $0.334 ($0.049) | Google Gemma 4 26B A4B, instruction-tuned. | **Fallback order** when the default is unavailable: `deepseek-v4-flash` → `deepseek-v4.1-flash` → `kimi-k2-thinking` → `glm-5.3` → `qwen3.8-max`. No model is marked as a designated vision model (`models.visionModel`) — Hyper's own pages disagree with each other about which models support image input (see `deepseek-v4-flash` above), and the disagreement was left unresolved rather than guessed at. --- ## Verification status Tier-2 onboarding normally requires a live capability sweep, gated by `pnpm run verify:provider-onboarding`. This entry was deliberately onboarded **without** a key, so that step has not run yet: | Probe | Result | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | **Unauthenticated** `GET /v1/models`, HTTP 200, 2026-09-28 — 23 models, matches Hyper's own docs statement that this endpoint needs no auth ("Browse the catalog — no auth required"). | | Auth rejection | Not probed — would require a real or deliberately-invalid API key, i.e. a credential, which this onboarding pass never created. | | Tool calling | Documented as an accepted parameter (`tools`, "Tool/function definitions") on the Chat Completions reference page; no worked example, no live call. | | Structured output | **Not documented anywhere** in Hyper's API docs — `response_format` never appears. | | Streaming + tools combo | Not documented and not probed — `toolsWithStreaming` is `false` pending verification. | | Live capability sweep | Not run. `evidence.liveMatrix` is `null`. | Two documented inconsistencies were found and are flagged rather than silently resolved: - The 401 error body shown on Hyper's Authentication page (`type: "invalid_request_error"`) disagrees with the error-type table on the Chat Completions page, which maps HTTP 401 to `authentication_error`. The catalog's `errorRules` entry matches on the message text (`"invalid api key"`, case-insensitive) rather than on either `type` value, so it doesn't depend on resolving the disagreement. - Hyper's marketing models page (`docs/models.html`) lists "DeepSeek V4 Flash and GLM 5.1" as supporting attachments, but the live `/v1/models` roster reports `deepseek-v4-flash` as `vision: false` and has no `glm-5.1` model at all. The catalog trusts the live roster's `capabilities.vision` field over the marketing copy. --- ## Troubleshooting | Symptom | Cause | Fix | | -------------------------------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | | `Invalid Charm Hyper API key` | `CHARM_HYPER_API_KEY` unset, wrong, or missing the `sk-hyper-` prefix | Check the key in the Hyper Dashboard at https://hyper.charm.land | | Model not found | The roster changed since 2026-09-28 | Pick a current id from the unauthenticated `GET /v1/models` roster | | Structured output silently unavailable | `structuredOutput` is `false` — Hyper's docs never mention `response_format` | Use `generate()` without `schema`, or verify support live before relying on it | | Unsure if tool calls stream correctly | `toolsWithStreaming` is `false` — never documented or probed | Test with `stream: false` first, or run the live matrix before depending on streamed tool calls | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration, and what live verification still needs to happen - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Chutes Provider Guide # Chutes Provider Guide Chutes is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/chutes.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status: docs- and roster-verified, not yet live-verified.** > This entry was onboarded credential-free — every fact below comes from an > unauthenticated `GET /v1/models` call and Chutes' own public docs/pricing > pages, never from a request made with an API key. No `POST` request of any > kind was sent to Chutes. That means capability flags (tools, structured > output, vision), error-message shapes and the billing policy are the > vendor's own documentation, not a NeuroLink live probe — see > [Verification status](#verification-status) below, and re-run the > live-verification steps in > [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) > with a real key before relying on this provider for anything that needs > proven behavior (e.g. `structuredOutputWithTools`, which is left `false` > here specifically because no combined tools+schema probe was possible). ## Quick Start ### 1. Get an API key 1. Visit: https://chutes.ai/signup and create an account (pick a username; sign up with Google, GitHub, or optionally link a Bittensor wallet — no card is asked for on this page) 2. Manage billing and create API keys at https://api.chutes.ai (account/billing/API-key management is a separate host from the inference API) 3. Review current token pricing at https://chutes.ai/pricing before making requests — pay-as-you-go per token (USD per 1M tokens) plus optional paid Plus/Pro plans; no free trial credits are documented, so budget for a funded account from the first call 4. Set `CHUTES_API_KEY` in your .env file — keys are issued with a `cpk_` prefix and must be sent as `Authorization: Bearer CHUTES_API_KEY` ### 2. Configure ```bash export CHUTES_API_KEY=cpk_your-api-key export CHUTES_MODEL=moonshotai/Kimi-K2.6-TEE # optional — overrides the default model export CHUTES_BASE_URL=https://llm.chutes.ai/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "chutes", model: "moonshotai/Kimi-K2.6-TEE", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider chutes ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "chutes", credentials: { chutes: { apiKey: process.env.CHUTES_API_KEY } }, }); ``` --- ## Models All context/output figures and pricing below are read directly from the vendor's own unauthenticated `GET https://llm.chutes.ai/v1/models` response (re-run 2026-09-28, HTTP 200, 14 models) — never invented. Where a field was absent from that response (two entries below), it is left blank rather than guessed. | Model | Context | Max output | Vision | $/M in · out (cached in) | Notes | | ---------------------------------------- | --------- | ---------- | ------------------ | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `moonshotai/Kimi-K2.6-TEE` ⭐ | 262,144 | 65,535 | yes (image, video) | $0.50 / $2.85 ($0.05) | Default — the model in Chutes' own homepage `chat/completions` code sample. `json_mode`, `structured_outputs`, `tools`, `reasoning` documented. | | `moonshotai/Kimi-K3-TEE` | 1,048,576 | 65,535 | yes (image, video) | $3.00 / $15.00 ($0.30) | Largest context window in the roster; same documented feature set as the default; fallback. | | `deepseek-ai/DeepSeek-V4-Flash-0731-TEE` | 1,048,576 | 131,072 | no | $0.44 / $1.32 ($0.044) | Largest documented max output in the roster; text-only; fallback. | | `zai-org/GLM-5.2-TEE` | 1,048,576 | 65,535 | no | $1.25 / $3.95 ($0.125) | Text-only; fallback. | | `Qwen/Qwen3.5-397B-A17B-TEE` | 262,144 | 65,536 | yes (image) | $0.45 / $3.00 ($0.045) | MoE model; fallback. | | `Qwen/Qwen3.6-27B-TEE` | 262,144 | 65,536 | yes (image) | $0.30 / $2.00 ($0.03) | Fallback. | | `Qwen/Qwen3.8-27B-TEE` | 262,144 | 65,536 | yes (image) | $0.24 / $2.20 ($0.024) | Fallback. | | `Qwen/Qwen3-235B-A22B-Thinking-2507-TEE` | 262,144 | 262,144 | no | $0.2989 / $1.1957 ($0.0299) | Reasoning-focused variant; max output equals the full context window, so give it a generous token budget. | | `deepseek-ai/DeepSeek-V3.2-TEE` | 131,072 | 65,536 | no | $1.00 / $1.00 ($0.10) | Fallback. | | `zai-org/GLM-5.1-TEE` | 202,752 | 65,535 | no | $0.98 / $3.08 ($0.098) | Prior GLM generation; fallback. | | `google/gemma-4-31B-turbo-TEE` | 131,072 | 65,536 | yes (image) | $0.12 / $0.37 ($0.012) | Roster reports a larger 262,144 `max_model_len`; `context_length` (131,072) is used as the documented context window. | | `Qwen/Qwen3-32B-TEE` | 40,960 | 40,960 | no | $0.104 / $0.416 ($0.0104) | Smallest context window in the roster; fallback. | | `unsloth/Mistral-Nemo-Instruct-2407-TEE` | — | — | no | $0.0245 / $0.0978 ($0.0024) | Cheapest model in the roster; only `max_model_len` (131,072) is documented — context/output/vision/feature fields are absent, so they're left blank here rather than guessed. | | `Nemotron-3-Nano-Omni-30B-TEE` | — | — | no | $0.0245 / $0.0978 ($0.0024) | Same undocumented-field pattern as Mistral Nemo above. The "Omni" name suggests multimodal support, but nothing in the public roster confirms it, so vision is left `false` rather than inferred from the name. | Context window shown is the catalog default of 262,144 tokens (the default model's own context window); the default max output is 65,535 tokens (`moonshotai/Kimi-K2.6-TEE`'s documented `max_output_length`). **Fallback order** when the default is unavailable: `moonshotai/Kimi-K3-TEE` → `deepseek-ai/DeepSeek-V4-Flash-0731-TEE` → `zai-org/GLM-5.2-TEE` → `Qwen/Qwen3.5-397B-A17B-TEE` → `Qwen/Qwen3.6-27B-TEE` → `Qwen/Qwen3.8-27B-TEE` → `Qwen/Qwen3-235B-A22B-Thinking-2507-TEE` → `deepseek-ai/DeepSeek-V3.2-TEE` → `zai-org/GLM-5.1-TEE` → `google/gemma-4-31B-turbo-TEE` → `Qwen/Qwen3-32B-TEE` → `unsloth/Mistral-Nemo-Instruct-2407-TEE` → `Nemotron-3-Nano-Omni-30B-TEE`. --- ## Billing Chutes' [pricing page](https://chutes.ai/pricing) shows pay-as-you-go token pricing ("No subscription, no minimum, no markup") plus two optional paid plans (Plus at $10/mo, Pro at $20/mo, each bundling a daily quota and a discount off PAYG rates), an Enterprise tier, and a per-second-billed "Private Chutes" dedicated-GPU option. A Bittensor-wallet TAO payment option is also offered alongside standard payment. The page's own FAQ asks **"Is there a free trial?"**, but that answer was collapsed in every fetch of the page during this onboarding and could not be confirmed either way — nor does any other public page state that new accounts receive free credits. Signup itself (https://chutes.ai/signup) does not ask for a card, but that is not the same as confirming free usage. Given the absence of documented free credits, `billingPolicy` is recorded conservatively as `no-free-tier`. Treat this as unconfirmed rather than a claim that no free tier exists — verify directly in the Chutes console before onboarding a team on the assumption of either outcome. --- ## Verification status Tier-2 onboarding normally requires a live-key capability sweep (`docs/provider-integration/tiers/tier-2-catalog-entry.md`, "Live verification"), gated by `pnpm run verify:provider-onboarding`. This entry was added under a **credential-free** onboarding pass instead: no Chutes API key was ever created or used, and no authenticated or `POST` request was sent to any Chutes endpoint. Everything below is either a public document or a single unauthenticated `GET`. | Probe | Result | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Roster | Unauthenticated `GET https://llm.chutes.ai/v1/models`, HTTP 200, 14 models, re-run 2026-09-28. `/v1/models` is itself documented by Chutes as a "public catalog (no key required)." | | Wire shape | Chutes' own homepage Python sample posts to `https://llm.chutes.ai/v1/chat/completions` with `model` + `messages` + `Authorization: Bearer $CHUTES_API_KEY` + `stream: true` — never executed here, only read. | | Tools / structured output | Confirmed from docs only: the "Function Calling, Agents, and Tool Use" guide shows OpenAI-shaped `tools`/`tool_choice`/`tool_call_id`, and the same guide shows a separate `response_format: {"type": "json_object"}` JSON-mode example. No request combining both was found or attempted. | | Auth failure shape | Not probed (would require a `POST`, which credential-free onboarding forbids) and not given verbatim in the docs, so `errorRules` is empty — NeuroLink's default error classifier handles this provider until a live probe supplies a documented shape. | | Live capability matrix | **Not run.** `evidence.liveMatrix` is `null`. Run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=chutes` with a real `CHUTES_API_KEY` before depending on this provider for tool calling, structured output, or vision in production. | --- ## Troubleshooting | Symptom | Cause | Fix | | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | Requests hit an anonymous rate limit (HTTP 429) | No token, or an invalid token, was sent | Set `CHUTES_API_KEY`, and send it as `Authorization: Bearer ` — `X-API-Key` is documented as unsupported for inference calls | | Model not found | The roster changed since 2026-09-28 | Pick a current id from the unauthenticated `GET /v1/models` roster | | Structured output silently dropped when tools are used | `structuredOutputWithTools` is `false` — no combined probe was possible | This is intentional pending a live-key check, not a bug; NeuroLink's runtime conflict retry drops structured output and retries rather than losing the turn | | Unsure whether a specific model supports tools / JSON mode | `capabilities.tools` is `"model-dependent"` — two roster ids ship no `supported_features` at all | Check the model's entry in `GET /v1/models`, or consult the [Models](#models) table above | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration, and what live verification still needs to happen - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Cloudflare Clef Provider Guide # Cloudflare Clef Provider Guide **A provider of `decide`** — the same typed `boolean` / `choice` / `score` answers as [TypeSafe's Jev](/docs/getting-started/providers/typesafe), [Laya](/docs/getting-started/providers/laya), [XOR](/docs/getting-started/providers/xor), [SubQ](/docs/getting-started/providers/subq), [Perplexity](/docs/getting-started/providers/perplexity-decider), [OpenAI Decisions](/docs/getting-started/providers/openai-decisions) and [ScaleDown](/docs/getting-started/providers/scaledown), from Cloudflare's Clef models on Workers AI, and it also reads images. It emits no text at all. > This is not the [Cloudflare Workers AI text provider](/docs/getting-started/providers/cloudflare) > (`cloudflare`, which runs chat models). The two are separate providers that > read the same `CLOUDFLARE_API_KEY` and `CLOUDFLARE_ACCOUNT_ID`; see > [One token, two providers](#one-token-two-providers). > **Read [Limits](#limits) before you rely on it.** Workers AI's state window > changed in October 2026 (hosted service or model: unknown). Until 2026-10-04 it > read only about the first 2,048 tokens of the state, far less than the 64K > context Cloudflare documents, and ignored the rest without an error; on > 2026-10-07 it read states of at least 190,153 tokens (`clef-flash`) and 52,154 > (`clef`). NeuroLink refuses a state it estimates at more than 16,000 tokens, > inside what was read in full, and a longer wait than a fail-open feature can > afford. ## Overview Clef is a decision model: it reads a state and a set of typed questions and returns a probability for every allowed answer, with no free-form text and no reasoning tokens to wait for. Cloudflare publishes two sizes, `clef` (27B) and `clef-flash` (9B), and says it is releasing their weights under the Apache 2.0 license. Both answered in about a second from a developer machine. Cloudflare's pages call them available, and do not say whether they are generally available or in beta. ### Key Facts | | | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Provider id | `cloudflare-clef` | | Models | `clef` (27B, the default) and `clef-flash` (9B). `@cf/cloudflare/clef` and `@cf/cloudflare/clef-flash` are accepted too | | Question types | `boolean` (sent as `noul`), `choice` (2 to 255 options), `score` (2 to 10 levels) | | Questions per request | 64 | | Images | up to 4 per request: PNG, JPEG or WebP. No video | | State | read in full up to at least 190,153 tokens (`clef-flash`) and 52,154 (`clef`) on 2026-10-07; about 2,048 until 2026-10-04. NeuroLink refuses a state it estimates at more than 16,000 | | Request size | 256,000 bytes in NeuroLink, base64 image data included; the text alone is held to 195,584 characters on `clef-flash` | | Endpoint | `https://api.cloudflare.com/client/v4/accounts//ai/run/@cf/cloudflare/` | | Credentials | an API token with Workers AI permission, and the account id | | Price | $0.24 per million input tokens for `clef`, $0.09 for `clef-flash`; no output price is listed (Cloudflare's Workers AI pricing page) | | Measured latency | 2026-10-03: 0.3 to 1.0 s for a small request; 64 questions: 1.1 s (`clef-flash`), 1.3 s (`clef`); 2026-10-04: 1.5 s / 2.3 s | | Default decide provider | sixth of eight: after TypeSafe, Laya, XOR, SubQ and Perplexity, before OpenAI Decisions and ScaleDown | | Verified live | 2026-10-03 and 2026-10-04, with a real account (see [Limits](#limits)) | ## Quick Start ### 1. Get a token and your account id Create an API token with the **Workers AI: Read + Write** permission at [dash.cloudflare.com/profile/api-tokens](https://dash.cloudflare.com/profile/api-tokens), and copy your account id from the dashboard URL or the "Account ID" panel. ### 2. Configure ```bash export CLOUDFLARE_API_KEY=your-workers-ai-token export CLOUDFLARE_ACCOUNT_ID=your-account-id # Optional export CLOUDFLARE_CLEF_MODEL=clef-flash # default: clef export CLOUDFLARE_CLEF_BASE_URL=https://api.cloudflare.com/client/v4 # default ``` The base URL must be `https://`; `http://` is accepted only for `localhost`, `127.0.0.1` and `[::1]`, because every request carries the token. Or pass them in code, which wins over the environment: ```typescript const neurolink = new NeuroLink({ credentials: { cloudflareClef: { apiKey: "…", accountId: "…" }, // baseURL is optional }, }); ``` Both the token and the account id are needed: the account id is part of the route, so a token alone does not count as configured. ### 3. Use it ```typescript const result = await neurolink.decide({ provider: "cloudflare-clef", state: "Checkout has been failing for every customer for the last hour.", questions: { urgent: { type: "boolean", instructions: "Is this support request urgent?", }, team: { type: "choice", instructions: "Which team should handle this request?", criteria: { billing: "Payments, invoices, and refunds", technical: "Outages, errors, and configuration", sales: "Plans and upgrades", }, }, severity: { type: "score", instructions: "How severe is the customer impact?", criteria: ["No impact", "Minor", "Major", "Critical"], }, }, }); result.answers.urgent; // { type: "boolean", probability: 0.99 } result.answers.team; // { type: "choice", choice: "technical", probabilities: {…}, confidence: 0.53 } result.answers.severity; // { type: "score", score: 2.96, legend: {…}, probabilities: {…}, confidence: 0.92 } ``` The figures in the comments are what a live call to `clef` returned for this example on 2026-10-03, rounded; `clef-flash` answered the same example with 0.96, 0.82 and 0.50, 2.72. Pick the faster model for one call with `model: "clef-flash"`. ### From the CLI ```bash neurolink decide "Checkout has been failing for every customer for the last hour." \ --provider cloudflare-clef \ --questions '{"urgent":{"type":"boolean","instructions":"Is this support request urgent?"}}' ``` ## Images Pass up to four images beside the state, as a Buffer, a file path or a `data:image/…;base64,` URL; an `http(s)` URL is refused. PNG, JPEG and WebP are read; `image/jpg` is accepted as a JPEG alias and sent as `image/jpeg`. Other formats are refused before they are sent. ```typescript await neurolink.decide({ provider: "cloudflare-clef", state: "Look at the attached image.", images: ["./photo.png"], questions: { color: { type: "choice", instructions: "What colour is the image?", criteria: { red: "red", blue: "blue" }, }, }, }); ``` - **They travel in their own `images` array**, not inside the state. Cloudflare places them before the state. - **The Workers AI API accepts no video.** Its model page says it does, but the API refuses a video and has no field for one, so NeuroLink refuses a `video` too. - **Pixels:** Cloudflare documents 16 megapixels an image. 16.00 megapixels were accepted (4096 × 3900 at 15.97 MP, 8000 × 2000 and 16000 × 1000 at 16.00 MP); 16.38 megapixels (4096 × 4000) were refused with a 422. The limit is on the pixel count, not on either side. - **Cost:** an image costs at most about 1,000 input tokens however large it is. A test request with one 512 × 512 image counted 389 input tokens in all, one with a 1,024 × 1,024 image counted 1,157, and larger images up to the pixel limit counted between 1,125 and 1,157. - **How many:** exactly four tiny PNG/JPEG/WebP images succeeded on both models on 2026-10-04; a fifth was refused with a 422. Four is also NeuroLink's limit. - **NeuroLink's size limit is 256,000 bytes** for the encoded request body, including base64 image data. A 195 KB PNG encodes to about 260,000 characters and is refused locally. **Resize or compress a photo to well under 190 KB first.** The 2026-10-03 API probe accepted a 195 KB PNG and refused a 202 KB one. That boundary has since moved: on 2026-10-05 both models accepted PNG requests with encoded bodies up to 492,485 bytes and refused 532,505 bytes (`clef-flash`) and 532,499 (`clef`) (see below), so the 195/202 KB figures are historical and NeuroLink's cap is the stricter limit. ## When NeuroLink uses it Built-in features that call `decide()` pick the first decision provider that is configured, in this order: TypeSafe, Laya, XOR, [SubQ](/docs/getting-started/providers/subq), Perplexity, Clef, [OpenAI Decisions](/docs/getting-started/providers/openai-decisions), then [ScaleDown](/docs/getting-started/providers/scaledown). A host with none of the first five, but with `CLOUDFLARE_API_KEY` and `CLOUDFLARE_ACCOUNT_ID` set for the Workers AI text provider, therefore has Clef as its default decision provider. Naming `provider: "cloudflare-clef"` reaches it whatever else is configured. Because of the state limit below, a built-in feature whose state is longer than about 16,000 estimated tokens (about 60,000 characters of prose) gets a refusal from Clef, which each of them treats as "carry on as before". Clef suits short decisions: routing a request, a guardrail on one action, classifying one message or one picture. ## What is sent to Cloudflare ```json POST https://api.cloudflare.com/client/v4/accounts//ai/run/@cf/cloudflare/clef Authorization: Bearer { "model": "clef", "state": "Checkout has been failing for every customer for the last hour.", "questions": { "urgent": { "type": "noul", "instructions": "Is this support request urgent?" } }, "images": ["data:image/png;base64,…"] } ``` `boolean` is the SDK's name for the wire's `noul`. `model` is sent although the path already names it: Cloudflare's schema marks it required, and a body whose `model` differs from the path is refused. A request with no `model` was accepted live and answered by `clef-flash`, so sending it matters only for following the schema. Cloudflare wraps every answer in its own envelope, and NeuroLink reads the answers out of it: ```json { "result": { "model": "clef", "answers": { "urgent": { "type": "noul", "noul": 0.9551 } }, "usage": { "input_tokens": 346, "output_tokens": 0 } }, "success": true, "errors": [], "messages": [] } ``` The request id is the `cf-ai-req-id` response header; where that is absent (a rejected token never reaches the model) it is the edge's `cf-ray`. ## One token, two providers `cloudflare-clef` and `cloudflare` read the same two variables, but each has its own credentials slice, so the two cannot be mixed up: | | `cloudflare` (text) | `cloudflare-clef` (decide) | | --------------- | --------------------------- | ---------------------------- | | Token | `CLOUDFLARE_API_KEY` | `CLOUDFLARE_API_KEY` | | Account id | `CLOUDFLARE_ACCOUNT_ID` | `CLOUDFLARE_ACCOUNT_ID` | | SDK credentials | `credentials.cloudflare` | `credentials.cloudflareClef` | | Serves | `generate()` and `stream()` | `decide()` only | `credentials.cloudflare` does **not** configure `decide`. Setting the two variables for the text provider also lets `decide()` use Clef when no other decision provider is configured, and no switch turns that off while the two variables are set in the environment. A host that wants the Workers AI text provider without Clef can give the text provider its token and account id only through `credentials.cloudflare`, and leave the environment variables unset. ## Limits ### Measured on a real account, October 2026 The Workers AI endpoint ignored text past about 2,048 tokens until 2026-10-04, far below Cloudflare's documented 64K context, and read far more on 2026-10-07 (hosted service or model: unknown). Request-size refusals also changed between two measurement dates. The original measurements were on 2026-10-03; the bounded follow-up campaign used 133 probe calls on 2026-10-04, with one request at a time. **Which model:** on both `clef-flash` and `clef`, the follow-up still read the fact at the 2026-10-03 `clef-flash` lower bound for logs, number lists, digit arrays and compact JSON, and did not read it 2.5% to 3.1% further on. English prose and random CJK had already matched on both models. It also checked the question count, pixel and four/five-image boundaries on both models, the id, option, score-level and PNG/JPEG/WebP boundaries on `clef`, and the `image/jpg` case on both models. Natural-script prose was measured on `clef`; a reworked many-key object probe matched on both. TypeScript, minified JSON and synthetic Devanagari/emoji cuts remain 9B-only measurements. Historical latency, billing and burst figures retain their dates. | Limit | Documented | Measured | | ------------------ | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | State | a 65,536-token context window; the schema adds that long text "is truncated to fit the model's token limit" | **2026-10-03 and 2026-10-04: text past about 2,048 tokens ignored without an error. 2026-10-07: states of at least 190,153 tokens (`clef-flash`) and 52,154 (`clef`) read in full. Hosted service or model: unknown** | | Request size | 4 MiB an image, 8 MiB in all, 13 MiB for the body | 2026-10-04, both models: 520,000 text characters accepted, 525,000 refused with 413/code 5021; NeuroLink retains its 256,000-byte cap; 2026-10-24: images not counted (below) | | Questions | 1 to 64 | 64 sent, the 65th refused with a 422 | | Question ids | letters, digits, `_`, `.`, `-`, up to 100 | the same; 101 characters and a space refused | | Options and levels | 2 to 255 options, 2 to 10 levels | the same; 256 and 11 refused | | Images | up to 4, 16 megapixels each | 4 tiny images accepted, 5 refused; PNG/JPEG/WebP and image/jpg accepted; 16.00 MP accepted, 16.38 MP refused on both models | | Video | the model page says it reads video | refused: no field, and not accepted in `images` | | Rate | not documented on the model page; the pricing page links a limits page and a free allowance of 10,000 neurons a day | 60 requests sent at once: 56 answered, 4 refused with a 429 | **The state window (2026-10-03 and 2026-10-04; see [the change of 2026-10-07](#the-state-window-changed-on-2026-10-07)).** A fact placed past about 2,048 tokens of state was ignored (a 75-character sentence repeated for 60,000 characters: the fact was used at 10,500 characters and ignored from 12,000), a question about the end of a long text was answered from its beginning, and the reported input tokens stayed at about 2,190 for any longer text, which is also what is billed. The cut falls at a different character count for each kind of text. The first five rows are real text; the last three are **synthetic**, built from cycled code points, so natural text in those scripts may tokenise differently: | Text | Characters before the cut | Per token | | ------------------------------------------ | ------------------------- | -------------------------------------- | | English prose (Cloudflare's launch post) | 7,517 | 3.7 characters | | TypeScript (this repository's providers) | 8,768 | 4.3 characters | | Minified JSON (a documentation index) | 9,900 | 4.8 characters | | Log lines (generated) | 2,863 | 1.4 characters | | A list of numbers (generated) | 2,040 | 1.0 characters (each digit is a token) | | A JSON array of single digits (generated) | 2,043 | 1.0 characters (commas count as well) | | Four-digit numbers, space separated | 2,039 | 1.0 characters | | Records as an object array or compact JSON | 5,141 (97 records) | 2.5 characters | | The same records, pretty-printed JSON text | 4,055 (49 records) | 2.0 characters | | Random CJK ideographs (synthetic) | 1,170 | 1.75 tokens a character | | Cycled Devanagari (synthetic) | 1,791 | 1.14 tokens a character | | Cycled emoji (synthetic) | 707 | 2.9 tokens a character | An array of records passed as `state` was cut at the same place as compact JSON text. On both models, the follow-up still read the fact at the 2026-10-03 `clef-flash` lower bound and did not read it 2.5% to 3.1% further on: 2,863–2,935 characters for logs, 2,040–2,091 for number lists, 2,043–2,095 for digit arrays, and 97–100 records for compact JSON. These two-point checks do not establish exact tokenizer boundaries. The many-key object control failed three times, then passed after an explicit field-name question and zero-padded keys were introduced together. On both models the hidden field stopped being read between 128 and 134 preceding keys. The lower bound is 4,883 characters of compact JSON and 2,299 tokens from the provider's estimator. This verifies the tested object shape; it does not establish that every structured state is serialized identically by Workers AI. Natural samples were composed as about 3,000 code points of ordinary prose and repeated to 12,000 to find a cut. The intervals below are on `clef` (27B); the estimate is evaluated at the lower, still-visible bound. | Sample | Characters before cut, lower–upper | NeuroLink estimate at lower bound | | ------------------------------- | ---------------------------------- | --------------------------------- | | Chinese prose | 3,749–4,499 | 5,584 | | Japanese prose | 3,749–4,499 | 5,588 | | Korean prose | 4,499–5,249 | 5,309 | | Hindi prose | 2,999–3,749 | 3,751 | | Emoji-rich English conversation | 5,249–5,999 | 2,396 | All exceeded 1,500 estimated tokens, the limit at the time, before the observed cut, so no estimator rate changed then. The mixed emoji conversation is not a measurement of every emoji or multi-code-point sequence. **The request size changed.** On 2026-10-03, `clef-flash` accepted 262,000 text characters and refused 270,000; a 195 KB PNG was accepted and a 202 KB one refused. The 250,000-character request was first tested on 2026-10-04. On that date both models accepted 270,000, 500,000, 510,000 and 520,000 text characters, then refused 525,000, 530,000 and 1,000,000 with 413/code 5021. The refusal estimate is the encoded body bytes / 4: it equals that figure rounded up in seven of the eight refusals measured on 2026-10-04 and 2026-10-05, and is one lower in the eighth (a 532,505-byte body gave 133,126). What changed was the refusal threshold: on 2026-10-03, `clef-flash` accepted an estimate of 65,527 and refused 67,527; on 2026-10-04, both models accepted 130,026 (`clef`) / 130,027 (`clef-flash`) and refused 131,276 / 131,277. The error still prints a 65,536-token context. **Inference:** the new interval contains 131,072, twice the printed figure; the reason is unknown. The observed text ceiling is between 520,000 and 525,000 characters, not a stable API guarantee. **Images, 2026-10-05.** The image boundary was measured with one request at a time and incompressible PNGs. `clef-flash` accepted bodies of 252,365, 268,377, 400,441 and 492,485 bytes (one image of about 190, 202, 300 and 370 KB) and refused 532,505 bytes (about 400 KB) with 413/code 5021, estimate 133,126. `clef` accepted a 300 KB image (400,435 bytes) and four 75 KB images together (400,758 bytes), and refused the 400 KB image (532,499 bytes, estimate 133,125). Text and images therefore reach a refusal at about the same body size, between 520,108 and 525,102 bytes for text and between 492,485 and 532,499 for images. **Inference:** both intervals contain 524,288 bytes (131,072 x 4); the reason the limit moved is unknown. **Located on 2026-10-23.** For a plain-text body, Cloudflare refuses with 413/code 5021 exactly when the estimate (the body's characters / 4, which for these ASCII bodies is bytes / 4) exceeds twice the context window its message prints, and with 422/code 3030 ("Request requires N tokens; the maximum is M") when the real token count exceeds the window. `clef`'s message prints a window of 65,536 tokens (its real-token maximum is 65,529), so its 5021 edge is 524,288 bytes: bodies of 524,284 and 524,288 bytes got 422, those of 524,292 and 524,296 got 5021. `clef-flash`'s window had fallen to 24,576 tokens (the date is unknown), so its edge is 196,608 bytes: 196,604 and 196,608 got 422, 196,612 and 196,616 got 5021. With text of about 5.5 characters a token, `clef-flash` refuses above about 136,000 characters (136,250 accepted, 136,875 refused, 422); "a" x N, 8 characters a token, is accepted up to 195,118 characters. These bodies were plain text sent raw to the service. The byte rule is not what the service applies to a request with an image: live case 19.14 sends an image body of about 253 KB through NeuroLink to `clef-flash`, more than its 196,608 bytes, and the question is answered (it passed on 2026-10-20, 2026-10-22 and 2026-10-23). The images are not counted; what is counted is under [What the 413 counts](#what-the-413-counts). NeuroLink keeps the 256,000-byte encoded-body cap. For images it remains far below what the service takes, because the images are not counted (see the next section). For text it does not: `clef-flash`'s text edge is 196,608 characters and `clef`'s 524,288, so the text is checked on its own, per model. Live case 19.14 sends an image request just under the cap through NeuroLink; live canaries 19.11 and 19.11b check the text-only service ceiling on `clef-flash` and `clef`. ### What the 413 counts The paragraph above gives the edges for plain text. What the estimate is made of was measured on 2026-10-23 and 2026-10-24, one request at a time and with the daily allocation spent. That does not hide the size gate: it answers 413 before the allocation check answers 429/code 4006, so a 413 means refused by the gate and a 429 means the request passed it (these probes read no answer). - **The estimate is the characters of the request's JSON without its `images` array** (the key included), over four, rounded half up. A text of 196,609 characters got 429 on `clef-flash` and 196,610 got 5021 (estimate 49,153; twice 24,576 is 49,152); on `clef`, 524,288 got 429 and 524,292 got 5021. - **The images are not in it.** Bodies of 396,820 and 517,199 bytes (one and four images, the text at the edge) and 632,380 and 1,168,636 bytes (one image of about 0.5 and 1.1 MB, a text of 100,000 characters) got 429 on `clef-flash`, not 5021, while a text of 196,612 characters got 5021 with the same 200 KB image beside it. That was an inference from the order of the two refusals, made with the allocation spent. Once it was restored (2026-10-24) the answers were read: image bodies of 196,616 bytes (8 over the text edge) and 1,168,636 bytes on `clef-flash`, and of 524,292 and 724,504 bytes on `clef` (one image each and a short text), got HTTP 200 with 258, 906, 749 and 825 input tokens; the status and the token counts were read, not the content of the answers. Live case 19.14, which sends about 253 KB with an image, is answered. On 2026-10-05 the estimate was the whole body over four (133,126 for 532,505 bytes); it no longer is. - **It counts characters, not bytes.** 98,252 "é" (196,612 bytes in UTF-8) got 429; 98,252 newlines, which JSON writes as two characters each, got 5021. NeuroLink therefore holds the text of a Clef request (the body without `images`) to 195,584 characters on `clef-flash` and 523,264 on `clef`, which is eight characters per window token less 1,024, and refuses more locally as `max_tokens_exceeded`, the kind Cloudflare's own 413 gets. A model it does not know has no such limit. Reaching it takes a text that its state limit above does not allow except through the questions or control characters, which JSON writes as up to six characters each. ### The state window changed on 2026-10-07 > **The window described above no longer applies.** On 2026-10-07 the Workers AI > endpoint read the whole state. This section records what was measured; the > numbers above stay as the record of 2026-10-03 and 2026-10-04. Measured with one request at a time between 07:24 and 08:12 UTC, with a fact placed at the end of the state (the part a cut would drop) and the question "what colour does the text say the vault code is?". A fact counts as read when the answer's probability for its colour is at least 0.8. | State | Model | Characters | Input tokens billed | Fact read (probability) | Time | | --------------------------------- | ------------ | ---------- | ------------------- | ----------------------- | ------ | | Prose, fact at 55,000 | `clef-flash` | 60,032 | 10,555 | yes (0.980) | 0.8 s | | Prose, fact at 55,000 | `clef` | 60,032 | 10,555 | yes (0.996) | 2.0 s | | Prose, no fact (control) | `clef-flash` | 60,000 | 10,547 | no (0.297) | 1.1 s | | Prose, no fact (control) | `clef` | 60,000 | 10,547 | no (0.170) | 2.0 s | | Prose, fact at 200,000 | `clef-flash` | 240,032 | 41,755 | yes (0.978) | 3.0 s | | Prose, fact at the end | `clef-flash` | 300,031 | 52,154 | yes (0.984) | 4.9 s | | Prose, fact at the end | `clef` | 300,031 | 52,154 | yes (0.996) | 11.8 s | | Prose, fact at the end | `clef-flash` | 500,031 | 86,819 | yes (0.985) | 19.2 s | | JSON array of digits, fact at end | `clef-flash` | 115,031 | 115,153 | yes (0.986) | 11.3 s | | JSON array of digits, fact at end | `clef-flash` | 158,031 | 158,153 | yes (0.987) | 30.9 s | | JSON array of digits, fact at end | `clef-flash` | 190,031 | 190,153 | yes (0.986) | 39.0 s | | JSON array of digits, fact at end | `clef` | 190,031 | none | HTTP 529, code 5012 | 15.2 s | The billed input tokens now follow the text (on 2026-10-03 and 2026-10-04 they stayed at about 2,190 for any longer state), and the largest states tried on `clef-flash` were read in full: no upper bound was found below 190,153 tokens, past the 65,536-token context the model page documents. The `clef` (27B) model read a 52,154-token state, and answered **HTTP 529, code 5012, "Clef inference failed"** after 15 s for the 190,153-token array; it was not tried between those sizes. That 529 is the first server-side error seen from this API. Latency grows with the input: 1.7 to 1.9 s for 20,954 tokens on `clef-flash`, about 0.2 s per 1,000 input tokens from 50,000 tokens up on both models (11.8 s for 52,154 tokens on `clef`), and the first request after a pause can be much slower (19.7 s for 30,153 tokens). Another session reported, from its own saved benchmark, that `clef` answered 22 of 2,000 short questions differently on 2026-10-07 than on 2026-10-05; that was not verified here. This is one day of data, from a service whose behaviour changed between 2026-10-03, 2026-10-04, 2026-10-05 and 2026-10-07. Cloudflare was not asked why. NeuroLink's local state limit was raised in response, from 1,500 to 16,000 estimated tokens (see [What NeuroLink refuses before any request](#what-neurolink-refuses-before-any-request)). ### What NeuroLink refuses before any request | Refused | Limit | Error kind | | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------- | | A state estimated over 16,000 tokens | digits 1 token each, punctuation 0.75, emoji 3, other non-ASCII text 1.5, letters about 4 characters a token | `max_tokens_exceeded` | | More than 64 questions in one `decide()` | 64 | `max_tokens_exceeded` | | A request body over 256,000 bytes | 256,000 | `invalid_request` | | `clef-flash`: text without images over 195,584 characters | 195,584 (`clef`: 523,264) | `max_tokens_exceeded` | | More than 4 images, a video, or a format other than PNG, JPEG or WebP | | `invalid_request` | | A model name that is not a plain name, such as `clef/../x` | | `invalid_request` | | A missing token or account id, or a base URL that cannot work | | `authentication` or `invalid_request` | `NeuroLink.tryDecide()`, which every built-in feature calls, splits a question map at 64 and runs up to four batches at once, so only a direct `decide()` meets the 64-question refusal. **Why 16,000.** The limit is an estimate in NeuroLink's own tokens, not the model's. Until 2026-10-04 it was 1,500, chosen so that the estimate reached it before the endpoint ignored the rest of the state. On 2026-10-07 the endpoint read far more, and the limit became 16,000 estimated tokens for two reasons: - It stays well inside what was read in full. The estimate runs 35% over the real token count for English prose (60,032 characters estimated 16,150 and billed 10,555) and 14% under it for a JSON array of digits, whose commas cost a token each (190,031 characters estimated 166,260 and billed 190,153), so the limit is at most about 18,400 real tokens, 2.8 times fewer than the 52,154 `clef` read in full. Punctuation is charged 0.75 and emoji 3 because the tokenizer counts them that way; the rates now approximate real tokens and no longer stand for a cut. - It bounds the wait. Large states took about 0.2 s per 1,000 input tokens on both models, so the default timeout is the 5 s allowance plus 250 ms for each full 1,000 estimated tokens: 9 s at the limit. A fail-open feature that waits on Clef is held no longer than that. A state of ordinary prose is refused at about 60,000 characters. The service changed several times in a few days, so live canaries 19.10 and 19.10b read a fact at the end of a state just under this limit on both models and fail if the service stops reading below it; the other estimates are measurements for the samples described above, not a guarantee for every script or emoji sequence. ### What is not verified - The status Cloudflare returns for a token without Workers AI permission. No such token was available. A 403 is treated as an ordinary `invalid_request`, not `authentication`, so that if it does mean a missing permission, fixing it in the dashboard works at once, without restarting the process. - Any 5xx other than one 529. Cloudflare answered a single server error, HTTP 529 with code 5012 ("Clef inference failed"), to a 190,153-token state on `clef` on 2026-10-07; the retry and classification of 500, 502, 503 and 504 rest on ordinary HTTP conventions. - What a Workers Paid account that has run out of credit gets. Only the Free plan's daily allocation running out was seen (HTTP 429, code 4006, 2026-10-05); it is not retried. Cloudflare documents a reset at 00:00 UTC, but this account was still refused at 02:38 and 04:12 UTC on 2026-10-06 and answered again at 07:24 UTC on 2026-10-07, so when the allowance returns here is not verified. - The 27B TypeScript, minified-JSON and synthetic Devanagari/emoji cuts; see the model coverage above. - The rate limit. Only a burst of 60 was tried. - Whether Cloudflare's service is generally available or in beta. - Whether the state window (about 2,048 tokens until 2026-10-04, none found by 2026-10-07) and the changing request-size limit belong to the hosted service or to the model itself. The open weights on Hugging Face were not run. - Whether either limit changes again. The live decide suite carries four canary cases that fail with an instruction to re-measure: 19.10 and 19.10b send a prose state and a digit array just under NeuroLink's own limit, with a fact at the very end, to both models, and fail if the service stops reading below that limit; 19.11 and 19.11b check both sides of the text-only request ceiling on `clef-flash` and `clef`. None of them notices a service that reads more than the limit allows. ### Latency and the timeout On 2026-10-03, a small request answered in 0.3 to 1.0 s from a developer machine; 64 questions took 1.1 s on `clef-flash` and 1.3 s on `clef`; the slowest of 60 requests sent at once took 2.2 s. On 2026-10-04, a 64-question request with the same questions and a shorter state took 1.5 s on `clef-flash` and 2.3 s on `clef`. The default timeout is 5 s plus 250 ms for each full 1,000 estimated state tokens (5 s for a short state, 9 s at the 16,000-token limit); on 2026-10-07 large states took about 0.2 s per 1,000 input tokens (1.7 to 1.9 s for 20,954 tokens on `clef-flash`; 11.8 s for 52,154 on `clef`). Pass `timeoutMs` to change it for one call. ## Errors Cloudflare answers with its own envelope, `{ "success": false, "errors": [{ "code", "message" }] }`, and a refusal from the model nests a second envelope, with a trailing request id, inside `message`. NeuroLink flattens both to one line and takes the request id out of the text. | Status | Code | Seen for | Kind | Retried | | ------ | ----- | ----------------------------------------------------------------------------------------- | ----------------------------------- | ------------------------------ | | 401 | 10000 | a token Cloudflare does not know | `authentication` | no; trips the breaker | | 403 | | never seen; a token without Workers AI permission may draw it | `invalid_request` | no; does not trip the breaker | | 400 | 5006 | no questions; an unknown question type | `invalid_request` | no | | 400 | 7000 | a model path that does not exist ("No route for that URI") | `invalid_request` | no | | 400 | 6003 | a body that is not JSON | `invalid_request` | no | | 422 | 5012 | a validation failure: 65 questions, a fifth image, an unknown field, an empty instruction | `invalid_request` | no | | 413 | 5021 | a request past the estimate above | `max_tokens_exceeded` | no | | 429 | 3040 | "Capacity temporarily exceeded"; no `Retry-After` | `rate_limit` | yes, after the default backoff | | 429 | 4006 | "you have used up your daily free allocation of 10,000 neurons"; no `Retry-After` | `rate_limit` | no | | 529 | 5012 | "Clef inference failed", seen once (`clef`, a 190,153-token state, after 15 s) | `server` | yes, once | | 5xx | | any other 5xx: never seen from Cloudflare | `server`, or `overloaded` for a 503 | yes, once | Only a 401 is `authentication`. After one, that provider instance refuses further calls without sending anything; construct a new one with a working token. "Yes" means one retry, after about 250 to 500 ms; the base class retries once. ## Troubleshooting - **"requires the account id"** — set `CLOUDFLARE_ACCOUNT_ID` or `credentials.cloudflareClef.accountId`. - **"The state is ~N tokens; Cloudflare's … model reads at most 1500"** — shorten the state, or send only the part the question is about. Cloudflare would have cut the rest without telling you. - **"No route for that URI"** — the model name or the base URL is wrong. Clef is served as `clef` and `clef-flash`, and the base URL must end in `/client/v4`. - **"The Cloudflare base URL must use https:// unless it points at this machine"** — the override is an `http://` URL whose host is not `localhost`, `127.0.0.1` or `[::1]`. A plain-http request would send the token unencrypted. Use `https://`, or reach the server through a port-forward to `localhost`. - **"Cloudflare answered with a redirect"** — the endpoint replied 301, 302, 307 or 308. The provider does not follow it and does not retry. Set the base URL to the address the redirect leads to. - **A 429 "Capacity temporarily exceeded"** — retried for you; if it keeps happening, send fewer requests at once. - **A 429 "you have used up your daily free allocation of 10,000 neurons"** — the Free plan's allowance for the day is gone. It is not retried, because nothing changes until the allowance returns (Cloudflare documents a reset at 00:00 UTC; on this account it came back later, see "What is not verified"); upgrade to Workers Paid or wait. Built-in features that use Clef as their default fall back as on any failure. - **An image is refused as "The request is N bytes; Cloudflare accepts at most 256000"** — that is NeuroLink's own cap on the whole encoded body, base64 included. Cloudflare's 413 gate does not count the images, so it would take more. Resize or compress the image to well under 190 KB; a 195 KB PNG, which Cloudflare accepted, is about 260,000 characters in base64 and is refused here. - **A request is refused as "The request's text, without its images, is N characters; Cloudflare's "clef-flash" model accepts at most 195584"** — the state and the questions together are past what that model takes; images do not count towards it. Shorten them. - **`decide()` uses Clef although you never chose it** — you have the Workers AI token and account id set and no other decision provider; see [When NeuroLink uses it](#when-neurolink-uses-it). ## See also - [The `decide` inference type](/docs/features/decide-inference-type) - [TypeSafe (Jev) Provider Guide](/docs/getting-started/providers/typesafe) - [Laya Provider Guide](/docs/getting-started/providers/laya) - [XOR Provider Guide](/docs/getting-started/providers/xor) - [Perplexity Decisions Provider Guide](/docs/getting-started/providers/perplexity-decider) - [SubQ Provider Guide](/docs/getting-started/providers/subq) - [OpenAI Decisions Provider Guide](/docs/getting-started/providers/openai-decisions) - [ScaleDown Provider Guide](/docs/getting-started/providers/scaledown) - [Cloudflare Workers AI text provider](/docs/getting-started/providers/cloudflare) - [Clef on Workers AI](https://developers.cloudflare.com/workers-ai/models/clef/) - [Introducing Clef: our open-source decision models, and new RL fine-tuning platform](https://blog.cloudflare.com/clef-decision-models/) (Cloudflare Blog) --- ## Cloudflare Workers AI Provider Guide # Cloudflare Workers AI Provider Guide **Open-model inference at the edge via Cloudflare Workers AI** ## Quick Start ### 1. Get Credentials You need both: - A Cloudflare **Account ID** (Cloudflare dashboard → right sidebar) - A Workers AI **API token** with the `Workers AI Read & Write` permission (Profile → API Tokens → Create Token) ### 2. Configure ```bash CLOUDFLARE_ACCOUNT_ID=your-account-id CLOUDFLARE_API_KEY=your-workers-ai-token CLOUDFLARE_MODEL=@cf/meta/llama-3.3-70b-instruct-fp8-fast ``` ### 3. Generate ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "cloudflare", input: { text: "Why is Cloudflare's edge network significant?" }, }); console.log(result.content); ``` --- ## Supported Models (sample) | Model ID | Notes | | ------------------------------------------ | -------------- | | `@cf/meta/llama-3.3-70b-instruct-fp8-fast` | Default | | `@cf/meta/llama-3.1-70b-instruct` | Llama 3.1 70B | | `@cf/meta/llama-3.1-8b-instruct` | Fast tier | | `@cf/meta/llama-3.2-11b-vision-instruct` | Vision-capable | Browse: [https://developers.cloudflare.com/workers-ai/models](https://developers.cloudflare.com/workers-ai/models) --- ## CLI Usage ```bash pnpm run cli generate "..." --provider cloudflare ``` --- ## Provider Aliases | Alias | Example | | ------------ | ----------------------- | | `cloudflare` | `--provider cloudflare` | | `cf` | `--provider cf` | --- ## Configuration Reference | Environment Variable | Required | Default | | ----------------------- | -------- | ------------------------------------------ | | `CLOUDFLARE_ACCOUNT_ID` | Yes | — | | `CLOUDFLARE_API_KEY` | Yes | — | | `CLOUDFLARE_MODEL` | No | `@cf/meta/llama-3.3-70b-instruct-fp8-fast` | --- ## Also configures decisions `CLOUDFLARE_API_KEY` and `CLOUDFLARE_ACCOUNT_ID` also configure a separate provider, the [Cloudflare Clef provider](/docs/getting-started/providers/cloudflare-clef) (`cloudflare-clef`), which serves `decide()` and emits no text. It is the sixth of the eight decision providers NeuroLink falls back to: built-in features that call `decide()` use the first one configured, in the order TypeSafe, Laya, XOR, SubQ, Perplexity, Clef, [OpenAI Decisions](/docs/getting-started/providers/openai-decisions), then [ScaleDown](/docs/getting-started/providers/scaledown). So a host that set these two variables only for this text provider, and has no other decision provider configured, has Clef as its default decision provider, and no switch turns that off while they are set. `credentials.cloudflare` does **not** configure `decide`; Clef reads its own slice, `credentials.cloudflareClef`. The text provider itself is unchanged: it still serves `generate()` and `stream()` with the same variables, models and base URL. See [One token, two providers](/docs/getting-started/providers/cloudflare-clef#one-token-two-providers). --- ## See Also - [Cloudflare Clef Provider](/docs/getting-started/providers/cloudflare-clef) — typed `decide()` judgments on the same token and account id - [Together AI Provider](/docs/getting-started/providers/together-ai) - [Fireworks Provider](/docs/getting-started/providers/fireworks) --- ## Cohere Provider Guide # Cohere Provider Guide **Command R chat + Embed v3 embeddings via the Cohere API** ## Quick Start ### 1. Get an API Key [https://dashboard.cohere.com/api-keys](https://dashboard.cohere.com/api-keys) ### 2. Configure ```bash COHERE_API_KEY=your-key COHERE_MODEL=command-r-plus-08-2024 ``` ### 3. Generate Text ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "cohere", input: { text: "Summarise the BM25 retrieval algorithm." }, }); console.log(result.content); ``` ### 4. Generate Embeddings ```typescript const provider = await ProviderFactory.createProvider("cohere"); const vec = await provider.embed("How does CRISPR work?"); console.log(vec.length); // 1024 for embed-english-v3.0 ``` --- ## Supported Models | Model ID | Family | Notes | | ----------------------------- | ---------------- | ------------------------ | | `command-r-plus-08-2024` | Chat (default) | Flagship | | `command-r-08-2024` | Chat | Mid-tier | | `command-r7b-12-2024` | Chat | Most compact | | `command-a-reasoning-08-2025` | Reasoning | Reasoning traces | | `embed-english-v3.0` | Embeddings (def) | 1024 dim, English | | `embed-multilingual-v3.0` | Embeddings | 1024 dim, 100+ languages | --- ## CLI Usage ```bash pnpm run cli generate "Explain RAG in 3 sentences" --provider cohere ``` --- ## Configuration Reference | Environment Variable | Required | Default | | -------------------- | -------- | ----------------------------------------- | | `COHERE_API_KEY` | Yes | — | | `COHERE_MODEL` | No | `command-r-plus-08-2024` | | `COHERE_BASE_URL` | No | `https://api.cohere.com/compatibility/v1` | --- ## Feature Support Matrix | Feature | Support | | ----------------- | ------------ | | Text generation | Yes | | Streaming | Yes | | Tool calling | Yes | | Structured output | Yes | | Vision | No | | Embeddings | Yes (native) | | Reranking | Yes | --- ## Troubleshooting - **`Not Found`** — the chosen model may not be available on your tier. Try `command-r-plus-08-2024` or `command-r-08-2024`. --- ## See Also - [Voyage Provider](/docs/getting-started/providers/voyage) - [Jina Provider](/docs/getting-started/providers/jina) --- ## Crusoe Provider Guide # Crusoe Provider Guide Crusoe is a **Tier-2 catalog provider**: its integration is one JSON file (`src/lib/providers/catalog/crusoe.json`) rather than hand-written code. That file is the source of truth for this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** Crusoe's `GET https://api.inference.crusoecloud.com/v1/models` > needs a key (it answers HTTP 401 without one), so the twelve model ids come > from the vendor's public > [Available models page](https://docs.crusoecloud.com/serverless-inference/available-models) > and the roster has not been checked. No account was created and no API key > was used to build this entry. `evidence.liveMatrix` is `null` until someone > runs the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://console.crusoecloud.com/request-foundry (the "Create a Managed AI account →" link on https://docs.crusoecloud.com/create-an-account, which says "Use Google or Github for the quickest signup.") 2. Create an API key: the Getting Started page (https://docs.crusoecloud.com/quickstart/getting-started-with-serverless-inference) says to visit the Intelligence Foundry on the console, select Inference from the left nav, click Create API Key, optionally provide an alias and expiration date, then click Create to view and save your API key 3. Billing as the vendor states it: see [Billing](#billing) below 4. Set `CRUSOE_API_KEY` in your .env file ### 2. Configure ```bash export CRUSOE_API_KEY=your-api-key export CRUSOE_MODEL=deepseek-ai/DeepSeek-V4-Flash # optional — overrides the default model export CRUSOE_BASE_URL=https://api.inference.crusoecloud.com/v1 # optional — overrides the base URL ``` The Getting Started page's Python example reads `CRUSOE_API_KEY`, the same name NeuroLink reads. The developer hub's LangChain integration reads the base URL from `CRUSOE_API_BASE`; NeuroLink reads `CRUSOE_BASE_URL`. ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "crusoe", model: "deepseek-ai/DeepSeek-V4-Flash", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider crusoe ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "crusoe", credentials: { crusoe: { apiKey: process.env.CRUSOE_API_KEY } }, }); ``` --- ## Billing Three Crusoe pages are quoted here as printed; the entry records `free-with-card`. - The docs announcement bar ([Serverless Inference overview](https://docs.crusoecloud.com/serverless-inference/overview)) reads "Use $5 in free credits to explore Serverless Inference and Serverless Fine-Tuning". - The [Create an account page](https://docs.crusoecloud.com/create-an-account) says "To provision resources or use the managed inference service, you must enable billing on your account. You will need a valid, non-prepaid credit card to proceed." - The [Serverless rate limits page](https://docs.crusoecloud.com/serverless-inference/rate-limits) lists default limits by account status: | Account status | TPM per model | RPM per model | | -------------------- | ------------- | ------------- | | No payment method | 500,000 | 30 | | Payment method added | 2,000,000 | 600 | The Create an account page and the rate limits page's "No payment method" row are both quoted above. `billingPolicy` is a required enum (`free-tier`, `free-with-card`, `no-free-tier`) with no value for that difference, and `free-with-card` is recorded. The [Usage and billing page](https://docs.crusoecloud.com/serverless-inference/usage-billing-models) lists the Billing of Serverless Inference as "Per-token" and points to [crusoe.ai/cloud/pricing](https://www.crusoe.ai/cloud/pricing) for pricing information. --- ## Models | Model | Context | Vision | $/M in · out (cached) | Notes | | ----------------------------------------------- | ------- | ------ | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `deepseek-ai/DeepSeek-V4-Flash` ⭐ | 1M | no | $0.14 / $0.28 ($0.03) | NeuroLink default. | | `deepseek-ai/DeepSeek-V4-Pro` | 1M | no | $1.74 / $3.48 ($0.15) | Fallback. | | `openai/gpt-oss-120b` | 128k | no | $0.05 / $0.20 ($0.05) | Fallback. The Zed README sets `"tools": true` and `"images": false` for this id and says it supports `reasoning_effort` values `low`, `medium` and `high`. | | `zai/GLM-5.3` | 1M | no | $1.40 / $4.40 ($0.26) | Fallback. | | `moonshotai/Kimi-K2.6` | 256K | yes | $0.70 / $3.50 ($0.35) | Fallback. | | `google/gemma-4-31b-it` | 262k | yes | $0.14 / $0.40 ($0.14) | Fallback. | | `nvidia/Nemotron-3-Nano-30B-A3B` | 261,144 | no | $0.05 / $0.20 ($0.03) | Fallback. | | `nvidia/Nemotron-3-Super-120B-A12B` | 261,144 | no | $0.30 / $2.40 ($0.15) | Fallback. | | `nvidia/Nemotron-3-Nano-Omni-Reasoning-30B-A3B` | 256,000 | yes | $0.30 / $1.83 ($0.30) | Fallback; `models.visionModel`. Vision comes from the pricing row heading "(Text, Image, Video)". | | `nvidia/nemotron-3.5-lightning-30b-a3b` | 1M | no | $0.05 / $0.20 ($0.03) | Fallback. | | `qwen/Qwen3.8-27B` | 256k | yes | — | Fallback. | | `zai/GLM-5.3-Flash` | 1M | yes | $0.15 / $0.50 ($0.03) | Fallback. | The model ids and context labels are copied from the [Available models page](https://docs.crusoecloud.com/serverless-inference/available-models) (retrieved 2026-09-29; TYPE column `instruct` on these twelve rows). The catalog records each context label read as a decimal figure: "1M" as 1,000,000, "262k" as 262,000, "256K" and "256k" as 256,000, "128k" as 128,000. Three rows record a figure from another Crusoe page in place of the Available models label "262k". The [model hub](https://www.crusoe.ai/cloud/managed-inference) shows the Context value "261,144" under the headings "Nemotron 3 Nano 30B A3B FP8" and "Nemotron 3 Super 120B A12B FP8", and 261,144 is recorded for both. For `nvidia/Nemotron-3-Nano-Omni-Reasoning-30B-A3B` the hub shows the Context value "256,000" under the heading "Nemotron 3 Nano Omni 30B A3B Reasoning", and the [Crusoe blog post](https://www.crusoe.ai/resources/blog/nvidia-nemotron-3-nano-omni-now-available) says "a 256K-token context window"; 256,000 is recorded. No per-model maximum output is recorded. Prices come from the Serverless Inference table on [crusoe.ai/cloud/pricing](https://www.crusoe.ai/cloud/pricing) (retrieved 2026-09-29; header "(Price per 1 million tokens)", columns Input tokens, Output tokens and Cached tokens). That table names models by two heading elements rather than by id, for example "DeepSeek" and "V4 Flash", so each row was matched to an id by those headings; the Available models page says "For each model's pricing information, see pricing". `models.defaultContextWindow` (128,000) and `models.defaultMaxOutputTokens` (8,192) are conservative placeholders for model ids outside the catalog; the vendor does not publish them. **Vision:** `vision: true` is set for `nvidia/Nemotron-3-Nano-Omni-Reasoning-30B-A3B`, from the pricing row headings "Nemotron 3 Nano Omni 30B A3B Reasoning" and "(Text, Image, Video)", and for four more ids from the sources below; the other seven ids are `vision: false`. `vision` is a required boolean in the catalog schema, and `false` is a placeholder on those seven ids except `openai/gpt-oss-120b`, where the Zed README sets `"images": false`. No image request was sent, so vision has not been probed. - `moonshotai/Kimi-K2.6`: a [Crusoe blog post](https://www.crusoe.ai/resources/blog/430-tokens-per-second-optimizing-kimi-k2-6-and-k2-7-for-production) says "Kimi K2.6 is a native multimodal agentic model built for long-horizon coding, autonomous execution, tool use, and complex workflows." and the [model card](https://huggingface.co/moonshotai/Kimi-K2.6) linked from this id's row on the Available models page says "K2.6 supports Image and Video input." - `google/gemma-4-31b-it`: the [model card](https://huggingface.co/google/gemma-4-31B-it) linked from this id's row on the Available models page says "Gemma 4 models are multimodal, handling text and image input (with audio supported on E2B, E4B, and 12B) and generating text output." - `qwen/Qwen3.8-27B`: the [model card](https://huggingface.co/Qwen/Qwen3.8-27B) linked from this id's row on the Available models page says "Native support for image and video understanding, from STEM diagrams and documents to hour-scale videos." - `zai/GLM-5.3-Flash`: the [model card](https://huggingface.co/zai-org/GLM-5.3-Flash) linked from this id's row on the Available models page says "the first natively multimodal model in the GLM-5 series", and the [Z.ai docs page](https://docs.z.ai/guides/llm/glm-5.3-flash) linked from that card shows the value "Video / Image / Text / File" under the card title "Input Modality". **Fallback order** when the default is unavailable: `deepseek-ai/DeepSeek-V4-Pro` → `openai/gpt-oss-120b` → `zai/GLM-5.3` → `moonshotai/Kimi-K2.6` → `google/gemma-4-31b-it` → `nvidia/Nemotron-3-Nano-30B-A3B` → `nvidia/Nemotron-3-Super-120B-A12B` → `nvidia/Nemotron-3-Nano-Omni-Reasoning-30B-A3B` → `nvidia/nemotron-3.5-lightning-30b-a3b` → `qwen/Qwen3.8-27B` → `zai/GLM-5.3-Flash`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `openai/gpt-oss-120b`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Crusoe — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /v1/models` answered HTTP 401 on 2026-09-29, so the model ids come from the Available models page (retrieved 2026-09-29) and the roster has not been verified | | Auth-failure shape | unauthenticated `GET /v1/models` and `GET /v1/chat/completions` each answered HTTP 401 on 2026-09-29 with `content-type: application/json` and the body `{"errors":["Authentication failed"]}`. The body has no code field, so `authProbe` records the status and no code. `errorRules` carry 401, 429 and 503 | | Billing | three public pages quoted under [Billing](#billing) above, 2026-09-29 — no signup performed | | Tools / structured output | not exercised. Tool calling is shown in the developer hub's Zed and LangChain READMEs and structured output in the LangChain README; no request was sent, and no combined tools+schema request was sent, so `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=crusoe` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting The causes and resolutions below are worded by Crusoe pages. | Symptom | Cause as the vendor states it | Resolution as the vendor states it | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | HTTP 429 | "Your project exceeded its TPM or RPM limit for the model." ([Serverless rate limits](https://docs.crusoecloud.com/serverless-inference/rate-limits)) | "Both 429 and 503 responses are transient, so you can retry the request with exponential backoff rather than failing immediately." The same page links [Contact us](https://www.crusoe.ai/contact-sales) for a rate limit increase | | HTTP 503 | "Your request is within your limits, but the shared endpoint is experiencing unusually high load and can't accept it right now." (same page) | The same sentence as above: retry the request with exponential backoff | | A deprecated model id | "Five Serverless Inference models were deprecated on September 12, 2026." (Available models page) | "Update your API calls to use a recommended replacement model from the table below." The page's table lists Z.ai GLM-5.1, Z.ai GLM-5.2, DeepSeek V3, Qwen3 235B A22B and Llama 3.3 70B as deprecated | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## D-ID Provider Guide (avatar) # D-ID Provider Guide **Lip-synced talking-head videos via the D-ID `/talks` API** ## Quick Start ### 1. Get an API Key [https://studio.d-id.com/account-settings](https://studio.d-id.com/account-settings) ### 2. Configure ```bash DID_API_KEY=your-d-id-key ``` ### 3. Generate ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "vertex", output: { mode: "avatar", avatar: { provider: "d-id", image: readFileSync("./portrait.jpg"), // Buffer | path | URL text: "Hello, this is your AI presenter.", ttsProvider: "openai-tts", voice: "alloy", }, }, }); if (result.avatar?.buffer) { writeFileSync("./talk.mp4", result.avatar.buffer); } ``` --- ## CLI Usage ```bash pnpm run cli generate "Hello world" \ --provider d-id \ --avatarImage ./portrait.jpg \ --avatarText "Welcome to NeuroLink" \ --avatarOutput ./talk.mp4 ``` --- ## Configuration Reference | Environment Variable | Required | Description | | -------------------- | -------- | ------------ | | `DID_API_KEY` | Yes | D-ID API key | --- ## See Also - [HeyGen Provider](/docs/getting-started/providers/heygen) - [MuseTalk via Replicate](/docs/getting-started/providers/musetalk) --- ## Alibaba Cloud Model Studio (DashScope) Provider Guide # Alibaba Cloud Model Studio (DashScope) Provider Guide Alibaba Cloud Model Studio (DashScope) is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/dashscope.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** The vendor's `/models` endpoint needs a key (an > unauthenticated GET of it returns HTTP 401), so the model ids come from the > vendor's public documentation pages and the roster has not been checked > against the API. No account was created and no API key was used to build it. > `evidence.liveMatrix` is `null` until someone runs the live capability matrix > with a real key (see [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://account.alibabacloud.com/register/intl_register.htm and create an Alibaba Cloud account (linked from https://www.alibabacloud.com/help/en/model-studio/first-api-call-to-qwen) 2. Complete your account information, then open https://modelstudio.console.alibabacloud.com/ap-southeast-1 and agree to the service agreement to activate Model Studio (Singapore region); https://www.alibabacloud.com/help/en/model-studio/new-free-quota says the system then grants a free quota automatically 3. Create an API key at https://modelstudio.console.alibabacloud.com/ap-southeast-1/settings/api-key with the region set to Singapore; https://www.alibabacloud.com/help/en/model-studio/get-api-key states that each region has its own endpoint, API keys, and model list, and that they cannot be used across regions. Copy the key when it is shown 4. Free quota, per https://www.alibabacloud.com/help/en/model-studio/new-free-quota: valid for 90 days, typically 1,000,000 tokens for each model, and "After the free quota is exhausted, you are automatically billed on a pay-as-you-go basis." 5. Set `DASHSCOPE_API_KEY` in your .env file (the vendor's examples use the same variable name) ### 2. Configure ```bash export DASHSCOPE_API_KEY=your-api-key export DASHSCOPE_MODEL=qwen3.8-max # optional — overrides the default model export DASHSCOPE_BASE_URL=https://dashscope-intl.aliyuncs.com/compatible-mode/v1 # optional — for example the workspace-dedicated domain ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "dashscope", model: "qwen3.8-max", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider dashscope ``` Per-request credentials are passed the same way as for the other catalog providers: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "dashscope", credentials: { dashscope: { apiKey: process.env.DASHSCOPE_API_KEY } }, }); ``` --- ## Base URL The catalog uses `https://dashscope-intl.aliyuncs.com/compatible-mode/v1`. The vendor's [regions page](https://www.alibabacloud.com/help/en/model-studio/regions) lists `dashscope-intl.aliyuncs.com` as the Singapore DashScope domain, labelled "existing domain", and says the China (Beijing) and Singapore regions each support one service deployment scope, Chinese mainland and International respectively. The [OpenAI-compatible Chat page](https://www.alibabacloud.com/help/en/model-studio/qwen-api-via-openai-chat-completions) says "The existing domain remains fully functional." The regions page also documents a workspace-dedicated domain, `https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1`, labelled "(recommended)" in its endpoint comparison. To use it, set `DASHSCOPE_BASE_URL` to that URL with your workspace id. The same page states: "The DashScope domain (dashscope.aliyuncs.com) will no longer support new features after September 30, 2026." --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ------------------- | ------- | ---------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `qwen3.8-max` ⭐ | 1M | yes | $2 / $6 | NeuroLink default. The model in the vendor's OpenAI-compatible examples; the text-generation page says "For the strongest reasoning, choose qwen3.8-max." Thinking mode, Function Calling, Built-in tools and Structured output Supported. | | `qwen3.8-flash` | 1M | yes | $0.15 / $0.47 | Fallback. Thinking mode, Function Calling, Built-in tools and Structured output Supported. | | `qwen3.7-plus` | 1M | yes | — | Fallback. The text-generation page says "We recommend qwen3.7-plus for balanced performance and cost, with full tool calling and a 1M-token context window for large codebases." | | `qwen3.8-max-0902` | 1M | yes | $2 / $6 | Fallback. Thinking mode, Function Calling, Built-in tools and Structured output Supported. | | `qwen3.7-flash` | 1M | yes | — | Fallback. Thinking mode, Function Calling, Built-in tools and Structured output Supported. | | `deepseek-v4-pro` | 1M | no | $2.40 / $4.80 | Fallback. Thinking mode, Function Calling and Structured output Supported; Built-in tools Unsupported. | | `deepseek-v4-flash` | 1M | no (placeholder) | $0.20 / $0.40 | Fallback. Thinking mode, Function Calling and Structured output Supported; Built-in tools Unsupported. | | `kimi-k3` | — | yes | $3 / $15 | Fallback. Named under Text generation and under Image & video, Understanding on the Models page. | Where the sources are: - **Context, thinking mode, function calling, built-in tools, structured output**: the Recommended models table on the text-generation page. The `1M` label is recorded as 1,000,000, since the pricing page states "K means 1,000 and M means 1,000,000". `kimi-k3` has no context figure in the catalog. - **Prices**: the pricing page, Singapore tab, International deployment scope, per 1 million tokens, where the page gives one input price and one output price for the model. `qwen3.7-plus` and `qwen3.7-flash` are left to the pricing page itself. - **Vision**: `yes` on the ids the vendor's [vision page](https://www.alibabacloud.com/help/en/model-studio/vision) names in its image-quantity limits ("Qwen3.8-Max, Qwen3.8-Flash, Qwen3.7-Plus series: Up to 2,048 images" and "Qwen3.7-Flash, Qwen3.6-Plus, Qwen3.6-Flash, Qwen3.5-Plus, Qwen3.5-Flash, Qwen3-VL, Qwen-VL, QVQ series: Up to 256 images"), on `qwen3.8-max-0902`, which the Visual understanding page ([vision-model](https://www.alibabacloud.com/help/en/model-studio/vision-model)) names in its Video support list ("Up to 2 hours / 2 GB") and whose Recommended models row lists Max images 2048 and Max videos 64, and on `kimi-k3`, which the Models page lists under Image & video, Understanding. `deepseek-v4-pro` carries `false`: the [error-code page](https://www.alibabacloud.com/help/en/model-studio/error-code) refers to "plain-text models like qwen3-max, qwen-plus, or deepseek-v4-pro". The schema requires a boolean, and `deepseek-v4-flash` carries `false` as a placeholder. `models.defaultContextWindow` (128,000) and `models.defaultMaxOutputTokens` (8,192) are conservative placeholders; the vendor does not publish a general default. They apply wherever the catalog sets no value, which includes model ids outside the catalog, the context window of `kimi-k3` and the max output tokens of each catalog id. **Fallback order** when the default is unavailable: `qwen3.8-flash` → `qwen3.7-plus` → `qwen3.8-max-0902` → `qwen3.7-flash` → `deepseek-v4-pro` → `deepseek-v4-flash` → `kimi-k3`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Alibaba Cloud Model Studio (DashScope) — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /compatible-mode/v1/models`, HTTP 401 without a key, 2026-09-29. Model ids are taken from the vendor's text-generation and Models pages (retrieved 2026-09-29); the roster is not verified | | Auth-failure shape | the same GET returned a JSON body with `error.message` "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY).", `error.type` "invalid_request_error", `error.param` null, `error.code` null and a top-level `request_id`; `errorRules` carries a status `401` rule | | Endpoint check | an unauthenticated GET of `/compatible-mode/v1/chat/completions` answered HTTP 400 with `code` "InvalidParameter" and `message` "Request method 'GET' is not supported."; that message is also listed on the vendor's error-code page | | Billing | the free quota page says "the platform automatically grants you a free quota for various models" on first activation (Singapore region), valid for 90 days, and "After the free quota is exhausted, you are automatically billed on a pay-as-you-go basis." — 2026-09-29 | | Other error rules | `FreeTierOnly` (HTTP 403) and `Arrearage` (HTTP 400) rules follow the vendor's error-code page; neither was triggered | | Tools / structured output | documented on the function calling and structured output pages; neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=dashscope` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting The rows below restate what the vendor's [error-code page](https://www.alibabacloud.com/help/en/model-studio/error-code) gives for the named error. | Symptom | Cause the vendor lists | Fix the vendor lists | | --------------------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | | HTTP 401 `invalid_api_key` | Among the causes: the API key and the base URL belong to different regions | Use an API key from the Singapore region page together with the Singapore base URL | | HTTP 403 `AllocationQuota.FreeTierOnly` | "Cause 2": the free quota exhaustion stop was enabled and requests were made after the free quota ran out | Disable the free quota exhaustion stop switch to continue on a paid basis | | HTTP 400 `Arrearage` | The Alibaba Cloud account associated with the API key has an overdue payment | Check Expenses and Costs on the vendor's billing console and recharge | | HTTP 404 `model_not_found` | The model does not exist, or Model Studio has not been activated | Compare the `model` value with the Models page; activate model services in the Model Marketplace | | HTTP 429 `Throttling` | API calls triggered rate limiting | "Reduce call frequency or retry later." | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Deepgram Provider Guide # Deepgram Provider Guide **Fast, accurate speech-to-text with streaming, speaker diarization, and smart formatting** > **STT-only in NeuroLink** — Deepgram is registered as the STT provider id > `deepgram`. Deepgram's TTS product is not wired in NeuroLink today; for > TTS use `openai-tts`, `elevenlabs`, `azure-tts`, or `google-ai`. ------------------- | --------------------------------------------- | | **Provider ID** | `deepgram` | | **API endpoint** | `https://api.deepgram.com/v1/listen` | | **Streaming endpoint** | `wss://api.deepgram.com/v1/listen` | | **Default model** | `nova-2` | | **Formats** | mp3, wav, ogg, opus | | **Max audio** | 2 hours (7,200 seconds) per request | | **Languages** | 40+ languages and dialects | | **Streaming** | Yes (WebSocket-based real-time transcription) | --- ## Quick Start ### 1. Get an API Key Sign up at [https://console.deepgram.com](https://console.deepgram.com) and create an API key under **Settings → API Keys**. ### 2. Configure Environment Add to your `.env` file: ```bash # Required DEEPGRAM_API_KEY=your-deepgram-api-key # Optional: default model (default: nova-2) DEEPGRAM_MODEL=nova-2 # Optional: default language (default: en-US) DEEPGRAM_LANGUAGE=en-US ``` ### 3. Install NeuroLink ```bash npm install @juspay/neurolink # or pnpm add @juspay/neurolink ``` ### 4. Transcribe Your First Audio File ```typescript const ai = new NeuroLink(); const audioBuffer = readFileSync("./recording.wav"); const result = await ai.generate({ input: { text: "Transcribe the following audio." }, stt: { enabled: true, provider: "deepgram", audio: audioBuffer, format: "wav", }, }); if (result.transcription) { console.log("Transcript:", result.transcription.text); console.log("Confidence:", result.transcription.confidence); console.log("Duration:", result.transcription.duration, "seconds"); } ``` --- ## Supported Models | Model ID | Description | Best For | | ------------------ | -------------------------------------------------- | --------------------------------------- | | `nova-2` (default) | Fastest, lowest Word Error Rate in the Nova family | General transcription, production use | | `nova-2-general` | General-purpose variant, same as `nova-2` | Broad use cases | | `nova-2-meeting` | Optimised for multi-speaker meeting audio | Video conferences, recordings | | `nova-2-phonecall` | Tuned for telephone audio quality | Call centre, PSTN audio | | `nova-2-voicemail` | Handles background noise and compressed audio | Voicemail transcription | | `nova-2-finance` | Finance-domain vocabulary boost | Earnings calls, financial content | | `nova-2-medical` | Medical terminology | Clinical notes, consultations | | `nova-3` | Next-generation model with improved accuracy | Demanding accuracy requirements | | `nova` | Previous generation Nova | Legacy compatibility | | `enhanced` | High accuracy, slower processing | Archival, quality-critical paths | | `base` | Fastest, lower accuracy | Draft transcriptions, cost optimisation | --- ## SDK Usage ### Basic Transcription ```typescript const ai = new NeuroLink(); const audio = readFileSync("./meeting.wav"); const result = await ai.generate({ input: { text: "Transcribe this audio." }, stt: { enabled: true, provider: "deepgram", audio, format: "wav", language: "en-US", }, }); if (result.transcription) { console.log(result.transcription.text); } ``` ### Choosing a Model ```typescript const result = await ai.generate({ input: { text: "Transcribe this meeting recording." }, stt: { enabled: true, provider: "deepgram", audio, format: "wav", model: "nova-2-meeting", } as DeepgramSTTOptions, }); ``` ### Smart Formatting Smart formatting cleans up numbers, currency, dates, and other structured data automatically: ```typescript const result = await ai.generate({ input: { text: "Transcribe with formatting." }, stt: { enabled: true, provider: "deepgram", audio, format: "wav", smartFormat: true, // Formats "twenty five dollars" → "$25" } as DeepgramSTTOptions, }); ``` ### Speaker Diarization Identify who spoke when in multi-speaker audio: ```typescript const result = await ai.generate({ input: { text: "Transcribe and identify speakers." }, stt: { enabled: true, provider: "deepgram", audio, format: "wav", speakerDiarization: true, }, }); if (result.transcription) { console.log("Transcript:", result.transcription.text); console.log("Speakers found:", result.transcription.speakers); // Word-level speaker attribution for (const word of result.transcription.words ?? []) { console.log( `${word.speaker ?? "?"}: "${word.word}" [${word.startTime}s–${word.endTime}s]`, ); } } ``` ### Utterance Segmentation Split audio into utterance-level segments with speaker and timing information: ```typescript const result = await ai.generate({ input: { text: "Segment into utterances." }, stt: { enabled: true, provider: "deepgram", audio, format: "wav", utterances: true, speakerDiarization: true, } as DeepgramSTTOptions, }); if (result.transcription?.segments) { for (const seg of result.transcription.segments) { console.log(`[${seg.startTime}s] ${seg.speaker ?? "Speaker"}: ${seg.text}`); } } ``` ### Word-Level Timestamps ```typescript const result = await ai.generate({ input: { text: "Transcribe with word timings." }, stt: { enabled: true, provider: "deepgram", audio, format: "wav", wordTimestamps: true, }, }); if (result.transcription?.words) { for (const word of result.transcription.words) { console.log( `"${word.word}" at ${word.startTime}s (confidence: ${word.confidence?.toFixed(2)})`, ); } } ``` ### Custom Vocabulary / Keyword Boosting Improve recognition of domain-specific terms: ```typescript const result = await ai.generate({ input: { text: "Transcribe technical content." }, stt: { enabled: true, provider: "deepgram", audio, format: "wav", keywords: ["NeuroLink", "EulerHS", "Juspay", "HyperSDK"], keywordBoost: "high", } as DeepgramSTTOptions, }); ``` ### Content Redaction Automatically redact sensitive data from transcripts: ```typescript const result = await ai.generate({ input: { text: "Transcribe and redact PII." }, stt: { enabled: true, provider: "deepgram", audio, format: "wav", redact: ["pci", "ssn"], // Redact credit card and SSN numbers } as DeepgramSTTOptions, }); ``` ### Real-Time Streaming Transcription Use the `DeepgramSTT` handler directly for WebSocket-based streaming: ```typescript const handler = new DeepgramSTT(process.env.DEEPGRAM_API_KEY); async function* readAudioStream(filePath: string): AsyncIterable { const stream = createReadStream(filePath, { highWaterMark: 4096 }); for await (const chunk of stream) { yield chunk as Buffer; } } const audioStream = readAudioStream("./live-audio.wav"); for await (const segment of handler.transcribeStream(audioStream, { language: "en-US", smartFormat: true, speakerDiarization: true, })) { const status = segment.isFinal ? "[FINAL]" : "[partial]"; console.log(`${status} ${segment.text}`); } ``` ### Per-Call Credential Override ```typescript const result = await ai.generate({ input: { text: "Transcribe with a per-request key." }, stt: { enabled: true, provider: "deepgram", audio, format: "wav", }, credentials: { deepgram: { apiKey: "user-specific-deepgram-key", }, }, }); ``` --- ## CLI Usage ### Basic Transcription ```bash # Transcribe an audio file neurolink generate "Respond to audio" \ --stt --stt-provider deepgram \ --input-audio recording.wav # Specify model neurolink generate "Transcribe this meeting" \ --stt --stt-provider deepgram \ --stt-model nova-2-meeting \ --input-audio meeting.mp3 ``` ### Language Selection ```bash neurolink generate "Transcribe Spanish audio" \ --stt --stt-provider deepgram \ --stt-language es \ --input-audio audio-es.wav ``` ### Smart Formatting ```bash neurolink generate "Transcribe with smart formatting" \ --stt --stt-provider deepgram \ --stt-smart-format \ --input-audio recording.wav ``` ### Speaker Diarization ```bash neurolink generate "Identify speakers" \ --stt --stt-provider deepgram \ --stt-diarize \ --input-audio meeting.wav ``` --- ## Supported Languages Deepgram supports 40+ languages and regional dialects. Key languages available with diarization and punctuation: | Code | Language | | ------- | ------------ | | `en` | English | | `en-US` | English (US) | | `en-GB` | English (UK) | | `es` | Spanish | | `fr` | French | | `de` | German | | `it` | Italian | | `pt` | Portuguese | | `nl` | Dutch | | `ja` | Japanese | | `ko` | Korean | | `zh` | Chinese | | `hi` | Hindi | | `ru` | Russian | For the full language list, see the [Deepgram language support docs](https://developers.deepgram.com/docs/models-languages-overview). --- ## Configuration Reference | Environment Variable | Required | Default | Description | | -------------------- | -------- | -------- | ------------------------------ | | `DEEPGRAM_API_KEY` | Yes | — | Deepgram API key | | `DEEPGRAM_MODEL` | No | `nova-2` | Default transcription model | | `DEEPGRAM_LANGUAGE` | No | `en-US` | Default transcription language | --- ## Feature Support Matrix | Feature | Supported | Notes | | ---------------------- | --------- | ---------------------------------------------- | | Batch transcription | Yes | Up to 2 hours per request | | Real-time streaming | Yes | WebSocket via `transcribeStream()` | | Speaker diarization | Yes | `speakerDiarization: true` | | Word-level timestamps | Yes | Included by default when words are returned | | Smart formatting | Yes | `smartFormat: true` — numbers, dates, currency | | Utterance segmentation | Yes | `utterances: true` | | Keyword boosting | Yes | `keywords` + `keywordBoost` | | Content redaction | Yes | PCI, SSN number redaction | | Profanity filter | Yes | `profanityFilter: true` | | Custom vocabulary | Yes | `keywords` array | | Multi-format input | Yes | mp3, wav, ogg, opus | | Confidence scores | Yes | Per-transcript and per-word | | 40+ languages | Yes | `language` option | --- ## Troubleshooting ### "deepgram provider not configured" The `DEEPGRAM_API_KEY` environment variable is missing or not loaded. ```bash echo $DEEPGRAM_API_KEY export DEEPGRAM_API_KEY=your-key-here ``` Create or rotate keys at [https://console.deepgram.com](https://console.deepgram.com). ### "HTTP 401" — Invalid API key Your key is invalid or has been revoked. Generate a new one from the Deepgram console. ### "HTTP 402" — Insufficient credits Your account balance is exhausted. Top up at [https://console.deepgram.com/billing](https://console.deepgram.com/billing). ### "HTTP 429" — Rate limit exceeded Too many concurrent requests. Implement exponential backoff or reduce concurrency. Rate limits are documented in the [Deepgram API docs](https://developers.deepgram.com/docs/rate-limits). ### Empty transcript returned Audio may be silent, below detection threshold, or in the wrong language. Verify: 1. The audio buffer is not empty (`audioBuffer.length > 0`). 2. The `format` matches the actual audio encoding. 3. The `language` matches the audio's spoken language. ### "Deepgram STT request timed out after 30 seconds" The request took longer than 30 seconds — typically due to very long audio or network issues. For audio over 30 minutes, consider splitting into chunks. ### Streaming WebSocket disconnects Check that `DEEPGRAM_API_KEY` is valid and that your network allows outbound WebSocket connections to `wss://api.deepgram.com`. Firewall or proxy configurations may block WebSocket upgrades. ### Diarization not appearing in results Diarization requires multi-speaker audio with clearly separated voices. Single-speaker audio will return no speaker labels. Also confirm `speakerDiarization: true` is set, and that you are using a model that supports it (Nova-2 and above). --- ## See Also - [Audio Input (STT) Guide](/docs/features/audio-input) — complete multi-provider STT reference - [Voice Agent Guide](/docs/features/voice-agent) — building full voice assistants - [OpenAI TTS Provider Guide](/docs/getting-started/providers/openai-tts) — text-to-speech counterpart - [ElevenLabs Provider Guide](/docs/getting-started/providers/elevenlabs) — alternative TTS with voice cloning --- **Need Help?** Join the [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## DeepInfra Provider Guide # DeepInfra Provider Guide DeepInfra is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/deepinfra.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** Every field below comes from DeepInfra's own public > documentation and an unauthenticated `GET /v1/openai/models` call — no API > key was created or used to build it. `evidence.liveMatrix` is `null` until > someone runs the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://deepinfra.com/dash/api_keys and sign in (Google, GitHub, email & password, or Corporate SSO — see https://docs.deepinfra.com/account/signing-in) 2. Create an API key and copy it when it is shown 3. No free tier: DeepInfra requires a card or pre-payment before any request succeeds (https://deepinfra.com/pricing) 4. Set `DEEPINFRA_API_KEY` in your .env file ### 2. Configure ```bash export DEEPINFRA_API_KEY=your-api-key export DEEPINFRA_MODEL=deepseek-ai/DeepSeek-V4-Flash-0731 # optional — overrides the default model export DEEPINFRA_BASE_URL=https://api.deepinfra.com/v1/openai # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "deepinfra", model: "deepseek-ai/DeepSeek-V4-Flash-0731", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider deepinfra ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "deepinfra", credentials: { deepinfra: { apiKey: process.env.DEEPINFRA_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ------------------------------------------- | ------- | ------ | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | `deepseek-ai/DeepSeek-V4-Flash-0731` ⭐ | 1M | no | $0.06 / $0.18 (cached $0.015) | Recommended — the exact model used in DeepInfra's own tool-calling docs example and named as reasoning_effort-capable in its reasoning docs. | | `deepseek-ai/DeepSeek-V4-Pro-0813` | 1M | no | $1.30 / $2.60 (cached $0.10) | Larger DeepSeek variant; roster-listed only; fallback. | | `openai/gpt-oss-120b` | 131K | no | $0.037 / $0.17 | OpenAI's open-weight 120B model; reasoning-tagged on the live roster; fallback. | | `moonshotai/Kimi-K3` | 1M | yes | $2.85 / $14.25 (cached $0.285) | Named in DeepInfra's tool-calling docs as "the current Kimi model in our catalog"; roster-tagged vision; fallback. | | `zai-org/GLM-5.2` | 1M | no | $0.75 / $2.40 (cached $0.14) | Named in DeepInfra's reasoning docs as reasoning_effort-capable; fallback. | | `anthropic/claude-haiku-4-5` | 200K | yes | $1.00 / $5.00 | Claude Haiku 4.5 served through DeepInfra's marketplace; roster-tagged vision + reasoning_effort; fallback. | | `Qwen/Qwen3-14B` | 41K | no | $0.12 / $0.24 | Smaller Qwen reasoning-tagged model; roster-listed only; fallback. | | `meta-llama/Llama-4-Scout-17B-16E-Instruct` | 328K | yes | $0.10 / $0.30 | Roster-tagged vision; fallback; `models.visionModel`. | Context and pricing are taken from an unauthenticated `GET https://api.deepinfra.com/v1/openai/models` call made 2026-09-28 (187 models total; 8 curated into this catalog). `models.defaultContextWindow` (128,000) and `models.defaultMaxOutputTokens` (16,384) are the vendor's documented general fallback figures — DeepInfra's own docs state the per-response output cap is "model-dependent, with a hard cap of 16384 tokens … for most models" (docs.deepinfra.com/chat/overview) — not per-model values, since DeepInfra's live roster reports each model's `max_tokens` field equal to its context length (not a distinct output ceiling). **Fallback order** when the default is unavailable: `deepseek-ai/DeepSeek-V4-Pro-0813` → `openai/gpt-oss-120b` → `moonshotai/Kimi-K3` → `zai-org/GLM-5.2` → `anthropic/claude-haiku-4-5` → `Qwen/Qwen3-14B` → `meta-llama/Llama-4-Scout-17B-16E-Instruct`. Vision tags (`vision: true`) come from the `vlm`/`vision` tags DeepInfra's own live roster attaches to each model, not from an independent image-input probe — no key was used to send a real image request. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for DeepInfra — **docs- and roster-verified, not live-verified**: | Probe | Result | | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /v1/openai/models`, HTTP 200, 187 models, 2026-09-28 — no key used | | Billing | public pricing page confirms "You have to add a card or pre-pay or you won't be able to use our services" — no free tier, 2026-09-28 | | Auth-failure shape | not documented anywhere DeepInfra publishes (docs site has no errors page; the public OpenAPI spec at `api.deepinfra.com/openapi.json` documents only 200/422 for `chat/completions`) and not probed live — `errorRules` is empty | | Tools / structured output | documented on docs.deepinfra.com/chat/tool-calling and /chat/structured-outputs respectively; neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=deepinfra` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | | Requests fail immediately | No card on file / no pre-payment balance | DeepInfra requires billing setup before any request succeeds; add a card or pre-pay | | Model not found | The roster changed since 2026-09-28 | Pick a current id from the unauthenticated `GET /v1/openai/models` roster | | Structured output ignored with tools attached | `structuredOutputWithTools` is `false` on this entry — untested combination | NeuroLink omits `response_format` automatically whenever tools are present, before sending | | Tool calls not returned | Tool calling on DeepInfra is model-dependent | Use a model DeepInfra names as tool-capable (e.g. the default, or `moonshotai/Kimi-K3`) | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## DeepSeek Provider Guide # DeepSeek Provider Guide **Text and image input with DeepSeek-V4.1-Flash and DeepSeek-V4-Pro through a single API** ## Quick Start ### 1. Get an API Key Sign up at [https://platform.deepseek.com](https://platform.deepseek.com) and create an API key under **API Keys**. ### 2. Configure Environment Add to your `.env` file: ```bash # Required DEEPSEEK_API_KEY=sk-... # Optional: override the default model (default: deepseek-chat) DEEPSEEK_MODEL=deepseek-chat # Optional: override the base URL (default: https://api.deepseek.com) DEEPSEEK_BASE_URL=https://api.deepseek.com ``` ### 3. Install NeuroLink ```bash npm install @juspay/neurolink # or pnpm add @juspay/neurolink ``` ### 4. Generate Your First Response ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "deepseek", input: { text: "Explain the difference between synchronous and asynchronous programming.", }, }); console.log(result.content); ``` --- ## Supported Models | Model ID | Serves | Context | Images | Notes | | ------------------- | ------------------- | ------- | ------ | ------------------------------------------------ | | `deepseek-chat` | DeepSeek-V4.1-Flash | 1M | Yes | Default; alias of `deepseek-flash`, thinking off | | `deepseek-reasoner` | DeepSeek-V4.1-Flash | 1M | Yes | Alias of `deepseek-flash`, thinking on | | `deepseek-flash` | DeepSeek-V4.1-Flash | 1M | Yes | Thinking on by default | | `deepseek-v4-pro` | DeepSeek-V4-Pro | 1M | No | Thinking on by default | Pass any model ID via `--model` (CLI) or `model:` (SDK). `GET /models` on `api.deepseek.com` lists only `deepseek-flash` and `deepseek-v4-pro`; the two older ids are accepted as aliases. --- ## SDK Usage ### Basic Generation ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "deepseek", input: { text: "Write a TypeScript function to debounce an async function." }, }); console.log(result.content); ``` ### Using the Reasoner Model ```typescript const result = await ai.generate({ provider: "deepseek", model: "deepseek-reasoner", input: { text: "Prove that the square root of 2 is irrational." }, }); // The reasoning trace is available separately from the final answer console.log(result.content); ``` Note: with thinking on, responses take longer because the model reasons before answering. ### Streaming ```typescript const ai = new NeuroLink(); const stream = await ai.stream({ provider: "deepseek", input: { text: "Explain how B-trees work, step by step." }, }); for await (const chunk of stream.stream) { process.stdout.write(chunk); } ``` ### Per-Call Credential Override Pass credentials at call time to override the instance-level or environment-variable defaults. Useful when routing requests for different users through separate DeepSeek accounts. ```typescript const result = await ai.generate({ provider: "deepseek", input: { text: "Hello, world!" }, credentials: { deepseek: { apiKey: "sk-user-specific-key", }, }, }); ``` You can also override the base URL per call — useful when pointing at a self-hosted OpenAI-compatible proxy in front of DeepSeek: ```typescript const result = await ai.generate({ provider: "deepseek", input: { text: "Hello" }, credentials: { deepseek: { apiKey: "sk-...", baseURL: "https://my-proxy.example.com/v1", }, }, }); ``` --- ## CLI Usage ### Basic Commands ```bash # Generate with default model (deepseek-chat) pnpm run cli generate "What is the halting problem?" --provider deepseek # Use an alias pnpm run cli generate "Hello" --provider ds # Use the reasoning model pnpm run cli generate "Prove P != NP (attempt)" --provider deepseek --model deepseek-reasoner # Interactive loop mode pnpm run cli loop --provider deepseek ``` ### Streaming via CLI The CLI streams output by default when a TTY is attached. No extra flags are required. ```bash pnpm run cli generate "Explain TCP/IP in detail" --provider deepseek --model deepseek-chat ``` --- ## Provider Aliases The DeepSeek provider can be referenced by any of the following names: | Alias | Example | | ---------- | --------------------- | | `deepseek` | `--provider deepseek` | | `ds` | `--provider ds` | --- ## Configuration Reference | Environment Variable | Required | Default | Description | | -------------------- | -------- | -------------------------- | ------------------------------------------- | | `DEEPSEEK_API_KEY` | Yes | — | DeepSeek API key (starts with `sk-`) | | `DEEPSEEK_MODEL` | No | `deepseek-chat` | Default model to use | | `DEEPSEEK_BASE_URL` | No | `https://api.deepseek.com` | Base URL for the API (override for proxies) | --- ## Feature Support Matrix | Feature | `deepseek-chat` | `deepseek-reasoner` | `deepseek-flash` | `deepseek-v4-pro` | | ----------------- | --------------- | ------------------- | ---------------- | ----------------- | | Text generation | Yes | Yes | Yes | Yes | | Streaming | Yes | Yes | Yes | Yes | | Tool calling | Yes | See below | See below | See below | | Structured output | Yes | Not tested | Not tested | Not tested | | Vision / images | Yes | Yes | Yes | No | | Embeddings | No | No | No | No | | Reasoning trace | No | Yes | Yes | Yes | --- ## Troubleshooting ### "Invalid DeepSeek API key" The `DEEPSEEK_API_KEY` is missing or incorrect. ```bash # Verify the variable is set echo $DEEPSEEK_API_KEY # Set it inline export DEEPSEEK_API_KEY=sk-... ``` Get or rotate keys at [https://platform.deepseek.com/api_keys](https://platform.deepseek.com/api_keys). ### "DeepSeek account has insufficient balance" Your account credit is exhausted. Top up at [https://platform.deepseek.com/usage](https://platform.deepseek.com/usage). ### "DeepSeek rate limit exceeded" Too many requests in a short window. Implement exponential backoff or reduce request concurrency. Rate limits are published in the [DeepSeek API docs](https://platform.deepseek.com/api-docs). ### "Model not found" DeepSeek answers an unknown id with `400` and "The supported API model names are deepseek-flash, deepseek-v4-pro". Use one of those, or the `deepseek-chat` / `deepseek-reasoner` aliases. ### Slow responses with thinking on Expected. `deepseek-reasoner`, `deepseek-flash` and `deepseek-v4-pro` reason before answering, which adds latency. Use `deepseek-chat` for latency-sensitive paths. ### Tool calls failing with thinking on DeepSeek's [thinking mode guide](https://api-docs.deepseek.com/guides/thinking_mode) says each turn's `reasoning_content` must be sent back on every later request once tools are in play, and that the API returns `400` otherwise. NeuroLink does this for you: the DeepSeek catalog entry sets `quirks.replayReasoningContent`, so both `generate()` and `stream()` send the reasoning back on each follow-up request. (Tested live on 2026-09-26, the API accepted follow-ups with or without it, but NeuroLink follows the documented contract.) If a tool loop still fails, check whether you are replaying conversation history yourself without each assistant turn's reasoning. For tool-heavy workflows where you don't need the reasoning, `deepseek-chat` keeps thinking off. --- ## See Also - [Implementation spec](/docs/provider-integration/02-deepseek) — internal wire-format details and design decisions - [OpenAI Compatible provider](/docs/getting-started/providers/openai-compatible) — generic provider for any OpenAI-compatible endpoint - [LiteLLM provider](/docs/getting-started/providers/litellm) — proxy-based multi-provider access --- **Need Help?** Join the [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## ElevenLabs Music Provider Guide # ElevenLabs Music Provider Guide **Music + sound-effect generation via the ElevenLabs Music / SFX API** ## Quick Start ### 1. Get an API Key [https://elevenlabs.io/app/settings/api-keys](https://elevenlabs.io/app/settings/api-keys) ### 2. Configure ```bash ELEVENLABS_API_KEY=your-key ``` ### 3. Generate Music ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "vertex", output: { mode: "music", music: { provider: "elevenlabs-music", prompt: "Calm cinematic ambient pad, soft piano, slow tempo", duration: 30, }, }, }); if (result.music?.buffer) { writeFileSync("./music.mp3", result.music.buffer); } ``` ### Sound Effects ```typescript const sfx = await ai.generate({ provider: "vertex", output: { mode: "music", music: { provider: "elevenlabs-sound", prompt: "A heavy metal door slamming shut, with reverb", duration: 4, }, }, }); ``` --- ## CLI Usage ```bash pnpm run cli generate "Lo-fi study beat" \ --provider elevenlabs-music \ --musicDuration 60 --musicOutput ./music.mp3 ``` --- ## Configuration Reference | Environment Variable | Required | Description | | -------------------- | -------- | -------------- | | `ELEVENLABS_API_KEY` | Yes | ElevenLabs key | --- ## Troubleshooting - **`401 payment_required`** — your ElevenLabs subscription has an open invoice. Complete payment at [https://elevenlabs.io/app/subscription](https://elevenlabs.io/app/subscription) to re-enable the music endpoint. --- ## See Also - [Beatoven Provider](/docs/getting-started/providers/beatoven) - [Lyria Provider](/docs/getting-started/providers/lyria) - [ElevenLabs TTS](/docs/getting-started/providers/elevenlabs) --- ## ElevenLabs Provider Guide # ElevenLabs Provider Guide **Studio-quality, multilingual text-to-speech with dynamic voice discovery and voice cloning** -------------- | ------------------------------------------------------------------------ | | **Provider ID** | `elevenlabs` | | **API endpoint** | `https://api.elevenlabs.io/v1` | | **Default model** | `eleven_multilingual_v2` | | **Default voice** | Rachel (`21m00Tcm4TlvDq8ikWAM`) | | **Formats** | mp3 (44.1 kHz), wav (raw PCM 44.1 kHz), ogg/opus (Opus 48 kHz) | | **Max input** | 5,000 characters per request | | **Languages** | 29+ languages per voice (auto-detected from input) | | **Streaming** | Not supported in NeuroLink integration (batch only) | | **STT** | `elevenlabs-stt` (Scribe) — see [Speech-to-Text](#speech-to-text-scribe) | --- ## Quick Start ### 1. Get an API Key Sign up at [https://elevenlabs.io](https://elevenlabs.io) and copy your API key from **Profile → API Key**. ### 2. Configure Environment Add to your `.env` file: ```bash # Required ELEVENLABS_API_KEY=your-api-key-here # Optional: default voice ID (default: Rachel — 21m00Tcm4TlvDq8ikWAM) ELEVENLABS_VOICE_ID=21m00Tcm4TlvDq8ikWAM # Optional: default model (default: eleven_multilingual_v2) ELEVENLABS_MODEL=eleven_multilingual_v2 ``` ### 3. Install NeuroLink ```bash npm install @juspay/neurolink # or pnpm add @juspay/neurolink ``` ### 4. Synthesise Your First Audio ```typescript const ai = new NeuroLink(); const result = await ai.generate({ input: { text: "Hello! This is ElevenLabs speaking through NeuroLink." }, tts: { enabled: true, provider: "elevenlabs", format: "mp3", }, }); if (result.audio) { writeFileSync("output.mp3", result.audio.buffer); console.log(`Saved ${result.audio.size} bytes to output.mp3`); } ``` --- ## Supported Models | Model ID | Description | Use Case | | ------------------------ | --------------------------------------------------------- | --------------------------------- | | `eleven_multilingual_v2` | Default; 29 languages, highest quality | General use, multilingual content | | `eleven_v3` | Most expressive; 70+ languages, accepts `language` | Narration, dialogue | | `eleven_flash_v2_5` | Lowest latency (~75 ms), 32 languages, accepts `language` | Real-time, conversational agents | | `eleven_flash_v2` | Lowest latency, English only | Real-time English | | `eleven_turbo_v2_5` | Fast, 32 languages, accepts `language` | Low-latency multilingual | | `eleven_turbo_v2` | Fast, lower latency variant, English | Real-time applications | | `eleven_monolingual_v1` | English-only, optimised for English naturalness | English-only apps | Pass the model ID explicitly via the `ElevenLabsTTSOptions.model` field or let the integration default to `eleven_multilingual_v2`. **Language pinning.** Set `tts.language` (generic) or `tts.languageCode` (ElevenLabs-specific) to pin the language; a BCP-47 tag such as `en-US` is reduced to `en`. The code is sent on every model except `eleven_multilingual_v2`, the one model the API rejects it on — there it is logged and dropped, and the model auto-detects the language from the text. Models that do not use the field (`eleven_flash_v2`, `eleven_turbo_v2`, `eleven_monolingual_v1`) ignore it server-side rather than failing. --- ## SDK Usage ### Direct Text Synthesis Synthesise the input text without calling an AI model: ```typescript const ai = new NeuroLink(); const result = await ai.generate({ input: { text: "ElevenLabs produces natural-sounding speech in 29 languages.", }, tts: { enabled: true, provider: "elevenlabs", format: "mp3", }, }); if (result.audio) { console.log("Format:", result.audio.format); console.log("Size:", result.audio.size, "bytes"); console.log("Provider:", result.audio.metadata?.provider); } ``` ### Specifying a Voice Voices are identified by their `voice_id` string. Use a known ID directly, or list available voices programmatically (see [Voice Discovery](#voice-discovery)): ```typescript const result = await ai.generate({ input: { text: "A specific voice selected by ID." }, tts: { enabled: true, provider: "elevenlabs", voice: "21m00Tcm4TlvDq8ikWAM", // Rachel — the default format: "mp3", }, }); ``` ### AI Response Synthesis Generate a response with an AI model and then synthesise it: ```typescript const result = await ai.generate({ provider: "openai", input: { text: "Explain quantum computing in two sentences." }, tts: { enabled: true, provider: "elevenlabs", mode: "response", // Synthesise the AI-generated text, not the prompt voice: "21m00Tcm4TlvDq8ikWAM", format: "mp3", }, }); ``` ### Multilingual Synthesis ElevenLabs detects the language of your input automatically. No extra configuration is needed: ```typescript // Spanish await ai.generate({ input: { text: "Buenos días. ¿Cómo puedo ayudarte hoy?" }, tts: { enabled: true, provider: "elevenlabs", format: "mp3" }, }); // French await ai.generate({ input: { text: "Bonjour! Comment puis-je vous aider?" }, tts: { enabled: true, provider: "elevenlabs", format: "mp3" }, }); // Hindi await ai.generate({ input: { text: "नमस्ते! मैं आपकी कैसे सहायता कर सकता हूँ?" }, tts: { enabled: true, provider: "elevenlabs", format: "mp3" }, }); ``` ### Voice Settings Tuning Fine-tune the voice character using ElevenLabs-specific options: ```typescript const result = await ai.generate({ input: { text: "Fine-tuned voice output." }, tts: { enabled: true, provider: "elevenlabs", voice: "21m00Tcm4TlvDq8ikWAM", format: "mp3", // ElevenLabs-specific settings (cast required for typed access) stability: 0.6, // 0–1: higher = more consistent, lower = more expressive similarityBoost: 0.8, // 0–1: how closely to match the original voice style: 0.2, // 0–1: style exaggeration (v2 models only) useSpeakerBoost: true, // Boost speaker clarity speed: 1.1, // 0.7–1.2 on ElevenLabs; values outside are clamped with a warning voiceSettings: { stability: 0.7 }, // raw voice_settings passthrough; wins on conflict } as ElevenLabsTTSOptions, }); ``` `speed` is the generic `TTSOptions.speed` (0.25–4.0). ElevenLabs accepts only 0.7–1.2, so out-of-range values are clamped into that band — with a `logger.warn` — rather than rejected. ### Bitrates, timeouts and retries ```typescript tts: { enabled: true, provider: "elevenlabs", format: "ogg", // → opus_48000_ opusBitrate: 96, // 32 | 64 | 96 | 128 | 192 (default 64) mp3Bitrate: 192, // 32 | 64 | 96 | 128 | 192 (default 128), used when format is mp3 timeoutMs: 20_000, // per attempt (default 30 000) retries: 2, // after the first attempt (default 1) baseUrl: "https://api.elevenlabs.io/v1", // override, e.g. a proxy } as ElevenLabsTTSOptions ``` A request is retried on `429`, any `5xx`, a per-attempt timeout or a transport error (a refused or reset connection, a DNS failure), honouring `Retry-After` when the response carries one (capped at 10 s) and backing off exponentially from 500 ms otherwise. A `4xx` other than `429` fails immediately and is marked non-retriable, as does anything thrown before a request exists (a malformed `baseUrl`). `generate()`'s own synthesis timeout is raised to at least `timeoutMs × (1 + retries)` plus pause slack — using the defaults above (30 s, one retry) for any knob you leave unset — so the handler's retry loop is never cut short from outside, including on a default call. To stop early, pass an `abortSignal` to `generate()` (or `signal` on the TTS options when calling the handler directly): the attempt in flight is aborted and no further attempt is made. `timeoutMs` is capped at 2³¹−1 ms, the largest delay a timer honours. An `mp3Bitrate` / `opusBitrate` outside the listed values falls back to the default with a warning rather than being sent. ### Save to File ```typescript const result = await ai.generate({ input: { text: "Saving ElevenLabs audio to disk." }, tts: { enabled: true, provider: "elevenlabs", voice: "21m00Tcm4TlvDq8ikWAM", format: "mp3", output: "./audio/output.mp3", // NeuroLink saves automatically if set }, }); ``` ### Per-Call Credential Override ```typescript const result = await ai.generate({ input: { text: "Using a per-request API key." }, tts: { enabled: true, provider: "elevenlabs", }, credentials: { elevenlabs: { apiKey: "user-specific-elevenlabs-key", }, }, }); ``` --- ## CLI Usage ### Basic TTS ```bash # Synthesise text using ElevenLabs neurolink generate "Hello from ElevenLabs!" --tts --tts-provider elevenlabs # Save to file neurolink generate "Saving to disk." \ --tts --tts-provider elevenlabs \ --tts-output output.mp3 ``` ### Choose a Voice ```bash neurolink generate "Custom voice ID." \ --tts --tts-provider elevenlabs \ --tts-voice 21m00Tcm4TlvDq8ikWAM ``` ### Synthesise AI Response ```bash neurolink generate "Write a product tagline for a fintech app." \ --provider openai \ --tts --tts-provider elevenlabs \ --tts-use-ai-response \ --tts-output tagline.mp3 ``` ### Multilingual ```bash neurolink generate "Bonjour! Comment puis-je vous aider?" \ --tts --tts-provider elevenlabs \ --tts-output french.mp3 ``` --- ## Voice Discovery ElevenLabs voices are fetched dynamically from your account. The result includes both the ElevenLabs library voices and any custom or cloned voices in your account. ```typescript try { const handler = new ElevenLabsTTS(process.env.ELEVENLABS_API_KEY); const voices = await handler.getVoices(); for (const voice of voices) { console.log(`${voice.id} — ${voice.name} (${voice.gender})`); } } catch (error) { console.error( "Failed to fetch voices:", error instanceof Error ? error.message : String(error), ); } ``` Voices are cached for **5 minutes** per handler instance to avoid redundant API calls. --- ## Supported Languages `eleven_multilingual_v2` supports 29 languages. The following are recognised by the NeuroLink voice metadata: | Code | Language | | ---- | ---------- | | `en` | English | | `es` | Spanish | | `fr` | French | | `de` | German | | `it` | Italian | | `pt` | Portuguese | | `pl` | Polish | | `hi` | Hindi | | `ar` | Arabic | | `zh` | Chinese | | `ja` | Japanese | | `ko` | Korean | For the full language list, refer to the [ElevenLabs documentation](https://elevenlabs.io/docs/api-reference/how-to-use-tts-with-streaming). --- ## Audio Formats | Format | Extension | ElevenLabs `output_format` | Sample Rate | `audio.format` | | ------ | --------- | -------------------------------- | ----------- | -------------- | | `mp3` | `.mp3` | `mp3_44100_` (128) | 44,100 Hz | `mp3` | | `wav` | `.wav` | `pcm_44100` — raw PCM, no header | 44,100 Hz | `pcm16` | | `ogg` | `.ogg` | `opus_48000_` (64) | 48,000 Hz | `opus` | | `opus` | `.opus` | `opus_48000_` (64) | 48,000 Hz | `opus` | ElevenLabs has no `ogg_*` output family — Ogg/Opus is `opus_48000_`. Earlier NeuroLink releases sent `ogg_22050` for `ogg`/`opus`, which the API rejects with a 422; that is fixed. The returned Ogg container starts with the `OggS` page marker and an `OpusHead` packet. `wav` output is **headerless** PCM (reported as `pcm16`): wrap it with `createWavFile()` from `@juspay/neurolink/voice` before writing a `.wav` file, and pass the sample rate — `createWavFile` defaults to 16 kHz, while ElevenLabs PCM is 44.1 kHz, so a header written with the default plays 2.76× slow and low: ```typescript const result = await ai.generate({ input: { text: "Raw PCM, wrapped as WAV." }, tts: { enabled: true, provider: "elevenlabs", format: "wav" }, }); if (result.audio) { writeFileSync( "out.wav", createWavFile(result.audio.buffer, result.audio.sampleRate), // 44100 ); } ``` --- ## Configuration Reference | Environment Variable | Required | Default | Description | | --------------------- | -------- | ------------------------------ | ----------------------------------------------- | | `ELEVENLABS_API_KEY` | Yes | — | ElevenLabs API key (shared by TTS, STT, music) | | `ELEVENLABS_BASE_URL` | No | `https://api.elevenlabs.io/v1` | API base URL including `/v1` (proxies, tests) | | `ELEVENLABS_VOICE_ID` | No | `21m00Tcm4TlvDq8ikWAM` | Default voice (Rachel); a per-call `voice` wins | | `ELEVENLABS_MODEL` | No | `eleven_multilingual_v2` | Default TTS model; a per-call `model` wins | --- ## Feature Support Matrix | Feature | Supported | Notes | | ---------------------- | --------- | ------------------------------------------------------------------- | | Text synthesis | Yes | | | AI response synthesis | Yes | Set `mode: "response"` | | Multilingual support | Yes | 29 languages, auto-detected | | Language pinning | Yes | `language` (ISO 639-1; `en-US` → `en`) on all but `multilingual_v2` | | Voice discovery | Yes | Dynamic API fetch, 5-minute cache | | Custom / cloned voices | Yes | Pass voice ID from your ElevenLabs account | | Voice stability tuning | Yes | `stability`, `similarityBoost`, `style`, `voiceSettings` | | Multiple formats | Yes | mp3 (bitrate), raw pcm, opus 48 kHz (bitrate) | | Streaming TTS | No | Batch synthesis only in NeuroLink | | Speed control | Yes | `speed`, clamped to 0.7–1.2 | | Retries | Yes | `retries` (default 1) on 429/5xx/timeout, honours `Retry-After` | | Speech-to-text | Yes | `elevenlabs-stt` (Scribe), aliases `scribe`, `elevenlabs` | --- ## Speech-to-Text (Scribe) The same key also unlocks ElevenLabs Scribe for batch transcription. The STT handler is registered as `elevenlabs-stt`, with `scribe` and `elevenlabs` as aliases — the STT and TTS registries are separate, so `stt: { provider: "elevenlabs" }` and `tts: { provider: "elevenlabs" }` resolve to different handlers. ```typescript const result = await ai.generate({ input: { text: "Summarise what was said." }, stt: { enabled: true, audio: readFileSync("./meeting.mp3"), provider: "elevenlabs", // or "elevenlabs-stt" / "scribe" format: "mp3", speakerDiarization: true, // → diarize=true speakerCount: 2, // → num_speakers=2 // language: "en", // → language_code; omit to auto-detect // model: "scribe_v2_medical", // default scribe_v2 // tagAudioEvents: true, // "(laughter)" etc. — NeuroLink sends false by default } as ElevenLabsSTTOptions & { audio: Buffer }, }); result.transcription?.text; // full transcript result.transcription?.words; // [{ word, startTime, endTime, speaker }] result.transcription?.speakers; // ["speaker_0", "speaker_1"] result.transcription?.language; // "eng" ``` Request shape: `POST {baseUrl}/speech-to-text`, header `xi-api-key`, multipart fields `file`, `model_id` (default `scribe_v2`; `scribe_v1` is deprecated by ElevenLabs and any newer id can be passed as a string), `language_code` (only when you set `language`; a BCP-47 tag like `en-US` is reduced to `en`), `tag_audio_events` (`false` unless `tagAudioEvents: true`), `diarize`, `num_speakers`. Spacing and audio-event entries in Scribe's `words[]` are dropped from `transcription.words`; `speaker_id` becomes `speaker`. `transcription.confidence` is the mean per-word `exp(logprob)` over the spoken words when Scribe reports one; when no word carries a `logprob` it falls back to `language_probability`, and to `0` when that is missing too. `transcription.metadata.confidenceSource` says which it was — `"word_logprobs"`, `"language_probability"` or `"none"` — because Scribe's `language_probability` measures how sure it is of the _language_, not the words (garbled and clean audio both score ~0.99), and it is always exposed under its own name as `transcription.metadata.languageProbability`. `timeoutMs` (default 60 000, covering the response body as well as the headers) and `baseUrl` are accepted on the same options. Scribe is batch-only: `supportsStreaming` is `false` and there is no `transcribeStream`. CLI (`--stt` is a flag; the file goes in `--input-audio`): ```bash neurolink generate "Summarise" --stt --stt-provider elevenlabs-stt --input-audio ./meeting.mp3 ``` --- ## Troubleshooting ### "ElevenLabs API key not configured" The `ELEVENLABS_API_KEY` environment variable is missing or was not loaded. ```bash echo $ELEVENLABS_API_KEY export ELEVENLABS_API_KEY=your-key-here ``` Retrieve your key from [https://elevenlabs.io/app/settings/api-keys](https://elevenlabs.io/app/settings/api-keys). ### "HTTP 401" — Unauthorised Your API key is invalid or has been revoked. Generate a new key from the ElevenLabs dashboard. ### "HTTP 429" — Rate limit or quota exceeded You have reached your character quota for the billing period, or exceeded the per-minute request rate. Check your usage at [https://elevenlabs.io/app/subscription](https://elevenlabs.io/app/subscription). ### "HTTP 400" — Request too long The input text exceeds 5,000 characters. Split the content into chunks: ```typescript function chunkText(text: string, maxLen = 4500): string[] { const chunks: string[] = []; for (let i = 0; i `. ### Voice not found You passed a `voice` ID that does not exist in your account. List available voices to confirm: ```typescript const handler = new ElevenLabsTTS(); const voices = await handler.getVoices(); console.log(voices.map((v) => `${v.id}: ${v.name}`).join("\n")); ``` ### "Failed to get voices" Voice discovery failed (network error or invalid key). The 5-minute cache shields against transient failures, but a hard failure at startup will propagate. Ensure `ELEVENLABS_API_KEY` is valid and the ElevenLabs API is reachable. --- ## See Also - [TTS Integration Guide](/docs/features/tts) — complete multi-provider TTS reference - [OpenAI TTS Provider Guide](/docs/getting-started/providers/openai-tts) — alternative TTS provider - [Audio Input (STT)](/docs/features/audio-input) — speech-to-text counterpart - [Voice Agent Guide](/docs/features/voice-agent) — building full voice assistants --- **Need Help?** Join the [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## EmpirioLabs AI Provider Guide # EmpirioLabs AI Provider Guide [EmpirioLabs AI](https://empiriolabs.ai) is a specialized AI inference and integration provider. It hosts open-source models on GPU infrastructure it manages, runs optimized endpoints for proprietary models, helps teams ship their own models, and offers on-demand GPU Cloud instances and hosted AI agents. Its model catalog spans text, image, audio, video, transcription, embedding, reranking, research and 3D models. API reference and guides are in the [EmpirioLabs AI docs](https://docs.empiriolabs.ai). In NeuroLink, EmpirioLabs AI is a **Tier-2 catalog provider**: it speaks the OpenAI wire format, so its entire integration is one JSON file (`src/lib/providers/catalog/empiriolabs.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status: docs- and roster-verified, not yet live-verified.** > This entry was onboarded credential-free — no API key was created and no > chat, streaming or tool-call request was ever sent. Everything below comes > from the vendor's own public docs (docs.empiriolabs.ai) and an > **unauthenticated** `GET /v1/models` call. `evidence.liveMatrix` is `null` > in the catalog file until someone runs the live capability sweep with a > real key (see [Live verification](/docs/provider-integration/tiers/tier-2-catalog-entry#live-verification)). ## Quick Start ### 1. Get an API key 1. Visit: https://platform.empiriolabs.ai and create an account 2. Create an API key from the dashboard (keys use the `sk-empiriolabs-` prefix, up to 50 per account) 3. Selected models (e.g. GLM 4.7 Flash) run at $0 cost; other models draw from prepaid credits topped up via the dashboard Billing page — confirm current pricing before heavy use 4. Set `EMPIRIOLABS_API_KEY` in your .env file ### 2. Configure ```bash export EMPIRIOLABS_API_KEY=sk-empiriolabs-your-api-key export EMPIRIOLABS_MODEL=glm-5-3 # optional — overrides the default model export EMPIRIOLABS_BASE_URL=https://api.empiriolabs.ai/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "empiriolabs", model: "glm-5-3", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider empiriolabs ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "empiriolabs", credentials: { empiriolabs: { apiKey: process.env.EMPIRIOLABS_API_KEY } }, }); ``` --- ## Models | Model | Context | Max out | Vision | Structured output | $/M in · out (cached) | Notes | | ------------------------ | ------- | ------- | ------ | ----------------- | ----------------------- | ------------------------------------------------------------------------------------------------------- | | `glm-5-3` ⭐ | 1M | 131,072 | no | `json_object` | $1.40 / $4.40 ($1.40) | Recommended — roster `is_featured: true`; reasoning, function calling, web search. | | `glm-5-3-flash` | 1M | 131,072 | yes | `json_object` | $0.075 / $0.25 ($0.075) | Lighter/cheaper sibling; also vision (`document_understanding`, `video_understanding`); fallback. | | `glm-5-2` | 1M | 131,072 | no | `json_object` | $1.40 / $4.40 ($1.40) | Prior GLM generation; fallback. | | `kimi-k3` | 1M | 131,072 | yes | `json_schema` | $3.00 / $15.00 ($3.00) | Moonshot Kimi K3 — multimodal, agentic coding; strict schema output; fallback. | | `qwen3-7-max` | 1M | 65,536 | no | `json_schema` | $2.50 / $7.50 ($2.50) | Alibaba flagship reasoning model with code interpreter; lower max output than the GLM family; fallback. | | `minimax-m2-7-highspeed` | 200K | 32,768 | no | `json_object` | $0.30 / $1.20 ($0.03) | Smallest context/output in this set; lightest/cheapest fallback. | All context, output, pricing and structured-output values above are read directly from the unauthenticated `GET https://api.empiriolabs.ai/v1/models` response (2026-09-28), not invented or estimated. This 6-model set is a curated subset — the full roster returned 217 ids spanning text, vision, audio, video, image and 3D-generation models; only text/chat-completions models with documented `function_calling` are catalogued here. **Fallback order** when the default is unavailable: `glm-5-3-flash` → `glm-5-2` → `kimi-k3` → `qwen3-7-max` → `minimax-m2-7-highspeed`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for EmpirioLabs AI: | Probe | Result | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | **unauthenticated** `GET /v1/models`, HTTP 200, 217 models, 2026-09-28. No API key was created or used. | | Auth rejection | Not probed (would require a key). Documented shape only: `docs.empiriolabs.ai/authentication` states a missing/malformed/unknown token returns `401 Unauthorized`. | | Wire compatibility | Documented only: `docs.empiriolabs.ai/compatibility` states the endpoint "accepts the same request body as the OpenAI Chat Completions API" and lists `messages`, `model`, `stream`, `temperature`, `max_tokens`, `response_format` as supported. | | Live capability sweep | **Not run.** `evidence.liveMatrix` is `null`. No chat, streaming, tool-call or structured-output request has been sent to this vendor. | Because no live probe was possible, `capabilities.toolsWithStreaming` and `capabilities.structuredOutputWithTools` are conservatively `false`, and `capabilities.tools` is `"model-dependent"` rather than an unqualified `true` — the roster shows `function_calling` on 97 of 217 models, not the whole catalog. Whoever runs the live matrix next should re-check these flags against real responses, per [Live verification](/docs/provider-integration/tiers/tier-2-catalog-entry#live-verification). --- ## Documented quirks worth knowing (not catalog quirks) - **Implicit system prompt**: EmpirioLabs AI docs say every chat model has a built-in identity message that is prepended automatically when your request has no `system`/`developer` role message. Supplying your own system message fully replaces it (no merging). This doesn't require a named catalog `quirks` entry — it only changes behavior when you omit a system message — but it's worth knowing if a completion reads oddly "in character." - **`response_format` is per-model**: sending a structured-output format a model doesn't support returns `HTTP 400` per the vendor's docs. Check `GET /v1/models/{modelId}` for a given model's `structured_output` value (`json_schema`, `json_object`, or absent) before relying on it. --- ## Troubleshooting | Symptom | Cause | Fix | | ------------------------------------------------------ | --------------------------------------------------------------------- | --------------------------------------------------------------------------------- | | `Invalid EmpirioLabs API key` | `EMPIRIOLABS_API_KEY` unset or wrong | Check the key at https://platform.empiriolabs.ai | | `401 Unauthorized` | Token missing, malformed, or not found (per vendor docs) | Confirm the header is `Authorization: Bearer sk-empiriolabs-...` | | `402 Payment Required` (documented, not live-verified) | Account has insufficient prepaid credits | Top up credits via the dashboard Billing page, or pick a $0 free model | | `429 Too Many Requests` | Rate limit exceeded (new accounts: 50 RPM / 2,000,000 TPM) | Retry with exponential backoff, or email support@empiriolabs.ai for higher limits | | `HTTP 400` on `response_format` | The chosen model doesn't support the requested structured-output mode | Check `GET /v1/models/{modelId}` for that model's `structured_output` value | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration, including the live-verification steps this entry still needs - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Featherless AI Provider Guide # Featherless AI Provider Guide Featherless AI is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/featherless-ai.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** Every field below comes from Featherless's own published > docs and an unauthenticated `GET /v1/models` call — no API key was used to > write this entry, so no request-response wire behavior (streaming, tool > calling, structured output) has actually been exercised end to end yet. See > [Verification status](#verification-status) for exactly what was and was > not checked. ## Quick Start ### 1. Get an API key 1. Visit: https://featherless.ai/register and create an account (or https://featherless.ai/login if you already have one) 2. Subscribe to a plan — Chat ($25/mo, unlimited tokens, 32K context) or Developer ($50/mo in credits, billed per token, up to 256K context); Featherless has no free or keyless tier 3. Generate an API key from the API keys section of your account 4. Set `FEATHERLESS_AI_API_KEY` in your .env file ### 2. Configure ```bash export FEATHERLESS_AI_API_KEY=your-api-key export FEATHERLESS_AI_MODEL=unsloth/Llama-3.3-70B-Instruct # optional — overrides the default model export FEATHERLESS_AI_BASE_URL=https://api.featherless.ai/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "featherless-ai", model: "unsloth/Llama-3.3-70B-Instruct", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider featherless-ai ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "featherless-ai", credentials: { "featherless-ai": { apiKey: process.env.FEATHERLESS_AI_API_KEY }, }, }); ``` --- ## Models Featherless's live roster is enormous — 22,060 models as of 2026-09-28, spanning mainline instruction-tuned checkpoints alongside a very large number of community roleplay, uncensored and "abliterated" (safety-refusal-removed) fine-tunes; Featherless's own site markets these as first-class catalog filters ("LLMs for Roleplay", "Uncensored Models", "Abliterated Models"). This catalog entry lists 12 models — a bounded, verifiable slice, not the whole roster — chosen to include the default, its closest official counterpart, and a representative spread of the architectures Featherless serves (Llama-3.3-70B family, QRWKV, RWKV5). | Model | Context | Vision | $/M in · out | Notes | | ---------------------------------------------- | ------- | ------ | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `unsloth/Llama-3.3-70B-Instruct` ⭐ | 32K | no | $2.60 / $3.00 | Recommended — an ungated community re-upload of Meta's Llama 3.3 70B Instruct. Chosen as default because the official `meta-llama` id is gated (see below). Roster reports `tool_use: true`. | | `meta-llama/Llama-3.3-70B-Instruct` | 32K | no | $0.65 / $0.75 | Meta's official weights. Hugging-Face-gated on Featherless (HTTP 403 until unlocked in the account UI) — kept as a fallback, not the default. | | `Sao10K/L3.3-70B-Euryale-v2.3` | 32K | no | $0.65 / $0.75 | Roleplay/long-form-writing Llama-3.3-70B fine-tune. Not gated; roster-listed only. | | `EVA-UNIT-01/EVA-LLaMA-3.33-70B-v0.0` | 32K | no | $2.60 / $3.00 | Creative-writing/roleplay Llama-3.3-70B fine-tune. Not gated; roster-listed only. | | `EVA-UNIT-01/EVA-LLaMA-3.33-70B-v0.1` | 32K | no | $2.60 / $3.00 | Later revision of the EVA-LLaMA line above. Not gated; roster-listed only. | | `KaraKaraWitch/Llama-MiraiFanfare-3.3-70B` | 32K | no | $2.60 / $3.00 | Community Llama-3.3-70B fine-tune. Not gated; roster-listed only. | | `huihui-ai/Llama-3.3-70B-Instruct-abliterated` | 32K | no | $0.65 / $0.75 | Safety-refusal-ablated Llama 3.3 70B Instruct. Not gated; roster-listed only. | | `recursal/QRWKV6-32B-Instruct-Preview-v0.1` | 32K | no | $0.27 / $0.65 | Non-transformer RWKV-hybrid architecture; one of the few model classes Featherless's docs call out at the 32K context tier. Not gated; roster-listed only. | | `RWKV/v6-Finch-14B-HF` | 16K | no | $0.11 / $0.28 | RWKV v6 "Finch" 14B, non-transformer architecture. Not gated; roster-listed only. | | `RWKV/EagleX-7B-Chat-V0.5-pth` | 16K | no | $0.10 / $0.20 | Early RWKV5-architecture chat checkpoint. Not gated; roster-listed only. | | `recursal/EagleX_1-7T_Chat` | 16K | no | $0.10 / $0.20 | RWKV5-architecture, chat-tuned. Not gated; roster-listed only. | | `recursal/EagleX_1-7T` | 16K | no | $0.10 / $0.20 | RWKV5-architecture base checkpoint (non-chat-tuned). Not gated; roster-listed only. | Context window and pricing come directly from the live, unauthenticated `GET /v1/models` response (`context_length`, `pricing.input`/`pricing.output`, already expressed as $ per million tokens) fetched 2026-09-28 — not from invented numbers. Featherless does not document a per-request output-token ceiling anywhere in its docs (`max_tokens` is described only as "Maximum number of tokens generated per output sequence", with no number given), so `defaultMaxOutputTokens` (4096) follows the same conservative, undocumented-cap convention already used by several other catalog entries (Fireworks, Groq, Mistral, Novita, Perplexity, Together AI, xAI) rather than a Featherless-specific figure. **Fallback order** when the default is unavailable: `meta-llama/Llama-3.3-70B-Instruct` → `Sao10K/L3.3-70B-Euryale-v2.3` → `EVA-UNIT-01/EVA-LLaMA-3.33-70B-v0.0` → `EVA-UNIT-01/EVA-LLaMA-3.33-70B-v0.1` → `KaraKaraWitch/Llama-MiraiFanfare-3.3-70B` → `huihui-ai/Llama-3.3-70B-Instruct-abliterated` → `recursal/QRWKV6-32B-Instruct-Preview-v0.1` → `RWKV/v6-Finch-14B-HF` → `RWKV/EagleX-7B-Chat-V0.5-pth` → `recursal/EagleX_1-7T_Chat` → `recursal/EagleX_1-7T`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This entry was built **entirely credential-free** — no signup, no API key, no POST request to Featherless was made — so it records what a public, unauthenticated pass can prove and nothing more: | Probe | Result | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /v1/models`, HTTP 200, 22,060 models, 2026-09-28 | | Billing | unauthenticated `GET https://featherless.ai/pricing`, HTTP 200, 2026-09-28 — no free tier found anywhere on the page; plans start at $25/mo | | Auth rejection | **not probed** — would require a POST request, which credential-free onboarding does not permit | | Live capability sweep | **not run** (`evidence.liveMatrix` is `null`) — chat, streaming, tool calling and structured output are all unverified against a real request | | Docs pages read | Overview, API overview and common options, Completions (`/v1/chat/completions` and `/v1/completions`), Quickstart guide, API examples and snippets, Tool Calling, Embeddings, Vision, Chat template kwargs, Models & Model Compatibility, Error codes, Pricing — none of these documents `response_format` or `stream:true` for chat/text completions | Because of this, `capabilities.streaming`, `capabilities.structuredOutput`, and `capabilities.structuredOutputWithTools` are all conservatively `false`, and `capabilities.tools` is `"model-dependent"` (Featherless's own Tool Calling guide frames it that way, naming only `moonshotai/Kimi-K2-Instruct` and the `Qwen 3` family as natively supported). A live-verification pass with a real API key — `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=featherless-ai` — is required before any of these flags should be promoted, per [Tier-2 onboarding: Live verification](/docs/provider-integration/tiers/tier-2-catalog-entry#live-verification). --- ## Troubleshooting | Symptom | Cause | Fix | | ------------------------------------------- | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Invalid Featherless API key` | `FEATHERLESS_AI_API_KEY` unset or wrong | Check the key in your Featherless account at https://featherless.ai/register | | HTTP 403, "model is gated" | The requested model (e.g. `meta-llama/Llama-3.3-70B-Instruct`) is Hugging-Face-gated on Featherless | Open the model's page on featherless.ai while signed in and click "Unlock Model" to accept its license, or use the ungated `unsloth/Llama-3.3-70B-Instruct` default instead | | Model not found | The roster changed since 2026-09-28, or the id was mistyped | Pick a current id from the unauthenticated `GET /v1/models` roster or https://featherless.ai/models | | HTTP 400, "This Model is Cold" | Featherless documents cold/loading/warm model states; a cold model needs to load | Retry — warm-up can take from a few minutes up to an hour for very large models, per Featherless's error-codes page | | HTTP 503, "Service Temporarily Unavailable" | Featherless documents this as insufficient capacity, not downtime | Retry the same request; Featherless's own guidance is to retry up to three times | | Unexpected billing | No free or keyless tier exists | Confirm plan choice at https://featherless.ai/#pricing before heavy use — Chat is a flat $25/mo, Developer is metered credits | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Fireworks AI Provider Guide # Fireworks AI Provider Guide **Open-model inference tuned for low-latency production workloads** ## Quick Start ### 1. Get an API Key [https://fireworks.ai/account/api-keys](https://fireworks.ai/account/api-keys) ### 2. Configure Environment ```bash FIREWORKS_API_KEY=fw_your-key FIREWORKS_MODEL=accounts/fireworks/models/kimi-k3 ``` ### 3. Generate ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "fireworks", input: { text: "Summarise the Raft consensus algorithm." }, }); console.log(result.content); ``` --- ## Supported Models (sample) | Model ID | Vision | Notes | | ---------------------------------------- | ------ | ----------------------------------- | | `accounts/fireworks/models/kimi-k3` | Yes | Default — newest Moonshot flagship | | `accounts/fireworks/models/gpt-oss-120b` | No | Text fallback (`fallbackModelName`) | | `accounts/fireworks/models/qwen3p8-max` | Yes | Qwen flagship | | `accounts/fireworks/models/glm-5p3` | No | Rejects image inputs | Fireworks lists models on `/models` that are not deployed for serverless use, so the catalog only keeps ids that answered a real chat call. `kimi-k2p6`, the default until September 2026, now returns 404 `not deployed` and is retired. Browse: [https://fireworks.ai/models](https://fireworks.ai/models) --- ## CLI Usage ```bash pnpm run cli generate "..." --provider fireworks pnpm run cli generate "..." --provider fireworks --model accounts/fireworks/models/qwen3p8-max ``` --- ## Provider Aliases | Alias | Example | | ----------- | ---------------------- | | `fireworks` | `--provider fireworks` | --- ## Configuration Reference | Environment Variable | Required | Default | | -------------------- | -------- | --------------------------------------- | | `FIREWORKS_API_KEY` | Yes | — | | `FIREWORKS_MODEL` | No | `accounts/fireworks/models/kimi-k3` | | `FIREWORKS_BASE_URL` | No | `https://api.fireworks.ai/inference/v1` | --- ## Troubleshooting - **`Model not found, inaccessible, and/or not deployed`** — your account has not deployed the requested model. Check [https://fireworks.ai/models](https://fireworks.ai/models) and either deploy it or pick a serverless one. --- ## See Also - [Together AI Provider](/docs/getting-started/providers/together-ai) - [Groq Provider](/docs/getting-started/providers/groq) --- ## Fish Audio TTS Provider Guide # Fish Audio TTS Provider Guide **Low-cost text-to-speech — S2 Pro voice cloning, multilingual, ~80% cheaper than ElevenLabs** ## Quick Start ### 1. Get an API Key Sign up at [https://fish.audio/](https://fish.audio/) and create an API key from the dashboard. ### 2. Configure Environment ```bash # Required FISH_AUDIO_API_KEY=... # Optional: override the default voice (any reference_id from the Fish library) # FISH_AUDIO_VOICE_ID=... # Optional: override the base URL # FISH_AUDIO_BASE_URL=https://api.fish.audio ``` ### 3. Synthesize Your First Audio ```typescript const ai = new NeuroLink(); const result = await ai.generate({ // The LLM provider doesn't matter — TTS-only flows skip the LLM call // when `tts.useAiResponse` is false (default) provider: "openai", input: { text: "Hello world from Fish Audio" }, tts: { enabled: true, provider: "fish-audio", format: "mp3", }, }); if (result.audio) { writeFileSync("./hello.mp3", result.audio.buffer); } ``` --- ## SDK Usage ### Basic Synthesis (Default Voice) ```typescript const result = await ai.generate({ provider: "openai", input: { text: "The quick brown fox jumps over the lazy dog." }, tts: { enabled: true, provider: "fish-audio" }, }); ``` ### Custom Voice (Voice Cloning) Get a `reference_id` from your Fish Audio dashboard after uploading 15s of reference audio: ```typescript const result = await ai.generate({ provider: "openai", input: { text: "..." }, tts: { enabled: true, provider: "fish-audio", voice: "your-custom-reference-id", format: "mp3", }, }); ``` ### TTS-Augmented LLM Response When `useAiResponse: true`, NeuroLink first calls the LLM, then synthesizes the LLM output through Fish Audio: ```typescript const result = await ai.generate({ provider: "openai", // generates the text input: { text: "Tell me a 2-sentence joke" }, tts: { enabled: true, provider: "fish-audio", useAiResponse: true, format: "mp3", }, }); console.log(result.content); // joke text writeFileSync("joke.mp3", result.audio.buffer); ``` ### WAV / PCM16 Output ```typescript // WAV (44.1 kHz) const wav = await ai.generate({ provider: "openai", input: { text: "..." }, tts: { enabled: true, provider: "fish-audio", format: "wav" }, }); // PCM16 — raw 16-bit signed-LE PCM, NO RIFF header. Useful for // realtime streaming pipelines that want raw samples. const pcm = await ai.generate({ provider: "openai", input: { text: "..." }, tts: { enabled: true, provider: "fish-audio", format: "pcm16" }, }); ``` ### Per-Call Credentials ```typescript const result = await ai.generate({ provider: "openai", input: { text: "..." }, tts: { enabled: true, provider: "fish-audio" }, credentials: { /* ... no Fish Audio per-call slice yet — set FISH_AUDIO_API_KEY env */ }, }); ``` --- ## CLI Usage ```bash # Basic — default voice + mp3 pnpm run cli generate "Hello world" \ --tts --tts-provider fish-audio \ --output ./hello.mp3 # With a custom voice pnpm run cli generate "Hello world" \ --tts --tts-provider fish-audio \ --tts-voice your-custom-reference-id \ --output ./hello.mp3 # WAV format pnpm run cli generate "Hello world" \ --tts --tts-provider fish-audio \ --tts-format wav --output ./hello.wav ``` --- ## Configuration Reference | Environment Variable | Required | Default | Description | | --------------------- | -------- | ---------------------------------- | -------------------------- | | `FISH_AUDIO_API_KEY` | Yes | — | Fish Audio API key | | `FISH_AUDIO_VOICE_ID` | No | `fb6c0e1ea91e427fb9a93b9bbf0a1e4d` | Default reference_id voice | | `FISH_AUDIO_BASE_URL` | No | `https://api.fish.audio` | Base URL | --- ## Voice Models | Model | Notes | | ------------ | ------------------------------ | | `s1` | Latest, best quality (default) | | `speech-1.6` | Previous flagship | | `speech-1.5` | Older / cheaper | Voices are identified by `reference_id` strings from the Fish library. Browse and clone voices in your Fish Audio dashboard. --- ## Feature Support Matrix | Feature | Fish Audio | | -------------- | --------------------- | | Text-to-speech | Yes | | Voice cloning | Yes (15s reference) | | Multilingual | Yes (14 languages) | | MP3 output | Yes | | WAV output | Yes (44.1 kHz) | | PCM16 output | Yes (raw, no RIFF) | | OPUS output | Falls back to MP3 | | Streaming | No (synchronous only) | | `getVoices()` | Not implemented | --- ## Troubleshooting ### "Invalid Fish Audio API key" ```bash echo $FISH_AUDIO_API_KEY export FISH_AUDIO_API_KEY=... ``` Get / rotate at [https://fish.audio/](https://fish.audio/). ### "Fish Audio rate limit exceeded" Free tier has hourly limits. Upgrade your plan or implement exponential backoff. The handler maps 408 / 429 / 5xx to retriable errors. ### "Fish Audio synthesis failed: 422" Usually means the `reference_id` is invalid or the text is too long (>5000 chars). Truncate the text or check the voice id in your dashboard. ### Audio sounds robotic / low quality Try a higher-quality model (`model: "s1"` if you're on `speech-1.5`) or clone your own reference voice from a 15s clean audio sample. Default voices are generic — voice-cloned reference_ids almost always sound better. ### "PCM16 output is unplayable in audio players" `pcm16` is RAW samples, not WAV — players need a header. To play, write a WAV header yourself (44 bytes) before the PCM data, or use the `wav` format which produces a complete RIFF/WAV file. --- ## See Also - [TTS Feature Guide](/docs/features/tts) — overall TTS architecture and supported providers - [ElevenLabs TTS](/docs/getting-started/providers/elevenlabs) — sibling TTS provider with the largest voice library - [OpenAI TTS](/docs/getting-started/providers/openai-tts) — sibling TTS provider with `tts-1` / `tts-1-hd` - [Adding a TTS provider](/docs/provider-integration/16-adding-tts-provider) — internal reference for the integration pattern --- **Need Help?** Open a [GitHub Discussion](https://github.com/juspay/neurolink/discussions) or [issue](https://github.com/juspay/neurolink/issues). --- ## Flatkey Provider Guide # Flatkey Provider Guide **One API key and one balance across 100+ supported AI models** ## Quick Start ### 1. Get an API Key Create a key at [https://console.flatkey.ai/keys](https://console.flatkey.ai/keys). ### 2. Configure Environment Add to `.env`: ```bash OPENAI_COMPATIBLE_BASE_URL=https://router.flatkey.ai/v1 OPENAI_COMPATIBLE_API_KEY=sk-fk-your-key OPENAI_COMPATIBLE_MODEL=gpt-4o-mini ``` ### 3. Verify the Connection ```bash curl https://router.flatkey.ai/v1/models \ -H "Authorization: Bearer $FLATKEY_API_KEY" ``` ### 4. Generate ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "openai-compatible", input: { text: "Explain vector databases in two sentences." }, }); console.log(result.content); ``` ```bash npx @juspay/neurolink generate "Hello from Flatkey!" --provider openai-compatible --model "gpt-4o-mini" ``` --- ## Model Discovery Flatkey exposes its catalog through the standard endpoint, so NeuroLink's auto-discovery works without extra configuration: ```bash npx @juspay/neurolink models --provider openai-compatible ``` The full catalog is also browsable at [https://flatkey.ai/models](https://flatkey.ai/models). --- ## Configuration Reference | Variable | Required | Description | | ---------------------------- | -------- | ----------------------------------------------------------- | | `OPENAI_COMPATIBLE_BASE_URL` | Yes | Flatkey endpoint — `https://router.flatkey.ai/v1` | | `OPENAI_COMPATIBLE_API_KEY` | Yes | API key from [the console](https://console.flatkey.ai/keys) | | `OPENAI_COMPATIBLE_MODEL` | No | Default model; overridable per request | Flatkey routes to upstream providers, so per-model availability follows the live catalog rather than a fixed list. A machine-readable integration summary is published at [https://flatkey.ai/SKILL.md](https://flatkey.ai/SKILL.md). --- ## Troubleshooting **401 Unauthorized** The key is missing or malformed. Keys start with `sk-fk-` and are issued at [https://console.flatkey.ai/keys](https://console.flatkey.ai/keys). Confirm the value is exported in the environment NeuroLink runs in. **404 on chat completions** Check that `OPENAI_COMPATIBLE_BASE_URL` ends with `/v1`. The gateway follows the OpenAI path layout, so the version segment is part of the base URL. **Model not found** Model IDs must match the live catalog exactly. List what your key can reach: ```bash npx @juspay/neurolink models --provider openai-compatible ``` **Empty or truncated responses** Upstream providers apply their own limits. Try a different model from the catalog to isolate whether the behaviour is model-specific. --- ## See Also - [OpenAI-Compatible Providers Guide](/docs/getting-started/providers/openai-compatible) - [OpenRouter Provider Guide](/docs/getting-started/providers/openrouter) - [LiteLLM Provider Guide](/docs/getting-started/providers/litellm) --- ## FriendliAI Provider Guide # FriendliAI Provider Guide FriendliAI is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/friendli.json`) rather than hand-written code. That file is the source of truth for everything on this page. ## Quick Start ### 1. Get an API key 1. Visit: https://suite.friendli.ai/ and sign in 2. Create a Personal Access Token for the serverless endpoints 3. New accounts start with trial credit; confirm current billing terms in the console before heavy use 4. Set `FRIENDLI_API_KEY` in your .env file ### 2. Configure ```bash export FRIENDLI_API_KEY=your-api-key export FRIENDLI_MODEL=zai-org/GLM-5.3 # optional — overrides the default model export FRIENDLI_BASE_URL=https://api.friendli.ai/serverless/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "friendli", model: "zai-org/GLM-5.3", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider friendli ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "friendli", credentials: { friendli: { apiKey: process.env.FRIENDLI_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | --------------------------- | ------- | ------ | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `zai-org/GLM-5.3` ⭐ | 1M | no | $1.4 / $4.4 (cached $0.26) | Recommended — the only model in this roster capability-probed end to end (real tool call, SSE streaming, json_object). Heavy internal reasoner via `reasoning`/`reasoning_content` — give it a generous `maxTokens`. Rejects image/video input (HTTP 422). | | `zai-org/GLM-5.3-Flash` | 1M | no | — | Lighter/faster sibling of the default; roster-listed only, not itself capability-probed; fallback. | | `zai-org/GLM-5.2` | 1M | no | — | Prior GLM generation; roster-listed only; fallback. | | `zai-org/GLM-5.1` | 1M | no | — | Prior GLM generation; roster-listed only; fallback. | | `google/gemma-4-31B-it` | 1M | no | — | Google Gemma 4 31B instruct-tuned; roster-listed only; fallback. | | `deepseek-ai/DeepSeek-V3.2` | 1M | no | — | DeepSeek V3.2; roster-listed only; fallback. | | `MiniMaxAI/MiniMax-M2.5` | 1M | no | — | MiniMax M2.5; roster-listed only; fallback. | Context window shown is the catalog default of 1,048,576 tokens; the default max output is 131,072 tokens (`zai-org/GLM-5.3`'s documented per-request output ceiling, distinct from the context window). **Fallback order** when the default is unavailable: `zai-org/GLM-5.3-Flash` → `zai-org/GLM-5.2` → `zai-org/GLM-5.1` → `google/gemma-4-31B-it` → `deepseek-ai/DeepSeek-V3.2` → `MiniMaxAI/MiniMax-M2.5`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for FriendliAI: | Probe | Result | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Roster | authenticated GET /serverless/v1/models, HTTP 200, 2026-09-06 | | Auth rejection | HTTP 401, 2026-09-06 | | Live capability sweep | 2026-09-06, probed against the default model (`zai-org/GLM-5.3`) with generous pacing after an initial fast-cadence run tripped Friendli's rate limit. Chat, streaming (SSE, 62 events, terminal `[DONE]`), and a real structured tool call (`finish_reason=tool_calls`) all passed. `response_format: json_object` returned 200; `tools` + a JSON schema together returned HTTP 422. A real image part returned HTTP 422 (`"This model does not support image/video inputs"`). Only the default model was probed end to end; the other 6 roster ids are roster-verified by id only. | --- ## Troubleshooting | Symptom | Cause | Fix | | ------------------------------------------------------ | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | `Invalid Friendli API key` | `FRIENDLI_API_KEY` unset or wrong | Check the key at https://suite.friendli.ai/ | | Model not found | The roster changed since 2026-09-06 | Pick a current id from the authenticated `/serverless/v1/models` roster | | Frequent 429s | Friendli's rate limits are tight | Pace requests at least 20 seconds apart and retry | | Structured output silently dropped when tools are used | Friendli rejects `response_format` when `tools` is present (HTTP 422) | NeuroLink omits `response_format` automatically whenever tools are present, before sending — this is expected, not a bug | | Empty content at a small `maxTokens` | `zai-org/GLM-5.3` spends its budget on `reasoning_content` first | Give reasoning prompts a generous `maxTokens` budget | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## GMI Cloud Provider Guide # GMI Cloud Provider Guide GMI Cloud is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/gmicloud.json`) rather than hand-written code. That file is the source of truth for everything on this page. ## Quick Start ### 1. Get an API key 1. Visit: https://console.gmicloud.ai 2. Sign in and select the Inference service 3. Create an API key; check Console → Inference → Model Hub for current model pricing 4. Set `GMICLOUD_API_KEY` in your .env file ### 2. Configure ```bash export GMICLOUD_API_KEY=your-api-key export GMICLOUD_MODEL=MiniMaxAI/MiniMax-M3 # optional — overrides the default model export GMICLOUD_BASE_URL=https://api.gmi-serving.com/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "gmicloud", model: "MiniMaxAI/MiniMax-M3", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider gmicloud ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "gmicloud", credentials: { gmicloud: { apiKey: process.env.GMICLOUD_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ------------------------- | ------- | ------ | ------------ | -------------------------------------------------- | | `MiniMaxAI/MiniMax-M3` ⭐ | 1M | no | — | MiniMaxAI/MiniMax-M3 — live GMI Cloud-probed model | **Fallback order** when the default is unavailable: `MiniMaxAI/MiniMax-M3`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for GMI Cloud: | Probe | Result | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | authenticated GET /v1/models, HTTP 200, 2026-09-03 | | Auth rejection | HTTP 401, 2026-09-03 | | Live capability sweep | 2026-09-03 — MiniMax-M3 accepted max_completion_tokens=524288 and rejected 1048576 with an explicit 524288 limit. Structured output: the endpoint ignores response_format (json_schema and json_object both return prose with no prompt h | --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------- | ----------------------------------- | ----------------------------------------------------------------- | | `Invalid GMI Cloud API key` | `GMICLOUD_API_KEY` unset or wrong | Check the key at https://console.gmicloud.ai | | Model not found | The roster changed since 2026-09-03 | Pick a current id; catalog providers retire models without notice | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Google AI Studio Provider Guide # Google AI Studio Provider Guide **Direct access to Google's Gemini models with generous free tier and simple API key authentication** ## Quick Start ### 1. Get Your API Key 1. Visit [Google AI Studio](https://aistudio.google.com/) 2. Sign in with your Google account (no GCP project needed) 3. Click **Get API Key** in the top navigation 4. Click **Create API Key** 5. Copy the generated key (starts with `AIza`) ### 2. Configure NeuroLink Add to your `.env` file: ```bash GOOGLE_AI_API_KEY=AIza-your-api-key-here ``` ### 3. Test the Setup ```bash # CLI - Test with default model npx @juspay/neurolink generate "Hello from Google AI!" --provider google-ai # CLI - Use specific Gemini model npx @juspay/neurolink generate "Explain quantum physics" \ --provider google-ai \ --model "gemini-2.5-flash" # SDK node -e " const { NeuroLink } = require('@juspay/neurolink'); (async () => { const ai = new NeuroLink(); const result = await ai.generate({ input: { text: 'Hello from Gemini!' }, provider: 'google-ai' }); console.log(result.content); })(); " ``` --- ## Free Tier Details ### Current Limits (Updated 2025) | Resource | Free Tier Limit | Notes | | ----------------------------- | --------------- | -------------------------------- | | **Requests per Minute (RPM)** | 15 RPM | Per API key | | **Tokens per Minute (TPM)** | 1M TPM | Combined input + output | | **Requests per Day (RPD)** | 1,500 RPD | Rolling 24-hour window | | **Concurrent Requests** | 15 | Max simultaneous requests | | **Context Length** | Up to 1M tokens | Model-dependent (Gemini 2.5 Pro) | ### Free Tier Capacity Estimate ``` Daily Capacity: - 1,500 requests/day × 500 tokens/request = 750K tokens/day - Equivalent to ~300 pages of text per day - Or ~150 detailed conversations Monthly Capacity (30 days): - 45,000 requests/month - ~22.5M tokens/month - Covers most small-medium applications ``` ### When to Upgrade You should consider upgrading to **Vertex AI** when: - ✅ Exceeding 1,500 requests/day consistently - ✅ Need for SLA guarantees - ✅ Enterprise compliance requirements (HIPAA, SOC2) - ✅ Multi-region deployment - ✅ Advanced security features (VPC, customer-managed encryption) - ✅ Fine-tuning custom models --- ## Model Selection Guide ### Available Gemini Models | Model | Model ID | Context Window | Max Output | Multimodal | | --------------------- | ------------------------------- | -------------- | ---------- | ------------------------------- | | Gemini 3.1 Pro | `gemini-3.1-pro-preview` | 1,048,576 | 65,536 | Text, images, audio, video, PDF | | Gemini 3 Flash | `gemini-3-flash-preview` | 1,048,576 | 65,536 | Text, images, audio, video, PDF | | Gemini 3.1 Flash Lite | `gemini-3.1-flash-lite-preview` | 1,048,576 | 65,536 | Text, images, audio, video | | Gemini 2.5 Pro | `gemini-2.5-pro` | 1,048,576 | 65,536 | Text, images, audio, video, PDF | | **Gemini 2.5 Flash** | `gemini-2.5-flash` | 1,048,576 | 65,536 | Text, images, audio, video | | Gemini 2.5 Flash Lite | `gemini-2.5-flash-lite` | 1,048,576 | 65,536 | Text, images, audio, video | :::note[Gemini 3 Models are in Preview] Gemini 3.1 Pro, Gemini 3 Flash, and Gemini 3.1 Flash Lite carry the `-preview` suffix and may change behavior before reaching general availability. Pin to a specific model ID in production and monitor the [Gemini API changelog](https://ai.google.dev/gemini-api/docs/changelog) for graduation announcements and deprecation timelines. ::: ### Deprecated / Retiring Models | Model | Model ID | Status | Notes | | ---------------- | ------------------ | --------------------- | ----------------------------------- | | Gemini 2.0 Flash | `gemini-2.0-flash` | Retiring June 1, 2026 | Migrate to `gemini-2.5-flash` | | Gemini 1.5 Pro | `gemini-1.5-pro` | **SHUT DOWN** | Returns 404. Use `gemini-2.5-pro` | | Gemini 1.5 Flash | `gemini-1.5-flash` | **SHUT DOWN** | Returns 404. Use `gemini-2.5-flash` | ### Embedding Models | Model | Model ID | Dimensions | Multimodal | Status | | -------------------------- | ---------------------------- | ---------- | -------------------------- | ------------------------------ | | Gemini Embedding 001 | `gemini-embedding-001` | 3,072 | Text only | Current default | | Gemini Embedding 2 Preview | `gemini-embedding-2-preview` | 3,072 | Text, images, video, audio | NEW -- preview | | Text Embedding 004 | `text-embedding-004` | 768 | Text only | **Was shut down** Jan 14, 2026 | Configure the embedding model via the `GOOGLE_AI_EMBEDDING_MODEL` environment variable or pass it directly: ```typescript const provider = await ProviderFactory.createProvider("google-ai"); // Use default embedding model (gemini-embedding-001) const embedding = await provider.embed("Hello world"); // Use the new multimodal embedding model const previewEmbedding = await provider.embed( "Hello world", "gemini-embedding-2-preview", ); ``` ### Model Selection by Use Case ```typescript // Extended thinking for complex problems (Gemini 3.1) const deepReasoning = await ai.generate({ input: { text: "Solve this complex mathematical proof..." }, provider: "google-ai", model: "gemini-3.1-pro-preview", // Best reasoning with thinking thinkingConfig: { thinkingLevel: "high" }, // Enable extended thinking }); // Fast reasoning with thinking (Gemini 3 Flash) const fastReasoning = await ai.generate({ input: { text: "Analyze this code and find bugs" }, provider: "google-ai", model: "gemini-3-flash-preview", // Fast + reasoning thinkingConfig: { thinkingLevel: "medium" }, }); // Real-time applications (speed priority) const realtime = await ai.generate({ input: { text: "Quick customer query" }, provider: "google-ai", model: "gemini-2.5-flash", // Fastest response (default) }); // Complex reasoning (quality priority) const complex = await ai.generate({ input: { text: "Analyze this complex business scenario..." }, provider: "google-ai", model: "gemini-2.5-pro", // Most capable }); // Multimodal processing const multimodal = await ai.generate({ input: { text: "Describe this image", images: ["data:image/jpeg;base64,..."], }, provider: "google-ai", model: "gemini-2.5-pro", // Best for multimodal }); // Cost-optimized general tasks const general = await ai.generate({ input: { text: "General customer support query" }, provider: "google-ai", model: "gemini-2.5-flash-lite", // Balanced performance/cost }); ``` ### Context Length Comparison ``` Model Context Limits: - gemini-3.1-pro-preview: 1,048,576 tokens (524 novels) - gemini-3-flash-preview: 1,048,576 tokens (524 novels) - gemini-3.1-flash-lite-preview: 1,048,576 tokens (524 novels) - gemini-2.5-pro: 1,048,576 tokens (524 novels) - gemini-2.5-flash: 1,048,576 tokens (524 novels) - gemini-2.5-flash-lite: 1,048,576 tokens (524 novels) For comparison: - GPT-4 Turbo: 128,000 tokens - Claude 3.5 Sonnet: 200,000 tokens ``` --- ## Extended Thinking (Gemini 3.x and 2.5) Gemini 3.x and 2.5 models support **Extended Thinking**, a feature that allows the model to "think" more deeply before responding. This improves reasoning quality for complex tasks like mathematical proofs, code analysis, and multi-step problem solving. ### Thinking Levels | Level | Description | Use Case | Token Budget | | ----------- | ---------------------------------- | ----------------------------------- | ------------ | | **minimal** | Basic reasoning with minimal usage | Quick decisions, simple queries | ~500 tokens | | **low** | Quick reasoning, minimal overhead | Simple analysis, quick decisions | ~1K tokens | | **medium** | Balanced thinking depth | Code review, moderate complexity | ~8K tokens | | **high** | Deep reasoning, maximum thinking | Complex proofs, architecture design | ~24K tokens | ### Configuration ```typescript const ai = new NeuroLink(); // Enable extended thinking with thinkingLevel const result = await ai.generate({ input: { text: "Prove that the square root of 2 is irrational" }, provider: "google-ai", model: "gemini-3.1-pro-preview", thinkingConfig: { thinkingLevel: "high" }, // 'minimal' | 'low' | 'medium' | 'high' }); console.log(result.content); ``` ### Extended Thinking Examples ```typescript // Mathematical reasoning with high thinking const mathProof = await ai.generate({ input: { text: "Prove the Pythagorean theorem using at least three different methods", }, provider: "google-ai", model: "gemini-3.1-pro-preview", thinkingConfig: { thinkingLevel: "high" }, }); // Code architecture analysis const codeReview = await ai.generate({ input: { text: `Review this code for potential issues and suggest improvements: ${codeSnippet}`, }, provider: "google-ai", model: "gemini-3-flash-preview", thinkingLevel: "medium", }); // Quick analysis with minimal thinking overhead const quickAnalysis = await ai.generate({ input: { text: "What's the time complexity of binary search?" }, provider: "google-ai", model: "gemini-3-flash-preview", thinkingLevel: "low", }); ``` ### CLI Usage with Thinking ```bash # Use Gemini 3.1 with extended thinking npx @juspay/neurolink generate "Solve this logic puzzle..." \ --provider google-ai \ --model "gemini-3.1-pro-preview" \ --thinking-level high # Fast reasoning with medium thinking npx @juspay/neurolink generate "Analyze this code pattern" \ --provider google-ai \ --model "gemini-3-flash-preview" \ --thinking-level medium ``` ### Best Practices for Extended Thinking 1. **Match thinking level to task complexity**: Use `low` for simple queries, `high` for complex reasoning 2. **Consider latency**: Higher thinking levels increase response time 3. **Token budget awareness**: Thinking tokens count toward your quota 4. **Streaming recommended**: Use streaming for high thinking levels to see progress ```typescript // Stream thinking responses for better UX const thinkingResult = await ai.stream({ input: { text: "Design a distributed caching system" }, provider: "google-ai", model: "gemini-3.1-pro-preview", thinkingConfig: { thinkingLevel: "high" }, }); for await (const chunk of thinkingResult.stream) { if ("content" in chunk) process.stdout.write(chunk.content); } ``` --- ## Rate Limiting and Quotas ### Understanding Rate Limits Google AI Studio enforces **three types of limits**: 1. **RPM (Requests Per Minute)**: 15 requests in any 60-second window 2. **TPM (Tokens Per Minute)**: 1M tokens in any 60-second window 3. **RPD (Requests Per Day)**: 1,500 requests in any 24-hour window ### Rate Limit Handling ```typescript // ✅ Good: Implement exponential backoff async function generateWithBackoff(prompt: string, maxRetries = 3) { for (let attempt = 0; attempt setTimeout(resolve, delay)); } else { throw error; } } } throw new Error("Max retries exceeded"); } ``` ### Quota Monitoring ```typescript // Track quota usage class QuotaTracker { private requestsToday = 0; private requestsThisMinute = 0; private tokensThisMinute = 0; private minuteStart = Date.now(); private dayStart = Date.now(); async checkQuota() { const now = Date.now(); // Reset minute counters if (now - this.minuteStart > 60000) { this.requestsThisMinute = 0; this.tokensThisMinute = 0; this.minuteStart = now; } // Reset day counter if (now - this.dayStart > 86400000) { this.requestsToday = 0; this.dayStart = now; } // Check limits if (this.requestsThisMinute >= 15) { throw new Error("RPM limit reached (15/min)"); } if (this.tokensThisMinute >= 1000000) { throw new Error("TPM limit reached (1M/min)"); } if (this.requestsToday >= 1500) { throw new Error("RPD limit reached (1500/day)"); } } recordUsage(tokens: number) { this.requestsThisMinute++; this.requestsToday++; this.tokensThisMinute += tokens; } } // Usage const tracker = new QuotaTracker(); async function generate(prompt: string) { await tracker.checkQuota(); const result = await ai.generate({ input: { text: prompt }, provider: "google-ai", enableAnalytics: true, }); tracker.recordUsage(result.usage.totalTokens); return result; } ``` ### Rate Limiting Best Practices ```typescript // ✅ Good: Request queuing for high-volume apps class RequestQueue { private queue: Array void; reject: (error: any) => void; }> = []; private processing = false; private requestsThisMinute = 0; private minuteStart = Date.now(); async enqueue(prompt: string): Promise { return new Promise((resolve, reject) => { this.queue.push({ prompt, resolve, reject }); this.processQueue(); }); } private async processQueue() { if (this.processing || this.queue.length === 0) return; this.processing = true; while (this.queue.length > 0) { // Check rate limit (15 RPM) const now = Date.now(); if (now - this.minuteStart > 60000) { this.requestsThisMinute = 0; this.minuteStart = now; } if (this.requestsThisMinute >= 15) { // Wait until minute resets await new Promise((resolve) => setTimeout(resolve, 4000)); // 4s delay continue; } const item = this.queue.shift()!; try { const result = await ai.generate({ input: { text: item.prompt }, provider: "google-ai", }); this.requestsThisMinute++; item.resolve(result); } catch (error) { item.reject(error); } } this.processing = false; } } // Usage const queue = new RequestQueue(); const result = await queue.enqueue("Your prompt"); ``` --- ## SDK Integration ### Basic Usage ```typescript const ai = new NeuroLink(); // Simple generation const result = await ai.generate({ input: { text: "Explain machine learning" }, provider: "google-ai", }); console.log(result.content); ``` ### Multimodal Capabilities ```typescript // Image analysis const imageAnalysis = await ai.generate({ input: { text: "Describe what you see in this image", images: ["data:image/jpeg;base64,/9j/4AAQSkZJRg..."], }, provider: "google-ai", model: "gemini-2.5-flash", }); // Video analysis const videoAnalysis = await ai.generate({ input: { text: "Summarize the key events in this video", videos: ["data:video/mp4;base64,..."], }, provider: "google-ai", model: "gemini-2.5-pro", }); // Audio transcription and analysis const audioAnalysis = await ai.generate({ input: { text: "Transcribe and analyze the sentiment", audio: ["data:audio/mp3;base64,..."], }, provider: "google-ai", model: "gemini-2.5-flash", }); ``` ### Streaming Responses ```typescript // Stream long responses for better UX const streamResult = await ai.stream({ input: { text: "Write a detailed article about AI" }, provider: "google-ai", model: "gemini-2.5-flash", }); for await (const chunk of streamResult.stream) { if ("content" in chunk) process.stdout.write(chunk.content); } ``` ### Large Context Handling ```typescript // Leverage 1M token context window (Gemini 2.5 Pro) const largeDocument = readFileSync("large-document.txt", "utf-8"); const analysis = await ai.generate({ input: { text: `Analyze this entire document and provide key insights:\n\n${largeDocument}`, }, provider: "google-ai", model: "gemini-2.5-pro", // 1M context window }); ``` ### Tool/Function Calling ```typescript // Function calling (supported in Gemini models) const tools = [ { name: "get_weather", description: "Get current weather for a location", parameters: { type: "object", properties: { location: { type: "string", description: "City name" }, }, required: ["location"], }, }, ]; const result = await ai.generate({ input: { text: "What's the weather in London?" }, provider: "google-ai", model: "gemini-2.5-flash", tools, }); console.log(result.toolCalls); // Function calls to execute ``` --- ## CLI Usage ### Basic Commands ```bash # Generate with default model npx @juspay/neurolink generate "Hello Gemini" --provider google-ai # Use specific model npx @juspay/neurolink gen "Write code" \ --provider google-ai \ --model "gemini-2.5-flash" # Stream response npx @juspay/neurolink stream "Tell a story" --provider google-ai # Check provider status npx @juspay/neurolink status --provider google-ai ``` ### Advanced Usage ```bash # With temperature and max tokens npx @juspay/neurolink gen "Creative writing prompt" \ --provider google-ai \ --model "gemini-2.5-pro" \ --temperature 0.9 \ --max-tokens 2000 # Interactive mode npx @juspay/neurolink loop --provider google-ai --model "gemini-2.5-flash" # Multimodal: Image analysis (requires image file) npx @juspay/neurolink gen "Describe this image" \ --provider google-ai \ --model "gemini-2.5-flash" \ --image ./photo.jpg ``` --- ## Configuration Options ### Environment Variables ```bash # Required GOOGLE_AI_API_KEY=AIza-your-key-here # Optional GOOGLE_AI_MODEL=gemini-2.5-flash # Default model GOOGLE_AI_TIMEOUT=60000 # Request timeout (ms) GOOGLE_AI_MAX_RETRIES=3 # Retry attempts on rate limits GOOGLE_AI_BASE_URL=https://generativelanguage.googleapis.com # Custom endpoint ``` ### Programmatic Configuration ```typescript const ai = new NeuroLink({ providers: [ { name: "google-ai", config: { apiKey: process.env.GOOGLE_AI_API_KEY, defaultModel: "gemini-2.5-flash", timeout: 60000, maxRetries: 3, retryDelay: 1000, }, }, ], }); ``` --- ## Google AI Studio vs Vertex AI ### When to Use Google AI Studio ✅ **Choose Google AI Studio when:** - Development and prototyping - Low-volume production (\1,500 requests/day) - Enterprise compliance (HIPAA, SOC2) - SLA guarantees required - Multi-region deployment - VPC/private networking - Custom model fine-tuning - Advanced security controls ### Feature Comparison | Feature | Google AI Studio | Vertex AI | | -------------------- | ------------------------- | ---------------------- | | **Authentication** | API key | Service account (GCP) | | **Free Tier** | ✅ Yes (15 RPM, 1.5K RPD) | ❌ No | | **Rate Limits** | 15 RPM, 1M TPM | Custom quotas | | **SLA** | ❌ No | ✅ Yes (99.9%) | | **Compliance** | Basic | HIPAA, SOC2, ISO | | **Regions** | Global | Multi-region choice | | **VPC Support** | ❌ No | ✅ Yes | | **Setup Complexity** | Low (1 API key) | High (GCP project) | | **Best For** | Development, POCs | Production, enterprise | ### Migration Path ```typescript // Start with Google AI Studio for development const devAI = new NeuroLink({ providers: [ { name: "google-ai", config: { apiKey: process.env.GOOGLE_AI_API_KEY, }, }, ], }); // Migrate to Vertex AI for production const prodAI = new NeuroLink({ providers: [ { name: "vertex", config: { projectId: "your-gcp-project", location: "us-central1", credentials: "/path/to/service-account.json", }, }, ], }); // Hybrid: Use both with failover const hybridAI = new NeuroLink({ providers: [ { name: "vertex", priority: 1, // Prefer Vertex for production condition: (req) => req.env === "production", }, { name: "google-ai", priority: 2, // Fallback to AI Studio condition: (req) => req.env !== "production", }, ], }); ``` --- ## Troubleshooting ### Common Issues #### 1. "API key not valid" **Problem**: API key is incorrect or expired. **Solution**: ```bash # Verify key format (should start with AIza) echo $GOOGLE_AI_API_KEY # Regenerate key at https://aistudio.google.com/ # Ensure no extra spaces in .env GOOGLE_AI_API_KEY=AIza-your-key # ✅ Correct GOOGLE_AI_API_KEY= AIza-your-key # ❌ Extra space ``` #### 2. "429 Too Many Requests" **Problem**: Exceeded rate limits (15 RPM, 1M TPM, or 1500 RPD). **Solution**: ```typescript // Implement backoff strategy (see Rate Limiting section above) // Or reduce request frequency // Monitor quota usage in the Google AI Studio console // Check that the provider is configured and reachable const health = await ai.checkProviderHealth("google-ai"); console.log("Provider healthy:", health.isHealthy, health.error); ``` #### 3. "Resource Exhausted" (Quota) **Problem**: Exceeded daily quota (1,500 requests/day). **Solution**: - Wait for quota reset (24-hour rolling window) - Upgrade to Vertex AI for higher quotas - Implement request caching: ```typescript // Cache frequent queries const cache = new Map(); async function cachedGenerate(prompt: string) { if (cache.has(prompt)) { console.log("Cache hit"); return cache.get(prompt); } const result = await ai.generate({ input: { text: prompt }, provider: "google-ai", }); cache.set(prompt, result); return result; } ``` #### 4. Slow Response Times **Problem**: Network latency or model processing time. **Solution**: ```typescript // Use streaming for immediate feedback const result = await ai.stream({ input: { text: "Your prompt" }, provider: "google-ai", model: "gemini-2.5-flash", // Fastest model }); for await (const chunk of result.stream) { if ("content" in chunk) { // Display partial results immediately process.stdout.write(chunk.content); } } ``` #### 5. "Model not found" **Problem**: Invalid or deprecated model name. **Solution**: ```typescript // Use current model names const validModels = [ "gemini-3.1-pro-preview", // ✅ Latest with thinking "gemini-3-flash-preview", // ✅ Fast with thinking "gemini-3.1-flash-lite-preview", // ✅ Lite preview "gemini-2.5-pro", // ✅ Production flagship "gemini-2.5-flash", // ✅ Default model "gemini-2.5-flash-lite", // ✅ Cost-optimized "gemini-2.0-flash", // ⚠️ Retiring June 1, 2026 "gemini-1.5-pro", // ❌ SHUT DOWN (returns 404) "gemini-1.5-flash", // ❌ SHUT DOWN (returns 404) ]; const result = await ai.generate({ input: { text: "test" }, provider: "google-ai", model: "gemini-2.5-flash", // Use default }); ``` --- ## Best Practices ### 1. Quota Management ```typescript // ✅ Good: Implement quota tracking class GoogleAIClient { private dailyRequests = 0; private dayStart = Date.now(); async generate(prompt: string) { // Reset daily counter if (Date.now() - this.dayStart > 86400000) { this.dailyRequests = 0; this.dayStart = Date.now(); } // Check quota if (this.dailyRequests >= 1450) { // Buffer before hard limit console.warn("Approaching daily quota limit"); // Switch to backup provider or queue request } const result = await ai.generate({ input: { text: prompt }, provider: "google-ai", }); this.dailyRequests++; return result; } } ``` ### 2. Error Handling ```typescript // ✅ Good: Comprehensive error handling async function robustGenerate(prompt: string) { try { return await ai.generate({ input: { text: prompt }, provider: "google-ai", }); } catch (error) { if (error.message.includes("429")) { // Rate limit - implement backoff await new Promise((r) => setTimeout(r, 2000)); return robustGenerate(prompt); } else if (error.message.includes("quota")) { // Quota exhausted - switch provider return await ai.generate({ input: { text: prompt }, provider: "openai", // Fallback }); } else if (error.message.includes("timeout")) { // Timeout - retry with shorter timeout return await ai.generate({ input: { text: prompt }, provider: "google-ai", timeout: 30000, }); } else { throw error; } } } ``` ### 3. Model Selection ```typescript // ✅ Good: Choose appropriate model for task function selectModel(task: string, needsThinking: boolean = false): string { const taskType = analyzeTask(task); // Use Gemini 3.x for tasks requiring deep reasoning if (needsThinking || /prove|reason|analyze deeply|architecture/.test(task)) { return taskType === "realtime" ? "gemini-3-flash-preview" // Fast thinking : "gemini-3.1-pro-preview"; // Deep thinking } switch (taskType) { case "simple": return "gemini-2.5-flash-lite"; // Fast, cost-effective case "complex": return "gemini-3.1-pro-preview"; // High capability with thinking case "realtime": return "gemini-2.5-flash"; // Lowest latency case "multimodal": return "gemini-2.5-pro"; // Best multimodal default: return "gemini-2.5-flash"; // Default } } function analyzeTask(task: string): string { if (task.length (); private TTL = 3600000; // 1 hour async generate(prompt: string, options: any = {}) { const cacheKey = this.getCacheKey(prompt, options); const cached = this.cache.get(cacheKey); // Return cached if fresh if (cached && Date.now() - cached.timestamp < this.TTL) { console.log("Cache hit"); return cached.result; } // Generate fresh result const result = await ai.generate({ input: { text: prompt }, provider: "google-ai", ...options, }); // Store in cache this.cache.set(cacheKey, { result, timestamp: Date.now(), }); return result; } private getCacheKey(prompt: string, options: any): string { const hash = createHash("sha256"); hash.update(JSON.stringify({ prompt, options })); return hash.digest("hex"); } } ``` --- ## Known Limitations ### Tools + JSON Schema Cannot Be Used Together :::warning[Critical Limitation] Gemini models (including Gemini 3) cannot use function calling (tools) and JSON schema output simultaneously. You must choose one or the other. ::: **Google API Limitation:** Google AI Studio (all Gemini models including Gemini 3) cannot combine function calling with structured output (JSON schema). This is a fundamental Google API constraint documented in the [Gemini API documentation](https://ai.google.dev/gemini-api/docs/). **Error:** ``` Function calling with a response mime type: 'application/json' is unsupported ``` **Solution:** ```typescript // ❌ This will fail - tools + schema together const badResult = await neurolink.generate({ input: { text: "Analyze this data" }, schema: MyZodSchema, provider: "google-ai", model: "gemini-3.1-pro-preview", tools: myTools, // Cannot use tools with schema! }); // ✅ Correct approach - disable tools when using schema const result = await neurolink.generate({ input: { text: "Analyze this data" }, schema: MyZodSchema, output: { format: "json" }, provider: "google-ai", model: "gemini-3.1-pro-preview", disableTools: true, // Required for schemas }); // ✅ Alternative - use tools without schema const toolResult = await neurolink.generate({ input: { text: "What's the weather in London?" }, provider: "google-ai", model: "gemini-3-flash-preview", tools: myTools, // Works fine without schema }); ``` **Industry Context:** - This limitation affects ALL frameworks using Gemini (LangChain, Vercel AI SDK, Agno, Instructor) - All use the same workaround: disable tools when using schemas - This applies to all Gemini versions including Gemini 3 preview models - Check official Google AI Studio documentation for future updates **Alternative Approaches:** 1. Use OpenAI or Anthropic providers (support both simultaneously) 2. Use Vertex AI with Claude models (via Anthropic integration) 3. Choose between tools OR schemas for Gemini models 4. Chain requests: first call with tools, second call with schema ### Complex Schema Limitations **"Too many states for serving" Error:** When using complex Zod schemas, you may encounter: ``` Error: 9 FAILED_PRECONDITION: Too many states for serving ``` **Solutions:** 1. Simplify schema (reduce nesting, array sizes) 2. Use `disableTools: true` (reduces state count) 3. Split complex operations into multiple simpler calls See [Troubleshooting Guide](/docs/reference/troubleshooting) for details. --- ## Related Documentation - **[Provider Setup Guide](/docs/getting-started/provider-setup)** - General provider configuration - **[Google Vertex AI Guide](/docs/getting-started/providers/google-vertex)** - Enterprise Vertex AI setup - **[Cost Optimization](/docs/cookbook/cost-optimization)** - Reduce AI costs - **[Cost Optimization](/docs/cookbook/cost-optimization)** - Handle quotas and rate limits --- ## Additional Resources - **[Google AI Studio](https://aistudio.google.com/)** - Get API keys - **[Gemini API Documentation](https://ai.google.dev/docs)** - Official API docs - **[Gemini Models](https://ai.google.dev/models/gemini)** - Model capabilities - **[Pricing](https://ai.google.dev/pricing)** - Free tier and paid pricing --- **Need Help?** Join our [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## Google Vertex AI Provider Guide # Google Vertex AI Provider Guide **Enterprise AI on Google Cloud with Claude, Gemini, and custom models** ## Quick Start ### 1. Create GCP Project ```bash # Create project gcloud projects create my-ai-project --name="My AI Project" # Set project gcloud config set project my-ai-project # Enable Vertex AI API gcloud services enable aiplatform.googleapis.com ``` ### 2. Setup Authentication **Option A: Service Account (Production)** ```bash # Create service account gcloud iam service-accounts create vertex-ai-sa \ --display-name="Vertex AI Service Account" # Grant Vertex AI User role gcloud projects add-iam-policy-binding my-ai-project \ --member="serviceAccount:vertex-ai-sa@my-ai-project.iam.gserviceaccount.com" \ --role="roles/aiplatform.user" # Create key file gcloud iam service-accounts keys create vertex-key.json \ --iam-account=vertex-ai-sa@my-ai-project.iam.gserviceaccount.com # Set environment variable export GOOGLE_APPLICATION_CREDENTIALS="$(pwd)/vertex-key.json" ``` **Option B: Application Default Credentials (Development)** ```bash # Login with your Google account gcloud auth application-default login ``` **Option C: Workload Identity (GKE)** ```bash # Bind Kubernetes service account to GCP service account gcloud iam service-accounts add-iam-policy-binding \ vertex-ai-sa@my-ai-project.iam.gserviceaccount.com \ --role roles/iam.workloadIdentityUser \ --member "serviceAccount:my-ai-project.svc.id.goog[default/my-ksa]" ``` ### 3. Configure NeuroLink ```bash # .env GOOGLE_VERTEX_PROJECT_ID=my-ai-project GOOGLE_VERTEX_LOCATION=us-central1 GOOGLE_APPLICATION_CREDENTIALS=/path/to/vertex-key.json ``` ```typescript const ai = new NeuroLink({ providers: [ { name: "vertex", config: { projectId: process.env.GOOGLE_VERTEX_PROJECT_ID, location: process.env.GOOGLE_VERTEX_LOCATION, credentials: process.env.GOOGLE_APPLICATION_CREDENTIALS, }, }, ], }); const result = await ai.generate({ input: { text: "Hello from Vertex AI!" }, provider: "vertex", model: "gemini-2.0-flash", }); console.log(result.content); ``` --- ## Regional Deployment ### Available Regions | Region | Location | Models Available | Latency | | ------------------------ | -------------- | ---------------- | -------------------- | | **us-central1** | Iowa, USA | All models | Low (US) | | **us-east1** | South Carolina | All models | Low (US East) | | **us-west1** | Oregon, USA | All models | Low (US West) | | **europe-west1** | Belgium | All models | Low (EU) | | **europe-west2** | London, UK | All models | Low (UK) | | **europe-west4** | Netherlands | All models | Low (EU) | | **asia-northeast1** | Tokyo, Japan | All models | Low (Asia) | | **asia-southeast1** | Singapore | All models | Low (Southeast Asia) | | **asia-south1** | Mumbai, India | All models | Low (India) | | **australia-southeast1** | Sydney | All models | Low (Australia) | ### Multi-Region Setup ```typescript const ai = new NeuroLink({ providers: [ // US deployment { name: "vertex-us", config: { projectId: process.env.GOOGLE_VERTEX_PROJECT_ID, location: "us-central1", credentials: process.env.GOOGLE_APPLICATION_CREDENTIALS, }, region: "us", priority: 1, condition: (req) => req.userRegion === "us", }, // EU deployment { name: "vertex-eu", config: { projectId: process.env.GOOGLE_VERTEX_PROJECT_ID, location: "europe-west1", credentials: process.env.GOOGLE_APPLICATION_CREDENTIALS, }, region: "eu", priority: 1, condition: (req) => req.userRegion === "eu", }, // Asia deployment { name: "vertex-asia", config: { projectId: process.env.GOOGLE_VERTEX_PROJECT_ID, location: "asia-southeast1", credentials: process.env.GOOGLE_APPLICATION_CREDENTIALS, }, region: "asia", priority: 1, condition: (req) => req.userRegion === "asia", }, ], failoverConfig: { enabled: true }, }); ``` --- ## Available Models ### Gemini Models (Google) | Model | Description | Context | Best For | Pricing | | -------------------------- | ------------------------- | ---------- | ------------------------ | -------------------------------- | | **gemini-3-pro-preview** | Latest, extended thinking | 1M tokens | Deep reasoning, analysis | Preview | | **gemini-3-flash-preview** | Fast with thinking | 1M tokens | Balanced speed/quality | Preview | | **gemini-2.0-flash** | Fast model | 1M tokens | Speed, real-time | $0.075/1M input, $0.30/1M output | | **gemini-1.5-pro** | Most capable | 2M tokens | Complex reasoning | $1.25/1M in | | **gemini-1.5-flash** | Balanced | 1M tokens | General tasks | $0.075/1M in | | **gemini-1.0-pro** | Stable version | 32K tokens | Production | $0.50/1M in | > **Note:** Gemini 3 models (`gemini-3-pro-preview`, `gemini-3-flash-preview`) are preview models and may have stricter rate limits than production models. Monitor your usage and expect potential API changes during the preview period. ### Claude Models (Anthropic via Vertex) | Model | Description | Context | Best For | Pricing | | --------------------- | ---------------- | ----------- | --------------- | ----------- | | **claude-3-5-sonnet** | Latest Anthropic | 200K tokens | Complex tasks | $3/1M in | | **claude-3-opus** | Most capable | 200K tokens | Highest quality | $15/1M in | | **claude-3-haiku** | Fast, affordable | 200K tokens | High-volume | $0.25/1M in | ### Model Selection Examples ```typescript // Use Gemini for speed const fast = await ai.generate({ input: { text: "Quick query" }, provider: "vertex", model: "gemini-2.0-flash", }); // Use Gemini Pro for complex reasoning const complex = await ai.generate({ input: { text: "Detailed analysis..." }, provider: "vertex", model: "gemini-1.5-pro", }); // Use Claude for highest quality const premium = await ai.generate({ input: { text: "Critical task..." }, provider: "vertex", model: "claude-3-5-sonnet", }); ``` --- ## Extended Thinking (Gemini 3) Gemini 3 models support **Extended Thinking**, which enables the model to perform deeper reasoning before generating responses. This is ideal for complex analysis, multi-step problem solving, and tasks requiring careful deliberation. ### Thinking Levels | Level | Description | Use Case | Latency Impact | | ----------- | ---------------------------------- | ---------------------------------- | -------------- | | **minimal** | Near-zero thinking (Flash only) | Simple queries requiring speed | Minimal | | **low** | Minimal thinking, faster responses | Simple queries, quick answers | Low | | **medium** | Balanced thinking and speed | General tasks, moderate complexity | Moderate | | **high** | Deep reasoning, thorough analysis | Complex problems, critical tasks | Higher | ### Basic Usage ```typescript const ai = new NeuroLink({ providers: [ { name: "vertex", config: { projectId: process.env.GOOGLE_VERTEX_PROJECT_ID, location: process.env.GOOGLE_VERTEX_LOCATION, }, }, ], }); // Enable extended thinking with Gemini 3 const result = await ai.generate({ input: { text: "Analyze the trade-offs between microservices and monolithic architecture for a startup with 5 engineers.", }, provider: "vertex", model: "gemini-3-pro-preview", thinkingLevel: "high", // 'minimal' | 'low' | 'medium' | 'high' }); console.log(result.content); ``` ### Thinking Level Examples ```typescript // Low thinking - Quick responses for simple queries const quick = await ai.generate({ input: { text: "What is the capital of France?" }, provider: "vertex", model: "gemini-3-flash-preview", thinkingLevel: "low", }); // Medium thinking - Balanced for everyday tasks const balanced = await ai.generate({ input: { text: "Summarize the key points of this article..." }, provider: "vertex", model: "gemini-3-flash-preview", thinkingLevel: "medium", }); // High thinking - Deep analysis for complex problems const deep = await ai.generate({ input: { text: `Given the following codebase architecture, identify potential security vulnerabilities and suggest remediation strategies...`, }, provider: "vertex", model: "gemini-3-pro-preview", thinkingLevel: "high", }); ``` ### Streaming with Extended Thinking ```typescript // Stream responses with thinking enabled const stream = await ai.stream({ input: { text: "Design a distributed caching strategy for a high-traffic e-commerce platform.", }, provider: "vertex", model: "gemini-3-pro-preview", thinkingLevel: "high", }); for await (const chunk of stream) { process.stdout.write(chunk.content); } ``` ### Best Practices for Extended Thinking 1. **Match thinking level to task complexity**: Use `low` for simple queries, `high` for complex analysis 2. **Consider latency requirements**: Higher thinking levels increase response time 3. **Use with complex prompts**: Extended thinking shines with multi-step reasoning tasks 4. **Monitor token usage**: Thinking processes consume additional tokens > **Important:** Extended Thinking is only available on Gemini 3 models (`gemini-3-pro-preview`, `gemini-3-flash-preview`). Using `thinkingLevel` with other models will be ignored. --- ## Gemini 3 Multi-Turn Tool Calling (Agentic Loops) Gemini 3 models use a **native `@google/genai` SDK path** inside NeuroLink. It exists because of `thoughtSignature`: Gemini 3 attaches that token to every tool-calling response, and it has to survive into the replayed conversation history or agentic turns break after the first step. The generic adapter layer NeuroLink used to run on (the Vercel AI SDK, since removed) stripped it; the native path carries it through. ### How It Works When NeuroLink detects a Gemini 3 model + tools, it routes to the native path automatically. You use the same SDK API — nothing changes on your end: ```typescript const result = await neurolink.generate({ input: { text: "Run my agentic workflow..." }, provider: "vertex", model: "gemini-3-flash-preview", tools: { myTool: { ... } }, sessionId: "session-123", // enables Redis conversation history maxSteps: 20, }); ``` ### `thoughtSignature` and History Replay Gemini 3 returns a `thoughtSignature` token with every response that includes function calls. This token must be echoed back as a **sibling field** on each `functionCall` part in conversation history: ```typescript // How NeuroLink stores it in Redis → how it replays it to Gemini { functionCall: { name: "getStatus", args: { id: "abc" } }, thoughtSignature: "" } ``` Without this, Gemini treats each step as a new conversation and stops calling tools after step 1. ### Parallel Tool Calls and `stepIndex` Within one agentic step, Gemini can return multiple function calls simultaneously. NeuroLink tags every stored tool call/result with a `stepIndex` (integer, increments per step) so that `prependConversationHistory` can group them into the correct single model turn: ``` Step 1 → model turn: [functionCall(toolA), functionCall(toolB)] // stepIndex: 1 user turn: [functionResponse(toolA), functionResponse(toolB)] Step 2 → model turn: [functionCall(toolC)] // stepIndex: 2 user turn: [functionResponse(toolC)] ``` Putting two steps into separate model turns would create consecutive model turns, which Gemini rejects with a validation error. ### Multi-Execution Session Isolation (`executionId`) When the same `sessionId` is used by multiple agentic loop invocations (for example, an orchestrator spawning a child agent via `continueOrchestratorWorkflow`), each invocation restarts `stepIndex` at 1. Without isolation, step 1 from Execution A and step 1 from Execution B would be grouped into the same model turn, producing an invalid Gemini history. NeuroLink assigns a UUID `executionId` to each invocation and uses it as a prefix in the grouping key: ``` Execution A, step 1 → key "exec::1" Execution B, step 1 → key "exec::1" ← never collide ``` Old messages without an `executionId` fall back to the `turn::` key for backward compatibility. ### Timeout Defaults The native generate path defaults to **5 minutes** (300 s) to accommodate long multi-step agentic loops. Override with `options.timeout`: ```typescript const result = await neurolink.generate({ ... timeout: "10m", // "2m", "300s", or milliseconds }); ``` If the timeout fires mid-stream, NeuroLink surfaces a `TimeoutError` rather than returning empty content silently. ### Constraints - **No tools + JSON schema simultaneously** — Gemini 3 cannot use function calling and `structuredOutput` with a JSON schema at the same time. NeuroLink automatically disables tools when a JSON schema output is requested and logs a warning. - **Gemini 3 only** — This particular branch activates only for model names matching the Gemini 3 pattern. Every other Vertex model is also served natively: Gemini through `@google/genai` and Claude through `@anthropic-ai/vertex-sdk`. --- ## IAM & Permissions ### Required IAM Roles ```bash # Minimum roles for Vertex AI roles/aiplatform.user # Use Vertex AI services roles/serviceusage.serviceUsageConsumer # Use GCP APIs # Additional roles for specific features roles/aiplatform.admin # Manage models and endpoints roles/storage.objectViewer # Read from Cloud Storage roles/bigquery.dataViewer # Read from BigQuery ``` ### Service Account Setup ```bash # Create service account with minimal permissions gcloud iam service-accounts create vertex-readonly \ --display-name="Vertex AI Read-Only" # Grant only necessary permissions gcloud projects add-iam-policy-binding my-ai-project \ --member="serviceAccount:vertex-readonly@my-ai-project.iam.gserviceaccount.com" \ --role="roles/aiplatform.user" # For production, use custom role with least privilege gcloud iam roles create vertexAIInference \ --project=my-ai-project \ --title="Vertex AI Inference Only" \ --permissions=aiplatform.endpoints.predict,aiplatform.endpoints.get ``` ### Workload Identity for GKE ```yaml # kubernetes-sa.yaml apiVersion: v1 kind: ServiceAccount metadata: name: vertex-ai-sa namespace: default annotations: iam.gke.io/gcp-service-account: vertex-ai-sa@my-ai-project.iam.gserviceaccount.com ``` ```bash # Bind Kubernetes SA to GCP SA gcloud iam service-accounts add-iam-policy-binding \ vertex-ai-sa@my-ai-project.iam.gserviceaccount.com \ --role roles/iam.workloadIdentityUser \ --member "serviceAccount:my-ai-project.svc.id.goog[default/vertex-ai-sa]" ``` --- ## VPC & Private Connectivity ### Private Service Connect ```bash # Create Private Service Connect endpoint gcloud compute addresses create vertex-psc-ip \ --region=us-central1 \ --subnet=my-subnet gcloud compute forwarding-rules create vertex-psc-endpoint \ --region=us-central1 \ --network=my-vpc \ --address=vertex-psc-ip \ --target-service-attachment=projects/my-project/regions/us-central1/serviceAttachments/vertex-ai ``` ### VPC Service Controls ```bash # Create access policy gcloud access-context-manager policies create \ --title="Vertex AI Access Policy" # Create perimeter gcloud access-context-manager perimeters create vertex_perimeter \ --title="Vertex AI Perimeter" \ --resources=projects/my-ai-project \ --restricted-services=aiplatform.googleapis.com \ --policy=POLICY_ID ``` --- ## Custom Model Deployment ### Deploy Custom Model ```python # Python example for custom model deployment from google.cloud import aiplatform aiplatform.init(project='my-ai-project', location='us-central1') # Upload model model = aiplatform.Model.upload( display_name='my-custom-model', artifact_uri='gs://my-bucket/model/', serving_container_image_uri='gcr.io/my-project/serving-image:latest' ) # Create endpoint endpoint = aiplatform.Endpoint.create( display_name='my-model-endpoint' ) # Deploy model to endpoint model.deploy( endpoint=endpoint, machine_type='n1-standard-4', min_replica_count=1, max_replica_count=3 ) ``` ### Use Custom Endpoint with NeuroLink ```typescript const ai = new NeuroLink({ providers: [ { name: "vertex-custom", config: { projectId: process.env.GOOGLE_VERTEX_PROJECT_ID, location: "us-central1", credentials: process.env.GOOGLE_APPLICATION_CREDENTIALS, endpoint: "projects/my-project/locations/us-central1/endpoints/12345", }, }, ], }); const result = await ai.generate({ input: { text: "Your prompt" }, provider: "vertex-custom", }); ``` --- ## Monitoring & Logging ### Cloud Logging Integration ```typescript const logging = new Logging({ projectId: process.env.GOOGLE_VERTEX_PROJECT_ID, }); const log = logging.log("vertex-ai-requests"); const ai = new NeuroLink({ providers: [ { name: "vertex", config: { projectId: process.env.GOOGLE_VERTEX_PROJECT_ID, location: "us-central1", }, }, ], onSuccess: async (result) => { // Log to Cloud Logging const metadata = { resource: { type: "global" }, severity: "INFO", }; const entry = log.entry(metadata, { event: "ai_generation_success", provider: result.provider, model: result.model, tokens: result.usage.totalTokens, cost: result.cost, latency: result.latency, }); await log.write(entry); }, }); ``` ### Cloud Monitoring Metrics ```typescript const client = new MetricServiceClient(); async function writeMetric(tokens: number, cost: number) { const projectId = process.env.GOOGLE_VERTEX_PROJECT_ID; const projectPath = client.projectPath(projectId); const dataPoint = { interval: { endTime: { seconds: Date.now() / 1000 }, }, value: { doubleValue: tokens }, }; const timeSeriesData = { metric: { type: "custom.googleapis.com/vertex_ai/tokens_used", labels: { model: "gemini-1.5-pro" }, }, resource: { type: "global", labels: { project_id: projectId }, }, points: [dataPoint], }; const request = { name: projectPath, timeSeries: [timeSeriesData], }; await client.createTimeSeries(request); } ``` --- ## Cost Management ### Pricing Overview ``` Gemini Pricing (per 1M tokens): - gemini-2.0-flash: $0.075 input, $0.30 output - gemini-1.5-pro: $1.25 input, $5.00 output - gemini-1.5-flash: $0.075 input, $0.30 output Claude on Vertex (per 1M tokens): - claude-3-5-sonnet: $3 input, $15 output - claude-3-opus: $15 input, $75 output - claude-3-haiku: $0.25 input, $1.25 output Custom Model: Based on compute (n1-standard-4: ~$0.19/hour) ``` ### Budget Alerts ```bash # Set budget alert gcloud billing budgets create \ --billing-account=BILLING_ACCOUNT_ID \ --display-name="Vertex AI Budget" \ --budget-amount=1000 \ --threshold-rule=percent=50 \ --threshold-rule=percent=90 \ --threshold-rule=percent=100 ``` ### Cost Tracking ```typescript class VertexCostTracker { private monthlyCost = 0; calculateCost( model: string, inputTokens: number, outputTokens: number, ): number { const pricing: Record = { "gemini-2.0-flash": { input: 0.075, output: 0.3 }, "gemini-1.5-pro": { input: 1.25, output: 5.0 }, "claude-3-5-sonnet": { input: 3.0, output: 15.0 }, }; const rates = pricing[model] || pricing["gemini-2.0-flash"]; const cost = (inputTokens / 1_000_000) * rates.input + (outputTokens / 1_000_000) * rates.output; this.monthlyCost += cost; return cost; } getMonthlyTotal(): number { return this.monthlyCost; } } const costTracker = new VertexCostTracker(); const result = await ai.generate({ input: { text: "Your prompt" }, provider: "vertex", model: "gemini-1.5-pro", enableAnalytics: true, }); const cost = costTracker.calculateCost( result.model, result.usage.promptTokens, result.usage.completionTokens, ); console.log(`Request cost: $${cost.toFixed(4)}`); console.log(`Monthly total: $${costTracker.getMonthlyTotal().toFixed(2)}`); ``` --- ## Production Patterns ### Pattern 1: Multi-Model Strategy ```typescript const ai = new NeuroLink({ providers: [ // Fast, cheap for simple queries { name: "vertex-flash", config: { projectId: process.env.GOOGLE_VERTEX_PROJECT_ID, location: "us-central1", }, model: "gemini-2.0-flash", condition: (req) => req.complexity === "low", }, // Balanced for medium complexity { name: "vertex-pro", config: { projectId: process.env.GOOGLE_VERTEX_PROJECT_ID, location: "us-central1", }, model: "gemini-1.5-pro", condition: (req) => req.complexity === "medium", }, // Premium for critical tasks { name: "vertex-claude", config: { projectId: process.env.GOOGLE_VERTEX_PROJECT_ID, location: "us-central1", }, model: "claude-3-5-sonnet", condition: (req) => req.complexity === "high", }, ], }); ``` ### Pattern 2: A/B Testing ```typescript // Deploy two model versions for A/B testing const ai = new NeuroLink({ providers: [ { name: "vertex-model-a", config: { /*...*/ }, model: "gemini-1.5-pro", weight: 1, // 50% traffic tags: ["experiment-a"], }, { name: "vertex-model-b", config: { /*...*/ }, model: "claude-3-5-sonnet", weight: 1, // 50% traffic tags: ["experiment-b"], }, ], loadBalancing: "weighted-round-robin", onSuccess: (result) => { // Track A/B test metrics analytics.track({ experiment: result.tags[0], model: result.model, latency: result.latency, quality: result.quality, }); }, }); ``` --- ## Best Practices ### 1. ✅ Use Service Accounts with Minimal Permissions ```bash # ✅ Good: Least privilege gcloud iam roles create vertexInferenceOnly \ --permissions=aiplatform.endpoints.predict ``` ### 2. ✅ Enable Private Service Connect ```bash # ✅ Good: Private connectivity gcloud compute forwarding-rules create vertex-psc ``` ### 3. ✅ Monitor Costs ```typescript // ✅ Good: Track every request const cost = costTracker.calculateCost(model, inputTokens, outputTokens); ``` ### 4. ✅ Use Multi-Region for HA ```typescript // ✅ Good: Regional failover providers: [ { name: "vertex-us", region: "us-central1", priority: 1 }, { name: "vertex-eu", region: "europe-west1", priority: 2 }, ]; ``` ### 5. ✅ Log to Cloud Logging ```typescript // ✅ Good: Centralized logging await log.write(entry); ``` --- ## Troubleshooting ### Common Issues #### 1. "Permission Denied" **Problem**: Missing IAM permissions. **Solution**: ```bash # Grant required role gcloud projects add-iam-policy-binding my-ai-project \ --member="serviceAccount:vertex-ai-sa@my-ai-project.iam.gserviceaccount.com" \ --role="roles/aiplatform.user" ``` #### 2. "Quota Exceeded" **Problem**: Exceeded API quota. **Solution**: ```bash # Request quota increase gcloud services enable serviceusage.googleapis.com gcloud alpha services quota update \ --service=aiplatform.googleapis.com \ --consumer=projects/my-ai-project \ --metric=aiplatform.googleapis.com/online_prediction_requests \ --value=10000 ``` #### 3. "Model Not Found" **Problem**: Model not available in region. **Solution**: ```bash # Check available models in region gcloud ai models list --region=us-central1 # Use different region GOOGLE_VERTEX_LOCATION=europe-west1 ``` --- ## Known Limitations ### Tools + JSON Schema Cannot Be Used Simultaneously (Gemini Models) **Google API Limitation:** All Google Gemini models on Vertex AI (including Gemini 3 preview models) cannot combine function calling (tools) with structured output (JSON schema) in the same request. This is a fundamental Google API constraint. **Affected models:** All Gemini models including `gemini-3-pro-preview`, `gemini-3-flash-preview`, `gemini-2.0-flash`, `gemini-1.5-pro`, `gemini-1.5-flash` **Note:** This limitation ONLY affects Gemini models. Anthropic Claude models via Vertex AI do NOT have this limitation. **Error:** ``` Function calling with a response mime type: 'application/json' is unsupported ``` **Solution for Gemini models:** ```typescript // ✅ Correct approach with Gemini (including Gemini 3) const result = await neurolink.generate({ input: { text: "Analyze this data" }, schema: MyZodSchema, output: { format: "json" }, provider: "vertex", model: "gemini-3-pro-preview", // or any Gemini model disableTools: true, // Required for ALL Gemini models when using schema }); ``` **With Extended Thinking (Gemini 3):** ```typescript // ✅ Using schema with Gemini 3 Extended Thinking const result = await neurolink.generate({ input: { text: "Analyze this complex data and provide structured insights" }, schema: MyZodSchema, output: { format: "json" }, provider: "vertex", model: "gemini-3-pro-preview", thinkingLevel: "high", disableTools: true, // Still required even with thinking enabled }); ``` **Claude models work without restriction:** ```typescript // ✅ Claude via Vertex AI supports both const result = await neurolink.generate({ input: { text: "Analyze this data" }, schema: MyZodSchema, output: { format: "json" }, provider: "vertex", model: "claude-3-5-sonnet-20241022", // No disableTools needed - Claude supports both }); ``` **Industry Context:** - This limitation affects ALL frameworks using Gemini (LangChain, Vercel AI SDK, Agno, Instructor) - All use the same workaround: disable tools when using schemas - Future Gemini versions may support both - check official Google Cloud documentation for updates ### Preview Model Rate Limits (Gemini 3) **Preview models** (`gemini-3-pro-preview`, `gemini-3-flash-preview`) have stricter rate limits than production models: - Lower requests per minute (RPM) quotas - Lower tokens per minute (TPM) quotas - Potential for API changes without notice - Not recommended for production workloads without fallback **Recommended pattern for production:** ```typescript const ai = new NeuroLink({ providers: [ // Primary: Gemini 3 preview { name: "vertex-gemini3", config: { projectId: process.env.GOOGLE_VERTEX_PROJECT_ID, location: "us-central1", }, model: "gemini-3-pro-preview", priority: 1, }, // Fallback: Stable Gemini 2 { name: "vertex-gemini2", config: { projectId: process.env.GOOGLE_VERTEX_PROJECT_ID, location: "us-central1", }, model: "gemini-2.0-flash", priority: 2, }, ], failoverConfig: { enabled: true }, }); ``` ### Complex Schema Limitations **"Too many states for serving" Error:** When using complex Zod schemas with Gemini, you may encounter: ``` Error: 9 FAILED_PRECONDITION: Too many states for serving ``` **Solutions:** 1. Simplify schema (reduce nesting, array sizes) 2. Use `disableTools: true` (reduces state count) 3. Use Claude models via Vertex AI (no such limitation) See [Troubleshooting Guide](/docs/reference/troubleshooting) for details. --- ## Related Documentation - **[Provider Setup Guide](/docs/getting-started/provider-setup)** - General configuration - **[Multi-Region Deployment](/docs/guides/enterprise/multi-region)** - Geographic distribution - **[Cost Optimization](/docs/cookbook/cost-optimization)** - Reduce costs - **[Compliance Guide](/docs/guides/enterprise/compliance)** - Security --- ## Additional Resources - **[Vertex AI Documentation](https://cloud.google.com/vertex-ai/docs)** - Official docs - **[Vertex AI Pricing](https://cloud.google.com/vertex-ai/pricing)** - Pricing calculator - **[GCP Console](https://console.cloud.google.com/)** - Manage resources - **[gcloud CLI](https://cloud.google.com/sdk/gcloud)** - Command-line tool --- **Need Help?** Join our [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## GradientAI Provider Guide # GradientAI Provider Guide GradientAI (DigitalOcean) is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/gradientai.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** The vendor's `GET /v1/models` needs a key (an unauthenticated > GET answers HTTP 401), so the model ids come from DigitalOcean's public docs and > the roster has not been checked. No account was created and no API key was used > to build it. `evidence.liveMatrix` is `null` until someone runs the live > capability matrix with a real key (see > [Verification status](#verification-status) below). DigitalOcean's docs now brand the product "Inference"; the API reference describes the serverless API as part of "DigitalOcean Gradient™ AI Agentic Cloud". ## Quick Start ### 1. Get an API key 1. Visit: https://cloud.digitalocean.com/model-studio/manage-keys (the Control Panel page that https://docs.digitalocean.com/products/inference/how-to/manage-model-access-keys/ names for creating and managing model access keys; it shows the DigitalOcean login when signed out) and sign in to a DigitalOcean account 2. Click Create model access key, enter a name, and copy the secret key when it is shown: the docs state "Copy and store it securely before closing the window." 3. Prepaid balance: the docs state "Serverless Inference requires a positive prepaid account balance before you can send inference requests." (https://docs.digitalocean.com/products/inference/how-to/manage-serverless-inference-prepayment/) 4. Set `GRADIENTAI_API_KEY` in your .env file ### 2. Configure ```bash export GRADIENTAI_API_KEY=your-model-access-key export GRADIENTAI_MODEL=llama-4-maverick # optional — overrides the default model export GRADIENTAI_BASE_URL=https://inference.do-ai.run/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "gradientai", model: "llama-4-maverick", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider gradientai ``` Per-request credentials use the standard NeuroLink pattern: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "gradientai", credentials: { gradientai: { apiKey: process.env.GRADIENTAI_API_KEY } }, }); ``` --- ## Models | Model | Context | Max output | Vision | $/M in · out (cache read) | Notes | | ------------------------ | --------- | ------------- | ------ | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `llama-4-maverick` ⭐ | 128,000 | 16,384 | — | $0.25 / $0.87 | NeuroLink default. Models page row "Llama 4 Maverick 17B 128E Instruct"; the Chat Completions page uses `model="llama-4-maverick"` in its Python OpenAI SDK example. | | `deepseek-v4.1-flash` | 1,048,576 | 1,048,576 | yes | $0.30 / $1.20 ($0.006) | NeuroLink fallback and `models.visionModel`. Usage notes "Prompt caching", "Native vision (text and images)". | | `deepseek-v4-pro-0813` | 1,048,576 | 1,048,576 | — | $1.32 / $3.96 ($0.044) | Usage notes "Input context window of up to 1M tokens", "Prompt caching". | | `deepseek-v4-flash-0731` | 1,048,576 | 1,048,576 | — | $0.14 / $0.28 ($0.028) | NeuroLink fallback. Usage notes "Input context window of up to 1M tokens", "Prompt caching". | | `deepseek-3.2` | 163,840 | 163,840 | — | $0.50 / $1.60 ($0.15) | Models page row "DeepSeek V3.2". Usage note "Prompt caching". | | `glm-5.2` | 262,144 | 262,144 | — | $1.40 / $4.40 ($0.21) | NeuroLink fallback. Usage notes "Text only", "Tool calling", "Structured outputs", "Reasoning". | | `kimi-k2.6` | 262,144 | 262,144 | yes | $0.95 / $4.00 ($0.19) | NeuroLink fallback. Models by Provider table: "both with prompt caching and multimodal vision support"; Features page lists it with "Text and image inputs". | | `kimi-k3` | 1,048,576 | Not published | yes | $3.00 / $15.00 ($0.30) | Usage notes "Chat Completions API for sending prompts for serverless inference", "Native vision (text, images)"; Features page lists it with "Text and image inputs". | | `glm-5.3-flash` | 1,048,576 | 1,048,576 | yes | $0.15 / $0.50 ($0.03) | Usage notes "Multimodal: text, image, and video inputs", "Tool calling", "Structured outputs", "Reasoning". | | `mimo-v2.5-pro` | 262,144 | 262,144 | — | $0.80 / $3.00 ($0.16) | Models page row "MiMo V2.5 Pro". Usage notes "Text only", "Tool calling", "Structured outputs", "Reasoning". | | `nemotron-3-ultra-550b` | 131,072 | 131,072 | — | $0.90 / $1.70 | Models page row "Nemotron 3 Ultra". Usage note "Evaluations judge model". | | `gemma-4-31B-it` | 256,000 | 8,192 | — | $0.18 / $0.50 ($0.036) | NeuroLink fallback. Row "Gemma 4" on the models and pricing pages. Usage note "Prompt caching". | Context window, max output tokens and usage notes are from the [models page](https://docs.digitalocean.com/products/inference/details/models/); prices are from the [pricing page](https://docs.digitalocean.com/products/inference/details/pricing/) (USD per 1M tokens, Standard processing mode). Both were retrieved 2026-09-29. The ids have not been compared with a live `GET /v1/models` roster. On the models page the `glm-5.2` and `mimo-v2.5-pro` rows show context window 262,144 in the table and the usage note "Input context window of up to 1M tokens"; the entry records the table figure. `models.defaultContextWindow` (32,768) and `models.defaultMaxOutputTokens` (4,096) are placeholders the vendor does not publish. **Vision:** `vision: true` is set on the four rows above marked "yes", where the models page, the Features page or both state image input for that model. The entry sets `vision: false` on the other rows. **Fallback order** when the default is unavailable: `deepseek-v4.1-flash` → `deepseek-v4-flash-0731` → `glm-5.2` → `kimi-k2.6` → `gemma-4-31B-it`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `deepseek-v4-flash-0731`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for GradientAI — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://inference.do-ai.run/v1/models` answered HTTP 401 on 2026-09-29 without a key, so model ids are taken from the models page (retrieved 2026-09-29); roster not verified | | Auth-failure shape | the 401 body was `{"id": "Unauthorized", "message": "Unable to authenticate you" }`; `authProbe` records status 401, code `Unauthorized`; `errorRules` covers 401, 429 (body documented in the API reference) and the 404 "Model not found" response described on the Model Support Policy page | | Chat route | unauthenticated `GET https://inference.do-ai.run/v1/chat/completions` answered HTTP 405 with an empty body on 2026-09-29; the documented verb is POST and no POST was sent | | Billing | prepayment page: "Serverless Inference requires a positive prepaid account balance before you can send inference requests." — 2026-09-29 | | Tools / structured output | `tools` and `tool_choice` are in the API reference; "Tool calling" and "Structured outputs" appear as per-model usage notes on the models page; neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=gradientai` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting Each row restates what a DigitalOcean page says; the source page is named in the Symptom column. | Symptom | Cause | Fix | | ------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | HTTP 401 `Unable to authenticate you` ([API reference](https://docs.digitalocean.com/reference/api/reference/serverless-inference/)) | The API reference describes 401 as "Authentication failed due to invalid credentials." | Authenticate with a model access key or a DigitalOcean personal access token ([overview](https://docs.digitalocean.com/products/inference/how-to/si-overview/)) | | Key stops working ([model access keys page](https://docs.digitalocean.com/products/inference/how-to/manage-model-access-keys/)) | "Regeneration takes effect immediately, with no grace period during which both the old and new keys are valid." | "update any application that uses the key as soon as you regenerate it" | | Access suspended ([prepayment page](https://docs.digitalocean.com/products/inference/how-to/manage-serverless-inference-prepayment/)) | "When your balance reaches $0, DigitalOcean suspends your access to Serverless Inference until you replenish it." | "add a prepayment balance manually or enable auto-reload" | | HTTP 404 `Model not found` ([Model Support Policy](https://docs.digitalocean.com/products/inference/details/model-support-policy/)) | "The model is no longer accessible. Requests to these model IDs return a 404 Model not found error." (for deprecated models) | "Update the model ID parameter in your code to the new model ID" | | HTTP 429 ([API reference](https://docs.digitalocean.com/reference/api/reference/serverless-inference/)) | The API reference describes 429 as "The API rate limit has been exceeded." | — | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [Providers index](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) - DigitalOcean pages opened for this entry: [Use Serverless Inference](https://docs.digitalocean.com/products/inference/how-to/use-serverless-inference/), [Serverless Inference API Endpoints](https://docs.digitalocean.com/products/inference/how-to/si-endpoints/), [Chat Completions API](https://docs.digitalocean.com/products/inference/how-to/use-chat-completions-api/), [Available models](https://docs.digitalocean.com/products/inference/details/models/), [Pricing](https://docs.digitalocean.com/products/inference/details/pricing/), [Features](https://docs.digitalocean.com/products/inference/details/features/) --- ## Groq Provider Guide # Groq Provider Guide **Sub-100ms inference of open-weight models via Groq's LPU — best for latency-sensitive applications** ## Quick Start ### 1. Get an API Key Sign up at [https://console.groq.com/](https://console.groq.com/) and create an API key at [https://console.groq.com/keys](https://console.groq.com/keys). ### 2. Configure Environment ```bash # Required GROQ_API_KEY=gsk_... # Optional: override the default model (default: llama-3.3-70b-versatile) GROQ_MODEL=llama-3.1-8b-instant # Optional: override the base URL # GROQ_BASE_URL=https://api.groq.com/openai/v1 ``` ### 3. Generate Your First Response ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "groq", input: { text: "What's the fastest way to compute Fibonacci numbers?" }, }); console.log(result.content); ``` --- ## SDK Usage ### Basic Generation ```typescript const result = await ai.generate({ provider: "groq", input: { text: "Write a haiku about programming." }, }); ``` ### Lowest-Latency Tier For chatbots / autocomplete where TTFT matters most: ```typescript const result = await ai.generate({ provider: "groq", model: "llama-3.1-8b-instant", input: { text: "What's 2+2?" }, }); ``` ### Vision Input ```typescript const screenshot = readFileSync("./screenshot.png"); const result = await ai.generate({ provider: "groq", model: "llama-3.2-90b-vision-preview", input: { text: "What's wrong with this UI?", images: [screenshot], }, }); ``` ### Streaming Streaming through Groq is particularly responsive due to the LPU: ```typescript const stream = await ai.stream({ provider: "groq", input: { text: "Explain how B-trees work, step by step." }, }); for await (const chunk of stream.stream) { if ("content" in chunk) process.stdout.write(chunk.content); } ``` ### Tool Calling ```typescript const result = await ai.generate({ provider: "groq", input: { text: "What's the weather in San Francisco?" }, tools: { getWeather: { description: "Get current weather", parameters: { location: { type: "string" } }, execute: async ({ location }) => `72°F sunny in ${location}`, }, }, }); ``` For tool-heavy workflows, consider `llama3-groq-70b-8192-tool-use-preview` (a tool-tuned variant). ### Per-Call Credentials ```typescript const result = await ai.generate({ provider: "groq", input: { text: "..." }, credentials: { groq: { apiKey: "user-key" } }, }); ``` --- ## CLI Usage ```bash # Default model pnpm run cli generate "Quick question" --provider groq # Lowest latency pnpm run cli generate "Hi" --provider groq --model llama-3.1-8b-instant # Vision pnpm run cli generate "Describe this" --provider groq \ --model llama-3.2-90b-vision-preview --image ./pic.jpg # Loop / chat pnpm run cli loop --provider groq ``` --- ## Provider Aliases | Alias | Example | | ------ | ----------------- | | `groq` | `--provider groq` | --- ## Configuration Reference | Environment Variable | Required | Default | Description | | -------------------- | -------- | -------------------------------- | ------------- | | `GROQ_API_KEY` | Yes | — | Groq API key | | `GROQ_MODEL` | No | `llama-3.3-70b-versatile` | Default model | | `GROQ_BASE_URL` | No | `https://api.groq.com/openai/v1` | Base URL | --- ## Feature Support Matrix | Feature | llama-3.3-70b | llama-3.1-8b-instant | llama-3.2-vision | mixtral-8x7b | gemma2-9b | | ----------------- | ------------- | -------------------- | ---------------- | ------------ | --------- | | Text generation | Yes | Yes | Yes | Yes | Yes | | Streaming | Yes | Yes | Yes | Yes | Yes | | Tool calling | Yes | Yes | Limited | Yes | Yes | | Structured output | Yes | Yes | Limited | Yes | Yes | | Vision | No | No | Yes | No | No | | Embeddings | No | No | No | No | No | | Context window | 128K | 128K | 128K | 32K | 8K | --- ## Troubleshooting ### "Invalid Groq API key" ```bash echo $GROQ_API_KEY export GROQ_API_KEY=gsk_... ``` Get / rotate at [https://console.groq.com/keys](https://console.groq.com/keys). ### "Groq rate limit exceeded" Free-tier limits are tight (RPM and TPM). Implement exponential backoff or upgrade at [https://console.groq.com/settings/billing](https://console.groq.com/settings/billing). ### "Groq model 'X' was decommissioned" Groq deprecates older models periodically. Pick a current model from [https://console.groq.com/docs/models](https://console.groq.com/docs/models). ### "Whisper-large-v3 is in the model list — can I transcribe?" The Whisper models on Groq are STT (speech-to-text), not chat models. Use NeuroLink's STT path with `provider: "openai-stt"` or `"deepgram"` for transcription — Groq's Whisper endpoint isn't exposed through the LLM provider class today. ### Latency feels normal, not sub-100ms TTFT depends on input prompt length and model size. For sub-100ms, keep the prompt short (\<200 tokens) and use `llama-3.1-8b-instant`. Also: ensure your network round-trip to `api.groq.com` is low — test from a region close to Groq's PoPs. --- ## See Also - [xAI Grok Provider](/docs/getting-started/providers/xai) — sibling OpenAI-compat with Grok 3 - [DeepSeek Provider](/docs/getting-started/providers/deepseek) — sibling with reasoning models - Together AI — sibling open-model gateway (no setup doc yet; see `src/lib/providers/togetherAi.ts`) - [Adding a new LLM provider](/docs/provider-integration/15-adding-llm-provider) — internal reference --- **Need Help?** Open a [GitHub Discussion](https://github.com/juspay/neurolink/discussions) or [issue](https://github.com/juspay/neurolink/issues). --- ## Hetzner Inference Provider Guide # Hetzner Inference Provider Guide Hetzner Inference is a **Tier-2 catalog provider**: its integration is one JSON file (`src/lib/providers/catalog/hetzner-inference.json`) rather than hand-written code. That file is the source of truth for this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** Hetzner's `GET /models` needs a key, so the model ids come > from its public docs page and the roster has not been checked. No account was > created and no API key was used to build the entry. `evidence.liveMatrix` is > `null` (see [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API token 1. Visit: https://experiments.hetzner.com/inference — the page is client-rendered; its public JavaScript bundle labels the token area "Tokens" and the button "Create API Token" (sign-in was not attempted while building this entry) 2. Create an API token and copy it. The docs' curl examples (https://docs.hetzner.com/general/company-and-policy/experiments/inference/) use the header `Authorization: Bearer ` 3. Billing as the vendor states it: "As long as the Inference API remains in experimental status, it is free of charge." (FAQ, same docs page) 4. Set `HETZNER_INFERENCE_API_KEY` in your .env file ### 2. Configure ```bash export HETZNER_INFERENCE_API_KEY=your-api-token export HETZNER_INFERENCE_MODEL=Qwen/Qwen3.6-35B-A3B-FP8 # optional — overrides the default model export HETZNER_INFERENCE_BASE_URL=https://inference.hetzner.com/api/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "hetzner-inference", model: "Qwen/Qwen3.6-35B-A3B-FP8", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider hetzner-inference ``` Per-request credentials: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "hetzner-inference", credentials: { hetznerInference: { apiKey: process.env.HETZNER_INFERENCE_API_KEY }, }, }); ``` --- ## Models | Model | Context | Vision | Notes | | ----------------------------- | ------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `Qwen/Qwen3.6-35B-A3B-FP8` ⭐ | 262,144 | yes | NeuroLink default. Type "Causal LM + Vision (MoE, 35B total / 3B active)"; named in the docs page's four code examples, including its image example. | | `Qwen3.8-27B` | 262,144 | yes | Fallback. Type "Dense"; Modalities "Text, Image". | The figures come from the Available Models table of https://docs.hetzner.com/general/company-and-policy/experiments/inference/ (retrieved 2026-09-29): Context Length "262,144 tokens" and Modalities "Text, Image" on both rows. The same page says "Only a selected list of models is available. This selection will change during the experimental phase." and "The response of the models endpoint is definitive." `models.defaultContextWindow` (32,768) and `models.defaultMaxOutputTokens` (4,096) are placeholders the vendor does not publish. They apply to model ids outside the catalog, and the output figure applies to both catalog rows, which carry no `maxOutputTokens`. **Fallback order** when the default is unavailable: `Qwen3.8-27B`. Licenses, as the page's Open-Source Model Licenses table lists them: rows "Qwen3.6-35B-A3B" and "Qwen3.8-27B", each with Developer "Alibaba Cloud (Qwen Team)" and License "Apache 2.0". The page also says "By using this API, you acknowledge the applicable license terms of the underlying model(s)." --- ## Rate limits The docs FAQ says "Current limits are applied per API key:" followed by a table with Timeframe "60s", Input Tokens "4M" and Output Tokens "100k". A second table, introduced by "Additionally, we enforce request-level rate-limits as follows:", lists Timeframe "60s" and Requests "10". The FAQ continues: "If you exceed any of the rate limits, the API will respond with HTTP Status Code 429." `errorRules` maps HTTP 429 to NeuroLink's rate-limit error class and HTTP 401 to its authentication class. --- ## Data handling The docs FAQ says "We do not store the content of request and response and we do not plan on doing so in the future (unless some law requires us to do so)." --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Hetzner Inference — **docs-verified only, not live-verified**: | Probe | Result | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://inference.hetzner.com/api/v1/models`, HTTP 401, 2026-09-29 — no key used; the model ids are taken from the docs page's Available Models table, and the roster has not been checked | | Auth-failure shape | the same unauthenticated `GET /models` returned HTTP 401, content-type `application/json; charset=utf-8`, body `{"error":"unauthorized"}`; an unauthenticated `GET /chat/completions` on the same day answered HTTP 404, content-type `text/plain; charset=utf-8`, body "404 page not found". No POST request was sent | | Billing | public docs FAQ, 2026-09-29: "As long as the Inference API remains in experimental status, it is free of charge. Should this status change, we will notify you in advance via email with detailed information." | | Capabilities | `text` is `true` because the docs page shows chat-completion examples in Python and curl; the other capability flags are `false` (not declared), and no request exercising them was sent | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. | --- ## Troubleshooting | Symptom | What the vendor states or what was observed | | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | HTTP 401 | Observed 2026-09-29: an unauthenticated `GET /models` answered HTTP 401 with `{"error":"unauthorized"}`. NeuroLink reads the token from `HETZNER_INFERENCE_API_KEY` | | HTTP 429 | Docs FAQ: "If you exceed any of the rate limits, the API will respond with HTTP Status Code 429." Limits are listed under [Rate limits](#rate-limits) | | Model ids differ from the table above | Docs page: "This selection will change during the experimental phase." and "The response of the models endpoint is definitive." | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## HeyGen Provider Guide (avatar) # HeyGen Provider Guide **Talking-head avatar videos via HeyGen's V2 API** ## Quick Start ### 1. Get an API Key + Avatar ID [https://app.heygen.com/settings/api](https://app.heygen.com/settings/api) and pick an avatar id from your avatar library. ### 2. Configure ```bash HEYGEN_API_KEY=your-key HEYGEN_TEST_AVATAR_ID=avatar_xxx # Optional — for the avatar test suite ``` ### 3. Generate ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "vertex", // unused — driven by output.avatar output: { mode: "avatar", avatar: { provider: "heygen", image: "avatar_xxx", // HeyGen avatar id text: "Hello from NeuroLink", // HeyGen runs TTS internally voice: "voice_xxx", // HeyGen voice id (optional) }, }, }); if (result.avatar?.buffer) { writeFileSync("./avatar.mp4", result.avatar.buffer); } ``` --- ## CLI Usage ```bash pnpm run cli generate "Hello world" \ --provider heygen \ --avatarImage avatar_xxx \ --avatarVoice voice_xxx \ --avatarOutput ./avatar.mp4 ``` --- ## Configuration Reference | Environment Variable | Required | Description | | ----------------------- | -------- | -------------------------------- | | `HEYGEN_API_KEY` | Yes | HeyGen API key | | `HEYGEN_TEST_AVATAR_ID` | No | Optional avatar id for test runs | --- ## See Also - [D-ID Provider](/docs/getting-started/providers/d-id) - [MuseTalk via Replicate](/docs/getting-started/providers/musetalk) --- ## Hugging Face Provider Guide # Hugging Face Provider Guide **Access open-source AI models through Hugging Face Inference Providers** ## Quick Start ### 1. Get Your API Token 1. Visit [Hugging Face](https://huggingface.co/) 2. Create a free account (no credit card required) 3. Go to [Settings → Access Tokens](https://huggingface.co/settings/tokens) 4. Click "New token" 5. Give it a name (e.g., "NeuroLink") 6. Select "Read" permissions 7. Copy the token (starts with `hf_...`) ### 2. Configure NeuroLink Add to your `.env` file: ```bash HUGGINGFACE_API_KEY=hf_your_token_here ``` :::warning[Security Best Practice] Never commit your API token to version control. Always use environment variables and add `.env` to your `.gitignore` file. ::: ### 3. Test the Setup ```bash # CLI - Test with default model npx @juspay/neurolink generate "Hello from Hugging Face!" --provider huggingface # CLI - Use specific model npx @juspay/neurolink generate "Write a poem" --provider huggingface --model "Qwen/Qwen2.5-72B-Instruct" # SDK node -e " const { NeuroLink } = require('@juspay/neurolink'); (async () => { const ai = new NeuroLink(); const result = await ai.generate({ input: { text: 'Hello from Hugging Face!' }, provider: 'huggingface' }); console.log(result.content); })(); " ``` --- ## Model Selection Guide ### Popular Models by Category #### 1. **General Text Generation** | Model | Size | Description | Best For | | ------------------------------------------- | ------- | ------------------------------------ | ------------------------------- | | `Qwen/Qwen2.5-72B-Instruct` | 72B | Qwen 2.5 instruction-tuned (default) | General tasks, high quality | | `Qwen/Qwen3-235B-A22B` | 235B | Latest Qwen 3 MoE flagship | Complex reasoning, multilingual | | `Qwen/Qwen3-32B` | 32B | Qwen 3 dense model | Balanced quality and speed | | `Qwen/Qwen3-8B` | 8B | Qwen 3 efficient model | Fast responses, low cost | | `meta-llama/Llama-3.3-70B-Instruct` | 70B | Meta Llama 3.3 instruction-tuned | Conversational AI, reasoning | | `meta-llama/Llama-4-Scout-17B-16E-Instruct` | 17B MoE | Meta Llama 4 Scout | Efficient multimodal tasks | | `deepseek-ai/DeepSeek-R1` | 671B | DeepSeek reasoning model | Math, logic, step-by-step | | `deepseek-ai/DeepSeek-V3-0324` | 671B | DeepSeek V3 general-purpose | General tasks, coding | | `google/gemma-3-27b-it` | 27B | Google Gemma 3 instruction-tuned | General tasks, research | | `google/gemma-3-12b-it` | 12B | Google Gemma 3 mid-size | Balanced performance | | `google/gemma-3-4b-it` | 4B | Google Gemma 3 lightweight | Edge deployment, fast | | `microsoft/phi-4` | 14B | Microsoft Phi-4 | Reasoning, STEM tasks | #### 2. **Code Generation** | Model | Description | Best For | | ----------------------------------- | --------------------------------- | ---------------------- | | `Qwen/Qwen2.5-Coder-32B-Instruct` | Qwen 2.5 code specialist | Complex coding tasks | | `deepseek-ai/DeepSeek-V3-0324` | DeepSeek V3 with strong code perf | Full-stack development | | `meta-llama/Llama-3.3-70B-Instruct` | Llama 3.3 with code capabilities | Code review, refactor | #### 3. **Summarization** | Model | Description | Best For | | ------------------------- | ------------------------- | -------------------- | | `facebook/bart-large-cnn` | News summarization | Articles, news | | `Qwen/Qwen3-8B` | Qwen 3 with summarization | General summaries | | `google/pegasus-xsum` | Extreme summarization | Very brief summaries | #### 4. **Translation** | Model | Languages | Best For | | ------------------------------------------ | -------------- | -------------------------- | | `facebook/mbart-large-50-many-to-many-mmt` | 50 languages | Multi-language translation | | `Helsinki-NLP/opus-mt-*` | Language pairs | Specific language pairs | #### 5. **Question Answering** | Model | Description | Best For | | ----------------------------- | ------------------- | -------------- | | `deepset/roberta-base-squad2` | SQuAD-trained | Factual Q&A | | `Qwen/Qwen2.5-72B-Instruct` | General QA via chat | Open-ended Q&A | ### Model Selection by Use Case ```typescript // General conversation const general = await ai.generate({ input: { text: "Explain quantum computing" }, provider: "huggingface", model: "Qwen/Qwen2.5-72B-Instruct", }); // Code generation const code = await ai.generate({ input: { text: "Write a Python function to sort a list" }, provider: "huggingface", model: "Qwen/Qwen2.5-Coder-32B-Instruct", }); // Summarization const summary = await ai.generate({ input: { text: "Summarize: [long article text]" }, provider: "huggingface", model: "facebook/bart-large-cnn", }); // Translation const translation = await ai.generate({ input: { text: "Translate to French: Hello, how are you?" }, provider: "huggingface", model: "facebook/mbart-large-50-many-to-many-mmt", }); ``` --- ## Free Tier Details ### What's Included - ✅ **Monthly credits** for Inference Providers on a free account - ✅ **No credit card** required for the free credits - ⚠️ **`402` once the credits are spent** — buy pre-paid credits or subscribe to PRO to continue See [Hugging Face's pricing page](https://huggingface.co/docs/inference-providers/pricing) for the current allowance. ### Spending the credits - **Best Practice**: Combine with other providers so a spent allowance falls back instead of failing ```typescript // Rate limit friendly approach const ai = new NeuroLink({ providers: [ { name: "huggingface", priority: 1 }, // Free tier first { name: "google-ai", priority: 2 }, // Fallback to Google AI ], }); ``` ### Limitations ⚠️ **Free Tier Constraints:** - Models load on-demand (first request may be slow) - Rate limits per model (use multiple models to scale) - No guaranteed uptime (community infrastructure) - Some popular models may have queues **For Production:** - Use Hugging Face for experimentation - Consider paid inference for critical workloads - Combine with other providers for reliability --- ## SDK Integration ### Basic Usage ```typescript const ai = new NeuroLink(); // Simple generation const result = await ai.generate({ input: { text: "Write a haiku about coding" }, provider: "huggingface", }); console.log(result.content); ``` ### With Specific Model ```typescript // Use Qwen 2.5 for instruction following const qwen = await ai.generate({ input: { text: "Explain Docker in simple terms" }, provider: "huggingface", model: "Qwen/Qwen2.5-72B-Instruct", }); // Use Qwen Coder for code generation const coder = await ai.generate({ input: { text: "Create a REST API endpoint in Express.js" }, provider: "huggingface", model: "Qwen/Qwen2.5-Coder-32B-Instruct", }); ``` ### Multi-Model Strategy ```typescript // Try multiple models for best results const models = [ "Qwen/Qwen2.5-72B-Instruct", "meta-llama/Llama-3.3-70B-Instruct", "google/gemma-3-27b-it", ]; for (const model of models) { try { const result = await ai.generate({ input: { text: "Your prompt here" }, provider: "huggingface", model, }); console.log(`${model}: ${result.content}`); } catch (error) { console.log(`${model} failed, trying next...`); } } ``` ### With Streaming ```typescript // Stream responses for better UX const result = await ai.stream({ input: { text: "Write a long story about space exploration" }, provider: "huggingface", model: "Qwen/Qwen2.5-72B-Instruct", }); for await (const chunk of result.stream) { process.stdout.write(chunk.content); } ``` ### With Error Handling ```typescript try { const result = await ai.generate({ input: { text: "Your prompt" }, provider: "huggingface", maxTokens: 500, temperature: 0.7, }); console.log(result.content); } catch (error) { if (error.message.includes("rate limit")) { console.log("Rate limited - try another model or wait"); } else if (error.message.includes("loading")) { console.log("Model is loading - try again in a moment"); } else { console.error("Error:", error.message); } } ``` --- ## CLI Usage ### Basic Commands ```bash # Generate with default model npx @juspay/neurolink generate "Hello world" --provider huggingface # Use specific model npx @juspay/neurolink gen "Write code" --provider huggingface --model "Qwen/Qwen2.5-Coder-32B-Instruct" # Stream response npx @juspay/neurolink stream "Tell a story" --provider huggingface # Check available models npx @juspay/neurolink models --provider huggingface ``` ### Advanced Usage ```bash # With temperature control npx @juspay/neurolink gen "Creative story" \ --provider huggingface \ --model "Qwen/Qwen2.5-72B-Instruct" \ --temperature 0.9 \ --max-tokens 1000 # Save output to file npx @juspay/neurolink gen "Technical documentation" \ --provider huggingface \ --model "google/gemma-3-27b-it" \ > output.txt # Interactive mode npx @juspay/neurolink loop --provider huggingface ``` ### Model Comparison ```bash # Compare different models for model in "Qwen/Qwen2.5-72B-Instruct" \ "meta-llama/Llama-3.3-70B-Instruct" \ "google/gemma-3-27b-it"; do echo "Testing $model:" npx @juspay/neurolink gen "What is AI?" \ --provider huggingface \ --model "$model" echo "---" done ``` --- ## Configuration Options ### Environment Variables ```bash # Required HUGGINGFACE_API_KEY=hf_your_token_here # Optional HUGGINGFACE_BASE_URL=https://api-inference.huggingface.co # Custom endpoint HUGGINGFACE_MODEL=Qwen/Qwen2.5-72B-Instruct # Default model HUGGINGFACE_TIMEOUT=60000 # Request timeout (ms) ``` ### Programmatic Configuration ```typescript const ai = new NeuroLink({ providers: [ { name: "huggingface", config: { apiKey: process.env.HUGGINGFACE_API_KEY, defaultModel: "Qwen/Qwen2.5-72B-Instruct", timeout: 60000, }, }, ], }); ``` --- ## Troubleshooting ### Common Issues #### 1. "Model is currently loading" **Problem**: Model hasn't been used recently and needs to load. **Solution**: ```bash # Wait 20-30 seconds and retry # Or use a popular model that's always loaded npx @juspay/neurolink gen "test" \ --provider huggingface \ --model "Qwen/Qwen2.5-72B-Instruct" ``` #### 2. "Rate limit exceeded" **Problem**: Too many requests in a short window. A `402` instead means the monthly credits are spent — see [Free credits](#spending-the-credits). **Solution**: ```typescript // Switch to a different model const alternativeModels = [ "Qwen/Qwen2.5-72B-Instruct", "google/gemma-3-27b-it", "meta-llama/Llama-3.3-70B-Instruct", ]; // Or use multi-provider fallback const ai = new NeuroLink({ providers: [ { name: "huggingface", priority: 1 }, { name: "google-ai", priority: 2 }, // Fallback ], }); ``` #### 3. "Invalid API token" **Problem**: Token is incorrect or expired. **Solution**: 1. Verify token at https://huggingface.co/settings/tokens 2. Ensure token has "Read" permissions 3. Check for typos in `.env` file 4. Token should start with `hf_` #### 4. "Model not found" **Problem**: Model name is incorrect or private. **Solution**: ```bash # Verify model exists at huggingface.co # Use exact model ID: username/model-name npx @juspay/neurolink gen "test" \ --provider huggingface \ --model "Qwen/Qwen2.5-72B-Instruct" # ✅ Correct format ``` #### 5. Slow Response Times **Problem**: Model is loading or under high load. **Solution**: - Use popular models (always loaded) - Add timeout handling - Consider caching results - Use streaming for long responses ```typescript const result = await ai.generate({ input: { text: "Your prompt" }, provider: "huggingface", timeout: 120000, // 2 minute timeout }); ``` --- ## Best Practices ### 1. Model Selection ```typescript // ✅ Good: Use appropriate model for task const code = await ai.generate({ input: { text: "Write a function" }, model: "Qwen/Qwen2.5-Coder-32B-Instruct", // Code specialist }); // ❌ Avoid: Using a task-specific model for unrelated tasks const badCode = await ai.generate({ input: { text: "Write a function" }, model: "facebook/bart-large-cnn", // Summarization model, not for code }); ``` ### 2. Rate Limit Management ```typescript // ✅ Good: Rotate between models const models = [ "Qwen/Qwen2.5-72B-Instruct", "google/gemma-3-27b-it", "meta-llama/Llama-3.3-70B-Instruct", ]; let requestCount = 0; // Track the number of requests const modelIndex = requestCount % models.length; const result = await ai.generate({ input: { text: prompt }, provider: "huggingface", model: models[modelIndex], }); requestCount++; // Increment after each request ``` ### 3. Error Handling ```typescript // ✅ Good: Handle model loading gracefully async function generateWithRetry(prompt, maxRetries = 3) { for (let i = 0; i setTimeout(resolve, 30000)); } else { throw error; } } } } ``` ### 4. Production Deployment ```typescript // ✅ Good: Use Hugging Face with fallback const ai = new NeuroLink({ providers: [ { name: "huggingface", priority: 1, config: { defaultModel: "Qwen/Qwen2.5-72B-Instruct", }, }, { name: "google-ai", // Free tier fallback priority: 2, }, { name: "anthropic", // Paid fallback for critical priority: 3, }, ], }); ``` --- ## Performance Optimization ### 1. Model Warm-Up ```typescript // Keep popular models warm with periodic requests setInterval(async () => { await ai.generate({ input: { text: "ping" }, provider: "huggingface", model: "Qwen/Qwen2.5-72B-Instruct", maxTokens: 1, }); }, 300000); // Every 5 minutes ``` ### 2. Caching ```typescript // Cache responses for repeated queries const cache = new Map(); async function cachedGenerate(prompt) { if (cache.has(prompt)) { return cache.get(prompt); } const result = await ai.generate({ input: { text: prompt }, provider: "huggingface", }); cache.set(prompt, result); return result; } ``` ### 3. Parallel Requests ```typescript // Use different models in parallel to avoid rate limits const prompts = ["prompt1", "prompt2", "prompt3"]; const models = [ "Qwen/Qwen2.5-72B-Instruct", "google/gemma-3-27b-it", "meta-llama/Llama-3.3-70B-Instruct", ]; const results = await Promise.all( prompts.map((prompt, i) => ai.generate({ input: { text: prompt }, provider: "huggingface", model: models[i], }), ), ); ``` --- ## Related Documentation - **[Provider Setup Guide](/docs/getting-started/provider-setup)** - General provider configuration - **[SDK API Reference](/docs/sdk/api-reference)** - Complete API documentation - **[CLI Commands](/docs/cli/commands)** - CLI reference - **[Multi-Provider Failover](/docs/guides/enterprise/multi-provider-failover)** - Enterprise patterns --- ## Additional Resources - **[Hugging Face Models](https://huggingface.co/models)** - Browse all models - **[Hugging Face Inference API](https://huggingface.co/docs/api-inference/index)** - API documentation - **[Model Cards](https://huggingface.co/docs/hub/model-cards)** - Understanding model capabilities - **[Hugging Face Hub](https://huggingface.co/docs/hub/index)** - Platform documentation --- **Need Help?** Join our [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## Ideogram Provider Guide (image-gen) # Ideogram Provider Guide **Text-aware image generation via Ideogram V3** ## Quick Start ### 1. Get an API Key [https://ideogram.ai/manage-api](https://ideogram.ai/manage-api) ### 2. Configure ```bash IDEOGRAM_API_KEY=your-key ``` ### 3. Generate an Image ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "ideogram", model: "V_3", input: { text: 'Movie poster with the title "Test Run", dramatic lighting' }, }); if (result.imageOutput?.base64) { writeFileSync( "./poster.png", Buffer.from(result.imageOutput.base64, "base64"), ); } ``` --- ## Supported Models | Model ID | Notes | | -------- | ------------------------- | | `V_3` | Default; current flagship | | `V_2` | Earlier version | --- ## CLI Usage ```bash pnpm run cli generate 'Vintage travel poster: "Tokyo 1985"' \ --provider ideogram --imageOutput ./poster.png ``` --- ## Configuration Reference | Environment Variable | Required | Default | | -------------------- | -------- | ------- | | `IDEOGRAM_API_KEY` | Yes | — | | `IDEOGRAM_MODEL` | No | `V_3` | --- ## See Also - [Stability AI Provider](/docs/getting-started/providers/stability) - [Recraft Provider](/docs/getting-started/providers/recraft) --- ## Inception Labs Provider Guide # Inception Labs Provider Guide Inception Labs is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/inception-labs.json`) rather than hand-written code. That file is the source of truth for everything on this page. ## Quick Start ### 1. Get an API key 1. Visit: https://platform.inceptionlabs.ai and sign in (Google OAuth works) 2. New accounts get 100M free tokens with no card required 3. Create an API key under Dashboard -> API Keys 4. Set `INCEPTION_LABS_API_KEY` in your .env file ### 2. Configure ```bash export INCEPTION_LABS_API_KEY=your-api-key export INCEPTION_LABS_MODEL=mercury-2 # optional — overrides the default model export INCEPTION_LABS_BASE_URL=https://api.inceptionlabs.ai/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "inception-labs", model: "mercury-2", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider inception-labs ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "inception-labs", credentials: { inceptionLabs: { apiKey: process.env.INCEPTION_LABS_API_KEY }, }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | -------------- | ------- | ------ | ------------- | ------------------------------------------------------------------------------------------------------------------------- | | `mercury-2` ⭐ | 125K | no | $0.25 / $0.75 | Mercury 2, Inception's enterprise diffusion LLM (dLLM); reasoning, tool use, structured output; 128K context, 1000+ tok/s | **Fallback order** when the default is unavailable: `mercury-2`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for Inception Labs: | Probe | Result | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | authenticated GET /v1/models, HTTP 200, 2026-09-03 | | Auth rejection | HTTP 401 `invalid_api_key`, 2026-09-03 | | Live capability sweep | 2026-09-03 — Full capability sweep on mercury-2: chat, stream, system_role, content_text_parts, sampling_params, tools, tools_stream, tools_roundtrip_null, tool_choice_without_tools, json_object, json_schema and tools_plus_schema all | --- ## Troubleshooting | Symptom | Cause | Fix | | -------------------------------- | --------------------------------------- | --------------------------------------------------------------------- | | `Invalid Inception Labs API key` | `INCEPTION_LABS_API_KEY` unset or wrong | Check the key at https://platform.inceptionlabs.ai/dashboard/api-keys | | Model not found | The roster changed since 2026-09-03 | Pick a current id; catalog providers retire models without notice | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Inceptron Provider Guide # Inceptron Provider Guide Inceptron is a **Tier-2 catalog provider**: an OpenAI-compatible endpoint described by one JSON file (`src/lib/providers/catalog/inceptron.json`) rather than hand-written code. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** The fields below come from Inceptron's own public pages, > an unauthenticated `GET /v1/models` call and an unauthenticated > `GET /v1/chat/completions` call — no account was created and no API key was > used to build it. `evidence.liveMatrix` is `null` until someone runs the live > capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://console.inceptron.io and sign in or sign up — the sign-in page shows Continue with Google, Continue with GitHub and Sign in with email, and links to https://console.inceptron.io/auth/signup 2. Create an API key — the Introduction page says: "After signing up, navigate to the account section of the dashboard to create an API key." (https://docs.inceptron.io/introduction) 3. Set `INCEPTRON_API_KEY` in your .env file (the docs' examples read INCEPTRON_API_KEY) The Authentication guide ([docs](https://docs.inceptron.io/Guides/authentication)) says: > You can find your API key in your Inceptron account dashboard under the "API Keys" section. ### 2. Configure ```bash export INCEPTRON_API_KEY=your-api-key export INCEPTRON_MODEL=zai-org/GLM-5.3 # optional — overrides the default model export INCEPTRON_BASE_URL=https://api.inceptron.io/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "inceptron", model: "zai-org/GLM-5.3", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider inceptron ``` Per-request credentials also work: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "inceptron", credentials: { inceptron: { apiKey: process.env.INCEPTRON_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out (cache read) | Notes | | ------------------------------------ | --------- | ------ | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `zai-org/GLM-5.3` ⭐ | 1,048,576 | no | $1.40 / $4.40 ($0.26) | NeuroLink default. The model in the docs' Get Started, Introduction, Chat Completions, Error Handling and Streaming code examples and in the Kilo Code and OpenCode config. Tags: text, code, tool-calling, reasoning. | | `moonshotai/Kimi-K2.6` | 262,144 | yes | $0.73 / $3.50 ($0.25) | NeuroLink fallback. The model in the docs' tool-calling examples. Tags: multimodal, tool-calling, reasoning. `models.visionModel`. | | `deepseek-ai/DeepSeek-V4-Flash-0731` | 1,048,576 | no | $0.13 / $0.28 ($0.03) | NeuroLink fallback. Tags: text, code, tool-calling, reasoning. | | `zai-org/GLM-5.2` | 1,048,576 | no | $1.20 / $4.20 ($0.26) | NeuroLink fallback. Tags: text, code, tool-calling, reasoning. | | `moonshotai/Kimi-K2.7-Code` | 262,144 | yes | $0.75 / $3.50 ($0.20) | Tags: multimodal, tool-calling, reasoning. | | `zai-org/GLM-5.3-Flash` | 1,048,576 | no | $0.15 / $0.50 ($0.07) | The vendor homepage shows the text "Try GLM 5.3 Flash". The models page shows "1.3M context"; the roster `context_length` is 1048576 and `contextWindow` uses that figure. Tags: text, code, tool-calling, reasoning. | Prices, the context labels ("1M context", "262K context") and the tags come from the models page, https://www.inceptron.io/models, opened 2026-09-29. The exact context figures 1,048,576 and 262,144 are the `context_length` values in an unauthenticated `GET https://api.inceptron.io/v1/models` call made the same day; for `zai-org/GLM-5.3` the Kilo Code guide also states "GLM-5.3 supports a 1M-token context window (1,048,576 tokens)" ([docs](https://docs.inceptron.io/Guides/kilo-code)). The `pricing` field in the roster response carries different values from the models page for each of the 6 models; this entry uses the models page. The roster's `max_output_length` is 1048576 for `zai-org/GLM-5.3`, `deepseek-ai/DeepSeek-V4-Flash-0731`, `zai-org/GLM-5.2` and `zai-org/GLM-5.3-Flash`, and 262144 for `moonshotai/Kimi-K2.6` and `moonshotai/Kimi-K2.7-Code`. The Kilo Code guide's config block for `zai-org/GLM-5.3` sets `limit` to context 1048576 and output 1048576. No per-model `maxOutputTokens` is set in the catalog entry. `models.defaultContextWindow` (128,000) and `models.defaultMaxOutputTokens` (16,384) are NeuroLink placeholders for model ids outside the catalog, not vendor figures. Each model's `status` field holds `production`, a placeholder for a value the catalog schema requires; it is not a vendor statement. The docs' [Models API Reference](https://docs.inceptron.io/API%20Reference/models) lists 18 ids: `deepseek-ai/DeepSeek-V4-Flash-0731`, `zai-org/GLM-5.3`, `moonshotai/Kimi-K2.7-Code`, `moonshotai/Kimi-K2.6` and `zai-org/GLM-5.2` with Deployment Mode `Serverless`, and 13 more with Deployment Mode `Custom`. The 13 `Custom` ids are not in the live roster and not in this catalog. **Vision:** `moonshotai/Kimi-K2.6` and `moonshotai/Kimi-K2.7-Code` are `vision: true` from the models page tag `multimodal` and the roster's `input_modalities` of `["text","image"]`; no image request was sent. The other four models have `input_modalities` of `["text"]` on the roster and are `vision: false`. **Fallback order** when the default is unavailable: `moonshotai/Kimi-K2.6` → `deepseek-ai/DeepSeek-V4-Flash-0731` → `zai-org/GLM-5.2`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `deepseek-ai/DeepSeek-V4-Flash-0731`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Inceptron — **docs- and roster-verified, not live-verified**: | Probe | Result | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /v1/models`, HTTP 200, 6 models, 2026-09-29 — no key used | | Auth-failure shape | unauthenticated `GET https://api.inceptron.io/v1/chat/completions`, HTTP 401, body `{"error":{"code":"unauthorized","message":"Missing or invalid authorization header","type":"invalid_request_error"}}`, 2026-09-29 — no key used. `errorRules` match 401 (probe and docs) and 429 (docs) | | Tools / structured output | tool calling and streamed tool calls are documented on the Chat Completions API Reference and the Tool Calling guide; neither tools nor structured output was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=inceptron` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting The Error Handling page (https://docs.inceptron.io/Guides/error-handling) lists these HTTP status codes, quoted as it shows them: | Status | Vendor's description | | ------ | --------------------------------------------------------------------------------------------- | | 400 | Your request was malformed. This could be due to missing required parameters or invalid JSON. | | 401 | Your API key is missing, invalid, or disabled. | | 429 | You have exceeded your rate limit. | | 500 | Something went wrong on our end. Please wait and try again. | --- ## Pages opened for this entry Opened on 2026-09-29 with unauthenticated GET requests: - https://docs.inceptron.io (Get Started) - https://docs.inceptron.io/introduction - https://docs.inceptron.io/API%20Reference/chat-completions - https://docs.inceptron.io/API%20Reference/models - https://docs.inceptron.io/Guides/authentication - https://docs.inceptron.io/Guides/error-handling - https://docs.inceptron.io/Guides/kilo-code - https://docs.inceptron.io/Guides/streaming-responses - https://docs.inceptron.io/Guides/tool-calling - https://www.inceptron.io/models - https://www.inceptron.io/pricing - https://console.inceptron.io - https://console.inceptron.io/auth/signup - https://api.inceptron.io/v1/models - https://api.inceptron.io/v1/chat/completions --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [Providers index](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Inco Provider Guide # Inco Provider Guide Inco is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/inco.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** Every field below was built from Inco's own published > documentation (`https://platform.inco.ai/docs`) and an unauthenticated > `GET https://api.inco.ai/v1/models` — no API key was used or obtained. > Capabilities that can only be proven with a working key (tool calling, > structured output, vision replies, the exact 401/404/429 error bodies) are > left conservative (`false`) or undocumented until a live capability sweep > runs. See [Live verification](#live-verification-still-needed) below. ## Quick Start ### 1. Get an API key 1. Visit: https://platform.inco.ai/waitlist and request access — Inco is currently waitlist-gated, not open signup; existing users sign in at https://platform.inco.ai/sign-in 2. Once approved, create an API key on the dashboard's Keys page (https://platform.inco.ai/keys) — it is shown in full only once and starts with `sk-inco-` 3. Add prepaid credit before use: billing is strictly pay-per-token with no free tier, and a zero balance returns HTTP 402 (`credit_balance_exhausted`) until you top up 4. Set `INCO_API_KEY` in your .env file ### 2. Configure ```bash export INCO_API_KEY=your-api-key export INCO_MODEL=glm-5.3 # optional — overrides the default model export INCO_BASE_URL=https://api.inco.ai/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "inco", model: "glm-5.3", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider inco ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "inco", credentials: { inco: { apiKey: process.env.INCO_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out (cached) | Notes | | -------------------------- | ------- | ------ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------ | | `glm-5.3` ⭐ | 1M | no | $1.40 / $4.40 ($0.26) | Default (editorial pick). Standard tier, 744B params, exposes `reasoning_effort`. | | `deepseek-v4.1-flash` | 1M | no | $0.30 / $1.20 ($0.006) | Standard tier, 552B params, `reasoning_effort`. Fallback. | | `kimi-k3` | 1M | no | $3.00 / $15.00 ($0.30) | Standard tier, 2.8T params (MoE), `reasoning_effort`. Fallback. | | `glm-5.3-flash` | 1M | no | $0.15 / $0.50 ($0.03) | Standard tier, 320B params. Fallback. | | `minimax-m3` | 1M | yes | $0.30 / $1.20 ($0.06) | Standard tier, 428B params, `reasoning_effort`. Vision per the catalog's `modalities` field — not live-probed. Fallback. | | `glm-5.3:fast` | 1M | no | $2.80 / $8.80 ($0.52) | Fast-tier sibling of the default; ~2x price for lower latency. Fallback. | | `kimi-k3:fast` | 1M | no | $6.00 / $30.00 ($0.60) | Fast-tier sibling of `kimi-k3`. Fallback. | | `deepseek-v4.1-flash:fast` | 1M | yes | $0.60 / $2.40 ($0.012) | Fast-tier sibling; vision per `modalities` (the non-fast id has no `modalities` field) — not live-probed. Fallback. | | `glm-5.3-flash:fast` | 1M | yes | $0.15 / $0.50 ($0.03) | Fast-tier sibling; vision per `modalities` (the non-fast id has no `modalities` field) — not live-probed. Fallback. | | `minimax-m3:fast` | 1M | yes | $0.60 / $2.40 ($0.12) | Fast-tier sibling of `minimax-m3`, same vision claim. Fallback. | Context window shown is the documented `context_length` of 1,048,576 tokens for every model (from the live, unauthenticated `GET /v1/models` response, 2026-09-28). Inco's catalog does not publish a separate per-request output token ceiling, so `defaultMaxOutputTokens` uses a conservative generic default (4,096) rather than an invented vendor number. Vision is read directly from the live catalog's own `modalities` field (`input: ["text","image"]`), which four of the ten ids carry and six do not — this is vendor-reported metadata, not a probed capability; no image request has actually been sent to Inco. **Fallback order** when the default is unavailable: `deepseek-v4.1-flash` → `kimi-k3` → `glm-5.3-flash` → `minimax-m3` → `glm-5.3:fast` → `kimi-k3:fast` → `deepseek-v4.1-flash:fast` → `glm-5.3-flash:fast` → `minimax-m3:fast`. --- ## Live verification still needed Tier-2 onboarding normally requires an authenticated roster probe, an auth rejection probe, and a live capability sweep (`docs/provider-integration/tiers/tier-2-catalog-entry.md`). This entry was built **credential-free** — no signup, no key, no POST request to Inco — so none of that could run yet: | Probe | Result | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | **Done.** Unauthenticated `GET /v1/models`, HTTP 200, 2026-09-28, 10 models — matches the vendor docs' claim that the catalog "can be fetched without a key." | | Docs cross-check | **Done.** `https://platform.inco.ai/docs` confirms the OpenAI Chat Completions wire shape, `Authorization: Bearer sk-inco-...` auth, and the documented error `code` values (`invalid_api_key`, `key_expired`, `model_not_found`, `rate_limit_exceeded`, `spend_limit_exceeded`, `credit_balance_exhausted`) used to build `errorRules` — no literal JSON error bodies were shown on the page, only the code table. | | Auth rejection (live) | **Not run.** Would require a `POST /v1/chat/completions` with a missing/bad key — out of scope for a credential-free pass. | | Billing (live) | **Not run.** Billing policy (`no-free-tier`, prepaid, HTTP 402 on empty balance) is taken from the docs' own wording, not a live probe. | | Tool calling | **Not documented, not probed.** `capabilities.tools` is `false` until the vendor's docs or a live probe show function calling. | | Structured output | **Not documented, not probed.** `capabilities.structuredOutput` and `structuredOutputWithTools` are `false` — no combined (or even single) probe was possible without a key. | | Vision | **Vendor-reported metadata only.** Four ids carry a `modalities` field naming image input; no image request has been sent. | | Live capability matrix | **Not run.** `evidence.liveMatrix` is `null`. Once a key is obtained (waitlist approval), run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=inco` and record the result there. | Anyone picking this up with a working key should re-run the roster probe (rosters drift), then follow the four-step live-verification checklist in `tiers/tier-2-catalog-entry.md` before flipping any capability flag from `false` to `true`. --- ## Troubleshooting | Symptom | Cause | Fix | | -------------------------------- | -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | `Invalid Inco API key` | `INCO_API_KEY` unset, wrong, or expired | Check the key on the dashboard's Keys page (https://platform.inco.ai/keys) | | Model not found | The roster changed since 2026-09-28, or the id is mistyped | Pick a current id from the unauthenticated `GET /v1/models` roster | | HTTP 402 on every request | Prepaid balance is empty (`credit_balance_exhausted`) — no free tier | Top up credit on the dashboard before retrying | | HTTP 429, `spend_limit_exceeded` | Your account's monthly spending cap was hit | Raise the cap on the Limits page, or wait for the next billing cycle | | HTTP 429, `rate_limit_exceeded` | Per-minute request limit hit | Back off and retry; check the `x-inco-ratelimit-scope` response header (`quota` vs `upstream`) | | Can't sign up | Access is currently gated by a waitlist, not open signup | Join the waitlist at https://platform.inco.ai/waitlist | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Inference.net Provider Guide # Inference.net Provider Guide Inference.net is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/inference-net.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** It was onboarded credential-free — built entirely from the > vendor's public documentation and an unauthenticated `GET /v1/models` call, > with no API key ever created or used. No chat/stream/tool/structured-output > request has been made against the live API yet. `evidence.liveMatrix` is > `null` until someone runs the live capability sweep in > [Live verification](/docs/provider-integration/tiers/tier-2-catalog-entry#live-verification) > with a real key. ## Quick Start ### 1. Get an API key 1. Visit: https://inference.net/register/ and sign up 2. Create an Inference.net project API key from the dashboard (this is the gateway key — do not confuse it with a third-party provider key used only for the separate "proxy mode") 3. New accounts start on a pay-as-you-go, $0-usage tier; confirm current terms at https://inference.net/pricing before heavy use 4. Set `INFERENCE_API_KEY` in your .env file ### 2. Configure ```bash export INFERENCE_API_KEY=your-api-key export INFERENCE_NET_MODEL=glm-5.2 # optional — overrides the default model export INFERENCE_NET_BASE_URL=https://api.inference.net/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "inference-net", model: "glm-5.2", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider inference-net ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "inference-net", credentials: { "inference-net": { apiKey: process.env.INFERENCE_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out · cache | Notes | | ------------------------ | ------- | ------ | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | `glm-5.2` ⭐ | 1M | no | $1.30 / $4.40 (cached $0.20) | Recommended — used in the vendor's own quickstart request example; native Zhipu GLM-5.2, hosted directly by Inference.net. | | `glm-5.3` | 1M | no | $0.90 / $3.00 (cached $0.15) | Newer GLM generation; one of the few roster models whose live entry lists chat + responses + messages endpoint support. | | `glm-5.3-flash` | 1M | yes | $0.09 / $0.28 (cached $0.02) | Cheapest model in this entry; the only one of these 8 whose live roster entry documents image + video input. | | `llama-3.3-70b-instruct` | 131K | no | $0.13 / $0.40 | Meta Llama 3.3 70B Instruct, open-weight; widely-recognized baseline fallback. | | `deepseek-v3.2` | 164K | no | $0.70 / $2.00 (cached $0.35) | DeepSeek V3.2, open-weight fallback. | | `gpt-4.1-mini` | 1M | yes | $0.40 / $1.60 (cached $0.10) | OpenAI GPT-4.1 mini, reachable through Inference.net's gateway. | | `gemini-2.5-flash` | 1M | yes | $0.30 / $2.50 (cached $0.03) | Google Gemini 2.5 Flash, reachable through the gateway. | | `claude-haiku-4-5` | 200K | yes | $1.00 / $5.00 (cached $0.10) | Anthropic Claude Haiku 4.5, reachable through the gateway; Claude-family entries list only the "messages" endpoint. | Context, pricing and vision (`input_modalities`) for every row above were read directly from the live, unauthenticated `GET https://api.inference.net/v1/models` response on 2026-09-28 (HTTP 200, 63 models total on the roster). This catalog entry lists a curated 8-model slice of that roster, not all 63 — the full list spans Claude, GPT, Gemini, DeepSeek, GLM, Kimi, Llama, Qwen, Gemma, Nemotron and Inference.net's own Schematron structured-extraction models. **Fallback order** when the default is unavailable: `glm-5.3` → `glm-5.3-flash` → `llama-3.3-70b-instruct` → `deepseek-v3.2` → `gpt-4.1-mini` → `gemini-2.5-flash` → `claude-haiku-4-5`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for Inference.net today: | Probe | Result | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | **unauthenticated** GET `/v1/models`, HTTP 200, 63 models, 2026-09-28. No API key was created or used. | | Auth rejection | Not probed — a real or invalid-key request would be an authenticated/POST call, which credential-free onboarding does not make. `errorRules` declares a conventional HTTP 401 → authentication mapping based on the vendor's "OpenAI-compatible" framing, not a live 401. | | Capability probes | Not run. `tools` and `response_format` are asserted **only** because the vendor's own API reference documents them as request parameters (https://docs.inference.net/api/api-quickstart, retrieved 2026-09-28); no combined tools+schema request was ever sent, so `structuredOutputWithTools` and `toolsWithStreaming` are both `false`. | | Live capability sweep | **Not run.** `evidence.liveMatrix` is `null`. A future pass with a real key must run the live matrix per [Live verification](/docs/provider-integration/tiers/tier-2-catalog-entry#live-verification) before this line is filled in. | Because no live request has ever been sent, every capability flag above should be read as "documented by the vendor," not "proven to work." NeuroLink's generic conflict-retry and JSON-repair layers are the intended safety net if a documented capability turns out to behave differently once probed live. --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Invalid Inference.net API key` | `INFERENCE_API_KEY` unset or wrong | Check the key in the Inference.net dashboard: https://inference.net/register/ | | Model not found | The roster changed since 2026-09-28 | Pick a current id from the live `GET /v1/models` roster | | Key rejected even though it looks right | The gateway key and a provider key (for "proxy mode") got swapped | Only the Inference.net project key goes in `INFERENCE_API_KEY`; a provider key (e.g. an OpenAI key) is only for the separate `x-inference-provider-api-key` proxy-mode header, not used by this catalog entry | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## io.net Intelligence Provider Guide # io.net Intelligence Provider Guide io.net Intelligence is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/io-intelligence.json`) rather than hand-written code. That file is the source of truth for everything on this page. ## Quick Start ### 1. Get an API key 1. Visit: https://ai.io.net/ 2. Sign in or create an io.net account 3. Create an API key for your project in the console 4. Set `IO_INTELLIGENCE_API_KEY` in your .env file ### 2. Configure ```bash export IO_INTELLIGENCE_API_KEY=your-api-key export IO_INTELLIGENCE_MODEL=meta-llama/Llama-3.3-70B-Instruct # optional — overrides the default model export IO_INTELLIGENCE_BASE_URL=https://api.intelligence.io.solutions/api/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "io-intelligence", model: "meta-llama/Llama-3.3-70B-Instruct", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider io-intelligence ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "io-intelligence", credentials: { ioIntelligence: { apiKey: process.env.IO_INTELLIGENCE_API_KEY }, }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ---------------------------------------------------- | ------- | ------ | -------------------- | --------------------------------------------------- | | `zai-org/GLM-5.3-Flash` | 256K | yes | $0.147997 / $0.49399 | Z.ai: GLM 5.3 Flash | | `zai-org/GLM-5.3` | 256K | no | $1.39 / $4.4 | Z.ai: GLM 5.3 | | `Qwen/Qwen3.8-27B` | 64K | yes | $0.39 / $2.99 | Qwen: Qwen3.8 27B | | `deepseek-ai/DeepSeek-V4-Flash-0731` | 256K | no | $0.196 / $0.534 | DeepSeek: DeepSeek V4 Flash 0731 | | `moonshotai/Kimi-K3` | 1M | yes | $3.18 / $15.9 | MoonshotAI: Kimi K3 | | `XiaomiMiMo/MiMo-V2.5` | 1M | no | $0.1934 / $0.6268 | Xiaomi: MiMo-V2.5 | | `zai-org/GLM-5.2` | 256K | no | $1.552 / $4.884 | Z.ai: GLM 5.2 | | `moonshotai/Kimi-K2.7-Code` | 256K | yes | $1.026 / $4.53 | MoonshotAI: Kimi K2.7 Code | | `Qwen/Qwen3.6-35B-A3B` | 256K | yes | $0.1872 / $1.24675 | Qwen: Qwen3.6 35B A3B | | `Qwen/Qwen3.6-27B` | 32K | yes | $0.399 / $3.19 | Qwen: Qwen3.6 27B | | `MiniMaxAI/MiniMax-M2.7` | 256K | no | $0.426 / $1.62 | MiniMaxAI: MiniMax M2.7 | | `deepseek-ai/DeepSeek-V4-Flash` | 32K | no | $0.199 / $0.512 | DeepSeek: DeepSeek V4 Flash | | `deepseek-ai/DeepSeek-V4-Pro` | 1M | no | $1.618 / $3.288 | DeepSeek: DeepSeek V4 Pro | | `moonshotai/Kimi-K2.6` | 256K | yes | $0.76744 / $3.43436 | MoonshotAI: Kimi K2.6 | | `zai-org/GLM-5.1` | 198K | no | $1.29 / $4.22 | Z.ai: GLM 5.1 | | `MiniMaxAI/MiniMax-M2.5` | 192K | no | $0.294 / $1.176 | MiniMaxAI/MiniMax-M2.5 | | `moonshotai/Kimi-K2.5` | 256K | yes | $0.5284 / $2.785 | MoonshotAI: Kimi K2.5 | | `zai-org/GLM-5` | 198K | no | $0.85 / $2.774 | Z.ai: GLM 5 | | `deepseek-ai/DeepSeek-V3.2` | 160K | no | $1.4301 / $2.4063 | DeepSeek: DeepSeek V3.2 | | `moonshotai/Kimi-K2-Thinking` | 256K | no | $0.6 / $2.5 | MoonshotAI: Kimi K2 Thinking | | `zai-org/GLM-4.5-Air` | 128K | no | $0.165 / $0.975 | Z.ai: GLM-4.5-Air | | `google/gemma-4-26b-a4b-it` | 256K | no | $0.116 / $0.38 | Google: Gemma 4 26B A4B | | `zai-org/GLM-4.7-Flash` | 195K | no | $0.062625 / $0.4 | Z.ai: GLM 4.7 Flash | | `zai-org/GLM-4.7` | 198K | no | $0.88 / $2.37 | Z.ai: GLM 4.7 | | `moonshotai/Kimi-K2-Instruct-0905` | 256K | no | $0.57 / $2.3 | MoonshotAI: Kimi K2 Instruct 0905 | | `openai/gpt-oss-120b` | 128K | no | $0.188 / $0.7 | OpenAI: gpt-oss-120b | | `deepseek-ai/DeepSeek-R1-0528` | 125K | no | $0.56775 / $2.279 | DeepSeek: R1 0528 | | `zai-org/GLM-4.6` | 128K | no | $0.536 / $2.07 | Z.ai: GLM 4.6 | | `Qwen/Qwen3-Next-80B-A3B-Instruct` | 256K | no | $0.1175 / $1.136 | Qwen: Qwen3 Next 80B A3B Instruct | | `Intel/Qwen3-Coder-480B-A35B-Instruct-int4-mixed-ar` | 104K | no | $0.445 / $2.145 | Intel: Qwen3 Coder 480B A35B Instruct INT4 Mixed AR | | `meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8` | 420K | yes | $0.274 / $0.8992 | Meta-Llama: Llama 4 Maverick 17B 128E Instruct FP8 | | `mistralai/Mistral-Nemo-Instruct-2407` | 125K | no | $0.0635 / $0.09875 | Mistral: Mistral Nemo Instruct 2407 | | `openai/gpt-oss-20b` | 63K | no | $0.067 / $0.24 | OpenAI: gpt-oss-20b | | `meta-llama/Llama-3.3-70B-Instruct` ⭐ | 125K | no | $0.6066 / $1.0386 | Meta: Llama 3.3 70B Instruct | **Fallback order** when the default is unavailable: `meta-llama/Llama-3.3-70B-Instruct` → `openai/gpt-oss-20b` → `zai-org/GLM-4.5-Air`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for io.net Intelligence: | Probe | Result | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | authenticated GET /v1/models, HTTP 200, 2026-09-03 | | Auth rejection | HTTP 401, 2026-09-03 | | Live capability sweep | 2026-09-03 — SDK end-to-end via dist: generate, stream, tool call (nonce round-trip) and json_schema structured output all pass. Tools + schema: after a tool result the vendor answers finish_reason=tool_calls with no tool_calls and n | --- ## Troubleshooting | Symptom | Cause | Fix | | ------------------------------------- | ---------------------------------------- | ----------------------------------------------------------------- | | `Invalid io.net Intelligence API key` | `IO_INTELLIGENCE_API_KEY` unset or wrong | Check the key at https://ai.io.net/ | | Model not found | The roster changed since 2026-09-03 | Pick a current id; catalog providers retire models without notice | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Jina AI Provider Guide # Jina AI Provider Guide **Multilingual embeddings + reranking through the Jina AI API** ## Quick Start ### 1. Get an API Key Sign up at [https://jina.ai/](https://jina.ai/) and grab a key from the dashboard. ### 2. Configure Environment ```bash JINA_API_KEY=your-jina-api-key # Optional: override the default model JINA_MODEL=jina-embeddings-v3 ``` ### 3. Generate Embeddings ```typescript const provider = await ProviderFactory.createProvider("jina"); const vector = await provider.embed("How does CRISPR-Cas9 work?"); console.log(vector.length); // 1024 ``` --- ## Supported Models | Model ID | Family | Dim | Notes | | ------------------------------------ | ---------- | ---- | ------------------------------------- | | `jina-embeddings-v3` | Embeddings | 1024 | Default; multilingual, 8K context | | `jina-embeddings-v2-base-en` | Embeddings | 768 | English, 8K context | | `jina-embeddings-v2-base-code` | Embeddings | 768 | Code-specialised | | `jina-reranker-v2-base-multilingual` | Reranking | n/a | Multilingual reranker (RAG pipelines) | --- ## CLI Usage ```bash # Generate an embedding via CLI (uses the SDK under the hood) pnpm run cli embed "What is photosynthesis?" --provider jina ``` --- ## Provider Aliases | Alias | Example | | ------ | ----------------- | | `jina` | `--provider jina` | --- ## Configuration Reference | Environment Variable | Required | Default | Description | | -------------------- | -------- | ------------------------ | ----------------- | | `JINA_API_KEY` | Yes | — | Jina AI API key | | `JINA_MODEL` | No | `jina-embeddings-v3` | Default model | | `JINA_BASE_URL` | No | `https://api.jina.ai/v1` | Base URL override | --- ## Feature Support Matrix | Feature | Support | | --------------- | ------------------------------ | | Text generation | No | | Streaming | No | | Tool calling | No | | Embeddings | Yes — `embed()`, `embedMany()` | | Reranking | Yes (via Jina Reranker model) | --- ## Troubleshooting - **`401 Unauthorized`** — check `JINA_API_KEY`. - **`429 Too Many Requests`** — Jina's free tier has tight per-minute caps. Add exponential backoff or upgrade your plan. --- ## See Also - [Voyage Provider](/docs/getting-started/providers/voyage) - [Cohere Provider](/docs/getting-started/providers/cohere) --- ## Kling AI Provider Guide (video) # Kling AI Provider Guide **Image-to-video generation via Kling AI** ## Quick Start ### 1. Get API Credentials Sign up at [https://kling.ai/](https://kling.ai/) and grab the Access Key ID + Secret from the developer dashboard. ### 2. Configure ```bash KLING_ACCESS_KEY=your-access-key KLING_SECRET_KEY=your-secret-key ``` ### 3. Generate a Video ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "kling", output: { mode: "video", video: { provider: "kling", resolution: "720p", length: 5 }, }, input: { text: "Smooth camera dolly through the scene, cinematic colour grade", images: [readFileSync("./input.jpg")], }, }); if (result.video?.data) { writeFileSync("./output.mp4", result.video.data); } ``` --- ## CLI Usage ```bash pnpm run cli generate "Camera pans left across the city" \ --image ./skyline.jpg \ --provider kling --videoOutput ./output.mp4 ``` --- ## Configuration Reference | Environment Variable | Required | Description | | -------------------- | -------- | ---------------- | | `KLING_ACCESS_KEY` | Yes | Kling access key | | `KLING_SECRET_KEY` | Yes | Kling secret key | --- ## See Also - [Runway Provider](/docs/getting-started/providers/runway) - [Vertex Veo Provider](/docs/getting-started/providers/google-vertex) --- ## KosCompute Provider Guide # KosCompute Provider Guide > **Verification status:** this entry is **docs- and roster-verified only — > not yet live-verified.** It was onboarded credential-free: no KosCompute > API key was ever created or used. Every field below comes from > KosCompute's public docs (`https://api.koscompute.com/docs/`) and an > **unauthenticated** `GET /v1/models` call (no auth header). No `POST` > request was ever sent, so no generate, stream, tool-calling or > structured-output capability has been exercised end to end. Treat > `capabilities.tools`, `.structuredOutput` and `.thinking` as > documentation-grade, not wire-proven, until `evidence.liveMatrix` is > filled in by a live run. KosCompute is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/koscompute.json`) rather than hand-written code. That file is the source of truth for everything on this page. ## Quick Start ### 1. Get an API key KosCompute does not publish a public signup or key-issuance flow. The quickstart docs assume the key already exists: 1. Obtain a key out of band (no public signup page exists as of 2026-09-28). 2. Confirm current billing terms directly with KosCompute — none are public. 3. Set `KOSCOMPUTE_API_KEY` in your `.env` file. 4. Optional sanity check before spending a real request: `curl https://api.koscompute.com/v1/models` needs no key and returns the live roster. ### 2. Configure ```bash export KOSCOMPUTE_API_KEY=your-api-key export KOSCOMPUTE_MODEL=qwen/qwen3.8-27b # optional — overrides the default model export KOSCOMPUTE_BASE_URL=https://api.koscompute.com/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain speculative decoding in one paragraph." }, provider: "koscompute", model: "qwen/qwen3.8-27b", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider koscompute ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "koscompute", credentials: { koscompute: { apiKey: process.env.KOSCOMPUTE_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | --------------------- | -------------------------------- | ------ | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `qwen/qwen3.8-27b` ⭐ | 262,144 (text) / 131,072 (image) | yes | $0.35 / $2.20 (cached $0.09) | Only chat-capable model in the roster. Reasoning-capable (`extended_thinking`, up to 8,192 thinking tokens, effort levels none/low/medium/xhigh). Max output 32,768 tokens. | Context window and max output shown are the catalog defaults (262,144 / 32,768 tokens), taken directly from the model's own entry in the live, unauthenticated `GET /v1/models` response (`context_length`, `max_output_length`) on 2026-09-28. Pricing is that same response's precomputed per-MTok fields (`input`, `output`, `cache_read`). **Fallback order:** none — `qwen/qwen3.8-27b` is the only chat model KosCompute serves, so it is both the default and its own (schema-exempt) single-entry fallback list. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for KosCompute — and, just as importantly, what it does **not** yet record: | Probe | Result | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | **unauthenticated** GET `/v1/models`, HTTP 200, 7 models, 2026-09-28. No API key was used or required for this call. | | Auth rejection | Not probed. Would require a `POST` with an invalid key, which this credential-free onboarding pass does not send. | | Live capability sweep | **Not run.** `evidence.liveMatrix` is `null`. `capabilities.tools`, `.structuredOutput`, `.toolsWithStreaming` and `.thinking` are set from the vendor's docs (tool-calling, structured-output and streaming guides) plus the served model's own `supported_features` array on the live roster — not from an executed chat/stream/tool-call/schema request. `structuredOutputWithTools` is `false` because no combined `tools` + `response_format` request was — or could be — attempted without a key. | Until a live run fills in `evidence.liveMatrix`, treat this provider as **documentation-grade**: the wire shape (base URL, auth header, request/response field names) is well-documented and consistent with the standard OpenAI-compatible contract, but no NeuroLink call has actually exercised it. --- ## Troubleshooting | Symptom | Cause | Fix | | ------------------------------------ | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `Invalid KosCompute API key` | `KOSCOMPUTE_API_KEY` unset, wrong, expired, or lacks access | KosCompute's docs describe 401 as "missing, invalid, expired, inactive, or conflicting credentials" but publish no example error body or code string | | Model not found | Wrong model id, or the roster changed since 2026-09-28 | Pick a current id from an unauthenticated `GET https://api.koscompute.com/v1/models` | | 429 with `concurrent_limit_exceeded` | Per-key concurrency limit exceeded | Wait for an in-flight request to finish, or reduce parallel requests, before retrying | | No signup page found | Expected — KosCompute publishes no public signup or key-management page | Obtain a key out of band; there is no self-serve console to link to | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Laya Provider Guide # Laya Provider Guide **A provider of `decide`** — the same typed `boolean` / `choice` / `score` answers as [TypeSafe's Jev](/docs/getting-started/providers/typesafe), from an open-weights model you can run yourself. It emits no text at all. ------------------ | ------------------------------------------------------------------------------------------------- | | Inference type | `decide` only | | Checkpoints | `typed-decisions` (default, fine-tuned for typed decisions), `multilingual`, `english`, or `auto` | | Input window | 1,024 tokens (`typed-decisions`, `multilingual`); 512 (`english`) | | Questions per request | up to 64 | | Endpoint | `/predict`; the base URL is required, with no default | | Precedence | used automatically when its key and base URL are set and no TypeSafe key is | --- ## Quick Start ### 1. Get an endpoint and a key Run a Laya server (see [below](#running-your-own-laya-server)), or use a LiteLLM proxy with a pass-through route to one. On LiteLLM, create a virtual key and add the route's `/predict` path (and `/health`, if you want to probe it) to the key's **Allowed Routes**; a key without them is refused with a 403 `Key/team not allowed to access passthrough route`. ### 2. Configure Both the base URL and the key are required. Set them in the environment: ```bash export LAYA_BASE_URL=https://your-proxy.example.com/laya # NeuroLink calls /predict export LAYA_API_KEY=sk-... # the key your endpoint accepts export LAYA_MODEL=typed-decisions # optional ``` or in the config passed to the SDK, exactly as for any other provider. Values passed per call override the constructor's, which override the environment: ```typescript const neurolink = new NeuroLink({ credentials: { laya: { baseURL: "https://your-proxy.example.com/laya", apiKey: process.env.MY_LAYA_KEY, }, }, }); ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.decide({ provider: "laya", state: "We were billed twice for March. Please refund it today.", questions: { team: { type: "choice", instructions: "Which team should handle this?", criteria: { billing: "Payments and refunds", technical: "Bugs", sales: "Pricing", }, }, urgent: { type: "boolean", instructions: "Is this urgent?" }, }, }); const team = readDecisionChoice(result.answers, "team"); ``` ### From the CLI ```bash neurolink decide "We were billed twice for March." --provider laya \ --questions '{"urgent":{"type":"boolean","instructions":"Is this urgent?"}}' ``` --- ## When NeuroLink uses it Every built-in consumer of `decide` — model routing, relevance-driven compaction, tool routing and RAG planning — asks for the default decision provider. That is the first one that is configured — in the environment or in the `credentials` passed to the SDK — in the order TypeSafe, Laya, [XOR](/docs/getting-started/providers/xor), [SubQ](/docs/getting-started/providers/subq), [Perplexity](/docs/getting-started/providers/perplexity-decider), [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef), [OpenAI Decisions](/docs/getting-started/providers/openai-decisions), then [ScaleDown](/docs/getting-started/providers/scaledown). TypeSafe has two keys, `TYPESAFE_API_KEY` and `AI_GATEWAY_API_KEY` (its Vercel AI Gateway route), and either one counts. Laya counts only with both its key and its base URL, and so does XOR. SubQ counts with its key alone, `SUBQ_API_KEY`. Perplexity counts with its key alone, and that key, `PERPLEXITY_API_KEY`, is shared with Perplexity's text provider. Cloudflare Clef counts only with both `CLOUDFLARE_API_KEY` and `CLOUDFLARE_ACCOUNT_ID`, the same two variables the Workers AI text provider reads. OpenAI Decisions counts with its key alone, `OPENAI_API_KEY`, which the OpenAI chat provider reads too. ScaleDown counts with its key alone, `SCALEDOWN_API_KEY`, which no other provider reads. So: - **A TypeSafe key, plus Laya's key and base URL:** built-in features use TypeSafe; Laya runs only where a caller asks for `provider: "laya"`. - **Only Laya's key and base URL:** built-in features use Laya. - **Laya's key and base URL, plus XOR's:** built-in features use Laya; XOR runs only where a caller asks for `provider: "xor"`. - **A Laya key with no base URL:** Laya is not configured. Built-in features ignore it, and `provider: "laya"` fails with `Laya requires a base URL`. - **Laya's key and base URL, plus a Perplexity key:** built-in features use Laya; Perplexity runs only where a caller asks for `provider: "perplexity-decider"`. - **Laya's key and base URL, plus `CLOUDFLARE_API_KEY` and `CLOUDFLARE_ACCOUNT_ID`:** built-in features use Laya; Cloudflare Clef runs only where a caller asks for `provider: "cloudflare-clef"`. - **Laya's key and base URL, plus `SUBQ_API_KEY`:** built-in features use Laya; SubQ runs only where a caller asks for `provider: "subq"`. - **Laya's key and base URL, plus `SCALEDOWN_API_KEY`:** built-in features use Laya; ScaleDown runs only where a caller asks for `provider: "scaledown"`. - **None of TypeSafe, Laya, XOR, SubQ, Perplexity, Cloudflare Clef, OpenAI Decisions or ScaleDown:** everything behaves exactly as it did without a decision model. --- ## Limits **The window is small.** Laya's encoders read 1,024 tokens, and 512 on the `english` checkpoint, against roughly 33,000 for Jev. Part of that is reserved for each question and its options, so NeuroLink allows about 768 tokens of state on `typed-decisions` and `multilingual`, and 320 on `english`, `auto` and any model name it does not recognise. Laya's server does not refuse a longer state — it answers from the start of it and says nothing — so NeuroLink refuses it instead, before any network call, with `max_tokens_exceeded`. The size is an estimate, not Laya's tokenizer: about four characters per token for ASCII text, and 1.5 tokens per character for other scripts (0.6 on `multilingual`), calibrated against a live Laya 0.3.5 server. It errs toward refusing. Built-in consumers treat a refusal as "carry on as before", which means long-prompt model routing usually falls back to the heuristic when Laya is the only decision provider. **Many options degrade it.** A `choice`'s options share a fixed token budget, so accuracy drops past about 20 options; some Laya servers also reject a question whose options overflow the budget, as `invalid_request`. **Pick the checkpoint deliberately.** Laya's own benchmark puts its general `english` and `multilingual` checkpoints close to chance on typed decisions without fine-tuning; `typed-decisions` is the fine-tuned one, which is why it is the default. --- ## Errors | Reply | Kind | Retried | | ----------------------------------------------- | ------------------------------------------------------- | ------- | | 401 / 403 from the proxy | `authentication` — the provider instance stops retrying | no | | 400 / 422 from Laya | `invalid_request`, with Laya's reason | no | | 413 from Laya | `max_tokens_exceeded` | no | | 429 | `rate_limit` | yes | | 503 | `overloaded` | yes | | other 5xx | `server` | yes | | more questions or state than Laya reads (local) | `max_tokens_exceeded`, with no network call | no | | no base URL configured (local) | `invalid_request`, with no network call | no | LiteLLM's 401 text echoes a masked copy of the rejected key and its hash; the provider drops that part before the message reaches a log or an error. --- ## Running your own Laya server Laya's example server exposes the same `/predict` route. Point `LAYA_BASE_URL` at it: ```bash pip install "laya[serve]" python examples/server.py # from the Laya repository; serves :8000 export LAYA_BASE_URL=http://127.0.0.1:8000 ``` --- ## Troubleshooting - **`Laya requires a base URL`** — set `LAYA_BASE_URL`, or pass `credentials.laya.baseURL`. There is no default endpoint. - **`Authentication failed`** — the proxy rejected the key. Check it in the LiteLLM Dashboard, including its Allowed Routes. The provider instance does not retry after a rejection. - **A 403 with `error code: 1010`** — Cloudflare in front of your proxy blocked the client by its signature. Node's `fetch` is accepted; a proxy or agent that rewrites the user agent may not be. - **`exceeded the provider's token limit`** — the state is larger than Laya reads. Shorten it, or configure TypeSafe for long inputs. - **Built-in routing never uses Laya** — a TypeSafe key is also set and takes precedence, or Laya has no base URL. --- ## See also - [The `decide` inference type](/docs/features/decide-inference-type) - [TypeSafe (Jev) Provider Guide](/docs/getting-started/providers/typesafe) - [XOR Provider Guide](/docs/getting-started/providers/xor) - [Perplexity Decisions Provider Guide](/docs/getting-started/providers/perplexity-decider) - [Cloudflare Clef Provider Guide](/docs/getting-started/providers/cloudflare-clef) - [SubQ Provider Guide](/docs/getting-started/providers/subq) - [OpenAI Decisions Provider Guide](/docs/getting-started/providers/openai-decisions) - [ScaleDown Provider Guide](/docs/getting-started/providers/scaledown) - [Laya on GitHub](https://github.com/NandhaKishorM/laya) --- ## Lemonfox AI Provider Guide # Lemonfox AI Provider Guide Lemonfox AI is a **Tier-2 catalog provider**: its integration is one JSON file (`src/lib/providers/catalog/lemonfox-ai.json`) rather than hand-written code. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** The vendor's `GET https://api.lemonfox.ai/v1/models` needs a > key (it answers HTTP 401 without one), so the two model ids come from the > vendor's public chat API page, https://www.lemonfox.ai/apis/chat (retrieved > 2026-09-29), and the roster has not been checked. No account was created and no > API key was used to build it. `evidence.liveMatrix` is `null` until someone > runs the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://lemonfox.ai/signup (the "Get started" and "Start Your Free Trial" links on https://www.lemonfox.ai/apis/chat both point to /signup); sign-up was not attempted while building this entry 2. Create an API key at https://lemonfox.ai/apis/keys — https://www.lemonfox.ai/apis/chat links "create an API key" to that page, and the API's 401 reply says "You can obtain an API key from https://lemonfox.ai/apis/keys." 3. Billing as the vendor states it: see [Billing](#billing) below 4. Set `LEMONFOX_AI_API_KEY` in your .env file ### 2. Configure ```bash export LEMONFOX_AI_API_KEY=your-api-key export LEMONFOX_AI_MODEL=deepseek-v4-flash # optional — overrides the default model export LEMONFOX_AI_BASE_URL=https://api.lemonfox.ai/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "lemonfox-ai", model: "deepseek-v4-flash", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider lemonfox-ai ``` Per-request credentials: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "lemonfox-ai", credentials: { lemonfoxAi: { apiKey: process.env.LEMONFOX_AI_API_KEY } }, }); ``` --- ## Billing What the vendor's public pages show (retrieved 2026-09-29): - https://www.lemonfox.ai/ — "Try our APIs for 1 month for free." - https://www.lemonfox.ai/apis/chat — "First month for free!" and "Start Your Free Trial" - https://www.lemonfox.ai/terms — Lemon Fox GmbH uses Paddle as its Merchant of Record and offers "subscription-based pricing and usage-based pricing" The entry records `free-with-card`, the growth queue's classification, because the catalog schema has no unknown value; it is not a vendor statement of sign-up terms. --- ## Models | Model | Context | Price / 1M tokens | Notes | | ---------------------- | ------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `deepseek-v4-flash` ⭐ | 1M | $0.50 | NeuroLink default. Vendor: "DeepSeek V4 Flash is our default model — fast, cost-effective, and suitable for most tasks." | | `mimo-v2.5-pro` | — | $1.25 | NeuroLink fallback. Vendor: "MiMo V2.5 Pro is a powerful model from Xiaomi, recommended for complex reasoning and coding tasks." | Model ids, the 1M context figure and the two prices come from the model table on https://www.lemonfox.ai/apis/chat (retrieved 2026-09-29), whose price column is headed "Price / 1M tokens". The table's context text for `deepseek-v4-flash` reads "Supports a 1M token context window."; the catalog stores it as 1,000,000 (NeuroLink's decimal reading of "1M"). `mimo-v2.5-pro` has no context window set. The page also shows the model parameter as "Specify the model ID to be used. Default: deepseek-v4-flash. Also supported: mimo-v2.5-pro." `models.defaultContextWindow` (32,768) and `models.defaultMaxOutputTokens` (4,096) are placeholders the vendor does not publish, for model ids outside the catalog; the page's `max_tokens` parameter reads "integer, optional, default: infinity". `pricingPerMTok` is unset on both models because the catalog field takes separate input and output figures and the table has the one "Price / 1M tokens" column. Each model's `vision` flag is `false` in the catalog, a placeholder for a boolean the schema requires; it is not a vendor statement. Each model's `status` is `production`, a value the schema requires. **Deprecated models:** a second table on the same page, under the heading "Deprecated models", lists `llama-8b-chat` ("Deprecated. Llama 3.1 8B — use deepseek-v4-flash instead.", $0.50) and `llama-70b-chat` ("Deprecated. Llama 3.3 70B — use mimo-v2.5-pro instead.", $1.25). These two ids are not in this catalog. **Fallback order** when the default is unavailable: `deepseek-v4-flash` → `mimo-v2.5-pro`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Lemonfox AI — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /v1/models`, HTTP 401, 2026-09-29 — no key used; model ids taken from https://www.lemonfox.ai/apis/chat; roster not verified | | Billing | public pages listed under [Billing](#billing), 2026-09-29 — no signup performed | | Auth-failure shape | unauthenticated GETs of `/v1/models`, `/v1/chat/completions` and `/v1` each answered HTTP 401 with the same JSON body (`status` 401, `error.type` `invalid_request_error`, `error.code` null, `error.message` beginning "You didn't provide an API key."); `errorRules` holds one rule, for status `401`; no POST request was sent | | Tools / structured output | not declared: the parameter list on https://www.lemonfox.ai/apis/chat is `messages`, `model`, `max_tokens`, `stop`, `stream`, `frequency_penalty`, `presence_penalty`, `temperature` and `top_p`, and no request exercising tools or structured output was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=lemonfox-ai` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting | Symptom | Cause | Fix | | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | HTTP 401 | The vendor's reply to a request with no key: "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY)." | Set `LEMONFOX_AI_API_KEY`; keys are at https://lemonfox.ai/apis/keys | | `llama-8b-chat` or `llama-70b-chat` set as model | The chat API page lists these ids under "Deprecated models" | The page says "use deepseek-v4-flash instead" for `llama-8b-chat` and "use mimo-v2.5-pro instead" for `llama-70b-chat` | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [Provider guides](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Lilac Provider Guide # Lilac Provider Guide Lilac is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/lilac.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs- and roster-verified, not > yet live-verified.** Every model id, context window, output ceiling and > price below comes from an unauthenticated `GET /v1/models` call (no API > key used) cross-checked against Lilac's published docs. No request that > needs a key — chat completions, streaming, tool calls, structured output — > has been probed end to end. Capability flags reflect only what the docs > state; run the live matrix (see > [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry)) > before trusting this provider in production. ## Quick Start ### 1. Get an API key 1. Visit: https://console.getlilac.com and sign up with your email or a Google account 2. Create an organization, then go to API Keys in the dashboard and create a new key — it is shown only once, so copy it immediately 3. Go to Billing, click Add Credits and complete the Stripe checkout (as little as $5.00) — a positive credit balance is required before you can make any API request; there is no free tier or free credits 4. Set `LILAC_API_KEY` in your .env file New-model requests and enterprise monthly-invoicing setup both go through contact@getlilac.com. ### 2. Configure ```bash export LILAC_API_KEY=your-api-key export LILAC_MODEL=moonshotai/kimi-k2.6 # optional — overrides the default model export LILAC_BASE_URL=https://api.getlilac.com/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "lilac", model: "moonshotai/kimi-k2.6", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider lilac ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "lilac", credentials: { lilac: { apiKey: process.env.LILAC_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ------------------------- | ------- | ------ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `moonshotai/kimi-k2.6` ⭐ | 262K | yes | $0.70 / $3.50 (cached $0.16) | Default — the model used in every code sample on Lilac's own quickstart and chat-completions docs, including its vision example. Roster-verified only, not capability-probed. | | `minimaxai/minimax-m3` | 1M | yes | $0.28 / $1.10 (cached $0.05) | Largest context in the roster; native multimodal 428B MoE reasoning model. Fallback. | | `zai-org/glm-5.2` | 512K | no | $0.90 / $3.00 (cached $0.17) | Only non-vision model on the roster; its `reasoning_effort` also works as a plain top-level field, not only inside `chat_template_kwargs`. Fallback. | | `google/gemma-4-31b-it` | 256K | yes | $0.11 / $0.35 | Cheapest model; does not list `structured_outputs` in its supported parameters (only `response_format`), and docs flag a structured-output caveat under `enable_thinking: false`. Fallback. | Context window and output-ceiling numbers are from `GET /v1/models` (unauthenticated, 2026-09-28); the API reports the per-model `max_completion_tokens` equal to that same model's context length, so treat it as an upper bound rather than a separately proven output cap. Pricing is cross-checked against https://docs.getlilac.com/inference/models (same date) and matches exactly. **Fallback order** when the default is unavailable: `minimaxai/minimax-m3` → `zai-org/glm-5.2` → `google/gemma-4-31b-it`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for Lilac — and, just as importantly, what it does **not** record yet: | Probe | Result | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Roster | unauthenticated `GET /v1/models`, HTTP 200, 4 models, 2026-09-28 — ids match the docs page exactly (`google/gemma-4-31b-it`, `minimaxai/minimax-m3`, `moonshotai/kimi-k2.6`, `zai-org/glm-5.2`) | | Auth rejection | **not probed** — a request with an invalid key would need to `POST /v1/chat/completions`, which this onboarding pass deliberately never sends | | Live capability sweep | **not run** — no key was available or used. `errorRules` is intentionally empty in the JSON (no documented auth-failure shape to encode); NeuroLink's generic default error classifier (401 → authentication, 429 → rate-limit, 404 → invalid-model) applies until a live probe adds provider-specific rules | | Billing | Docs-only: prepaid Stripe credits, no free tier, no minimum spend once funded ("no minimums or contracts"); a positive balance is required before the first request | Do not treat this provider as production-ready until someone with a Lilac key runs the live matrix and records the result in `evidence.liveMatrix`. --- ## Troubleshooting | Symptom | Cause | Fix | | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | Requests fail immediately | No credit balance — Lilac requires a positive balance before any call succeeds | Add credits via Billing → Add Credits at https://console.getlilac.com | | Model not found | The roster changed since 2026-09-28 | Pick a current id from the unauthenticated `GET /v1/models` roster | | Frequent 429s | Lilac's documented limit is 200 requests/minute per organization | Respect the `Retry-After` header and back off; request a higher limit via contact@getlilac.com | | Structured output silently malformed | Gemma 4 only — combining its reasoning parser with `enable_thinking: false` can disable structured output per Lilac's docs | Leave `enable_thinking` at its default for Gemma 4, or use a different model for schema-strict calls | | `embed()` throws | Lilac does not support embeddings | Use a provider that does (see [Embeddings](/docs/features/embeddings)) | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## LiteLLM Provider Guide # LiteLLM Provider Guide **Access hundreds of AI models across 100+ providers through the NeuroLink LiteLLM provider via a LiteLLM proxy server** ## Quick Start ### 1. Set Up a LiteLLM Proxy Server Before using the NeuroLink `litellm` provider, you need a running LiteLLM proxy. See the [Setting Up LiteLLM Proxy](#setting-up-litellm-proxy) section below for full details, or get started quickly: ```bash pip install 'litellm[proxy]' litellm --model openai/gpt-4o-mini --port 4000 ``` ### 2. Configure Environment Variables Add to your `.env` file: ```bash # Required: URL of your LiteLLM proxy server LITELLM_BASE_URL=http://localhost:4000 # Optional: API key for the proxy (default: "sk-anything") LITELLM_API_KEY=sk-your-proxy-key # Optional: Override the default model (default: openai/gpt-4o-mini) LITELLM_MODEL=openai/gpt-4o-mini ``` ### 3. Test the Setup ```bash # CLI - Generate with the LiteLLM provider npx @juspay/neurolink generate "Hello from LiteLLM!" --provider litellm # CLI - Verify the connection npx @juspay/neurolink generate "Explain AI" --provider litellm ``` --- ## Environment Variables | Variable | Required | Default | Description | | ------------------ | -------- | ----------------------- | ----------------------------------------- | | `LITELLM_BASE_URL` | No | `http://localhost:4000` | URL of your LiteLLM proxy server | | `LITELLM_API_KEY` | No | `sk-anything` | API key for authenticating with the proxy | | `LITELLM_MODEL` | No | `openai/gpt-4o-mini` | Default model in `provider/model` format | --- ## Default Model The default model is `openai/gpt-4o-mini` (from `LiteLLMModels.OPENAI_GPT_4O_MINI`). Override it by setting `LITELLM_MODEL` in your environment or passing `--model` on the CLI. --- ## Model Name Format LiteLLM uses a `provider/model` format for model names. Examples: ``` openai/gpt-4o-mini # OpenAI openai/gpt-4o # OpenAI anthropic/claude-3-5-sonnet-20240620 # Anthropic vertex_ai/gemini-2.5-pro # Google Vertex AI gemini/gemini-2.0-flash # Google AI Studio groq/llama-3.1-70b-versatile # Groq mistral/mistral-large-latest # Mistral AI bedrock/anthropic.claude-3-5-sonnet-20240620-v1:0 # AWS Bedrock together_ai/meta-llama/Llama-3-70b-chat-hf # Together AI ``` See the full list at [LiteLLM Supported Providers](https://docs.litellm.ai/docs/providers). --- ## SDK Usage ### Basic Usage ```typescript const ai = new NeuroLink(); // Generate with the default LiteLLM model (openai/gpt-4o-mini) const result = await ai.generate({ input: { text: "Hello from LiteLLM!" }, provider: "litellm", }); console.log(result.content); ``` ### With a Specific Model ```typescript // Use Anthropic Claude via LiteLLM const result = await ai.generate({ input: { text: "Explain quantum computing" }, provider: "litellm", model: "anthropic/claude-3-5-sonnet-20240620", }); // Use Google Gemini via LiteLLM const geminiResult = await ai.generate({ input: { text: "Summarize this article" }, provider: "litellm", model: "gemini/gemini-2.0-flash", }); ``` ### Streaming ```typescript const result = await ai.stream({ input: { text: "Write a story about space exploration" }, provider: "litellm", model: "openai/gpt-4o", }); for await (const chunk of result.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } ``` ### Multi-Model Workflow ```typescript // Route requests to different models based on complexity async function generateSmart( prompt: string, complexity: "low" | "medium" | "high", ) { const modelMap = { low: "openai/gpt-4o-mini", medium: "anthropic/claude-3-5-sonnet-20240620", high: "openai/gpt-4o", }; return await ai.generate({ input: { text: prompt }, provider: "litellm", model: modelMap[complexity], }); } ``` --- ## CLI Usage ```bash # Generate with default model npx @juspay/neurolink generate "Hello LiteLLM" --provider litellm # Use a specific model npx @juspay/neurolink generate "Write code" --provider litellm --model "openai/gpt-4o" # Stream a response npx @juspay/neurolink stream "Tell a story" --provider litellm # Interactive loop mode npx @juspay/neurolink loop --provider litellm # With temperature and max tokens npx @juspay/neurolink generate "Creative writing prompt" \ --provider litellm \ --model "anthropic/claude-3-5-sonnet-20240620" \ --temperature 0.9 \ --max-tokens 1000 ``` --- ## Available Models The `LiteLLMModels` enum provides commonly used model identifiers: | Enum Value | Model ID | | ------------------------------ | -------------------------------------- | | `OPENAI_GPT_4O_MINI` | `openai/gpt-4o-mini` | | `OPENAI_GPT_4O` | `openai/gpt-4o` | | `OPENAI_GPT_5` | `openai/gpt-5` | | `ANTHROPIC_CLAUDE_SONNET_4_6` | `anthropic/claude-sonnet-4-6` | | `ANTHROPIC_CLAUDE_3_5_SONNET` | `anthropic/claude-3-5-sonnet-20240620` | | `VERTEX_GEMINI_2_5_PRO` | `vertex_ai/gemini-2.5-pro` | | `GEMINI_2_0_FLASH` | `gemini/gemini-2.0-flash` | | `GROQ_LLAMA_3_1_70B_VERSATILE` | `groq/llama-3.1-70b-versatile` | | `MISTRAL_LARGE` | `mistral/mistral-large-latest` | You can also pass any model string your LiteLLM proxy is configured to serve. Use the proxy's `/v1/models` endpoint to discover available models dynamically. --- ## Error Handling The LiteLLM provider returns specific error types for common failure scenarios: | Error | Cause | Resolution | | ----------------------------- | ----------------------------------- | -------------------------------------------------------- | | `NetworkError` (ECONNREFUSED) | LiteLLM proxy server is not running | Start the proxy at the configured `LITELLM_BASE_URL` | | `AuthenticationError` | Invalid `LITELLM_API_KEY` | Check your API key matches the proxy's master key | | `RateLimitError` | Upstream rate limit exceeded | Wait and retry, or configure load balancing in the proxy | | `InvalidModelError` | Model not configured in proxy | Add the model to your LiteLLM proxy configuration | --- ## Setting Up LiteLLM Proxy The NeuroLink `litellm` provider requires a running LiteLLM proxy server. This section covers how to set one up. ### Install LiteLLM ```bash pip install 'litellm[proxy]' ``` ### Quick Start (Single Model) ```bash # Start a proxy that routes to a single model litellm --model openai/gpt-4o-mini --port 4000 ``` ### Configuration File (Multiple Models) Create `litellm_config.yaml`: ```yaml model_list: - model_name: openai/gpt-4o-mini litellm_params: model: gpt-4o-mini api_key: ${OPENAI_API_KEY} - model_name: anthropic/claude-3-5-sonnet litellm_params: model: claude-3-5-sonnet-20241022 api_key: ${ANTHROPIC_API_KEY} - model_name: gemini/gemini-pro litellm_params: model: gemini/gemini-pro api_key: ${GOOGLE_API_KEY} general_settings: master_key: ${LITELLM_MASTER_KEY} ``` Start the proxy: ```bash litellm --config litellm_config.yaml --port 4000 ``` ### Load Balancing Distribute requests across multiple providers or API keys: ```yaml model_list: - model_name: gpt-4-balanced litellm_params: model: gpt-4 api_key: ${OPENAI_API_KEY_1} - model_name: gpt-4-balanced litellm_params: model: gpt-4 api_key: ${OPENAI_API_KEY_2} router_settings: routing_strategy: simple-shuffle ``` ### Automatic Failover Configure fallback providers for reliability: ```yaml model_list: - model_name: smart-model litellm_params: model: gpt-4 api_key: ${OPENAI_API_KEY} - model_name: smart-model litellm_params: model: claude-3-5-sonnet-20241022 api_key: ${ANTHROPIC_API_KEY} router_settings: enable_fallbacks: true num_retries: 2 ``` ### Budget Management Set spending limits per virtual key: ```bash litellm --config config.yaml --create_key \ --key_name "team-frontend" \ --budget 100 ``` ### Docker Deployment ```yaml # docker-compose.yml version: "3.8" services: litellm: image: ghcr.io/berriai/litellm:main-latest ports: - "4000:4000" volumes: - ./litellm_config.yaml:/app/config.yaml command: ["litellm", "--config", "/app/config.yaml", "--port", "4000"] environment: - OPENAI_API_KEY=${OPENAI_API_KEY} - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY} ``` --- ## Troubleshooting ### Common Issues #### 1. "LiteLLM proxy server not available" **Problem**: The proxy server is not running or is unreachable. **Solution**: ```bash # Check if proxy is running curl http://localhost:4000/health # Start proxy litellm --config litellm_config.yaml --port 4000 # Verify LITELLM_BASE_URL points to the correct address echo $LITELLM_BASE_URL ``` #### 2. "Invalid LiteLLM configuration" **Problem**: The API key does not match the proxy's master key. **Solution**: ```bash # Verify master_key in proxy config grep master_key litellm_config.yaml # Ensure LITELLM_API_KEY matches echo $LITELLM_API_KEY ``` #### 3. "Model not available in LiteLLM proxy" **Problem**: The requested model is not configured in the proxy's `model_list`. **Solution**: ```yaml # Add the model to litellm_config.yaml model_list: - model_name: your-model litellm_params: model: openai/gpt-4o api_key: ${OPENAI_API_KEY} ``` Then restart the proxy. #### 4. "Rate limit exceeded" **Problem**: Upstream provider rate limit hit. **Solution**: Configure load balancing across multiple API keys or providers in your LiteLLM proxy config. --- ## Related Documentation - **[OpenAI Compatible Guide](/docs/getting-started/providers/openai-compatible)** - OpenAI-compatible providers - **[Provider Setup Guide](/docs/getting-started/provider-setup)** - General provider configuration - **[Cost Optimization](/docs/cookbook/cost-optimization)** - Reduce AI costs --- ## Additional Resources - **[LiteLLM Documentation](https://docs.litellm.ai/)** - Official docs - **[Supported Providers](https://docs.litellm.ai/docs/providers)** - 100+ providers list - **[LiteLLM GitHub](https://github.com/BerriAI/litellm)** - Source code - **[LiteLLM Proxy Docs](https://docs.litellm.ai/docs/proxy/quick_start)** - Proxy setup --- **Need Help?** Join our [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## llama.cpp Provider Guide # llama.cpp Provider Guide **Fully offline GGUF inference — connect NeuroLink directly to a `llama-server` process** ## Quick Start ### 1. Install and Build llama.cpp ```bash # Clone the repo git clone https://github.com/ggerganov/llama.cpp cd llama.cpp # Build (CPU-only — works on any machine) cmake -B build cmake --build build --config Release -j $(nproc) # The server binary is now at build/bin/llama-server ``` For GPU-accelerated builds, see the [llama.cpp build docs](https://github.com/ggerganov/llama.cpp/blob/master/docs/build.md). ### 2. Download a GGUF Model ```bash # Example: download Llama 3.2 3B Instruct Q4 from Hugging Face huggingface-cli download \ bartowski/Llama-3.2-3B-Instruct-GGUF \ Llama-3.2-3B-Instruct-Q4_K_M.gguf \ --local-dir ./models ``` Or download directly from [https://huggingface.co/models](https://huggingface.co/models) — search for GGUF variants. ### 3. Start the Server ```bash # Basic startup (CPU inference) ./build/bin/llama-server \ -m ./models/Llama-3.2-3B-Instruct-Q4_K_M.gguf \ --port 8080 # With tool/function calling support (recommended) ./build/bin/llama-server \ -m ./models/Llama-3.2-3B-Instruct-Q4_K_M.gguf \ --port 8080 \ --jinja # GPU-accelerated (N layers offloaded to GPU) ./build/bin/llama-server \ -m ./models/Llama-3.2-3B-Instruct-Q4_K_M.gguf \ --port 8080 \ -ngl 99 ``` The server prints `listening on http://127.0.0.1:8080` when ready. ### 4. Configure Environment (Optional) No environment variables are required for a default setup: ```bash # Override the base URL if using a non-default port or remote host LLAMACPP_BASE_URL=http://localhost:8080/v1 # Pin a specific model name (default: auto-discover from /v1/models) LLAMACPP_MODEL= # API key — only needed if llama-server is behind an auth-proxying reverse-proxy LLAMACPP_API_KEY= ``` ### 5. Install NeuroLink ```bash npm install @juspay/neurolink # or pnpm add @juspay/neurolink ``` ### 6. Generate Your First Response ```typescript const ai = new NeuroLink(); // Omit `model:` — NeuroLink discovers the loaded model automatically const result = await ai.generate({ provider: "llamacpp", input: { text: "Explain the difference between a stack and a heap." }, }); console.log(result.content); ``` --- ## Model Auto-Discovery When no `model` is specified (and `LLAMACPP_MODEL` is empty), the provider queries `GET /v1/models` with a 5-second timeout. The first model returned is used — which is whichever GGUF file the server was started with. If discovery fails, the provider falls back to `"loaded-model"` as a placeholder and logs a warning. The next call re-attempts discovery, so you do not need to restart your application after starting `llama-server`. ```typescript // Auto-discover const result = await ai.generate({ provider: "llamacpp", input: { text: "What is a closure in programming?" }, // No `model:` field }); ``` To pin the model explicitly: ```typescript const result = await ai.generate({ provider: "llamacpp", model: "Llama-3.2-3B-Instruct-Q4_K_M", // match the ID from /v1/models input: { text: "What is a closure?" }, }); ``` --- ## SDK Usage ### Basic Generation (Auto-Discover) ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "llamacpp", input: { text: "Write a Rust function to compute the nth Fibonacci number iteratively.", }, }); console.log(result.content); ``` ### Streaming ```typescript const ai = new NeuroLink(); const stream = await ai.stream({ provider: "llamacpp", input: { text: "Explain how the Linux kernel schedules processes." }, }); for await (const chunk of stream.stream) { process.stdout.write(chunk); } ``` ### Per-Call Base URL Override Useful when `llama-server` runs on a different machine on your local network or on a non-default port. ```typescript const result = await ai.generate({ provider: "llamacpp", input: { text: "Hello from the network!" }, credentials: { llamacpp: { baseURL: "http://192.168.1.42:8080/v1", }, }, }); ``` If your `llama-server` is behind an auth-proxying reverse-proxy: ```typescript const result = await ai.generate({ provider: "llamacpp", input: { text: "Hello" }, credentials: { llamacpp: { baseURL: "https://llama.internal.example.com/v1", apiKey: "bearer-token-for-proxy", }, }, }); ``` --- ## CLI Usage ### Basic Commands ```bash # Auto-discover the loaded model pnpm run cli generate "What is garbage collection?" --provider llamacpp # Use provider aliases pnpm run cli generate "Hello" --provider llama.cpp pnpm run cli generate "Hello" --provider llama-cpp # Pin a model explicitly pnpm run cli generate "Describe merge sort" \ --provider llamacpp \ --model Llama-3.2-3B-Instruct-Q4_K_M # Interactive loop (re-discovers model on each request) pnpm run cli loop --provider llamacpp # Connect to a server on a different host LLAMACPP_BASE_URL=http://192.168.1.42:8080/v1 \ pnpm run cli generate "Hello from network" --provider llamacpp ``` --- ## Provider Aliases | Alias | Example | | ----------- | ---------------------- | | `llamacpp` | `--provider llamacpp` | | `llama.cpp` | `--provider llama.cpp` | | `llama-cpp` | `--provider llama-cpp` | --- ## Configuration Reference | Environment Variable | Required | Default | Description | | -------------------- | -------- | -------------------------- | ------------------------------------------------------------------ | | `LLAMACPP_BASE_URL` | No | `http://localhost:8080/v1` | Base URL of the llama-server | | `LLAMACPP_MODEL` | No | `""` (auto-discover) | Specific model ID; leave blank for auto-discovery via `/v1/models` | | `LLAMACPP_API_KEY` | No | `llamacpp` (placeholder) | Auth token — only needed for reverse-proxy setups with auth | --- ## Feature Support | Feature | Supported | Notes | | --------------- | --------------- | ---------------------------------------------------------------------- | | Text generation | Yes | | | Streaming | Yes | | | Tool calling | Model-dependent | Start `llama-server` with `--jinja` for function-call template support | | Vision / images | Model-dependent | Load a multimodal GGUF (LLaVA-style) | | Embeddings | No | Use OpenAI or another embeddings provider | | Auto-discovery | Yes | Queries `/v1/models` at request time; falls back gracefully | --- ## llama-server Tips ### Context Window Set a larger context window at startup with `-c`: ```bash ./build/bin/llama-server -m model.gguf -c 8192 --port 8080 ``` ### GPU Offloading Use `-ngl N` to offload N transformer layers to GPU (requires a CUDA or Metal build): ```bash ./build/bin/llama-server -m model.gguf -ngl 99 --port 8080 ``` ### Multiple CPU Threads ```bash ./build/bin/llama-server -m model.gguf -t 8 --port 8080 ``` ### Tool / Function Calling Start with `--jinja` to enable Jinja-based chat template processing, which is required for function calling on most models: ```bash ./build/bin/llama-server -m model.gguf --jinja --port 8080 ``` --- ## Troubleshooting ### "llama.cpp server not reachable" `llama-server` is not running or is on a different address. ```bash # Test reachability curl http://localhost:8080/v1/models # Start the server ./build/bin/llama-server -m ./models/your-model.gguf --port 8080 ``` ### "llama.cpp request timed out" CPU inference can be slow, especially for large models or long prompts. Reduce the model size (use a smaller Q4 quantisation), increase GPU offloading, or raise the NeuroLink timeout setting. ### HTTP 400 — model does not support tools Tool calling requires the model to understand function-call syntax. Restart `llama-server` with `--jinja` and use a model fine-tuned for instruction following (e.g., Llama 3.1/3.2 Instruct). ```bash # With Jinja for tool support ./build/bin/llama-server -m model.gguf --jinja --port 8080 ``` ### Auto-discovery keeps returning "loaded-model" `llama-server` is running but `/v1/models` returned an empty list, or the server is not reachable. Confirm the server started successfully: ```bash curl http://localhost:8080/health curl http://localhost:8080/v1/models ``` ### Server crashes or runs out of memory Your model is too large for available RAM. Use a more aggressively quantised variant (Q2 or Q4) or a smaller model. You can also limit the batch size at startup with `-b 512`. --- ## See Also - [Implementation spec](/docs/provider-integration/05-llamacpp) — internal design details and auto-discovery mechanics - [LM Studio provider](/docs/getting-started/providers/lm-studio) — GUI-based alternative with the same auto-discovery pattern - [Ollama provider](/docs/getting-started/providers/ollama) — another popular local model runtime with a model management layer - [OpenAI Compatible provider](/docs/getting-started/providers/openai-compatible) — generic provider for any OpenAI-compatible endpoint --- **Need Help?** Join the [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## LLM Tech Provider Guide # LLM Tech Provider Guide > **Verification status:** this entry is **docs- and roster-verified only — > not yet live-verified.** It was onboarded credential-free: no LLM Tech API > key was ever created or used. Every field below comes from LLM Tech's > public model page (`https://llmtech.eu/models/qwen3.8-27b`) and an > **unauthenticated** `GET /v1/models` call (no auth header, no key). No > `POST` request was ever sent, so no generate, stream, tool-calling or > structured-output capability has been exercised end to end. Treat > `capabilities.tools`, `.structuredOutput` and `.thinking` as > documentation-grade, not wire-proven, until `evidence.liveMatrix` is filled > in by a live run. LLM Tech is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/llmtech.json`) rather than hand-written code. That file is the source of truth for everything on this page. ## Quick Start ### 1. Get an API key LLM Tech does not publish a public signup or self-service key-issuance flow: 1. Email `artem@llmtech.eu` to request a key (self-service is planned but not live as of 2026-09-28). 2. Once issued, paste the key into `https://llmtech.eu/cabinet/` to see current-month billing, a daily usage chart, and invoice line items — there is no separate account or login. 3. Confirm current pricing before heavy use: input $0.25/M, output $2.09/M, cached input $0.04/M tokens, per `https://llmtech.eu/models/qwen3.8-27b`. 4. Set `LLMTECH_API_KEY` in your `.env` file. ### 2. Configure ```bash export LLMTECH_API_KEY=your-api-key export LLMTECH_MODEL=nvidia/Qwen3.8-27B-NVFP4 # optional — overrides the default model export LLMTECH_BASE_URL=https://api.llmtech.eu/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain NVFP4 quantization in one paragraph." }, provider: "llmtech", model: "nvidia/Qwen3.8-27B-NVFP4", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider llmtech ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "llmtech", credentials: { llmtech: { apiKey: process.env.LLMTECH_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ----------------------------- | ------- | ------ | ---------------------------- | ------------------------------------------------------------------------------------------------------------ | | `nvidia/Qwen3.8-27B-NVFP4` ⭐ | 262,144 | yes | $0.25 / $2.09 (cached $0.04) | LLM Tech's only model. Reasoning-capable via `enable_thinking`/`reasoning_effort`. Max output 32,768 tokens. | Context window and max output shown are the catalog defaults (262,144 / 32,768 tokens), taken directly from the model's own entry in the live, unauthenticated `GET /v1/models` response (`context_length`, `max_output` / `max_output_tokens`) on 2026-09-28. Pricing is that same response's `pricing_per_m` fields, which match the vendor's model page exactly. **Fallback order:** none — `nvidia/Qwen3.8-27B-NVFP4` is the only model LLM Tech serves, so it is both the default and its own (schema-exempt) single-entry fallback list. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for LLM Tech — and, just as importantly, what it does **not** yet record: | Probe | Result | | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | **unauthenticated** GET `/v1/models`, HTTP 200, 1 model, 2026-09-28. No API key was used or required for this call. | | Auth rejection | Not probed. Would require a `POST` with an invalid key, which this credential-free onboarding pass does not send. | | Live capability sweep | **Not run.** `evidence.liveMatrix` is `null`. `capabilities.tools`, `.structuredOutput`, `.thinking` and vision are set from the vendor's model page plus the served model's own `features` array on the live roster — not from an executed chat/stream/tool-call/schema request. `structuredOutputWithTools` and `toolsWithStreaming` are `false` because no combined request was — or could be — attempted without a key. | Until a live run fills in `evidence.liveMatrix`, treat this provider as **documentation-grade**: the wire shape (base URL, OpenAI-compatible request/ response field names) is well-documented, but no NeuroLink call has actually exercised it. --- ## Troubleshooting | Symptom | Cause | Fix | | ---------------------------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | `Invalid LLM Tech API key` | `LLMTECH_API_KEY` unset or wrong | LLM Tech's docs do not publish an example auth-error body or code string; re-check the key with your issuer | | Model not found | The roster changed since 2026-09-28 | Re-check with an unauthenticated `GET https://api.llmtech.eu/v1/models` | | No signup page found | Expected — LLM Tech has no public signup page yet | Email `artem@llmtech.eu` for a key; self-service is planned but not live | | Unexpectedly high image cost | Image tokens bill at the input rate | Budget accordingly — a 64×64 PNG costs 64 image tokens per the vendor's own example | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## LM Studio Provider Guide # LM Studio Provider Guide **Run any GGUF model privately on your own hardware — no cloud, no API key required** ## Quick Start ### 1. Download and Start LM Studio 1. Download LM Studio from [https://lmstudio.ai](https://lmstudio.ai) for your platform. 2. Open the app and search for a model in the **Discover** tab (e.g., `Llama 3.2 3B Instruct`). 3. Click **Download** and wait for it to complete. 4. Go to the **Local Server** tab (icon that looks like ``). 5. Select the model you downloaded and click **Start Server**. The server starts on `http://localhost:1234` by default. ### 2. Configure Environment (Optional) No environment variables are required for a default setup. Optionally: ```bash # Override the base URL if you run LM Studio on a non-default port or host LM_STUDIO_BASE_URL=http://localhost:1234/v1 # Pin a specific model (default: auto-discover from /v1/models) LM_STUDIO_MODEL= # API key — only needed if you run LM Studio behind an auth-proxying reverse-proxy LM_STUDIO_API_KEY= ``` ### 3. Install NeuroLink ```bash npm install @juspay/neurolink # or pnpm add @juspay/neurolink ``` ### 4. Generate Your First Response Auto-discovery: NeuroLink calls `/v1/models` and uses the first loaded model. ```typescript const ai = new NeuroLink(); // Omit `model:` entirely — NeuroLink discovers the loaded model automatically const result = await ai.generate({ provider: "lm-studio", input: { text: "Explain the concept of entropy in information theory." }, }); console.log(result.content); ``` --- ## Model Auto-Discovery When no `model` is specified (and `LM_STUDIO_MODEL` is empty), the provider calls `GET /v1/models` with a 5-second timeout. It picks the first model returned — whichever is currently loaded in LM Studio. If discovery fails (server not running, no model loaded), the provider falls back to a `"local-model"` placeholder and logs a warning. The next call will re-attempt discovery, so there is no need to restart your Node process after starting LM Studio. ```typescript // Auto-discover — best for interactive local development const result = await ai.generate({ provider: "lm-studio", input: { text: "Hello!" }, // No `model:` field }); ``` To pin a specific model, pass it explicitly: ```typescript const result = await ai.generate({ provider: "lm-studio", model: "llama-3.2-3b-instruct", // must match the ID shown in LM Studio input: { text: "Hello!" }, }); ``` --- ## SDK Usage ### Basic Generation (Auto-Discover) ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "lm-studio", input: { text: "Write a haiku about type safety." }, }); console.log(result.content); ``` ### Streaming ```typescript const ai = new NeuroLink(); const stream = await ai.stream({ provider: "lm-studio", input: { text: "Explain monads in Haskell as if I am a TypeScript developer.", }, }); for await (const chunk of stream.stream) { process.stdout.write(chunk); } ``` ### Per-Call Base URL Override Useful if you run LM Studio on a different machine on your local network, or on a non-default port. ```typescript const result = await ai.generate({ provider: "lm-studio", input: { text: "Hello from across the network!" }, credentials: { lmStudio: { baseURL: "http://192.168.1.42:1234/v1", }, }, }); ``` If your LM Studio server is behind an auth-proxying reverse-proxy (rare), pass the key too: ```typescript const result = await ai.generate({ provider: "lm-studio", input: { text: "Hello" }, credentials: { lmStudio: { baseURL: "https://lmstudio.internal.example.com/v1", apiKey: "bearer-token-for-proxy", }, }, }); ``` --- ## CLI Usage ### Basic Commands ```bash # Auto-discover the loaded model pnpm run cli generate "What is quantum entanglement?" --provider lm-studio # Use provider aliases pnpm run cli generate "Hello" --provider lmstudio pnpm run cli generate "Hello" --provider lms # Pin a model explicitly pnpm run cli generate "Summarise the SOLID principles" \ --provider lm-studio \ --model llama-3.2-3b-instruct # Interactive loop (auto-discovers model on each request) pnpm run cli loop --provider lm-studio # Point at a non-default server address LM_STUDIO_BASE_URL=http://192.168.1.42:1234/v1 \ pnpm run cli generate "Hello from network" --provider lm-studio ``` --- ## Provider Aliases | Alias | Example | | ----------- | ---------------------- | | `lm-studio` | `--provider lm-studio` | | `lmstudio` | `--provider lmstudio` | | `lms` | `--provider lms` | --- ## Configuration Reference | Environment Variable | Required | Default | Description | | -------------------- | -------- | -------------------------- | ----------------------------------------------------------- | | `LM_STUDIO_BASE_URL` | No | `http://localhost:1234/v1` | Base URL of the LM Studio server | | `LM_STUDIO_MODEL` | No | `""` (auto-discover) | Specific model ID to use; leave blank for auto-discovery | | `LM_STUDIO_API_KEY` | No | `lm-studio` (placeholder) | Auth token — only needed for reverse-proxy setups with auth | --- ## Feature Support | Feature | Supported | Notes | | --------------- | --------------- | ------------------------------------------------------ | | Text generation | Yes | | | Streaming | Yes | | | Tool calling | Model-dependent | Requires a model that understands function-call syntax | | Vision / images | Model-dependent | Load a vision model (e.g., LLaVA, Qwen-VL) | | Embeddings | No | Use OpenAI or another embeddings provider | | Auto-discovery | Yes | Fetches active model from `/v1/models` at request time | --- ## Troubleshooting ### "LM Studio server not reachable" The server is not running or is on a different URL. 1. Open LM Studio and go to the **Local Server** tab. 2. Select a model and click **Start Server**. 3. Confirm the port shown (default: 1234) matches `LM_STUDIO_BASE_URL`. ```bash # Test reachability curl http://localhost:1234/v1/models ``` ### "Load a model in the LM Studio app" LM Studio's server returned an empty model list. Go to the **Local Server** tab, select a model from the dropdown, and click the load/start button. ### "LM Studio model X is not loaded" You pinned a specific model ID (`LM_STUDIO_MODEL` or `model:` in SDK/CLI), but that model is not loaded in LM Studio. Either load the model in the app or leave the model field blank to use whatever is already loaded. ### "LM Studio request timed out" Large models on CPU-only machines can be very slow. Try: - A smaller quantised model (Q4 instead of Q8) - A model with fewer parameters - Increasing the timeout via NeuroLink's global timeout settings ### Tool calls not working Not all models support tool/function calling format. Load a model that was fine-tuned for instruction following and tool use (e.g., Llama 3.1, Mistral 7B Instruct v0.3). Check the model's documentation on Hugging Face for capability flags. --- ## See Also - [Implementation spec](/docs/provider-integration/04-lm-studio) — internal design details and auto-discovery mechanics - [llama.cpp provider](/docs/getting-started/providers/llamacpp) — headless alternative using the `llama-server` binary directly - [Ollama provider](/docs/getting-started/providers/ollama) — another popular local model runtime - [OpenAI Compatible provider](/docs/getting-started/providers/openai-compatible) — generic provider for any OpenAI-compatible endpoint --- **Need Help?** Join the [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## Google Lyria Provider Guide (music) # Google Lyria Provider Guide **Music generation via Google Lyria 3 Pro** ## Quick Start ### 1. Get an API Key [https://aistudio.google.com/apikey](https://aistudio.google.com/apikey) ### 2. Configure Any of these env vars work: ```bash GOOGLE_AI_LYRIA_API_KEY=your-key # or GOOGLE_AI_API_KEY=your-key # or GEMINI_API_KEY=your-key ``` ### 3. Generate Music ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "vertex", output: { mode: "music", music: { provider: "lyria", prompt: "Uplifting orchestral cinematic with strings and brass", duration: 30, }, }, }); if (result.music?.buffer) { writeFileSync("./lyria.wav", result.music.buffer); } ``` --- ## CLI Usage ```bash pnpm run cli generate "Calm piano melody for studying" \ --provider lyria --musicDuration 60 --musicOutput ./music.wav ``` --- ## Configuration Reference | Environment Variable | Required (one-of) | Description | | ------------------------- | ----------------- | ---------------------- | | `GOOGLE_AI_LYRIA_API_KEY` | Yes (one-of) | Lyria-specific API key | | `GOOGLE_AI_API_KEY` | Yes (one-of) | General Google AI key | | `GEMINI_API_KEY` | Yes (one-of) | Gemini key (alias) | --- ## See Also - [Beatoven Provider](/docs/getting-started/providers/beatoven) - [ElevenLabs Music Provider](/docs/getting-started/providers/elevenlabs-music) --- ## Mancer Provider Guide # Mancer Provider Guide Mancer is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/mancer.json`) rather than hand-written code. That file is the source of truth for everything on this page. ## Quick Start ### 1. Get an API key 1. Visit: https://mancer.tech/dashboard and sign in 2. Create an API key (prefix mcr\_) 3. Without credits only the free model 'mytholite' answers; every other model returns 402 until you add credits at https://mancer.tech/pricing 4. Set `MANCER_API_KEY` in your .env file ### 2. Configure ```bash export MANCER_API_KEY=your-api-key export MANCER_MODEL=deepseek-v4-flash # optional — overrides the default model export MANCER_BASE_URL=https://neuro.mancer.tech/oai/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "mancer", model: "deepseek-v4-flash", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider mancer ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "mancer", credentials: { mancer: { apiKey: process.env.MANCER_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ------------------------ | ------- | ------ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `mythomax` | 8K | no | $0.14 / $0.24 | MythoMax (LLaMA 2, Simplified Alpaca format) — pricing and limits from the authenticated /oai/v1/models roster, 2026-09-03 | | `deepseek-v4-flash` ⭐ | 1M | no | $0.07 / $0.2 | DeepSeek V4 Flash — Mancer's flagship general model; paid credits required — pricing and limits from the authenticated /oai/v1/models roster, 2026-09-03 | | `deepseek-v4-flash-0731` | 1M | no | $0.07 / $0.2 | DeepSeek V4 Flash, 2026-07-31 snapshot; paid credits required — pricing and limits from the authenticated /oai/v1/models roster, 2026-09-03 | | `mytholite` | 3K | no | $0 / $0 | MythoLite — Mancer's free demo model (2,560-token context, 150-token completions, Simplified Alpaca format); the only model usable with a zero balance — pricing and limits from the authenticated /oai/v1/models roster, 2026-09-03 | | `remm-slerp` | 6K | no | $0.14 / $0.26 | ReMM-SLERP (Simplified Alpaca format) — pricing and limits from the authenticated /oai/v1/models roster, 2026-09-03 | | `magnum-72b-v4` | 32K | no | $1 / $2 | Magnum 72B v4 (ChatML format) — pricing and limits from the authenticated /oai/v1/models roster, 2026-09-03 | | `glm-4.7` | 128K | no | $0.28 / $1 | GLM-4.7 — pricing and limits from the authenticated /oai/v1/models roster, 2026-09-03 | | `gpt-oss-120b` | 128K | no | $0.022 / $0.2 | GPT-OSS 120B — pricing and limits from the authenticated /oai/v1/models roster, 2026-09-03 | | `weaver-alpha` | 8K | no | $0.16 / $0.3 | Weaver Alpha (Simplified Alpaca format) — pricing and limits from the authenticated /oai/v1/models roster, 2026-09-03 | | `dans-pe-1.3-24b` | 32K | no | $0.2 / $0.8 | Dan's PersonalityEngine 1.3 24B — pricing and limits from the authenticated /oai/v1/models roster, 2026-09-03 | **Fallback order** when the default is unavailable: `deepseek-v4-flash` → `gpt-oss-120b`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for Mancer: | Probe | Result | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Roster | authenticated GET /oai/v1/models; full response retained as evidence/mancer-roster-authenticated.json in the campaign scratchpad and every catalog price/limit machine-checked against it (Mancer re-prices — gpt-oss-120b input moved 0.024 → 0.022 within the day), HTTP 200, 2026-09-03 | | Auth rejection | HTTP 401, 2026-09-03 | | Live capability sweep | 2026-09-03 — 18-probe harness on the free model mytholite: roster, chat, max_completion_tokens, system role, content parts, sampling params, SSE stream (usage chunk + [DONE]), json_schema (valid JSON matching schema) and json_object | --- ## Troubleshooting | Symptom | Cause | Fix | | ------------------------ | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | `Invalid Mancer API key` | `MANCER_API_KEY` unset or wrong | Check the key at https://mancer.tech/dashboard | | Model not found | The roster changed since 2026-09-03 | Pick a current id; catalog providers retire models without notice | | Tools silently absent | Mancer declares `tools: false` | Use a tool-capable provider for agentic work — see [provider capabilities](/docs/reference/provider-feature-compatibility) | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Meta Model API Provider Guide # Meta Model API Provider Guide Meta Model API is a **Tier-2 catalog provider**: OpenAI-wire-compatible, so its entire integration is one JSON file (`src/lib/providers/catalog/meta-model-api.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** The vendor's `GET https://api.meta.ai/v1/models` needs a key > (an unauthenticated GET on 2026-09-29 answered HTTP 401), so the model ids > come from Meta's public docs and the roster has not been checked. No account > was created and no API key was used to build this entry. > `evidence.liveMatrix` is `null` until someone runs the live capability matrix > with a real key (see [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://dev.meta.ai/ — the page carries a "Start building" button whose link target is /api/auth/login 2. Create an API key: the Authentication page (https://dev.meta.ai/docs/authentication) lists the steps "Log in and open the API keys tab.", "Click Create API key, give it a descriptive name, and click Create." and "Copy the key right away. You only see it once." 3. Authentication is a Bearer token: the Authentication page says "Pass the key as a Bearer token in the Authorization header:", and the Error handling page (https://dev.meta.ai/docs/error-handling) lists `Malformed API key (not in LLM|{id}|{secret} format)` as a cause of HTTP 401 4. Billing as the vendor states it: the Pricing page (https://dev.meta.ai/docs/pricing-rate-limits) says "You pay only for what you use." and the Authentication and billing page (https://dev.meta.ai/docs/muse-code/auth) says "Meta Model API billing is usage-based: you're billed for the tokens your requests consume." 5. Set `META_MODEL_API_API_KEY` in your .env file (the vendor's examples read `MODEL_API_KEY`, which NeuroLink does not) ### 2. Configure ```bash export META_MODEL_API_API_KEY=your-api-key export META_MODEL_API_MODEL=muse-spark-1.3 # optional — overrides the default model export META_MODEL_API_BASE_URL=https://api.meta.ai/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "meta-model-api", model: "muse-spark-1.3", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider meta-model-api ``` Per-request credentials use the same call shape as the other catalog providers: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "meta-model-api", credentials: { metaModelApi: { apiKey: process.env.META_MODEL_API_API_KEY } }, }); ``` --- ## Billing The Pricing page (https://dev.meta.ai/docs/pricing-rate-limits) says "You pay only for what you use." and lists these prices per 1M tokens: | Tier | Cached input | Input | Output | | ----------- | ------------ | ----- | ------ | | Standard | $0.15 | $1.25 | $4.25 | | Contributor | $0.002 | $0.10 | $0.20 | The Authentication and billing page (https://dev.meta.ai/docs/muse-code/auth) says "Meta Model API billing is usage-based: you're billed for the tokens your requests consume." and lists two steps for a team admin: "Add a payment method." and "Create an API key." The Pricing page's Muse Voice Transcribe paragraph says "ZDR is priced at parity with Standard, and platform free-tier credits apply." The entry records the schema value `no-free-tier` as a placeholder: the schema has no unknown value, and the value is not a vendor statement. Rate limits on the Pricing page: Standard tier 3,000 requests per minute and 4,000,000 tokens per minute; Contributor tier 100 requests per minute and 3,000,000 tokens per minute. The page says "Limits apply per team, not per API key." --- ## Models | Model | Tier | Context | Vision | $/M in · out (cached input) | Notes | | ---------------------------- | ----------- | --------- | ------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `muse-spark-1.3` ⭐ | Standard | 1,048,576 | yes | $1.25 / $4.25 ($0.15) | NeuroLink default. Models page: "the latest version, tuned for agentic workflows (multi-step tool, browser, and long-horizon tasks) with improved coding over 1.2." and "Recommended for new work." Output figure 131072 (see below). | | `muse-spark-1.2` | Standard | 1,048,576 | yes | $1.25 / $4.25 ($0.15) | NeuroLink fallback. Models page: "the previous version." Home page card: "A coding-optimized model purpose-built for agentic workflows." | | `muse-spark-1.1` | Standard | 1,048,576 | yes | $1.25 / $4.25 ($0.15) | NeuroLink fallback. Models page: "the original version." Home page card: "Built for agentic workflows, coding, computer use & multimodal perception." | | `muse-spark-1.3-contributor` | Contributor | 1,048,576 | yes | $0.10 / $0.20 ($0.002) | Models page: the Contributor variant "trades a lower price for permission to train on your prompts and completions". Not in `models.fallbacks`. | | `muse-spark-1.2-contributor` | Contributor | 1,048,576 | yes | $0.10 / $0.20 ($0.002) | Models page: the Contributor variant "trades a lower price for permission to train on your prompts and completions". Not in `models.fallbacks`. | Context, tier and input modalities come from the "Available Muse Spark models" table on the [Models page](https://dev.meta.ai/docs/models) (retrieved 2026-09-29); prices come from the [Pricing page](https://dev.meta.ai/docs/pricing-rate-limits). The Models page lists `muse-image-1.0`, `muse-voice-transcribe-1.0` and `sam-3.1` in separate per-family tables; they are not in this catalog. The Chat Completions page says "Chat Completions serves the Muse Spark text models." **Output figure:** `muse-spark-1.3` carries `maxOutputTokens: 131072`, the value in the [Coding agents guide](https://dev.meta.ai/docs/coding-agents) entry for that model id: "Limits: context = 1048576, output = 131072". `models.defaultContextWindow` (1,048,576) is the context window the [Overview](https://dev.meta.ai/docs/overview) and Models pages state for the Muse Spark models. `models.defaultMaxOutputTokens` (16,384) is a NeuroLink placeholder that the vendor does not publish. **Vision:** the five catalog models are `vision: true`. The "Available Muse Spark models" table on the Models page lists image among their input modalities, and the [Image understanding page](https://dev.meta.ai/docs/image-understanding) says "image understanding is fully supported" on Chat Completions. **Status:** the `status` field of the five models holds `production`, a placeholder for a value the catalog schema requires; it is not a vendor statement. **Fallback order** when the default is unavailable: `muse-spark-1.2` → `muse-spark-1.1`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `muse-spark-1.1`. The Contributor-tier ids are in `models.catalog` and `models.topModels`; `models.fallbacks` lists the Standard-tier ids. --- ## Vendor-documented request parameters These are statements on Meta's own pages about request fields on Chat Completions. They are quoted as written and were not exercised against the API. | Request | What the vendor page says | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `tool_choice` other than auto | Tool calling page: "tool_choice must be "auto": Only "auto" (the default) is supported on both Chat Completions and the Responses API; "none", "required", and named function choices return HTTP 400" | | `reasoning_effort: "none"` | Chat Completions page: "Muse Spark always reasons, so reasoning_effort: "none" returns HTTP 400." | | `n` above 1 | Chat Completions page: "Only n=1 is supported; values greater than 1 return HTTP 400." | | `stop` | Chat Completions page, OpenAI compatibility notes table: "Not supported on reasoning models. This matches OpenAI's behavior on o3 and o4-mini." | | `logprobs: true` | Chat Completions page: "logprobs: true returns HTTP 400" | | `max_tokens` | Chat Completions page, Parameters table: "The deprecated alias max_tokens is still accepted." | | `system` role | Chat Completions page: "accepted for OpenAI compatibility and treated at the same level as developer" | --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Meta Model API — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://api.meta.ai/v1/models` answered HTTP 401 on 2026-09-29, so model ids are taken from the [Models page](https://dev.meta.ai/docs/models); the roster has not been checked. The [List models reference](https://dev.meta.ai/docs/api-reference/models/list-models) shows `GET /models` called with a Bearer key | | Auth-failure shape | unauthenticated `GET https://api.meta.ai/v1/models`: HTTP 401, `content-type: application/json`, body `{"error":{"code":"invalid_api_key","message":"Unauthorized","param":null,"type":"authentication_error"}}`. An unauthenticated `GET https://api.meta.ai/v1/chat/completions` answered HTTP 401 with the same body and the header `allow: POST` | | Billing | public Pricing and Authentication and billing pages, quoted in [Billing](#billing) above; no signup performed, 2026-09-29 | | Tools / structured output | documented on the Tool calling and Structured output pages; neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=meta-model-api` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting The Vendor statement column quotes the vendor's own pages. | Symptom | Vendor statement | NeuroLink note | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | | HTTP 401 | Error handling page: "The API key was missing, invalid, or revoked." Its fix line: "Send a valid Authorization: Bearer $MODEL_API_KEY header." | NeuroLink reads `META_MODEL_API_API_KEY`; the vendor's examples use `MODEL_API_KEY` | | HTTP 402 | Error handling page: "The request cannot be completed due to a billing issue." Its fix line: "Check account status and billing details in the Model API dashboard." | The example body's `error.code` is `billing_not_configured` | | HTTP 404, code `model_not_found` | Quickstart page: "404 model_not_found: use a valid model ID such as muse-spark-1.3 (the default in these examples) or muse-spark-1.1 exactly." | The five catalog ids are listed in [Models](#models) | | HTTP 429 | Error handling page: "Your team has exceeded the rate limit." Its fix line: "Implement exponential backoff with jitter." | Limits are listed in [Billing](#billing) | | HTTP 504 on a non-streaming request | Chat Completions page: "a non-streaming request that runs too long returns HTTP 504". Error handling page fix line: "Stream the response by setting stream: true." | Use `neurolink.stream()` for a streamed request | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) - Meta Model API pages opened for this entry: [Home](https://dev.meta.ai/), [Overview](https://dev.meta.ai/docs/overview), [Quickstart](https://dev.meta.ai/docs/quickstart), [Authentication](https://dev.meta.ai/docs/authentication), [Models](https://dev.meta.ai/docs/models), [Pricing and rate limits](https://dev.meta.ai/docs/pricing-rate-limits), [Chat Completions](https://dev.meta.ai/docs/protocols/chat-completions), [Tool calling](https://dev.meta.ai/docs/tool-calling), [Structured output](https://dev.meta.ai/docs/structured-output), [Reasoning](https://dev.meta.ai/docs/reasoning), [Image understanding](https://dev.meta.ai/docs/image-understanding), [Coding agents](https://dev.meta.ai/docs/coding-agents), [Authentication and billing](https://dev.meta.ai/docs/muse-code/auth), [Error handling](https://dev.meta.ai/docs/error-handling) --- ## MiniMax Provider Guide # MiniMax Provider Guide MiniMax is a **Tier-2 catalog provider**: its integration is one JSON file (`src/lib/providers/catalog/minimax.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** MiniMax's `GET https://api.minimax.io/v1/models` answers > HTTP 401 without a key, so the model ids come from MiniMax's public docs and > the roster has not been checked. No account was created and no API key was > used to build the entry. `evidence.liveMatrix` is `null` until someone runs > the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://platform.minimax.io/login?source=platform_docs and register or log in (https://platform.minimax.io/docs/guides/quickstart-preparation) 2. Pay-as-you-go: open API Keys > Create new secret key at https://platform.minimax.io/user-center/basic-information/interface-key and copy the API Key (https://platform.minimax.io/docs/guides/quickstart-preparation) 3. Token Plan: view your Subscription Key at https://platform.minimax.io/user-center/payment/token-plan. MiniMax-M3.1-Flash-Preview is stated as available only through Token Plan and MiniMax Code for now, and the Subscription Key is stated as not interchangeable with pay-as-you-go API Keys (https://platform.minimax.io/docs/api-reference/text-openai-api, https://platform.minimax.io/docs/token-plan/intro) 4. Billing as the vendor words it: "Pay-as-you-go uses standard Open Platform API Keys and consumes your account balance by actual usage." (https://platform.minimax.io/docs/guides/pricing-paygo) and "New users without subscription can try the free quota from Pay-as-you-go" (https://platform.minimax.io/docs/solutions/eigent, a tutorial dated January 23, 2026) 5. Set `MINIMAX_API_KEY` in your .env file ### 2. Configure ```bash export MINIMAX_API_KEY=your-api-key export MINIMAX_MODEL=MiniMax-M3 # optional — overrides the default model export MINIMAX_BASE_URL=https://api.minimax.io/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "minimax", model: "MiniMax-M3", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider minimax ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "minimax", credentials: { minimax: { apiKey: process.env.MINIMAX_API_KEY } }, }); ``` --- ## Billing MiniMax's pay-as-you-go pricing page (https://platform.minimax.io/docs/guides/pricing-paygo) says: "Pay-as-you-go uses standard Open Platform API Keys and consumes your account balance by actual usage." The Prerequisites page (https://platform.minimax.io/docs/guides/quickstart-preparation) says: "For pay-as-you-go, access Billing/Balance to top up if needed." MiniMax's Eigent tutorial (https://platform.minimax.io/docs/solutions/eigent, dated January 23, 2026 and written for MiniMax M2.1) says: "New users without subscription can try the free quota from Pay-as-you-go". The catalog schema has no `unknown` billing value, so the entry records `free-tier` as the closest value. It is not a MiniMax statement of terms. --- ## Models | Model | Context | Max output | Vision | $/M in · out (cache read) | Notes | | ---------------------------- | --------- | ---------- | ------ | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `MiniMax-M3` ⭐ | 1,000,000 | 524,288 | yes | $0.30 / $1.20 ($0.06) | NeuroLink default. "Frontier multimodal coding model with 1M context window". Prices are the Standard tab, "≤ 512k input tokens", with $0.60 / $2.40 / $0.12 struck through beside them and the label "Permanent 50% off"; "> 512k input tokens" is $0.60 / $2.40 ($0.12), with $1.20 / $4.80 / $0.24 struck through. Priority tab: "Pricing is 1.5x standard." RPM 200, TPM 10,000,000. | | `MiniMax-M3.1-Flash-Preview` | 1,000,000 | 524,288 | yes | — | "Frontier multimodal coding model with 1M context window and tunable thinking depth". "MiniMax-M3.1-Flash-Preview is available only through Token Plan and MiniMax Code for now." Not in the fallback chain. | | `MiniMax-M2.7` | 204,800 | 204,800 | no | $0.3 / $1.2 ($0.06) | "Beginning the journey of recursive self-improvement". Cache write $0.375. RPM 500, TPM 20,000,000. | | `MiniMax-M2.7-highspeed` | 204,800 | 204,800 | no | $0.6 / $2.4 ($0.06) | "M2.7 Highspeed: Same performance, faster and more agile (output speed approximately 100 tps)". Cache write $0.375. RPM 500, TPM 20,000,000. | | `MiniMax-M2.5` | 204,800 | 204,800 | no | $0.3 / $1.2 ($0.03) | "Peak Performance. Ultimate Value. Master the Complex". Listed under "Legacy Models". Cache write $0.375. | | `MiniMax-M2.5-highspeed` | 204,800 | 204,800 | no | $0.6 / $2.4 ($0.03) | "M2.5 highspeed: Same performance, faster and more agile (output speed approximately 100 tps)". Listed under "Legacy Models". Cache write $0.375. | | `MiniMax-M2.1` | 204,800 | 204,800 | no | $0.3 / $1.2 ($0.03) | "Powerful Multi-Language Programming Capabilities with Comprehensively Enhanced Programming Experience". Listed under "Legacy Models". Cache write $0.375. | | `MiniMax-M2.1-highspeed` | 204,800 | 204,800 | no | $0.6 / $2.4 ($0.03) | "Faster and More Agile (output speed approximately 100 tps)". Listed under "Legacy Models". Cache write $0.375. | | `MiniMax-M2` | 204,800 | not set | no | $0.3 / $1.2 ($0.03) | "Agentic capabilities, Advanced reasoning". Listed under "Legacy Models". Cache write $0.375. Max output is not set; see the paragraph below the table. | Context windows come from the Supported Models table of the OpenAI SDK page (https://platform.minimax.io/docs/api-reference/text-openai-api, retrieved 2026-09-29). Max output figures come from the `max_completion_tokens` description in the Chat Completions reference (https://platform.minimax.io/docs/api-reference/text-chat-openai): "the maximum is 524288 (512K)" for `MiniMax-M3.1-Flash-Preview` and `MiniMax-M3`, and "the maximum is 204800 (200K)" for other models. Prices come from the pay-as-you-go pricing page (https://platform.minimax.io/docs/guides/pricing-paygo, retrieved 2026-09-29); the `MiniMax-M2.5`, `MiniMax-M2.5-highspeed`, `MiniMax-M2.1`, `MiniMax-M2.1-highspeed` and `MiniMax-M2` rows sit in that page's Legacy Models section. Rate limits come from https://platform.minimax.io/docs/guides/rate-limits. `MiniMax-M2` has no max output figure in the catalog. The Models page (https://platform.minimax.io/docs/guides/models-intro), under Legacy Models, lists "Maximum Output: 128k tokens (including CoT)" for `MiniMax-M2`, while the Chat Completions reference says "the maximum is 204800 (200K)" for models other than `MiniMax-M3.1-Flash-Preview` and `MiniMax-M3`. The two pages give different figures, so the field is left unset for this id. `vision: true` is set where the OpenAI SDK page states image input. `vision: false` is set for `MiniMax-M2.7`, `MiniMax-M2.7-highspeed`, `MiniMax-M2.5`, `MiniMax-M2.5-highspeed`, `MiniMax-M2.1`, `MiniMax-M2.1-highspeed` and `MiniMax-M2`. The Anthropic API page (https://platform.minimax.io/docs/api-reference/text-anthropic-api, retrieved 2026-09-29) says in its `messages` row: "The M2.7, M2.5, M2.1, and M2 series support text and tool-call content blocks only; they do not support image or video input". `models.defaultContextWindow` (204,800) and `models.defaultMaxOutputTokens` (65,536) apply to ids outside the catalog. 204,800 is the context window the OpenAI SDK page lists for the `MiniMax-M2.x` models, and 65,536 is the recommended `max_completion_tokens` the Chat Completions reference gives for models other than `MiniMax-M3.1-Flash-Preview` and `MiniMax-M3`. **Fallback order** when the default is unavailable: `MiniMax-M2.7` → `MiniMax-M2.7-highspeed` → `MiniMax-M2.5` → `MiniMax-M2.5-highspeed` → `MiniMax-M2.1` → `MiniMax-M2.1-highspeed` → `MiniMax-M2`. The runtime fallback model name is set explicitly to `MiniMax-M2.7`. `MiniMax-M3.1-Flash-Preview` is in the catalog but not in the fallback chain, because the vendor states it is available only through Token Plan and MiniMax Code for now. **Status values:** `production` is a value the schema requires, not a MiniMax statement; `preview` is used for the one id the vendor names Preview. --- ## Reasoning output The OpenAI SDK page says: "For native OpenAI API with `MiniMax-M3.1-Flash-Preview` `MiniMax-M3` `MiniMax-M2.7` `MiniMax-M2.7-highspeed` `MiniMax-M2.5` `MiniMax-M2.5-highspeed` `MiniMax-M2.1` `MiniMax-M2.1-highspeed` `MiniMax-M2` models, the `content` field will contain `` tag content, which must be preserved completely", and separately: "`MiniMax-M3.1-Flash-Preview` provides the model's thinking content separately through the `reasoning_content` field, which must also be preserved completely". The same page lists `reasoning_split` as an "Output-format switch": "When `true`, thinking content is separated into the `reasoning_content` field; when `false`, thinking stays inside `content` wrapped in `` tags." This catalog entry does not send `reasoning_split`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for MiniMax — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://api.minimax.io/v1/models` answers HTTP 401 without a key (2026-09-29), so model ids are taken from the OpenAI SDK page (retrieved 2026-09-29); **roster not verified** | | Auth-failure shape | unauthenticated `GET https://api.minimax.io/v1/models` returned HTTP 401 with body `{"type":"error","error":{"type":"authorized_error","message":"login fail: Please carry the API secret key in the 'Authorization' field of the request header (1004)","http_code":"401"},"request_id":"…"}` (2026-09-29). An unauthenticated `GET https://api.minimax.io/v1/chat/completions` returned HTTP 404 with `content-type: text/plain` and the body `404 page not found`. No POST was sent, so `errorRules` match status 401 and the vendor's documented messages | | Billing | public pay-as-you-go pricing page, Prerequisites page and Eigent tutorial quoted in [Billing](#billing) above, 2026-09-29 — the schema has no `unknown` value, so `free-tier` is the closest value | | Tools / structured output | function calling is documented on the Chat Completions reference and the OpenAI SDK page; nothing was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=minimax` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting Causes and fixes in quotation marks are MiniMax's wording, with the page named. | Symptom | Cause | Fix | | --------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | HTTP 401 with `login fail: Please carry the API secret key in the 'Authorization' field of the request header (1004)` | The error-code table lists 1004 as "not authorized / token not match group / cookie is missing, log in again" (errorcode page) | "please check your API Key and make sure it is correct and active." (https://platform.minimax.io/docs/api-reference/errorcode) | | Error 1008 "insufficient balance" | Listed in the error-code table | "Please check your account balance." (https://platform.minimax.io/docs/api-reference/errorcode) | | Error 1002 "rate limit" | Listed in the error-code table | "Please retry your requests later." (https://platform.minimax.io/docs/api-reference/errorcode) | | Empty `content` with `finish_reason: "length"` | "Thinking tokens count toward it too" (OpenAI SDK page, `max_tokens` row) | "If generation stops due to `length`, try increasing this value." (Chat Completions reference, `max_completion_tokens`) | | `MiniMax-M3.1-Flash-Preview` selected | "MiniMax-M3.1-Flash-Preview is available only through Token Plan and MiniMax Code for now." (https://platform.minimax.io/docs/guides/text-generation) | "Get your Subscription Key" (https://platform.minimax.io/docs/guides/text-generation) | | Error after setting `temperature` above 2 | "The `temperature` parameter range is [0, 2], recommended value: 1.0, values outside this range will return an error" (OpenAI SDK page) | "recommended value: 1.0" (OpenAI SDK page) | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) - MiniMax pages this entry was built from: [OpenAI SDK](https://platform.minimax.io/docs/api-reference/text-openai-api), [Chat Completions](https://platform.minimax.io/docs/api-reference/text-chat-openai), [Anthropic API](https://platform.minimax.io/docs/api-reference/text-anthropic-api), [Models](https://platform.minimax.io/docs/guides/models-intro), [Model Invocation](https://platform.minimax.io/docs/guides/text-generation), [Pay as You Go](https://platform.minimax.io/docs/guides/pricing-paygo), [Rate Limits](https://platform.minimax.io/docs/guides/rate-limits), [Error Codes](https://platform.minimax.io/docs/api-reference/errorcode), [Prerequisites](https://platform.minimax.io/docs/guides/quickstart-preparation), [Token Plan Overview](https://platform.minimax.io/docs/token-plan/intro) --- ## Mistral AI Provider Guide # Mistral AI Provider Guide **European AI excellence with GDPR compliance and competitive free tier** ## Quick Start ### 1. Get Your API Key 1. Visit [Mistral AI Console](https://console.mistral.ai/) 2. Create a free account 3. Go to "API Keys" section 4. Click "Create new key" 5. Copy the key (format: `xxx...`) ### 2. Configure NeuroLink Add to your `.env` file: ```bash MISTRAL_API_KEY=your_api_key_here ``` ### 3. Test the Setup ```bash # CLI - Test with default model npx @juspay/neurolink generate "Bonjour! Comment allez-vous?" --provider mistral # CLI - Use specific model npx @juspay/neurolink generate "Explain quantum physics" --provider mistral --model "mistral-large-latest" # SDK node -e " const { NeuroLink } = require('@juspay/neurolink'); (async () => { const ai = new NeuroLink(); const result = await ai.generate({ input: { text: 'Hello from Mistral AI!' }, provider: 'mistral' }); console.log(result.content); })(); " ``` --- ## Model Selection Guide ### Available Models | Model | Model ID | Context | Vision | Use Case | | ---------------------- | ------------------------- | ------- | ------ | -------------------------------------------------------- | | **Mistral Large 3** | `mistral-large-latest` | 256K | Yes | Flagship, agentic — native vision replaces Pixtral Large | | **Mistral Medium 3.1** | `mistral-medium-latest` | 128K | Yes | Balanced performance/cost | | **Mistral Small 4** | `mistral-small-latest` | 128K | Yes | MoE architecture, strong reasoning at low cost | | **Magistral Medium** | `magistral-medium-latest` | 128K | Yes | Reasoning-focused | | **Magistral Small** | `magistral-small-latest` | 128K | Yes | Reasoning (Apache 2.0 license) | | **Codestral** | `codestral-latest` | 256K | No | Code generation and review | | **Devstral 2** | `devstral-2512` | 256K | No | Agentic coding workflows | | **Pixtral Large** | `pixtral-large` | 128K | Yes | Vision (deprecated — use Mistral Large 3) | | **Mistral Embed** | `mistral-embed` | — | — | Embeddings (1024 dimensions) | | **Codestral Embed** | `codestral-embed` | — | — | Code embeddings | :::info[Pixtral Large Superseded] Pixtral Large has been superseded by **Mistral Large 3**, which includes native vision capabilities alongside its flagship text performance. New projects should use `mistral-large-latest` for both text and vision tasks. The `pixtral-large` model ID remains available but is considered deprecated. ::: ### Free Tier Details ✅ **What's Included:** - **$5 free credits** for new users - **No time limit** on free credits - **All models available** on free tier - **No credit card** required for signup **Free Tier Estimate:** - ~2.5M tokens with mistral-small - ~625K tokens with mistral-large - ~5M tokens with codestral ### Model Selection by Use Case ```typescript // Complex reasoning and analysis const complex = await ai.generate({ input: { text: "Analyze this business strategy..." }, provider: "mistral", model: "mistral-large-latest", }); // General production workloads const general = await ai.generate({ input: { text: "Customer support query" }, provider: "mistral", model: "mistral-small-latest", }); // Code generation and review const code = await ai.generate({ input: { text: "Write a REST API in Python" }, provider: "mistral", model: "codestral-latest", }); ``` NeuroLink does not serve embeddings through Mistral. For RAG, pair Mistral for generation with a [provider that supports embeddings](/docs/features/embeddings). --- ## GDPR Compliance & European Deployment ### Why Mistral for EU Companies **Built-in GDPR Compliance:** - ✅ European company (France-based) - ✅ EU data centers - ✅ GDPR-compliant by design - ✅ No data sent to US servers - ✅ Data residency in Europe ### Data Residency Configuration ```typescript // Ensure EU data residency via environment variables // Set MISTRAL_API_KEY in your .env file // Set MISTRAL_REGION=eu to explicitly use EU endpoints const ai = new NeuroLink(); const result = await ai.generate({ input: { text: "Your prompt" }, provider: "mistral", }); ``` ### GDPR Compliance Checklist ```typescript // ✅ GDPR-compliant setup // Configure via environment variables: // MISTRAL_API_KEY=your-key // MISTRAL_REGION=eu const gdprAI = new NeuroLink(); // Document data processing const result = await gdprAI.generate({ input: { text: userQuery }, provider: "mistral", metadata: { userId: "anonymized-id", purpose: "customer-support", legalBasis: "consent", }, }); ``` ### Compliance Features | Feature | Mistral AI | Other Providers | | -------------------- | ----------------- | --------------- | | **EU Data Centers** | ✅ Yes | ⚠️ Limited | | **GDPR Compliance** | ✅ Built-in | ⚠️ Varies | | **Data Residency** | ✅ EU-only option | ⚠️ Often US | | **Privacy Controls** | ✅ Granular | ⚠️ Limited | | **Audit Logs** | ✅ Available | ⚠️ Varies | --- ## SDK Integration ### Basic Usage ```typescript const ai = new NeuroLink(); // Simple generation const result = await ai.generate({ input: { text: "Explain artificial intelligence" }, provider: "mistral", }); console.log(result.content); ``` ### With Specific Model ```typescript // Use Mistral Large for complex tasks const large = await ai.generate({ input: { text: "Analyze this complex business scenario..." }, provider: "mistral", model: "mistral-large-latest", temperature: 0.7, maxTokens: 2000, }); // Use Codestral for code generation const code = await ai.generate({ input: { text: "Create a FastAPI application with authentication" }, provider: "mistral", model: "codestral-latest", }); ``` ### Streaming Responses ```typescript // Stream long responses for better UX for await (const chunk of ai.stream({ input: { text: "Write a detailed technical article about microservices" }, provider: "mistral", model: "mistral-large-latest", })) { process.stdout.write(chunk.content); } ``` ### Multi-Language Support ```typescript // Mistral excels at European languages const languages = [ { lang: "French", prompt: "Expliquez la blockchain" }, { lang: "Spanish", prompt: "Explica la inteligencia artificial" }, { lang: "German", prompt: "Erkläre maschinelles Lernen" }, { lang: "Italian", prompt: "Spiega il deep learning" }, ]; for (const { lang, prompt } of languages) { const result = await ai.generate({ input: { text: prompt }, provider: "mistral", }); console.log(`${lang}: ${result.content}`); } ``` ### Cost Tracking ```typescript // Track costs with analytics const result = await ai.generate({ input: { text: "Your prompt" }, provider: "mistral", model: "mistral-small-latest", enableAnalytics: true, }); // Calculate cost (mistral-small: €2/1M tokens) const cost = (result.usage.total / 1_000_000) * 2; console.log(`Cost: €${cost.toFixed(4)}`); console.log(`Tokens used: ${result.usage.total}`); ``` --- ## CLI Usage ### Basic Commands ```bash # Generate with default model npx @juspay/neurolink generate "Hello Mistral" --provider mistral # Use specific model npx @juspay/neurolink gen "Write code" --provider mistral --model "codestral-latest" # Stream response npx @juspay/neurolink stream "Tell a story" --provider mistral # Check status npx @juspay/neurolink status --provider mistral ``` ### Advanced Usage ```bash # With temperature and max tokens npx @juspay/neurolink gen "Creative writing" \ --provider mistral \ --model "mistral-large-latest" \ --temperature 0.9 \ --max-tokens 2000 # Code generation with Codestral npx @juspay/neurolink gen "Create a React component" \ --provider mistral \ --model "codestral-latest" \ > component.tsx # Interactive mode npx @juspay/neurolink loop --provider mistral --model "mistral-large-latest" ``` ### Cost-Effective Workflows ```bash # Use mistral-small for production (cheaper) npx @juspay/neurolink gen "Customer query: How do I reset my password?" \ --provider mistral \ --model "mistral-small-latest" # Use mistral-large only for complex tasks npx @juspay/neurolink gen "Analyze quarterly financial performance" \ --provider mistral \ --model "mistral-large-latest" ``` --- ## Configuration Options ### Environment Variables ```bash # Required MISTRAL_API_KEY=your_api_key_here # Optional MISTRAL_BASE_URL=https://api.mistral.ai # Custom endpoint MISTRAL_DEFAULT_MODEL=mistral-small-latest # Default model MISTRAL_TIMEOUT=60000 # Request timeout (ms) MISTRAL_REGION=eu # Enforce EU endpoints ``` ### Programmatic Configuration ```typescript // Configure via environment variables: // MISTRAL_API_KEY=your-key // MISTRAL_DEFAULT_MODEL=mistral-small-latest // MISTRAL_REGION=eu // MISTRAL_TIMEOUT=60000 const ai = new NeuroLink(); const result = await ai.generate({ input: { text: "Your prompt" }, provider: "mistral", }); ``` --- ## Enterprise Deployment ### Production Setup ```typescript // Enterprise-grade Mistral configuration via environment variables: // MISTRAL_API_KEY=your-key // MISTRAL_REGION=eu // MISTRAL_TIMEOUT=120000 const enterpriseAI = new NeuroLink({ enableOrchestration: true, // Enable provider orchestration/failover }); // Use Mistral as primary, with Anthropic as fallback const result = await enterpriseAI.generate({ input: { text: "Enterprise query" }, provider: "mistral", }); ``` ### Multi-Region Deployment ```typescript // Serve EU and global users // Configure MISTRAL_REGION=eu in your environment const multiRegionAI = new NeuroLink(); // Route EU users to Mistral (EU data residency) async function handleRequest(userRegion: string, prompt: string) { const provider = userRegion === "EU" ? "mistral" : "openai"; return multiRegionAI.generate({ input: { text: prompt }, provider, }); } ``` ### Cost Optimization ```typescript // Smart model selection based on complexity async function generateWithCostOptimization(prompt: string) { const complexity = estimateComplexity(prompt); const model = complexity > 0.7 ? "mistral-large-latest" // Complex: €8/1M : "mistral-small-latest"; // Simple: €2/1M return await ai.generate({ input: { text: prompt }, provider: "mistral", model, }); } function estimateComplexity(prompt: string): number { // Complexity scoring constants (0-1 scale) const LENGTH_WEIGHT = 0.3; // Characters per 1000 const CODE_COMPLEXITY_WEIGHT = 0.4; // Technical implementation tasks const ANALYSIS_COMPLEXITY_WEIGHT = 0.5; // Deep analysis/reasoning tasks const LENGTH_SCALE = 1000; // Normalize character count const length = prompt.length; const hasCodeKeywords = /function|class|api|database/i.test(prompt); const hasAnalysisKeywords = /analyze|compare|evaluate|assess/i.test(prompt); return ( (length / LENGTH_SCALE) * LENGTH_WEIGHT + (hasCodeKeywords ? CODE_COMPLEXITY_WEIGHT : 0) + (hasAnalysisKeywords ? ANALYSIS_COMPLEXITY_WEIGHT : 0) ); } ``` --- ## Troubleshooting ### Common Issues #### 1. "Invalid API Key" **Problem**: API key is incorrect or expired. **Solution**: ```bash # Verify key at console.mistral.ai # Ensure no extra spaces in .env MISTRAL_API_KEY=your_key_here # ✅ Correct MISTRAL_API_KEY= your_key_here # ❌ Extra space ``` #### 2. "Rate Limit Exceeded" **Problem**: Exceeded free tier or paid tier limits. **Solution**: ```typescript // Implement exponential backoff async function generateWithBackoff(prompt, maxRetries = 3) { for (let i = 0; i setTimeout(r, delay)); } else { throw error; } } } } ``` #### 3. "Insufficient Credits" **Problem**: Free tier exhausted. **Solution**: - Add payment method in Mistral console - Use fallback provider - Monitor usage: ```typescript // Track usage to avoid surprises const result = await ai.generate({ input: { text: prompt }, provider: "mistral", enableAnalytics: true, }); console.log(`Tokens used: ${result.usage.total}`); console.log(`Estimated cost: €${(result.usage.total / 1_000_000) * 2}`); ``` #### 4. Slow Response Times **Problem**: Model or network latency. **Solution**: ```typescript // Use streaming for immediate feedback for await (const chunk of ai.stream({ input: { text: "Long prompt requiring detailed response" }, provider: "mistral", })) { // Display partial results immediately console.log(chunk.content); } ``` --- ## Best Practices ### 1. GDPR-Compliant Usage ```typescript // ✅ Good: Anonymize user data const result = await ai.generate({ input: { text: sanitizeUserInput(userQuery) }, provider: "mistral", metadata: { userId: hashUserId(userId), // Hash, don't store raw timestamp: new Date().toISOString(), purpose: "customer-support", }, }); // Document processing await auditLog.record({ action: "ai-generation", provider: "mistral", legalBasis: "legitimate-interest", dataRetention: "30-days", }); ``` ### 2. Cost Optimization ```typescript // ✅ Good: Use appropriate model for task const customerSupport = await ai.generate({ input: { text: "How do I reset my password?" }, provider: "mistral", model: "mistral-small-latest", // €2/1M vs €8/1M }); // ✅ Good: Cache common queries const cache = new Map(); const cacheKey = `mistral:${userQuery}`; if (cache.has(cacheKey)) { return cache.get(cacheKey); } const result = await ai.generate({ input: { text: userQuery }, provider: "mistral", }); cache.set(cacheKey, result); ``` ### 3. Multi-Language Support ```typescript // ✅ Good: Leverage Mistral's multilingual strength const supportedLanguages = ["en", "fr", "es", "de", "it"]; async function generateInLanguage(prompt, language) { const languagePrompt = language !== "en" ? `[Respond in ${language}] ${prompt}` : prompt; return await ai.generate({ input: { text: languagePrompt }, provider: "mistral", // Excellent European language support }); } ``` --- ## Related Documentation - **[Provider Setup Guide](/docs/getting-started/provider-setup)** - General provider configuration - **[GDPR Compliance Guide](/docs/guides/enterprise/compliance)** - GDPR implementation - **[Cost Optimization](/docs/cookbook/cost-optimization)** - Reduce AI costs - **[Multi-Region Deployment](/docs/guides/enterprise/multi-region)** - Geographic distribution --- ## Additional Resources - **[Mistral AI Console](https://console.mistral.ai/)** - API keys and billing - **[Mistral AI Documentation](https://docs.mistral.ai/)** - Official docs - **[Mistral Models](https://docs.mistral.ai/models/)** - Model capabilities - **[Pricing](https://mistral.ai/pricing/)** - Current pricing --- **Need Help?** Join our [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## Moark Provider Guide # Moark Provider Guide Moark is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no known behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/moark.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status: docs- and roster-verified, not yet live-verified.** > This entry was onboarded credential-free — no API key was created or used. > Everything below comes from Moark's public docs > (`https://moark.com/docs/...`) and an unauthenticated > `GET https://moark.com/v1/models` (2026-09-28, HTTP 200, 222 models). No > `chat/completions` request was ever sent, so `capabilities`, error shapes > and per-model context/output limits are **not** wire-proven. Before relying > on this provider in production, run the live-verification steps in > [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) > with a funded key. ## Quick Start ### 1. Get an API key 1. Visit: https://moark.com and sign in — no separate signup page is documented, only workbench login 2. Go to 工作台 → 设置 → 访问令牌 (Workbench → Settings → Access Tokens) at https://moark.com/dashboard/tokens and create a token 3. Fund a prepaid resource package before making live calls (e.g. the all-model package, https://moark.com/serverless-api/order?package=1910) — billing is prepaid, charged per-call or per-token (https://moark.com/docs/products/apis, retrieved 2026-09-28); models can be tried free in the web console, but no formal free-tier API policy is documented, and package usage is non-refundable (https://moark.com/docs/billing/purchase, retrieved 2026-09-28) 4. Set `MOARK_API_KEY` in your .env file ### 2. Configure ```bash export MOARK_API_KEY=your-api-key export MOARK_MODEL=Qwen3-8B # optional — overrides the default model export MOARK_BASE_URL=https://api.moark.com/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "moark", model: "Qwen3-8B", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider moark ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "moark", credentials: { moark: { apiKey: process.env.MOARK_API_KEY } }, }); ``` --- ## Models | Model | Vision | Notes | | ---------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Qwen3-8B` ⭐ | no | Recommended — Moark's own docs name this (and `Qwen3-4B`) as its suggested free-testing/validation model; the only documented recommendation that also matches a currently-live roster id. Not capability-probed. | | `Qwen3-4B` | no | Named alongside `Qwen3-8B` as a free testing/validation model; smaller sibling. Roster-listed only; fallback. | | `ERNIE-4.5-Turbo` | no | Baidu ERNIE 4.5 Turbo — Moark's docs suggest this for multilingual use cases. Roster-listed only; fallback. | | `GLM-5.3` | no | Zhipu GLM-5.3 — on the live roster; not named specifically in Moark's docs. Roster-listed only; fallback. | | `kimi-k3` | no | Moonshot AI Kimi K3 — closest live match to the docs' "long text" pick (`kimi-k2-instruct`, no longer on the roster). Roster-listed only; fallback. | | `DeepSeek-V4-Pro-0813` | no | DeepSeek V4 Pro — closest live match to the docs' "specialized reasoning" pick (`DeepSeek-R1`, no longer on the roster). Roster-listed only; fallback. | No context window, max output tokens or pricing are shown per model. Moark's docs give only a generic "32K、128K 等" illustration — not tied to any specific model — and the unauthenticated `GET /v1/models` response returns only `{id, object, created, owned_by}`, with no `context_length` or pricing fields. The catalog's `defaultContextWindow` (32,000) and `defaultMaxOutputTokens` (4,096) are therefore **not vendor-confirmed per-model figures**: the context number reflects the vendor's own generic example text, and the output-token number is an unverified conservative placeholder. Both need a live probe (or an authenticated roster call that returns real per-model limits) before they can be trusted. **Fallback order** when the default is unavailable: `Qwen3-4B` → `ERNIE-4.5-Turbo` → `GLM-5.3` → `kimi-k3` → `DeepSeek-V4-Pro-0813`. The other 216 models on Moark's roster (vision, image, video, audio, embedding, reranking, moderation, TTS/ASR, etc.) are intentionally left out of this catalog entry, which covers only the OpenAI-compatible chat surface. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Moark — **deliberately thinner than a live-verified entry**, since no key was created: | Probe | Result | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://moark.com/v1/models`, HTTP 200, 222 models, 2026-09-28 | | Docs cross-check | `docs/openapi/v1`, `docs/products/apis`, `docs/products/apis/texts/text-generation`, `docs/products/apis/texts/function-calling`, `docs/billing/purchase` — all fetched 2026-09-28, confirm OpenAI-compatible wire shape, Bearer auth, and prepaid billing | | Auth rejection | **not probed** — would require a POST request, out of scope for credential-free onboarding | | Live capability sweep | **not run** — no key was created or used | Because no authenticated or POST request was made, `capabilities.tools` is recorded as `"model-dependent"` (the docs name specific Function-Calling models rather than claiming universal support), `structuredOutput` and `structuredOutputWithTools` are `false` (no `response_format` wire example exists, only the vendor's own `guided_json`/`guided_choice` extensions), and `errorRules` is empty (no documented error-body shape was found). --- ## Troubleshooting | Symptom | Cause | Fix | | ------------------------------------------ | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | Requests fail with an auth-shaped error | `MOARK_API_KEY` unset, wrong, or the account has no funded package | Check the token at https://moark.com/dashboard/tokens and confirm a prepaid package is active | | Model not found | The roster changed since 2026-09-28 | Pick a current id from the unauthenticated `GET https://moark.com/v1/models` roster | | Structured output not returned as expected | This entry doesn't send `response_format` — Moark only documents `guided_json`/`guided_choice` | Not currently wired through the generic OpenAI-compat client; treat `structuredOutput` as unsupported until a live probe proves otherwise | | Tool calls silently ignored | Function calling is documented as model-dependent, not universal | Confirm the chosen model is one of Moark's documented Function-Calling models before relying on `tools` | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration, and the live-verification steps this entry still needs - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## ModelScope Provider Guide # ModelScope Provider Guide ModelScope is a **Tier-2 catalog provider**: OpenAI-compatible, defined by one JSON file (`src/lib/providers/catalog/modelscope.json`) rather than hand-written code. This page is written from that file. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** The fields below come from ModelScope's own public > documentation and unauthenticated GET requests — no account was created and > no API key was used to build it. `evidence.liveMatrix` is `null` until > someone runs the live capability matrix with a real key (see > [Verification status](#verification-status) below). The docs text on this page was read on 2026-09-29 from the raw document files that the docs site loads, because the rendered pages at `modelscope.cn/docs` are a JavaScript shell. The English build is `https://resouces.modelscope.cn/document/docdata/2026-9-28_15-50-EN/dist/model-service/API-Inference/intro/intro_EN.md` (and the matching `limits`, `codewhale`, `magicube`, `accounts/registration` and `accounts/token` files); the Chinese build is under `https://resouces.modelscope.cn/document/docdata/2026-9-28_15-49-CN/dist/index.json` (its `model-service/API-Inference/intro/intro_CN.md` sibling holds the Chinese intro page). Quotes below are English unless a Chinese build is named. ## Quick Start ### 1. Get an API key 1. Visit: https://modelscope.cn/home and register or log in with the "Log in/Register" button in the top right corner (https://modelscope.cn/docs/accounts/registration) 2. Bind an Alibaba Cloud account and complete real-name verification: "After account registration, you must bind your Alibaba Cloud account and complete real-name verification before using API-Inference." (https://modelscope.cn/docs/model-service/API-Inference/intro; binding steps: https://modelscope.cn/docs/accounts/aliyun-binding-and-authorization) 3. Create an access token at https://modelscope.cn/my/myaccesstoken; the token guide (https://modelscope.cn/docs/accounts/token) has you specify a validity period, "Long-term use" or "Short-term use" 4. Free for registered users: "API-Inference is provided free of charge to registered ModelScope users." (intro page); the limits page (https://modelscope.cn/docs/model-service/API-Inference/limits) states that API Inference "implements certain limits on usage quotas and concurrency" 5. Set `MODELSCOPE_API_KEY` in your .env file ### 2. Configure ```bash export MODELSCOPE_API_KEY=your-access-token export MODELSCOPE_MODEL=Qwen/Qwen3.5-35B-A3B # optional — overrides the default model export MODELSCOPE_BASE_URL=https://api-inference.modelscope.cn/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "modelscope", model: "Qwen/Qwen3.5-35B-A3B", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider modelscope ``` Per-request credentials use the same shape as the other catalog providers: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "modelscope", credentials: { modelscope: { apiKey: process.env.MODELSCOPE_API_KEY } }, }); ``` --- ## Billing The entry records `free-tier`. What the vendor's pages say: - Intro page: "API-Inference is provided free of charge to registered ModelScope users." - Limits page (https://modelscope.cn/docs/model-service/API-Inference/limits): "The free inference API is powered by Alibaba Cloud computing resources." and "Your ModelScope account must first be linked to an Alibaba Cloud account." - Limits page: "Please do not use it for online tasks requiring high concurrency or SLA guarantees". It continues "If you have commercial usage requirements, we recommend using APIs from commercial platforms." - Limits page: "The allowed concurrency for different models will be dynamically rate-limited according to platform load" - Limits page: "API Inference calls can be redeemed by magicubes." with three cost tiers, "Lightweight models: ~0.5 Magicubes per call", "Standard models: ~1 Magicube per call" and "Flagship models: ~2 Magicubes per call". - Magicube page (https://modelscope.cn/docs/magicube/intro): Magicubes can be redeemed for "Civision inference, Civision training, and API Inference services". Its earning table lists "Daily Login Bonus" (action "Sign in", reward "200 Magicubes/day") and "Account Linking Bonus" (action "Link Alibaba Cloud account", reward "50 Magicubes/day"). --- ## Models | Model | `vision` | Notes | | --------------------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Qwen/Qwen3.5-35B-A3B` ⭐ | true | NeuroLink default. The id used in the intro page's chat, Anthropic-compatible and Vision Models examples; `models.visionModel`. | | `Qwen/Qwen3.5-27B` | true | Fallback. Named in the Chinese intro page's Responses API example and in the LangChain integration page's examples (https://modelscope.cn/docs/ecosystem-integrations/api-usage/langchain). The intro page says "integrated models like Qwen3.5 that support vision". Model API task: `image-text-to-text`. | | `deepseek-ai/DeepSeek-V4-Pro-0813` | false | Fallback. Listed on the roster. Model API task: `text-generation`. | | `ZhipuAI/GLM-5.2` | false | Fallback. Listed on the roster. Model API task: `text-generation`. | | `Qwen/Qwen3.5-397B-A17B` | true | Listed on the roster. The intro page says "integrated models like Qwen3.5 that support vision". Model API task: `image-text-to-text`. | | `Qwen/Qwen3.5-122B-A10B` | true | Listed on the roster. The intro page says "integrated models like Qwen3.5 that support vision". Model API task: `image-text-to-text`. | | `deepseek-ai/DeepSeek-V4-Flash-0731` | false | Listed on the roster. Model API task: `text-generation`. | | `MiniMax/MiniMax-M3` | true | Listed on the roster. Model API task: `image-text-to-text`. | | `stepfun-ai/Step-3.7-Flash` | true | Listed on the roster. Model API task: `image-text-to-text`. | | `Qwen/Qwen3.8-27B` | true | Listed on the roster. Model API task: `image-text-to-text`. | | `mistralai/Mistral-Large-Instruct-2407` | false | Listed on the roster. Model API task: `text-generation`. | | `Qwen/Qwen3.8-Flash-Next` | true | Listed on the roster. Model API task: `image-text-to-text`. | The ids come from an unauthenticated `GET https://api-inference.modelscope.cn/v1/models` call made 2026-09-29 (HTTP 200, 35 models; 12 of them are in this catalog). Each roster entry has the fields `id`, `object` (an empty string), `owned_by` (`system`) and `created`. "Model API task" is the `Data.Tasks` field of an unauthenticated `GET https://www.modelscope.cn/api/v1/models/` made 2026-09-29. The catalog does not set a per-model context window, output limit or price. `models.defaultContextWindow` (32,768) and `models.defaultMaxOutputTokens` (4,096) are placeholders. **Fallback order** when the default is unavailable: `Qwen/Qwen3.5-27B` → `deepseek-ai/DeepSeek-V4-Pro-0813` → `ZhipuAI/GLM-5.2`. The runtime fallback model name (`models.fallbackModelName`) is `Qwen/Qwen3.5-27B`. **Vision:** `vision: true` is set for `Qwen/Qwen3.5-35B-A3B`, the id the intro page's Vision Models example calls with an `image_url` content part, for the other Qwen3.5 ids on the basis of the intro page sentence quoted in the table, and for `Qwen/Qwen3.8-27B`, `Qwen/Qwen3.8-Flash-Next`, `MiniMax/MiniMax-M3` and `stepfun-ai/Step-3.7-Flash` on the basis of their model API task, `image-text-to-text`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for ModelScope — **docs- and roster-verified, not live-verified**: | Probe | Result | | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /v1/models`, HTTP 200, 35 models, 2026-09-29 — no key used | | Billing | intro page: "API-Inference is provided free of charge to registered ModelScope users."; limits page: "free of charge", 2026-09-29 | | Auth-failure shape | unauthenticated `GET /v1/tasks/abc` (the AIGC task-polling route used in the intro page's example) answered HTTP 401 with the JSON body `{"errors":{"message":"Authentication failed, please make sure that a valid ModelScope token is supplied."},"request_id":"..."}`; an unauthenticated `GET /v1/chat/completions` answered HTTP 404 with the plain-text body `404 page not found`, 2026-09-29. `errorRules` holds one rule, status `401` → authentication | | Capabilities | `text` and `streaming` come from the intro page's chat example with `stream=True`; `thinking` is `true` on the basis of the Codewhale integration page sentence quoted under Key Facts; `tools`, `structuredOutput` and `embeddings` are `false`; no combined tools+schema request was sent, so `structuredOutputWithTools` is `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=modelscope` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting Each row is a statement from a ModelScope page, quoted from the docs text described at the top of this page. | Situation | What the vendor says | Page | | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | | Newly registered account | "After account registration, you must bind your Alibaba Cloud account and complete real-name verification before using API-Inference." | intro | | A model id is no longer served | "Over time, as new models are launched, older models may be deprecated and no longer supported. To ensure your API calls work properly, please configure a currently supported model ID." | intro | | A model id is no longer served | "As new models are released, older models may gradually be removed from API Inference." | limits | | Reasoning models | "Please refer to the API-Inference sample code on the model page as the authoritative source", "especially for reasoning models, as their calling methods may have subtle differences from standard LLMs" | intro | | Concurrency or quota limits | "The allowed concurrency for different models will be dynamically rate-limited according to platform load" | limits | | Production traffic with concurrency needs | "Please do not use it for online tasks requiring high concurrency or SLA guarantees" | limits | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Moonshot AI (Kimi) Provider Guide # Moonshot AI (Kimi) Provider Guide Moonshot AI's Kimi API is a **Tier-2 catalog provider**: OpenAI-wire-compatible, so its integration is one JSON file (`src/lib/providers/catalog/moonshot-ai.json`) rather than hand-written code. That file is the source of truth for everything on this page. The one behavioural setting it carries is the `replayReasoningContent` quirk, explained under [Key Facts](#key-facts). > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** The vendor's `GET /v1/models` needs a key (an unauthenticated > GET answers HTTP 401), so the model ids come from the vendor's public docs at > https://platform.kimi.ai/docs/models and the roster has not been checked. > `evidence.liveMatrix` is `null` until someone runs the live capability matrix > with a real key (see [Verification status](#verification-status) below). No > account was created and no API key was used to build this entry. ## Quick Start ### 1. Get an API key 1. Visit: https://platform.kimi.ai/console/api-keys and sign in, then create and copy an API key (https://platform.kimi.ai/docs/overview describes signing in to the Kimi API Platform and creating a key under API Keys) 2. Create the key on platform.kimi.ai: the errors page states that keys issued on platform.kimi.ai are independent from keys issued on other regional Kimi platforms, and that "Mixing keys across platforms returns 401." (https://platform.kimi.ai/docs/api/errors) 3. Top up before use: "To prevent abuse, you need to recharge at least $1 to start using, and when your cumulative recharge reaches $5, you will receive a $5 voucher." (https://platform.kimi.ai/docs/pricing/limits); the Kimi K3 page states "Kimi K3 is a flagship model: it is unlocked after a successful top-up (minimum $1)." (https://platform.kimi.ai/docs/guide/kimi-k3-quickstart) 4. Set `MOONSHOT_AI_API_KEY` in your .env file (`MOONSHOT_API_KEY`, the variable Kimi's own docs use, is also read) ### 2. Configure ```bash export MOONSHOT_AI_API_KEY=your-api-key export MOONSHOT_AI_MODEL=kimi-k3 # optional — overrides the default model export MOONSHOT_AI_BASE_URL=https://api.moonshot.ai/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "moonshot-ai", model: "kimi-k3", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider moonshot-ai ``` Per-request credentials work as they do for the other catalog providers: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "moonshot-ai", credentials: { moonshotAi: { apiKey: process.env.MOONSHOT_AI_API_KEY } }, }); ``` --- ## Billing The [Recharge and Rate Limiting](https://platform.kimi.ai/docs/pricing/limits) page says: "To prevent abuse, you need to recharge at least $1 to start using, and when your cumulative recharge reaches $5, you will receive a $5 voucher." The [Compare with Other Kimi Products](https://platform.kimi.ai/docs/guide/product-plans) page describes the Kimi API Open Platform as "pay-as-you-go billing with no subscription plan"; the Troubleshooting page repeats "pay-as-you-go with no subscription plan". The entry records `no-free-tier`. The [Troubleshooting](https://platform.kimi.ai/docs/guide/troubleshooting) page also answers "Can I try the models before topping up?" with "You can run a minimal test in the Playground to confirm whether a model and prompt fit your scenario". The limits page lists rate limits by cumulative recharge amount. Tier0 (cumulative recharge $1) is listed as concurrency 1, RPM 3, TPM 500,000 and TPD 1,500,000. --- ## Models | Model | Context | Vision | $/M in · out (cached) | Notes | | -------------------------- | --------- | ------ | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `kimi-k3` ⭐ | 1,048,576 | yes | $3.00 / $15.00 (cached $0.30) | NeuroLink default. Model List: "Kimi's most capable model to date". Cache write $3.00 (TTL 5min) or $6.00 (TTL 1h). "K3 always has thinking mode enabled". | | `kimi-k2.7-code` | 262,144 | yes | $0.95 / $4.00 (cached $0.19) | Fallback. Model List: "Kimi's dedicated coding model." "Kimi K2.7 Code does not support non-thinking mode." | | `kimi-k2.7-code-highspeed` | 262,144 | yes | $1.90 / $8.00 (cached $0.38) | Fallback. Model List: "High-Speed version of Kimi K2.7 Code model, with output speed of approximately 180 Tokens/s and up to 260 Tokens/s in short context scenarios". "the same model as Kimi K2.7 Code". Same page: "(Currently, the resource is limited, and the experience of the high-speed model may be slightly fluctuate,we are gradually increasing the resource.)" | | `kimi-k2.6` | 262,144 | yes | $0.95 / $4.00 (cached $0.16) | Fallback. Model List: "Supports both visual and text input, thinking and non-thinking modes, and dialogue and Agent tasks." "thinking is on by default, can be disabled". response_format guide: "kimi-k2.6 occasionally behaves unstably with complex schemas; for example, $ref may return a Markdown code block, oneOf may be ignored, and partial=true may output fields outside the schema." | Context windows and prices come from the [pricing page](https://platform.kimi.ai/docs/pricing/chat), retrieved 2026-09-29. Its K3 table columns are "Cached Input Price", "Input Price" and "Output Price"; its K2 table columns are "Input Price (Cache Hit)", "Input Price (Cache Miss)" and "Output Price". The catalog records the cache-hit price as `cachedInput` and the cache-miss price as `input`. Prices are per 1M tokens and "exclude applicable taxes". `vision: true` for the four models comes from the [vision guide](https://platform.kimi.ai/docs/guide/use-kimi-vision-model), which names `kimi-k3`, `kimi-k2.6`, `kimi-k2.7-code` and `kimi-k2.7-code-highspeed` in its description of the Kimi Vision Model. It also states that for K3 "Vision input does not support public image URLs. Use base64 or `ms://`" ([Kimi K3 page](https://platform.kimi.ai/docs/guide/kimi-k3-quickstart)). Output limits stated by the vendor: for `kimi-k3`, `max_completion_tokens` "defaults to 131072 and can be set up to 1048576" ([Kimi K3 page](https://platform.kimi.ai/docs/guide/kimi-k3-quickstart)); the [Troubleshooting](https://platform.kimi.ai/docs/guide/troubleshooting) page gives "the maximum output length is `1024*1024 - prompt_tokens`" for `kimi-k3` and "the maximum output length is `256*1024 - prompt_tokens`" for `kimi-k2.7-code` and `kimi-k2.6`. No per-model `maxOutputTokens` is recorded in the catalog. `models.defaultContextWindow` (262,144) and `models.defaultMaxOutputTokens` (131,072) apply to model ids outside the catalog and are placeholders: 262,144 is the context window the pricing page lists for `kimi-k2.7-code`, `kimi-k2.7-code-highspeed` and `kimi-k2.6`, and 131,072 is the `max_completion_tokens` default the vendor states for `kimi-k3`. The vendor publishes no figure for such ids. The Model List's Deprecated Models section names `kimi-k2.5`, the `moonshot-v1` series, the `kimi-k2` series, `kimi-latest` and `kimi-thinking-preview`; they are not in the catalog. **Fixed sampling parameters:** the [parameter reference](https://platform.kimi.ai/docs/api/models-overview) lists `temperature`, `top_p`, `n`, `presence_penalty` and `frequency_penalty` as "Cannot be modified" for `kimi-k3`, `kimi-k2.7-code` and `kimi-k2.6`, and states that "Fixed" means "the parameter cannot be modified: passing any other value returns an error, so do not pass it explicitly." **Fallback order** when the default is unavailable: `kimi-k2.7-code` → `kimi-k2.6` → `kimi-k2.7-code-highspeed`. The order is the catalog's own choice. The runtime fallback model name the loader derives (`fallbacks[1]`) is `kimi-k2.6`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Moonshot AI — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://api.moonshot.ai/v1/models` answered HTTP 401 on 2026-09-29, so the roster was not read; the four model ids come from https://platform.kimi.ai/docs/models (retrieved 2026-09-29) and match the chat request schema in https://platform.kimi.ai/docs/openapi.json | | Auth-failure shape | the same unauthenticated GET returned HTTP 401 with body `{"error":{"message":"Incorrect API key provided","type":"incorrect_api_key_error"}}` (no `error.code` field); the [errors page](https://platform.kimi.ai/docs/api/errors) lists `incorrect_api_key_error` — "Incorrect API key provided" under 401. No key was used | | Billing | the [limits page](https://platform.kimi.ai/docs/pricing/limits) says "you need to recharge at least $1 to start using" — see [Billing](#billing), 2026-09-29 | | Tools / structured output | documented on the tool-calls and response_format guides linked above; the tool-calling and structured-output paths were not exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=moonshot-ai` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting The rows restate what the vendor's [errors page](https://platform.kimi.ai/docs/api/errors) or [Troubleshooting](https://platform.kimi.ai/docs/guide/troubleshooting) page says. | Symptom | Cause (vendor wording) | Fix (vendor wording) | | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | | HTTP 401 `incorrect_api_key_error` | "The API key was not provided, or the key is incorrect." | "Make sure the endpoint matches the platform where the key was created." | | HTTP 404 `resource_not_found_error` | "Model not found, or this account does not have permission to access the model" | "Check the spelling of the `model` parameter and the account tier." | | HTTP 429 `engine_overloaded_error` | "The service node is under high load (for example, peak-hour capacity pressure)." | "Wait as indicated by `Retry-After`, reduce concurrency, and retry with exponential backoff." | | HTTP 429 `rate_limit_reached_error` | "an organization-level concurrency, RPM, TPM, or TPD limit was reached" | "Reduce request frequency, or see Top-up and Rate Limits to upgrade your tier" | | HTTP 429 `exceeded_current_quota_error` | "insufficient balance, an overdue account, or an expired voucher" | "Check `available_balance` with the balance API and top up." | | HTTP 504 on a long non-streaming request | "No response from the server for 900 seconds; the gateway returns an HTML timeout page." | "Use streaming output (`stream: true`)." | | `finish_reason` is `length` | "the number of tokens generated by the current model exceeded the `max_completion_tokens` parameter" | "we recommend increasing `max_completion_tokens` appropriately" | | Error after passing `temperature` or `top_p` | "passing any other value returns an error" | "do not pass it explicitly" | | Error after passing `tool_choice: required` to K2.x | "These models do not support `required` and return an error if it is passed" | "only `kimi-k3` supports it" | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Morph Provider Guide # Morph Provider Guide Morph is a **Tier-2 catalog provider**: OpenAI-wire-compatible with one documented quirk, so its entire integration is one JSON file (`src/lib/providers/catalog/morph.json`) rather than hand-written code. That file is the source of truth for everything on this page. ## Quick Start ### 1. Get an API key 1. Visit: https://morphllm.com/dashboard and sign in 2. Add a payment method (required to lift the 5 req/min limit) 3. Generate an API key from the dashboard 4. Set `MORPH_API_KEY` in your .env file ### 2. Configure ```bash export MORPH_API_KEY=your-api-key export MORPH_MODEL=morph-v3-large # optional — overrides the default model export MORPH_BASE_URL=https://api.morphllm.com/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Summarize the following diff." }, provider: "morph", model: "morph-v3-large", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider morph ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "morph", credentials: { morph: { apiKey: process.env.MORPH_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ------------------- | ------- | ------ | ------------ | ---------------------------------------------------------------------------------------------------------------------------- | | `morph-v3-large` ⭐ | 262K | no | $0.9 / $1.9 | Recommended default; a "Fast Apply" code-editing model. Emits tool-call syntax as literal text rather than a real tool call. | | `morph-v3-fast` | 262K | no | $0.8 / $1.2 | Faster/cheaper sibling; silently ignores the `tools` parameter if one is sent. | Both models share a 262,144-token context window and a 131,072-token max output, per the catalog default. **Fallback order** when the default is unavailable: `morph-v3-fast`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for Morph: | Probe | Result | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | authenticated GET /v1/models, HTTP 200, 2026-09-05 | | Auth rejection | HTTP 401, 2026-09-05 | | Live capability sweep | 2026-09-05, probed against both models. Plain chat and streaming worked on each. Sending OpenAI's content-parts array format returned HTTP 500 (confirming the need for `messageContentFormat: "string"`). Tool-call requests did not produce a real tool call on either model — `morph-v3-large` echoed `` syntax as text content, `morph-v3-fast` returned a normal text answer as if no `tools` had been sent. `response_format: json_object` succeeded on both models. | --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `Invalid Morph API key` | `MORPH_API_KEY` unset or wrong | Check the key at https://morphllm.com/dashboard | | Tools silently absent or echoed as text | Morph declares `tools: false` and doesn't honor the parameter | Use a tool-capable provider for agentic work — see [provider feature compatibility](/docs/reference/provider-feature-compatibility) | | Stuck at 5 requests/minute | No payment method on file yet | Add a card in the [Morph dashboard](https://morphllm.com/dashboard) to lift the limit | | Model not found | The roster changed since 2026-09-05 | Use `morph-v3-large` or `morph-v3-fast` — Morph's catalog only lists these two | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how quirks like `messageContentFormat` work - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## MuseTalk Provider Guide (avatar via Replicate) # MuseTalk Provider Guide **Lip-synced avatar videos via the MuseTalk model on Replicate** ## Quick Start ### 1. Get a Replicate Token [https://replicate.com/account/api-tokens](https://replicate.com/account/api-tokens) ### 2. Configure ```bash REPLICATE_API_TOKEN=r8_your-token ``` ### 3. Generate ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "vertex", output: { mode: "avatar", avatar: { provider: "musetalk", // routes to Replicate-hosted MuseTalk image: readFileSync("./portrait.jpg"), audio: readFileSync("./narration.mp3"), }, }, }); if (result.avatar?.buffer) { writeFileSync("./avatar.mp4", result.avatar.buffer); } ``` --- ## CLI Usage ```bash pnpm run cli generate "" \ --provider musetalk \ --avatarImage ./portrait.jpg \ --avatarAudio ./narration.mp3 \ --avatarOutput ./avatar.mp4 ``` --- ## Configuration Reference | Environment Variable | Required | Description | | --------------------- | -------- | ------------------------ | | `REPLICATE_API_TOKEN` | Yes | Replicate token (shared) | --- ## See Also - [HeyGen Provider](/docs/getting-started/providers/heygen) - [D-ID Provider](/docs/getting-started/providers/d-id) - [Replicate Provider](/docs/getting-started/providers/replicate) --- ## Nebius Token Factory Provider Guide # Nebius Token Factory Provider Guide Nebius Token Factory is a **Tier-2 catalog provider**: OpenAI-wire-compatible, with no catalog quirks set, so its entire integration is one JSON file (`src/lib/providers/catalog/nebius.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs-verified, not yet > live-verified.** The vendor's `GET /v1/models` needs a key (an unauthenticated > request answers HTTP 401), so the model ids come from the vendor's public model > catalog and the roster has not been checked against the API. No account was > created and no API key was used to build it. `evidence.liveMatrix` is `null` > until someone runs the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://tokenfactory.nebius.com/ and create an account; the quickstart (https://docs.tokenfactory.nebius.com/quickstart) says: "Log in using your Google or GitHub account" 2. Create an API key (https://docs.tokenfactory.nebius.com/api-reference/introduction#authentication): go to the API keys section, click Create API key, enter the key name, click Create, and save the displayed key — "Save the displayed API key. You cannot open it later in Nebius Token Factory." 3. Billing (https://docs.tokenfactory.nebius.com/other-capabilities/billing-new): "Billing setup is mandatory—you cannot complete onboarding without it." "Setting up a billing account requires a bank card." "Upon first sign-up, you receive $1 in trial credit, valid for 30 days." 4. Set `NEBIUS_API_KEY` in your .env file (the vendor's docs read NEBIUS_API_KEY) ### 2. Configure ```bash export NEBIUS_API_KEY=your-api-key export NEBIUS_MODEL=Qwen/Qwen3-235B-A22B-Instruct-2507 # optional — overrides the default model export NEBIUS_BASE_URL=https://api.tokenfactory.nebius.com/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "nebius", model: "Qwen/Qwen3-235B-A22B-Instruct-2507", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider nebius ``` Per-request credentials: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "nebius", credentials: { nebius: { apiKey: process.env.NEBIUS_API_KEY } }, }); ``` --- ## Models | Model | Context (`max_model_len`) | Vision | Price per M tokens, in / out | Notes | | --------------------------------------- | ------------------------- | ------ | ---------------------------- | ---------------------------------------------------------------------- | | `Qwen/Qwen3-235B-A22B-Instruct-2507` ⭐ | 262,144 | no | 0.2 / 0.6 | NeuroLink default; `JSON mode` tag; `function_calling` in `use_cases`. | | `deepseek-ai/DeepSeek-V4-Flash-0731` | 1,024,000 | no | 0.14 / 0.28 | Fallback; `JSON mode` tag; `function_calling` in `use_cases`. | | `openai/gpt-oss-120b` | 131,072 | no | 0.15 / 0.6 | Fallback; `JSON mode` tag; `function_calling` in `use_cases`. | | `Qwen/Qwen3-30B-A3B-Instruct-2507` | 262,144 | no | 0.1 / 0.3 | Fallback; `JSON mode` tag; `function_calling` in `use_cases`. | | `NousResearch/Hermes-4-405B` | 131,072 | no | 1 / 3 | Fallback; `JSON mode` tag; `function_calling` in `use_cases`. | | `nvidia/Nemotron-3_5-Lightning` | 1,048,576 | no | 0.06 / 0.24 | `function_calling` in `use_cases`. | | `openbmb/MiniCPM-V-4_5` | 32,000 | yes | 0.658 / 1.11 | `JSON mode` tag; catalog type `image2text`; `models.visionModel`. | Model ids, context lengths and prices come from the vendor's public model catalog, retrieved 2026-09-29: [`/api/public/models_info`](https://tokenfactory.nebius.com/api/public/models_info) (its Markdown view is at [`/model-catalog.md`](https://tokenfactory.nebius.com/model-catalog.md), which says "The JSON endpoint is the authoritative machine-readable source"). Context is each model's `max_model_len`; the catalog also gives a rounded `context_window_k`. Prices are the catalog's `input_price_per_million_tokens` and `output_price_per_million_tokens` values, copied as published. The catalog's `status: active` is recorded here as `production`. The default and the four fallbacks are the models in this entry whose catalog record carries both the `JSON mode` tag and `function_calling` in `use_cases`; the other two follow in `topModels`. **Vendor descriptions** (the public model catalog's `description` field, quoted): - `Qwen/Qwen3-235B-A22B-Instruct-2507` — "Balanced Qwen3 flagship tuned for strong general reasoning, chat quality, and tool use." - `deepseek-ai/DeepSeek-V4-Flash-0731` — "DeepSeek V4 Flash 0731 is a 1M-context reasoning model designed for coding and agentic workloads." - `openai/gpt-oss-120b` — "Open-weight agentic model with configurable reasoning, full CoT visibility, strong tool use, and fine-tuning support." - `Qwen/Qwen3-30B-A3B-Instruct-2507` — "Versatile 30B instruct model optimized for high-quality chat, reasoning, and coding." - `NousResearch/Hermes-4-405B` — "Hybrid-reasoning model trained on verified CoT traces for strong math, coding, and step-by-step reliability." - `nvidia/Nemotron-3_5-Lightning` — "NVIDIA's 30B-parameter hybrid MoE model with 3B active parameters per token, designed for efficient agentic reasoning, tool use, coding, and long-context workflows." - `openbmb/MiniCPM-V-4_5` — "MiniCPM-V-4.5 – Compact multimodal model for image, multi-image, high-FPS/long-video, OCR/PDF understanding, with switchable fast/deep thinking." `models.defaultMaxOutputTokens` (8,192) is the value the chat completion reference gives for an omitted `max_tokens`: "If omitted or set to null, defaults to 8192 tokens." `models.defaultContextWindow` (32,000) is a placeholder the vendor does not publish. The [inference overview](https://docs.tokenfactory.nebius.com/ai-models-inference/overview) describes two model flavors, Base and Fast, and says: "To use the Fast flavor, append `-fast` to the model name in the API." The ids in this entry are the ones in the public model catalog's `flavors[].model_id`. Code samples in the docs name other ids, for example `deepseek-ai/DeepSeek-R1-0528` on the quickstart and `meta-llama/Meta-Llama-3.1-70B-Instruct` on the API introduction. Nebius records serverless model removals in its [June 2026](https://docs.tokenfactory.nebius.com/june-2026-deprecation-notice) and [August 2026](https://docs.tokenfactory.nebius.com/august-2026-deprecation-notice) deprecation notices, both of which say "Token Factory does not automatically reroute requests from deprecated models." The August notice lists `deepseek-ai/DeepSeek-V4-Flash-0731` and `nvidia/Nemotron-3_5-Lightning` in its "Recommended Replacement" column. **Fallback order** when the default is unavailable: `deepseek-ai/DeepSeek-V4-Flash-0731` → `openai/gpt-oss-120b` → `Qwen/Qwen3-30B-A3B-Instruct-2507` → `NousResearch/Hermes-4-405B`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `openai/gpt-oss-120b`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Nebius Token Factory — **docs-verified, not live-verified**: | Probe | Result | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /v1/models` answered HTTP 401 with `{"detail":"Couldn't authenticate. Reason: token is not present"}`, 2026-09-29 — no key used. Model ids are taken from the public model catalog (`/api/public/models_info`), so the roster is not verified against the API | | Chat endpoint | unauthenticated `GET /v1/chat/completions` answered HTTP 405 with `allow: POST` and `{"detail":"Method Not Allowed"}`, 2026-09-29; no POST was sent | | Billing | the [billing page](https://docs.tokenfactory.nebius.com/other-capabilities/billing-new) states a bank card is required to set up a billing account and a $1 trial credit valid for 30 days on first sign-up, 2026-09-29 | | Error shapes | statuses and example bodies from the [chat completion reference](https://docs.tokenfactory.nebius.com/api-reference/inference/create-chat-completion): 401 `Couldn't authenticate. Reason: token is not present`, 402 `Payment Required: You have exhausted your budget. Please add funds to continue using the API.`, 404 ``The model `unknown-model` does not exist.``, 429 (response description "Rate limit exceeded"). `errorRules` match the status codes `401`, `402`, `404` and `429`; the 429 rule points to the `Retry-After` header on the rate-limits page | | Tools / structured output | documented on the function-calling and structured-output pages; neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false`. The chat completion reference's `response_format` description reads `Only {'type': 'json_object'} or {'type': 'text' } is supported.`, while its `ResponseFormat` schema lists `text`, `json_object` and `json_schema` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=nebius` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting Each row uses a status and body the vendor's chat completion reference shows, or a statement from a vendor page named in the row. | Symptom | Cause | Fix | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | HTTP 401 | The reference's 401 example body is `Couldn't authenticate. Reason: token is not present` | The API introduction says to include the key in the `Authorization: Bearer` header; NeuroLink sends `NEBIUS_API_KEY` that way | | HTTP 402 | The reference's 402 example body is `Payment Required: You have exhausted your budget. Please add funds to continue using the API.` | Add funds — see "Topping up your balance" on the [billing page](https://docs.tokenfactory.nebius.com/other-capabilities/billing-new) | | HTTP 404 | The reference's 404 example body is ``The model `unknown-model` does not exist.`` | Take the id from the [public model catalog](https://tokenfactory.nebius.com/model-catalog.md) | | HTTP 429 | The [rate-limits page](https://docs.tokenfactory.nebius.com/ai-models-inference/rate-limits) says "If you exceed the active limit you will receive HTTP 429." | The same page describes the `Retry-After` header as "The time in seconds to wait before making another request if the rate limit is exceeded." | | Structured output ignored with tools attached | `structuredOutputWithTools` is `false` on this entry — untested combination | NeuroLink omits `response_format` automatically whenever tools are present, before sending | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Neuralwatt Provider Guide # Neuralwatt Provider Guide Neuralwatt is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/neuralwatt.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status**: this entry is **docs- and roster-verified, not yet > live-verified**. It was onboarded credential-free — no API key was created, > no signup was completed, and no authenticated or `POST` request was sent to > Neuralwatt. Everything below comes from Neuralwatt's public documentation > (`docs.neuralwatt.com`) and an unauthenticated `GET /v1/models` call. See > [Live verification](#live-verification-still-needed) for what a follow-up > pass with a real key still needs to confirm. ## Quick Start ### 1. Get an API key 1. Visit: https://portal.neuralwatt.com and sign up 2. Add a payment method in **Dashboard > Billing** — new accounts start with a $0 balance, and adding a card grants $1.00 in free trial credit (no charge is made; the credit is valid for 30 days) 3. Navigate to **Dashboard > API Keys** and create a new key — copy it immediately, it is shown in full only once and starts with `sk-` 4. Set `NEURALWATT_API_KEY` in your `.env` file ### 2. Configure ```bash export NEURALWATT_API_KEY=your-api-key export NEURALWATT_MODEL=glm-5.3 # optional — overrides the default model export NEURALWATT_BASE_URL=https://api.neuralwatt.com/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "neuralwatt", model: "glm-5.3", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider neuralwatt ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "neuralwatt", credentials: { neuralwatt: { apiKey: process.env.NEURALWATT_API_KEY } }, }); ``` --- ## Models | Model | Context | Max output | Vision | $/M in · out · cached | Notes | | --------------------- | ------- | ---------- | ------ | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `glm-5.3` ⭐ | 1M | — | no | $1.45 / $4.50 / $0.145 | ZhipuAI GLM 5.3 — used in every quickstart code sample; reasoning is mandatory on this model (default effort `max`). Max output tokens undocumented for this model on the roster. | | `glm-5.3-flash` | 1M | — | yes | $0.15 / $0.50 / $0.03 | Lighter/cheaper GLM 5.3 sibling; roster-listed only; fallback. | | `qwen-3.8-27b` | 262K | 131,072 | yes | $0.45 / $3.20 / $0.25 | Dense 27B VL model; first entry on the live roster; used as `models.visionModel` (documented image limits: 20 images/request, 200 total). | | `qwen3.6-35b` | 262K | — | yes | $0.29 / $1.15 / $0.029 | Roster-listed only; fallback. | | `kimi-k2.7-code` | 262K | — | yes | $0.95 / $4.00 / $0.095 | MoonshotAI's code-oriented Kimi model; roster-listed only; fallback. | | `kimi-k3` | 1M | — | yes | $3.00 / $15.00 / $0.30 | MoonshotAI's general-purpose Kimi model; roster-listed only; fallback. | | `deepseek-v4.1-flash` | 1M | 393,216 | yes | $0.15 / $0.60 / $0.015 | Roster-listed only; fallback. | | `gemma-4-31b` | 262K | 16,384 | yes | $0.144 / $0.42 / $0.0144 | NVIDIA-owned Gemma 4 31B build; roster-listed only; fallback. | Context window shown is each model's own `max_context_length` from the live roster; the catalog's provider-wide `defaultContextWindow` (1,048,560) and `defaultMaxOutputTokens` (4,096) apply to any model that doesn't declare its own value — 4,096 is a **generic placeholder**, not a Neuralwatt-documented ceiling, since `glm-5.3` (the default model) has no `max_output_tokens` in its own roster entry. The live roster carries **21** models in total (Qwen, MoonshotAI Kimi, ZhipuAI GLM, DeepSeek and an NVIDIA Gemma build); this catalog curates 8 — one representative per non-`-flex`/non-`-fast` pricing tier per model family. The `-flex` (discounted async) and `-fast` (lower-latency) pricing variants seen on the roster (e.g. `glm-5.3-flex`, `qwen3.6-35b-fast`) are not included as separate catalog entries. **Fallback order** when the default is unavailable: `glm-5.3-flash` → `qwen-3.8-27b` → `qwen3.6-35b` → `kimi-k2.7-code` → `kimi-k3` → `deepseek-v4.1-flash` → `gemma-4-31b`. --- ## Live verification (still needed) This entry was onboarded **without credentials**, from Neuralwatt's public documentation and an unauthenticated `GET /v1/models` call only. It is **docs- and roster-verified, not live-verified**. Before treating it as fully proven, a follow-up pass with a real API key should run the Tier-2 live-verification steps ([Tier-2 onboarding: live verification](/docs/provider-integration/tiers/tier-2-catalog-entry#live-verification)): - **Auth rejection** — confirm the documented `401` `{"error":{"message":"Invalid API key","type":"authentication_error","code":"invalid_api_key"}}` shape actually comes back for a bad key. - **Capability probe** — confirm `tools` actually works for `glm-5.3` (and check whether it varies across the roster, per Neuralwatt's own "not all models support tool calling" caveat) before ever promoting `capabilities.tools` off `"model-dependent"`. - **Structured output** — Neuralwatt does not document a `response_format` parameter at all, despite the roster exposing a `json_mode` capability flag. A live probe should establish whether `response_format` is silently accepted, ignored, or rejected before `capabilities.structuredOutput` is ever set to `true`. - **Tools + streaming, tools + structured output** — both undocumented and unprobed; a combined live request is required before setting either to `true`. - **`evidence.liveMatrix`** — currently `null` in the catalog JSON; fill it in once the above is run, per `pnpm run verify:provider-onboarding`. --- ## Verification status This is what the catalog currently records for Neuralwatt: | Probe | Result | | --------------------- | -------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated GET `https://api.neuralwatt.com/v1/models`, HTTP 200, 21 models, 2026-09-28 — credential-free, no key used | | Auth rejection | not attempted — this onboarding sent no authenticated or `POST` request to Neuralwatt | | Live capability sweep | not run (`evidence.liveMatrix: null`) — see [Live verification](#live-verification-still-needed) | --- ## Troubleshooting | Symptom | Cause | Fix | | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `Invalid Neuralwatt API key` | `NEURALWATT_API_KEY` unset or wrong | Check the key in the portal's Dashboard > API Keys at https://portal.neuralwatt.com | | Model not found | The roster changed since 2026-09-28 | Pick a current id from the unauthenticated `GET /v1/models` roster | | Tool calls silently not made | The model doesn't support tool calling (varies per model per Neuralwatt's own docs) | Check the model's `capabilities.tools` on `GET /v1/models` before relying on tool calling on it | | Structured output not honored | `response_format` is undocumented on Neuralwatt's chat-completions endpoint | Don't rely on `response_format`; NeuroLink's `coerceJsonToSchema` repair layer is the fallback for `generate({ schema })` | | Missing energy/cost data in a stream | Comes through as SSE comment lines (`: energy {...}`, `: cost {...}`), which standard SSE/OpenAI-SDK clients drop | Parse the raw stream if you need it; not required for normal generation | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Novita AI Provider Guide # Novita AI Provider Guide Novita AI is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/novita.json`) rather than hand-written code. That file is the source of truth for everything on this page. ## Quick Start ### 1. Get an API key 1. Visit: https://novita.ai/settings/key-management and sign in 2. Generate an API key (it will start with `sk_`) 3. Set `NOVITA_API_KEY` in your .env file ### 2. Configure ```bash export NOVITA_API_KEY=sk_your-api-key export NOVITA_MODEL=zai-org/glm-5.3-flash # optional — overrides the default model export NOVITA_BASE_URL=https://api.novita.ai/openai/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "novita", model: "zai-org/glm-5.3-flash", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider novita ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "novita", credentials: { novita: { apiKey: process.env.NOVITA_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ----------------------------------- | ------- | ------ | ------------------------------ | ------------------------------------------------------------------------------------------------------------- | | `zai-org/glm-5.3-flash` ⭐ | 128K | no | $0.075 / $0.25 (cached $0.015) | Recommended default and test model; reasoning model — check `finish_reason` before trusting a short response. | | `meta-llama/llama-3.3-70b-instruct` | 128K | no | — | Plain instruct chat model; fallback. | | `deepseek/deepseek-v3-0324` | 128K | no | — | Non-reasoning DeepSeek chat model; fallback. | | `qwen/qwen-2.5-72b-instruct` | 128K | no | — | Plain instruct chat model; fallback. | | `google/gemma-3-27b-it` | 128K | no | — | Non-reasoning instruct model; fallback. | Context window shown is the catalog default of 128,000 tokens; the default max output is 4,096 tokens — noticeably smaller than most catalog providers, so raise `maxTokens` explicitly for longer completions or reasoning-heavy prompts on the default model. **Fallback order** when the default is unavailable: `meta-llama/llama-3.3-70b-instruct` → `deepseek/deepseek-v3-0324` → `qwen/qwen-2.5-72b-instruct` → `google/gemma-3-27b-it`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for Novita AI: | Probe | Result | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Roster | authenticated GET /openai/v1/models, HTTP 200, 2026-09-05 | | Auth rejection | HTTP 401 (`FAILED_TO_AUTH`), 2026-09-05 | | Live capability sweep | 2026-09-05, probed against the default model. Chat, streaming, and a real structured tool call all passed. `response_format: json_object` succeeded both alone and combined with `tools` in the same request — confirmed at the SDK level, which is why `structuredOutputWithTools` is `true` for this provider, unlike Friendli or Morph. | --- ## Troubleshooting | Symptom | Cause | Fix | | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | | `FAILED_TO_AUTH` | `NOVITA_API_KEY` unset, wrong, or not `sk_`-prefixed | Rotate the key at https://novita.ai/settings/key-management | | `MODEL_NOT_FOUND` | The roster changed since 2026-09-05 | Pick a current id from https://novita.ai/models or the authenticated `/openai/v1/models` roster | | Truncated or empty content on the default model | `zai-org/glm-5.3-flash` is a reasoning model and the catalog default max output is only 4,096 tokens | Raise `maxTokens` for longer or reasoning-heavy completions | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## NVIDIA NIM Provider Guide # NVIDIA NIM Provider Guide **Hundreds of optimised AI models on NVIDIA's GPU-accelerated inference platform — or your own self-hosted NIM deployment** ## Quick Start ### 1. Get an API Key Sign up at [https://build.nvidia.com](https://build.nvidia.com) and create an API key under [API Keys](https://build.nvidia.com/settings/api-keys). ### 2. Configure Environment Add to your `.env` file: ```bash # Required NVIDIA_NIM_API_KEY=nvapi-... # Optional: override the default model (default: openai/gpt-oss-20b) NVIDIA_NIM_MODEL=openai/gpt-oss-20b # Optional: self-hosted NIM base URL (default: https://integrate.api.nvidia.com/v1) NVIDIA_NIM_BASE_URL=https://integrate.api.nvidia.com/v1 # Optional: NIM-specific generation parameters NVIDIA_NIM_TOP_K=40 NVIDIA_NIM_MIN_P=0.05 NVIDIA_NIM_REPETITION_PENALTY=1.1 NVIDIA_NIM_MIN_TOKENS=1 NVIDIA_NIM_CHAT_TEMPLATE= ``` ### 3. Install NeuroLink ```bash npm install @juspay/neurolink # or pnpm add @juspay/neurolink ``` ### 4. Generate Your First Response ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "nvidia-nim", input: { text: "Explain gradient descent in simple terms." }, }); console.log(result.content); ``` --- ## Supported Models NIM hosts hundreds of models. NeuroLink ships with these popular models pre-enumerated: ### OpenAI gpt-oss (default) | Model ID | Context | Vision | Reasoning | | -------------------- | ------- | ------ | --------- | | `openai/gpt-oss-20b` | 128K | No | Yes | `openai/gpt-oss-20b` always reasons: the trace comes back as `reasoning_content` whether or not you pass a thinking option, and it counts against `maxTokens`. See [Reasoning and `thinkingLevel`](#reasoning-and-thinkinglevel). ### Meta Llama | Model ID | Context | Vision | Reasoning | | ------------------------------------ | ------- | ------ | --------- | | `meta/llama-3.3-70b-instruct` | 128K | No | No | | `meta/llama-3.1-405b-instruct` | 128K | No | No | | `meta/llama-3.1-70b-instruct` | 128K | No | No | | `meta/llama-3.2-90b-vision-instruct` | 128K | Yes | No | | `meta/llama-3.2-11b-vision-instruct` | 128K | Yes | No | ### NVIDIA Nemotron (Reasoning) | Model ID | Context | Vision | Reasoning | | ---------------------------------------- | ------- | ------ | --------- | | `nvidia/llama-3.3-nemotron-super-49b-v1` | 128K | No | Yes | | `nvidia/llama-3.1-nemotron-nano-8b-v1` | 128K | No | Yes | | `nvidia/llama-3.1-nemotron-70b-instruct` | 128K | No | Yes | ### DeepSeek (Hosted on NIM) | Model ID | Context | Vision | Reasoning | | ------------------------------------------- | ------- | ------ | --------- | | `deepseek-ai/deepseek-r1` | 128K | No | Yes | | `deepseek-ai/deepseek-r1-distill-llama-70b` | 128K | No | Yes | ### Other Models | Model ID | Context | Notes | | --------------------------------------- | ------- | ---------------- | | `mistralai/mixtral-8x22b-instruct-v0.1` | 64K | Large MoE | | `mistralai/mixtral-8x7b-instruct-v0.1` | 32K | Efficient MoE | | `microsoft/phi-4` | 16K | Compact, capable | | `google/gemma-3-27b-it` | 128K | Google Gemma | > **Availability, checked 2026-10-24.** NVIDIA's `GET https://integrate.api.nvidia.com/v1/models` lists `openai/gpt-oss-20b`, `meta/llama-3.2-90b-vision-instruct`, `meta/llama-3.2-11b-vision-instruct` and `nvidia/llama-3.1-nemotron-70b-instruct` from the tables above, and none of the others. A chat request to `meta/llama-3.3-70b-instruct` or `meta/llama-3.1-70b-instruct` answers HTTP 410, "has reached its end of life on 2026-08-26T09:00:00Z and is no longer available"; `nvidia/llama-3.3-nemotron-super-49b-v1` and `mistralai/mixtral-8x22b-instruct-v0.1` also answer 410, and `deepseek-ai/deepseek-r1` and `meta/llama-3.1-405b-instruct` answer 404. `nvidia/llama-3.1-nemotron-70b-instruct` is listed but answered 404 ("not found for account") to the key used for the check. `openai/gpt-oss-20b` and `meta/llama-3.2-11b-vision-instruct` each answered a plain request and a tool-calling request. The `NvidiaNimModels` enum keeps the retired members so existing code compiles. Browse the full catalog at [https://build.nvidia.com/models](https://build.nvidia.com/models). You can pass any model ID via `--model` or `model:` — NIM returns 404 for IDs that are not in the catalog. --- ## SDK Usage ### Basic Generation ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "nvidia-nim", input: { text: "Write a TypeScript utility to deep-clone a plain object." }, }); console.log(result.content); ``` ### Using a Specific Model ```typescript const result = await ai.generate({ provider: "nvidia-nim", model: "mistralai/mixtral-8x22b-instruct-v0.1", input: { text: "Summarise the key ideas in the CAP theorem." }, }); ``` ### Reasoning and `thinkingLevel` Two separate questions decide what you get: 1. **Does the model reason?** That is a property of the model. `openai/gpt-oss-20b`, the default, reasons on every request: NIM returns the trace as `reasoning_content` and NeuroLink exposes it as `result.reasoning` (and as reasoning chunks when streaming). No option is needed to turn it on. 2. **Can NeuroLink switch it on or tune it?** That is a property of the provider code, and on NIM it is narrower than the `thinkingLevel` type suggests: - `thinkingLevel` is honoured on `stream()` only. Any level other than `minimal` adds `chat_template_kwargs: { thinking: true, enable_thinking: true, reasoning_budget: }` to the request. `generate()` does not forward it: the request body carries no `chat_template_kwargs`. - The three active levels are not distinguished. `low`, `medium` and `high` send the same flags, so `thinkingLevel` is an on/off switch here, with `minimal` meaning off. - NeuroLink never sends `reasoning_effort` to NIM, so that knob is not available through it. - An HTTP 400 that names `reasoning_budget` or `chat_template` gets one automatic retry without that field. A 400 about the other thinking flags (`thinking`, `enable_thinking`) is not retried and is returned to you. ```typescript // The trace is there without any thinking option. const result = await ai.generate({ provider: "nvidia-nim", model: "openai/gpt-oss-20b", input: { text: "What is 17 * 23? Answer with just the number." }, maxTokens: 512, }); console.log(result.reasoning); // the model's reasoning trace console.log(result.content); // the answer ``` Reasoning tokens count toward `maxTokens`. With a small budget the model can spend all of it reasoning and stop with `finish_reason: "length"` and an empty `content`. On `openai/gpt-oss-20b`, `maxTokens: 16` returned an empty answer for a one-word reply, while 64 and 256 returned it. Leave a few hundred tokens of headroom for short answers, more for hard prompts. ### Streaming ```typescript const ai = new NeuroLink(); const stream = await ai.stream({ provider: "nvidia-nim", model: "openai/gpt-oss-20b", input: { text: "Walk me through building a REST API with Hono and TypeScript.", }, }); for await (const chunk of stream.stream) { process.stdout.write(chunk); } ``` ### Per-Call Credential Override ```typescript const result = await ai.generate({ provider: "nvidia-nim", input: { text: "Hello" }, credentials: { nvidiaNim: { apiKey: "nvapi-per-user-key", }, }, }); ``` For self-hosted NIM clusters, override the base URL per call: ```typescript const result = await ai.generate({ provider: "nvidia-nim", input: { text: "Hello from self-hosted NIM" }, credentials: { nvidiaNim: { apiKey: "internal-token", baseURL: "https://nim.internal.example.com/v1", }, }, }); ``` --- ## CLI Usage ### Basic Commands ```bash # Generate with the default model pnpm run cli generate "What is the transformer architecture?" --provider nvidia-nim # Use provider aliases pnpm run cli generate "Hello" --provider nim pnpm run cli generate "Hello" --provider nvidia # Specify a model pnpm run cli generate "Explain reinforcement learning" \ --provider nvidia-nim \ --model mistralai/mixtral-8x22b-instruct-v0.1 # Reasoning model with thinking enabled pnpm run cli generate "Solve: what is 17! mod 13?" \ --provider nvidia-nim \ --model deepseek-ai/deepseek-r1 \ --thinking-level high # Interactive loop pnpm run cli loop --provider nvidia-nim ``` --- ## Provider Aliases | Alias | Example | | ------------ | ----------------------- | | `nvidia-nim` | `--provider nvidia-nim` | | `nvidia` | `--provider nvidia` | | `nim` | `--provider nim` | --- ## Configuration Reference | Environment Variable | Required | Default | Description | | ------------------------------- | -------- | ------------------------------------- | ------------------------------------------ | | `NVIDIA_NIM_API_KEY` | Yes | — | NVIDIA NIM API key (starts with `nvapi-`) | | `NVIDIA_NIM_MODEL` | No | `openai/gpt-oss-20b` | Default model | | `NVIDIA_NIM_BASE_URL` | No | `https://integrate.api.nvidia.com/v1` | Base URL (override for self-hosted NIM) | | `NVIDIA_NIM_TOP_K` | No | — | Top-K sampling; `-1` to disable | | `NVIDIA_NIM_MIN_P` | No | — | Minimum token probability; `0` to disable | | `NVIDIA_NIM_REPETITION_PENALTY` | No | — | Anti-repetition factor; `1` is neutral | | `NVIDIA_NIM_MIN_TOKENS` | No | — | Minimum output length in tokens | | `NVIDIA_NIM_CHAT_TEMPLATE` | No | — | Override the model's default chat template | --- ## Self-Hosted NIM If you run NIM on your own GPU cluster, set `NVIDIA_NIM_BASE_URL` to point at your cluster. Authentication is still forwarded via `Authorization: Bearer`, so set `NVIDIA_NIM_API_KEY` to any non-empty value if your cluster does not require it (or to your actual cluster token if it does). ```bash NVIDIA_NIM_API_KEY=internal-token NVIDIA_NIM_BASE_URL=https://nim.cluster.example.com/v1 ``` --- ## Feature Support | Feature | Supported | Notes | | --------------- | --------- | ---------------------------------------------------------------------------------------------------------------- | | Text generation | Yes | | | Streaming | Yes | | | Tool calling | Yes | Most models; depends on model support | | Vision / images | Yes | Model-dependent (Llama 3.2 Vision, etc.) | | Reasoning trace | Yes | Model-dependent; `openai/gpt-oss-20b` always returns one. `thinkingLevel` is an on/off switch on `stream()` only | | Embeddings | No | Use OpenAI or Bedrock for embeddings | --- ## Troubleshooting ### "Invalid NVIDIA NIM API key" The `NVIDIA_NIM_API_KEY` is missing, expired, or incorrect. ```bash echo $NVIDIA_NIM_API_KEY export NVIDIA_NIM_API_KEY=nvapi-... ``` Get or rotate keys at [https://build.nvidia.com/settings/api-keys](https://build.nvidia.com/settings/api-keys). ### "NVIDIA NIM rate limit exceeded" Your account has hit its request-per-minute or token-per-day limit. Upgrade your account, reduce request frequency, or implement backoff. Check your current usage at [https://build.nvidia.com/usage](https://build.nvidia.com/usage). ### "NVIDIA NIM model not available" The model ID is not in the NIM catalog, or your account tier does not have access. ```bash # Browse the catalog open https://build.nvidia.com/models ``` Use the exact model ID shown on the model's page (e.g., `openai/gpt-oss-20b`). ### HTTP 410 "has reached its end of life" The request named a model NVIDIA has retired, for example `meta/llama-3.1-70b-instruct` or `meta/llama-3.3-70b-instruct` (retired 2026-08-26). If you did not pass `model:`, look for a stale `NVIDIA_NIM_MODEL` in your `.env` or shell: it takes precedence over the built-in default (`openai/gpt-oss-20b`). Remove it or set it to a model from the current catalog. ### "NVIDIA NIM quota exceeded" Account-level token or compute quota reached. Check your NIM dashboard. ### HTTP 400 with `reasoning_budget` or `chat_template` in the error The model does not support one of the NIM-specific extras. The provider automatically retries without the rejected parameter. If you see this error surfaced, it means the second attempt also failed — check the rest of the error message for the root cause. ### Empty `content` with `finish_reason: "length"` A reasoning model spent the whole `maxTokens` budget on its reasoning before it started the answer. The reasoning is in `result.reasoning`; raise `maxTokens` (a few hundred tokens is enough for a short answer on `openai/gpt-oss-20b`). ### Thinking level has no visible effect - On `generate()`, `thinkingLevel` is not forwarded to NIM at all; use `stream()`. - On `stream()`, any level except `minimal` sends the same thinking flags, so `low`, `medium` and `high` behave alike. - A model that already reasons on every request, such as `openai/gpt-oss-20b`, returns its trace with or without the flags. - If the model rejects `reasoning_budget` with a 400 that names it, the provider retries once without it. A rejection of `thinking` or `enable_thinking` is not retried and comes back as the 400. --- ## See Also - [Implementation spec](/docs/provider-integration/03-nvidia-nim) — internal wire-format details and NIM-specific extras - [DeepSeek provider](/docs/getting-started/providers/deepseek) — if you only need DeepSeek-R1 via the official DeepSeek API - [OpenAI Compatible provider](/docs/getting-started/providers/openai-compatible) — generic provider for any OpenAI-compatible endpoint --- **Need Help?** Join the [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## Ollama Provider Guide # Ollama Provider Guide **Run AI models locally with full privacy - no API key or cloud service required** ------------------ | ---------------------- | ------------------------------------------------- | | **Native** (default) | `/api/generate` | Standard text generation and streaming | | **OpenAI-compatible** | `/v1/chat/completions` | Tool calling, chat-format messages, compatibility | Tool calling always uses the OpenAI-compatible endpoint regardless of the mode setting. --- ## Quick Start ### 1. Install Ollama ```bash brew install ollama ``` ```bash curl -fsSL https://ollama.ai/install.sh | sh ``` ### 2. Start Ollama and Pull a Model ```bash # Start the Ollama service (may auto-start on install) ollama serve # Pull the default model ollama pull llama3.2:latest # Verify installation ollama list ``` ### 3. Configure NeuroLink Add to your `.env` file: ```bash # Optional: All values below show defaults. Ollama works with zero configuration. # Override the default model OLLAMA_MODEL=llama3.2:latest # Override the base URL (default: http://localhost:11434) OLLAMA_BASE_URL=http://localhost:11434 ``` ### 4. Test the Setup ```typescript const ai = new NeuroLink(); const result = await ai.generate({ input: { text: "Explain quantum computing in simple terms" }, provider: "ollama", }); console.log(result.content); ``` ```bash # Quick generation pnpm run cli -- generate "Hello from local AI!" \ --provider ollama # Use a specific model pnpm run cli -- generate "Write a haiku about AI" \ --provider ollama \ --model "mistral:latest" # Interactive loop mode pnpm run cli -- loop \ --provider ollama \ --model "llama3.1:8b" ``` --- ## Supported Models ### Available Models (from `OllamaModels` enum) Any model in the [Ollama library](https://ollama.ai/library) can be used by passing its tag to `--model`. The `OllamaModels` enum in `src/lib/constants/enums.ts` provides named constants for common models: #### Llama Series | Enum Key | Model ID | Description | | ----------------- | ----------------- | ---------------------------------------- | | `LLAMA4_SCOUT` | `llama4:scout` | Llama 4 multimodal with vision and tools | | `LLAMA4_MAVERICK` | `llama4:maverick` | Llama 4 multimodal with vision and tools | | `LLAMA3_3_70B` | `llama3.3:70b` | High-performance 70B | | `LLAMA3_2_LATEST` | `llama3.2:latest` | Optimized for edge deployment (default) | | `LLAMA3_2_3B` | `llama3.2:3b` | Compact 3B edge model | | `LLAMA3_2_1B` | `llama3.2:1b` | Ultra-compact 1B model | | `LLAMA3_1_8B` | `llama3.1:8b` | Open model rivaling proprietary models | | `LLAMA3_1_70B` | `llama3.1:70b` | Large-scale open model | | `LLAMA3_1_405B` | `llama3.1:405b` | Largest open Llama model | #### Qwen Series | Enum Key | Model ID | Description | | ------------- | ------------- | -------------------------------- | | `QWEN3_4B` | `qwen3:4b` | Advanced reasoning, multilingual | | `QWEN3_8B` | `qwen3:8b` | Advanced reasoning, multilingual | | `QWEN3_14B` | `qwen3:14b` | Advanced reasoning, multilingual | | `QWEN3_32B` | `qwen3:32b` | Advanced reasoning, multilingual | | `QWEN3_72B` | `qwen3:72b` | Advanced reasoning, multilingual | | `QWQ_32B` | `qwq:32b` | Reasoning-specialized model | | `QWEN2_5_72B` | `qwen2.5:72b` | Enhanced coding and mathematics | #### DeepSeek Series | Enum Key | Model ID | Description | | -------------------- | -------------------- | -------------------------- | | `DEEPSEEK_R1_7B` | `deepseek-r1:7b` | State-of-the-art reasoning | | `DEEPSEEK_R1_14B` | `deepseek-r1:14b` | Reasoning at 14B scale | | `DEEPSEEK_R1_32B` | `deepseek-r1:32b` | Reasoning at 32B scale | | `DEEPSEEK_R1_70B` | `deepseek-r1:70b` | Large-scale reasoning | | `DEEPSEEK_V3_LATEST` | `deepseek-v3:latest` | Mixture of Experts model | #### Mistral Series | Enum Key | Model ID | Description | | ---------------------- | ---------------------- | ---------------------------- | | `MISTRAL_LATEST` | `mistral:latest` | Efficient general-purpose 7B | | `MISTRAL_SMALL_LATEST` | `mistral-small:latest` | Compact Mistral variant | | `MISTRAL_NEMO_LATEST` | `mistral-nemo:latest` | Nemo architecture | | `MISTRAL_LARGE_LATEST` | `mistral-large:latest` | Largest Mistral model | #### Code-Specialized Models | Enum Key | Model ID | Description | | ------------------- | ------------------- | ------------------------- | | `CODELLAMA_7B` | `codellama:7b` | Code-focused Llama 7B | | `CODELLAMA_13B` | `codellama:13b` | Code-focused Llama 13B | | `CODELLAMA_34B` | `codellama:34b` | Code-focused Llama 34B | | `CODELLAMA_70B` | `codellama:70b` | Code-focused Llama 70B | | `QWEN2_5_CODER_7B` | `qwen2.5-coder:7b` | Qwen coding model | | `QWEN2_5_CODER_32B` | `qwen2.5-coder:32b` | Qwen coding model (large) | | `STARCODER2_3B` | `starcoder2:3b` | Compact code generation | | `STARCODER2_15B` | `starcoder2:15b` | Larger code generation | #### Vision-Language Models | Enum Key | Model ID | Description | | ----------------- | ----------------- | --------------------------- | | `LLAVA_7B` | `llava:7b` | Vision-language 7B | | `LLAVA_13B` | `llava:13b` | Vision-language 13B | | `LLAVA_34B` | `llava:34b` | Vision-language 34B | | `LLAVA_LLAMA3_8B` | `llava-llama3:8b` | LLaVA with Llama 3 backbone | #### Other Notable Models | Enum Key | Model ID | Description | | ------------------------ | ------------------------ | ----------------------------- | | `GEMMA3_LATEST` | `gemma3:latest` | Google Gemma 3 | | `GEMMA2_27B` | `gemma2:27b` | Google Gemma 2 large | | `PHI4_LATEST` | `phi4:latest` | Microsoft Phi 4 | | `PHI3_MINI` | `phi3:mini` | Microsoft Phi 3 compact | | `MIXTRAL_8X7B` | `mixtral:8x7b` | Mixture of Experts | | `MIXTRAL_8X22B` | `mixtral:8x22b` | Large Mixture of Experts | | `COMMAND_R_PLUS` | `command-r-plus:104b` | Cohere enterprise model | | `GLM_5_LATEST` | `glm-5:latest` | Z.AI flagship reasoning | | `NEMOTRON_3_NANO_LATEST` | `nemotron-3-nano:latest` | NVIDIA hybrid MoE, 1M context | ### Default Model The default model is `llama3.2:latest` (set via `OllamaModels.LLAMA3_2_LATEST` in the provider registry). The internal `OllamaLanguageModel` uses `llama3.1:8b` as its default with `llama3.2:latest` as a fallback when the primary model fails. Override the default with the `OLLAMA_MODEL` environment variable. Model names are matched by prefix, so `llama3.2` will match `llama3.2:latest` on your Ollama instance. This also means `gemma3:27b` matches `gemma3:27b-fp16`. ### Model Selection by Use Case ```typescript const ai = new NeuroLink(); // Fast responses on limited hardware const quickResult = await ai.generate({ input: { text: "Summarize this text..." }, provider: "ollama", model: "llama3.2:1b", }); // Balanced general purpose (recommended) const balancedResult = await ai.generate({ input: { text: "Analyze this problem..." }, provider: "ollama", model: "llama3.1:8b", }); // Code generation const codeResult = await ai.generate({ input: { text: "Write a Python function to sort a linked list" }, provider: "ollama", model: "codellama:7b", }); // Deep reasoning const reasoningResult = await ai.generate({ input: { text: "Prove this mathematical theorem..." }, provider: "ollama", model: "deepseek-r1:14b", }); // Image analysis (vision model) const visionResult = await ai.generate({ input: { text: "Describe what you see", images: ["data:image/jpeg;base64,..."], }, provider: "ollama", model: "llava:7b", }); ``` ### Model Recommendations by System Resources | RAM | Recommended Models | | ------ | -------------------------------------------------------------- | | 8 GB | `llama3.2:1b`, `phi3:mini`, `gemma2:2b` | | 16 GB | `llama3.1:8b`, `mistral:latest`, `codellama:7b`, `qwen3:8b` | | 32 GB+ | `llama3.3:70b`, `mixtral:8x7b`, `deepseek-r1:32b`, `qwen3:32b` | | 64 GB+ | `llama3.1:405b`, `mixtral:8x22b`, `deepseek-v3:latest` | --- ## Provider Aliases The Ollama provider is registered with the following aliases in the provider registry: | Alias | Description | | -------- | ---------------------------------- | | `ollama` | Primary provider name | | `local` | Convenience alias for local models | Both aliases resolve to the same `OllamaProvider`. Use either in the `--provider` flag or the `provider` option: ```bash # These are equivalent pnpm run cli -- generate "Hello" --provider ollama pnpm run cli -- generate "Hello" --provider local ``` --- ## OpenAI-Compatible Mode By default, NeuroLink uses Ollama's native API (`/api/generate`). Setting `OLLAMA_OPENAI_COMPATIBLE=true` switches all requests to the OpenAI-compatible endpoint (`/v1/chat/completions`). ### When to Use OpenAI-Compatible Mode - Your Ollama deployment only exposes the OpenAI-compatible route (e.g., certain hosted or proxied setups) - You want consistent message formatting across providers - You need chat-format messages instead of raw prompt concatenation ### Configuration ```bash # Enable OpenAI-compatible mode OLLAMA_OPENAI_COMPATIBLE=true ``` ### Behavior Differences | Feature | Native Mode (`/api/generate`) | OpenAI-Compatible Mode (`/v1/chat/completions`) | | ---------------- | ---------------------------------- | ----------------------------------------------- | | Message format | Concatenated prompt string | Chat messages array | | System prompt | Sent as `system` field | Sent as system message role | | Streaming format | NDJSON lines with `response` field | SSE with `data:` prefix, `choices[0].delta` | | Image support | Native `images` field (base64) | Text-only (images converted to text) | :::note[Tool Calling and API Mode] Tool calling always uses the `/v1/chat/completions` endpoint regardless of the `OLLAMA_OPENAI_COMPATIBLE` setting. This is because Ollama's tool/function calling support is only available through the OpenAI-compatible API. ::: --- ## Tool Use / Function Calling Ollama supports tool calling through its OpenAI-compatible endpoint. The provider converts tools to the OpenAI function calling format and handles multi-step tool execution in a conversation loop. ### Tool Capability Detection By default, tool calling is assumed to be supported for all models. You can restrict tool calling to specific models by configuring `OLLAMA_TOOL_CAPABLE_MODELS` or setting `providers.ollama.modelBehavior.toolCapableModels` in the model configuration. ### Recommended Models for Tool Calling The provider includes static recommendations via `OllamaProvider.getToolCallingRecommendations()`: | Model | Speed | Quality | Size | Notes | | -------------------------- | ----- | ------- | ------ | ------------------------------------------- | | `llama3.1:8b-instruct` | Fast | Good | 4.6 GB | Best balance of speed and tool capability | | `mistral:7b-instruct-v0.3` | Fast | Good | 4.1 GB | Lightweight with reliable function calling | | `hermes3:8b-llama3.1` | Fast | Good | 4.6 GB | Specialized for tool execution | | `codellama:34b-instruct` | Slow | High | 19 GB | Excellent for code-related tool calling | | `firefunction-v2:70b` | Slow | High | 40 GB | Optimized specifically for function calling | ### SDK Example ```typescript const tools = [ { name: "get_weather", description: "Get current weather for a location", parameters: { type: "object", properties: { location: { type: "string", description: "City name" }, }, required: ["location"], }, }, ]; const result = await ai.generate({ input: { text: "What's the weather in Tokyo?" }, provider: "ollama", model: "llama3.1:8b", tools, }); console.log(result.toolCalls); ``` ### Multi-Step Tool Execution The provider supports multi-step tool execution with a configurable maximum number of iterations (controlled by `maxSteps`, defaulting to `DEFAULT_MAX_STEPS`). In each iteration: 1. The model receives the conversation history and available tools 2. If the model returns tool calls, NeuroLink executes them automatically 3. Tool results are appended to the conversation history 4. The model is called again with the updated context 5. This repeats until the model returns a final text response or the iteration limit is reached --- ## Streaming Responses Streaming is supported in both native and OpenAI-compatible modes. ```typescript const stream = await ai.stream({ input: { text: "Write a detailed article about local AI" }, provider: "ollama", model: "llama3.1:8b", }); ``` ```bash pnpm run cli -- stream "Write a story about a robot" \ --provider ollama ``` The provider performs a health check (`GET /api/version`) before each streaming request to give an early, actionable error if Ollama is not running. --- ## Multimodal Capabilities ### Image Analysis Vision-capable models (LLaVA, Llama 3.2 vision variants) can analyze images. In native mode, images are sent as base64-encoded data in the Ollama `images` field. In OpenAI-compatible mode, images are converted to text descriptions. ```typescript const result = await ai.generate({ input: { text: "Describe what you see in this image", images: ["data:image/jpeg;base64,..."], }, provider: "ollama", model: "llava:7b", }); ``` ```bash pnpm run cli -- generate "Describe this image" \ --provider ollama \ --model "llava:7b" \ --image ./photo.jpg ``` :::note[PDF Support] Ollama has no native PDF input, so NeuroLink renders each page to an image and sends those instead. This means PDFs work, but only with a **vision model** such as `llava:7b` — a text-only model receives nothing usable. ```bash pnpm run cli -- generate "Summarize this document" \ --provider ollama \ --model "llava:7b" \ --pdf ./report.pdf ``` The image fallback converts **at most the first 20 pages** (a token-overflow guard in the message builder) and costs one image per converted page. Anything past page 20 is not sent at all, so for longer documents use a provider with native PDF support — OpenAI, Anthropic, Google Vertex AI or Google AI Studio. ::: --- ## Configuration Reference ### Environment Variables | Variable | Description | Default | Required | | ---------------------------- | ---------------------------------------------------------------- | --------------------------- | -------- | | `OLLAMA_BASE_URL` | Base URL for the Ollama API | `http://localhost:11434` | No | | `OLLAMA_MODEL` | Default model to use | `llama3.2:latest` | No | | `OLLAMA_TIMEOUT` | Request timeout in milliseconds | `240000` (4 minutes) | No | | `OLLAMA_OPENAI_COMPATIBLE` | Set to `true` to use the OpenAI-compatible API endpoint | `false` | No | | `OLLAMA_TOOL_CAPABLE_MODELS` | Comma-separated list of model patterns that support tool calling | (empty, all models assumed) | No | ### CLI Provider Options | Flag | Values | Description | | ------------------- | -------------------- | ----------------------- | | `--provider` / `-p` | `ollama` or `local` | Use Ollama provider | | `--model` / `-m` | Any Ollama model tag | Specific model to use | | `--image` | File path | Image for vision models | --- ## Error Handling The Ollama provider maps errors to specific error types with actionable guidance: | Error Type | Condition | | ------------------- | ----------------------------------------------------------- | | `NetworkError` | Connection refused (Ollama not running), endpoint not found | | `InvalidModelError` | Requested model not pulled locally | | `TimeoutError` | Request exceeded the configured timeout | | `ProviderError` | Other Ollama-side failures | --- ## Troubleshooting ### "Connection refused" / Ollama not running The most common error. The provider checks `OLLAMA_BASE_URL` (default `http://localhost:11434`) and will fail if Ollama is not serving. ```bash # Start Ollama ollama serve # Verify it is running curl http://localhost:11434/api/version # Check if the port is in use lsof -i :11434 # macOS/Linux netstat -an | findstr 11434 # Windows ``` If Ollama is running on a different host or port: ```bash OLLAMA_BASE_URL=http://your-host:11434 ``` ### "Model not found" The model must be pulled before it can be used. Ollama downloads models on demand. ```bash # Pull the model you need ollama pull llama3.2:latest # List installed models ollama list # Try a lightweight model first ollama pull phi3:mini ``` ### Timeout errors with large models Large models (70B+) can take a long time to load into memory on the first request, and inference is slower. Increase the timeout: ```bash # Increase to 10 minutes for very large models OLLAMA_TIMEOUT=600000 ``` ### Slow performance - Close other memory-intensive applications - Use a smaller model variant (e.g., `llama3.2:1b` instead of `llama3.1:70b`) - GPU acceleration is automatic on supported hardware: - **Apple Silicon**: Metal acceleration on M1/M2/M3/M4 - **NVIDIA**: Automatic if CUDA drivers are installed - **AMD**: ROCm support on Linux ### Tool calls not working 1. Ensure your model supports function calling (see [Recommended Models for Tool Calling](#recommended-models-for-tool-calling)) 2. Tool calling always uses the `/v1/chat/completions` endpoint; verify it is accessible: ```bash curl http://localhost:11434/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{"model": "llama3.1:8b", "messages": [{"role": "user", "content": "hello"}]}' ``` ### 404 errors from the API The Ollama version may be too old or the API endpoint has changed. ```bash # Check version ollama --version # Update Ollama # macOS: brew upgrade ollama # Linux: curl -fsSL https://ollama.ai/install.sh | sh ``` --- ## Privacy and Security - **All data stays local**: No network calls to external services during inference - **No telemetry from Ollama**: Ollama does not track usage - **Air-gap capable**: After pulling models, works entirely offline - **No API keys stored**: No credentials to manage or rotate --- ## Related Documentation - **[Provider Setup Guide](/docs/getting-started/provider-setup)** - General provider configuration --- ## Additional Resources - **[Ollama](https://ollama.ai)** - Official website and downloads - **[Ollama Model Library](https://ollama.ai/library)** - Browse available models - **[Ollama GitHub](https://github.com/ollama/ollama)** - Source code and documentation --- ## OpenAI-Compatible Providers Guide # OpenAI Compatible Provider Guide **Connect to any OpenAI-compatible API: OpenRouter, vLLM, LocalAI, and more** ---------------------- | ------------------------------------ | ---------------------- | | **OpenRouter** | AI provider aggregator (100+ models) | Multi-provider access | | **Flatkey** | Unified gateway, one key & balance | Multi-provider access | | **vLLM** | High-performance inference server | Self-hosted models | | **LocalAI** | Local OpenAI alternative | Privacy, offline usage | | **Text Generation WebUI** | Community inference server | Local LLMs | | **Custom APIs** | Your own OpenAI-compatible service | Proprietary models | --- ## Quick Start ### Option 1: OpenRouter (Recommended for Beginners) OpenRouter provides access to 100+ models from multiple providers through a single API. #### 1. Get OpenRouter API Key 1. Visit [OpenRouter.ai](https://openrouter.ai/) 2. Sign up for free account 3. Go to [Keys](https://openrouter.ai/keys) 4. Create new key 5. Add credits ($5 minimum) #### 2. Configure NeuroLink ```bash # Add to .env OPENAI_COMPATIBLE_BASE_URL=https://openrouter.ai/api/v1 OPENAI_COMPATIBLE_API_KEY=sk-or-v1-your-key-here ``` #### 3. Test Setup ```bash # Auto-discover available models npx @juspay/neurolink models --provider openai-compatible # Generate with specific model npx @juspay/neurolink generate "Hello from OpenRouter!" \ --provider openai-compatible \ --model "anthropic/claude-3.5-sonnet" ``` ### Option 2: vLLM (Self-Hosted) vLLM is a high-performance inference server for running models locally. #### 1. Install vLLM ```bash # Install vLLM pip install vllm # Start server with a model python -m vllm.entrypoints.openai.api_server \ --model mistralai/Mistral-7B-Instruct-v0.2 \ --port 8000 ``` #### 2. Configure NeuroLink ```bash # Add to .env OPENAI_COMPATIBLE_BASE_URL=http://localhost:8000/v1 OPENAI_COMPATIBLE_API_KEY=none # vLLM doesn't require key ``` #### 3. Test Setup ```bash npx @juspay/neurolink generate "Hello from vLLM!" \ --provider openai-compatible ``` ### Option 3: LocalAI (Privacy-Focused) LocalAI runs completely offline for maximum privacy. #### 1. Install LocalAI ```bash # Using Docker docker run -p 8080:8080 \ -v $PWD/models:/models \ localai/localai:latest # Or install directly curl https://localai.io/install.sh | sh ``` #### 2. Configure NeuroLink ```bash OPENAI_COMPATIBLE_BASE_URL=http://localhost:8080/v1 OPENAI_COMPATIBLE_API_KEY=none ``` --- ## Model Auto-Discovery NeuroLink automatically discovers available models through the `/v1/models` endpoint. ### Discover Available Models ```bash # List all models from endpoint npx @juspay/neurolink models --provider openai-compatible ``` ### SDK Auto-Discovery ```typescript // getAvailableModels() is on the concrete provider class, not on the // AIProvider type that createProvider() returns, so narrow it for TypeScript. type ModelLister = { getAvailableModels(): Promise }; const ai = new NeuroLink(); // Discover models programmatically (returns the model ids as strings) const provider = (await ProviderFactory.createProvider( "openai-compatible", )) as unknown as ModelLister; const models = await provider.getAvailableModels(); console.log("Available models:", models); // Use discovered model const result = await ai.generate({ input: { text: "Hello!" }, provider: "openai-compatible", model: models[0], // Use first available model }); ``` --- ## OpenRouter Integration OpenRouter aggregates 100+ models from multiple providers. ### Available Models on OpenRouter ```bash # List all OpenRouter models npx @juspay/neurolink models --provider openai-compatible # Popular models available: # - anthropic/claude-3.5-sonnet # - openai/gpt-4-turbo # - google/gemini-pro-1.5 # - meta-llama/llama-3-70b-instruct # - mistralai/mistral-large ``` ### Model Selection by Provider ```typescript // Use Claude through OpenRouter const claude = await ai.generate({ input: { text: "Explain quantum computing" }, provider: "openai-compatible", model: "anthropic/claude-3.5-sonnet", }); // Use GPT-4 through OpenRouter const gpt4 = await ai.generate({ input: { text: "Write a poem" }, provider: "openai-compatible", model: "openai/gpt-4-turbo", }); // Use Gemini through OpenRouter const gemini = await ai.generate({ input: { text: "Analyze this data" }, provider: "openai-compatible", model: "google/gemini-pro-1.5", }); ``` ### OpenRouter Features ```typescript // Cost tracking (OpenRouter provides in response) const result = await ai.generate({ input: { text: "Your prompt" }, provider: "openai-compatible", model: "anthropic/claude-3.5-sonnet", enableAnalytics: true, }); console.log("Tokens used:", result.usage.totalTokens); console.log("Cost:", result.cost); // OpenRouter returns actual cost // Provider selection preferences const result = await ai.generate({ input: { text: "Your prompt" }, provider: "openai-compatible", model: "openai/gpt-4", headers: { "X-Provider-Preferences": "order:cost", // Cheapest first }, }); ``` --- ## vLLM Integration vLLM provides high-performance inference for self-hosted models. ### Starting vLLM Server ```bash # Basic setup python -m vllm.entrypoints.openai.api_server \ --model mistralai/Mistral-7B-Instruct-v0.2 \ --port 8000 # With GPU optimization python -m vllm.entrypoints.openai.api_server \ --model mistralai/Mistral-7B-Instruct-v0.2 \ --tensor-parallel-size 2 \ # Multi-GPU --gpu-memory-utilization 0.9 \ --port 8000 # With quantization for lower memory python -m vllm.entrypoints.openai.api_server \ --model TheBloke/Mistral-7B-Instruct-v0.2-AWQ \ --quantization awq \ --port 8000 ``` ### NeuroLink Configuration for vLLM ```typescript const ai = new NeuroLink({ providers: [ { name: "openai-compatible", config: { baseUrl: "http://localhost:8000/v1", apiKey: "none", // vLLM doesn't require authentication defaultModel: "mistralai/Mistral-7B-Instruct-v0.2", }, }, ], }); // Use vLLM-hosted model const result = await ai.generate({ input: { text: "Explain Docker containers" }, provider: "openai-compatible", }); ``` ### Multiple vLLM Instances ```typescript // Load balance across multiple vLLM servers const ai = new NeuroLink({ providers: [ { name: "openai-compatible-1", config: { baseUrl: "http://server1:8000/v1", apiKey: "none", }, priority: 1, }, { name: "openai-compatible-2", config: { baseUrl: "http://server2:8000/v1", apiKey: "none", }, priority: 1, }, ], loadBalancing: "round-robin", }); ``` --- ## SDK Integration ### Basic Usage ```typescript const ai = new NeuroLink(); // Simple generation const result = await ai.generate({ input: { text: "Hello from OpenAI Compatible!" }, provider: "openai-compatible", }); console.log(result.content); ``` ### With Model Selection ```typescript // Specify exact model (OpenRouter format) const result = await ai.generate({ input: { text: "Explain blockchain" }, provider: "openai-compatible", model: "anthropic/claude-3.5-sonnet", }); // Or use auto-discovered model (ProviderFactory and ModelLister as in // "SDK Auto-Discovery" above) const provider = (await ProviderFactory.createProvider( "openai-compatible", )) as unknown as ModelLister; const models = await provider.getAvailableModels(); const result = await ai.generate({ input: { text: "Your prompt" }, provider: "openai-compatible", model: models[0], }); ``` ### Streaming ```typescript // Stream responses for better UX for await (const chunk of ai.stream({ input: { text: "Write a long story" }, provider: "openai-compatible", model: "anthropic/claude-3.5-sonnet", })) { process.stdout.write(chunk.content); } ``` ### Custom Headers ```typescript // Pass custom headers (e.g., for OpenRouter) const result = await ai.generate({ input: { text: "Your prompt" }, provider: "openai-compatible", headers: { "HTTP-Referer": "https://your-app.com", "X-Title": "YourApp", "X-Provider-Preferences": "order:cost", }, }); ``` ### Error Handling ```typescript // getAvailableModels() is on the concrete provider class, not on the // AIProvider type that createProvider() returns, so narrow it for TypeScript. type ModelLister = { getAvailableModels(): Promise }; try { const result = await ai.generate({ input: { text: "Your prompt" }, provider: "openai-compatible", model: "non-existent-model", }); } catch (error) { if (error.message.includes("model not found")) { // List available models const provider = (await ProviderFactory.createProvider( "openai-compatible", )) as unknown as ModelLister; const models = await provider.getAvailableModels(); console.log("Available models:", models); } else if (error.message.includes("connection")) { console.error("Cannot connect to endpoint"); } else { throw error; } } ``` --- ## CLI Usage ### Basic Commands ```bash # Generate with default model npx @juspay/neurolink generate "Hello world" --provider openai-compatible # Use specific model npx @juspay/neurolink gen "Write code" \ --provider openai-compatible \ --model "anthropic/claude-3.5-sonnet" # Stream response npx @juspay/neurolink stream "Tell a story" \ --provider openai-compatible # List available models npx @juspay/neurolink models --provider openai-compatible ``` ### OpenRouter-Specific Commands ```bash # Use cheap models for cost optimization npx @juspay/neurolink gen "Customer support query" \ --provider openai-compatible \ --model "meta-llama/llama-3-8b-instruct" # Cheap # Use premium models for complex tasks npx @juspay/neurolink gen "Complex analysis task" \ --provider openai-compatible \ --model "anthropic/claude-3-opus" # Premium ``` --- ## Configuration Options ### Environment Variables ```bash # Required OPENAI_COMPATIBLE_BASE_URL=https://openrouter.ai/api/v1 OPENAI_COMPATIBLE_API_KEY=sk-or-v1-your-key # Optional OPENAI_COMPATIBLE_MODEL=anthropic/claude-3.5-sonnet # Default model OPENAI_COMPATIBLE_TIMEOUT=60000 # Timeout (ms) OPENAI_COMPATIBLE_VERIFY_SSL=true # SSL verification ``` ### Programmatic Configuration ```typescript const ai = new NeuroLink({ providers: [ { name: "openai-compatible", config: { baseUrl: process.env.OPENAI_COMPATIBLE_BASE_URL, apiKey: process.env.OPENAI_COMPATIBLE_API_KEY, defaultModel: "anthropic/claude-3.5-sonnet", timeout: 60000, headers: { "HTTP-Referer": "https://yourapp.com", "X-Title": "YourApp", }, }, }, ], }); ``` --- ## Use Cases ### 1. Multi-Provider Access via OpenRouter ```typescript // Access multiple providers through one endpoint const providers = { claude: "anthropic/claude-3.5-sonnet", gpt4: "openai/gpt-4-turbo", gemini: "google/gemini-pro-1.5", llama: "meta-llama/llama-3-70b-instruct", }; for (const [name, model] of Object.entries(providers)) { const result = await ai.generate({ input: { text: "Explain quantum computing in one sentence" }, provider: "openai-compatible", model, }); console.log(`${name}: ${result.content}`); } ``` ### 2. Self-Hosted Private Models ```typescript // Complete privacy with local vLLM const privateAI = new NeuroLink({ providers: [ { name: "openai-compatible", config: { baseUrl: "http://localhost:8000/v1", apiKey: "none", }, }, ], }); // Process sensitive data locally const result = await privateAI.generate({ input: { text: sensitiveData }, provider: "openai-compatible", }); // Data never leaves your infrastructure ``` ### 3. Cost Optimization ```typescript // Compare costs across providers via OpenRouter async function generateCheapest(prompt: string) { const models = [ { name: "llama-3-8b", model: "meta-llama/llama-3-8b-instruct", costPer1M: 0.2, }, { name: "mistral-7b", model: "mistralai/mistral-7b-instruct", costPer1M: 0.15, }, { name: "gemma-7b", model: "google/gemma-7b-it", costPer1M: 0.1 }, ]; // Sort by cost models.sort((a, b) => a.costPer1M - b.costPer1M); // Try cheapest first for (const { model } of models) { try { return await ai.generate({ input: { text: prompt }, provider: "openai-compatible", model, }); } catch (error) { continue; // Try next model } } } ``` --- ## Troubleshooting ### Common Issues #### 1. "Connection refused" **Problem**: Endpoint is not accessible. **Solution**: ```bash # Test endpoint manually (local development) curl http://localhost:8000/v1/models # Test endpoint manually (production - always use HTTPS) curl https://your-production-endpoint.com/v1/models # Check if server is running ps aux | grep vllm # Verify firewall allows connection telnet localhost 8000 ``` #### 2. "Model not found" **Problem**: Model ID is incorrect or not available. **Solution**: ```bash # List available models first npx @juspay/neurolink models --provider openai-compatible # Use exact model ID from list npx @juspay/neurolink gen "test" \ --provider openai-compatible \ --model "exact-model-id-from-list" ``` #### 3. "Invalid API key" **Problem**: API key format is incorrect (OpenRouter). **Solution**: ```bash # OpenRouter keys start with sk-or-v1- OPENAI_COMPATIBLE_API_KEY=sk-or-v1-your-key # ✅ Correct # For local servers, use 'none' or empty string OPENAI_COMPATIBLE_API_KEY=none # ✅ For vLLM ``` --- ## Best Practices ### 1. Model Discovery ```typescript // getAvailableModels() is on the concrete provider class, not on the // AIProvider type that createProvider() returns, so narrow it for TypeScript. type ModelLister = { getAvailableModels(): Promise }; // ✅ Good: Auto-discover models on startup const provider = (await ProviderFactory.createProvider( "openai-compatible", )) as unknown as ModelLister; const models = await provider.getAvailableModels(); console.log("Available models:", models); // Cache model list const modelCache = new Map(); modelCache.set("openai-compatible", models); ``` ### 2. Endpoint Health Checks ```typescript // getAvailableModels() is on the concrete provider class, not on the // AIProvider type that createProvider() returns, so narrow it for TypeScript. type ModelLister = { getAvailableModels(): Promise }; // ✅ Good: Verify endpoint before use async function healthCheck() { try { const provider = (await ProviderFactory.createProvider( "openai-compatible", )) as unknown as ModelLister; const models = await provider.getAvailableModels(); return models.length > 0; } catch (error) { return false; } } if (await healthCheck()) { // Use provider } else { // Fall back to alternative } ``` ### 3. Cost Tracking ```typescript // ✅ Good: Track usage with OpenRouter const result = await ai.generate({ input: { text: prompt }, provider: "openai-compatible", enableAnalytics: true, }); await costTracker.record({ provider: "openrouter", model: result.model, tokens: result.usage.totalTokens, cost: result.cost, }); ``` --- ## Related Documentation - **[Provider Setup Guide](/docs/getting-started/provider-setup)** - General provider configuration - **[Cost Optimization](/docs/cookbook/cost-optimization)** - Reduce AI costs - **[Enterprise Multi-Region](/docs/guides/enterprise/multi-region)** - Self-hosted and vLLM deployment --- ## Additional Resources - **[OpenRouter](https://openrouter.ai/)** - Multi-provider aggregator - **[vLLM Documentation](https://docs.vllm.ai/)** - Self-hosted inference - **[LocalAI](https://localai.io/)** - Local OpenAI alternative - **[OpenAI API Spec](https://platform.openai.com/docs/api-reference)** - API standard --- **Need Help?** Join our [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## OpenAI Decisions Provider Guide # OpenAI Decisions Provider Guide **A provider of `decide`** — the same typed `boolean` / `choice` / `score` answers as [TypeSafe's Jev](/docs/getting-started/providers/typesafe), [Laya](/docs/getting-started/providers/laya), [XOR](/docs/getting-started/providers/xor), [Perplexity](/docs/getting-started/providers/perplexity-decider) and [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef), from OpenAI's Decisions API, and it also reads images. It emits no text at all. > This is not the [OpenAI chat provider](/docs/getting-started/providers/openai) (`openai`), which serves > `generate()` and `stream()`. The two share one API key, which has a > consequence worth reading before you set it. See > [What is sent to OpenAI](#what-is-sent-to-openai) and > [One key, two providers](#one-key-two-providers). > **Public beta.** OpenAI documents the Decisions API as a public beta, so its > wire may change before general availability. NeuroLink lists its one model as > `preview`. Much about the endpoint is not established: see > [What is not established](#what-is-not-established). No request in this > guide, or in NeuroLink's tests, records a reply from the live endpoint; the > replies in the tests are stand-ins built from OpenAI's published examples. ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Provider id | `openai-decisions` (no aliases) — distinct from `openai`, the chat provider | | Inference type | `decide` only | | Model | `gpt-6-luna`; `OPENAI_DECISIONS_MODEL` or a per-call `model` sets it | | Key | `OPENAI_API_KEY`, shared with the OpenAI chat provider, or `credentials.openaiDecisions.apiKey` | | Endpoint | `https://api.openai.com/v1/decisions`; `OPENAI_DECISIONS_BASE_URL` can name another origin | | Media | images as inline data URLs, up to 8 per request (NeuroLink's own allowance, not OpenAI's); the endpoint has no video part | | Request body cap | 32 MiB on the encoded request, NeuroLink's own allowance, not OpenAI's | | State window | 922,000 tokens is reported as an advisory figure (the model page's input figure); NeuroLink never refuses on it | | Questions per request | 200, the figure in OpenAI's Python SDK, read from documentation on 2026-10-17 and not tried against the live endpoint; `tryDecide()` splits a longer set into requests of at most 200, and a direct `decide()` is not refused locally | | Default timeout | 10 seconds for any number of questions; `timeoutMs` or `--timeout` replaces it. A starting point, not a measurement | | Cost | priced per input token, input only; see [Cost](#cost) for the rate, its source and its date | | Precedence | used automatically only when none of TypeSafe, Laya, XOR, SubQ, Perplexity or Cloudflare Clef is configured: the seventh of eight, ahead of only [ScaleDown](/docs/getting-started/providers/scaledown). Its environment key is skipped for this while `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL` names a host other than `https://api.openai.com` (a gateway's key); see [A gateway's key](#a-gateways-key-is-never-used-for-the-default) | | Status | public beta; NeuroLink's model status is `preview` | --- ## Quick Start ### 1. Get a key Create one in the [OpenAI dashboard](https://platform.openai.com/api-keys). It is the same kind of key the OpenAI chat provider uses. ### 2. Configure Set the key in the environment: ```bash export OPENAI_API_KEY=sk-... # the key; see "One key, two providers" export OPENAI_DECISIONS_MODEL=gpt-6-luna # optional export OPENAI_DECISIONS_BASE_URL=https://api.openai.com # optional; an origin ``` or in the config passed to the SDK, exactly as for any other provider. Values passed per call override the constructor's, which override the environment: ```typescript // For the whole instance const neurolink = new NeuroLink({ credentials: { openaiDecisions: { apiKey: process.env.MY_OPENAI_DECISIONS_KEY }, }, }); // Or for one call await neurolink.decide({ provider: "openai-decisions", credentials: { openaiDecisions: { apiKey: process.env.MY_OPENAI_DECISIONS_KEY }, }, state: "The headphones sound great, but the battery died after two weeks.", questions: { defect: { type: "boolean", instructions: "Is a defect reported?" }, }, }); ``` `credentials.openaiDecisions` is its own slice (`apiKey` and `baseURL`). A key passed as `credentials.openai` belongs to the chat provider and does not configure this one. `OPENAI_BASE_URL`, which moves the chat provider, never routes a decision, and neither does `OPENAI_MODEL` pick its model; the overrides for this provider are `OPENAI_DECISIONS_BASE_URL` and `OPENAI_DECISIONS_MODEL`. `OPENAI_BASE_URL`, `OPENAI_API_BASE` and the SDK's `credentials.openai.baseURL` are read for one purpose only: to tell whether the environment key is OpenAI's own, so that a gateway's key is not used for the default; see [A gateway's key](#a-gateways-key-is-never-used-for-the-default). ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.decide({ provider: "openai-decisions", state: { title: "Battery died after two weeks", review: "The headphones sound great, but the battery stopped charging after two weeks.", }, questions: { defect: { type: "boolean", instructions: "Does the review report a defect?", }, sentiment: { type: "choice", instructions: "What is the overall sentiment of the review?", criteria: { positive: "Mostly satisfied", mixed: "Praise and complaints in one review", negative: "Mostly dissatisfied", }, }, severity: { type: "score", instructions: "How severe is the reported problem?", criteria: ["Cosmetic", "Inconvenient", "Product unusable"], }, }, }); const sentiment = readDecisionChoice(result.answers, "sentiment"); ``` A `boolean` answer carries a probability and no confidence of its own. A `choice` or `score` answer carries the confidence the endpoint reports; when a reply omits it, NeuroLink uses the highest probability in that answer's distribution instead. Whether the endpoint's confidence is calibrated is not established, so tune a threshold on it against your own labelled data. ### From the CLI The CLI reads the same environment variables: ```bash neurolink decide "The battery stopped charging after two weeks." \ --provider openai-decisions \ --questions '{"defect":{"type":"boolean","instructions":"Is a defect reported?"}}' ``` The text output ends with a `Cost:` line, priced from the input tokens the endpoint reports. --- ## How a question is sent OpenAI's wire differs from the one the other decide providers share, so NeuroLink translates both ways. You write the same `boolean`, `choice` and `score` questions as for any provider. | NeuroLink | Sent to `/v1/decisions` | | ------------------- | ----------------------------------------------------------------------------------------------------- | | `state` (text) | `input`, the text as given | | `state` (an object) | `input`, the object as JSON text | | `state` with images | `input` as one user message: an `input_text` part, then one `input_image` part per image | | question id | the question's `name`, echoed back on its answer | | `boolean` | `type: "predicate"` with `instructions` | | `choice` | `type: "choice"` with `choices`: one `{ value, description }` per option, in the order you wrote them | | `score` | `type: "score"` with `levels`: one `{ label, description }` per level, lowest first | | the model | `model` in the body (`gpt-6-luna` unless you set another) | A `boolean` question has no per-side text on this wire, so each side you give in `criteria` is appended to its `instructions`, with fixed wording: ``` Answer true when: Answer false when: ``` Either line is left out when you did not give that side. A `choice` option whose text is `null` is sent without a `description`. For a `score`, the `label` is the level's index (`"0"`, `"1"`, ...) and the rubric text goes in `description`, so a returned level and its label cannot disagree about which level it is. Option names that look like integers (`"1"`, `"2"`) are reordered by JavaScript's key order, as for every decide provider. ### Worked example These are the three examples from [OpenAI's Decisions guide](https://developers.openai.com/api/docs/guides/decisions) (saved 2026-10-07), as NeuroLink sends and reads them. The questions: ```typescript const result = await neurolink.decide({ provider: "openai-decisions", state: "Customer photo and complaint text go here.", questions: { visible_damage: { type: "boolean", instructions: "Does the product have visible damage, such as a crack, tear, or dent? Ignore shadows and damage to the packaging.", }, department: { type: "choice", instructions: "Which department should handle this complaint?", criteria: { billing: "Payments, invoices, and refunds.", technical: "Problems using the product.", shipping: "Delivery and tracking.", other: "Requests outside these categories.", }, }, severity: { type: "score", instructions: "How severe is this issue?", criteria: [ "Appearance only; no lost functionality.", "A task fails, but another way works.", "A task fails with no workaround.", ], }, }, }); ``` go out as: ```json { "model": "gpt-6-luna", "input": "Customer photo and complaint text go here.", "questions": [ { "type": "predicate", "name": "visible_damage", "instructions": "Does the product have visible damage, such as a crack, tear, or dent? Ignore shadows and damage to the packaging." }, { "type": "choice", "name": "department", "instructions": "Which department should handle this complaint?", "choices": [ { "value": "billing", "description": "Payments, invoices, and refunds." }, { "value": "technical", "description": "Problems using the product." }, { "value": "shipping", "description": "Delivery and tracking." }, { "value": "other", "description": "Requests outside these categories." } ] }, { "type": "score", "name": "severity", "instructions": "How severe is this issue?", "levels": [ { "label": "0", "description": "Appearance only; no lost functionality." }, { "label": "1", "description": "A task fails, but another way works." }, { "label": "2", "description": "A task fails with no workaround." } ] } ] } ``` The guide's example answers, read back by `name`: | Question | Answer in the guide | `result.answers[name]` | | ---------------- | ----------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `visible_damage` | `probability` 0.92 | `{ type: "boolean", probability: 0.92 }` | | `department` | `choice` `billing`; probabilities 0.95 / 0.02 / 0.01 / 0.02; `confidence` 0.93 | `{ type: "choice", choice: "billing", confidence: 0.93, probabilities: { billing: 0.95, technical: 0.02, shipping: 0.01, other: 0.02 } }` | | `severity` | `score` 1.1; probabilities `0.1` / `0.7` / `0.2` for levels 0, 1 and 2; `confidence` 0.55 | `{ type: "score", score: 1.1, confidence: 0.55, probabilities: { "0": 0.1, "1": 0.7, "2": 0.2 }, legend: { "0": "Appearance only; …", … } }` | The score is the probability-weighted average of the level indices (0 × 0.1 + 1 × 0.7 + 2 × 0.2 = 1.1), the same meaning as NeuroLink's score everywhere. The endpoint returns no legend, so NeuroLink builds `legend` from the rubric you sent, keyed by level index, and a level with no text has the empty string. A level `label` in the reply is not read: the integer `value` identifies the level. ### What a reply must look like NeuroLink checks each answer against the question it asked and drops an answer that fails any check, with a warning that names the question and never quotes the reply. It does not repair or default an answer, and the other answers in the same reply survive. An answer is dropped when: - it has no `name`, or a `name` NeuroLink did not ask, or the same `name` appears more than once (every answer under a repeated name is dropped); - its `type` is not the type asked (`predicate`, `choice` or `score`); - a probability is not a number from 0 to 1; - a `choice`'s `choice` is not one of the options asked, or its `probabilities` do not list each asked option exactly once; - a `score`'s `probabilities` do not list each level index exactly once as an integer `value`, or its `score` is not a number from 0 to the highest index; - its `confidence` is a number outside 0 to 1 (a missing or non-numeric one is replaced by the highest probability in the distribution); - its probabilities do not sum to 1, within a tolerance of 0.01 (with a rounding slack of 1e-9 for floating point). Whether OpenAI rounds the probabilities it returns, and by how much, is not established; an answer whose rounding drifts past the tolerance is dropped like any other. A `refusal` answer (`type: "refusal"`) means the model declined that question. NeuroLink has no refusal answer type: the question is simply absent from `result.answers`, and a warning records `the model declined to answer ""`. A question the reply never mentions is absent too, without a warning. Every internal consumer treats an absent answer as no decision. A reply whose `answers` is not an array fails as a `server` error. --- ## Images OpenAI's Decisions API reads images, and no video part exists. Pass them as for any decide provider that reads images: ```typescript await neurolink.decide({ provider: "openai-decisions", state: "A product photo from a listing.", images: ["./photo.png"], questions: { damaged: { type: "boolean", instructions: "Is the product visibly damaged?", }, }, }); ``` or `neurolink decide ... --provider openai-decisions --image ./photo.png` from the CLI. An image can be a `Buffer`, a file path or a `data:` URL; a remote `http(s)` URL is not fetched for you. Every image is sent inline as a base64 data URL in an `input_image` part. The endpoint takes no hosted URL and no file id, and NeuroLink sets no `detail`. NeuroLink refuses these before any request, as a non-retried `invalid_request`: - more than 8 images, which is NeuroLink's own allowance (the same number it allows XOR and Perplexity), not a limit OpenAI documents; - a video, because the endpoint has no video part; - an image NeuroLink cannot recognise from its bytes, a file that cannot be read, or an encoded request body over 32 MiB (also NeuroLink's own number). The accepted image formats, the per-request image limit and the body cap on OpenAI's side are not established. NeuroLink does not check the format against a list of OpenAI's, because it has none to check against. --- ## When NeuroLink uses it Every built-in consumer of `decide` asks for the default decision provider. That is the first one that is configured, in the environment or in the `credentials` passed to the SDK, in the order TypeSafe, Laya, XOR, [SubQ](/docs/getting-started/providers/subq), Perplexity, [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef), OpenAI Decisions, then [ScaleDown](/docs/getting-started/providers/scaledown). TypeSafe counts with either of its keys, `TYPESAFE_API_KEY` or `AI_GATEWAY_API_KEY`. Laya and XOR each count only with both their key and their base URL. Perplexity counts with its key alone. Cloudflare Clef counts only with both `CLOUDFLARE_API_KEY` and `CLOUDFLARE_ACCOUNT_ID`. OpenAI Decisions counts with its key alone, a non-blank `OPENAI_API_KEY` or `credentials.openaiDecisions.apiKey`, except that a key found only in the environment does not count while `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL` names a host other than `https://api.openai.com`: see [A gateway's key is never used for the default](#a-gateways-key-is-never-used-for-the-default). ScaleDown counts with its key alone, `SCALEDOWN_API_KEY`, which no other provider reads. A caller can always name it with `provider: "openai-decisions"`. So: - **Only an OpenAI key, and no base URL for another host:** built-in features use OpenAI Decisions. - **An OpenAI key beside `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL` naming a gateway:** the key is taken to be the gateway's, and built-in features behave exactly as they did without a decision model, unless `OPENAI_DECISIONS_BASE_URL` is set or a `credentials.openaiDecisions` key or base URL is passed. - **An OpenAI key, plus any key or credentials that configure an earlier provider:** built-in features use the earlier provider, in the order above. OpenAI Decisions runs only where a caller asks for `provider: "openai-decisions"`. - **An OpenAI key, plus `SCALEDOWN_API_KEY`:** built-in features use OpenAI Decisions, which comes ahead of ScaleDown. ScaleDown runs only where a caller asks for `provider: "scaledown"`. - **A key for the chat provider only:** the same as the first case. The key is shared, so the chat provider's key also configures this one. See [One key, two providers](#one-key-two-providers). - **None of TypeSafe, Laya, XOR, SubQ, Perplexity, Cloudflare Clef, OpenAI Decisions or ScaleDown configured:** everything behaves exactly as it did without a decision model. The classifier router's `auto` gate counts the credentials given to the `NeuroLink` constructor, the environment and the request's own per-call credentials, so a `credentials.openaiDecisions` passed on a single call can make `auto` pick `jev`. The decision goes to that account only when no provider ahead of OpenAI Decisions is configured; otherwise it goes to the earlier provider, as in the cases above, because per-call credentials add a provider and do not pin one. The other consumers NeuroLink wires itself that run inside a `generate()` or `stream()` call (tool routing and compaction) forward that call's `credentials` to the decision too. Compaction triggered by `compactSession()`, which has no request, uses the constructor's credentials and the environment. Where the built-in consumers use the default provider (what each one sends is listed in [What is sent to OpenAI](#what-is-sent-to-openai)): | Area | What the decision replaces | | ---------------------------------------------------------------- | --------------------------------------------------------------- | | [Model routing](/docs/features/classifier-router-jev-strategy) | difficulty + capabilities + risk + model pick in one round trip | | [Model catalogue](/docs/features/classifier-router-catalog) | one `choice` over the registry ranks all N candidates at once | | [Context budget](/docs/features/context-budget) | a rubric-placed scope reading lowers the compaction threshold | | [Relevance compaction](/docs/features/relevance-compaction) | per-message keep/drop, plus a gate on the generated summary | | [Tool / MCP routing](/docs/features/tool-routing-decision-model) | one `boolean` per server, replacing a 15s LLM call | | [RAG retrieval](/docs/features/rag-retrieval-planning) | per-query `topK` / hybrid / graph / rerank planning | Each is fail-open: any refusal, timeout or error leaves behaviour as it was. Each also records a `model.decision` span, so a decision path that has stopped working is visible rather than indistinguishable from one never configured. The speech-to-text correction check also asks for the default decision provider, for a host that passes a dictionary to `transcribe()`; see below. Calling it yourself is the other use. It suits the same work as any decision model: routing, classifying and grading against a rubric, gating an action on a threshold, and the same questions about an image. It is wrong for a final answer a user reads, or anything that needs a rationale: a decision carries a probability, never an explanation. See [the `decide` inference type](/docs/features/decide-inference-type). --- ## What is sent to OpenAI OpenAI receives the `state` and the questions of every decision made on your behalf. The questions are NeuroLink's fixed wording, plus text from your own conversation where a consumer quotes it; the `state` is where your text goes. This is what each built-in consumer sends and what turns it on, read from the code: - **Model routing.** One request behind the router, the model catalogue and the per-request context budget. - _Sends:_ the first 8,000 characters of the prompt of the call being routed, plus whether tools are available, whether the request includes images, the estimated input tokens, the requested thinking level, whether a session is bound and how many prior messages the caller passed in. When the pool has more than one model, the questions carry the ids and descriptions of the models in it. The images, the session id and the conversation itself are not sent. - _Turned on by:_ `classifierRouter.enabled` with a `pool`: **an opt-in.** With the default `classifier: "auto"`, a configured decision provider selects the decision strategy. `classifier: "heuristic"` or `"llm"` never calls a decision provider. A call that pins both `provider` and `model` is not routed. - **Relevance compaction.** Stage 0 of context compaction. - _Sends:_ the current request (first 4,000 characters) and, for each earlier user or assistant message that is plain text (not a tool call or result, a summary or a pinned skill), its role and its first 1,200 characters. That text travels twice, once in the state and once in the message's question. By default the six most recent messages are never sent (`contextRelevance.protectRecent`), and at most 300 are asked about. - _Turned on by:_ **nothing beyond a configured decision provider.** It runs inside context compaction, which starts when a conversation outgrows its context budget. - **Summary-quality gate.** Guards the summarization stage of compaction. - _Sends:_ the generated summary (first 12,000 characters) and the last 60 messages it replaced, each with its role and its first 1,200 characters. - _Turned on by:_ **nothing beyond a configured decision provider.** It runs after the summarization stage has written a summary. - **Tool / MCP routing.** - _Sends:_ the routing query, at most 10,000 characters: the current query, preceded by up to the six most recent user and assistant text turns. Also, for each routable server, its name, its description (or its tool names, when it has none) and its tool count. One question per server, up to 200, quotes the same. - _Turned on by:_ `toolRouting.enabled` with a `servers` catalogue and at least two routable servers: **an opt-in.** - **RAG retrieval planning.** - _Sends:_ the search query (first 4,000 characters). The retrieved passages are not sent. - _Turned on by:_ passing a `decide` function to `RAGPipeline` or `createRAGPipeline`: **an opt-in, by wiring.** The `rag: { files }` shortcut on `generate()` and `stream()` never does. - **Speech-to-text correction.** The dictionary guard of [`transcribe()`](/docs/features/transcribe). - _Sends:_ the first 4,000 characters of the transcript, the caller's one-line `context` (or a fixed default), and, per dictionary candidate, the heard word and the dictionary term and its `meaning`. - _Turned on by:_ passing a `correction` dictionary to `transcribe()` or `transcribeStream()` with `guard` left at its default, `"decide"`. A host that sets `OPENAI_API_KEY` only for Whisper (the speech-to-text provider, which reads the same variable) and passes a dictionary therefore sends the transcript text to a second OpenAI endpoint. `guard: "none"` never calls a decision provider. So model routing, tool routing and RAG planning need an opt-in, and relevance compaction, the summary gate and (with a dictionary) the transcript guard need none. A call you make yourself to `neurolink.decide()` sends the `state`, `questions` and `images` you pass, to the provider you name or to the default one. NeuroLink declares a cap of 200 questions per request for this provider. The figure is from OpenAI's Python SDK, whose type for the `questions` field reads "Ask 1–200 questions about the input" (`src/openai/types/decision_create_params.py` in `openai/openai-python`, read on 2026-10-17); OpenAI's Decisions guide states no number. `tryDecide()`, which every built-in consumer calls, therefore splits a longer set into requests of at most 200 questions, keeps the questions in the order given, runs up to four requests at a time and joins the answers. The state (and any images) travels with every request, so a split set pays for the state's input tokens once for each request. Relevance compaction can ask about up to 300 messages, which goes out as one request of 200 questions and one of the rest; tool routing asks about up to 200 servers, which fits in one. A request the endpoint refuses loses only its own questions, and the consumer carries on without that decision. Questions a host adds through `decisionHooks` are capped at 200 minus NeuroLink's own count, dropped from the end with a warning. The row is advisory (see [Key Facts](#key-facts)), so the cap is reported by `decisionLimits()` and used to split in `tryDecide()`, but a direct `neurolink.decide()` with more than 200 questions is not refused locally: it is sent whole and the server answers it. **Going over 200 was not tried against the live endpoint**, so what the endpoint does with 201 is not established; the 200 rests on the SDK's wording alone. Treat each request like any hosted provider call for data handling and retention: it is a request to `api.openai.com` made with your key. Besides the body, each request carries two headers, `Authorization: Bearer ` and `Content-Type: application/json`, and no other. --- ## One key, two providers `OPENAI_API_KEY` is the variable the [OpenAI chat provider](/docs/getting-started/providers/openai) reads to serve `generate()` and `stream()`. It is also the variable that configures this provider, and nothing else needs to be set. **This changes what a host with only an OpenAI key does by default.** A host that set the key only to use OpenAI chat has also configured `decide`: - **With none of TypeSafe, Laya, XOR, SubQ, Perplexity or Cloudflare Clef configured, the texts listed in [What is sent to OpenAI](#what-is-sent-to-openai) go to OpenAI's Decisions API, and each decision is a paid call.** Context compaction needs no other opt-in, so a host with long conversations starts sending conversation text the first time one outgrows its budget. Model routing, tool routing and RAG planning do so only where you have turned them on. A host that passes a transcription dictionary also sends transcript text. No code changes: the key is the switch. - **It is fail-open, and the six providers ahead of it take precedence.** If you have configured any of them, the shared key changes nothing for the built-in consumers. A failure here leaves behaviour as it was, so a key the Decisions endpoint does not accept costs requests, not correctness. - **A rejected key is not remembered across calls.** A 401 stops one provider instance from retrying, but `neurolink.decide()` and `neurolink.tryDecide()` build a fresh provider for every call, so the breaker never latches across them. A host whose key the endpoint rejects makes one failing request for each decision site that runs, every time it runs. - **With no decision provider configured at all, nothing is sent.** ### A gateway's key is never used for the default `OPENAI_API_KEY` is also the key of every OpenAI-compatible gateway (LiteLLM, vLLM, LM Studio and the like), and a host that points the chat provider at one sets `OPENAI_BASE_URL` (or, in LangChain-style setups, `OPENAI_API_BASE`), or an SDK host passes `credentials.openai.baseURL`, to it. The chat provider prefers the credentials field over the variable. That key belongs to the gateway, and the decision text belongs on the gateway's side of the wire, so NeuroLink does not take such a key to be OpenAI's: **while `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL` names a host other than `https://api.openai.com`, the environment key is not used to pick OpenAI Decisions as the default.** The built-in consumers send nothing to `api.openai.com` for it: each behaves as it did without a decision model, and the "no decision provider" error says why the key is ignored. Only a call that names the provider reaches OpenAI, as described below. The check reads each value's origin, that is scheme, host and port, compared without regard to case. A path, a trailing slash and `/v1` do not matter. | `OPENAI_BASE_URL` / `OPENAI_API_BASE` / `credentials.openai.baseURL` | The environment key is used for the default | | ----------------------------------------------------------------------------------- | ------------------------------------------- | | unset, empty or blank | yes | | `https://api.openai.com`, `https://api.openai.com/v1/`, `https://API.openai.com` | yes | | `https://gateway.example/v1`, `http://127.0.0.1:4000/v1`, `http://localhost:11434` | no | | `https://eu.api.openai.com`, `http://api.openai.com`, `https://api.openai.com:8443` | no: another host, scheme or port | | `api.openai.com` (no scheme), `not a url`, `ftp://...` | no: not an http(s) URL | Any one of the three naming another host is enough, even if another names OpenAI: the check errs on the side of keeping the key at home. The credentials field is read from the credentials the call is given, which is the instance's merged with the call's field by field, so a per-call `credentials.openai.baseURL` replaces the instance's. A value that is not text, or not a URL, is another host. A regional OpenAI host such as `https://eu.api.openai.com` is also "another host" here: set `OPENAI_DECISIONS_BASE_URL` (or `credentials.openaiDecisions.baseURL`) to it, which routes this provider there on purpose. The check does **not** apply, and the key is used for the default, when you have routed this provider on purpose: - `OPENAI_DECISIONS_BASE_URL` is set to a non-blank value, whatever `OPENAI_BASE_URL` or `credentials.openai.baseURL` says; decisions then go to that URL, never to the chat host; - `credentials.openaiDecisions` supplies a key, which always counts, or a base URL, which routes this provider on purpose so the environment key stands. It never applies to a call that names the provider. A call with `provider: "openai-decisions"` (or `--provider openai-decisions` on the CLI) uses the key from the environment even beside a gateway `OPENAI_BASE_URL` or `credentials.openai.baseURL`, and sends it to `https://api.openai.com` unless `OPENAI_DECISIONS_BASE_URL` or `credentials.openaiDecisions.baseURL` says otherwise. Naming the provider is intent, so a host whose `OPENAI_API_KEY` is a gateway's must not name it: it routes this provider on purpose with `OPENAI_DECISIONS_BASE_URL` or `credentials.openaiDecisions` (a key and a base URL), or does not use it. The check is data on the catalog entry (`decide.ambientKeyGuard`, with the variables to read and the origins to trust) and is read by the default resolution only. It applies to this provider alone: TypeSafe, Laya, XOR, SubQ, Perplexity and Cloudflare Clef resolve as before. Unlike the Perplexity and Cloudflare lines, `.env.example` ships its `OPENAI_API_KEY` line active, with the placeholder `sk-your-openai-api-key-here` for the chat provider. NeuroLink's check for a configured provider does not recognise a placeholder, so an unedited copy of that file configures this provider with a key OpenAI will not accept: each decision site that runs then makes a failing request, and the consumers fail open. Replace the placeholder with your key, or remove the line. A key in a `.env` file counts as a key in the environment. Importing the SDK loads the `.env` in the current working directory, and the CLI does the same at start; when `DOTENV_CONFIG_PATH` is set, that file is loaded instead. A key that sits in `.env` therefore configures `decide` exactly as one exported in the shell does. To keep a key that was set for OpenAI chat from activating decisions, use one of these: 1. **Hand the key to the chat provider through the SDK, not the environment, and keep it out of `.env`.** `new NeuroLink({ credentials: { openai: { apiKey } } })` configures the chat provider and not this one, because NeuroLink looks for this provider's key in `OPENAI_API_KEY` and in `credentials.openaiDecisions`, never in `credentials.openai`. The key must also be absent from `.env`: remove the `OPENAI_API_KEY` line from that file as well as from the shell, or point `DOTENV_CONFIG_PATH` at a file that does not have it. With no `OPENAI_API_KEY` in the environment or in a loaded `.env`, OpenAI Decisions is not configured. The CLI reads only the environment and the `.env` it loads, so a CLI run that has the variable set in either place has decisions configured; set it only for the commands that need it. 2. **Configure an earlier provider.** TypeSafe, Laya, XOR, SubQ, Perplexity or Cloudflare Clef then answers every built-in consumer, and OpenAI Decisions runs only where a caller names it. The same texts go to that provider instead. 3. **Switch off the opt-in consumers, or pin the router's strategy.** `classifierRouter: { classifier: "heuristic" }` keeps routing in-process (`"llm"` sends the prompt to the classifier model instead). Leave `toolRouting.enabled` unset, and do not pass `decide` to a `RAGPipeline`. Pass `guard: "none"` in a transcription `correction`. This does not cover compaction. Compaction's relevance stage and summary gate have no switch of their own while a decision provider is configured, and there is no switch that turns this provider off while the key is set, short of a gateway `OPENAI_BASE_URL` (which also moves the chat provider; see [A gateway's key](#a-gateways-key-is-never-used-for-the-default)). A test that asserts the "nothing configured" path must blank `OPENAI_API_KEY` as well as the other decision keys, or it will find this provider. --- ## What is not established Each item below is **not measured**: nothing NeuroLink was built or tested from says what the endpoint does, and no live request was made. Where NeuroLink had to choose, it chose to send only documented fields, to refuse nothing locally on OpenAI's behalf, and to drop a bad answer rather than guess. 1. Whether `/v1/decisions` uses OpenAI's general error envelope, and the status and text of a refusal for an over-length input. NeuroLink reads an error's `error.message` when there is one, and classifies by HTTP status. 2. The maximum number of choices per question (the benchmarks NeuroLink has in mind need 77 and 151; OpenAI's Python SDK documents 2 to 255, which NeuroLink does not enforce) and of levels per score, and what a question `name` may contain. The question maximum is documented (200, see [What is sent to OpenAI](#what-is-sent-to-openai)), but what the endpoint does with more than 200 was not tried live. 3. The endpoint's input ceiling (the model page gives 922,000 input tokens for the model in general), the number of images per request, the request body cap and the accepted image formats. 4. Whether `probabilities` always covers every supplied option, in what order, and how the numbers are rounded. NeuroLink reads each distribution by key, not by position, and requires each asked option exactly once. 5. The endpoint's rate limits. The model page lists limits for the model, not for this endpoint. 6. How long a request takes, for any size. The 10-second default timeout is a starting point. 7. Whether a regional host such as `https://eu.api.openai.com` serves this endpoint with the same request. The base URL can be changed to try one. --- ## Cost $0.10 per 1M input tokens, input only, from [OpenAI's Decisions guide](https://developers.openai.com/api/docs/guides/decisions) as read on 2026-10-07. Regional and long-context multipliers are not modelled. NeuroLink prices a decision from the input tokens the reply reports and counts output tokens at nothing, so `result.usage` and the CLI's `Cost:` line are an estimate from that one rate, not a bill. A reply that reports no usage is priced at zero. --- ## Errors | Reply | Kind | Retried | | -------------------------------------------------------------------- | ------------------------------------------------------- | ---------------------------------------- | | 401 | `authentication` — the provider instance stops retrying | no | | 429 (every one) | `rate_limit` | no | | 503 | `overloaded` | yes, once (after `Retry-After`, if sent) | | other 5xx (500, 502, 504) | `server` | yes, once | | any other status, including 400, 402, 403 and 404 | `invalid_request`, with the reply's own message | no | | a 200 whose `answers` is not an array | `server` | no | | no response within the timeout | `timeout` | yes, once | | the request fails before any reply (connection refused, DNS failure) | `network` | yes, once | | the caller's own `signal` aborts the request | `network` | no | | more than 8 images, a video, or an unusable image (local) | `invalid_request`, with no network call | no | | an encoded request over 32 MiB (local) | `invalid_request`, with no network call | no | | no key configured (local) | `authentication`, with no network call | no | | a base URL that cannot work (local) | `invalid_request`, with no network call | no | Only a 401 disables the provider instance, because a bad key does not fix itself: after the first rejection that instance stops sending requests. A 403 is not an authentication failure here: OpenAI uses it for an unsupported country, an account-level condition, so it is an `invalid_request` and does not latch. Every 429 is non-retryable, because OpenAI's general error documentation says that retrying a billing, spend or quota error cannot restore access and nothing NeuroLink has says which kind of 429 a given reply is. Because `neurolink.decide()` and `neurolink.tryDecide()` build a fresh provider per call, the 401 latch holds only for a provider instance you keep, not across public calls. NeuroLink has no rule for an over-length input: its refusal is not established, so it arrives as `invalid_request` with whatever message OpenAI sent. The request id comes from the `x-request-id` header. Before the message of an HTTP error reply reaches a log or an error, the provider removes the configured key, anything shaped like a key beginning `sk-`, long hex runs and embedded `data:` URLs. The message of a failure with no reply (the `network` and `timeout` kinds) goes through the same scrub, and any URL in it is cut to its scheme, host and path. --- ## Base URL `OPENAI_DECISIONS_BASE_URL`, or `credentials.openaiDecisions.baseURL`, replaces `https://api.openai.com`. It is an origin: - trailing slashes and one trailing `/v1` are stripped, so `https://api.openai.com/v1/` and `https://api.openai.com` are the same; - `http://` is accepted only for `localhost`, `127.0.0.1` and `[::1]`, because the request carries the key and the state. Any other host needs `https://`; `0.0.0.0` and the rest of `127.0.0.0/8` do not count as this machine; - a user name or password, a query string, a fragment, a scheme other than `http` or `https`, `http://` to a host other than those three, or a value that is not an absolute URL is refused before any request, with a message that never repeats the value; - a redirect from the endpoint is refused rather than followed, so the decision is never replayed at an address the server chooses; - the request goes to `/v1/decisions`. --- ## Troubleshooting - **`No decision provider is configured` although `OPENAI_API_KEY` is set** — `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL` names a host other than `https://api.openai.com`, so the key is taken to be a gateway's. See [A gateway's key](#a-gateways-key-is-never-used-for-the-default): set `OPENAI_DECISIONS_BASE_URL` or pass `credentials.openaiDecisions` to route this provider on purpose. Naming the provider in a call is not a way out when the key is a gateway's: a named call sends the environment key to `api.openai.com`. - **`OpenAI Decisions requires an API key`** — set `OPENAI_API_KEY`, or pass `credentials.openaiDecisions.apiKey`. A key passed as `credentials.openai` does not count. - **A 401** — OpenAI rejected the key. The provider instance stops retrying after a rejection, so fix the key and construct a new one. - **A 403** — OpenAI's general error documentation lists a 403 for an unsupported country; what this endpoint's own 403s mean is not established. It does not latch the instance, so a change on the account side works at once. - **A 400 naming the model** — `OPENAI_DECISIONS_MODEL`, or a per-call `model`, names something other than a model the endpoint supports. - **`The OpenAI Decisions base URL must not carry credentials…`** — the override has a user name, a password, a query string or a fragment. Set it to the origin only, or leave it unset for `https://api.openai.com`. - **`The OpenAI Decisions base URL must start with https:// or http://`** — the value parses as a URL with another scheme, or is a host name and port with no scheme, such as `localhost:8080`, which reads as the scheme `localhost:`. Put `https://` in front, or `http://` for a server on this machine. - **`The OpenAI Decisions base URL must use https:// unless it points at this machine`** — the override is an `http://` URL whose host is not `localhost`, `127.0.0.1` or `[::1]`. A plain-http request would send the key and the state unencrypted. Use `https://`, or reach the server through a port-forward to `localhost`. - **`OpenAI Decisions answered with a redirect`** — the endpoint replied 301, 302, 307 or 308. The provider does not follow it and does not retry. Set the base URL to the address the redirect leads to. - **`The OpenAI Decisions base URL is not a valid absolute URL`** — the value does not parse as a URL at all, for example a bare host name. Write the origin with its scheme. - **`OpenAI Decisions accepts at most 8 images per request`** — NeuroLink's own allowance. Send fewer, or use a decision provider with a higher one. - **`OpenAI Decisions does not accept video`** — the endpoint has no video part. Send images, or use XOR. - **A question is missing from `result.answers`** — the model declined it (look for the warning), the reply left it out, or its answer failed one of the checks in [What a reply must look like](#what-a-reply-must-look-like). The warning names the question and never quotes the reply. - **Built-in routing never uses OpenAI Decisions** — an earlier provider is also configured and takes precedence, no key is set where the router's `auto` gate looks (it counts the constructor's credentials, the environment and the request's own per-call credentials), or the environment key is a gateway's, which the default skips (see [A gateway's key](#a-gateways-key-is-never-used-for-the-default)). - **State is being sent to OpenAI and I only set the key for chat** — see [What is sent to OpenAI](#what-is-sent-to-openai) and [One key, two providers](#one-key-two-providers). Check the `.env` your process loads as well as the shell: a key in either place configures `decide`. --- ## See also - [The `decide` inference type](/docs/features/decide-inference-type) - [TypeSafe (Jev) Provider Guide](/docs/getting-started/providers/typesafe) - [Laya Provider Guide](/docs/getting-started/providers/laya) - [XOR Provider Guide](/docs/getting-started/providers/xor) - [Perplexity Decisions Provider Guide](/docs/getting-started/providers/perplexity-decider) - [Cloudflare Clef Provider Guide](/docs/getting-started/providers/cloudflare-clef) - [ScaleDown Provider Guide](/docs/getting-started/providers/scaledown) - [OpenAI chat provider](/docs/getting-started/providers/openai) - [OpenAI's Decisions guide](https://developers.openai.com/api/docs/guides/decisions) --- ## OpenAI TTS Provider Guide # OpenAI TTS Provider Guide **High-quality neural text-to-speech with six distinct voices and HD quality option** ------------- | --------------------------------------------- | | **Provider ID** | `openai-tts` | | **API endpoint** | `https://api.openai.com/v1/audio/speech` | | **Models** | `tts-1` (standard), `tts-1-hd` (high quality) | | **Voices** | alloy, echo, fable, onyx, nova, shimmer | | **Formats** | mp3, wav, ogg (opus), opus | | **Max input** | 4,096 characters per request | | **Languages** | Follows input text language automatically | | **Streaming** | Not supported (batch synthesis only) | --- ## Quick Start ### 1. Get an API Key Sign up or log in at [https://platform.openai.com](https://platform.openai.com) and create a new secret key under **API keys**. ### 2. Configure Environment Add to your `.env` file: ```bash # Required OPENAI_API_KEY=sk-... ``` Default model (`tts-1`) and voice (`alloy`) are set in code; override per call via `tts.model` / `tts.voice` in the SDK or `--tts-model` / `--tts-voice` on the CLI. There is no `OPENAI_TTS_MODEL` / `OPENAI_TTS_VOICE` env var. ### 3. Install NeuroLink ```bash npm install @juspay/neurolink # or pnpm add @juspay/neurolink ``` ### 4. Synthesise Your First Audio ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "openai", input: { text: "Hello! Welcome to NeuroLink." }, tts: { enabled: true, provider: "openai-tts", format: "mp3", }, }); if (result.audio) { writeFileSync("output.mp3", result.audio.buffer); console.log(`Saved ${result.audio.size} bytes to output.mp3`); } ``` --- ## Supported Models | Model ID | Quality | Latency | Use Case | | ---------- | -------- | ------- | ---------------------------------------------- | | `tts-1` | Standard | Lower | Default; real-time apps, interactive voice UIs | | `tts-1-hd` | HD | Higher | Podcasts, narration, production audio assets | Select the HD model by passing `quality: "hd"` in TTS options — NeuroLink maps this automatically to `tts-1-hd`. --- ## SDK Usage ### Direct Text Synthesis Synthesise the input text directly without calling an AI model: ```typescript const ai = new NeuroLink(); const result = await ai.generate({ input: { text: "NeuroLink makes AI development simple." }, tts: { enabled: true, provider: "openai-tts", voice: "nova", format: "mp3", }, }); if (result.audio) { console.log("Format:", result.audio.format); console.log("Size:", result.audio.size, "bytes"); console.log("Latency:", result.audio.metadata?.latency, "ms"); } ``` ### AI Response Synthesis Generate a response with an AI model and then synthesise it: ```typescript const result = await ai.generate({ provider: "openai", input: { text: "Greet the user in a warm and friendly tone." }, tts: { enabled: true, provider: "openai-tts", useAiResponse: true, // Synthesise the AI-generated text, not the prompt voice: "shimmer", format: "mp3", }, }); ``` ### HD Quality Audio ```typescript const result = await ai.generate({ input: { text: "This is high-definition audio narration." }, tts: { enabled: true, provider: "openai-tts", quality: "hd", // Maps to tts-1-hd voice: "onyx", format: "wav", }, }); ``` ### Adjusting Playback Speed ```typescript const result = await ai.generate({ input: { text: "Speaking at 80% normal speed." }, tts: { enabled: true, provider: "openai-tts", voice: "alloy", speed: 0.8, // Range: 0.25 to 4.0 (default: 1.0) format: "mp3", }, }); ``` ### Save to File ```typescript const result = await ai.generate({ input: { text: "Saving audio to disk." }, tts: { enabled: true, provider: "openai-tts", voice: "echo", format: "mp3", output: "./audio/output.mp3", // NeuroLink saves automatically if set }, }); ``` ### Per-Call Credential Override ```typescript const result = await ai.generate({ input: { text: "Hello!" }, tts: { enabled: true, provider: "openai-tts", }, credentials: { openai: { apiKey: "sk-user-specific-key", }, }, }); ``` --- ## CLI Usage ### Basic TTS ```bash # Synthesise text directly neurolink generate "Hello, world!" --tts --tts-provider openai-tts # Choose a voice neurolink generate "Good morning!" --tts --tts-provider openai-tts --tts-voice nova # Save to file neurolink generate "Save this audio." \ --tts --tts-provider openai-tts \ --tts-voice shimmer \ --tts-output greeting.mp3 ``` ### HD Quality ```bash neurolink generate "Professional narration." \ --tts --tts-provider openai-tts \ --tts-quality hd \ --tts-voice onyx \ --tts-output narration.mp3 ``` ### Synthesise AI Response ```bash neurolink generate "Tell me a short story." \ --provider openai \ --tts --tts-provider openai-tts \ --tts-voice fable \ --tts-use-ai-response ``` ### Speed Adjustment ```bash neurolink generate "Slow and clear narration." \ --tts --tts-provider openai-tts \ --tts-voice alloy \ --tts-speed 0.75 ``` --- ## Available Voices | Voice ID | Gender | Character | Best For | | --------- | ------- | -------------------------------- | --------------------------------- | | `alloy` | Neutral | Balanced, clear, versatile | General purpose, default | | `echo` | Male | Crisp, authoritative | Announcements, business content | | `fable` | Neutral | Warm, expressive, storytelling | Narration, audiobooks | | `onyx` | Male | Deep, confident, professional | Voiceovers, documentary | | `nova` | Female | Bright, friendly, conversational | Voice assistants, customer-facing | | `shimmer` | Female | Soft, gentle, calm | Wellness apps, guided meditation | OpenAI voices are language-agnostic — they follow the language of the input text automatically, supporting English, Spanish, French, German, Japanese, and many more. --- ## Audio Formats | Format | Extension | Use Case | Notes | | ------ | --------- | --------------------------------------- | -------------------- | | `mp3` | `.mp3` | Default; web, mobile, general storage | 24 kHz sample rate | | `wav` | `.wav` | Uncompressed; audio editors, processing | 24 kHz sample rate | | `ogg` | `.ogg` | Browser streaming, web apps | Opus codec at 48 kHz | | `opus` | `.opus` | Low-bandwidth streaming | Opus codec at 48 kHz | --- ## Configuration Reference | Environment Variable | Required | Default | Description | | -------------------- | -------- | ------- | ---------------------------------- | | `OPENAI_API_KEY` | Yes | — | OpenAI API key (starts with `sk-`) | Defaults for model (`tts-1`) and voice (`alloy`) are set in code; override per call via `tts.model` / `tts.voice` in the SDK or `--tts-model` / `--tts-voice` on the CLI. There are no `OPENAI_TTS_MODEL` / `OPENAI_TTS_VOICE` env vars. --- ## Feature Support Matrix | Feature | Supported | Notes | | ---------------------- | --------- | ---------------------------------- | | Text synthesis | Yes | | | AI response synthesis | Yes | Set `useAiResponse: true` | | HD quality | Yes | `quality: "hd"` maps to `tts-1-hd` | | Speed control | Yes | 0.25 – 4.0 | | Voice selection | Yes | 6 neural voices | | Multiple formats | Yes | mp3, wav, ogg, opus | | Streaming TTS | No | Batch synthesis only | | Pitch / volume control | No | Not supported by OpenAI TTS API | | Custom voices | No | Only built-in voices supported | --- ## Troubleshooting ### "OpenAI TTS API key not configured" The `OPENAI_API_KEY` environment variable is missing or was not loaded. ```bash # Check the variable is set echo $OPENAI_API_KEY # Set it for the current session export OPENAI_API_KEY=sk-... ``` Create or rotate keys at [https://platform.openai.com/api-keys](https://platform.openai.com/api-keys). ### "HTTP 429" — Rate limit exceeded You have hit OpenAI's TTS rate limits. Implement exponential backoff or reduce request concurrency. Rate limits are per-key and depend on your usage tier. ### "HTTP 400" — Request too long The input text exceeds 4,096 characters. Split long content into smaller chunks and synthesise each separately. ```typescript function chunkText(text: string, maxLen = 4000): string[] { const chunks: string[] = []; for (let i = 0; i < text.length; i += maxLen) { chunks.push(text.slice(i, i + maxLen)); } return chunks; } ``` ### "OpenAI TTS request timed out after 30 seconds" A network issue or overloaded API caused the request to time out. Retry the request — the error is marked retriable by NeuroLink's error system. ### Audio sounds distorted at high speed Speeds above 2.0 can introduce artifacts. Use `speed: 1.0` – `1.5` for natural-sounding output. --- ## See Also - [TTS Integration Guide](/docs/features/tts) — complete multi-provider TTS reference - [Audio Input (STT)](/docs/features/audio-input) — speech-to-text counterpart - [OpenAI Provider Guide](/docs/getting-started/providers/openai) — full OpenAI text generation provider - [ElevenLabs Provider Guide](/docs/getting-started/providers/elevenlabs) — alternative TTS provider with voice cloning --- **Need Help?** Join the [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## OpenAI Provider Guide # OpenAI Provider Guide **Access GPT-5.4, GPT-5, GPT-4o, o-series reasoning models, and embedding models through the OpenAI API** ------ | --------------------------- | | `openai` | Canonical provider name | | `gpt` | Short alias for convenience | | `chatgpt` | Alternative alias | These aliases are registered in `src/lib/factories/providerRegistry.ts`. --- ## Quick Start ### 1. Get Your API Key 1. Visit [platform.openai.com/api-keys](https://platform.openai.com/api-keys) 2. Sign in or create an account 3. Click **Create new secret key** 4. Copy your new API key (starts with `sk-`) ### 2. Configure Environment Add to your `.env` file: ```bash # Required: Your OpenAI API key OPENAI_API_KEY=sk-your-key-here # Optional: Override default model (defaults to gpt-4o-mini) OPENAI_MODEL=gpt-4o ``` > **`OPENAI_API_KEY` also configures decisions.** The same variable configures the > [OpenAI Decisions provider](/docs/getting-started/providers/openai-decisions) (`openai-decisions`, which > serves `decide()`). So setting it for chat also lets NeuroLink's built-in > features send decision requests to OpenAI when no TypeSafe, Laya, XOR, SubQ, > Perplexity or Cloudflare Clef provider is configured, and context compaction > needs no other opt-in to do so. Those are paid calls, and they fail open. To > avoid that, pass the key through the SDK as `credentials.openai.apiKey` instead > of the environment, and keep it out of `.env` too: the SDK and the CLI load that > file into the environment, so an `OPENAI_API_KEY` line like the one above would > still configure decisions. See > [What is sent to OpenAI](/docs/getting-started/providers/openai-decisions#what-is-sent-to-openai) and > [One key, two providers](/docs/getting-started/providers/openai-decisions#one-key-two-providers). > > If you point the chat provider at a gateway (LiteLLM, vLLM and the like) with > `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL`, the key is the gateway's and is **not** > used for decisions by default: while any of them names a host other than > `https://api.openai.com`, NeuroLink's built-in features send nothing to OpenAI's > Decisions API (only a call that names `openai-decisions` does, with that key). See > [A gateway's key](/docs/getting-started/providers/openai-decisions#a-gateways-key-is-never-used-for-the-default). ### 3. Test the Setup ```typescript const ai = new NeuroLink(); const result = await ai.generate({ input: { text: "Explain quantum computing in simple terms" }, provider: "openai", model: "gpt-4o", }); console.log(result.content); ``` ```bash # Quick generation pnpm run cli -- generate "Hello from GPT!" \ --provider openai # Use specific model pnpm run cli -- generate "Write a haiku about AI" \ --provider openai \ --model "gpt-4o" # Interactive loop mode pnpm run cli -- loop \ --provider openai \ --model "gpt-4o-mini" ``` --- ## Supported Models ### Available Models (from `OpenAIModels` enum) | Enum Key | Model ID | Series | Context Window | Notes | | --------------------- | --------------------- | ------------ | -------------- | ------------------------ | | `GPT_6_ASTRA` | `gpt-6-astra` | GPT-6 | 1.05M | **New** (September 2026) | | `GPT_6_SOL` | `gpt-6-sol` | GPT-6 | 1.05M | **New** (September 2026) | | `GPT_6_LUNA` | `gpt-6-luna` | GPT-6 | 1.05M | **New** (September 2026) | | `GPT_5_4` | `gpt-5.4` | GPT-5.4 | 1.05M | **New** (March 2026) | | `GPT_5_4_MINI` | `gpt-5.4-mini` | GPT-5.4 | 400K | **New** (March 2026) | | `GPT_5_4_NANO` | `gpt-5.4-nano` | GPT-5.4 | 400K | **New** (March 2026) | | `GPT_5_3_CODEX` | `gpt-5.3-codex` | GPT-5.3 | 400K | | | `GPT_5_2` | `gpt-5.2` | GPT-5.2 | 400K | | | `GPT_5_2_CHAT_LATEST` | `gpt-5.2-chat-latest` | GPT-5.2 | 128K | | | `GPT_5_2_PRO` | `gpt-5.2-pro` | GPT-5.2 | 400K | | | `GPT_5_2_CODEX` | `gpt-5.2-codex` | GPT-5.2 | 400K | | | `GPT_5_1` | `gpt-5.1` | GPT-5.1 | 400K | | | `GPT_5_1_CHAT_LATEST` | `gpt-5.1-chat-latest` | GPT-5.1 | 128K | | | `GPT_5_1_CODEX` | `gpt-5.1-codex` | GPT-5.1 | 400K | | | `GPT_5_1_CODEX_MAX` | `gpt-5.1-codex-max` | GPT-5.1 | 400K | | | `GPT_5_1_CODEX_MINI` | `gpt-5.1-codex-mini` | GPT-5.1 | 400K | | | `GPT_5` | `gpt-5` | GPT-5 | 400K | | | `GPT_5_MINI` | `gpt-5-mini` | GPT-5 | 400K | | | `GPT_5_NANO` | `gpt-5-nano` | GPT-5 | 400K | | | `GPT_5_PRO` | `gpt-5-pro` | GPT-5 | 400K | | | `GPT_5_CHAT_LATEST` | `gpt-5-chat-latest` | GPT-5 | 128K | | | `GPT_5_CODEX` | `gpt-5-codex` | GPT-5 | 400K | | | `GPT_OSS_120B` | `gpt-oss-120b` | GPT OSS | 128K | | | `GPT_OSS_20B` | `gpt-oss-20b` | GPT OSS | 128K | | | `GPT_4_1` | `gpt-4.1` | GPT-4.1 | 1M | | | `GPT_4_1_MINI` | `gpt-4.1-mini` | GPT-4.1 | 1M | | | `GPT_4_1_NANO` | `gpt-4.1-nano` | GPT-4.1 | 1M | | | `GPT_4O` | `gpt-4o` | GPT-4o | 128K | | | `GPT_4O_MINI` | `gpt-4o-mini` | GPT-4o | 128K | **Default model** | | `O3` | `o3` | O-Series | 200K | | | `O3_MINI` | `o3-mini` | O-Series | 200K | | | `O3_PRO` | `o3-pro` | O-Series | 200K | | | `O4_MINI` | `o4-mini` | O-Series | 200K | | | `O1` | `o1` | O-Series | 200K | | | `O1_PREVIEW` | `o1-preview` | O-Series | 128K | Deprecated | | `O1_MINI` | `o1-mini` | O-Series | 128K | **Deprecated** | | `GPT_4` | `gpt-4` | GPT-4 Legacy | 8K | | | `GPT_4_TURBO` | `gpt-4-turbo` | GPT-4 Legacy | 128K | | | `GPT_3_5_TURBO` | `gpt-3.5-turbo` | Legacy | 16K | | Context window sizes are sourced from `src/lib/constants/contextWindows.ts`. Models without explicit entries use the provider default of 128K. ### Default Model The default model when no model is specified is **`gpt-4o-mini`** (set via `OpenAIModels.GPT_4O_MINI` in the provider registry). This can be overridden with the `OPENAI_MODEL` environment variable. > **Note:** When using NeuroLink SDK/CLI, the default is `gpt-4o-mini`. When instantiating `OpenAIProvider` directly without setting `OPENAI_MODEL`, the internal fallback is `gpt-5.4`. ### Model Selection by Use Case ```typescript const ai = new NeuroLink(); // Fast, cost-effective responses const quickResult = await ai.generate({ input: { text: "Summarize this text..." }, provider: "openai", model: "gpt-4o-mini", }); // Balanced multimodal performance const balancedResult = await ai.generate({ input: { text: "Analyze this code..." }, provider: "openai", model: "gpt-4o", }); // Latest flagship model const flagshipResult = await ai.generate({ input: { text: "Design a distributed system" }, provider: "openai", model: "gpt-5.4", }); // Deep reasoning with o-series const reasoningResult = await ai.generate({ input: { text: "Prove this mathematical theorem..." }, provider: "openai", model: "o3", }); // Large context with GPT-4.1 (1M tokens) const largeContextResult = await ai.generate({ input: { text: "Analyze this entire codebase..." }, provider: "openai", model: "gpt-4.1", }); ``` --- ## Multimodal Capabilities Models listed in `VISION_CAPABILITIES` for the `openai` provider support image analysis. This includes the GPT-5 family, GPT-4.1 family, GPT-4o family, and o-series models. ### Image Analysis ```typescript const result = await ai.generate({ input: { text: "Describe what you see in this image", images: ["data:image/jpeg;base64,..."], }, provider: "openai", model: "gpt-4o", }); ``` ```bash # From file path (CLI) pnpm run cli -- generate "Describe this image" \ --provider openai \ --model gpt-4o \ --image ./photo.jpg ``` The provider supports up to **10 images per request** (defined in `IMAGE_LIMITS` in `src/lib/adapters/providerImageAdapter.ts`). --- ## Embedding Support The OpenAI provider implements both `embed()` and `embedMany()` methods for generating vector embeddings. ### Default Embedding Model The default embedding model is **`text-embedding-3-small`**. This can be overridden with the `OPENAI_EMBEDDING_MODEL` environment variable. > **Note:** The `OPENAI_EMBEDDING_MODEL` env var is read by `getDefaultEmbeddingModel()`, but the public `embed()`/`embedMany()` methods fall back to `text-embedding-3-small` directly when no model argument is passed. To use a custom embedding model, pass it as the `modelName` parameter to `embed(text, modelName)`. ### Single Embedding ```typescript const ai = new NeuroLink(); // Generate a single embedding const result = await ai.generate({ input: { text: "Hello world" }, provider: "openai", }); // Or use the provider directly const embedding = await provider.embed("Hello world"); // Returns: number[] (e.g., 1536-dimensional vector) ``` ### Batch Embeddings ```typescript const embeddings = await provider.embedMany([ "First document", "Second document", "Third document", ]); // Returns: number[][] (array of embedding vectors) ``` ### Custom Embedding Model ```typescript // Use a specific embedding model const embedding = await provider.embed("Hello world", "text-embedding-3-large"); ``` ### Server Endpoints Embeddings are also available via server routes: - `POST /api/agent/embed` -- Single text embedding - `POST /api/agent/embed-many` -- Batch text embeddings --- ## Tool / Function Calling The OpenAI provider fully supports tool use (`supportsTools()` returns `true`). Tools are validated and filtered for OpenAI compatibility before being sent to the API. ```typescript const weatherTool = tool({ description: "Get current weather for a location", parameters: z.object({ location: z.string().describe("City name"), }), execute: async ({ location }) => { return { temperature: 72, condition: "sunny", location }; }, }); const result = await ai.generate({ input: { text: "What's the weather in Tokyo?" }, provider: "openai", model: "gpt-4o", tools: { get_weather: weatherTool }, }); ``` ### Tool Limits The provider enforces a maximum tool count (default: 150, configurable via the `OPENAI_MAX_TOOLS` environment variable). Tools exceeding this limit are silently truncated. ### Tool Validation The provider performs OpenAI-specific validation on each tool before sending: - Tools must have a `description` (string) and `execute` (function) - Parameters must be either a Zod schema or a valid JSON schema with `type: "object"` - Invalid tools are filtered out with a warning log --- ## Streaming Responses ```typescript const stream = await ai.stream({ input: { text: "Write a detailed article about AI" }, provider: "openai", model: "gpt-4o", }); for await (const chunk of stream.stream) { process.stdout.write(chunk.content); } ``` The streaming implementation is NeuroLink's own HTTP + SSE client (`src/lib/providers/openaiChatCompletionsBase.ts`), which parses the server-sent event stream directly and handles both text and tool-call chunks. Multi-step tool execution is supported with configurable `maxSteps`. ### CLI Streaming ```bash pnpm run cli -- stream "Write a story about a robot" \ --provider openai \ --model gpt-4o ``` --- ## Proxy Support The OpenAI provider uses `createProxyFetch()` to route API requests through a proxy when configured. The proxy is detected from standard environment variables: ```bash # HTTPS proxy (recommended for OpenAI API calls) HTTPS_PROXY=http://proxy.example.com:8080 # HTTP proxy HTTP_PROXY=http://proxy.example.com:8080 # Catch-all proxy ALL_PROXY=http://proxy.example.com:8080 # SOCKS proxy SOCKS_PROXY=socks5://proxy.example.com:1080 # Bypass proxy for specific hosts NO_PROXY=localhost,127.0.0.1,.internal.example.com ``` Priority order: protocol-specific (`HTTPS_PROXY` / `HTTP_PROXY`) > `ALL_PROXY` > `SOCKS_PROXY`. Both the generation/streaming requests and embedding requests use proxy-aware fetch. --- ## Configuration Reference ### Environment Variables | Variable | Description | Default | Required | | ------------------------ | ------------------------------------------ | ------------------------ | -------- | | `OPENAI_API_KEY` | API key for authentication | - | Yes | | `OPENAI_MODEL` | Default model to use | `gpt-4o-mini` | No | | `OPENAI_EMBEDDING_MODEL` | Default embedding model | `text-embedding-3-small` | No | | `OPENAI_MAX_TOOLS` | Maximum number of tools per request | `150` | No | | `HTTPS_PROXY` | HTTPS proxy URL | - | No | | `HTTP_PROXY` | HTTP proxy URL | - | No | | `ALL_PROXY` | Catch-all proxy URL | - | No | | `NO_PROXY` | Comma-separated list of proxy bypass hosts | - | No | ### CLI Provider Options | Flag | Values | Description | | ------------------- | -------------------------- | --------------------- | | `--provider` / `-p` | `openai`, `gpt`, `chatgpt` | Use OpenAI provider | | `--model` / `-m` | model ID string | Specific model to use | | `--temperature` | 0.0 - 2.0 | Sampling temperature | | `--max-tokens` | integer | Maximum output tokens | --- ## Error Handling The OpenAI provider maps errors to specific error types: | Error Type | Condition | | --------------------- | -------------------------------------------------------- | | `AuthenticationError` | Invalid API key (`API_KEY_INVALID` or `invalid_api_key`) | | `RateLimitError` | Rate limit exceeded (`rate_limit_error`) | | `InvalidModelError` | Model not found (`model_not_found`) | | `NetworkError` | Timeout errors | | `ProviderError` | All other OpenAI API errors | ### Common Issues #### "Invalid OpenAI API key" ```bash # Verify key is set echo $OPENAI_API_KEY | head -c 10 # Expected: sk-xxxxxxxx... # Get new key at https://platform.openai.com/api-keys ``` #### "Rate limit exceeded" 1. Wait and retry (the error message includes timing guidance) 2. Reduce request frequency 3. Use a smaller model (e.g., `gpt-4o-mini` instead of `gpt-4o`) 4. Request a rate limit increase from OpenAI #### "Model not found" Verify the model ID matches one of the values in the `OpenAIModels` enum. Model IDs are case-sensitive. --- ## Best Practices ### Security - **Never commit API keys** to version control - Use environment variables or secrets management - Rotate API keys periodically ```bash # Use .env file (not committed to git) echo "OPENAI_API_KEY=sk-..." >> .env # Add to .gitignore echo ".env" >> .gitignore ``` ### Cost Optimization - Use `gpt-4o-mini` for routine tasks (significantly cheaper than `gpt-4o`) - Use `gpt-5-nano` for simple classification or extraction tasks - Reserve `gpt-5.2-pro` and `o3-pro` for tasks requiring maximum capability - Monitor token usage via the OpenAI dashboard --- ## Related Documentation - **[Provider Setup Guide](/docs/getting-started/provider-setup)** -- General provider configuration - **[OpenAI Decisions Provider](/docs/getting-started/providers/openai-decisions)** -- Typed `decide()` judgments on the same key - **[OpenAI Compatible Provider](/docs/getting-started/providers/openai-compatible)** -- For OpenRouter, vLLM, and other OpenAI-compatible endpoints - **[Azure OpenAI Provider](/docs/getting-started/providers/azure-openai)** -- Azure-hosted OpenAI models --- ## Additional Resources - **[OpenAI Platform](https://platform.openai.com)** -- Manage API keys and usage - **[OpenAI Documentation](https://platform.openai.com/docs)** -- Official API docs - **[OpenAI Pricing](https://openai.com/pricing)** -- Pricing details - **[OpenAI Models](https://platform.openai.com/docs/models)** -- Model specifications --- ## OpenRouter Provider Guide # OpenRouter Provider Guide **Access 300+ AI models from 60+ providers through a single unified API** ## Quick Start ### 1. Get Your API Key Sign up at [https://openrouter.ai](https://openrouter.ai) and get your API key from [https://openrouter.ai/keys](https://openrouter.ai/keys). ### 2. Configure Environment Add your API key to `.env`: ```bash # Required OPENROUTER_API_KEY=sk-or-v1-... # Optional: Attribution (shows in OpenRouter dashboard) OPENROUTER_REFERER=https://yourapp.com OPENROUTER_APP_NAME="Your App Name" # Optional: Override default model OPENROUTER_MODEL=anthropic/claude-3-5-sonnet ``` ### 3. Install NeuroLink ```bash npm install @juspay/neurolink # or pnpm add @juspay/neurolink ``` ### 4. Start Using OpenRouter ```typescript const ai = new NeuroLink({ providers: [{ name: "openrouter", config: { apiKey: process.env.OPENROUTER_API_KEY, }, }], }); // Use default model (Claude 3.5 Sonnet) const result = await ai.generate({ input: { text: "What are the benefits of TypeScript?" }, }); console.log(result.content); ``` ```bash # Quick generation npx @juspay/neurolink generate "Hello from OpenRouter!" \ --provider openrouter # Use specific model npx @juspay/neurolink gen "Write a haiku about AI" \ --provider openrouter \ --model "openai/gpt-4o" # Interactive loop mode npx @juspay/neurolink loop \ --provider openrouter \ --model "anthropic/claude-3-5-sonnet" ``` --- ## Supported Models OpenRouter provides access to 300+ models. Here are the most popular: ### Anthropic Claude ```typescript // Latest models "anthropic/claude-3-5-sonnet"; // Best overall - 200K context "anthropic/claude-3-5-haiku"; // Fast & affordable - 200K context "anthropic/claude-3-opus"; // Most capable - 200K context ``` ### OpenAI ```typescript // GPT-4 series "openai/gpt-4o"; // Latest GPT-4 Omni "openai/gpt-4o-mini"; // Fast & affordable GPT-4 "openai/gpt-4-turbo"; // GPT-4 Turbo "openai/gpt-4"; // Original GPT-4 // GPT-3.5 "openai/gpt-3.5-turbo"; // Fast & cheap ``` ### Google ```typescript // Gemini models "google/gemini-2.0-flash"; // Latest Gemini - 1M context "google/gemini-1.5-pro"; // Gemini Pro - 1M context "google/gemini-1.5-flash"; // Fast Gemini ``` ### Meta Llama ```typescript // Llama 3.1 series "meta-llama/llama-3.1-405b-instruct"; // Largest open model "meta-llama/llama-3.1-70b-instruct"; // Balanced performance "meta-llama/llama-3.1-8b-instruct"; // Fast & efficient ``` ### Mistral AI ```typescript // Mistral models "mistralai/mistral-large"; // Most capable Mistral "mistralai/mixtral-8x22b-instruct"; // Large MoE model "mistralai/mixtral-8x7b-instruct"; // Efficient MoE ``` ### Free Models OpenRouter provides free access to select models: ```typescript // Popular free models "google/gemini-2.0-flash-exp:free"; "meta-llama/llama-3.1-8b-instruct:free"; "microsoft/phi-3-medium-128k-instruct:free"; ``` ### Browse All Models - **Web Dashboard**: [https://openrouter.ai/models](https://openrouter.ai/models) - **API**: Dynamically fetched via `provider.getAvailableModels()` --- ## Model Selection Guide ### By Use Case | Use Case | Recommended Model | Why | | ----------------------- | ----------------------------------- | ------------------------------------------- | | **General Chat** | `anthropic/claude-3-5-sonnet` | Best balance of quality, speed, and cost | | **Code Generation** | `openai/gpt-4o` | Excellent code understanding and generation | | **Long Documents** | `google/gemini-1.5-pro` | 1M token context window | | **Fast Responses** | `anthropic/claude-3-5-haiku` | Ultra-fast with good quality | | **Cost Optimization** | `openai/gpt-4o-mini` | Cheapest GPT-4 class model | | **Development/Testing** | `google/gemini-2.0-flash-exp:free` | Free tier available | | **Open Source** | `meta-llama/llama-3.1-70b-instruct` | Best open source model | | **Reasoning** | `anthropic/claude-3-opus` | Superior reasoning capabilities | ### By Performance Characteristics #### Speed Priority ```typescript // Fastest models (= MAX_DAILY_COST) { throw new Error("Daily budget exceeded"); } const result = await ai.generate({ input: { text: prompt }, enableAnalytics: true, }); dailyCost += result.analytics?.cost || 0; return result; } ``` ### 3. Rate Limiting Awareness OpenRouter has rate limits based on your account tier: ```typescript // Implement exponential backoff for rate limits async function generateWithRetry( prompt: string, maxRetries = 3, baseDelay = 1000, ) { for (let i = 0; i setTimeout(resolve, delay)); continue; } throw error; } } } ``` ### 4. Error Handling Patterns ```typescript // Comprehensive error handling async function generateSafely(prompt: string) { try { return await ai.generate({ input: { text: prompt }, provider: "openrouter", }); } catch (error) { if (error.message.includes("rate limit")) { // Handle rate limiting - wait and retry console.log("Rate limited, implementing backoff..."); await new Promise((resolve) => setTimeout(resolve, 5000)); return generateSafely(prompt); // Retry } else if (error.message.includes("insufficient_credits")) { // Handle insufficient credits console.error( "Out of credits! Add more at https://openrouter.ai/credits", ); throw new Error("Please add credits to continue"); } else if ( error.message.includes("model") && error.message.includes("not found") ) { // Handle model not available - fallback to different model console.log("Model unavailable, falling back to default"); return await ai.generate({ input: { text: prompt }, provider: "openrouter", model: "anthropic/claude-3-5-sonnet", // Reliable fallback }); } else { // Unknown error - log and rethrow console.error("OpenRouter error:", error.message); throw error; } } } ``` ### 5. Caching Strategies ```typescript // Implement response caching to reduce costs const responseCache = new Map(); const CACHE_TTL = 3600000; // 1 hour async function generateWithCache(prompt: string) { // Create cache key from prompt const cacheKey = createHash("sha256").update(prompt).digest("hex"); // Check cache const cached = responseCache.get(cacheKey); if (cached && Date.now() - cached.timestamp 10000) { console.warn(`Slow response: ${duration}ms`); } return result; } catch (error) { // Log errors to monitoring service console.error("Generation failed:", { prompt: prompt.substring(0, 100), duration: Date.now() - startTime, error: error.message, }); throw error; } } ``` --- ## Advanced Features ### 1. Dynamic Model Discovery ```typescript // getAvailableModels() is on the concrete provider class, not on the // AIProvider type that createProvider() returns, so narrow it for TypeScript. type ModelLister = { getAvailableModels(): Promise }; // Get all available models at runtime const provider = (await ProviderFactory.createProvider( "openrouter", )) as unknown as ModelLister; const models = await provider.getAvailableModels(); console.log(`${models.length} models available`); console.log("Sample models:", models.slice(0, 10)); // Filter models by provider const claudeModels = models.filter((m) => m.startsWith("anthropic/")); const openaiModels = models.filter((m) => m.startsWith("openai/")); console.log(`Claude models: ${claudeModels.length}`); console.log(`OpenAI models: ${openaiModels.length}`); ``` ### 2. Multi-Model Comparison ```typescript // Compare outputs from different models async function compareModels(prompt: string) { const models = [ "anthropic/claude-3-5-sonnet", "openai/gpt-4o", "google/gemini-1.5-pro", ]; const results = await Promise.all( models.map(async (model) => { const result = await ai.generate({ input: { text: prompt }, provider: "openrouter", model, enableAnalytics: true, }); return { model, content: result.content, cost: result.analytics?.cost, tokens: result.analytics?.tokens.total, time: result.analytics?.responseTime, }; }), ); // Analyze results console.table(results); return results; } ``` ### 3. Attribution Tracking ```typescript // Track usage in OpenRouter dashboard with custom attribution const ai = new NeuroLink({ providers: [ { name: "openrouter", config: { apiKey: process.env.OPENROUTER_API_KEY, // Shows up on openrouter.ai/activity dashboard referer: "https://myapp.com", appName: "My AI Application", }, }, ], }); // All requests will show attribution in dashboard const result = await ai.generate({ input: { text: "Hello!" }, }); ``` ### 4. Privacy Modes OpenRouter supports different privacy modes through model suffixes: ```typescript // Standard routing (default) "anthropic/claude-3-5-sonnet"; // Moderated (filtered for safety) "anthropic/claude-3-5-sonnet:moderated"; // Extended (longer timeout for large requests) "anthropic/claude-3-5-sonnet:extended"; // Free tier (when available) "google/gemini-2.0-flash-exp:free"; ``` --- ## CLI Usage ### Basic Commands ```bash # Use default model npx @juspay/neurolink generate "Hello OpenRouter" \ --provider openrouter # Specify model npx @juspay/neurolink gen "Write code" \ --provider openrouter \ --model "openai/gpt-4o" # Interactive loop mode npx @juspay/neurolink loop \ --provider openrouter \ --model "anthropic/claude-3-5-sonnet" # With temperature control npx @juspay/neurolink gen "Be creative" \ --provider openrouter \ --temperature 0.9 # With max tokens npx @juspay/neurolink gen "Write a long story" \ --provider openrouter \ --max-tokens 2000 ``` ### Model Comparison via CLI ```bash # Compare different models for model in "anthropic/claude-3-5-sonnet" "openai/gpt-4o" "google/gemini-1.5-pro"; do echo "Testing $model:" npx @juspay/neurolink gen "What is AI?" \ --provider openrouter \ --model "$model" echo "---" done ``` --- ## Pricing & Cost Management ### Understanding Costs OpenRouter charges per token with transparent pricing: - **Input tokens**: Cost to process your prompt - **Output tokens**: Cost to generate the response - **Caching**: Some models support prompt caching to reduce costs View current pricing at [https://openrouter.ai/models](https://openrouter.ai/models) ### Cost Comparison (Approximate) | Model | Input (per 1M tokens) | Output (per 1M tokens) | Best For | | ----------------------------- | --------------------- | ---------------------- | ----------------- | | `openai/gpt-4o-mini` | $0.15 | $0.60 | Cost optimization | | `google/gemini-2.0-flash` | $0.075 | $0.30 | Fast & cheap | | `anthropic/claude-3-5-haiku` | $0.25 | $1.25 | Speed & value | | `anthropic/claude-3-5-sonnet` | $3.00 | $15.00 | Balanced | | `openai/gpt-4o` | $2.50 | $10.00 | Code generation | | `anthropic/claude-3-opus` | $15.00 | $75.00 | Complex reasoning | ### Managing Your Budget ```typescript // Track spending across requests class BudgetTracker { private totalSpent = 0; private dailyLimit = 50.0; // $50/day async generate(prompt: string) { if (this.totalSpent >= this.dailyLimit) { throw new Error(`Daily budget of $${this.dailyLimit} exceeded`); } const result = await ai.generate({ input: { text: prompt }, provider: "openrouter", enableAnalytics: true, }); this.totalSpent += result.analytics?.cost || 0; console.log(`Spent: $${this.totalSpent.toFixed(4)} / $${this.dailyLimit}`); return result; } reset() { this.totalSpent = 0; } } const tracker = new BudgetTracker(); ``` --- ## Troubleshooting ### Common Issues #### 1. "Invalid API key" **Problem**: API key not set or incorrect. **Solution**: ```bash # Check if key is set echo $OPENROUTER_API_KEY # Get your key at https://openrouter.ai/keys export OPENROUTER_API_KEY=sk-or-v1-... # Add to .env file echo "OPENROUTER_API_KEY=sk-or-v1-..." >> .env ``` #### 2. "Rate limit exceeded" **Problem**: Too many requests in a short time. **Solution**: - Implement exponential backoff (see Best Practices above) - Upgrade your account at https://openrouter.ai/credits - Reduce request frequency - Use response caching #### 3. "Insufficient credits" **Problem**: Account balance is too low. **Solution**: ```bash # Check balance at https://openrouter.ai/credits # Add credits to your account # Set up auto-recharge for uninterrupted service ``` #### 4. "Model not found" **Problem**: Model name is incorrect or unavailable. **Solution**: ```bash # Check available models npx @juspay/neurolink models --provider openrouter # Or visit https://openrouter.ai/models # Use exact model ID format: "provider/model-name" ``` #### 5. "Request timeout" **Problem**: Request took too long. **Solution**: ```typescript // Increase timeout const result = await ai.generate({ input: { text: "Long task..." }, provider: "openrouter", timeout: 60000, // 60 seconds }); // Or use extended model variant const result = await ai.generate({ input: { text: "Long task..." }, provider: "openrouter", model: "anthropic/claude-3-5-sonnet:extended", }); ``` --- ## Comparison with Other Providers ### OpenRouter vs Direct Provider Access | Feature | OpenRouter | Direct Provider | | ---------------- | -------------------------- | ------------------------ | | **Model Access** | 300+ models, 60+ providers | Single provider's models | | **Setup** | One API key | Multiple API keys | | **Failover** | Automatic | Manual implementation | | **Pricing** | Competitive, transparent | Varies by provider | | **Rate Limits** | Unified limits | Provider-specific | | **Dashboard** | Centralized tracking | Separate dashboards | | **Switching** | Instant (same API) | Code changes required | ### When to Use OpenRouter **Use OpenRouter when:** - You want to experiment with multiple models - You need automatic failover for high availability - You want simplified billing across providers - You're building multi-model applications - You want to avoid vendor lock-in **Use Direct Providers when:** - You only need one specific model - You need provider-specific features (e.g., AWS Bedrock's VPC integration) - You have existing provider integrations - Your organization has enterprise agreements with specific providers --- ## Related Documentation - **[LiteLLM Provider](/docs/getting-started/providers/litellm)** - Alternative multi-provider solution - **[OpenAI Compatible](/docs/getting-started/providers/openai-compatible)** - OpenAI-compatible endpoints - **[Provider Setup Guide](/docs/getting-started/provider-setup)** - General provider configuration - **[Cost Optimization Guide](/docs/cookbook/cost-optimization)** - Reduce AI costs --- ## Additional Resources - **[OpenRouter Website](https://openrouter.ai)** - Main website - **[OpenRouter Models](https://openrouter.ai/models)** - Browse all models - **[OpenRouter Dashboard](https://openrouter.ai/activity)** - Usage tracking - **[OpenRouter Docs](https://openrouter.ai/docs)** - Official documentation - **[OpenRouter API Reference](https://openrouter.ai/docs/api-reference)** - API docs --- **Need Help?** Join our [GitHub Discussions](https://github.com/juspay/neurolink/discussions) or open an [issue](https://github.com/juspay/neurolink/issues). --- ## OVHcloud AI Endpoints Provider Guide # OVHcloud AI Endpoints Provider Guide OVHcloud AI Endpoints is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/ovhcloud.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status**: this entry is **docs- and roster-verified, not > yet live-verified**. It was built entirely from OVHcloud's own public > documentation pages and one unauthenticated `GET /v1/models` call — no > account was created, no key was issued, and no authenticated or `POST` > request was ever sent. `evidence.liveMatrix` is `null` until someone runs > the credentialed matrix (see [Live verification](/docs/provider-integration/tiers/tier-2-catalog-entry#live-verification) > below). ## Quick Start ### 1. Get an API key 1. Visit: https://www.ovhcloud.com/en/public-cloud/ai-endpoints/ and click Start now, which signs you in to (or creates) an OVHcloud Public Cloud manager account 2. In the manager, open Public Cloud > your project > AI & Machine Learning > AI Endpoints, and add a payment method to the project — OVHcloud > states that projects in Discovery mode (no payment method) cannot use > the service 3. Create an AI Endpoints API access token in that section; it is shown only once, so store it yourself, and note it can be given an expiration date and revoked 4. Set `OVH_AI_ENDPOINTS_ACCESS_TOKEN` in your .env file (this is the exact variable name OVHcloud's own code samples use) ### 2. Configure ```bash export OVH_AI_ENDPOINTS_ACCESS_TOKEN=your-access-token export OVHCLOUD_MODEL=gpt-oss-120b # optional — overrides the default model export OVHCLOUD_BASE_URL=https://oai.endpoints.kepler.ai.cloud.ovh.net/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "ovhcloud", model: "gpt-oss-120b", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider ovhcloud ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "ovhcloud", credentials: { ovhcloud: { apiKey: process.env.OVH_AI_ENDPOINTS_ACCESS_TOKEN }, }, }); ``` --- ## Models | Model | Context | Vision | Tools | $/M in · out | Notes | | ------------------------------------- | ------- | ------ | ----- | ------------- | --------------------------------------------------------------------------------------------------------------- | | `gpt-oss-120b` ⭐ | 131K | no | yes | $0.09 / $0.47 | Recommended — the vendor's own example model; docs confirm streaming, tools, reasoning, json_object/json_schema | | `gpt-oss-20b` | 131K | no | yes | $0.05 / $0.18 | Smaller gpt-oss sibling; roster-listed, catalog-page confirmed; fallback | | `Qwen3.6-27B` | 262K | yes | yes | $0.47 / $3.19 | Visual LLM (New); catalog-page confirmed; fallback | | `Qwen3.8-27B` | 262K | yes | yes | $0.47 / $3.19 | Visual LLM (New), newer sibling of 3.6; catalog-page confirmed | | `Qwen3.5-397B-A17B` | 262K | yes | yes | $0.71 / $4.25 | Largest MoE in the roster (397B params, ~17B active); catalog-page confirmed | | `Qwen3.5-9B` | 262K | yes | yes | $0.12 / $0.18 | Smallest of the Qwen3.x visual family; catalog-page confirmed | | `Meta-Llama-3_3-70B-Instruct` | 131K | no | yes | $0.74 / $0.74 | Plain non-reasoning instruct model; catalog-page confirmed | | `Qwen2.5-VL-72B-Instruct` | 32K | yes | no | $1.01 / $1.01 | Dedicated vision-language model; `models.visionModel`. No tools per catalog page | | `Qwen3-Coder-30B-A3B-Instruct` | 262K | no | n/a | $0.07 / $0.26 | Live roster only — not yet on the marketing catalog page as of 2026-09-28 | | `Mistral-Small-3.2-24B-Instruct-2506` | 131K | no | n/a | $0.10 / $0.31 | Live roster only — not yet on the marketing catalog page as of 2026-09-28 | | `Mistral-7B-Instruct-v0.3` | 65K | no | n/a | $0.11 / $0.11 | Live roster only — not yet on the marketing catalog page as of 2026-09-28 | | `Mistral-Nemo-Instruct-2407` | 65K | no | n/a | $0.14 / $0.14 | Live roster only — not yet on the marketing catalog page as of 2026-09-28 | | `Qwen3Guard-Gen-8B` | 32K | no | no | free | Moderation/safety classifier, Beta — excluded from fallbacks/topModels | | `Qwen3Guard-Gen-0.6B` | 32K | no | no | free | Smaller moderation/safety classifier, Beta — excluded from fallbacks/topModels | Context window and output cap per model are the live, unauthenticated `GET /v1/models` response's own `context_length` / `max_completion_tokens` fields (retrieved 2026-09-28). Pricing is that same response's per-token USD figures converted to $/MTok, cross-checked against the EUR prices on OVHcloud's public catalog page where a model appears there. **Fallback order** when the default is unavailable: `gpt-oss-20b` → `Meta-Llama-3_3-70B-Instruct` → `Qwen3.6-27B` → `Mistral-Small-3.2-24B-Instruct-2506` → `Qwen3.5-9B`. ### Out-of-scope (non-chat) endpoints OVHcloud AI Endpoints also serves speech-to-text (`whisper-large-v3`, `whisper-large-v3-turbo`), text-to-speech (four NVIDIA Riva voices), image generation (`stable-diffusion-xl-base-v10`) and embeddings (`bge-m3`, `bge-multilingual-gemma2`, `Qwen3-Embedding-8B`) on the same platform and base URL prefix. These are separate, non-chat-completions API shapes and are not part of this Tier-2 catalog entry, so `capabilities.embeddings` is `false` here even though the vendor documents embedding models elsewhere on the same platform. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for OVHcloud AI Endpoints — deliberately **credential-free**: | Probe | Result | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | **unauthenticated** GET `/v1/models`, HTTP 200, 2026-09-28 — 24 models returned; no key used | | Auth rejection | not probed — would require an authenticated request, which this credential-free onboarding does not send. The `errorRules` entry for authentication failures is taken verbatim from OVHcloud's written docs ("403 Forbidden: Authentication Failed"), not from a live probe | | Live capability sweep | **not run** (`evidence.liveMatrix` is `null`). `capabilities.tools`, `.streaming`, `.structuredOutput` and `.thinking` are set from OVHcloud's own getting-started guide, capabilities guide, and the `gpt-oss-120b` catalog card's "Supported Features" / "Output Formats" lists — not from a live request of any kind | Because no live request was ever made, treat every capability flag here as **doc-asserted, not wire-proven** until a credentialed pass fills in `evidence.liveMatrix` per [Tier-2 onboarding: Live verification](/docs/provider-integration/tiers/tier-2-catalog-entry#live-verification). --- ## Troubleshooting | Symptom | Cause | Fix | | ------------------------------- | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | Requests fail immediately | Project has no payment method attached ("Discovery mode") | Add a payment method to the Public Cloud project in the OVHcloud manager before creating/using an access token | | `Invalid or revoked ... token` | `OVH_AI_ENDPOINTS_ACCESS_TOKEN` unset, wrong, or revoked | Check/recreate the token under AI & Machine Learning > AI Endpoints in the OVHcloud manager | | Frequent 429s | Authenticated limit is 400 requests/minute per project per model | Pace requests and/or request a higher limit from OVHcloud support | | Model not found | The roster changed since 2026-09-28 | Pick a current id from the unauthenticated `GET /v1/models` roster | | Tool calls silently unsupported | `capabilities.tools` is model-dependent | Use a model the catalog page marks Function calling: Yes (e.g. `gpt-oss-120b`, not `Qwen2.5-VL-72B-Instruct`) | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration, and what a credentialed live-verification pass still needs to add - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Parasail Provider Guide # Parasail Provider Guide Parasail is a **Tier-2 catalog provider**: its integration is one JSON file (`src/lib/providers/catalog/parasail.json`) rather than hand-written code. That file is the source of truth for this page. The [Authentication page](https://docs.parasail.io/parasail-docs/api-reference/authentication.md) says "The API is fully OpenAI-compatible." > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** Parasail's `GET https://api.parasail.io/v1/models` needs a > key (an unauthenticated GET on 2026-09-29 answered HTTP 401), so the model ids > come from Parasail's public docs > ([Models page](https://docs.parasail.io/parasail-docs/products/overview/models.md), > retrieved 2026-09-29) and the roster has not been checked. No account was > created and no API key was used to build this entry. `evidence.liveMatrix` is > `null` until someone runs the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://www.saas.parasail.io/keys — the link the [Authentication page](https://docs.parasail.io/parasail-docs/api-reference/authentication.md) gives for getting an API key; sign-in was not attempted while building this entry 2. Create an API key and copy it when it is shown — the Authentication page steps read "Click Create API Key." and "Copy the key immediately—it's displayed only once." 3. Billing as the vendor states it: the [Pricing page](https://docs.parasail.io/parasail-docs/billing/pricing.md) says "To use models, create API keys, and access paid platform services, add a credit card. Without a card, you can still view the platform but can't use models or API keys." 4. Set `PARASAIL_API_KEY` in your .env file (the docs' examples use the environment variable `PARASAIL_API_KEY`) ### 2. Configure ```bash export PARASAIL_API_KEY=your-api-key export PARASAIL_MODEL=parasail-llama-33-70b-fp8 # optional — overrides the default model export PARASAIL_BASE_URL=https://api.parasail.io/v1 # optional ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "parasail", model: "parasail-llama-33-70b-fp8", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider parasail ``` Per-request credentials work as they do for other NeuroLink providers: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "parasail", credentials: { parasail: { apiKey: process.env.PARASAIL_API_KEY } }, }); ``` --- ## Billing The [Pricing page](https://docs.parasail.io/parasail-docs/billing/pricing.md) says "To use models, create API keys, and access paid platform services, add a credit card. Without a card, you can still view the platform but can't use models or API keys." The [Limits and Quotas page](https://docs.parasail.io/parasail-docs/operate-in-production/limits-and-quotas.md) has a rate-limit table with a product class "Serverless - Free" (RPM column "5"). The catalog's `billingPolicy` field takes one of three values and holds `no-free-tier` here as a placeholder; it is not a vendor statement of signup terms. --- ## Models | Model | Context | Max output | Vision | $/M in · out (cached) | Notes | | ---------------------------------------- | --------- | ---------- | ------ | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `parasail-llama-33-70b-fp8` ⭐ | 131,072 | 16,384 | no | $0.22 / $0.50 ($0.11) | NeuroLink default. Chat Completions guide example; Tools ✅ and Tool Choice ✅; Y under Guided JSON / JSON Schema, Regex and Choice. | | `parasail-llama-4-maverick-instruct-fp8` | 524,288 | 32,768 | no | $0.35 / $1.00 ($0.17) | Tools ✅ and Tool Choice ✅; Y under Guided JSON / JSON Schema, Regex and Choice. Fallback. | | `parasail-gpt-oss-120b` | 131,072 | 131,072 | no | $0.10 / $0.75 ($0.055) | Tools ✅ and Tool Choice ✅. Model-specific Notes page has "GPT-OSS reasoning control" and "Structured outputs with GPT-OSS" sections. Fallback. | | `parasail-gpt-oss-20b` | 131,072 | 131,072 | no | $0.03 / $0.15 ($0.02) | Tools ✅ and Tool Choice ✅. Same Model-specific Notes sections as `parasail-gpt-oss-120b`. Fallback. | | `parasail-deepseek-v4-flash` | 1,048,576 | 1,048,576 | no | $0.14 / $0.28 ($0.07) | Tools ✅ and Tool Choice ✅. Fallback. | | `parasail-deepseek-v4-pro` | 1,048,576 | 1,048,576 | no | $1.74 / $3.48 ($0.10) | Tools ✅ and Tool Choice ✅. Fallback. | | `parasail-kimi-k3` | 1,048,576 | 1,048,576 | no | $3.00 / $15.00 ($0.30) | Tools ✅ and Tool Choice ✅. Fallback. | | `parasail-glm-52` | 262,144 | 262,144 | no | $1.40 / $4.40 ($0.26) | Tools ✅ and Tool Choice ✅. Fallback. | | `parasail-qwen3p5-35b-a3b` | 262,144 | 262,144 | no | $0.15 / $1.00 ($0.05) | Tools ✅ and Tool Choice ✅; the Tool/Function Calling guide's Chat Completions example uses it. Fallback. | | `parasail-qwen25-vl-72b-instruct` | 128,000 | 128,000 | yes | $0.80 / $1.00 ($0.40) | The Multi-Modal guide's image example uses it, hence `vision: true` and `models.visionModel`. Tool/Function Calling guide: "also emits tool calls, but only reliably with" `tool_choice="required"`. Fallback. | | `parasail-gemma3-27b-it` | 131,072 | 131,072 | no | $0.08 / $0.45 ($0.04) | Y under Guided JSON / JSON Schema, Regex and Choice. Tool/Function Calling guide names it among models that "don't support the tools parameter today". Fallback. | | `parasail-minimax-m3` | 1,048,576 | 524,288 | no | $0.30 / $1.20 ($0.06) | Tools ✅ and Tool Choice ✅. Fallback. | Context window, max output and prices are read from the [Models page](https://docs.parasail.io/parasail-docs/products/overview/models.md) (retrieved 2026-09-29), which says "This catalog is generated daily from the live models endpoint." The [Pricing page](https://docs.parasail.io/parasail-docs/billing/pricing.md) shows the same input, output and cached-input figures for each of the 33 rows. The tool-calling markers come from the [Tool/Function Calling guide](https://docs.parasail.io/parasail-docs/guides/tool-function-calling.md) and the Y markers from the [Structured Output guide](https://docs.parasail.io/parasail-docs/guides/structured-output.md). The [Multi-Modal guide](https://docs.parasail.io/parasail-docs/guides/multi-modal.md) is the source for the one `vision: true`. `models.defaultContextWindow` (128,000) and `models.defaultMaxOutputTokens` (16,384) are placeholders the vendor does not publish as general values. They apply to model ids outside the catalog and equal the Context window cell of the Qwen2.5-VL 72B row and the Max output cell of the Llama 3.3 70B (FP8) row on the Models page. Each model's `status` is `production`, a value the catalog schema requires; it is not a vendor statement. Each `vision: false` is a placeholder for a boolean the schema requires, not a vendor statement. **Fallback order** when the default is unavailable: `parasail-llama-4-maverick-instruct-fp8` → `parasail-gpt-oss-120b` → `parasail-gpt-oss-20b` → `parasail-deepseek-v4-flash` → `parasail-deepseek-v4-pro` → `parasail-kimi-k3` → `parasail-glm-52` → `parasail-qwen3p5-35b-a3b` → `parasail-qwen25-vl-72b-instruct` → `parasail-gemma3-27b-it` → `parasail-minimax-m3`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `parasail-gpt-oss-120b`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Parasail — **docs-verified only, not yet live-verified**: | Probe | Result | | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://api.parasail.io/v1/models` answered HTTP 401 on 2026-09-29 — no key used, so the model ids are taken from the Models page (retrieved 2026-09-29) and the roster is not verified | | Billing | the Pricing page says "To use models, create API keys, and access paid platform services, add a credit card. Without a card, you can still view the platform but can't use models or API keys."; the Limits and Quotas page has a "Serverless - Free" rate-limit row; no signup was performed, 2026-09-29 | | Auth-failure shape | unauthenticated GETs of `/v1/models`, `/v1/chat/completions` and `/v1` each answered HTTP 401 with content-type `application/json;charset=ISO-8859-1` and the body text "Unauthorized. No bearer token provided." (plain text, no error code field), 2026-09-29; no POST was sent. `errorRules` match the statuses 401, 403, 404 and 429 from the Error responses table of the Chat Completions reference | | Tools / structured output | documented on the Tool/Function Calling and Structured Output guides; neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=parasail` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Documented error statuses The [Chat Completions reference](https://docs.parasail.io/parasail-docs/api-reference/chat-completions.md) says "Errors use OpenAI-compatible status codes and a JSON body with an `error` object (`message`, `type`, `code`)." and lists these statuses: | Status | Parasail's description | | ------ | -------------------------------------------------------------------------------------- | | `400` | Malformed request—invalid JSON, missing required field, or unsupported parameter value | | `401` | Missing or invalid API key | | `403` | API key lacks access to the requested model or resource | | `404` | Model or endpoint not found | | `429` | Rate limit or quota exceeded—back off and retry | | `500` | Internal server error—retry with exponential backoff | The [Tool/Function Calling guide](https://docs.parasail.io/parasail-docs/guides/tool-function-calling.md) says of models outside its table: "Depending on the model, a request with tools returns an error or plain text with no tool_calls." --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) - Parasail docs pages used for this entry: [Models](https://docs.parasail.io/parasail-docs/products/overview/models.md), [Pricing](https://docs.parasail.io/parasail-docs/billing/pricing.md), [Authentication](https://docs.parasail.io/parasail-docs/api-reference/authentication.md), [Chat Completions reference](https://docs.parasail.io/parasail-docs/api-reference/chat-completions.md), [Tool/Function Calling](https://docs.parasail.io/parasail-docs/guides/tool-function-calling.md), [Structured Output](https://docs.parasail.io/parasail-docs/guides/structured-output.md), [Multi-Modal](https://docs.parasail.io/parasail-docs/guides/multi-modal.md), [Model-specific Notes](https://docs.parasail.io/parasail-docs/products/overview/model-specific-notes.md), [Limits and Quotas](https://docs.parasail.io/parasail-docs/operate-in-production/limits-and-quotas.md) --- ## Pareto Inference Provider Guide # Pareto Inference Provider Guide > **Verification status:** this entry is **docs- and roster-verified only — > not yet live-verified.** It was onboarded credential-free: no Pareto > Inference API key was ever created or used. Every field below comes from > Pareto's public docs (`https://docs.paretoinference.com/`) and an > **unauthenticated** `GET /v1/models` call (no auth header). No `POST` > request was ever sent, so no generate, stream, tool-calling or > structured-output capability has been exercised end to end. Treat > `capabilities.tools` and `.thinking` as documentation-grade, not > wire-proven, until `evidence.liveMatrix` is filled in by a live run. Pareto Inference is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/pareto-inference.json`) rather than hand-written code. That file is the source of truth for everything on this page. ## Quick Start ### 1. Get an API key 1. Visit: https://paretoinference.com/dashboard and sign in 2. Add a payment card — Pareto has no free tier; a card and prepaid credits are required before a key is issued (https://docs.paretoinference.com/pricing) 3. Buy prepaid credits, then create your API key from the dashboard 4. Set `PARETO_INFERENCE_API_KEY` in your `.env` file ### 2. Configure ```bash export PARETO_INFERENCE_API_KEY=your-api-key export PARETO_INFERENCE_MODEL=z-ai/glm-5.3-flash # optional — overrides the default model export PARETO_INFERENCE_BASE_URL=https://api.paretoinference.com/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "pareto-inference", model: "z-ai/glm-5.3-flash", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider pareto-inference ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "pareto-inference", credentials: { "pareto-inference": { apiKey: process.env.PARETO_INFERENCE_API_KEY }, }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out · cached | Notes | | ----------------------- | --------------- | ------ | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `z-ai/glm-5.3-flash` ⭐ | not published\* | no | $0.09 / $0.30 (cached $0.018) | Only model Pareto serves. Max output documented as 1–131,072 tokens (default 131,072). \*Pareto publishes no context window; the catalog falls back to 131,072, the documented output ceiling, which is not a vendor context length. | \* Pareto's own docs state it does **not** disclose GLM 5.3 Flash's serving details ("We do not disclose the technical details of our GLM 5.3 Flash serving system"), and no context-window number appears on any public page. `models.defaultContextWindow` (131,072) is therefore a catalog fallback — the documented **output** ceiling, not a vendor context length — flagged in the catalog entry's description. Correct it once Pareto publishes a real figure or an authenticated probe reveals one. **Fallback order:** none — `z-ai/glm-5.3-flash` is the only model Pareto serves, so it is both the default and its own (schema-exempt) single-entry fallback list. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for Pareto Inference — and, just as importantly, what it does **not** yet record: | Probe | Result | | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | **unauthenticated** GET `/v1/models`, HTTP 200, 1 model (`z-ai/glm-5.3-flash`), 2026-09-28. No API key was used or required for this call. | | Auth rejection | Not probed. Would require a `POST` with an invalid key, which this credential-free onboarding pass does not send. Pareto's docs describe 401 as "the chat API key is missing, invalid, or no longer active," with no example error body. | | Live capability sweep | **Not run.** `evidence.liveMatrix` is `null`. `capabilities.tools` and `.thinking` are set from the vendor's own request-parameter table and its hedging language, not from an executed chat/stream/tool-call/schema request. `structuredOutput` and `toolsWithStreaming` are `false` because the same table hedges `response_format` and streamed tool calls with "Model support can differ" too. | Until a live run fills in `evidence.liveMatrix`, treat this provider as **documentation-grade**: the wire shape (base URL, auth header, request/ response field names) is well-documented and consistent with the standard OpenAI-compatible contract, but no NeuroLink call has actually exercised it. --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------------------- | -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | `Invalid Pareto Inference API key` | `PARETO_INFERENCE_API_KEY` unset, wrong, or expired | Pareto documents 401 as "the chat API key is missing, invalid, or no longer active" — check or replace the key in the dashboard | | 429 with `credit_exhausted` | Prepaid balance is empty | Buy more prepaid credits | | 429 with `credit_insufficient` | Held credits (reserved for `max_tokens`) are below what's needed | Lower `max_tokens`, or buy more credits | | 429 with `model_capacity` | The model itself is at capacity — not an account-level limit | Honor the `Retry-After` header and retry | | 502 mid-stream | The model request failed after the stream started | Retry the request; check whether a tool call already ran before retrying | | 503 | Temporary Pareto-side failure (e.g. maintenance, GPU outage) | Wait and retry; `Retry-After` gives the delay in seconds | | No context-window figure in the catalog | Pareto does not publish one and declines to disclose serving details | Treat `defaultContextWindow` as a catalog fallback (the documented output ceiling, not a vendor context length) until corrected by a real probe | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Perplexity Decisions Provider Guide # Perplexity Decisions Provider Guide **A provider of `decide`** — the same typed `boolean` / `choice` / `score` answers as [TypeSafe's Jev](/docs/getting-started/providers/typesafe), [Laya](/docs/getting-started/providers/laya), [XOR](/docs/getting-started/providers/xor), [SubQ](/docs/getting-started/providers/subq), [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef), [OpenAI Decisions](/docs/getting-started/providers/openai-decisions) and [ScaleDown](/docs/getting-started/providers/scaledown), from Perplexity's hosted Decisions API, and it also reads images. It emits no text at all. > This is not the [Perplexity text provider](/docs/getting-started/providers/perplexity) (`perplexity`, the > Sonar models), which serves `generate()` and `stream()`. The two share one API > key, which has a consequence worth reading before you set it. See > [What is sent to Perplexity](#what-is-sent-to-perplexity) and > [One key, two providers](#one-key-two-providers). --------------------- | ----------------------------------------------------------------------------------------------------------------- | | Provider id | `perplexity-decider` (no aliases) — distinct from `perplexity`, the Sonar text provider | | Inference type | `decide` only | | Model | `pplx-decider-v1-27b`; the API answers 400 to a missing or unknown model. `PERPLEXITY_DECIDER_MODEL` sets it | | Key | `PERPLEXITY_API_KEY`, shared with the Perplexity text provider, or `credentials.perplexityDecider.apiKey` | | Endpoint | `https://api.perplexity.ai/v1/decisions`; `PERPLEXITY_DECIDER_BASE_URL` can name another origin | | Media | images (PNG, JPEG or WebP), up to 8 per request; no video | | Questions per request | up to 128 | | Server input ceiling | under 262,144 tokens (state, questions and images); more is refused with an explicit 400, never cut off silently | | Images and that ceiling | billed as input tokens, and counted toward the ceiling at one token per 32 × 32 tile (measured) | | NeuroLink's state window | 100,000 estimated tokens: a deliberate local limit, not the server's | | Cost | $0.04 per million input tokens (image tokens included); output tokens are free. Perplexity's documented price | | Default timeout | 10 seconds plus 100 ms for each question (10.1 s for one, 22.8 s for 128); `timeoutMs` or `--timeout` replaces it | | Precedence | used automatically when TypeSafe, Laya, XOR and SubQ are not configured | Each limit, token rate and latency in this guide is either **measured on a real account in October 2026** or taken from Perplexity's documentation, and says which where it appears. Measured: the 128-question and 8-image caps, the 262,144-token input ceiling for the state, the questions and the images (nothing is cut off silently), characters per token for each kind of text, latency by input size and by question count, what an image costs, which image sizes stall (the 2,048-tile rule, checked at its edge: see [Images](#images)), and how the API answers a burst of requests. Documented and not tested: the 32 MiB request body, the price, and the option and level counts. Perplexity documents a limit of 10 requests per second for the account's tier (every organization, on every plan, with a token limit on large bursts), and a burst test on the one account tested saw the request limit act. --- ## Quick Start ### 1. Get a key Create one in the [Perplexity console](https://console.perplexity.ai). Any Perplexity API key works. ### 2. Configure Set the key in the environment: ```bash export PERPLEXITY_API_KEY=pplx-... # the key; see "One key, two providers" export PERPLEXITY_DECIDER_MODEL=pplx-decider-v1-27b # optional export PERPLEXITY_DECIDER_BASE_URL=https://api.perplexity.ai # optional; an origin ``` or in the config passed to the SDK, exactly as for any other provider. Values passed per call override the constructor's, which override the environment: ```typescript // For the whole instance const neurolink = new NeuroLink({ credentials: { perplexityDecider: { apiKey: process.env.MY_PERPLEXITY_KEY }, }, }); // Or for one call await neurolink.decide({ provider: "perplexity-decider", credentials: { perplexityDecider: { apiKey: process.env.MY_PERPLEXITY_KEY }, }, state: "The headphones sound great, but the battery died after two weeks.", questions: { defect: { type: "boolean", instructions: "Is a defect reported?" }, }, }); ``` `credentials.perplexityDecider` is its own slice. A key passed as `credentials.perplexity` belongs to the text provider and does not configure this one. `PERPLEXITY_BASE_URL`, which moves the text provider, is not read here; the override for this provider is `PERPLEXITY_DECIDER_BASE_URL`, and a trailing `/v1` on it is accepted. It must be `https://`; `http://` is accepted only for `localhost`, `127.0.0.1` and `[::1]`, because every request carries the key. ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.decide({ provider: "perplexity-decider", state: { title: "Battery died after two weeks", review: "The headphones sound great, but the battery stopped charging after two weeks.", }, questions: { defect: { type: "boolean", instructions: "Does the review report a defect?", }, sentiment: { type: "choice", instructions: "What is the overall sentiment of the review?", criteria: { positive: "Mostly satisfied", mixed: "Praise and complaints in one review", negative: "Mostly dissatisfied", }, }, severity: { type: "score", instructions: "How severe is the reported problem?", criteria: ["Cosmetic", "Inconvenient", "Product unusable"], }, }, }); const sentiment = readDecisionChoice(result.answers, "sentiment"); ``` NeuroLink's `boolean` question is sent to the API as its `noul` type, and the answer is read back as a `boolean`. A `boolean` answer carries a probability and no confidence of its own; a `choice` or `score` answer carries the confidence the API reports, which Perplexity describes as the model's own certainty estimate, not the top probability. Perplexity's API reference and quickstart do not call that confidence calibrated, and NeuroLink did not measure whether it is, so tune a threshold on it against your own labelled data. (The Hugging Face model card for the open-weights model describes its output as calibrated probabilities.) Perplexity also notes that identical requests occasionally differ in the second decimal place. Repeating a request returned the same numbers in NeuroLink's probe, but leave some margin when you set a threshold anyway. ### From the CLI The CLI reads the same environment variables: ```bash neurolink decide "The battery stopped charging after two weeks." \ --provider perplexity-decider \ --questions '{"defect":{"type":"boolean","instructions":"Is a defect reported?"}}' ``` The text output ends with a `Cost:` line, priced from the input tokens the API reports. --- ## Images Perplexity reads images alongside the `state`. TypeSafe, Laya, [SubQ](/docs/getting-started/providers/subq) and [ScaleDown](/docs/getting-started/providers/scaledown) do not read media. XOR reads one image and audio; Perplexity reads images only, and so do [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef), up to 4 of them, and [OpenAI Decisions](/docs/getting-started/providers/openai-decisions). In the probe of Perplexity's model it did read an image: asked red versus blue about one, it answered correctly at about 0.98 confidence. ```typescript const neurolink = new NeuroLink(); const result = await neurolink.decide({ provider: "perplexity-decider", state: "A product photo from a listing.", // Any mix of a file path, a Buffer and a data: URL images: ["./front.png", await readFile("./back.webp")], questions: { color: { type: "choice", instructions: "What color is the product?", criteria: { red: "Mostly red", blue: "Mostly blue" }, }, }, }); const color = readDecisionChoice(result.answers, "color"); console.log(result.mediaBytes); // encoded size of the images sent ``` From the CLI, pass `--image `, repeated for several: ```bash neurolink decide "What color is the square?" --provider perplexity-decider \ --image ./square.png \ --questions '{"color":{"type":"choice","instructions":"What color is the square?","criteria":{"red":"A red square","blue":"A blue square","green":"A green square"}}}' ``` On the wire the images go inside `state`: NeuroLink sends `state` as an array, your state first and then one OpenAI-style `image_url` part per image, each a base64 data URL. The API has no separate images field and rejects unknown fields. An image can also be the whole input (an image-only `state` was accepted in the probe); from the SDK, pass an empty string as `state` with `images`. The CLI always needs a state. The rules: - **Up to 8 images** per request. Measured: 8 images with three questions were accepted, and 9 images with one question were refused with a 400 whose message words the cap as "per question". NeuroLink applies the 8 to the request as a whole. - **PNG, JPEG or WebP only.** The type comes from the bytes, not the file extension. A GIF, or a `data:` URL of another type, is refused before any request, as a non-retryable `invalid_request`. The API refuses a GIF with a 400 too. - **Each is a Buffer, a local file path or a `data:` URL.** An `http(s)` URL is refused locally and never fetched. The API does not fetch URLs either: an `https` image URL returned a 400 in the probe. - **Each image may be at most 2,048 tiles of 32 × 32 pixels.** Round the width and the height to the nearest multiple of 32 and keep (width / 32) × (height / 32) at or under 2,048: by that count 1440 × 1440 (2,025 tiles) and 2048 × 1024 (2,048) fit, and 1600 × 1310 (2,050) does not. Perplexity documents this rule, and it was checked at its edge. Fitting sizes were answered in about a second: 1920 × 1080 (2,040 tiles) in 1.1 seconds, 2048 × 1024 (2,048, exactly the cap) in 1.3 and 1450 × 1450 in 1.1. That last one rounds to 45 tiles a side (45.3), 2,025 in all, where rounding up (46 a side, 2,116) would have failed. Oversized sizes stalled for about 56 seconds and came back as an HTML 504: 1600 × 1310 (2,050 tiles, two over), 1470 × 1470 (46 a side, 2,116, which would have fitted had each side been rounded down), 2048 × 2048 (4,096 tiles, tried twice) and 4000 × 3000 (11,750). So each side rounds to the nearest multiple of 32 and the cap is 2,048 tiles, as NeuroLink's check has it. The trigger is the tile count, not the file size (the 2048 × 2048 image was a 60 KB PNG) and not the raw pixel count: 1600 × 1310 is 2,096,000 pixels and stalled, while 2048 × 1024, at 2,097,152, did not. An oversized image is not refused with a 400, so NeuroLink reads each image's dimensions from its header and refuses it before any request, naming its size. An image whose dimensions cannot be read is sent as given. - **The whole request body may be at most 32 MiB**, Perplexity's documented limit, which the probe did not check. The limit applies to the encoded body, so the base64 form counts. A file over it is refused from its size, before it is read. - **No video.** `video` and `--video` are refused before any request with `Perplexity does not accept video.` - **Images are billed as input tokens.** Measured: about one input token for each 32 × 32 tile (1,024 pixels), billed like text, plus 95 to 103 more in the single-image requests measured. That is a fit to the sizes measured, not a documented rate: 1920 × 1080 (2,040 tiles) cost about 2,135 tokens, 1024 × 1024 (1,024 tiles) about 1,119, 512 × 512 (256 tiles) about 351, 2048 × 1024 (2,048 tiles) 2,151 and 1450 × 1450 (2,025 tiles) 2,128. The extra 95 to 103 looks like fixed overhead for the request, not a charge for each image: a request with eight images was counted as exactly 8 × 2,048 vision tokens, with its text only 52 tokens above the same text alone. A single-image request cannot tell the two apart, so this is a reading of the figures and not a documented rule. **Images count toward the 262,144-token input ceiling.** Measured: 1.1 million characters of text (250,624 input tokens) was answered, and the same text with eight 2,048-tile images was refused with a 400, `Total input tokens (250676 text + 16384 vision = 267060) exceeds maximum context length (262144)`. Each of those images counted as 2,048 vision tokens, one for each tile. So eight images at the cap take up to 16,384 tokens of the ceiling. NeuroLink's local window checks the state's text only, not the images or the questions, so a request that passes it can still be refused by the API for being over its input ceiling. The server words that refusal two ways, `Input length (…) exceeds or equals model's maximum context length (…)` for text alone and the `Total input tokens (… text + … vision = …) exceeds maximum context length (…)` above when images are in the request, and NeuroLink reports both as `max_tokens_exceeded`. - **The result carries `mediaBytes`**, the encoded size of the images sent. The `decide` spans carry `decision.images.count`, `decision.audio.count` and `decision.media.bytes`, and never any base64. --- ## When NeuroLink uses it Every built-in consumer of `decide` asks for the default decision provider. That is the first one that is configured, in the environment or in the `credentials` passed to the SDK, in the order TypeSafe, Laya, XOR, [SubQ](/docs/getting-started/providers/subq), Perplexity, [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef), [OpenAI Decisions](/docs/getting-started/providers/openai-decisions), then [ScaleDown](/docs/getting-started/providers/scaledown). TypeSafe counts with either of its keys, `TYPESAFE_API_KEY` or `AI_GATEWAY_API_KEY`. Laya and XOR each count only with both their key and their base URL. SubQ counts with its key alone, `SUBQ_API_KEY`. Perplexity counts with its key alone, a non-blank `PERPLEXITY_API_KEY` or `credentials.perplexityDecider.apiKey`. Cloudflare Clef counts only with both `CLOUDFLARE_API_KEY` and `CLOUDFLARE_ACCOUNT_ID`. OpenAI Decisions counts with its key alone, `OPENAI_API_KEY` or `credentials.openaiDecisions.apiKey`. ScaleDown counts with its key alone, `SCALEDOWN_API_KEY` or `credentials.scaledown.apiKey`, which no other provider reads. A caller can always name Perplexity with `provider: "perplexity-decider"`. So: - **Only a Perplexity key:** built-in features use Perplexity. - **A Perplexity key, plus TypeSafe's key, or Laya's or XOR's key and base URL, or `SUBQ_API_KEY`:** built-in features use TypeSafe, Laya, XOR or SubQ, in that order, whichever is configured. Perplexity runs only where a caller asks for `provider: "perplexity-decider"`. - **A Perplexity key, plus `CLOUDFLARE_API_KEY` and `CLOUDFLARE_ACCOUNT_ID`:** built-in features use Perplexity; Cloudflare Clef runs only where a caller asks for `provider: "cloudflare-clef"`. - **A Perplexity key, plus `SCALEDOWN_API_KEY`:** built-in features use Perplexity, which comes ahead of ScaleDown; ScaleDown runs only where a caller asks for `provider: "scaledown"`. - **A key for the text provider only:** the same as the first case. The key is shared, so the text provider's key also configures this one. See [One key, two providers](#one-key-two-providers). - **None of TypeSafe, Laya, XOR, SubQ, Perplexity, Cloudflare Clef, OpenAI Decisions or ScaleDown configured:** everything behaves exactly as it did without a decision model. The classifier router's `auto` gate counts the credentials given to the `NeuroLink` constructor, the environment and the request's own per-call credentials, so a per-call `credentials.perplexityDecider` can make `auto` pick `jev`. The other consumers NeuroLink wires itself (compaction and tool routing) send the surrounding request's credentials too, so they go to the caller's account. Where the built-in consumers use the default provider (what each one sends is listed in [What is sent to Perplexity](#what-is-sent-to-perplexity)): | Area | What the decision replaces | | ---------------------------------------------------------------- | --------------------------------------------------------------- | | [Model routing](/docs/features/classifier-router-jev-strategy) | difficulty + capabilities + risk + model pick in one round trip | | [Model catalogue](/docs/features/classifier-router-catalog) | one `choice` over the registry ranks all N candidates at once | | [Context budget](/docs/features/context-budget) | a rubric-placed scope reading lowers the compaction threshold | | [Relevance compaction](/docs/features/relevance-compaction) | per-message keep/drop, plus a gate on the generated summary | | [Tool / MCP routing](/docs/features/tool-routing-decision-model) | one `boolean` per server, replacing a 15s LLM call | | [RAG retrieval](/docs/features/rag-retrieval-planning) | per-query `topK` / hybrid / graph / rerank planning | Each is fail-open: any refusal, timeout or error leaves behaviour as it was. Each also records a `model.decision` span, so a decision path that has stopped working is visible rather than indistinguishable from one never configured. Calling it yourself is the other use. It suits the same work as any decision model: routing, classifying and grading against a rubric, gating an action on a threshold, and the same questions about an image. It is wrong for a final answer a user reads, or anything that needs a rationale: a decision carries a probability, never an explanation. See [the `decide` inference type](/docs/features/decide-inference-type). --- ## What is sent to Perplexity Perplexity receives the `state` and the questions of every decision made on your behalf. The questions are NeuroLink's fixed wording, plus text from your own conversation where a consumer quotes it; the `state` is where your text goes. This is what each built-in consumer sends and what turns it on, read from the code: - **Model routing.** One request behind the router, the model catalogue and the per-request context budget. - _Sends:_ the first 8,000 characters of the prompt of the call being routed, plus whether tools are available, whether the request includes images, the estimated input tokens, the requested thinking level, whether a session is bound and how many prior messages the caller passed in. When the pool has more than one model, the questions carry the ids and descriptions of the models in it. The images, the session id and the conversation itself are not sent. - _Turned on by:_ `classifierRouter.enabled` with a `pool`: **an opt-in.** With the default `classifier: "auto"`, a configured decision provider selects the decision strategy. `classifier: "heuristic"` or `"llm"` never calls a decision provider. A call that pins both `provider` and `model` is not routed. - **Relevance compaction.** Stage 0 of context compaction. - _Sends:_ the current request (first 4,000 characters) and, for each earlier user or assistant message that is plain text (not a tool call or result, a summary or a pinned skill), its role and its first 1,200 characters. That text travels twice, once in the state and once in the message's question. By default the six most recent messages are never sent (`contextRelevance.protectRecent`), and at most 300 are asked about. - _Turned on by:_ **nothing beyond a configured decision provider.** It runs inside context compaction, which starts when a conversation outgrows its context budget. - **Summary-quality gate.** Guards the summarization stage of compaction. - _Sends:_ the generated summary (first 12,000 characters) and the last 60 messages it replaced, each with its role and its first 1,200 characters. - _Turned on by:_ **nothing beyond a configured decision provider.** It runs after the summarization stage has written a summary. - **Tool / MCP routing.** - _Sends:_ the routing query, at most 10,000 characters: the current query, preceded by up to the six most recent user and assistant text turns. Also, for each routable server, its name, its description (or its tool names, when it has none) and its tool count. One question per server, up to 200, quotes the same. - _Turned on by:_ `toolRouting.enabled` with a `servers` catalogue and at least two routable servers: **an opt-in.** - **RAG retrieval planning.** - _Sends:_ the search query (first 4,000 characters). The retrieved passages are not sent. - _Turned on by:_ passing a `decide` function to `RAGPipeline` or `createRAGPipeline`: **an opt-in, by wiring.** The `rag: { files }` shortcut on `generate()` and `stream()` never does. So model routing, tool routing and RAG planning need an opt-in, and relevance compaction and the summary gate need none. A call you make yourself to `neurolink.decide()` sends the `state`, `questions` and `images` you pass, to the provider you name or to the default one. Two consumers can ask more questions in one request than Perplexity takes: relevance compaction asks about up to 300 messages and tool routing about up to 200 servers, against 128 here. `tryDecide()`, which every built-in consumer calls, splits such a request into batches of at most 128 questions, runs up to four at a time and joins the answers. The state goes with every batch, so it is sent, and billed, once for each. A batch that fails costs only its own questions, which then have no answer, and the consumer carries on without that decision. Measured live through the published package: 300 questions went out as 128, 128 and 44 and all 300 were answered, in order, in 2.5 seconds with no 429; 640 questions went out as five requests of 128 and all 640 were answered in 2.6 seconds, also with no 429. Treat each request like any hosted provider call for data handling and retention: it is a request to `api.perplexity.ai` made with your key. Besides the body, each request to `api.perplexity.ai` carries one identifying header, `X-Pplx-Integration: neurolink`: the same attribution the Perplexity text provider sends, and one Perplexity asks integrations to send on its own host. A `PERPLEXITY_DECIDER_BASE_URL` that points anywhere else gets no such header. --- ## One key, two providers `PERPLEXITY_API_KEY` is the variable the [Perplexity text provider](/docs/getting-started/providers/perplexity) reads to serve `generate()` and `stream()`. It is also the variable that configures this provider. Nothing else needs to be set, so a host that set the key only to use Sonar has also configured `decide`: - **With none of TypeSafe, Laya, XOR or SubQ configured, the texts listed in [What is sent to Perplexity](#what-is-sent-to-perplexity) go to Perplexity's Decisions API.** Context compaction needs no other opt-in, so a host with long conversations starts sending conversation text the first time one outgrows its budget. Model routing, tool routing and RAG planning do so only where you have turned them on. No code changes: the key is the switch. - **It is fail-open, and TypeSafe, Laya, XOR and SubQ take precedence.** If you have configured any of them, the shared key changes nothing for the built-in consumers, and a Perplexity failure leaves behaviour as it was. - **With no decision provider configured at all, nothing is sent.** An unedited copy of `.env.example` does not set the key, because its `PERPLEXITY_API_KEY` line is commented out. A key in a `.env` file counts as a key in the environment. Importing the SDK loads the `.env` in the current working directory, and the CLI does the same at start; when `DOTENV_CONFIG_PATH` is set, that file is loaded instead. A key that sits in `.env` therefore configures `decide` exactly as one exported in the shell does. To keep a key that was set for Sonar from activating decisions, use one of these: 1. **Hand the key to the text provider through the SDK, not the environment, and keep it out of `.env`.** `new NeuroLink({ credentials: { perplexity: { apiKey } } })` configures the text provider and not this one, because NeuroLink looks for this provider's key in `PERPLEXITY_API_KEY` and in `credentials.perplexityDecider`, never in `credentials.perplexity`. The key must also be absent from `.env`: remove the `PERPLEXITY_API_KEY` line from that file as well as from the shell, or point `DOTENV_CONFIG_PATH` at a file that does not have it. With no `PERPLEXITY_API_KEY` in the environment or in a loaded `.env`, Perplexity decisions are not configured. **Verified live** with the environment variable unset in the process: a `generate()` call to the Sonar provider with the key only in `credentials.perplexity.apiKey` returned content, while `decide()` with the same slice threw `No decision provider is configured` and `tryDecide()` returned `null`; the key in `credentials.perplexityDecider` made `decide()` answer. The CLI reads only the environment and the `.env` it loads, so a CLI run that has the variable set in either place has decisions configured; set it only for the commands that need it. 2. **Configure TypeSafe, Laya, XOR or SubQ.** One of them then answers every built-in consumer, and Perplexity runs only where a caller names it. The same texts go to that provider instead. 3. **Switch off the opt-in consumers, or pin the router's strategy.** `classifierRouter: { classifier: "heuristic" }` keeps routing in-process (`"llm"` sends the prompt to the classifier model instead). Leave `toolRouting.enabled` unset, and do not pass `decide` to a `RAGPipeline`. This does not cover compaction. Compaction's relevance stage and summary gate have no switch of their own while a decision provider is configured, and there is no switch that turns this provider off while the key is set. --- ## Limits ### Measured on a real account, October 2026 NeuroLink probed the live API from an account limited to 10 requests per second. These figures were observed, not taken from Perplexity's documentation: | What | Measured | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Questions per request | 128 accepted (128 answers in 8.9 s, 11,904 input tokens); 129 is refused with a 400. An extra minimal question adds about 92 input tokens, and a one-character state with one question bills 116. | | Images per request | 8 accepted (with three questions); 9 refused with a 400 (with one question; the message says "per question"). | | Input ceiling | Input of 262,144 tokens or more is refused with an explicit 400 (`Input length (262144) exceeds or equals model's maximum context length (262144)`, or with images in the request `Total input tokens (250676 text + 16384 vision = 267060) exceeds maximum context length (262144)`). The state, the questions and the images all count toward it; each 2,048-tile image counted as 2,048 vision tokens. Nothing is cut off silently: needles at the head and at the tail of a state were both found at 900,000 characters, and a tail needle at 1.55 million characters (251,350 input tokens, answered in 22.9 s). | | Tokens per character | By kind of text, in the table below. Other scripts: CJK about 0.46 tokens per character, Devanagari 0.44, emoji 2.6 per code point. | | Latency | Grows faster than linearly with input: 3.9 s at 65,000 tokens, 10 s at 146,000 and 22.9 s at 251,000, about 17,000, 15,000 and 11,000 tokens per second. One question on a short state took 0.3 to 1.1 s, and each question after the first added about 65 ms (128 minimal questions took 8.9 s on 11,904 input tokens). | | Image cost | About one input token for each 32 × 32 tile, plus 95 to 103 more that look like fixed overhead for the request and not a charge for each image: 1920 × 1080 (2,040 tiles) cost about 2,135 tokens, 1024 × 1024 (1,024 tiles) about 1,119, 512 × 512 (256 tiles) about 351, 2048 × 1024 (2,048 tiles) 2,151 and 1450 × 1450 (2,025 tiles) 2,128. Eight images in one request were counted as exactly 16,384 vision tokens, 2,048 each, with the text only 52 tokens above the same text alone. | | Image size | Seven sizes were tried. Answered in about a second: 1920 × 1080 (2,040 tiles) in 1.1 s, 2048 × 1024 (2,048 tiles, exactly the cap) in 1.3 s and 1450 × 1450 (45 tiles a side, 2,025) in 1.1 s. Stalled for about 56 seconds and returned an HTML 504: 1600 × 1310 (2,050 tiles, two over), 1470 × 1470 (46 tiles a side, 2,116), 2048 × 2048 (4,096, tried twice) and 4000 × 3000 (11,750). Each side rounds to the nearest multiple of 32 and the cap is 2,048 tiles. The trigger is the tile count, not the file size (the 2048 × 2048 image was a 60 KB PNG) and not the raw pixel count (1600 × 1310 is 2,096,000 pixels and stalled; 2048 × 1024, at 2,097,152, did not). | | Rate limit | 10 requests per second: a burst of 14 parallel requests got 10 answers and 4 replies of 429, and capacity returned within about 3 seconds. A 429 carries `Retry-After: 1`, in seconds. | Characters per token, by kind of text. Each sample was 40,000 characters, sent as the state of a one-question request, with the cost of the bare question subtracted: | Sample | Characters per token | | ------------------------------------------------------------ | -------------------- | | English prose (sentences from NeuroLink's own provider docs) | 4.34 | | TypeScript (four of NeuroLink's provider files) | 3.84 | | Minified JSON (the provider catalog files) | 3.36 | | Log lines (timestamps, hex ids, counters) | 1.35 | | JSON arrays of integers | 1.16 | | Repeated text (one phrase, or one letter) | 4.9 to 8.0 | Two more behaviours from the probe. A `choice` with a single option answers at once with confidence 1.0 and bills no tokens, so it carries no information. An empty string is accepted as a `state`. ### What Perplexity documents and the probe did not check - **The request body:** 32 MiB, refused with a 413. - **Names, options and levels:** every question needs a non-empty name; 1 to 255 options on a `choice`; 1 to 10 levels on a `score`. - **The price:** $0.04 per million input tokens, image tokens included, output free. - **The rate:** 10 requests per second for the account's tier, and a token limit that also applies to large bursts; either answers 429. The burst test above saw the request limit act on the one account tested, and the token limit was not tested. - **Not verified:** the status the API returns for an account with no credit. A key with no balance could not be created for the probe. Whatever comes back is classified by the table under [Errors](#errors): a 401 disables the provider instance, a 429 is retried once, and any other 4xx is an `invalid_request`. ### What NeuroLink refuses before any request These are NeuroLink's own limits, set from the measurements above. A request over any of them fails locally, with no network call, and every built-in consumer treats that as "carry on as before". - **A state estimated above 100,000 tokens** is refused with `max_tokens_exceeded`. The window is a deliberate local limit, **not a server limit**: the server reads up to 262,144 tokens in all. It is set lower because latency grows faster than linearly with input (3.9 s at 65,000 tokens, 10 s at 146,000), so a state of 100,000 tokens takes about 7 seconds of the 10-second allowance, an interpolation between those two measurements and not a measurement of its own, and a much larger one would likely time out and be retried into the same wait. The estimate is 3.81 characters per token for ASCII text (four, with a 5% margin), which is about 381,000 characters at the window, and half a token per non-ASCII character, near the measured rate for CJK (about 0.46) and Devanagari (0.44). It covers the text of the state only, not the questions or the images. - **The estimate is a guard, not a promise of acceptance.** Against the measured characters per token, it over-counts English prose (4.34) and is close for TypeScript (3.84). It under-counts minified JSON (3.36) by about 13%, which does not matter at the window: 380,000 characters of JSON, estimated at 100,000 tokens, are about 113,000 real tokens, far under the 262,144 the server reads. Log lines (1.35) are under-counted by about 2.8 times and arrays of integers (1.16) by about 3.3 times, and a state of either kind can pass the window and still be refused by the server for being over its ceiling: 380,000 characters of log lines are about 281,000 real tokens, and of integer arrays about 328,000. Text that is mostly emoji (2.6 tokens per code point, against the half token it charges) can be refused the same way. That refusal is reported as `max_tokens_exceeded` too, and is not retried. - **A state estimated above the window needs a smaller state, or another provider.** There is no setting that raises the window, so a larger state that would fit the server's ceiling can be sent only through a decision provider with a larger window. - **More than 128 questions in a `decide()` call** is refused with `max_tokens_exceeded`, the cap the API enforces. `tryDecide()` splits the request at 128 instead (see [What is sent to Perplexity](#what-is-sent-to-perplexity)). - **More than 8 images**, an image that is not PNG, JPEG or WebP, an image over 2,048 tiles of 32 × 32 pixels, a remote image URL, a video, or a body over 32 MiB is refused with `invalid_request`. A request that passes the local checks can still be refused by the API, for example because the questions or the images push the input past 262,144 tokens. A 400 that says the input exceeds the model's maximum context length, in either of the two wordings the server uses (see [Limits](#measured-on-a-real-account-october-2026)), arrives as `max_tokens_exceeded`, and any other 400 as an `invalid_request` carrying the API's own message. Neither is retried. ### Latency and the timeout **The default timeout is 10 seconds plus 100 ms for each question**: 10.1 seconds for one question and 22.8 seconds for the 128-question maximum. A `timeoutMs` you pass, or `--timeout` on the CLI, is used exactly as given, with nothing added. The 10 seconds are the allowance for reading the input. Latency grows faster than linearly with input (3.9 s at 65,000 tokens, 10 s at 146,000 and 22.9 s at 251,000), so a state of 100,000 tokens takes about 7 s, an interpolation between the 65,000- and 146,000-token measurements, and a larger one needs a larger `timeoutMs`. The 100 ms follows what a question costs: each one after the first added about 65 ms, and 128 minimal questions took 8.9 s on 11,904 input tokens, so a flat 10 seconds would have been nearly spent on the questions alone. Images count as input tokens too (see [Images](#images)). A timeout is retried once, so a request that stalls can take about twice the timeout plus a quarter to half a second before it fails: about 20 seconds at the default for one question. Pass a larger `timeoutMs` for a state of more than about 100,000 real tokens, which log lines and arrays of numbers reach well inside the window (see [What NeuroLink refuses](#what-neurolink-refuses-before-any-request)). A model that does not answer in time returns an HTML 504 after about a minute; NeuroLink's shorter timeout fires first, so it arrives as `timeout`, retried once. Each built-in consumer takes its timeout from where it is configured: - **Model routing** (with the model catalogue and the context budget, which share its request): `classifierRouter.timeoutMs` in the `NeuroLink` config, passed to the decision request when set. - **Relevance compaction:** `contextRelevance.timeoutMs` in the `NeuroLink` config. - **Summary-quality gate:** no setting. The `NeuroLink` config has none for it. - **Tool / MCP routing:** no setting for the decision request. `toolRouting.timeoutMs` bounds the generative router only. - **RAG planning:** no setting in the pipeline config. The pipeline calls the `decide` function you give it, so set `timeoutMs` in the call that function makes. Where there is no setting, or `timeoutMs` is left unset, the default above applies. ### Rate limits The account measured allows 10 requests per second. A 429 is retried once, after the wait its `Retry-After` header asks for. NeuroLink honours that header on any retried reply that carries it, and only as a whole number of seconds above zero or as an HTTP date in the future; anything else (zero, a negative number, a hex or exponent spelling, a fraction, a date already past) is ignored, and the default backoff of a quarter to half a second is used instead. A wait longer than what is left of the attempt's timeout is not taken: the error is thrown at once so a fail-open consumer is not held for the length of a cooldown, and a caller's abort signal ends a wait immediately. --- ## Errors | Reply | Kind | Retried | | -------------------------------------------------------------------- | ------------------------------------------------------- | ------------------------------ | | 401 | `authentication` — the provider instance stops retrying | no | | 413 | `max_tokens_exceeded` (the body is over 32 MiB) | no | | 400 saying the input exceeds the model's maximum context length | `max_tokens_exceeded` | no | | any other 4xx (for example another 400, 403, 404) | `invalid_request`, with Perplexity's own message | no | | 429 | `rate_limit` | yes, once, after `Retry-After` | | 503 | `overloaded` | yes, once | | other 5xx (500, 502, 504) | `server` | yes, once | | no response within the timeout | `timeout` | yes, once | | the request fails before any reply (connection refused, DNS failure) | `network` | yes, once | | the caller's own `signal` aborts the request | `network` | no | | state or questions over the limit (local) | `max_tokens_exceeded`, with no network call | no | | unusable images, or a video (local) | `invalid_request`, with no network call | no | | no key configured (local) | `authentication`, with no network call | no | | a base URL that cannot work (local) | `invalid_request`, with no network call | no | Only a 401 disables the provider instance, because a bad key does not fix itself: after the first rejection the instance stops sending requests. A 4xx that is not a 401, a 413, an over-length 400 or a 429 is something a caller or an account owner can fix without a restart, so it is `invalid_request` rather than a latch. Perplexity checks the key before it validates anything else, so a bad key answers 401 whatever else is wrong with the request. Perplexity answers with three error envelopes, each an `error` object that always has a `message` and a `type`. A 401 adds `code` as a number and no `param`. The gateway layer, which answered the 429 and the 400s for an unknown model or a bad field in testing, adds a null `code` and a null `param`. The model server, which answered the other 400s seen in testing (rules on questions, images and input length), adds `code` as a string, may add `model`, and sends no `param`. So `code` is a number, null or a string, and NeuroLink classifies by HTTP status first. It reads `message` (and `param`, when it names a field the message does not) and ignores `code`, which Perplexity says not to branch on. A 405 returned an empty body in testing; Perplexity documents an empty body for a 404 as well, which was not tested. The 504 arrives as an HTML page. A body that is not that envelope, empty or HTML, falls back to a short `Perplexity request failed with HTTP `, and the HTML is never echoed. The request id comes from the `x-request-id` header. Perplexity documents that a 401, a 404 and a 504 carry none, and a 401 was confirmed in testing, so those leave it undefined. Before the message of an HTTP error reply reaches a log or an error, the provider removes the configured key, anything shaped like a Perplexity key (`pplx-` followed by 30 or more characters, so a model name such as `pplx-decider-v1-27b-latest` stays readable), long hex runs and embedded `data:` URLs. The message of a failure with no reply (the `network` and `timeout` kinds) goes through the same scrub except for the Perplexity-key shape: it loses the configured key, long hex runs and embedded `data:` URLs, and any URL in it is cut to its scheme, host and path. --- ## Troubleshooting - **`Perplexity requires an API key`** — set `PERPLEXITY_API_KEY`, or pass `credentials.perplexityDecider.apiKey`. A key passed as `credentials.perplexity` does not count. - **A 401, `Invalid API key provided`** — Perplexity rejected the key, and it checks the key before anything else. The provider instance stops retrying after a rejection, so fix the key and construct a new one. - **A 400 naming the model** — `PERPLEXITY_DECIDER_MODEL`, or a per-call `model`, names something other than `pplx-decider-v1-27b`. - **`The Perplexity base URL must not carry credentials…`** — the override has a user name, a password, a query string or a fragment. Set it to the origin only, or leave it unset for `https://api.perplexity.ai`. - **`The Perplexity base URL must start with https:// or http://`** — the value parses as a URL with another scheme: an explicit one such as `ftp://`, or a host name and port with no scheme, such as `localhost:8080`, which reads as the scheme `localhost:`. Put `https://` in front, or `http://` for a server on this machine. - **`The Perplexity base URL must use https:// unless it points at this machine`** — the override is an `http://` URL whose host is not `localhost`, `127.0.0.1` or `[::1]`. A plain-http request would send the key unencrypted. Use `https://`, or reach the server through a port-forward to `localhost`. - **`Perplexity answered with a redirect`** — the endpoint replied 301, 302, 307 or 308. The provider does not follow it and does not retry. Set the base URL to the address the redirect leads to. - **`The Perplexity base URL is not a valid absolute URL`** — the value does not parse as a URL at all: a bare host name such as `api.perplexity.ai` (the likely mistake), an IP address and port such as `127.0.0.1:8080`, a path, or a scheme with no host. Write the origin with its scheme. - **A refused base URL in the debug log** — it is not there. A base URL that NeuroLink refuses (credentials, a query string, a fragment, a scheme other than http or https, http to a host other than this machine, or not a URL at all) is never written to the debug log: the line shows `(invalid)` in its place, because such a value can carry a secret. - **`Image N is not a PNG, JPEG or WebP image`** — Perplexity reads only those three. Convert the image first. - **`Image N is … pixels; Perplexity reads at most 2048 tiles`** — resize the image to fit, for example 1440 × 1440 or 2048 × 1024. - **A request with an image stalls until it times out, or fails as `server` with `HTTP 504` when the timeout is longer than a minute** — an image over the tile cap does this. NeuroLink refuses those before any request, but sends an image whose dimensions it cannot read as given. Resize the image. - **`Perplexity does not accept video`** — send images, or use a decision provider that reads video. - **`max_tokens_exceeded`** — the state is estimated above 100,000 tokens, a `decide()` call has more than 128 questions (`tryDecide()` splits them), or the server refused input of 262,144 tokens or more. Shorten the state, split it or the questions across requests, or use a decision provider with a larger window. - **`timeout`** — the request took longer than the timeout, 10 seconds plus 100 ms for each question by default, and a timeout is retried once, so the error arrives after about twice that. Raise `timeoutMs` for a state of more than about 100,000 real tokens, or send fewer or smaller images. - **`rate_limit`** — the account is over its request rate, 10 per second on the one measured. NeuroLink retries once after `Retry-After`. Batch every question into one request rather than fanning out. - **Built-in routing never uses Perplexity** — TypeSafe, Laya, XOR or SubQ is also configured and takes precedence, no key is set, or the router's `auto` gate did not see the key: it counts the constructor's credentials, the environment and the call's own credentials, so check that the key reaches one of those. - **State is being sent to Perplexity and I only set the key for Sonar** — see [What is sent to Perplexity](#what-is-sent-to-perplexity) and [One key, two providers](#one-key-two-providers). Check the `.env` your process loads as well as the shell: a key in either place configures `decide`. --- ## See also - [The `decide` inference type](/docs/features/decide-inference-type) - [TypeSafe (Jev) Provider Guide](/docs/getting-started/providers/typesafe) - [Laya Provider Guide](/docs/getting-started/providers/laya) - [XOR Provider Guide](/docs/getting-started/providers/xor) - [Cloudflare Clef Provider Guide](/docs/getting-started/providers/cloudflare-clef) - [SubQ Provider Guide](/docs/getting-started/providers/subq) - [OpenAI Decisions Provider Guide](/docs/getting-started/providers/openai-decisions) - [ScaleDown Provider Guide](/docs/getting-started/providers/scaledown) - [Perplexity text provider](/docs/getting-started/providers/perplexity) - [Perplexity Decisions API reference](https://docs.perplexity.ai/api-reference/decisions-post) --- ## Perplexity Provider Guide # Perplexity Provider Guide **Web-search-augmented generation via Perplexity's Sonar models** ## Quick Start ### 1. Get an API Key [https://www.perplexity.ai/settings/api](https://www.perplexity.ai/settings/api) ### 2. Configure ```bash PERPLEXITY_API_KEY=pplx-your-key PERPLEXITY_MODEL=sonar ``` > **`PERPLEXITY_API_KEY` also configures decisions.** The same variable configures > the [Perplexity Decisions provider](/docs/getting-started/providers/perplexity-decider) (`perplexity-decider`, > which serves `decide()`). So setting it for Sonar also lets NeuroLink's built-in > features send decision requests to Perplexity when no TypeSafe, Laya, XOR or SubQ > provider is configured, and context compaction needs no other opt-in to do so. > To avoid that, pass the key through the SDK as `credentials.perplexity.apiKey` > instead of the environment, and keep it out of `.env` too: the SDK and the CLI > load that file into the environment, so a `PERPLEXITY_API_KEY` line like the one > above would still configure decisions. (That the text provider reads this slice > is taken from the code and has not been run against the live API.) See > [What is sent to Perplexity](/docs/getting-started/providers/perplexity-decider#what-is-sent-to-perplexity) > and [One key, two providers](/docs/getting-started/providers/perplexity-decider#one-key-two-providers). ### 3. Generate ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "perplexity", input: { text: "What did the Fed announce yesterday?" }, }); console.log(result.content); ``` --- ## Supported Models | Model ID | Notes | | ----------------- | ----------------------------------- | | `sonar` | Default; fast search-augmented chat | | `sonar-pro` | Larger context, deeper search | | `sonar-reasoning` | Chain-of-thought reasoning | --- ## CLI Usage ```bash pnpm run cli generate "What were today's tech-stock movers?" --provider perplexity ``` --- ## Provider Aliases | Alias | Example | | ------------ | ----------------------- | | `perplexity` | `--provider perplexity` | --- ## Configuration Reference | Environment Variable | Required | Default | | --------------------- | -------- | --------------------------- | | `PERPLEXITY_API_KEY` | Yes | — | | `PERPLEXITY_MODEL` | No | `sonar` | | `PERPLEXITY_BASE_URL` | No | `https://api.perplexity.ai` | --- ## Feature Support Matrix | Feature | Support | | ----------------- | ------------ | | Text generation | Yes | | Streaming | Yes | | Tool calling | No | | Structured output | Limited | | Web search | Yes (native) | | Citations | Yes | --- ## See Also - [Perplexity Decisions Provider](/docs/getting-started/providers/perplexity-decider) — typed, calibrated `decide()` judgments on the same key - [Anthropic Provider](/docs/getting-started/providers/anthropic) — web-search via the `web_search` tool - [Vertex Provider](/docs/getting-started/providers/google-vertex) — Google search grounding --- ## Poolside Provider Guide # Poolside Provider Guide Poolside is a **Tier-2 catalog provider**: its entire integration is one JSON file (`src/lib/providers/catalog/poolside.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** Poolside's `GET https://inference.poolside.ai/v1/models` > needs a key (an unauthenticated GET answered HTTP 401), so the model id comes > from Poolside's public docs and the roster has not been checked. No account > was created and no API key was used to build it. `evidence.liveMatrix` is > `null` until someone runs the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://platform.poolside.ai/ — https://docs.poolside.ai/get-started/log-in.md says of the Poolside Platform option: "sign in to Poolside Platform or create an account" 2. Create an API key: https://docs.poolside.ai/api/overview.md says "Sign in to Poolside Platform, open the API Keys tab, and click New key." 3. Billing as the vendor states it: https://docs.poolside.ai/get-started/log-in.md describes the Poolside Platform option as "free developer access" and says "The API key created through Poolside Platform is for Poolside-hosted inference." 4. Authentication is HTTP Bearer: https://docs.poolside.ai/api/overview.md shows the header `Authorization: Bearer ` and exports the key as POOLSIDE_API_KEY, the name NeuroLink reads. Set `POOLSIDE_API_KEY` in your .env file ### 2. Configure ```bash export POOLSIDE_API_KEY=your-api-key export POOLSIDE_MODEL=poolside/laguna-s-2.1 # optional — overrides the default model export POOLSIDE_BASE_URL=https://inference.poolside.ai/v1 # optional — overrides the base URL ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "poolside", model: "poolside/laguna-s-2.1", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider poolside ``` Per-request credentials work the same way as for the other catalog providers: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "poolside", credentials: { poolside: { apiKey: process.env.POOLSIDE_API_KEY } }, }); ``` --- ## Billing [The log-in page](https://docs.poolside.ai/get-started/log-in.md) describes the Poolside Platform option as "free developer access" and says "The API key created through Poolside Platform is for Poolside-hosted inference." The catalog schema has three billing values (`free-tier`, `free-with-card`, `no-free-tier`); the entry holds `free-tier`, built from that wording. --- ## Models | Model | Context | Vision | Notes | | -------------------------- | ------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `poolside/laguna-s-2.1` ⭐ | not set | no | NeuroLink default — the model id the API page's quickstart examples and the examples page's examples use against `https://inference.poolside.ai/v1`. The [supported-models page](https://docs.poolside.ai/get-started/supported-models.md) lists "118B total, 8B active per token", "Mixture of Experts" and "Text-to-text". | Values come from Poolside's public docs, retrieved 2026-09-29: - **Context** — the catalog entry sets no `contextWindow` for this model, so `models.defaultContextWindow` (128,000) applies. The Context window row of the [supported-models page](https://docs.poolside.ai/get-started/supported-models.md) shows "1M tokens" for Laguna S 2.1, and the same page says "Model availability, provider-specific variants, and model IDs can vary by access method." - **Vision** — `false`. The [model release notes](https://docs.poolside.ai/release-notes/models.md) say Laguna S 2.1 "is text-to-text and does not support vision inputs". - **Description** — the release notes say Laguna S 2.1 is "built for agentic coding and long-horizon work". The supported-models page lists Reasoning as "Native reasoning with thinking on or off per request". - **Pricing** — no `pricingPerMTok` is set. `models.defaultContextWindow` (128,000) is a placeholder, not a vendor figure. `models.defaultMaxOutputTokens` (32,768) equals the `max_tokens` default in the Control generation table on the [examples page](https://docs.poolside.ai/api/openai-api-examples.md); it is not a per-model limit. The model's `status` field holds `production`, a placeholder for a value the catalog schema requires; it is not a vendor statement. **Fallback order:** the catalog has one model, so `poolside/laguna-s-2.1` is also the fallback. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Poolside — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://inference.poolside.ai/v1/models` answered HTTP 401 without a key on 2026-09-29, so the model id is taken from https://docs.poolside.ai/api/overview.md (retrieved 2026-09-29); roster not verified | | Billing | https://docs.poolside.ai/get-started/log-in.md describes the Poolside Platform option as "free developer access"; https://platform.poolside.ai/ opened and shows the title "Poolside Platform"; no signup was performed, 2026-09-29 | | Auth-failure shape | unauthenticated `GET /v1/models` answered HTTP 401, content-type `text/plain; charset=utf-8`, plain-text body "No Authorization header provided"; unauthenticated `GET /v1/chat/completions` answered HTTP 405 with an empty body. No POST request was sent. `errorRules` carry 401 (observed) and 403 (documented) | | Tools / structured output | function calling is documented on https://docs.poolside.ai/api/openai-api-examples.md; it was not exercised live, and no request using `response_format` or combining tools with a schema was sent — `structuredOutput` and `structuredOutputWithTools` stay `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=poolside` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | HTTP 401 with the body `No Authorization header provided` | Observed on 2026-09-29 for an unauthenticated `GET /v1/models`; https://docs.poolside.ai/api/overview.md says "Poolside-hosted inference and OpenRouter require an API key." | The same page says "Send it as a Bearer token in the Authorization header"; set `POOLSIDE_API_KEY` | | `403 Forbidden: please check the api-key you provided` | Listed under "Fix API key or token errors" on https://docs.poolside.ai/cli/troubleshooting.md, which says "These errors usually mean the prompt reached the agent, but the agent or model request could not authenticate." | That page's first step is "Check whether authentication environment variables are set." | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Prime Intellect Provider Guide # Prime Intellect Provider Guide Prime Intellect Inference is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/prime-intellect.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** Every field below comes from Prime Intellect's own public > documentation, its public OpenAPI spec, and unauthenticated `GET` requests to > `https://api.pinference.ai` — no API key was created or used to build it, and > no `POST` was sent. `evidence.liveMatrix` is `null` until someone runs the live > capability matrix with a real key (see [Verification status](#verification-status) > below). ## Quick Start ### 1. Get an API key 1. Visit: https://app.primeintellect.ai/dashboard/tokens (Settings -> API Keys) and sign in 2. Click Generate New Key and enable the **Inference** permission — without it requests fail with authentication errors (https://docs.primeintellect.ai/inference/overview); the key is shown only once, so copy it straight away (https://docs.primeintellect.ai/api-reference/api-keys) 3. Billing is automatic deduction from your Prime Intellect account balance (https://docs.primeintellect.ai/inference/overview); no free tier or trial credit is documented on the pages read, so add funds at https://app.primeintellect.ai/dashboard/billing and confirm current terms before the first call 4. Set `PRIME_INTELLECT_API_KEY` in your .env file (`PRIME_API_KEY`, the variable Prime's own docs use, is also read) ### 2. Configure ```bash export PRIME_INTELLECT_API_KEY=your-api-key export PRIME_INTELLECT_MODEL=openai/gpt-4.1-mini # optional — overrides the default model export PRIME_INTELLECT_BASE_URL=https://api.pinference.ai/api/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "prime-intellect", model: "openai/gpt-4.1-mini", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider prime-intellect ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "prime-intellect", credentials: { primeIntellect: { apiKey: process.env.PRIME_INTELLECT_API_KEY }, }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ------------------------------------ | --------- | ------ | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `openai/gpt-4.1-mini` ⭐ | 1,047,576 | yes | $0.40 / $1.60 | Recommended — Prime's Evaluating Environments guide lists it as "Fast, cost-effective (default)" and uses it as the default model of its inference-backed eval flow. | | `openai/gpt-4.1` | 1,047,576 | yes | $2 / $8 | Listed in the same guide as "Higher quality"; fallback. | | `anthropic/claude-sonnet-4.5` | 1,000,000 | yes | $3 / $15 | Listed in the same guide as "Strong reasoning"; fallback. | | `meta-llama/llama-3.3-70b-instruct` | 131,072 | no | $1.04 / $2.253 | Listed in the same guide as "Open-weight, balanced"; fallback. | | `google/gemini-2.5-flash` | 1,048,576 | yes | $0.30 / $2.50 | Listed in the same guide as "Fast multimodal". | | `Qwen/Qwen3-235B-A22B-Instruct-2507` | 262,144 | no | $0.25 / $1 | The guide lists a lowercase id that is not on today's roster; this id is the roster's differently cased entry. | | `z-ai/glm-5.3` | 1,048,576 | no | $1.40 / $4.40 (cached $0.26) | Served `hosted` on Prime infrastructure; reasoning is marked mandatory (default effort `max`); no `response_format` in its `supported_parameters`. | | `openai/gpt-5.4-mini` | 400,000 | yes | $0.75 / $4.50 | Named in the Troubleshooting page's direct-API examples. | | `openai/gpt-oss-120b` | 131,072 | no | $0.35 / $0.75 | Roster-listed only; reasoning marked mandatory. | | `deepseek/deepseek-v4-flash` | 1,048,576 | no | $0.44 / $1.32 | Roster-listed only. | | `anthropic/claude-haiku-4.5` | 200,000 | yes | $1 / $5 | Roster-listed only. | | `Qwen/Qwen3.5-122B-A10B` | not given | no | $0.30 / $0.90 (cached $0.27) | Served `hosted`; the roster gives no context window or modalities, so none are declared. Vision `false` is a schema default, not a vendor statement. | Context, output caps, prices and input modalities are taken from an unauthenticated `GET https://api.pinference.ai/api/v1/models` call made 2026-09-29 (125 models total; 12 curated into this catalog). Per-model `maxOutputTokens` in the JSON is the roster's `max_output_tokens` as served — for example 32,768 for the default, and 235,929 for `Qwen/Qwen3-235B-A22B-Instruct-2507`, which is reported as-is and not independently checked. `vision: true` follows the roster's image input modality; no image request was sent. `models.defaultContextWindow` (131,072) and `models.defaultMaxOutputTokens` (16,384) are **not** vendor-stated general defaults — Prime documents none. They are the smallest context and output figures the roster reports among the curated models, used as a conservative floor for any id without its own figure. Prices carry an `effective_at` date on the roster and Prime's overview page says pricing details are still to come, so treat them as a snapshot. The models were picked for the docs that name them (the Evaluating Environments guide and the Troubleshooting page), not ranked by quality. Prime's own docs also show `meta-llama/llama-3.1-70b-instruct`, `deepseek/deepseek-r1-0528` and `anthropic/claude-3-5-sonnet-20241022` in examples; none of those three ids is on today's roster, so they are not in the catalog. **Fallback order** when the default is unavailable: `openai/gpt-4.1` → `anthropic/claude-sonnet-4.5` → `meta-llama/llama-3.3-70b-instruct`. The derived single fallback is the second entry, `anthropic/claude-sonnet-4.5`, which routes to a different upstream than the default. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Prime Intellect — **docs- and roster-verified, not live-verified**: | Probe | Result | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Roster | unauthenticated `GET /api/v1/models`, HTTP 200, 125 models, 2026-09-29 — no key used | | Auth-failure shape | unauthenticated `GET /api/v1/models/openai/gpt-4.1-mini` with no credentials returned HTTP 401 `{"detail":"Authorization header or x-api-key missing", ...}` on 2026-09-29. The docs' invalid-key shape (`error.code: invalid_api_key`, on the Models API reference page) was **not** probed. One `errorRules` entry maps HTTP 401 and both wordings to an authentication error | | Billing | overview page: "Automatic deduction from your Prime Intellect account balance"; troubleshooting page documents an `insufficient_funds` error. No free tier stated | | Tools / structured output | **not described on any docs page read.** The declaration rests on the roster's per-model `supported_parameters` field (`tools`, `tool_choice`, `response_format`, `structured_outputs`), which is the vendor's own published metadata, not on a docs page or a live call. Neither was exercised, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Tools + streaming | not documented anywhere read — `toolsWithStreaming` is `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=prime-intellect` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. Pages opened to build this entry (all on 2026-09-29): - https://docs.primeintellect.ai/introduction - https://docs.primeintellect.ai/inference/overview - https://docs.primeintellect.ai/inference/usage - https://docs.primeintellect.ai/inference/troubleshooting - https://docs.primeintellect.ai/inference/team-accounts - https://docs.primeintellect.ai/api-reference/api-keys - https://docs.primeintellect.ai/api-reference/inference-models - https://docs.primeintellect.ai/api-reference/inference-chat-completions - https://docs.primeintellect.ai/tutorials-environments/evaluating - https://docs.primeintellect.ai/hosted-training/models-and-pricing - https://api.pinference.ai/openapi.json (public OpenAPI spec; defines the roster fields and shows the chat-completions request body accepts additional properties) - https://api.pinference.ai/api/v1/models (unauthenticated roster) - https://app.primeintellect.ai/dashboard/tokens and https://app.primeintellect.ai/dashboard/billing (both answer HTTP 200 and redirect to a sign-in page; nothing behind sign-in was opened) --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------ | | HTTP 401 / authentication error | Missing key, or a key created without the **Inference** permission (the overview page says this fails with auth errors) | Create a new key at https://app.primeintellect.ai/dashboard/tokens with Inference enabled and set `PRIME_INTELLECT_API_KEY` | | `insufficient_funds` error | The billing account behind the key cannot pay for the call (https://docs.primeintellect.ai/inference/troubleshooting) | Add funds in the Billing Dashboard, and make sure the key belongs to the account that has funds | | Team credits are not used | Prime bills a team only when a request carries an `X-Prime-Team-ID` header, and this catalog entry sets no extra headers (the catalog schema has no field for one) | Without the header Prime bills the key owner's personal balance; fund that balance, or configure the header outside this entry | | Model not found | The roster changed since 2026-09-29, or the id differs in case (the roster has both `qwen/...` and `Qwen/...` ids) | Pick a current id, copied exactly, from the unauthenticated `GET /api/v1/models` roster | | Structured output ignored with tools attached | `structuredOutputWithTools` is `false` on this entry — untested combination | NeuroLink omits `response_format` automatically whenever tools are present, before sending | | Tool calls or `response_format` rejected | Support is per-model: e.g. `z-ai/glm-5.3` lists `tools` but not `response_format`, and `Qwen/Qwen3.5-122B-A10B` lists neither on the roster | Check the model's `supported_parameters` on the roster, or use a model that lists what you need (e.g. the default) | | A model always reasons before answering | The roster marks reasoning as mandatory on some models (`z-ai/glm-5.3`, `openai/gpt-oss-120b`) | Prefer the default, or a model whose roster `reasoning.mandatory` is `false` | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Recraft Provider Guide (image-gen) # Recraft Provider Guide **Raster + native SVG image generation via Recraft V3** ## Quick Start ### 1. Get an API Key [https://www.recraft.ai/profile/api](https://www.recraft.ai/profile/api) ### 2. Configure ```bash RECRAFT_API_KEY=your-key ``` ### 3. Generate an Image ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "recraft", model: "recraftv3", input: { text: "A minimal flat illustration of a coffee cup" }, }); ``` --- ## Supported Models | Model ID | Output | Notes | | --------------- | ------ | ------------------------- | | `recraftv3` | Raster | Default; current flagship | | `recraftv3-svg` | SVG | Native vector output | | `recraftv2` | Raster | Previous generation | --- ## CLI Usage ```bash pnpm run cli generate "Minimal flat coffee cup icon" \ --provider recraft --model recraftv3-svg --imageOutput ./cup.svg ``` --- ## Configuration Reference | Environment Variable | Required | Default | | -------------------- | -------- | ----------- | | `RECRAFT_API_KEY` | Yes | — | | `RECRAFT_MODEL` | No | `recraftv3` | --- ## See Also - [Stability AI Provider](/docs/getting-started/providers/stability) - [Ideogram Provider](/docs/getting-started/providers/ideogram) --- ## Reka AI Provider Guide # Reka AI Provider Guide Reka AI is a **Tier-2 catalog provider**: its entire integration is one JSON file (`src/lib/providers/catalog/reka.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** Reka's `GET https://api.reka.ai/v1/models` needs a key (it > answers HTTP 401 without one), so the four model ids come from Reka's public > docs ([Models page](https://docs.reka.ai/chat/models.md), retrieved > 2026-09-29 for the first three and 2026-10-17 for `reka-flash-3`) and the > roster has not been checked. No account was created, no > API key was used and no POST request was sent to build it. > `evidence.liveMatrix` is `null` until someone runs the live capability matrix > with a real key (see [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://platform.reka.ai/sign-up (the "Start for free" and "Get started" links on https://platform.reka.ai/pricing point to /sign-up). The Quickstart (https://docs.reka.ai/quickstart.md) says "Create a free account on the Reka Platform to access your API key." and the FAQ (https://docs.reka.ai/resources/faqs.md) answers "How do I get an API key?" with "Go to Platform, > API Keys to generate or copy your key." 2. Billing as the vendor states it: https://docs.reka.ai/pricing.md says "Get started with no upfront costs."; the FAQ (https://docs.reka.ai/resources/faqs.md) answers "Do I need to pre-pay?" with "Yes. Add credits to your account before making requests." and says the balance error reads "P001: Insufficient Balance" when the balance hits $0 3. Authentication: the vendor's REST examples send the header X-Api-Key (https://docs.reka.ai/chat/overview.md) and the OpenAPI file https://docs.reka.ai/openapi/api-reference.yaml declares one security scheme, an apiKey in the header X-Api-Key; the OpenAI Python SDK examples pass api_key="YOUR_API_KEY" to the client (https://docs.reka.ai/quickstart.md) 4. Set `REKA_API_KEY` in your .env file ### 2. Configure ```bash export REKA_API_KEY=your-api-key export REKA_MODEL=reka-flash # optional — overrides the default model export REKA_BASE_URL=https://api.reka.ai/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "reka", model: "reka-flash", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider reka ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "reka", credentials: { reka: { apiKey: process.env.REKA_API_KEY } }, }); ``` --- ## Billing What the vendor's pages say, as opened on 2026-09-29: - The Quickstart (https://docs.reka.ai/quickstart.md): "Create a free account on the Reka Platform to access your API key." - The FAQ (https://docs.reka.ai/resources/faqs.md), "Do I need to pre-pay?": "Yes. Add credits to your account before making requests." It adds that when the balance hits $0 the error reads "P001: Insufficient Balance". - The API pricing page (https://docs.reka.ai/pricing.md) has a "Pay as you go" heading and says "Get started with no upfront costs. You only pay for what you use." - The platform pricing page (https://platform.reka.ai/pricing) shows a "Pay as you go" tile with the text "Add credits only when you need them." and a "Start for free" link to /sign-up; the page also carries the text "Free credits used". `billingPolicy` holds `free-tier`, one of the three values the catalog schema allows (`free-tier`, `free-with-card`, `no-free-tier`). --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ---------------- | ------- | ------ | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `reka-flash` ⭐ | — | yes | $0.80 / $2.00 | NeuroLink default. Named in the code examples of the Chat overview, Function Calling and Chat API reference pages; the pricing page describes "Reka Flash" as "Fast and cost-efficient model for most tasks". | | `reka-edge` | — | yes | $0.10 / $0.10 | Listed as "reka-edge (or reka-edge-2603)" on the Models page and the Quickstart (2026-09-29); the pricing page describes "Reka Edge" as "Compact model ideal for on-device execution". Fallback. | | `reka-edge-2603` | — | yes | $0.10 / $0.10 | Named in the same table row as `reka-edge`; the Models page (2026-10-17) lists it with Tools = Yes, and shows it in the example output of `GET /v1/models`. Vision and prices are those of the `reka-edge` row. | | `reka-flash-3` | — | no | $0.10 / $0.20 | On the Models page (2026-10-17) with input "Text" and Tools = No, so NeuroLink never sends it a `tools` array. Prices are from its card at https://developer.reka.ai/models. | Model ids come from https://docs.reka.ai/chat/models.md. As read on 2026-09-29 it said "Our baseline models always available for public access are:" and listed `reka-flash` and `reka-edge (or reka-edge-2603)`; prices for those came from https://docs.reka.ai/pricing.md ("Input Tokens (per 1M)" and "Output Tokens (per 1M)" columns, rows named "Reka Flash" and "Reka Edge"). As read on 2026-10-17 the table lists `reka-edge-2603` and `reka-flash-3` (among other models) and no longer names `reka-flash` or `reka-edge`, and it says "`GET /v1/models` is the authoritative list". Whether the API still serves the two bare ids is not confirmed; it needs a key. The prices of `reka-flash-3` are those shown on its card at https://developer.reka.ai/models. **Vision:** the first curl example on https://docs.reka.ai/overview.md sends an `image_url` content part to `reka-flash`, and the Quickstart's "First request" example (https://docs.reka.ai/quickstart.md) sends an `image_url` content part to `reka-edge` with the comment `# or "reka-flash"`. The [Chat with Image, Video, and Audio page](https://docs.reka.ai/chat/chat-with-image-video-and-audio.md) says "The supported types are: `image_url`, `video_url`, `audio_url`, and `pdf_url`." **Context and output limits:** no per-model figure is set, so a Context cell shows "—". `models.defaultContextWindow` (16,384) and `models.defaultMaxOutputTokens` (4,096) are placeholders the vendor does not publish. The Chat API reference describes `max_tokens` as "limited by the model's context length. Defaults to 1024." **Status:** each model's `status` field in the JSON holds `production`, a placeholder for a value the catalog schema requires; it is not a vendor statement. **Fallback order** when the default is unavailable: `reka-edge`. The runtime fallback model name the loader derives (`fallbacks[0]`) is also `reka-edge`. **Other Reka models:** the Models page says "Other models may be available." and that the Get Models API "allows you to list what models you have available to you." The pricing page also has a row named "Reka Core". --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Reka AI — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Roster | unauthenticated `GET /v1/models` answered HTTP 401 on 2026-09-29, so the model ids come from https://docs.reka.ai/chat/models.md; **roster not verified** | | Auth-failure shape | the same GET returned the JSON body `{"error":{"message":"Unauthorized","type":"authentication_error","code":null,"param":null}}`; `evidence.authProbe` records status 401 and code `authentication_error` (the body's `error.type`, because `error.code` is null). `errorRules` match 401, 429, 500 and the FAQ's `P001` text | | Chat endpoint | an unauthenticated `GET /v1/chat/completions` answered HTTP 405 with header `allow: POST` and body `{"detail":"Method Not Allowed"}`; no POST request was sent | | Billing | https://docs.reka.ai/pricing.md says "Get started with no upfront costs."; the FAQ answers "Do I need to pre-pay?" with "Yes. Add credits to your account before making requests."; https://platform.reka.ai/pricing has a "Start for free" link and the text "Free credits used"; no signup was performed | | Sign-up page | on 2026-09-29 an unauthenticated GET of https://platform.reka.ai/ answered HTTP 404, while GET https://platform.reka.ai/sign-up and https://platform.reka.ai/pricing answered HTTP 200; `setup.url` is the sign-up page | | Auth header | the vendor's REST examples and OpenAPI file use `X-Api-Key`; the OpenAI Python SDK examples pass `api_key=` to the client. NeuroLink's Tier-2 client uses Bearer authentication, and no authenticated request could be made to exercise it | | Tools / structured output | tool support per model comes from https://docs.reka.ai/chat/models.md and https://docs.reka.ai/chat/overview.md (retrieved 2026-10-17); neither tools nor structured output was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. The command is `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=reka`, which needs a real key. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting Each row is the Error Type and Client Action columns of the table on https://docs.reka.ai/errors.md. | Symptom | Vendor statement | Vendor's client action | | -------- | ---------------------- | ---------------------------------------------------------------------------------------------- | | HTTP 401 | `authentication_error` | "Ensure that you're using a valid Reka API key" | | HTTP 429 | `rate_limit_error` | "Wait until your rate limit is restored and retry, or upgrade your API tier for higher limits" | | HTTP 500 | `server_error` | "Retry with backoff. If this persists, contact Reka at contact@reka.ai" | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Replicate Provider Guide # Replicate Provider Guide **One auth token, five modalities — LLMs + image + video + avatar + music under a single `REPLICATE_API_TOKEN`** ---------- | -------------------------------------------------------------------------- | ---------------------------------- | | **LLM** | `provider: "replicate"` chat / streaming | `meta/meta-llama-3.1-70b-instruct` | | **Image gen** | `provider: "replicate"` with a model id matching `IMAGE_GENERATION_MODELS` | `black-forest-labs/flux-1.1-pro` | | **Video** | `output: { mode: "video", video: { provider: "replicate" } }` | `atonamy/wan-alpha` | | **Avatar** | `output: { mode: "avatar", avatar: { provider: "replicate" } }` | `lucataco/musetalk` | | **Music** | `output: { mode: "music", music: { provider: "replicate" } }` | `meta/musicgen` | Architectural detail: see [`docs/provider-integration/22-adding-multimodal-provider.md`](/docs/provider-integration/22-adding-multimodal-provider) — Replicate is the canonical worked example. ### Key Facts - **Protocol**: Async prediction lifecycle — POST `/v1/predictions` → poll until `succeeded` → fetch output. NeuroLink uses `Prefer: wait=60` so short jobs complete in the initial POST and skip polling entirely. - **Default base URL**: `https://api.replicate.com` - **Auth**: `Authorization: Token $REPLICATE_API_TOKEN` - **Pricing**: Per compute-second (not per-token) — NeuroLink reports a symbolic per-token rate so cost dashboards stay populated, but real billing is via Replicate's invoice - **Streaming**: Synthetic single-chunk stream from the predict result (true SSE streaming planned for a follow-up) - **Tool calling**: Not supported — Replicate predictions are stateless - **Reasoning trace**: Model-dependent (e.g., DeepSeek R1 on Replicate exposes its reasoning trace in the output array) --- ## Quick Start ### 1. Get an API Token Sign up at [https://replicate.com/](https://replicate.com/) and create an API token at [https://replicate.com/account/api-tokens](https://replicate.com/account/api-tokens). ### 2. Configure Environment ```bash # Required REPLICATE_API_TOKEN=r8_... # Optional: override the default LLM model REPLICATE_MODEL=meta/meta-llama-3.1-70b-instruct # Optional: override the base URL # REPLICATE_BASE_URL=https://api.replicate.com ``` ### 3. Generate Your First Response ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "replicate", input: { text: "Explain how a transformer's attention mechanism works." }, }); console.log(result.content); ``` --- ## SDK Usage by Modality ### LLM (chat / streaming) ```typescript const result = await ai.generate({ provider: "replicate", model: "meta/meta-llama-3.1-405b-instruct", input: { text: "Write Python that calculates compound interest." }, }); ``` Streaming: ```typescript const stream = await ai.stream({ provider: "replicate", model: "meta/meta-llama-3.1-70b-instruct", input: { text: "Tell me a story" }, }); for await (const chunk of stream.stream) { if ("content" in chunk) process.stdout.write(chunk.content); } ``` ### Image Generation ```typescript const result = await ai.generate({ provider: "replicate", model: "black-forest-labs/flux-1.1-pro", input: { text: "A serene mountain lake at sunrise, photorealistic" }, }); const buffer = Buffer.from(result.imageOutput.base64, "base64"); require("fs").writeFileSync("./output.png", buffer); ``` Other supported image models on Replicate (pass via `model:`): - `black-forest-labs/flux-1.1-pro` (default) - `black-forest-labs/flux-schnell` - `stability-ai/stable-diffusion-3.5-large` - `stability-ai/stable-diffusion-3.5-large-turbo` - `playgroundai/playground-v2.5-1024px-aesthetic` - `ideogram-ai/ideogram-v3` ### Video Generation ```typescript const sourceImage = readFileSync("./input.jpg"); const result = await ai.generate({ input: { text: "smooth zoom out", images: [sourceImage] }, output: { mode: "video", video: { provider: "replicate", model: "atonamy/wan-alpha", length: 4, aspectRatio: "16:9", }, }, }); require("fs").writeFileSync("./output.mp4", result.video.data); ``` ### Avatar (MuseTalk) ```typescript const portrait = readFileSync("./portrait.jpg"); const audio = readFileSync("./narration.mp3"); const result = await ai.generate({ output: { mode: "avatar", avatar: { provider: "replicate", // or "musetalk" alias image: portrait, audio, }, }, }); require("fs").writeFileSync("./avatar.mp4", result.avatar.buffer); ``` ### Music Generation (MusicGen) ```typescript const result = await ai.generate({ output: { mode: "music", music: { provider: "replicate", // or "musicgen" alias prompt: "Lo-fi hip-hop beat with vinyl crackle", duration: 8, tempo: 80, }, }, }); require("fs").writeFileSync("./track.mp3", result.music.buffer); ``` --- ## CLI Usage ```bash # LLM pnpm run cli generate "Hello" --provider replicate # Image gen pnpm run cli generate "A red panda" --provider replicate \ --model black-forest-labs/flux-1.1-pro --imageOutput ./panda.png # Video gen pnpm run cli generate "smooth pan" --image ./input.jpg \ --outputMode video --videoProvider replicate \ --videoOutput ./out.mp4 # Avatar pnpm run cli generate --outputMode avatar \ --avatarProvider replicate \ --avatarImage ./portrait.jpg \ --avatarAudio ./narration.mp3 \ --avatarOutput ./avatar.mp4 # Music pnpm run cli generate "Lo-fi beat" \ --outputMode music --musicProvider replicate \ --musicTempo 80 --musicDuration 8 --musicOutput ./track.mp3 ``` --- ## Configuration Reference | Environment Variable | Required | Default | Description | | --------------------- | -------- | ---------------------------------- | ------------------------------ | | `REPLICATE_API_TOKEN` | Yes | — | Replicate API token (`r8_...`) | | `REPLICATE_MODEL` | No | `meta/meta-llama-3.1-70b-instruct` | Default LLM model | | `REPLICATE_BASE_URL` | No | `https://api.replicate.com` | Base URL | --- ## Feature Support Matrix | Feature | LLM | Image | Video | Avatar | Music | | ----------------- | ------------------------ | ------------- | ----------------- | ------ | ----- | | Streaming | Synthetic (single chunk) | N/A | N/A | N/A | N/A | | Tool calling | No | N/A | N/A | N/A | N/A | | Structured output | Limited | N/A | N/A | N/A | N/A | | Vision input | Model-dependent | Yes (img2img) | Yes (start frame) | Yes | No | --- ## Cost Notes Replicate bills by **compute seconds**, not by tokens. NeuroLink reports a symbolic per-token rate so cost-attribution dashboards have non-zero values, but the authoritative billing is from Replicate's own [pricing dashboard](https://replicate.com/account/billing). --- ## Troubleshooting ### "Invalid Replicate API token" ```bash echo $REPLICATE_API_TOKEN export REPLICATE_API_TOKEN=r8_... ``` Get / rotate at [https://replicate.com/account/api-tokens](https://replicate.com/account/api-tokens). ### "Replicate model 'X' not found" Use the `owner/name` or `owner/name:version` format. Browse the catalog at [https://replicate.com/explore](https://replicate.com/explore). ### Cold-start delays First-call latency on rare models can spike (the inference container needs to warm). Subsequent calls reuse the warm container. NeuroLink caps polling at 5 minutes by default — bump `REPLICATE_BASE_URL` and `Prefer: wait=60` configuration in the lifecycle helper if you regularly hit this. ### Streaming feels chunky The current implementation runs the prediction synchronously and emits a single chunk. True SSE streaming is planned — for now use OpenAI / xAI / Groq for low-latency token streaming. ### Output is a URL, not base64 NeuroLink downloads the URL and converts to base64 to keep the `imageOutput` contract uniform. If you see a raw URL in the result, the download failed — check network access and Replicate's CDN status. --- ## See Also - [Adding a multi-modal provider](/docs/provider-integration/22-adding-multimodal-provider) — Replicate as the canonical example - [Adding a new modality](/docs/provider-integration/21-adding-new-modality) — how Avatar / Music categories were built - [Video Generation](/docs/features/video-generation) — feature page covering Vertex / Kling / Runway / Replicate - [`docs/provider-integration/22-adding-multimodal-provider.md`](/docs/provider-integration/22-adding-multimodal-provider) — implementation notes --- **Need Help?** Open a [GitHub Discussion](https://github.com/juspay/neurolink/discussions) or [issue](https://github.com/juspay/neurolink/issues). --- ## Runway Provider Guide (video) # Runway Provider Guide **Image-to-video generation via Runway Gen-3 / Gen-4** ## Quick Start ### 1. Get an API Key [https://app.runwayml.com/settings/developer](https://app.runwayml.com/settings/developer) ### 2. Configure ```bash RUNWAY_API_KEY=your-key ``` ### 3. Generate a Video ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "runway", output: { mode: "video", video: { provider: "runway", resolution: "720p", length: 5 }, }, input: { text: "Sci-fi establishing shot, soft golden hour light", images: [readFileSync("./input.jpg")], }, }); if (result.video?.data) { writeFileSync("./output.mp4", result.video.data); } ``` --- ## CLI Usage ```bash pnpm run cli generate "Camera slowly orbits the subject" \ --image ./portrait.jpg \ --provider runway --videoOutput ./output.mp4 ``` --- ## Configuration Reference | Environment Variable | Required | Description | | -------------------- | -------- | -------------- | | `RUNWAY_API_KEY` | Yes | Runway API key | --- ## See Also - [Kling Provider](/docs/getting-started/providers/kling) - [Vertex Veo Provider](/docs/getting-started/providers/google-vertex) --- ## Amazon SageMaker Provider Guide # Amazon SageMaker Provider Guide **Custom model endpoints on AWS SageMaker infrastructure** > **Version:** 9.26.x | **Status:** General Availability | **Streaming:** Not Available (see warning below) ------------- | ------------- | --------------------------------------------------- | ---------------------------------- | | **Llama** | `llama` | Meta Llama models deployed via JumpStart or custom | General-purpose, cost-effective | | **Mistral** | `mistral` | Mistral AI models on SageMaker | Coding, European compliance | | **Claude** | `claude` | Anthropic Claude models via custom containers | Complex reasoning | | **Hugging Face** | `huggingface` | Any Hugging Face Hub model via SageMaker containers | NLP, classification, summarization | | **JumpStart** | `jumpstart` | AWS JumpStart pre-built model packages | Quick deployment, managed updates | | **Custom** | `custom` | Any custom inference container or algorithm | Proprietary models, specialized | --- ## Quick Start ### 1. Deploy a Model Endpoint Before using the SageMaker provider, you need a running SageMaker endpoint. You can create one through the AWS Console, AWS CLI, or SageMaker SDK. ```bash # Example: Deploy a JumpStart Llama model via AWS CLI aws sagemaker create-endpoint \ --endpoint-name my-llama-endpoint \ --endpoint-config-name my-llama-config \ --region us-east-1 ``` Or via the AWS Console: 1. Open [SageMaker Console](https://console.aws.amazon.com/sagemaker) 2. Navigate to **Inference** > **Endpoints** 3. Create a new endpoint with your model 4. Wait for the endpoint status to become **InService** ### 2. Configure Environment Variables ```bash # Required: AWS credentials export AWS_ACCESS_KEY_ID=your_access_key export AWS_SECRET_ACCESS_KEY=your_secret_key # Required: SageMaker endpoint name export SAGEMAKER_DEFAULT_ENDPOINT=my-llama-endpoint # Optional: Region (defaults to us-east-1) export SAGEMAKER_REGION=us-east-1 # Optional: Model identifier export SAGEMAKER_MODEL=my-custom-llama # Optional: Model type for request formatting export SAGEMAKER_MODEL_TYPE=llama ``` ### 3. Use with NeuroLink SDK ```typescript const ai = new NeuroLink(); const result = await ai.generate({ input: { text: "Explain quantum computing in simple terms." }, provider: "sagemaker", }); console.log(result.content); ``` ### 4. Use with NeuroLink CLI ```bash # Basic generation neurolink generate "Explain quantum computing" --provider sagemaker # With specific model name neurolink generate "Write a haiku" --provider sagemaker --model my-custom-model ``` --- ## Environment Variables ### AWS Credentials (Required) | Variable | Required | Description | | ----------------------- | -------- | --------------------------------------------- | | `AWS_ACCESS_KEY_ID` | Yes | AWS access key ID for authentication | | `AWS_SECRET_ACCESS_KEY` | Yes | AWS secret access key for authentication | | `AWS_SESSION_TOKEN` | No | Session token for temporary credentials (STS) | ### Region Configuration Region is resolved in priority order: 1. Constructor `region` parameter (highest priority) 2. `SAGEMAKER_REGION` environment variable 3. `AWS_REGION` environment variable 4. `"us-east-1"` (default) | Variable | Default | Description | | ------------------ | ------------- | ---------------------------------- | | `SAGEMAKER_REGION` | - | SageMaker-specific region override | | `AWS_REGION` | `"us-east-1"` | General AWS region | ### Endpoint Configuration Endpoint name is resolved in priority order: 1. `SAGEMAKER_DEFAULT_ENDPOINT` 2. `SAGEMAKER_ENDPOINT_NAME` 3. `"default-endpoint"` (fallback; will fail connectivity checks) | Variable | Default | Description | | ---------------------------- | ------- | ----------------------------------------------------- | | `SAGEMAKER_DEFAULT_ENDPOINT` | - | Primary endpoint name (recommended) | | `SAGEMAKER_ENDPOINT_NAME` | - | Alternate endpoint name variable | | `SAGEMAKER_ENDPOINT` | - | Custom AWS service endpoint URL (for VPC/PrivateLink) | :::note[SAGEMAKER_ENDPOINT vs SAGEMAKER_DEFAULT_ENDPOINT] `SAGEMAKER_ENDPOINT` sets a custom AWS service URL (e.g., a VPC endpoint), while `SAGEMAKER_DEFAULT_ENDPOINT` and `SAGEMAKER_ENDPOINT_NAME` set the name of your deployed SageMaker model endpoint. ::: ### Model Configuration Model name is resolved in priority order: 1. `SAGEMAKER_MODEL` 2. `SAGEMAKER_MODEL_NAME` 3. `"sagemaker-model"` (default) | Variable | Default | Description | | ---------------------- | ------------------- | ------------------------------------------------------------------------------ | | `SAGEMAKER_MODEL` | `"sagemaker-model"` | Model identifier | | `SAGEMAKER_MODEL_NAME` | - | Alternate model name variable | | `SAGEMAKER_MODEL_TYPE` | `"custom"` | Model type: `llama`, `mistral`, `claude`, `huggingface`, `jumpstart`, `custom` | ### Request Configuration | Variable | Default | Description | | ----------------------------- | -------------------- | --------------------------------------------------- | | `SAGEMAKER_CONTENT_TYPE` | `"application/json"` | Content-Type header for requests | | `SAGEMAKER_ACCEPT` | `"application/json"` | Accept header for responses | | `SAGEMAKER_CUSTOM_ATTRIBUTES` | - | Custom attributes passed to the endpoint | | `SAGEMAKER_INPUT_FORMAT` | `"custom"` | Input format: `huggingface`, `jumpstart`, `custom` | | `SAGEMAKER_OUTPUT_FORMAT` | `"custom"` | Output format: `huggingface`, `jumpstart`, `custom` | ### Generation Defaults | Variable | Default | Description | | -------------------------- | ------- | --------------------------------------------------- | | `SAGEMAKER_MAX_TOKENS` | - | Maximum tokens to generate (model default if unset) | | `SAGEMAKER_TEMPERATURE` | - | Temperature for sampling (0.0 - 2.0) | | `SAGEMAKER_TOP_P` | - | Top-p (nucleus) sampling (0.0 - 1.0) | | `SAGEMAKER_STOP_SEQUENCES` | - | Comma-separated stop sequences | ### Client Configuration | Variable | Default | Description | | ----------------------- | ------- | --------------------------------------------- | | `SAGEMAKER_TIMEOUT` | `30000` | Request timeout in milliseconds (1000-300000) | | `SAGEMAKER_MAX_RETRIES` | `3` | Maximum retry attempts (0-10) | --- ## SDK Usage ### Basic Generation ```typescript const ai = new NeuroLink(); const result = await ai.generate({ input: { text: "Summarize the benefits of serverless architecture." }, provider: "sagemaker", }); console.log(result.content); ``` ### With Configuration Options ```typescript const result = await ai.generate({ input: { text: "Write a technical blog post about MLOps." }, provider: "sagemaker", model: "my-fine-tuned-llama", temperature: 0.8, maxTokens: 2000, }); ``` ### Testing Connectivity ```typescript const provider = new AmazonSageMakerProvider( "my-model", // model name "my-endpoint", // endpoint name "us-east-1", // region ); // Test configuration validity const connectionTest = await provider.testConnection(); console.log("Connected:", connectionTest.connected); // Get provider info const info = provider.getSageMakerInfo(); console.log("Endpoint:", info.endpointName); console.log("Model type:", info.modelType); console.log("Region:", info.region); ``` --- ## CLI Usage ### Basic Commands ```bash # Generate with SageMaker neurolink generate "Your prompt here" --provider sagemaker # Use provider alias neurolink generate "Your prompt here" --provider aws-sagemaker # Specify model name neurolink generate "Your prompt here" --provider sagemaker --model my-llama-model # With temperature neurolink generate "Creative writing task" --provider sagemaker --temperature 0.9 ``` ### Loop Mode ```bash # Start interactive session with SageMaker neurolink loop --provider sagemaker # Inside loop: # > set provider sagemaker # > set model my-fine-tuned-model # > Explain the transformer architecture ``` --- ## Feature Support ### Streaming: NOT Supported :::danger[Streaming Limitation] Calling `neurolink.stream()` with the SageMaker provider will throw a `SageMakerError`: ``` SageMaker streaming not yet fully implemented. Coming in next phase. ``` **Error details:** Code `MODEL_ERROR`, HTTP status 501. **Workaround:** Use `neurolink.generate()` instead. If you need streaming behavior in your application, consider using a different provider (e.g., Bedrock, OpenAI) or implement application-level chunking of the generate response. ::: ### Embeddings: NOT Supported The SageMaker provider does not implement `embed()` or `embedMany()`. Calling these methods will throw an error from the base provider. For embeddings on AWS, use the [AWS Bedrock provider](/docs/getting-started/providers/aws-bedrock) with Amazon Titan Embeddings or Cohere Embed models. ### Tool Use The SageMaker provider includes tool calling support at the language model level. Tools are converted to a format compatible with SageMaker endpoints. However, tool calling behavior depends entirely on the model deployed behind your endpoint: - Models that support function calling (e.g., fine-tuned Llama, Claude) should work with NeuroLink's tool system - Custom models or older model versions may not understand tool call formats - Test tool calling with your specific endpoint before relying on it in production ### Structured Output The provider supports `json_object` and `json_schema` response formats for models that can produce structured JSON. Again, actual support depends on the deployed model's capabilities. ### Batch Inference The SageMaker language model supports batch processing of multiple prompts with adaptive concurrency control: - Dynamic concurrency adjustment based on endpoint response times - Automatic error recovery for individual prompts in a batch - Configurable concurrency limits --- ## IAM Permissions ### Minimum Required Policy ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sagemaker:InvokeEndpoint", "sagemaker:InvokeEndpointWithResponseStream" ], "Resource": "arn:aws:sagemaker:*:ACCOUNT_ID:endpoint/*" } ] } ``` ### Restrictive Policy (Recommended for Production) ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sagemaker:InvokeEndpoint", "sagemaker:InvokeEndpointWithResponseStream" ], "Resource": [ "arn:aws:sagemaker:us-east-1:ACCOUNT_ID:endpoint/my-llama-endpoint", "arn:aws:sagemaker:us-east-1:ACCOUNT_ID:endpoint/my-mistral-endpoint" ] } ] } ``` ### Setup via AWS CLI ```bash # Create IAM policy cat > sagemaker-invoke-policy.json trust-policy.json < # Sakana AI Provider Guide Sakana AI is a **Tier-2 catalog provider**: it is expressed as OpenAI-wire-compatible with no quirks block, so its entire integration is one JSON file (`src/lib/providers/catalog/sakana-ai.json`) rather than hand-written code. That file is the source of truth for the facts on this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** The vendor's `GET https://api.sakana.ai/v1/models` needs a > key (it answers HTTP 401 without one), so the model ids come from Sakana AI's > public Models page and the roster has not been checked. No account was created > and no API key was used to build it. `evidence.liveMatrix` is `null` until > someone runs the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://console.sakana.ai/overview and sign in - the page shows "Login with Google" and "Send login link" 2. Create an API key - the Get Started page (https://console.sakana.ai/get-started) says: "Before using Fugu or Sakana Namazu, create an API key and copy the generated key. The key is shown only once, so store it somewhere secure before closing the dialog." 3. Billing as the vendor states it: the Pricing page (https://console.sakana.ai/pricing) lists Pay as you go rates per model and Subscription Plans (Standard $20/month, Pro $100/month, Max $200/month); the Get Started page says Sakana Namazu "is billed purely on a pay-as-you-go (per-token) basis." 4. Set `SAKANA_AI_API_KEY` in your .env file (`SAKANA_API_KEY`, which the Get Started page's curl example reads, is accepted as a fallback; the Models page's Python example reads `FUGU_API_KEY` and `FUGU_BASE_URL`, which NeuroLink does not) ### 2. Configure ```bash export SAKANA_AI_API_KEY=your-api-key export SAKANA_AI_MODEL=fugu # optional — overrides the default model export SAKANA_AI_BASE_URL=https://api.sakana.ai/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "sakana-ai", model: "fugu", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider sakana-ai ``` Per-request credentials work as they do for other providers: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "sakana-ai", credentials: { sakanaAi: { apiKey: process.env.SAKANA_AI_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out (cached) | Notes | | -------------------- | ------- | ------ | --------------------- | --------------------------------------------------------------------------------------------------------------- | | `fugu` ⭐ | 1M | yes | not recorded | NeuroLink default. Models page: "The default Fugu model." Fugu overview: "the ideal default for everyday work." | | `fugu-ultra` | 1M | yes | $5 / $30 ($0.50) | Models page: "The Fugu Ultra model, defaults to fugu-ultra-v2.0." Priced as `fugu-ultra-v2.0`. | | `fugu-ultra-v2.0` | 1M | yes | $5 / $30 ($0.50) | Models page: "V2.0 of Fugu Ultra." Pricing page: "Fixed pricing for fugu-ultra-v2.0 per 1M tokens." | | `fugu-ultra-v1.1` | 1M | yes | not recorded | Models page: "V1.1 of Fugu Ultra." | | `fugu-ultra-v1.0` | 1M | yes | not recorded | Models page: "V1.0 of Fugu Ultra, also known as fugu-ultra-20260615." | | `fugu-max` | 1M | yes | $2 / $6 ($0.25) | Models page: "The Fugu Max model, defaults to fugu-max-v1.0." Priced as `fugu-max-v1.0`. | | `fugu-max-v1.0` | 1M | yes | $2 / $6 ($0.25) | Models page: "V1.0 of Fugu Max, optimized for cost-performance." Pricing page: "regardless of context length." | | `sakana-namazu` | 256K | yes | $0.95 / $4.00 ($0.15) | Models page: "Alias that points to the latest version (currently sakana-namazu-v1.0)." | | `sakana-namazu-v1.0` | 256K | yes | $0.95 / $4.00 ($0.15) | Models page: "V1.0 of the Sakana Namazu model. A Japanese-specialized LLM." | **Sources.** Model ids come from the Supported models table on [console.sakana.ai/models](https://console.sakana.ai/models) (retrieved 2026-09-29); the Sakana Namazu property table is on the tab at [console.sakana.ai/models?model=sakana-namazu](https://console.sakana.ai/models?model=sakana-namazu). Prices come from [console.sakana.ai/pricing](https://console.sakana.ai/pricing): `fugu-ultra-v2.0` Standard price column $5 input, $30 output, $0.50 cached input (the Context > 272K column reads $10, $45 and $1.00), `fugu-max-v1.0` $2 input, $6 output, $0.25 cached input, and `sakana-namazu-v1.0` $0.95 input, $4.00 output, $0.15 cached input. The Pricing page's Fugu table says, for one agent, "You pay only the standard rate for the specific underlying model." and, for multiple agents, "We never stack model fees. You are charged a single rate based on the top tier model involved." No price is recorded for `fugu`, `fugu-ultra-v1.1` or `fugu-ultra-v1.0`. **Context and vision.** The Get Started page's Codex model catalog snippet lists `context_window` 1000000 and `input_modalities` text and image for the slugs `fugu`, `fugu-ultra` (display name "Fugu Ultra v2.0"), `fugu-max`, `fugu-ultra-v1.1` and `fugu-ultra-v1.0`. `fugu-ultra-v2.0` and `fugu-max-v1.0` take the same values as the slugs that the Models page says default to them. The Sakana Namazu tab lists Context window "256K tokens" (stored as 256000) and Image input "Supported (URL and base64)". `models.defaultContextWindow` (128,000) and `models.defaultMaxOutputTokens` (8,192) are conservative placeholders the vendor does not publish. **Fallback order** when the default is unavailable: `fugu-ultra` → `fugu-max` → `sakana-namazu`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `fugu-max`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Sakana AI — **docs-verified only, not yet live-verified**: | Probe | Result | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://api.sakana.ai/v1/models` answers HTTP 401 without a key, 2026-09-29 — model ids are taken from https://console.sakana.ai/models; the roster has not been checked | | Auth-failure shape | unauthenticated `GET /v1/models` returned HTTP 401 with JSON body `{"error":{"message":"Missing API key","type":"authentication_error","param":null,"code":null}}`, 2026-09-29; `errorRules` holds one rule, for status 401, and `evidence.authProbe.code` records the body's `error.type` because `error.code` is null. An unauthenticated `GET /v1/chat/completions` answered HTTP 405 | | Billing | the Pricing page lists Pay as you go rates and Subscription Plans at $20/month, $100/month and $200/month; the Get Started page says Sakana Namazu "is billed purely on a pay-as-you-go (per-token) basis", 2026-09-29 — no sign-up performed | | Tools / structured output | documented in the Chat Completions field tables on the Models page; neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=sakana-ai` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting Each row below is a statement from a Sakana AI page or the observed response body; NeuroLink has not exercised them with a key. | Symptom | What the vendor page or response says | Source | | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | | HTTP 401 with `error.message` "Missing API key" | Body returned by an unauthenticated `GET https://api.sakana.ai/v1/models` on 2026-09-29; the Get Started page's curl example sends the header `Authorization: Bearer $SAKANA_API_KEY` | api.sakana.ai response; Get Started page | | Client-side timeouts with `fugu-ultra` | "For complex tasks, especially when using fugu-ultra and fugu-cyber, you may need to increase client-side timeouts." | Get Started page | | `sakana-namazu` requests and a subscription | "Sakana Namazu is not included in subscription plans — it is billed purely on a pay-as-you-go (per-token) basis." | Get Started page | | A `fugu-cyber` id is needed | "In order to use Fugu Cyber, users must submit an access request form detailing their intended use case and providing verified contact information." | Models page | | Sampling fields have no effect | The Fugu Chat Completions table lists `temperature`, `top_p`, `stop`, `seed`, `frequency_penalty` and `presence_penalty` as "Accepted but ignored." | Models page | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## SambaNova Provider Guide # SambaNova Provider Guide **Open-weight flagships (Llama 3.3 70B, GPT-OSS 120B, DeepSeek V3.x, MiniMax, Gemma 4) on SambaNova's RDU-accelerated cloud** ## Quick Start ### 1. Get an API Key Sign up at [https://cloud.sambanova.ai](https://cloud.sambanova.ai) (Google/Microsoft OAuth), complete the profile step, add a payment method + credits under **Plans → Billing**, and create a key under **API Keys**. ### 2. Configure Environment ```bash # Required SAMBANOVA_API_KEY=... # Optional: override the default model SAMBANOVA_MODEL=gpt-oss-120b # Optional: override the base URL # SAMBANOVA_BASE_URL=https://api.sambanova.ai/v1 ``` ### 3. Generate Your First Response ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "sambanova", input: { text: "What is a reconfigurable dataflow unit?" }, }); console.log(result.content); ``` --- ## CLI Usage ```bash pnpm run cli generate "Quick question" --provider sambanova pnpm run cli stream "Count to ten" --provider sambanova pnpm run cli generate "Hi" --provider sambanova --model gpt-oss-120b ``` --- ## Configuration Reference | Environment Variable | Required | Default | Description | | -------------------- | -------- | ----------------------------- | ----------------- | | `SAMBANOVA_API_KEY` | Yes | — | SambaNova API key | | `SAMBANOVA_MODEL` | No | `Meta-Llama-3.3-70B-Instruct` | Default model | | `SAMBANOVA_BASE_URL` | No | `https://api.sambanova.ai/v1` | Base URL | --- ## Troubleshooting ### 402 on every call / "PAYMENT_METHOD_REQUIRED" The account has no credits — new accounts have no free allowance. Add a payment method and purchase credits at [cloud.sambanova.ai/plans/billing](https://cloud.sambanova.ai/plans/billing). ### "Invalid SambaNova API key" ```bash test -n "$SAMBANOVA_API_KEY" && echo "SAMBANOVA_API_KEY is set" || echo "SAMBANOVA_API_KEY is missing" ``` Rotate at [cloud.sambanova.ai/apis](https://cloud.sambanova.ai/apis). A bad key returns an OpenAI-shaped 401 with `"code": "invalid_api_key"`. ### 404 for a model that used to exist Preview models (`DeepSeek-V3.2`, `gemma-4-31B-it`) "may be removed at short notice" per the vendor. Verify with an authenticated `GET https://api.sambanova.ai/v1/models`. --- ## See Also - [Cerebras Provider](/docs/getting-started/providers/cerebras) — sibling wafer-scale speed provider - [Groq Provider](/docs/getting-started/providers/groq) — sibling LPU speed provider - [Tier 2 catalog entry guide](/docs/provider-integration/tiers/tier-2-catalog-entry) — internal wiring --- **Need Help?** Open a [GitHub Discussion](https://github.com/juspay/neurolink/discussions) or [issue](https://github.com/juspay/neurolink/issues). --- ## Sarvam AI Provider Guide # Sarvam AI Provider Guide Sarvam AI is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/sarvam.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status: docs- and roster-verified, not yet live-verified.** > This entry was onboarded credential-free — no Sarvam API key was ever > created or used. Every field below is sourced from Sarvam's own published > docs plus one unauthenticated `GET /v1/models` call; no authenticated > request (chat completion, streaming, tool call, structured output) has > been made against the live API. Treat `tools`, `structuredOutput`, > `toolsWithStreaming` and `thinking` as documented, not wire-proven, until > `evidence.liveMatrix` is filled in by a live capability sweep. See > [Verification status](#verification-status) below for exactly what is and > isn't proven. ## Quick Start ### 1. Get an API key 1. Visit: https://dashboard.sarvam.ai and sign in or create an account 2. Create an API subscription key from the dashboard (documented format: `sk_xxx`) 3. Every new account receives ₹100 in starter credits, then usage-based billing applies — see the [pricing page](https://docs.sarvam.ai/api/getting-started/pricing.md); no ongoing free tier beyond that starter credit is documented 4. Set `SARVAM_API_KEY` in your .env file ### 2. Configure ```bash export SARVAM_API_KEY=your-api-key export SARVAM_MODEL=sarvam-105b # optional — overrides the default model export SARVAM_BASE_URL=https://api.sarvam.ai/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "sarvam", model: "sarvam-105b", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider sarvam ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "sarvam", credentials: { sarvam: { apiKey: process.env.SARVAM_API_KEY } }, }); ``` ### Authentication note Sarvam's own raw-HTTP API reference examples authenticate with a standard `Authorization: Bearer ` header — exactly what NeuroLink's generic OpenAI-compatible provider sends, so no custom auth-header quirk is needed. Sarvam's stated preference is instead an `api-subscription-key` header, which its Python/TypeScript SDKs use; the docs say both are accepted on every endpoint. --- ## Models | Model | Context | Vision | $/M in · out | Notes | | --------------------------- | ------- | ------ | ------------ | -------------------------------------------------------------------------------------------------- | | `sarvam-105b` ⭐ | 128K | no | — | Recommended — flagship model, documented for "complex reasoning and agentic tasks." Default model. | | `sarvam-105b-conversations` | 32K | no | — | Documented for "real-time conversational and voice-agent workloads." Fallback. | Context window shown is each model's documented figure (128K / 32K). The catalog's `defaultMaxOutputTokens` is 2048 — the vendor's documented default for the `max_tokens` request parameter when a caller omits it, not a stated maximum (the docs say no maximum is documented). **Pricing** is published only in Indian Rupees, not USD: ₹29.28 input / ₹73.2 output / ₹10.98 cached-input per 1M tokens for both models (identical rates), per the [pricing page](https://docs.sarvam.ai/api/getting-started/pricing.md) (retrieved 2026-09-28). The catalog's `pricingPerMTok` field is left unset for both models rather than placing that INR figure in a field every other provider in this catalog uses for USD — there is no vendor-stated INR/USD rate to convert by without inventing a number. **Fallback order** when the default is unavailable: `sarvam-105b-conversations`. Neither model is documented as vision-capable. The request schema does declare an `image_url` content-part type (the standard OpenAI-compatible message shape), but Sarvam's docs make no claim that either model actually processes image input, so both are marked `vision: false`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for Sarvam AI — and, unusually, all of it is credential-free: | Probe | Result | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | **Unauthenticated** GET `https://api.sarvam.ai/v1/models`, HTTP 200, 2026-09-28 — returned exactly `sarvam-105b` and `sarvam-105b-conversations`, no API key used. | | Auth rejection | Not probed live (would require a POST request, out of scope for credential-free onboarding). The 403 shape below is transcribed from Sarvam's own authentication docs, not observed. | | Wire compatibility | Documentary only — Sarvam's API reference explicitly describes an OpenAI-shaped `messages` / `choices` / `finish_reason` / `object: "chat.completion"` schema, `tools`/`tool_choice`, `response_format` (`json_schema`, `json_object`), and `stream: true` (SSE) for this endpoint. | | Live capability sweep | **Not run.** `evidence.liveMatrix` is `null`. `tools`, `structuredOutput`, `toolsWithStreaming` and `thinking` in the catalog reflect vendor documentation, not a live probe; `structuredOutputWithTools` is `false` because no combined tools+schema request was possible without a key. | Documented auth failure shape (from [Sarvam's authentication docs](https://docs.sarvam.ai/api-reference/authentication), not independently observed): HTTP **403**, not 401 — Sarvam's docs state "Auth failures return HTTP `403`, not `401`" and use the same code for both bad keys and valid-but-forbidden requests: ```json { "error": { "code": "invalid_api_key_error", "message": "Invalid API key" } } ``` --- ## Troubleshooting | Symptom | Cause | Fix | | ------------------------------------------ | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- | | `Invalid Sarvam AI API key` | `SARVAM_API_KEY` unset or wrong | Check the key at https://dashboard.sarvam.ai | | HTTP 403 on every call | Sarvam returns 403 (not 401) for both bad and forbidden keys | Confirm the key is current and has access; see `error.code` in the response | | Model not found | Only `sarvam-105b` and `sarvam-105b-conversations` exist | Use one of those two ids — the endpoint serves no others | | Empty/short replies at a small `maxTokens` | `reasoning_effort` defaults to `medium`, and `reasoning_content` is billed as output | Give reasoning prompts a generous `maxTokens` budget or lower `reasoning_effort` | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## ScaleDown Provider Guide # ScaleDown Provider Guide **A provider of `decide`** — the same typed `boolean` / `choice` / `score` answers as [TypeSafe's Jev](/docs/getting-started/providers/typesafe), [Laya](/docs/getting-started/providers/laya), [XOR](/docs/getting-started/providers/xor), [SubQ](/docs/getting-started/providers/subq), [Perplexity](/docs/getting-started/providers/perplexity-decider), [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef) and [OpenAI Decisions](/docs/getting-started/providers/openai-decisions), from ScaleDown's hosted Classify models. It emits no text at all. > **Where the facts about ScaleDown come from.** Everything this guide says about > ScaleDown's endpoint comes from ScaleDown's own documentation and from probes > that the marketing session made on 2026-10-15. NeuroLink's project did not > probe it: no request to ScaleDown was made in building this provider, and the > 200 replies in NeuroLink's tests are stand-ins written from the documented > shape, and the error texts in the mocked tests are the ones the marketing > session reported. > The passages on the 402, the 422, the default timeout and the billing of > options also use a live test of this provider that the marketing session ran on > 2026-10-20 (301 `decide()` calls, 295 answered); each says so where it does. > Each item that nobody measured is listed under > [Not measured](#not-measured). ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Provider id | `scaledown`; the alias `scaledown-classify` names it too | | Inference type | `decide` only | | Models | `classify-1` (the default) and `classify`, which ScaleDown describes as its latest Classify model. Any other name is refused by ScaleDown with HTTP 422. `SCALEDOWN_MODEL` sets one | | Key | `SCALEDOWN_API_KEY`, or `credentials.scaledown.apiKey`. The variable is ScaleDown's own: no text provider reads it | | Key header | `x-api-key: `. NeuroLink never sends `Authorization: Bearer` to ScaleDown | | Endpoint | `POST https://api.scaledown.xyz/v1/scaledown`; `SCALEDOWN_BASE_URL` or `credentials.scaledown.baseURL` can name another base URL (see [Base URL](#base-url)) | | State | text only: a string goes out unchanged, any other value as its JSON text; see [How the state is sent](#how-the-state-is-sent) | | Questions per request | no cap declared | | State window | none declared, so nothing is refused locally on size; ScaleDown's input ceiling is not measured | | Media | none. Images and video attached to a `decide()` call are refused before any request; see [Images and video](#images-and-video) | | Default timeout | 30 seconds per attempt, declared in the entry; `timeoutMs` or `--timeout` replaces it; see [Timeouts](#timeouts) | | Cost | priced per input token, input only; see [Cost](#cost) for the rate, its source and its date | | Precedence | the last of the eight: used automatically only when none of TypeSafe, Laya, XOR, SubQ, Perplexity, Cloudflare Clef or OpenAI Decisions is configured | | Status | NeuroLink lists both models as `preview` | --- ## Quick Start ### 1. Get a key Create an account and an API key by following [ScaleDown's documentation](https://docs.scaledown.ai). Sign-up gives a free allowance; its expiry is not established. ScaleDown's documentation says a request made with no credit left returns HTTP 402, and a live test saw it return 402 for a key it does not recognise too (see [Errors](#errors)). ### 2. Configure Set the key in the environment: ```bash export SCALEDOWN_API_KEY=... # the key from ScaleDown export SCALEDOWN_MODEL=classify-1 # optional export SCALEDOWN_BASE_URL=https://api.scaledown.xyz # optional; see "Base URL" ``` or in the config passed to the SDK, exactly as for any other provider. Values passed per call override the constructor's, which override the environment: ```typescript // For the whole instance const neurolink = new NeuroLink({ credentials: { scaledown: { apiKey: process.env.MY_SCALEDOWN_KEY }, }, }); // Or for one call await neurolink.decide({ provider: "scaledown", credentials: { scaledown: { apiKey: process.env.MY_SCALEDOWN_KEY }, }, state: "We were billed twice for March. Please refund it today.", questions: { urgent: { type: "boolean", instructions: "Is this urgent?" }, }, }); ``` `credentials.scaledown` is its own slice (`apiKey` and `baseURL`). A blank `SCALEDOWN_API_KEY` or `credentials.scaledown.apiKey` counts as no key. ### Base URL `SCALEDOWN_BASE_URL` and `credentials.scaledown.baseURL` name the part of the URL in front of `/v1/scaledown`. It can be an origin, such as `https://api.scaledown.xyz`, or an origin with a path prefix, such as a gateway that forwards `https://gateway.example.com/scaledown` to ScaleDown. NeuroLink drops trailing slashes and appends `/v1/scaledown`, so a value that already ends in `/v1` would send the request to `/v1/v1/scaledown`. A blank value is no override. NeuroLink checks nothing else about the value before the request. ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.decide({ provider: "scaledown", state: "We were billed twice for March. Please refund it today.", questions: { team: { type: "choice", instructions: "Which team should handle this?", criteria: { billing: "Payments and refunds", technical: "Bugs", sales: "Pricing", }, }, urgent: { type: "boolean", instructions: "Is this urgent?" }, severity: { type: "score", instructions: "How severe is the problem?", criteria: ["Cosmetic", "Inconvenient", "Customer is blocked"], }, }, }); const team = readDecisionChoice(result.answers, "team"); ``` `result.model` is the model ScaleDown's reply names, which can differ from the one you asked for (`classify` is ScaleDown's name for its latest Classify model). `result.usage.inputTokens` is the reply's `usage.input_tokens`. ### From the CLI ```bash neurolink decide "We were billed twice for March." --provider scaledown \ --questions '{"urgent":{"type":"boolean","instructions":"Is this urgent?"}}' ``` The text output ends with a `Cost:` line, priced from the input tokens the reply reports (see [Cost](#cost)). --- ## How a request is sent ScaleDown's wire is System One's, so you write the same questions as for any other decide provider. | NeuroLink | Sent to `/v1/scaledown` | | --------- | ---------------------------------------------------------------------------------------------------------- | | the key | the header `x-api-key: `, beside `Content-Type: application/json`; there is no `Authorization` header | | the model | `model` in the body (`classify-1` unless you set another) | | `state` | `state`, always a string; see below | | `boolean` | a `noul` question with its `instructions` | | `choice` | a `choice` question; `criteria` maps each option name to its description | | `score` | a `score` question; `criteria` is an ordered list of level descriptions | The reply has the System One shape, an `answers` object keyed by question id, plus `model` and `usage` (`input_tokens`, `output_tokens` and a `cost` in USD). A `boolean` answer carries a probability. A `choice` or `score` answer carries the confidence the reply reports and a probability for each option or level; when a reply omits the confidence, NeuroLink uses the highest probability in that answer's distribution instead. Whether ScaleDown's confidence is calibrated is not established, so tune a threshold on it against your own labelled data. ScaleDown's documentation describes a `score` question's `criteria` as an ordered list of 2 to 10 level descriptions. NeuroLink does not enforce that; ScaleDown does: a list of 11 levels was refused with HTTP 422 in the live test of 2026-10-20 (`'criteria' must have between 2 and 10 levels, got 11`). ### How the state is sent ScaleDown's documentation says it reads only the `text` and `document` fields of the state, and treats a string state as shorthand for `{ "text": }`. NeuroLink therefore sends the state as a string, whatever you pass: | You pass | ScaleDown receives | | ----------------------------------------- | ----------------------------------------------- | | a string | the string, unchanged (not trimmed) | | an object, an array, a number, a boolean | its JSON text, as one string (`JSON.stringify`) | | `{}` or `[]` | the two-character text `{}` or `[]` | | a string that is empty or only whitespace | nothing: refused locally, before any request | Two consequences: - **An object state is classified as text.** ScaleDown does not read an object's other keys, so `{ "title": "...", "review": "..." }` reaches it as the JSON text of that object, and an object that has a `text` field is not unwrapped either. If you want it to read plain prose, pass a string. - **`{}` and `[]` are not refused.** They are non-blank text, so they are sent and ScaleDown classifies the literal characters. ScaleDown itself answers HTTP 422 (`'state.text' or 'state.document' must be provided`) to an empty or text-less state object, as the marketing session saw on 2026-10-15, but NeuroLink never sends one. Check for an empty container yourself if you want it refused. A blank string is refused as an `invalid_request`, with a message that names ScaleDown and the rule (`needs non-blank state text`) and never repeats the state. `decide()` rejects with it, `tryDecide()` returns `null`, and no request is made. This is a catalog setting, `decide.stateEncoding`: see [How the catalog entry says this](#how-the-catalog-entry-says-this). ### Choice options and billing ScaleDown's documentation says every option of a `choice` question is scored by a separate internal call. The input tokens a request was charged for did not grow with the number of options times the length of the state when that was measured. In the live test of 2026-10-20 one `choice` question, whose options each had a description of about 20 characters, was sent three times with the same 20,000-character state: | Options | Input tokens charged | If charged as options times state length, scaled from 3 options | | ------- | -------------------- | --------------------------------------------------------------- | | 3 | 2,966 | 2,966 | | 6 | 3,024 | 5,932 | | 12 | 3,137 | 11,864 | That is the state once, plus about 19 tokens for each option added to the three (58 for three more, 171 for nine more). The same 12 options on a 55-character state were charged 436 tokens. **Not known:** how ScaleDown counts these tokens, and so what the internal call per option adds to the count; whether the amount per option depends on the text of the options, the number of questions or the model; and whether the count holds beyond 12 options or 20,000 characters. The marketing session's figures from 2026-10-15, about 1,829 input tokens for a 20-option choice and about 13,059 for a 255-option choice, each on a one-sentence state, were not measured again and are not reconciled with the line above. NeuroLink declares no cap on options. A probe by the marketing session saw a 255-option choice answered and a 300-option choice refused with HTTP 502; the limit between them is not mapped. When ScaleDown answers a request with HTTP 502, as it did to the 300-option probe, NeuroLink reports a `server` error, retries once, and every built-in consumer then treats the decision as failed and falls back. Whether a refused request is charged is not established. Keep the number of options of a `choice` question modest, and see [Cost](#cost). --- ## When NeuroLink uses it Every built-in consumer of `decide` — model routing, relevance-driven compaction, tool routing and RAG planning — asks for the default decision provider. That is the first one that is configured, in the environment or in the `credentials` passed to the SDK, in the order TypeSafe, [Laya](/docs/getting-started/providers/laya), [XOR](/docs/getting-started/providers/xor), [SubQ](/docs/getting-started/providers/subq), [Perplexity](/docs/getting-started/providers/perplexity-decider), [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef), [OpenAI Decisions](/docs/getting-started/providers/openai-decisions), then ScaleDown. ScaleDown counts with its key alone. So: - **Only a ScaleDown key:** built-in features use ScaleDown, and each of their decisions is then a paid request (see [Cost](#cost)) that still falls back to what NeuroLink did before on any failure. - **A ScaleDown key, plus any earlier provider's key:** built-in features use that earlier provider. ScaleDown runs only where a caller asks for `provider: "scaledown"`. - **A blank `SCALEDOWN_API_KEY`:** no key. ScaleDown is not configured. - **`provider: "scaledown"` with no key:** an `authentication` error and no request. **ScaleDown is last on purpose, and its key is not shared.** Apart from ScaleDown, the providers that come after SubQ in the order are the ones whose key is also read by a text provider (Perplexity's, the Cloudflare pair and OpenAI's), placed behind it so that a key set only for a text provider cannot displace a decision provider a host set up on purpose. That reasoning does not cover ScaleDown, whose key belongs to no other provider: it was placed last, after OpenAI Decisions, as a deliberate choice and not by that rule. The effect is that an ambient `OPENAI_API_KEY`, `PERPLEXITY_API_KEY` or Cloudflare pair in the environment outranks a `SCALEDOWN_API_KEY` set on purpose. The one exception is a gateway's key: an `OPENAI_API_KEY` found only in the environment is skipped for the default while `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL` names a host other than `https://api.openai.com`, so with nothing earlier configured ScaleDown is the default. That skip does not apply when `OPENAI_DECISIONS_BASE_URL` is set or `credentials.openaiDecisions` supplies a key or a base URL; OpenAI Decisions then outranks ScaleDown again (see [A gateway's key](/docs/getting-started/providers/openai-decisions#a-gateways-key-is-never-used-for-the-default)). A host that wants ScaleDown for the built-in features must not have the earlier providers configured, or must name it in its own calls. The classifier router's `auto` strategy counts `SCALEDOWN_API_KEY` too: with only that key set, `auto` resolves to `jev` and ScaleDown answers. --- ## How the catalog entry says this `scaledown.json` needed two optional keys in its `decide` block that no earlier entry set, both read by the shared catalog engine for any entry that sets them. An entry that omits them behaves exactly as before. | Key | Value | What it does | | --------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authHeader` | `"x-api-key"` | The API key is sent as `x-api-key: ` and no `Authorization` header is sent at all. `"bearer"`, the default when the key is omitted, sends `Authorization: Bearer `. This is the decide request's own setting; `quirks.authHeaderStyle` belongs to the chat path and is not read here | | `stateEncoding` | `"text"` | The state that goes out is always a string: a string is sent unchanged (not trimmed), any other value as its JSON text, and a state that is blank after trimming is refused before any request as an `invalid_request`. Omitted means the state goes out as given | The rest of the entry is the same kind of data every decide entry carries: the `system-one` dialect, order 8, the endpoint `{baseURL}/v1/scaledown`, the model in the body, trailing slashes dropped from the base URL, and the error rules in the table below. The fields are also described in the generated API reference, under `DecideBlock`. --- ## Images and video ScaleDown's endpoint reads text only, and the catalog entry declares no media. An image or a video attached to a `decide()` call for ScaleDown is refused before any request, as an `invalid_request`, and the catalog marks both models `vision: false`. This refusal comes before the blank-state check, so a call that carries media is always refused for the media. To decide over images today, use [XOR](/docs/getting-started/providers/xor), [Perplexity](/docs/getting-started/providers/perplexity-decider), [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef) or [OpenAI Decisions](/docs/getting-started/providers/openai-decisions). --- ## Timeouts The default is 30,000 ms per attempt. The entry declares it (`timeouts.decideMs` in `scaledown.json`); 30,000 ms is also what the provider base class gives an entry that declares none. There is no shared 5,000 ms default: a provider that wants a shorter limit declares one, as TypeSafe, Laya and XOR declare 5,000 ms. 30 seconds is not derived from a measurement of ScaleDown, but a 5-second limit would have cut answers off. In the live test of 2026-10-20, with no `timeoutMs`, 10 identical 265-token requests were answered in 0.3 to 9.8 s, and two of them (6.1 s and 9.8 s) took longer than 5 s. A choice question is scored once per option, and the marketing session saw one ScaleDown 504 (`Endpoint request timed out`) after about 29 seconds. ScaleDown's own latency is otherwise not measured here, so a caller with many options or a long state should pass `timeoutMs`. A 504 that ScaleDown sends is classified `timeout` and is not retried. A timeout raised by NeuroLink's own clock before any response arrives is retried once, so a request that never answers fails after about twice the limit (a loopback stand-in, not ScaleDown, that did not answer in 30 s was cut off at 30,000 ms and retried, 60.4 s in all). A 200 whose body then stalls past the limit is not retried: the body read is cut off, the payload is empty, and the call fails after one limit with a `server` error for a response without an answers map; an error status whose body stalls follows that status's usual retry rule. That is read from the code, which every decision provider shares, not measured. --- ## Cost **List price:** USD 0.05 per million input tokens, with output tokens not charged, from ScaleDown's launch post and from the `usage.cost` in a response, as reported to this project by the marketing session on 2026-10-15. This project has not priced a call itself and has not checked the rate since, so check ScaleDown's dashboard for the current one. NeuroLink prices a decision from the input tokens the reply reports, at that one rate, and counts output tokens at nothing. It does not read the reply's `usage.cost`. `result.usage` and the CLI's `Cost:` line are therefore an estimate from the list price, not a bill. A reply that reports no usage is priced at zero. The sign-up allowance is a free allowance whose expiry is not established. --- ## Errors ScaleDown's documentation lists HTTP 402 (insufficient credits), 422 (invalid), 502 (model service error) and 504 (timeout). The marketing session also saw, on 2026-10-15, a 429 `Max queue length has been reached` (no rate-limit headers; it cleared after a few seconds) and a 504 `Endpoint request timed out`, and each was answered when it retried by hand. NeuroLink shows the `detail` text of an error body, whether it is a plain string, an object with a `message`, or a list of validation errors. A list, which is the form both 422 bodies took in the live test of 2026-10-20, is shown as `Request failed validation — : `, for up to five entries and without the `input` each entry echoes back (that is the request, state included). A body in any other form gives only `ScaleDown request failed with HTTP `; the kind and the retry behaviour do not change. | Reply | Kind | Retried | | ---------------------------------------------------- | ------------------------------------------------------------------------- | --------- | | 401 | `authentication` — the provider instance stops retrying | no | | 402 | `invalid_request` — no credit left, or a key ScaleDown does not recognise | no | | 422 | `invalid_request`, with ScaleDown's reason when the body shows one | no | | 429 | `rate_limit` | yes, once | | 502 | `server` | yes, once | | 504 | `timeout` | no | | other 5xx | `server` | yes, once | | any other status | `invalid_request` | no | | no response within the timeout | `timeout` | yes, once | | the request fails before any reply (DNS, connection) | `network` | yes, once | | a blank string state (local) | `invalid_request`, with no network call | no | | an image or a video (local) | `invalid_request`, with no network call | no | | no key configured (local) | `authentication`, with no network call | no | **A 402 does not tell an empty account from an unrecognised key.** In the live test of 2026-10-20 a made-up key was answered HTTP 402 `{"detail":"Insufficient credits"}` both times it was tried, and a real key was answered 200 immediately before and after each try, so the account had credit. ScaleDown documents the same status for an account with no credit left, and the body text is the same, so the status cannot say which it is. NeuroLink keeps the kind `invalid_request` and adds the ambiguity to the message: ```text Insufficient credits — ScaleDown answers HTTP 402 both when the account has no credit left and when it does not recognise the API key; check SCALEDOWN_API_KEY first. ``` It does not call a 402 `authentication`: that would stop a provider instance you keep, and an empty account is fixed by adding credit, not by changing the key. The 401 the marketing session saw on 2026-10-15 (`x-api-key header is required`) answered a request that sent the key as a Bearer token, so it carried no `x-api-key` header; NeuroLink always sends that header, and a missing key is refused before any request. Only a 401 stops the instance, because a bad key does not fix itself: after the first rejection that instance sends no more requests, and a new `NeuroLink` instance asks again. Because `neurolink.decide()` and `neurolink.tryDecide()` build a fresh provider for every call, the latch holds only for a provider instance you keep, not across public calls. A 402 and a 422 do not latch: after you add credit, correct the key or fix the request, the same instance works again. An error message never carries the API key. Before the message of an error reply reaches a log or an error, NeuroLink removes the configured key (if ScaleDown echoes it in a body), anything shaped like a key beginning `sk-`, long hex runs and embedded `data:` URLs. --- ## Data retention NeuroLink has not read ScaleDown's data-handling terms. The state and the questions of every request go to `api.scaledown.xyz`, including the ones the built-in consumers send for model routing, compaction, tool routing and RAG planning whenever ScaleDown is the default decision provider. Read ScaleDown's terms before sending anything sensitive. --- ## Not measured Each item below is **not measured** by NeuroLink: nothing it was built or tested from says what the endpoint does beyond the marketing session's probes, and no request was made to ScaleDown for this project. 1. **Context size and input ceiling**, for either model. The catalog records a `contextWindow` of 128000 and a `maxOutputTokens` of 1 for `classify-1`, and both are placeholders the catalog schema requires. 128000 is NeuroLink's own default window for a model it knows nothing about, and 1 is the figure SubQ's entry uses for a model that returns no text. Neither is a ScaleDown statement, and the entry declares no `decisionLimits`, so nothing is refused locally on the size of a state. 2. **Latency**, for any size of state or number of options. The 30-second default is declared in the entry, not derived from a measurement of ScaleDown. The live test of 2026-10-20 saw 265-token requests answered in 0.3 to 9.8 s and states of 20,000 to 150,000 characters (3 options) answered in under 1.3 s. 3. **Rate limits.** A 429 `Max queue length has been reached`, with no rate-limit headers, was seen by the marketing session on 2026-10-15; no limit is mapped. 4. **The maximum number of options in a `choice`, and of questions per request.** (A `score` with 11 levels was refused with HTTP 422 and one with 3 was answered; the rest of the range was not probed.) 5. **Whether `classify` moves** to a newer model, and what that would change in an answer. 6. **Accuracy** of its answers against any other decide provider, and whether its confidences are calibrated. 7. **How long the free allowance lasts.** Its expiry is not established. 8. **Whether a request ScaleDown refuses** (an HTTP 502, 422 or 504) **is charged.** 9. **ScaleDown's data-retention terms.** --- ## What has and has not been checked - **Read or probed by the marketing session on 2026-10-15, not by this project:** ScaleDown's documentation (the endpoint, the model names, the question kinds, the documented error statuses and the price); a request that sent the key as a Bearer token answered HTTP 401 `{"detail":"x-api-key header is required"}`; a model name other than `classify` or `classify-1` answered HTTP 422; a state with no `text` or `document` answered HTTP 422; the 255-option and 300-option choice requests above; the 429 and the 504 above. - **Live test by the marketing session, 2026-10-20:** 301 `decide()` calls through this provider (295 answered). It found the 402 for an unrecognised key, the list-shaped 422 body, the default timeout and the billing of options described above. Its two 422 bodies and the 402 text are what the mocked tests for those cases use. - **In this project:** the whole behaviour of the entry is tested against stand-in replies, except for the bodies just named: the mocked provider suite (the request headers, body and URL, every status above, the state rules, the order), the decide provider contract (`test/fixtures/decide/scaledown/contract.json`, whose rows are all stand-ins and none claims to have been seen live), and a CLI run against a local server on 127.0.0.1. None of them reaches ScaleDown. - **Not recorded in the catalog entry:** a live matrix. `evidence.liveMatrix` is still empty. --- ## Troubleshooting - **`ScaleDown requires an API key`** — set `SCALEDOWN_API_KEY`, or pass `credentials.scaledown.apiKey`. A blank value counts as unset. - **A 401** — ScaleDown rejected the key, and the message carries its text. Check the key. `neurolink.decide()` builds a fresh provider for every call, so the next call asks again; only a provider instance you keep stops sending after a rejection. - **A 402** — either no credit is left or ScaleDown does not recognise the key: both arrive as HTTP 402 `Insufficient credits`, and the message says so. Check `SCALEDOWN_API_KEY` (or the key you passed in `credentials.scaledown.apiKey`) first, then the balance. Fix whichever it is and call again; the same instance works again. - **A 422** — ScaleDown refused the request, and the message carries its reason. Two were recorded: a model name other than `classify` or `classify-1`, and a `score` question with more than 10 levels. For a `score` question the reason is the last of several entries; the ones before it are ScaleDown rejecting the other question types. - **`ScaleDown needs non-blank state text`** — the state was an empty string or only whitespace. Nothing was sent. - **`ScaleDown does not accept images or video`** — ScaleDown reads text only. Use a decision provider that reads images. - **A 502 on a `choice` question with very many options** — a probe by the marketing session saw a 300-option choice refused this way. Send fewer options. - **A 504 / `timeout`** — see [Timeouts](#timeouts). Pass a larger `timeoutMs`. - **A request to `/v1/v1/scaledown`** — `SCALEDOWN_BASE_URL` ends in `/v1`. Drop it. - **Built-in routing never uses ScaleDown** — an earlier provider is also configured and takes precedence (see [When NeuroLink uses it](#when-neurolink-uses-it)), or no key is set. - **A question is missing from `result.answers`** — the reply left it out, or its answer could not be read. An answer that could not be read is logged as a warning that names the question and never quotes the reply; a question the reply leaves out entirely is not logged, so look for it in `result.answers`. --- ## See also - [The `decide` inference type](/docs/features/decide-inference-type) - [TypeSafe (Jev) Provider Guide](/docs/getting-started/providers/typesafe) - [Laya Provider Guide](/docs/getting-started/providers/laya) - [XOR Provider Guide](/docs/getting-started/providers/xor) - [SubQ Provider Guide](/docs/getting-started/providers/subq) - [Perplexity Decisions Provider Guide](/docs/getting-started/providers/perplexity-decider) - [Cloudflare Clef Provider Guide](/docs/getting-started/providers/cloudflare-clef) - [OpenAI Decisions Provider Guide](/docs/getting-started/providers/openai-decisions) - [ScaleDown's documentation](https://docs.scaledown.ai) --- ## Scaleway Provider Guide # Scaleway Provider Guide Scaleway is a **Tier-2 catalog provider**: an OpenAI-compatible endpoint described by one JSON file (`src/lib/providers/catalog/scaleway.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** Scaleway's `GET /v1/models` needs a key (an unauthenticated > GET answers HTTP 401), so the model ids come from the vendor's public > supported-models page and the roster has not been checked against the API. No > account was created and no API key was used to build this entry. > `evidence.liveMatrix` is `null` until someone runs the live capability matrix > with a real key (see [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://account.scaleway.com/register?service=console and create a Scaleway account; the quickstart (https://www.scaleway.com/en/docs/generative-apis/quickstart/) lists "A Scaleway account logged into the console" and "A valid API key" as requirements 2. Create an API key (https://www.scaleway.com/en/docs/iam/credentials/create-api-keys/): click IAM & API keys on the top-right drop-down menu of the Scaleway console, open the API keys tab and click + Generate API key. The page says: "A screen displays showing the access key and secret key for your new API key and reminding you that this is your only chance to securely save the secret key." The quickstart passes the secret key as the OpenAI client's api_key. Querying models requires one of the permission sets GenerativeApisModelAccess, GenerativeApisFullAccess or AllProductsFullAccess (https://www.scaleway.com/en/docs/generative-apis/api-cli/using-generative-apis/) 3. Billing as the vendor states it: the pricing page (https://www.scaleway.com/en/pricing/model-as-a-service/) says "Try out new models with our free tier: 1 million tokens and 60 minutes of audio transcription."; the FAQ (https://www.scaleway.com/en/docs/generative-apis/faq/) says "After reaching this limit, you will be charged per million tokens processed and per minutes of audio processed."; the create-account page (https://www.scaleway.com/en/docs/account/how-to/create-an-account/) says "Ordering Scaleway resources requires a valid credit card."; the payment-method page (https://www.scaleway.com/en/docs/billing/how-to/add-payment-method/) says "Before you can order Scaleway resources, you must add a payment method to your account."; the rate-limits page (https://www.scaleway.com/en/docs/generative-apis/reference-content/rate-limits/) says "Base limits apply if you registered a valid payment method, and they are increased automatically if you also verify your identity." 4. Set `SCALEWAY_API_KEY` in your .env file (the vendor's examples read SCW_SECRET_KEY, which NeuroLink does not) ### 2. Configure ```bash export SCALEWAY_API_KEY=your-api-key export SCALEWAY_MODEL=mistral-small-3.2-24b-instruct-2506 # optional — overrides the default model export SCALEWAY_BASE_URL=https://api.scaleway.ai/v1 # optional — proxy or gateway; the project-scoped form is not exercised with NeuroLink ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "scaleway", model: "mistral-small-3.2-24b-instruct-2506", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider scaleway ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "scaleway", credentials: { scaleway: { apiKey: process.env.SCALEWAY_API_KEY } }, }); ``` --- ## Billing Scaleway's pricing page (https://www.scaleway.com/en/pricing/model-as-a-service/) says "Try out new models with our free tier: 1 million tokens and 60 minutes of audio transcription." and, under the price table, "You benefit from a free tier on the first 1,000,000 tokens. You'll be charged from token number 1,000,001." The FAQ (https://www.scaleway.com/en/docs/generative-apis/faq/) says "There is a Free Tier available for Serverless." and lists "1,000,000 tokens for models billed by tokens". Prices on the pricing page are in euros ("Prices before tax."), which is why the catalog carries no `pricingPerMTok` values. The create-account page (https://www.scaleway.com/en/docs/account/how-to/create-an-account/) says "Ordering Scaleway resources requires a valid credit card." The payment-method page (https://www.scaleway.com/en/docs/billing/how-to/add-payment-method/) says "Before you can order Scaleway resources, you must add a payment method to your account.", and the rate-limits page says "Base limits apply if you registered a valid payment method, and they are increased automatically if you also verify your identity." The entry records `free-with-card`, which is NeuroLink's classification of the Free Tier plus those payment-method sentences, not a Scaleway statement. --- ## Models | Model | Context (as printed) | Max output (Serverless) | Vision | €/M in · out | Notes | | ---------------------------------------- | -------------------- | ----------------------- | ------ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `mistral-small-3.2-24b-instruct-2506` ⭐ | 128k | 32k | yes | €0.15 / €0.35 | NeuroLink default; the id named in the Chat Completions reference's model field description and in the rate-limits page's `/chat/completions` example. | | `llama-3.3-70b-instruct` | 100k (Serverless) | 16k | no | €0.90 / €0.90 | Fallback; the id in the Chat Completions reference's example request. The vendor calls it "text-only (text in/text out)". | | `qwen3-235b-a22b-instruct-2507` | 250k | 16k | no | €0.75 / €2.25 | Fallback. | | `gemma-4-26b-a4b-it` | 256k | 32k | yes | €0.25 / €0.50 | Fallback. Reasoning efforts: none, low, medium, high. | | `qwen3.6-35b-a3b` | 256k | 32k | yes | €0.25 / €1.50 | Fallback. Reasoning efforts: none, low, medium, high. | | `qwen3.8-27b` | 256k | 32k | yes | €0.60 (cached €0.12) / €3.30 | Reasoning efforts: none, low, medium, xhigh. | | `qwen3.5-397b-a17b` | 250k | 16k | yes | €0.60 / €3.60 | Reasoning efforts: none, low, medium, high. | | `deepseek-v4-flash-0731` | 256k | 32k | no | €0.40 (cached €0.08) / €0.80 | Footnote: "During the preview stage, the context is limited to 256k". Reasoning efforts: none, low, high, max. | | `glm-5.2` | 256k | 16k | no | €1.80 / €5.50 | Footnote: "During the preview stage, the context is limited to 256k". Reasoning efforts: none, high, max. | | `mistral-medium-3.5-128b` | 180k | 16k | yes | €1.50 / €7.50 | Footnote: "During the preview stage, the context is limited to 180k". Reasoning efforts: none, high. | | `gpt-oss-120b` | 128k | 32k | no | €0.15 / €0.60 | The vendor says the Chat Completions API does not yet support tool-calling for this model. Reasoning efforts: low, medium, high. | Ids, context windows, maximum outputs, modalities and reasoning efforts come from the [supported-models page](https://www.scaleway.com/en/docs/generative-apis/reference-content/supported-models/) and prices from the [pricing page](https://www.scaleway.com/en/pricing/model-as-a-service/) (region Paris), both retrieved 2026-09-29. The eleven ids in the table appear on both pages, and the supported-models page's Available in Serverless? cell is Yes for these eleven ids. The `contextWindow` and `maxOutputTokens` values in the JSON are the decimal forms of the labels the vendor prints (256k → 256000). The three preview-marked models carry `status: "preview"`; the other statuses are `production` because the schema requires a value, not because Scaleway states it. **Vision:** `vision: true` marks the models whose Modalities entry lists Vision (`mistral-small-3.2-24b-instruct-2506`, `gemma-4-26b-a4b-it`, `qwen3.6-35b-a3b`, `qwen3.8-27b`, `qwen3.5-397b-a17b`, `mistral-medium-3.5-128b`). The supported-models page says "You will use vision models through the `/v1/chat/completions` endpoint." No image request was sent. `models.visionModel` is the default model. `models.defaultContextWindow` (100,000) and `models.defaultMaxOutputTokens` (16,000) are placeholders for ids outside the catalog. The vendor does not publish them; they equal the smallest Serverless context and maximum-output figures among the catalog models. **Fallback order** when the default is unavailable: `llama-3.3-70b-instruct` → `qwen3-235b-a22b-instruct-2507` → `gemma-4-26b-a4b-it` → `qwen3.6-35b-a3b`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `qwen3-235b-a22b-instruct-2507`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Scaleway — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://api.scaleway.ai/v1/models` answered HTTP 401 on 2026-09-29, so the model ids are taken from the supported-models page (retrieved 2026-09-29); the roster has not been checked against the API | | Auth-failure shape | unauthenticated `GET /v1/models` and `GET /v1/chat/completions` both answered HTTP 401 with the body `{"status":401,"error":"UNAUTHORIZED","message":"missing 'Authorization' header"}` (2026-09-29); `errorRules` carry 401 and the 403, 422 and 429 statuses listed on the Understanding common errors page | | Billing | the pricing page and FAQ state a Free Tier of 1,000,000 tokens; the create-account, payment-method and rate-limits pages state what the Quick Start quotes; 2026-09-29, no signup performed | | Tools / structured output | documented on the function-calling and structured-outputs pages; neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=scaleway` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | HTTP 401 | The vendor's Understanding common errors page lists 401 as "Unauthorized: The authorization header is missing." | Set `SCALEWAY_API_KEY`; the vendor's examples use `SCW_SECRET_KEY`, which NeuroLink does not read | | HTTP 403 | The vendor's page lists 403 as "Forbidden: Your API key does not exist or does not have the necessary permissions to access the requested resource." | The Using Generative APIs page lists the permission sets GenerativeApisModelAccess, GenerativeApisFullAccess and AllProductsFullAccess for querying models | | HTTP 422 | The vendor's page lists 422 as "Model Not Found: The model key is present in the request payload, but the corresponding model is not found." | The Chat Completions reference says "Refer to our supported models list or /models endpoint for available models." | | HTTP 429 | The vendor's page lists 429 as "Too Many Requests" (requests per minute) and "Too Many Tokens" (tokens per minute) | The rate-limits page lists ways to raise limits, starting with "Verify your identity to automatically increase your rate limit" | | Tool calls not returned on `gpt-oss-120b` | The supported-models page says "Currently, this model should be used through the Responses API, because the Chat Completions API does not yet support tool-calling for this model." | NeuroLink's catalog providers call `/chat/completions` | | Structured output ignored with tools attached | `structuredOutputWithTools` is `false` on this entry — untested combination | NeuroLink omits `response_format` automatically whenever tools are present, before sending | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## SiliconFlow Provider Guide # SiliconFlow Provider Guide SiliconFlow is a **Tier-2 catalog provider**: its integration is one JSON file (`src/lib/providers/catalog/siliconflow.json`) rather than hand-written code. That file is the source of truth for the values on this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** SiliconFlow's `GET https://api.siliconflow.com/v1/models` > answers HTTP 401 without a key, so the model ids come from SiliconFlow's > public docs and model pages and the roster has not been checked. No account > was created and no API key was used to build the entry. > `evidence.liveMatrix` is `null` until someone runs the live capability matrix > with a real key (see [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://cloud.siliconflow.com/ and create a SiliconFlow account (https://docs.siliconflow.com/en/userguide/quickstart) 2. Open the API Keys page at https://cloud.siliconflow.com/account/ak, click Create API Key and copy the key (https://docs.siliconflow.com/en/userguide/quickstart) 3. Billing as the vendor words it on https://www.siliconflow.com/pricing: "Flexible token pricing, high usage limits, and postpaid billing—plus $1 in free credits to get you started!" 4. Set `SILICONFLOW_API_KEY` in your .env file ### 2. Configure ```bash export SILICONFLOW_API_KEY=your-api-key export SILICONFLOW_MODEL=deepseek-ai/DeepSeek-V4-Pro # optional — overrides the default model export SILICONFLOW_BASE_URL=https://api.siliconflow.com/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "siliconflow", model: "deepseek-ai/DeepSeek-V4-Pro", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider siliconflow ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "siliconflow", credentials: { siliconflow: { apiKey: process.env.SILICONFLOW_API_KEY } }, }); ``` --- ## Billing SiliconFlow's [pricing page](https://www.siliconflow.com/pricing) says: "Flexible token pricing, high usage limits, and postpaid billing—plus $1 in free credits to get you started!" Its FAQ answers "Are there any minimum commitments?" with "No, there are no minimum commitments. You only pay for what you use, and you can start with $1 in free credits." The entry records `free-tier`. The [Error Handling](https://docs.siliconflow.com/en/faqs/error-code) page says of HTTP 403: "The most common reason is that the model requires real-name authentication." --- ## Models | Model | Context | Max tokens | Vision | Tools | JSON Mode | $/M in · out (cache read) | Notes | | -------------------------------- | ------- | ---------- | ------ | --------- | ------------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `deepseek-ai/DeepSeek-V4-Pro` ⭐ | 1049K | 393K | no | Supported | Supported | $1.50162 / $3.135 ($0.135) | NeuroLink default. About text begins "DeepSeek-V4-Pro is DeepSeek's flagship open-source MoE model". | | `deepseek-ai/DeepSeek-V4-Flash` | 1049K | 393K | no | Supported | Supported | $0.13 / $0.28 ($0.028) | About text begins "DeepSeek-V4-Flash is DeepSeek's latest open-source MoE model". | | `deepseek-ai/DeepSeek-V3.2` | 164K | 164K | no | Supported | Supported | $0.27 / $0.42 ($0.135) | About text begins "DeepSeek-V3.2 is a model that harmonizes high computational efficiency with superior reasoning and agent performance". | | `zai-org/GLM-5.1` | 205K | 131K | no | Supported | Not supported | $1.19 / $3.74 ($0.6) | About text begins "GLM-5.1 is Z.ai's next-generation flagship model built for agentic engineering". | | `zai-org/GLM-5` | 205K | 131K | no | Supported | Not supported | $0.95 / $2.55 ($0.2) | About text begins "GLM-5 is a next-generation open-source model for complex systems engineering and long-horizon agentic tasks". | | `moonshotai/Kimi-K2.6` | 262K | 262K | yes | Supported | Supported | $0.77 / $3.4 ($0.14) | About text begins "Kimi K2.6 is an open-source, native multimodal agentic model by Moonshot AI". | | `moonshotai/Kimi-K2.5` | 262K | 262K | yes | Supported | Supported | $0.45 / $2.25 ($0.07) | About text begins "Kimi K2.5 is an open-source, native multimodal agentic model". | | `Qwen/Qwen3.6-27B` | 262K | 262K | yes | Supported | Supported | $0.3 / $3.2 | About text begins "Qwen3.6-27B is the first open-weight small-to-mid-sized dense model in the Qwen3.6 series". | | `Qwen/Qwen3.6-35B-A3B` | 262K | 262K | yes | Supported | Supported | $0.24 / $1.8 ($0.15) | About text begins "Qwen3.6-35B-A3B is a large language model from Alibaba's Qwen3.6 series". | | `Qwen/Qwen3-32B` | 131K | not set | no | Supported | Supported | $0.14 / $0.57 | About text begins "Qwen3-32B is the latest large language model in the Qwen series with 32.8B parameters". | | `Qwen/Qwen3-VL-32B-Instruct` | 262K | 262K | yes | Supported | Supported | $0.2 / $0.6 | About text begins "Qwen3-VL is the vision-language model in the Qwen3 series". | | `google/gemma-4-31B-it` | 262K | 262K | yes | Supported | Supported | $0.75 / $1.0 ($0.25) | About text begins "Gemma 4 31B is Google DeepMind's latest open-source model". | Context, max tokens, prices and the Tools, JSON Mode and Support image input values come from the model pages at `https://www.siliconflow.com/models/` (retrieved 2026-09-29). The Context and Max tokens columns show the page's "K" values; the catalog records them as thousands (`1049K` is stored as 1,049,000). Prices are the page's Input Price, Output Price and Cache Read figures, shown with a $ sign per "/ M Tokens". The [pricing page](https://www.siliconflow.com/pricing) shows the same context length and prices for `deepseek-ai/DeepSeek-V4-Pro`, `zai-org/GLM-5.1`, `zai-org/GLM-5`, `moonshotai/Kimi-K2.6`, `moonshotai/Kimi-K2.5`, `Qwen/Qwen3.6-27B`, `Qwen/Qwen3.6-35B-A3B` and `google/gemma-4-31B-it`, under the names without the organisation prefix. The 12 ids are copied from the model enums of the API reference and match the ids on their model pages. `Qwen/Qwen3-32B` has no `maxOutputTokens` in the catalog. Its model page shows Max Tokens "131K", and the [Reasoning](https://docs.siliconflow.com/en/userguide/capabilities/reasoning) page lists the Qwen3 Series with Maximum Response Length 8192, Maximum Reasoning Chain Length 32768 and Maximum Context Length 131072. `models.defaultContextWindow` (32,768) and `models.defaultMaxOutputTokens` (4,096) are placeholders for ids outside the catalog that the vendor does not publish. The `status` of the catalog models is `production`, a value the schema requires, not a SiliconFlow statement. **Fallback order** when the default is unavailable: `deepseek-ai/DeepSeek-V4-Flash` → `deepseek-ai/DeepSeek-V3.2` → `zai-org/GLM-5.1` → `moonshotai/Kimi-K2.6` → `Qwen/Qwen3-32B`. The order is NeuroLink's choice, not a vendor ranking. The runtime fallback model name the loader derives (`fallbacks[1]`) is `deepseek-ai/DeepSeek-V3.2`. --- ## Reasoning fields The API reference documents `enable_thinking` ("Switches between thinking and non-thinking modes. Default is True.") for a list of models that includes `deepseek-ai/DeepSeek-V3.2`, `thinking_budget` ("Maximum number of tokens for chain-of-thought output.") and a `reasoning_content` field on the response message. The [Reasoning](https://docs.siliconflow.com/en/userguide/capabilities/reasoning) page says: "reasoning_content: Reasoning chain content, at the same level as content." This catalog entry does not send `enable_thinking` or `thinking_budget`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for SiliconFlow — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://api.siliconflow.com/v1/models` answers HTTP 401 without a key (2026-09-29), so model ids are taken from the [API reference](https://docs.siliconflow.com/en/api-reference/chat-completions/chat-completions) and the model pages (retrieved 2026-09-29); **roster not verified** | | Auth-failure shape | unauthenticated `GET https://api.siliconflow.com/v1/models` returned HTTP 401 with body `{"code":30014,"data":null,"message":"Token is invalid."}` and header `www-authenticate: Bearer realm="siliconflow", error="invalid_token", error_description="Token is invalid."` (2026-09-29). An unauthenticated `GET https://api.siliconflow.com/v1/chat/completions` returned HTTP 404 with `content-type: text/plain` and the body `Not Found`. No POST was sent, so the 401 rule rests on the GET above, and the 403, 429 and model-not-found rules on the [Error Handling](https://docs.siliconflow.com/en/faqs/error-code) page | | Billing | public [pricing page](https://www.siliconflow.com/pricing) statements quoted in [Billing](#billing) above, 2026-09-29 | | Tools / structured output | function calling is documented on the Function Calling page and `response_format` on the JSON Mode page; nothing was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=siliconflow` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting Causes and fixes in quotation marks are SiliconFlow's wording, with the page named. | Symptom | Cause | Fix | | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | HTTP 401 | "API Key is not properly set." ([Error Handling](https://docs.siliconflow.com/en/faqs/error-code)) | "Verify the API Key" ([Text Generation](https://docs.siliconflow.com/en/userguide/capabilities/text-generation), error code table) | | HTTP 403 | "The most common reason is that the model requires real-name authentication." ([Error Handling](https://docs.siliconflow.com/en/faqs/error-code)) | "For other cases, refer to the error message (message)." ([Error Handling](https://docs.siliconflow.com/en/faqs/error-code)) | | HTTP 429 | "Rate limits triggered." ([Error Handling](https://docs.siliconflow.com/en/faqs/error-code)) | "Refer to the error message (message) to determine whether the issue is related to RPM / RPD / TPM / TPD / IPM / IPD." ([Error Handling](https://docs.siliconflow.com/en/faqs/error-code)); "Implement exponential backoff retry mechanism" ([Text Generation](https://docs.siliconflow.com/en/userguide/capabilities/text-generation), error code table) | | HTTP 503 or 504 | "Generally caused by high system load." ([Error Handling](https://docs.siliconflow.com/en/faqs/error-code)) | "You can try again later." and "you can try using streaming output" ([Error Handling](https://docs.siliconflow.com/en/faqs/error-code)) | | HTTP 400 with code 20012 | The Error Handling page lists 400 as "Incorrect parameters." and shows the message "Model does not exist. Please check it carefully." | "Refer to the error message (message) to correct invalid request parameters." ([Error Handling](https://docs.siliconflow.com/en/faqs/error-code)) | | `max_tokens` set to the context length | "As some services are still being updated, avoid setting max_tokens to the window’s upper bound; reserve ~10k tokens as buffer for input and system overhead." ([API reference](https://docs.siliconflow.com/en/api-reference/chat-completions/chat-completions)) | "Ensure that input tokens + max_tokens do not exceed the model’s context window." (same page) | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) - SiliconFlow pages this entry was built from: [Quick Start](https://docs.siliconflow.com/en/userguide/quickstart), [Text Generation](https://docs.siliconflow.com/en/userguide/capabilities/text-generation), [Chat completions API reference](https://docs.siliconflow.com/en/api-reference/chat-completions/chat-completions), [List models](https://docs.siliconflow.com/en/api-reference/models/get-model-list), [Create embeddings](https://docs.siliconflow.com/en/api-reference/embeddings/create-embeddings), [Function Calling](https://docs.siliconflow.com/en/userguide/guides/function-calling), [JSON Mode](https://docs.siliconflow.com/en/userguide/guides/json-mode), [Reasoning](https://docs.siliconflow.com/en/userguide/capabilities/reasoning), [Stream Mode](https://docs.siliconflow.com/en/faqs/stream-mode), [Error Handling](https://docs.siliconflow.com/en/faqs/error-code), [Documentation index](https://docs.siliconflow.com/llms.txt), [Pricing](https://www.siliconflow.com/pricing), [Models](https://www.siliconflow.com/models), [SiliconFlow console](https://cloud.siliconflow.com/), [API Keys](https://cloud.siliconflow.com/account/ak) - SiliconFlow model pages (retrieved 2026-09-29): [DeepSeek-V4-Pro](https://www.siliconflow.com/models/deepseek-v4-pro), [DeepSeek-V4-Flash](https://www.siliconflow.com/models/deepseek-v4-flash), [DeepSeek-V3.2](https://www.siliconflow.com/models/deepseek-v3-2), [GLM-5.1](https://www.siliconflow.com/models/glm-5-1), [GLM-5](https://www.siliconflow.com/models/glm-5), [Kimi-K2.6](https://www.siliconflow.com/models/kimi-k2-6), [Kimi-K2.5](https://www.siliconflow.com/models/kimi-k2-5), [Qwen3.6-27B](https://www.siliconflow.com/models/qwen3-6-27b), [Qwen3.6-35B-A3B](https://www.siliconflow.com/models/qwen3-6-35b-a3b), [Qwen3-32B](https://www.siliconflow.com/models/qwen3-32b), [Qwen3-VL-32B-Instruct](https://www.siliconflow.com/models/qwen3-vl-32b-instruct), [gemma-4-31B-it](https://www.siliconflow.com/models/gemma-4-31b-it), [openai/gpt-oss-120b](https://www.siliconflow.com/models/gpt-oss-120b) --- ## 60db TTS Provider Guide # 60db TTS Provider Guide 60db is a hosted speech API with workspace-scoped voices. NeuroLink exposes its HTTP text-to-speech endpoint as `sixtydb`. ## Configuration Set `SIXTYDB_API_KEY` to your workspace API key. Supply a workspace voice UUID through `tts.voice`, or set `SIXTYDB_DEFAULT_VOICE`. There is no shared default voice. Existing LLM configuration still applies when using `NeuroLink.generate()`. ```typescript NeuroLink, TTSProcessor, registerDefaultTTSHandlers, } from "@juspay/neurolink"; registerDefaultTTSHandlers(); const voices = await TTSProcessor.getVoices("sixtydb"); if (!voices.length) throw new Error("No voices available in this workspace"); const sdk = new NeuroLink(); const result = await sdk.generate({ provider: "openai", input: { text: "Hello world." }, tts: { enabled: true, provider: "sixtydb", voice: voices[0].id, format: "wav", }, }); if (!result.audio) throw new Error("Speech synthesis failed"); writeFileSync("hello.wav", result.audio.buffer); ``` This synthesizes the input directly. Set `tts.useAiResponse: true` to synthesize the LLM response instead. ## Voice discovery `TTSProcessor.getVoices("sixtydb")` loads the workspace's quality and fast catalogs and caches their combined results for five minutes. Pass `{ languageCode: "hi" }` as the second argument to filter using the catalog's language labels. The selected voice determines the synthesis tier; no model ID is sent in the synthesis request. ## Audio and options | Option | Supported values | | ---------- | ------------------------------- | | `voice` | Workspace voice UUID | | `format` | `wav` (default), `pcm16` | | `speed` | 0.5–2; default 1 | | Input text | 1–5000 characters per synthesis | The handler requests mono LINEAR16 audio at 24 kHz. WAV output includes a RIFF header; `pcm16` is raw signed 16-bit little-endian audio. Other formats are rejected before the HTTP request. Native timestamp, pitch and volume controls are not exposed by this handler. The handler buffers each HTTP synthesis response. `stream()` uses NeuroLink's existing sentence-based TTS processing; it does not expose 60db's native audio stream. Each request has a 30-second timeout covering headers and response body, and a 64 MiB response limit. ## CLI With the workspace key and default voice configured: ```bash neurolink generate "Hello world." --provider openai --tts \ --tts-provider sixtydb --tts-format wav --tts-output hello.wav ``` Use `--tts-voice` to override the default workspace voice for one request. ## Explicit credentials For applications that manage credentials themselves, register an instance: ```typescript TTSProcessor.registerHandler("sixtydb", new SixtyDBTTS(workspaceApiKey)); ``` An optional second constructor argument overrides the API endpoint for an application-managed proxy. Credentials are sent as a Bearer token; HTTP redirects are rejected. ## Troubleshooting - Missing credentials: configure the workspace key before registration. - Missing voice or invalid UUID: list workspace voices and supply an ID from that catalog. - Unsupported format: select WAV or PCM16 explicitly, especially in the CLI, whose common format default is MP3. - Failed `generate()`: inspect `result.ttsMetadata` and check `result.audio` before saving. NeuroLink reports speech failures separately from text output. - HTTP authentication errors and malformed audio responses are non-retryable. See the [60db TTS reference](https://docs.60db.ai/api-reference/tts/text-to-speech) and [workspace voice reference](https://docs.60db.ai/api-reference/voices/get-voices) for the upstream request contract. --- ## Stability AI Provider Guide # Stability AI Provider Guide **Direct image generation — image-only provider with no chat / streaming (use the `imageOutput.base64` field on the result)** ## Quick Start ### 1. Get an API Key Sign up at [https://platform.stability.ai/](https://platform.stability.ai/) and create an API key at [https://platform.stability.ai/account/keys](https://platform.stability.ai/account/keys). ### 2. Configure Environment ```bash # Required STABILITY_API_KEY=sk-... # Optional: override the default model (default: stable-image-ultra) STABILITY_MODEL=stable-image-core # Optional: override the base URL # STABILITY_BASE_URL=https://api.stability.ai ``` ### 3. Generate Your First Image ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "stability", input: { text: "A serene mountain lake at sunrise, photorealistic" }, }); writeFileSync("./output.png", Buffer.from(result.imageOutput.base64, "base64")); ``` --- ## SDK Usage ### Basic Generation (Stable Image Ultra) ```typescript const result = await ai.generate({ provider: "stability", input: { text: "Cyberpunk Tokyo skyline at night" }, }); ``` ### Stable Image Core (Fast Tier) ```typescript const result = await ai.generate({ provider: "stability", model: "stable-image-core", input: { text: "A cute corgi puppy" }, }); ``` ### SD 3.5 Large ```typescript const result = await ai.generate({ provider: "stability", model: "sd3.5-large", input: { text: "Watercolor painting of a coffee cup" }, }); ``` ### Aspect Ratio + Negative Prompt The handler reads `aspectRatio` and `negativePrompt` from the options: ```typescript const result = await ai.generate({ provider: "stability", input: { text: "Portrait of a forest spirit, ethereal lighting" }, // Provider-specific extras aspectRatio: "16:9", negativePrompt: "blurry, low quality, deformed", } as any); // Cast — these fields aren't on the canonical TextGenerationOptions ``` (NeuroLink threads `aspectRatio` and `negativePrompt` through to the provider when present; canonical typing for image-gen extras is a follow-up improvement.) ### Per-Call Credentials ```typescript const result = await ai.generate({ provider: "stability", input: { text: "..." }, credentials: { stability: { apiKey: "sk-user-key" } }, }); ``` --- ## CLI Usage ```bash pnpm run cli generate "A red panda eating bamboo" \ --provider stability \ --imageOutput ./panda.png # Use the fast tier pnpm run cli generate "A red panda eating bamboo" \ --provider stability --model stable-image-core \ --imageOutput ./panda.png # SD 3.5 Large pnpm run cli generate "Watercolor painting" \ --provider stability --model sd3.5-large \ --imageOutput ./output.png ``` --- ## Provider Aliases | Alias | Example | | -------------- | ------------------------- | | `stability` | `--provider stability` | | `stability-ai` | `--provider stability-ai` | | `sd` | `--provider sd` | --- ## Configuration Reference | Environment Variable | Required | Default | Description | | -------------------- | -------- | -------------------------- | -------------------- | | `STABILITY_API_KEY` | Yes | — | Stability AI API key | | `STABILITY_MODEL` | No | `stable-image-ultra` | Default model | | `STABILITY_BASE_URL` | No | `https://api.stability.ai` | Base URL | --- ## Feature Support Matrix | Feature | stable-image-ultra | stable-image-core | sd3.5-large | | ---------------- | ------------------- | ----------------- | ----------- | | Image generation | Yes | Yes | Yes | | Text-to-image | Yes | Yes | Yes | | Image-to-image | No (this provider)¹ | No | No | | Aspect ratio | Yes | Yes | Yes | | Negative prompt | Yes | Yes | Yes | | Seed control | Yes | Yes | Yes | | Streaming | No | No | No | | Chat / tools | No | No | No | ¹ For image-to-image with Stable Diffusion, use Replicate-hosted SDXL variants via the [Replicate provider](/docs/getting-started/providers/replicate). --- ## Troubleshooting ### "Invalid Stability AI API key" ```bash echo $STABILITY_API_KEY export STABILITY_API_KEY=sk-... ``` Get / rotate at [https://platform.stability.ai/account/keys](https://platform.stability.ai/account/keys). ### "Stability AI rate limit exceeded" Stability has per-second rate limits per tier. Implement exponential backoff or upgrade your tier at [https://platform.stability.ai/account/credits](https://platform.stability.ai/account/credits). ### "Stability AI declined the request due to content policy" The prompt triggered Stability's content filter (`finish_reason: CONTENT_FILTERED`). Adjust the prompt and retry. Use a different model if you need looser filtering — but note that ALL Stable Image / SD 3.5 models on the hosted API enforce the same policy. ### "Stability AI returned no image" The upstream returned `finish_reason: ERROR` without an image. Check the prompt for malformed Unicode or excessive length (>2000 chars). ### "Model not found" Use one of the documented model IDs: `stable-image-ultra`, `stable-image-core`, `sd3.5-large`, `sd3.5-large-turbo`, `sd3.5-medium`. Note: some older Stability models (SDXL 1.0, Stable Diffusion 1.5) are deprecated on the hosted API — use Replicate to access them. --- ## See Also - Ideogram — sibling image-gen with strong typography (no setup doc yet; see `src/lib/providers/ideogram.ts`) - Recraft — sibling image-gen with vector / illustration focus (no setup doc yet; see `src/lib/providers/recraft.ts`) - [Replicate Provider](/docs/getting-started/providers/replicate) — image-gen via FLUX, SDXL variants, etc. - [Adding an image-gen provider](/docs/provider-integration/20-adding-image-gen-provider) — internal reference --- **Need Help?** Open a [GitHub Discussion](https://github.com/juspay/neurolink/discussions) or [issue](https://github.com/juspay/neurolink/issues). --- ## STACKIT Provider Guide # STACKIT Provider Guide STACKIT is a **Tier-2 catalog provider**: its integration is one JSON file (`src/lib/providers/catalog/stackit.json`) rather than hand-written code. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** STACKIT's `GET /models` needs a key (an unauthenticated > `GET /v1/models` on 2026-09-29 answered HTTP 403), so the model ids come from > STACKIT's public documentation and the roster has not been checked. No > account was created and no API key was used to build it. > `evidence.liveMatrix` is `null` until someone runs the live capability > matrix with a real key (see [Verification status](#verification-status) > below). ## Quick Start ### 1. Get an API key 1. Visit: https://portal.stackit.cloud and log in to the customer portal — the [Getting started](https://docs.stackit.cloud/products/data-and-ai/ai-model-serving/getting-started/getting-started-with-shared-models/) page says "To enable AI Model Serving login to the Customer portal and click at the sidebar on the left on AI Model Serving." and lists a STACKIT customer account, a STACKIT user account and a STACKIT project as prerequisites 2. Enable AI Model Serving, click Create token, enter a token name and optionally a lifetime in days, and confirm with "Order fee-based" ("To confirm click on Order fee-based."); the same page says "You can not retrieve the token again after closing the pane", so copy it when it is shown 3. Billing as the vendor states it: the May 6, 2025 [release note](https://docs.stackit.cloud/products/data-and-ai/ai-model-serving/release-notes/) says "STACKIT AI Model Serving offers you easy pay-as-you-go access to proven GenAI models"; the [product page](https://stackit.com/en/products/data-ai/stackit-ai-model-serving) offers "Register for a free trial access" — see [Billing](#billing) 4. Set `STACKIT_API_KEY` in your .env file (the docs' examples read `STACKIT_MODEL_SERVING_AUTH_TOKEN` and `STACKIT_MODEL_SERVING_API_KEY`, which NeuroLink does not read) ### 2. Configure ```bash export STACKIT_API_KEY=your-auth-token export STACKIT_MODEL=Qwen/Qwen3-VL-235B-A22B-Instruct-FP8 # optional — overrides the default model export STACKIT_BASE_URL=https://api.openai-compat.model-serving.eu01.onstackit.cloud/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "stackit", model: "Qwen/Qwen3-VL-235B-A22B-Instruct-FP8", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider stackit ``` Per-request credentials: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "stackit", credentials: { stackit: { apiKey: process.env.STACKIT_API_KEY } }, }); ``` --- ## Billing What the vendor's pages state, quoted as they appear: - Getting started, token creation: "To confirm click on Order fee-based." The Manage auth tokens page's token-creation steps say "Click on Order fee-based." - Release note, May 6, 2025: "STACKIT AI Model Serving offers you easy pay-as-you-go access to proven GenAI models" - [Product page](https://stackit.com/en/products/data-ai/stackit-ai-model-serving), advantages list: "Operate GenAI applications cost-effectively with our token-based billing." - Product page, heading "Register for a free trial access": "All registrations are manually checked by us. If you qualify, you will receive your personal token to use STACKIT AI Model Serving within 24 hours. The trial period ends automatically after 30 days." The product page's "STACKIT AI Model Serving price table" (Region cell "Germany South") shows these text-model rows, quoted as the cells read: | SKU | Billing | "Price per hour" cell | | ---------------------------------------- | ---------------- | --------------------- | | `Model Serving-llm-standard-input-EU01` | mio input token | 0.15000000000 € | | `Model Serving-llm-standard-output-EU01` | mio output token | 0.25000000000 € | | `Model Serving-llm-plus-input-EU01` | mio input token | 0.45000000000 € | | `Model Serving-llm-plus-output-EU01` | mio output token | 0.65000000000 € | | `Model Serving-llm-premium-input-EU01` | mio input token | 1.50000000000 € | | `Model Serving-llm-premium-output-EU01` | mio output token | 1.75000000000 € | The Available Shared Models page gives each chat model a Category cell (`LLM-Premium`, `LLM-Plus` or `LLM-Standard`), shown in the table below. The entry records `billingPolicy: no-free-tier` because the catalog schema takes one of three values and the token-creation step says "To confirm click on Order fee-based."; the free trial above is a separate, manually checked registration. The entry leaves `pricingPerMTok` empty: the vendor's prices are in euro and are recorded here as the vendor shows them. --- ## Models | Model | Category | Context | Max output | Vision | RPM / TPM | Notes | | -------------------------------------------- | -------------- | ------- | ---------- | --------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Qwen/Qwen3-VL-235B-A22B-Instruct-FP8` ⭐ | `LLM-Premium` | 200K | 16384 | yes (10 images) | 30 / 350000 | NeuroLink default. Features "Tool calling enabled". The row's text: "Meet Qwen3-VL – the most powerful vision-language model in the Qwen series to date." | | `cortecs/Llama-3.3-70B-Instruct-FP8-Dynamic` | `LLM-Plus` | 128K | 4096 | no | 80 / 200000 | Fallback. Features "Tool calling enabled". The model in the Getting started curl example ("In this guide we use Llama 3.3 70B."). | | `openai/gpt-oss-120b` | `LLM-Plus` | 131K | 8192 | no | 30 / 200000 | Fallback. Features "Tool calling & Reasoning enabled". | | `Qwen/Qwen3.8-27B` | `LLM-Plus` | 262K | 16384 | yes (10 images) | 45 / 350000 | Fallback. Features "Tool calling & Reasoning enabled"; Thinking budget "8192 Token". | | `google/gemma-4-31B-it` | `LLM-Plus` | 256K | 4096 | yes (10 images) | 80 / 200000 | Fallback. Features "Tool calling & Reasoning enabled". | | `openai/gpt-oss-20b` | `LLM-Standard` | 131K | 8192 | no | 80 / 200000 | Fallback. Features "Tool calling & Reasoning enabled". Row note: "We recommend configuring retries for tool calling to improve reliability." | The figures in the table are cells of the Available Shared Models page (retrieved 2026-09-29); the six rows show Type "Chat" and Status "Supported". The page writes context as "200K Token", "128K Token", "131K Token", "262K Token" and "256K Token"; the entry records those as 200000, 128000, 131000, 262000 and 256000, reading K as thousands. Vision comes from each row's Modalities cell ("Input are text and image and Output is text." for the three vision rows, "Input and output are text." for the others). RPM and TPM are the page's "RPM limit" and "TPM limit" cells; the [rate-limits page](https://docs.stackit.cloud/products/data-and-ai/ai-model-serving/how-tos/rate-limits-on-shared-models-_stackit-ai-model-serving/) says limits are applied per STACKIT project. `models.defaultContextWindow` (128000) and `models.defaultMaxOutputTokens` (4096) are placeholders the vendor does not publish as general values; they apply to model ids outside the catalog and equal the Context length "128K Token" and Maximum Generation "4096 Token" cells of the Llama 3.3 70B row. The `status` field of the six catalogued models holds `production`: the catalog schema requires a status (`production`, `preview` or `retired`) and the vendor's rows show Status "Supported". **Fallback order** when the default is unavailable: `cortecs/Llama-3.3-70B-Instruct-FP8-Dynamic` → `openai/gpt-oss-120b` → `Qwen/Qwen3.8-27B` → `google/gemma-4-31B-it` → `openai/gpt-oss-20b`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `openai/gpt-oss-120b`. **Left out of the catalog:** - Two chat rows show Status "Deprecated": `Qwen/Qwen3.6-27B` and `google/gemma-3-27b-it`. The [release notes](https://docs.stackit.cloud/products/data-and-ai/ai-model-serving/release-notes/) say "We kindly ask all customers to migrate their workloads to the new model Qwen/Qwen3.8-27B before December 08, 2026." and "We kindly ask all customers to migrate their workloads to the new model google/gemma-4-31B-it before 14 October 2026." - Two embedding rows (`intfloat/e5-mistral-7b-instruct`, `Qwen/Qwen3-VL-Embedding-8B`), for the embeddings reason in Key Facts. The [Use the models](https://docs.stackit.cloud/products/data-and-ai/ai-model-serving/how-tos/use-the-models/) page says "STACKIT AI Model Serving provides an OpenAI-compatible API, making it easy to integrate with existing tools and libraries." and "Important: The API is stateless and does not maintain session information." The Available Shared Models page gives a request body limit: "The maximum allowed request body size is 20 MiB." --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for STACKIT — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /v1/models` answered HTTP 403 (content-length 0, no body) on 2026-09-29, so the roster was not read; the six ids come from the Available Shared Models page, retrieved 2026-09-29 — no key used | | Billing | vendor pages quoted in [Billing](#billing), 2026-09-29 — no signup performed | | Auth-failure shape | unauthenticated GETs of `/v1/models`, `/v1/chat/completions` and `/v1` each answered HTTP 403 with content-length 0 and no body on 2026-09-29, so no error code was observable; no POST was sent. `errorRules` carry the two statuses the vendor's pages state: 404 (FAQ) and 429 (rate-limits page) | | Chat response shape | The sample reply shown under the Getting started page's `POST /v1/chat/completions` curl request reads `"object":"text_completion"` and `"choices":[{"index":0,"text":`; no POST request was sent, so no chat-completions reply was read directly | | Tools / structured output | per-model Features cells and the tool-calling how-to are recorded above; neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=stackit` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting Each row is what a STACKIT page says, with the page named. | Symptom | What the vendor's page says | Page | | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | HTTP 404 | "Most likely this is due to an incorrect “model” parameter in the request body." and "This means a chat model cannot be used to compute embeddings, or vice versa." | [FAQ](https://docs.stackit.cloud/products/data-and-ai/ai-model-serving/faq/) | | HTTP 429 | "Once you hit a rate limit (RPM or TPM)" the API responds with `429 Too Many Requests`; a heading on the page reads "Implement exponential backoff with jitter"; the page lists the headers `x-ratelimit-remaining-requests` and `x-ratelimit-remaining-tokens` | [Rate limits](https://docs.stackit.cloud/products/data-and-ai/ai-model-serving/how-tos/rate-limits-on-shared-models-_stackit-ai-model-serving/) | | Token does not work | Under "Why does my authentication token (aka API-key) not work?": "API base URL: https://api.openai-compat.model-serving.eu01.onstackit.cloud/v1" and "API key / Authentication token / Secret key: STACKIT AI Model Serving Auth Token" | [FAQ](https://docs.stackit.cloud/products/data-and-ai/ai-model-serving/faq/) | | Output truncated | "If it is set to "length", the generation was stopped due to the token cap." (the `finish_reason` field) | [FAQ](https://docs.stackit.cloud/products/data-and-ai/ai-model-serving/faq/) | | `LengthFinishReasonError` with structured output | "This problem can be solved by adjusting the frequency_penalty parameter. A value of 0.7 or higher has proven to be sufficient." | [FAQ](https://docs.stackit.cloud/products/data-and-ai/ai-model-serving/faq/) | | Llama 3.3 70B produces a hallucinated tool call | Under known issues, for `cortecs/Llama-3.3-70B-Instruct-FP8-Dynamic`: "To avoid hallucinated tool calls, do not send the tools parameter with an empty list." | [FAQ](https://docs.stackit.cloud/products/data-and-ai/ai-model-serving/faq/) | | Tool calling on GPT-OSS 20B | "We recommend configuring retries for tool calling to improve reliability." | [Available Shared Models](https://docs.stackit.cloud/products/data-and-ai/ai-model-serving/basics/available-shared-models/) | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## StepFun Provider Guide # StepFun Provider Guide StepFun is a **Tier-2 catalog provider**: its integration is one JSON file (`src/lib/providers/catalog/stepfun.json`) rather than hand-written code. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** StepFun's `GET https://api.stepfun.ai/v1/models` needs a key > (it answers HTTP 401 without one), so the five model ids come from the > vendor's public > [pricing page](https://platform.stepfun.ai/docs/en/guides/pricing/details.md) > and the roster has not been checked. No account was created and no API key > was used to build this entry. `evidence.liveMatrix` is `null` until someone > runs the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://platform.stepfun.ai/interface-key and sign in - the Quickstart (https://platform.stepfun.ai/docs/en/quickstart/overview.md) says "Sign in to the StepFun Open Platform and create and copy an API key on the Interface Keys page." 2. Billing as the vendor states it: the pricing overview (https://platform.stepfun.ai/docs/en/guides/pricing/intro.md) says fees are deducted "drawing from free credit first, then paid balance", and the Error Codes page (https://platform.stepfun.ai/docs/en/api-reference/error-codes.md) lists HTTP 402 as "Insufficient balance" with the resolution "Add funds to your account." 3. Set `STEPFUN_API_KEY` in your .env file ### 2. Configure ```bash export STEPFUN_API_KEY=your-api-key export STEPFUN_MODEL=step-5-preview # optional — overrides the default model export STEPFUN_BASE_URL=https://api.stepfun.ai/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "stepfun", model: "step-5-preview", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider stepfun ``` Per-request credentials are passed the same way as for the other catalog providers: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "stepfun", credentials: { stepfun: { apiKey: process.env.STEPFUN_API_KEY } }, }); ``` --- ## Billing The pricing overview ([pricing/intro](https://platform.stepfun.ai/docs/en/guides/pricing/intro.md)) says fees are deducted "drawing from free credit first, then paid balance". The [Error Codes page](https://platform.stepfun.ai/docs/en/api-reference/error-codes.md) lists HTTP `402` as "Insufficient balance" with the resolution "Add funds to your account." The [pricing details page](https://platform.stepfun.ai/docs/en/guides/pricing/details.md) says pay-as-you-go calls to the standard Open Platform API "are rate limited by tier according to the cumulative top-up amount on your account", and for individual accounts states "Individual accounts must complete identity verification first." Its individual-account tiers: | User tier | Cumulative top-up amount | Concurrency | RPM | TPM | | --------- | ------------------------ | ----------- | ----- | ---------- | | V0 | Under $15 | 5 | 100 | 500,000 | | V1 | $15 to $69 | 20 | 400 | 2,000,000 | | V2 | $70 to $299 | 30 | 600 | 3,000,000 | | V3 | $300 to $1,499 | 40 | 800 | 4,000,000 | | V4 | $1,500 and above | 130 | 2,600 | 13,000,000 | The entry records `no-free-tier` because the catalog schema requires one of `free-tier`, `free-with-card` or `no-free-tier`; the vendor pages quoted above are the billing statement. --- ## Models | Model | Context | Max output | Vision | $/M in · out (cache hit) | Notes | | ---------------------- | ------- | ---------- | ------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `step-5-preview` ⭐ | 1M | 64k | yes | $1.00 / $2.70 ($0.05) | NeuroLink default. "Step 5 Preview is StepFun's flagship model for agentic work." The Chat Completions page states "The examples below use step-5-preview by default." | | `step-3.7-flash` | 256K | — | yes | $0.20 / $1.15 ($0.04) | Fallback. "StepFun's flagship multimodal reasoning model." | | `step-3.5-flash` | 256K | — | no | $0.10 / $0.30 ($0.02) | Fallback. "StepFun's flagship language reasoning model"; the Quickstart table lists Input capabilities "Text only". | | `step-3.5-flash-2603` | 256K | — | no | $0.10 / $0.30 ($0.02) | Fallback. "Agent-optimized version: tuned from step-3.5-flash for high-frequency agent scenarios." | | `step-1o-turbo-vision` | 32K | — | yes | $0.36 / $1.15 ($0.07) | Fallback. Listed under "Pricing for Vision Models"; the welcome-page card says "Designed for social content creation, AI assistants, and image and video understanding." | Context, max output and prices are the vendor's figures from these pages (retrieved 2026-09-29): - `step-5-preview`: the [model page](https://platform.stepfun.ai/docs/en/guides/models/step-5-preview.md) gives Context window "1M tokens", Input types "Text, images, and video" and Maximum output "64k tokens". - `step-3.7-flash`: the [model page](https://platform.stepfun.ai/docs/en/guides/models/step-3.7-flash.md) states a context length of 256K tokens; the [Quickstart table](https://platform.stepfun.ai/docs/en/quickstart/overview.md) lists Input capabilities "Text, images, and video". - `step-3.5-flash`: the [model page](https://platform.stepfun.ai/docs/en/guides/models/step-3.5-flash.md) states a context length of 256K tokens. - `step-3.5-flash-2603`: the same model page describes it under Model variants; the [welcome page](https://platform.stepfun.ai/docs/en/welcome.md) card titled "Step 3.5 Flash 2603" shows the metric "Max context" (value 256K). - `step-1o-turbo-vision`: the welcome-page card titled "Step-1o Turbo Vision" shows the metric "Max context" (value 32K); the [Model Retirement and Migration page](https://platform.stepfun.ai/docs/en/guides/model-migration.md) lists it in the "Recommended replacement" column for step-1-8k, step-1-32k, step-1v-8k, step-1v-32k, step-2-mini, step-1o-vision-32k and step-2-16k. - Prices for the five models: the [pricing details page](https://platform.stepfun.ai/docs/en/guides/pricing/details.md) (per 1M tokens, input cache miss / input cache hit / output). The catalog stores the labels as decimal numbers (`1M` as 1,000,000, `256K` as 256,000, `32K` as 32,000, `64k` as 64,000). `models.defaultContextWindow` (32,000) and `models.defaultMaxOutputTokens` (16,384) are conservative placeholders for model ids outside the catalog; the vendor does not publish a general default. **Vision:** `vision: true` for `step-5-preview` and `step-3.7-flash` follows the Input capabilities "Text, images, and video" in the Quickstart table, and for `step-1o-turbo-vision` follows its "Pricing for Vision Models" listing and card text. `step-3.5-flash` and `step-3.5-flash-2603` are `vision: false`; the welcome-page card for `step-3.5-flash-2603` carries the category "Reasoning / text". **Status:** `step-5-preview` is marked `preview` because the vendor names it "Step 5 Preview". **Fallback order** when the default is unavailable: `step-3.7-flash` → `step-3.5-flash` → `step-3.5-flash-2603` → `step-1o-turbo-vision`. `models.fallbackModelName` is set to `step-3.7-flash`, which the Quickstart table lists with the same Input capabilities ("Text, images, and video") as the default. `models.visionModel` is `step-5-preview`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for StepFun — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /v1/models` answers HTTP 401 without a key (2026-09-29), so the roster has not been checked; model ids come from the vendor's pricing page (retrieved 2026-09-29) | | Billing | vendor wording quoted under [Billing](#billing): "drawing from free credit first, then paid balance"; HTTP 402 "Insufficient balance"; tiered rate limits by cumulative top-up amount, 2026-09-29 | | Auth-failure shape | unauthenticated `GET /v1/models` and `GET /v1/chat/completions` each answered HTTP 401 with the body `{"error":{"message":"Incorrect API key provided","type":"invalid_api_key"}}` on 2026-09-29 (the body has no `error.code` field; `authProbe.code` records `error.type`). `errorRules` match 401 plus 402, 429, 451 and 503 from the Error Codes page | | Tools / structured output | documented on the Tool Call and JSON Mode pages; neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false`. No POST request was sent, so the request fields NeuroLink's client can add (`stream_options`, `tool_choice`, a `json_schema` `response_format`) have not been exercised against StepFun | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=stepfun` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting These rows restate the vendor's [Error Codes page](https://platform.stepfun.ai/docs/en/api-reference/error-codes.md) (retrieved 2026-09-29). | Symptom | Cause (vendor wording) | Fix (vendor wording) | | -------- | ---------------------------------------------------------------------------- | --------------------------------------------------- | | HTTP 400 | "Request parameters are invalid." | "Check the docs and pass the parameters correctly." | | HTTP 401 | "Invalid authentication" | "Make sure you are using the correct API key." | | HTTP 402 | "Insufficient balance" | "Add funds to your account." | | HTTP 404 | "Incorrect request path" | "Update the request path per the docs." | | HTTP 429 | "Resource or rate limit exceeded, usually because requests are too frequent" | "Retry after a short delay." | | HTTP 451 | "The request or response content failed review" | "Modify the request and try again." | | HTTP 500 | "Server-side issue on our end" | "Retry shortly; contact us if it persists." | | HTTP 503 | "Server is currently overloaded" | "Retry after a short delay." | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Subconscious Provider Guide # Subconscious Provider Guide Subconscious is a **Tier-2 catalog provider**: its integration is one JSON file (`src/lib/providers/catalog/subconscious.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** It is built from Subconscious's public documentation and > pricing pages and unauthenticated GET requests to `/v1/models` and > `/v1/chat/completions`. No API key was created or used, and no POST request > was sent. `evidence.liveMatrix` is `null` until someone runs the live > capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit https://subconscious.dev/platform and sign up or sign in (the [quickstart](https://docs.subconscious.dev/quickstart) describes signing up on the platform and generating an API key from the dashboard) 2. Create an API key at https://subconscious.dev/platform/api-keys and copy it ([cloud API](https://docs.subconscious.dev/ways-to-use/cloud-api) says API keys are created and managed from the dashboard) 3. Pricing is at https://www.subconscious.dev/pricing (monthly token plans and usage-based per-token pricing) 4. Set `SUBCONSCIOUS_API_KEY` in your .env file ### 2. Configure ```bash export SUBCONSCIOUS_API_KEY=your-api-key export SUBCONSCIOUS_MODEL=subconscious/glm-5.3-marathon # optional — overrides the default model export SUBCONSCIOUS_BASE_URL=https://api.subconscious.dev/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "subconscious", model: "subconscious/glm-5.3-marathon", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider subconscious ``` Per-request credentials: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "subconscious", credentials: { subconscious: { apiKey: process.env.SUBCONSCIOUS_API_KEY } }, }); ``` --- ## Models | Model | Vision (placeholder) | $/M in · out | Notes | | ------------------------------------------- | -------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `subconscious/glm-5.3-marathon` | no | $1.40 / $4.40 (cached $0.26) | NeuroLink default. The pricing page lists it under the name "GLM-5.3 Marathon", with the description "Open-source frontier coding model". | | `subconscious/deepseek-v4.1-flash-marathon` | no | not attached (see below) | NeuroLink fallback. The homepage FAQ says "On our managed inference service, we serve GLM 5.3 Marathon and DeepSeek V4.1 Flash Marathon." The pricing page lists a different id, `subconscious/deepseek-v4-flash-marathon`, with the description "Multimodal & high-throughput DeepSeek V4". Not probed with a key. | | `subconscious/tim-qwen3.6-27b` | no | not attached | NeuroLink fallback. The vendor's [May 21, 2026 blog post](https://www.subconscious.dev/blog/introducing-tim-qwen3-6-27b) "Introducing TIM-Qwen3.6-27B" says the model is "available via the OpenAI chat completions and Anthropic messages API formats". Not probed with a key. | The three ids above are on the unauthenticated `GET /v1/models` roster (2026-09-29). The `vision` value (`false`, shown as `no` in the table) of the three listed models is a schema-required placeholder the vendor does not publish per model. Pricing comes from the pricing page (https://www.subconscious.dev/pricing, retrieved 2026-09-29), in USD per 1M tokens. It is attached to `subconscious/glm-5.3-marathon`, the id the page lists. The page lists `subconscious/deepseek-v4-flash-marathon` at $0.14 input / $0.28 output / $0.0028 cached; that id differs from the roster id `subconscious/deepseek-v4.1-flash-marathon`, so no pricing is attached to the roster id. `models.defaultContextWindow` (200,000) and `models.defaultMaxOutputTokens` (4,096) are placeholders the vendor does not publish per model; the catalog schema requires both. Neither was probed. The roster also lists `test-dsv4-vision`, which is not in this catalog. **Fallback order:** `subconscious/deepseek-v4.1-flash-marathon` → `subconscious/tim-qwen3.6-27b`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Subconscious — **docs- and roster-verified, not live-verified**: | Probe | Result | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://api.subconscious.dev/v1/models`, HTTP 200, 4 models, 2026-09-29 — no key used | | Route check | unauthenticated `GET https://api.subconscious.dev/v1/chat/completions` answered HTTP 405 with `allow: POST`, 2026-09-29; no `POST` was sent | | Billing | public pages read without an account: the [cloud API](https://docs.subconscious.dev/ways-to-use/cloud-api) page and the [pricing](https://www.subconscious.dev/pricing) page. The GLM-5.2 launch post (June 22, 2026) says "You also get $50 credits to test the model performance"; no account was created, so that offer was not tried, 2026-09-29 | | Error statuses | the [OpenAPI spec](https://docs.subconscious.dev/api-reference/openapi.json) lists 401 "Unauthorized because of a missing or invalid API key" and 429 "Rate limited due to too many requests or tokens per minute"; `errorRules` match on status alone and were not probed live | | Tools / structured output | declared `false`; nothing was exercised live | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. To run it: `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=subconscious` with a real key, then record the result. | --- ## Error statuses The OpenAPI spec (https://docs.subconscious.dev/api-reference/openapi.json) lists these responses for `/chat/completions`: | Status | Vendor description | NeuroLink class | | ------ | ------------------------------------------------------------ | ----------------- | | 400 | Bad request due to invalid parameters or unsupported options | not in errorRules | | 401 | Unauthorized because of a missing or invalid API key | `authentication` | | 429 | Rate limited due to too many requests or tokens per minute | `rate-limit` | | 500 | Internal server error | not in errorRules | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## SubQ Provider Guide # SubQ Provider Guide **A provider of `decide`** — the same typed `boolean` / `choice` / `score` answers as [TypeSafe's Jev](/docs/getting-started/providers/typesafe), [Laya](/docs/getting-started/providers/laya), [XOR](/docs/getting-started/providers/xor), [Perplexity](/docs/getting-started/providers/perplexity-decider) and [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef), from Subquadratic's hosted SubQ Snap. It emits no text at all. ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Provider id | `subq`; the aliases `subquadratic` and `subq-snap` name it too | | Inference type | `decide` only | | Model | `subq-snap-preview`, the only model on SubQ's Decisions endpoint. `SUBQ_MODEL` sets it | | Key | `SUBQ_API_KEY`, or `credentials.subq.apiKey`. Keys come from [console.subq.ai](https://console.subq.ai); the console shows one only once | | Endpoint | `https://api.subq.ai/v1/systemone`; `SUBQ_BASE_URL` or `credentials.subq.baseURL` can name another origin | | Questions per request | no cap declared | | State window | 376,000 estimated tokens, advisory: reported by `decisionLimits()`, never enforced. SubQ's own 400 response states a maximum model length of 393,216 tokens; see [Limits](#limits) | | Media | none. Images attached to a `decide()` call are refused before any request; see [Images](#images) | | Default timeout | 30 seconds per attempt; `timeoutMs` or `--timeout` replaces it | | Precedence | used automatically unless TypeSafe, Laya or XOR is configured; it comes ahead of Perplexity, Cloudflare Clef, OpenAI Decisions and ScaleDown | --- ## Quick Start ### 1. Get a key Sign up at [console.subq.ai](https://console.subq.ai) and create an API key. The console shows it once, so copy it then. SubQ answers HTTP 402 to a request made with no credits left. ### 2. Configure Set the key in the environment: ```bash export SUBQ_API_KEY=... # the key from the console export SUBQ_MODEL=subq-snap-preview # optional export SUBQ_BASE_URL=https://api.subq.ai # optional; an origin, without /v1 ``` or in the config passed to the SDK, exactly as for any other provider. Values passed per call override the constructor's, which override the environment: ```typescript const neurolink = new NeuroLink({ credentials: { subq: { apiKey: process.env.MY_SUBQ_KEY }, }, }); ``` `SUBQ_BASE_URL` and `credentials.subq.baseURL` name an origin. NeuroLink appends `/v1/systemone` and drops any trailing slashes, so a value that already ends in `/v1` would send the request to `/v1/v1/systemone`. ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.decide({ provider: "subq", state: "We were billed twice for March. Please refund it today.", questions: { team: { type: "choice", instructions: "Which team should handle this?", criteria: { billing: "Payments and refunds", technical: "Bugs", sales: "Pricing", }, }, urgent: { type: "boolean", instructions: "Is this urgent?" }, }, }); const team = readDecisionChoice(result.answers, "team"); ``` ### From the CLI ```bash neurolink decide "We were billed twice for March." --provider subq \ --questions '{"urgent":{"type":"boolean","instructions":"Is this urgent?"}}' ``` --- ## When NeuroLink uses it Every built-in consumer of `decide` — model routing, relevance-driven compaction, tool routing and RAG planning — asks for the default decision provider. That is the first one that is configured, in the environment or in the `credentials` passed to the SDK, in the order TypeSafe, [Laya](/docs/getting-started/providers/laya), [XOR](/docs/getting-started/providers/xor), SubQ, [Perplexity](/docs/getting-started/providers/perplexity-decider), [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef), [OpenAI Decisions](/docs/getting-started/providers/openai-decisions), then [ScaleDown](/docs/getting-started/providers/scaledown). SubQ counts with its key alone. It sits ahead of Perplexity, Clef and OpenAI Decisions because its key belongs to no other provider, so setting it can only be meant for SubQ, whereas theirs are shared with text providers and must not displace it. ScaleDown, whose key is also its own, was placed last on purpose. So: - **Only a SubQ key:** built-in features use SubQ. - **A SubQ key, plus a Perplexity key, the Cloudflare pair, `OPENAI_API_KEY` or `SCALEDOWN_API_KEY`:** built-in features use SubQ; Perplexity, Cloudflare Clef, OpenAI Decisions and ScaleDown run only where a caller asks for `provider: "perplexity-decider"`, `provider: "cloudflare-clef"`, `provider: "openai-decisions"` or `provider: "scaledown"`. - **A SubQ key, plus TypeSafe's key, or Laya's or XOR's key and base URL:** built-in features use TypeSafe, Laya or XOR, in that order, whichever is configured; SubQ runs only where a caller asks for `provider: "subq"`. - **A blank `SUBQ_API_KEY`:** no key. SubQ is not configured. --- ## Limits **The state window is advisory.** `decisionLimits()` reports 376,000 estimated state tokens, and the catalog records a model `contextWindow` of 393,216. Both come from one live observation made on 2026-10-13 for NeuroLink (not by this change): SubQ refused a request of 399,795 tokens with HTTP 400, and the message names a maximum model length of 393,216 tokens; the largest request it answered had 376,180 input tokens. So 393,216 is the maximum model length SubQ's own 400 response states, and 376,000 is a margin under the largest request it answered. Both are advisory: a longer state is sent, the server decides, and neither figure is a guarantee. The 376,000 counts NeuroLink's estimated tokens, which can differ from the tokens SubQ counts, so a state near it can still be refused. SubQ answers an over-length request with HTTP 400 and a `validation_error` body (`The decoder prompt (length 399795) is longer than the maximum model length of 393216 ...`). NeuroLink reports it as `invalid_request`, not retried; it is not reported as `max_tokens_exceeded`. **No question cap is declared.** SubQ's documentation gives no count; a `choice` question takes 2 to 255 options, a `score` question 2 to 10 levels, and a question name up to 100 characters. SubQ refuses a request outside those with HTTP 422, which NeuroLink reports as `invalid_request`, with SubQ's reason when the body is the documented object form. **Timeout.** The default is 30 seconds per attempt. SubQ's catalog entry declares no `timeouts.decideMs`, so the 30 seconds of the provider base class applies; it is not the 5 seconds that TypeSafe, Laya and XOR declare. A timeout raised by NeuroLink's own clock before any response arrives is retried once, so a request that never answers fails after about twice the limit (a loopback stand-in, not SubQ, that never answered was cut off at 30,000 ms and again after the retry, 60.3 to 60.5 s in all, in three runs). A 200 whose body then stalls past the limit is not retried: the body read is cut off, the payload is empty, and the call fails after one limit with a `server` error for a response without an answers map; an error status whose body stalls follows that status's usual retry rule. That is read from the code, not measured. SubQ's own latency is not measured here. A state near the window takes longer to read than a short one, so size `timeoutMs` for the states you send. **Price.** SubQ's documentation gives $0.05 per million input tokens and no charge for output tokens (read on 2026-10-13; check the console for the current rate). Each response carries `usage.input_tokens`, which `decide()` returns as `usage.inputTokens`. ### Images SubQ's documentation describes image input: up to 4 images per request, each an object with a `mediaType` and a one-line `base64` string, with no `data:` prefix. NeuroLink's `decide()` prepares images as `data:` URLs, and a catalog entry cannot yet describe the object form, so SubQ's entry declares no media. An image attached to a `decide()` call for SubQ is refused before any request, as `invalid_request`, and the catalog marks the model `vision: false`. To decide over images today, use [XOR](/docs/getting-started/providers/xor), [Perplexity](/docs/getting-started/providers/perplexity-decider) or [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef). --- ## Errors SubQ's documentation gives an error body of `{"detail": {"error_type": "…", "message": "…"}}`. NeuroLink shows the `message`, or a `detail` that is a plain string. A body in any other form, such as a `detail` that is an array, gives only `SubQ request failed with HTTP `; the kind and the retry behaviour do not change. | Reply | Kind | Retried | | ----- | ------------------------------------------------------------------------------------------ | ------- | | 401 | `authentication` — the provider instance stops retrying | no | | 402 | `invalid_request` — the account has no credits | no | | 403 | `invalid_request` — the key cannot use the model | no | | 400 | `invalid_request`, with SubQ's reason (for example a prompt past the maximum model length) | no | | 422 | `invalid_request`, with SubQ's reason (documented body form) | no | | 429 | `rate_limit` | yes | | 503 | `overloaded` | yes | | 5xx | `server` | yes | | other | `invalid_request` | no | | image | `invalid_request`, with no network call (see [Images](#images)) | no | Only a 401 stops the instance. A 402 is not treated as a rejected key on purpose: after you add credit, the same instance works again, with no restart. An error message never carries the API key; if SubQ echoes it, NeuroLink replaces it before the message reaches a log or an error. --- ## Data retention Check [SubQ's data retention page](https://docs.subq.ai/using-the-api/data-retention/) before sending anything sensitive. SubQ's documentation, as read on 2026-10-13 (a reading made before this page was written, and not repeated for it), says that prompts are kept indefinitely unless the organization sets otherwise, and that Decisions are unaffected by zero data retention. Check the page for the current terms. --- ## What has and has not been checked - **Read on 2026-10-13, before this page was written and not repeated for it:** SubQ's documentation (the endpoint, the error body shape, the limits on questions and images, the price and the retention terms), and an unauthenticated `GET https://api.subq.ai/v1/models` that listed `subq-snap-preview`. - **One decision was captured:** a single request from SubQ's documentation, answered HTTP 200. Its body is the contract fixture's success body, `test/fixtures/decide/subq/contract.json`. - **Observed live on 2026-10-13, in a run made for NeuroLink and not repeated for this page:** the over-length 400 above (its body is in the fixture as a `seen-live` row; the saved text of the message stops after "number of text token") and the largest request answered, 376,180 input tokens. - **Not captured:** any other error body. Every other error in that fixture is a stand-in written from the shape the documentation describes, and is labelled so. Whether a 422 ever carries an array `detail` is unknown. - **Not measured:** a question cap, and what an image costs. The catalog entry records no live matrix. --- ## Troubleshooting - **`SubQ requires an API key`** — set `SUBQ_API_KEY`, or pass `credentials.subq.apiKey`. A blank value counts as unset. - **`Authentication failed`** — SubQ answered 401. Check the key in the console, then build a new `NeuroLink` instance: an instance does not retry after a rejection. - **A 402** — the account has no credits. The message says so; add credit and call again. - **A 403** — the key cannot use the model. The message says why. - **A request to `/v1/v1/systemone`** — `SUBQ_BASE_URL` ends in `/v1`. It should be the origin, `https://api.subq.ai`. - **Built-in routing never uses SubQ** — another decision provider is also configured and takes precedence. --- ## See also - [The `decide` inference type](/docs/features/decide-inference-type) - [TypeSafe (Jev) Provider Guide](/docs/getting-started/providers/typesafe) - [Laya Provider Guide](/docs/getting-started/providers/laya) - [XOR Provider Guide](/docs/getting-started/providers/xor) - [Perplexity Decisions Provider Guide](/docs/getting-started/providers/perplexity-decider) - [Cloudflare Clef Provider Guide](/docs/getting-started/providers/cloudflare-clef) - [OpenAI Decisions Provider Guide](/docs/getting-started/providers/openai-decisions) - [ScaleDown Provider Guide](/docs/getting-started/providers/scaledown) - [SubQ's Decisions API](https://docs.subq.ai/endpoints/decisions-api/) --- ## Synthetic Provider Guide # Synthetic Provider Guide Synthetic is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks declared, so its entire integration is one JSON file (`src/lib/providers/catalog/synthetic.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status**: this entry is **docs- and roster-verified, not yet > live-verified**. Every model id, context window, output ceiling and price > below comes from an unauthenticated `GET /openai/v1/models` call plus the > vendor's own pricing page and LiteLLM's third-party provider page — no API > key was used or is required to onboard this entry. Nobody has yet run a > live capability sweep (chat, streaming, tool calls, structured output) > against Synthetic with a real key; `evidence.liveMatrix` is `null` until > that happens. Treat `capabilities.tools`, `.structuredOutput` and > `.thinking` as "documented by the vendor," not "wire-proven." ## Quick Start ### 1. Get an API key 1. Visit: https://synthetic.new and choose Sign up (or Log in if you already have an account) 2. Subscribe to a Pack ($1/day or $30/month, 500 requests/5hr per the pricing page) or set up enterprise usage-based billing — Synthetic has no free tier or keyless trial 3. Generate an API key from your account dashboard 4. Set `SYNTHETIC_API_KEY` in your .env file ### 2. Configure ```bash export SYNTHETIC_API_KEY=your-api-key export SYNTHETIC_MODEL=syn:large:text # optional — overrides the default model export SYNTHETIC_BASE_URL=https://api.synthetic.new/openai/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "synthetic", model: "syn:large:text", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider synthetic ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "synthetic", credentials: { synthetic: { apiKey: process.env.SYNTHETIC_API_KEY } }, }); ``` --- ## Models | Model | Context | Max out | Vision | $/M in · out · cached-in | Notes | | --------------------------------------------------- | ------- | ------- | ------ | ------------------------ | --------------------------------------------------------------------------------------------------------------- | | `syn:large:text` ⭐ | 512K | 64K | yes | $0.60 / $1.20 / $0.03 | Recommended — alias for `deepseek-ai/DeepSeek-V4.1-Flash`. Vendor: "an efficient near-Fable model with vision." | | `syn:small:text` | 192K | 64K | no | $0.10 / $0.50 / $0.02 | Alias for `zai-org/GLM-4.7-Flash` — smaller/faster, ~30B class; text-only input. | | `syn:large:vision` | 512K | 64K | yes | $3.00 / $15.00 / $0.45 | Alias for `moonshotai/Kimi-K3` — 2.8T-parameter flagship; the most expensive model in the roster. | | `syn:small:vision` | 256K | 64K | yes | $0.45 / $2.20 / $0.09 | Alias for `Qwen/Qwen3.8-27B` — small coding + vision model. | | `hf:zai-org/GLM-5.3-Flash` | 512K | 64K | yes | $0.15 / $0.50 / $0.04 | No `syn:` short alias. Vendor: "an extremely efficient, Opus-4.8-equivalent model with vision." | | `hf:openai/gpt-oss-120b` | 128K | 64K | no | $0.10 / $0.10 / $0.02 | OpenAI's open-weight gpt-oss-120b; strong reasoning + agentic use. | | `hf:nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-NVFP4` | 256K | 64K | no | $0.30 / $1.00 / $0.06 | Fast 120B model, good for coding agents. | | `hf:deepseek-ai/DeepSeek-V4.1-Flash` | 512K | 64K | yes | $0.60 / $1.20 / $0.03 | Same underlying model as `syn:large:text`, addressed by its full weights id. | | `hf:moonshotai/Kimi-K3` | 512K | 64K | yes | $3.00 / $15.00 / $0.45 | Same underlying model as `syn:large:vision`. | | `hf:Qwen/Qwen3.8-27B` | 256K | 64K | yes | $0.45 / $2.20 / $0.09 | Same underlying model as `syn:small:vision`. | | `hf:zai-org/GLM-4.7-Flash` | 192K | 64K | no | $0.10 / $0.50 / $0.02 | Same underlying model as `syn:small:text`. | All 11 ids and their pricing/context/output figures come directly from the unauthenticated `GET /openai/v1/models` response (HTTP 200, 2026-09-28); the `$/M` figures are the roster's per-token USD prices multiplied by 1,000,000. `syn:*` short aliases and their `hf:*` full-weights-id equivalents are the same served model with identical specs and pricing — both forms are valid values for `model`, so both are kept in the catalog. **Fallback order** when the default is unavailable: `syn:small:text` → `syn:large:vision` → `syn:small:vision` → `hf:zai-org/GLM-5.3-Flash` → `hf:openai/gpt-oss-120b` → `hf:nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-NVFP4` → `hf:deepseek-ai/DeepSeek-V4.1-Flash` → `hf:moonshotai/Kimi-K3` → `hf:Qwen/Qwen3.8-27B` → `hf:zai-org/GLM-4.7-Flash`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for Synthetic — **all credential-free**: | Probe | Result | | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /openai/v1/models`, HTTP 200, 11 models, 2026-09-28. No API key used or required for this endpoint. | | Billing | unauthenticated `GET https://synthetic.new/pricing`, HTTP 200, 2026-09-28 — no free tier; $1/day or $30/month subscription pack (500 req/5hr), or enterprise usage-based pricing. | | Third-party wire check | LiteLLM's Synthetic provider page confirms base URL `https://api.synthetic.new/openai/v1`, env var `SYNTHETIC_API_KEY`, and `/chat/completions` as the only supported operation. | | Live capability sweep | **Not yet run.** `evidence.liveMatrix` is `null`. Tool calling, structured output, streaming and the tools+schema combination are documented by the vendor's own `supported_features` roster field, not wire-proven against a real key. | Because no live key was used, `capabilities.structuredOutputWithTools` is `false` per Tier-2 policy — a documented individual capability is not evidence for the combined one. A future pass with a real `SYNTHETIC_API_KEY` should run the live matrix (`npx tsx test/continuous-test-suite-provider-matrix.ts --provider=synthetic`) and update `evidence.liveMatrix` accordingly. --- ## Troubleshooting | Symptom | Cause | Fix | | ---------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | | Auth error on first request | No documented auth-error shape yet (no live probe) | Check `SYNTHETIC_API_KEY` is set and valid; see https://synthetic.new for key management | | Model not found | The roster changed since 2026-09-28 | Pick a current id from the unauthenticated `GET /openai/v1/models` roster | | No free tier | Synthetic requires a paid Pack or usage-based billing | Subscribe at https://synthetic.new before making live calls | | Structured output + tools together fails | Not yet probed combined; declared unsupported (`structuredOutputWithTools: false`) until proven live | Send tools and `response_format` in separate requests until this is live-verified | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Telnyx Provider Guide # Telnyx Provider Guide Telnyx is a **Tier-2 catalog provider**: its integration is one JSON file (`src/lib/providers/catalog/telnyx.json`) rather than hand-written code. That file is the source of truth for this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** Telnyx's `GET /v2/ai/openai/models` needs a key (it answers > HTTP 401 without one), so the model ids come from Telnyx's public models page > and the roster has not been checked. No account was created and no API key > was used to build this entry. `evidence.liveMatrix` is `null` until someone > runs the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://telnyx.com/sign-up and create a Telnyx account — the Inference API Quickstart (https://developers.telnyx.com/docs/inference/getting-started) lists a "Telnyx account" and an "API Key" under Prerequisites 2. Create an API key at https://portal.telnyx.com/#/app/auth/v2, the link the Quickstart gives for the API Key 3. Authentication is HTTP Bearer: the Service tiers page (https://developers.telnyx.com/docs/inference/service-tiers) shows a curl request to https://api.telnyx.com/v2/ai/openai/models with the header Authorization: Bearer $TELNYX_API_KEY 4. Billing as the vendor states it: see [Billing](#billing) below 5. Set `TELNYX_API_KEY` in your .env file (the docs' examples read `TELNYX_API_KEY`) ### 2. Configure ```bash export TELNYX_API_KEY=your-api-key export TELNYX_MODEL=zai-org/GLM-5.3-Flash # optional — overrides the default model export TELNYX_BASE_URL=https://api.telnyx.com/v2/ai/openai # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "telnyx", model: "zai-org/GLM-5.3-Flash", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider telnyx ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "telnyx", credentials: { telnyx: { apiKey: process.env.TELNYX_API_KEY } }, }); ``` --- ## Billing `billingPolicy` in the catalog file is recorded as unknown in the growth queue; the catalog schema has no unknown value, so the file holds `no-free-tier` as a placeholder. It is not a vendor statement of signup terms. What the vendor's pages say: - The [Inference pricing page](https://telnyx.com/pricing/inference-api) shows a plan named PAY AS YOU GO described as "Standard rates. Card on file. Automatic tier discounts as usage crosses thresholds, no contract needed." - The [docs pricing page](https://developers.telnyx.com/docs/inference/models/pricing) says "Pay-per-token. No minimums, no commitments." and points to telnyx.com/pricing/inference-api for current per-model pricing. --- ## Models | Model | Context | Vision | $/M in · out (cached) | Notes | | ------------------------------------ | ------- | ----------------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `zai-org/GLM-5.3-Flash` ⭐ | 1M | false placeholder | $0.135 / $0.450 (cached $0.027) | NeuroLink default. Best For "Efficient multimodal coding and agentic workflows", tagged "(Recommended)"; the Quickstart's example model. | | `zai-org/GLM-5.3` | 1M | false placeholder | $1.250 / $4.000 (cached $0.240) | Fallback. Best For "Complex coding and long-horizon agent tasks"; pricing row "GLM-5.3 — Flagship frontier intelligence". | | `deepseek-ai/DeepSeek-V4.1-Flash` | 1M | false placeholder | $0.300 / $1.200 (cached $0.006) | Fallback. Best For "Low-latency multimodal inference"; the Service tiers page's Flex example model. | | `moonshotai/Kimi-K3` | 1M | false placeholder | $2.700 / $13.500 (cached $0.270) | Fallback. Best For "State-of-the-art open-weight intelligence for coding, reasoning, and multimodal work". | | `moonshotai/Kimi-K2.6` | 256K | false placeholder | $0.665 / $4.000 (cached $0.080) | Fallback. Best For "Voice AI"; Voice AI column "Verified — default". | | `zai-org/GLM-5.2` | 1M | false placeholder | $1.000 / $4.000 (cached $0.200) | Fallback. Best For "Coding, reasoning, 1M context window"; Voice AI column "Verified". | | `MiniMaxAI/MiniMax-M3-MXFP8` | 1M | false placeholder | $0.270 / $1.100 (cached $0.080) | Fallback. Best For "Cheapest while maintaining high intelligence". | | `deepseek-ai/DeepSeek-V4-Flash-0731` | 1M | false placeholder | not set | Fallback. Best For "Advanced coding, tool use, and long-horizon agentic workflows". | | `Qwen/Qwen3.8-27B` | 256K | false placeholder | $0.400 / $3.000 (cached $0.050) | Fallback. Best For "Multimodal coding and visual understanding across documents, diagrams, and video"; Voice AI column "Not supported". | Model ids, Context Length labels and the Best For text are read from [the models page](https://developers.telnyx.com/docs/inference/models), retrieved 2026-09-29. `contextWindow` is NeuroLink's decimal reading of the label (1M is 1,000,000 and 256K is 256,000). `models.defaultContextWindow` (128,000) is a placeholder the vendor does not publish, for model ids outside the catalog. Prices come from the second of the three chat-completions tables on [the Inference pricing page](https://telnyx.com/pricing/inference-api) (the page's selector lists Flex, Default and Priority in that order; the docs pricing page says omitting `service_tier` uses `default`). That page names rows by display name, and NeuroLink matched each row to a models-page id. The row "DeepSeek V4 Flash — Ultra-fast, cost-efficient inference" is not matched to a models-page id, so `deepseek-ai/DeepSeek-V4-Flash-0731` has no price in the catalog. **Fallback order** when the default is unavailable follows the models page's row order: `zai-org/GLM-5.3` → `deepseek-ai/DeepSeek-V4.1-Flash` → `moonshotai/Kimi-K3` → `moonshotai/Kimi-K2.6` → `zai-org/GLM-5.2` → `MiniMaxAI/MiniMax-M3-MXFP8` → `deepseek-ai/DeepSeek-V4-Flash-0731` → `Qwen/Qwen3.8-27B`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Telnyx — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://api.telnyx.com/v2/ai/openai/models` answers HTTP 401 without a key, 2026-09-29; model ids come from the models page and the roster has not been checked | | Auth-failure shape | unauthenticated `GET /models`: HTTP 401, header `www-authenticate: Bearer resource_metadata="https://api.telnyx.com/.well-known/oauth-protected-resource"`, JSON body `errors[0]` code `10009`, title "Authentication failed", detail "Could not find any usable credentials in the request." An unauthenticated `GET /chat/completions` answered HTTP 404 with code `10005`, title "Resource not found". No POST request was sent. `errorRules` holds one rule, for status 401 | | Billing | public pricing pages quoted under [Billing](#billing), 2026-09-29; no signup was performed | | Streaming / tools / structured output | documented on the Quickstart, Function Calling, Streaming and Parallel Calls and JSON Mode pages; these were not exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=telnyx` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | | HTTP 401, code `10009` | Telnyx's [error catalog](https://developers.telnyx.com/docs/overview/errors) describes 10009 "Authentication failed" as "The required authentication headers were either invalid or not included in the request." | Set `TELNYX_API_KEY`; the docs' examples read the same variable | | Structured output ignored with tools attached | `structuredOutputWithTools` is `false` on this entry — untested combination | NeuroLink omits `response_format` automatically whenever tools are present, before sending | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Thinking Machines Provider Guide # Thinking Machines Provider Guide Thinking Machines is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/thinking-machines.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** The vendor's `GET /models` needs a key (an unauthenticated > GET answered HTTP 401), so the model ids come from the vendor's public > [Models & Pricing page](https://tinker-docs.thinkingmachines.ai/tinker/models/) > and the roster has not been checked. No API key was created or used to build > this entry. `evidence.liveMatrix` is `null` until someone runs the live > capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://tinker.thinkingmachines.ai/keys — the [Quickstart](https://tinker-docs.thinkingmachines.ai/tinker/quickstart/) says "Or create an API key in the Tinker Console and set it as the TINKER_API_KEY environment variable." An unauthenticated GET of that URL redirects to a page titled "Sign in" (sign-in was not attempted while building this entry) 2. Authentication as the vendor states it: the OpenAI-compatible page says "Authenticate with your Tinker API key, by passing the same key used for Tinker as the API key to the OpenAI client." Its code example reads the key from `TINKER_API_KEY` 3. Billing as the vendor states it: see [Billing](#billing) 4. Set `THINKING_MACHINES_API_KEY` in your .env file (the vendor's examples read `TINKER_API_KEY`, which NeuroLink accepts as a fallback) ### 2. Configure ```bash export THINKING_MACHINES_API_KEY=your-api-key export THINKING_MACHINES_MODEL=moonshotai/Kimi-K2.6 # optional — overrides the default model export THINKING_MACHINES_BASE_URL=https://tinker.thinkingmachines.dev/services/tinker-prod/oai/api/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "thinking-machines", model: "moonshotai/Kimi-K2.6", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider thinking-machines ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "thinking-machines", credentials: { thinkingMachines: { apiKey: process.env.THINKING_MACHINES_API_KEY }, }, }); ``` ### Sampler checkpoints The OpenAI-compatible page says "Use a Tinker sampler weight path as the model name." and shows a path that begins with `tinker://`. A `tinker://` path passed as `model` is an id outside the catalog, so it uses `models.defaultContextWindow` (32768) and `models.defaultMaxOutputTokens` (8192). ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "thinking-machines", model: "tinker://", }); ``` --- ## Billing The vendor's Quickstart says: "Set up payment info in Billing, and see Models & Pricing for current training and sampling rates." The Billing link goes to https://tinker.thinkingmachines.ai/billing/; an unauthenticated GET of it redirects to the same "Sign in" page as the keys URL. The Models & Pricing page says "All prices are per million tokens." The catalog's `billingPolicy` field holds `no-free-tier` only because the schema requires one of three values; it is not a vendor statement. --- ## Models | Model | Context | Vision | $/M in · out (cached in) | Vendor type | Notes | | ----------------------------------------------- | ------- | ------------ | ------------------------ | --------------- | --------------------------------------------------------------------------------------------------------- | | `moonshotai/Kimi-K2.6` ⭐ | 32,768 | not declared | $2.205 / $5.49 ($0.441) | Hybrid + Vision | NeuroLink default. Named in the OpenCode tutorial's "Using a base model (no fine-tuning)" section. | | `Qwen/Qwen3.8-27B` | 65,536 | not declared | $1.86 / $5.595 ($0.372) | Hybrid + Vision | Fallback. Listed under "Recommended replacement" for Qwen3.6-27B. | | `Qwen/Qwen3.6-35B-A3B` | 65,536 | not declared | $0.54 / $1.335 ($0.108) | Hybrid + Vision | Listed under "Recommended replacement" for Qwen3.5-35B-A3B and Qwen3-30B-A3B. | | `Qwen/Qwen3.5-397B-A17B` | 65,536 | not declared | $3.00 / $7.50 ($0.60) | Hybrid + Vision | Listed under "Recommended replacement" for Qwen3-235B-A22B-Instruct-2507 and Qwen3-VL-235B-A22B-Instruct. | | `Qwen/Qwen3.5-9B` | 65,536 | not declared | $0.66 / $1.995 ($0.132) | Hybrid + Vision | Listed under "Recommended replacement" for Llama-3.1-8B-Instruct. | | `Qwen/Qwen3.5-4B` | 65,536 | not declared | $0.33 / $1.005 ($0.066) | Hybrid + Vision | Listed under "Recommended replacement" for Qwen3-4B-Instruct-2507. | | `Qwen/Qwen3-8B` | 32,768 | not declared | $0.195 / $0.60 ($0.039) | Hybrid | Fallback. Named on the Anthropic-Compatible API page, which documents a separate endpoint. | | `openai/gpt-oss-120b` | 32,768 | not declared | $0.33 / $0.84 ($0.066) | Reasoning | Fallback. | | `openai/gpt-oss-20b` | 32,768 | not declared | $0.18 / $0.45 ($0.036) | Reasoning | Listed in the Training table. | | `deepseek-ai/DeepSeek-V3.1` | 32,768 | not declared | $1.695 / $4.215 ($0.339) | Hybrid | Listed in the Training table. | | `zai-org/GLM-5.3:peft:262144` | 262,144 | not declared | $4.86 / $12.15 ($0.972) | Reasoning | The table row is named "GLM-5.3 (256K)". | | `nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16` | 65,536 | not declared | $0.57 / $1.44 ($0.114) | Hybrid | Row note "Limited-time 50% discount"; the page shows Prefill $1.14 and Sample $2.88 struck through. | Context, prices and vendor type come from the Training table on the [Models & Pricing page](https://tinker-docs.thinkingmachines.ai/tinker/models/) (retrieved 2026-09-29; the same data is published as [models.json](https://tinker-docs.thinkingmachines.ai/tinker/models.json)). Input is the Prefill column, output is the Sample column and the figure in brackets is the cached Prefill price; the page's Pricing Terms define Prefill as "Processing input/prompt tokens when sampling" and Sample as "Generating output tokens". Context is the table's label read with K = 1024 (the same table labels the id suffixes `:peft:131072` and `:peft:262144` as 128K and 256K). `models.defaultContextWindow` (32768) is the figure in the OpenCode tutorial's [Config fields table](https://tinker-docs.thinkingmachines.ai/tutorials/deployment/opencode/): "Max input tokens (32768 for most Tinker models)". `models.defaultMaxOutputTokens` (8192) is the `"output"` figure in both example configs of that tutorial, whose Config fields table describes `limit.output` as "Max output tokens". The catalog rows do not set `maxOutputTokens`, so the default applies to them. **Model ids:** `moonshotai/Kimi-K2.6` is the catalog id that the OpenCode tutorial shows as a models entry under its "Using a base model (no fine-tuning)" heading. The other eleven catalog ids are Tinker IDs from the Models & Pricing Training table. The verification level is docs-verified, not yet live-verified. **Vision:** `not declared` means the entry sets `vision` to `false`: image input through `/chat/completions` is not declared by this entry. The Vendor type column shows the Training table's Type label, and the Model Types section describes Vision models as "Vision-language models that accept images alongside text." **Status:** the rows' `status` is `preview`, following the OpenAI-compatible page's "(in beta)" title. The catalog schema requires a value; it is not a per-model vendor statement. **Fallback order** when the default is unavailable: `Qwen/Qwen3.8-27B` → `openai/gpt-oss-120b` → `Qwen/Qwen3-8B`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `openai/gpt-oss-120b`. **Retirements:** the vendor's [Model Deprecations page](https://tinker-docs.thinkingmachines.ai/tinker/model-deprecations/) says "Avoid building hard dependencies on any specific model, as models may be updated, replaced, or removed over time." --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Thinking Machines — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Roster | unauthenticated `GET /models` answers HTTP 401 without a key (2026-09-29), so the twelve model ids are taken from the Models & Pricing page and the roster has not been checked | | Endpoint shape | unauthenticated `GET /chat/completions` answered HTTP 405 with header `allow: POST` and body `{"detail":"Method Not Allowed"}`; the base URL itself answered HTTP 404 with body `{"detail":"Not Found"}`; no POST request was sent | | Auth-failure shape | unauthenticated `GET /models` answered HTTP 401, content-type `application/json`, body `{"detail":"X-Api-Key token is empty"}`; the body has no code field, so no code is recorded and `errorRules` holds one rule, for status `401` | | Billing | the Quickstart's Billing section, quoted under [Billing](#billing); no signup was performed | | Tools / structured output | not declared; no POST request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=thinking-machines` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting Each row below is a statement from the vendor's own pages. | Symptom | What the vendor says | Source | | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | | HTTP 400 when a request sets `reasoning_effort` | "Not all models support this parameter. Requests against a model that doesn't support it return HTTP 400." | [OpenAI-compatible page](https://tinker-docs.thinkingmachines.ai/tinker/compatible-apis/openai/) | | Reasoning trace missing from `content` | "separate_reasoning defaults to true; set it to false to keep the reasoning trace inlined in content." | [OpenAI-compatible page](https://tinker-docs.thinkingmachines.ai/tinker/compatible-apis/openai/) | | Prompt formatting differs from the checkpoint | On `/chat/completions` "the server renders them with the model’s default Hugging Face chat template"; "If your checkpoint expects a different renderer, render the prompt to token IDs yourself" | [OpenAI-compatible page](https://tinker-docs.thinkingmachines.ai/tinker/compatible-apis/openai/) | | Latency or throughput varies | "Latency and throughput may vary by model and may change without notice during the beta." and "If you need higher or more stable throughput, contact the Tinker team in our Discord for guidance on larger-scale setups." | [OpenAI-compatible page](https://tinker-docs.thinkingmachines.ai/tinker/compatible-apis/openai/) | | A model id is no longer served | "Switch to the recommended replacements listed below for any deprecated models." | [Model Deprecations page](https://tinker-docs.thinkingmachines.ai/tinker/model-deprecations/) | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Tinfoil Provider Guide # Tinfoil Provider Guide Tinfoil is a **Tier-2 catalog provider**: its integration is one JSON file (`src/lib/providers/catalog/tinfoil.json`) rather than hand-written code. That file is the source of truth for this page. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** The fields below come from Tinfoil's own public pages and > two unauthenticated GET requests (`/v1/models` and `/v1/chat/completions`) — > no account was created and no API key was used to build it. > `evidence.liveMatrix` is `null` until someone runs the live capability matrix > with a real key (see [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://dash.tinfoil.sh?tab=api-keys and sign in or sign up — https://docs.tinfoil.sh/get-api-key says "Create an account with your email or one of the social connections." 2. On the dashboard Products page, click Activate on the Private Inference card. Per https://docs.tinfoil.sh/get-api-key, if no payment method is on file you are redirected to a checkout page to enter your card details, and "You’re only charged based on usage." 3. The activation dialog creates a "Default API key" and, per the same page, "adds $1 in API credits to your account"; additional keys are created from API Keys in the sidebar 4. Set `TINFOIL_API_KEY` in your .env file (the examples on https://docs.tinfoil.sh/quickstart read TINFOIL_API_KEY) 5. NeuroLink sends requests straight to https://inference.tinfoil.sh/v1. https://docs.tinfoil.sh/sdk/direct-api-access says "but this is not recommended in production" and "Direct access skips the automatic attestation verification our SDKs perform". https://docs.tinfoil.sh/local-proxy/cli documents a local proxy that verifies enclave attestations and serves http://127.0.0.1:3301/v1 for OpenAI-compatible clients (not exercised with NeuroLink) ### 2. Configure ```bash export TINFOIL_API_KEY=your-api-key export TINFOIL_MODEL=kimi-k3 # optional — overrides the default model export TINFOIL_BASE_URL=https://inference.tinfoil.sh/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "tinfoil", model: "kimi-k3", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider tinfoil ``` Per-request credentials work as they do for the other catalog providers: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "tinfoil", credentials: { tinfoil: { apiKey: process.env.TINFOIL_API_KEY } }, }); ``` --- ## Direct HTTPS access The catalog's base URL, `https://inference.tinfoil.sh/v1`, is the endpoint the Tinfoil docs call "direct" access. The docs page for it ([Direct API Access](https://docs.tinfoil.sh/sdk/direct-api-access)) says "but this is not recommended in production" and "Direct access skips the automatic attestation verification our SDKs perform, so you have no cryptographic proof your data is processed in a secure enclave and no protection against man-in-the-middle attacks." It also says "We maintain direct HTTPS compatibility for debugging and simple testing (e.g., inference requests via cURL)." The coding-agents tutorial says "OpenAI-compatible clients don’t perform connection-time attestation themselves." ([docs](https://docs.tinfoil.sh/tutorials/coding-agents)) and the [Tinfoil Proxy CLI page](https://docs.tinfoil.sh/local-proxy/cli) describes a local proxy that listens on `http://127.0.0.1:3301`, verifies the enclave's attestation, and takes that address as the base URL for any OpenAI-compatible client. Pointing `TINFOIL_BASE_URL` at it follows those docs; NeuroLink through that proxy was not exercised. --- ## Billing Tinfoil's key guide ([docs](https://docs.tinfoil.sh/get-api-key)) describes the flow: sign up, click Activate on the Private Inference card, enter card details at checkout when no payment method is on file ("You’re only charged based on usage."), and receive a "Default API key" from a dialog that "adds $1 in API credits to your account". The homepage labels the API "Usage-based pricing" ([tinfoil.sh](https://tinfoil.sh)). The pricing page's Private Chat card lists $20 per month ([pricing](https://tinfoil.sh/pricing)); Private Chat and Private Inference are separate entries in the site's Products menu. The entry records `free-with-card`, the value among the schema's three (`free-tier`, `free-with-card`, `no-free-tier`) that matches a card at checkout plus a stated credit. Per-token prices are in the [Models](#models) table. --- ## Models | Model | Context | Vision | Price per 1M tokens in / out (cached in) | Notes | | --------------------- | --------- | ------ | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `kimi-k3` (default) | 262,144 | yes | 4 / 20 (0.8) | NeuroLink default. Roster description: "Moonshot's flagship multimodal MoE model with hybrid attention for long-context reasoning, coding, and agentic workflows". | | `gpt-oss-120b` | 131,072 | no | 0.15 / 0.6 | Fallback. The first inference example on the [quickstart](https://docs.tinfoil.sh/quickstart) uses this model ID. | | `gemma4-31b` | 262,144 | yes | 0.4 / 1 | Fallback. Strengths value on the chat models page: "Built-in thinking mode, image understanding, native function calling, multilingual support for 35+ languages". | | `llama3-3-70b` | 131,072 | no | 1.75 / 2.75 | Fallback. Roster description: "High-performance multilingual language model optimized for dialogue". | | `glm-5-3` | 1,048,576 | no | 1.8 / 5.75 (0.45) | Roster description: "Z.ai's latest flagship for agentic coding and long-horizon tasks, with a 1M-token context window". | | `glm-5-3-flash` | 1,048,576 | yes | 0.4 / 1.25 (0.1) | Roster description: "Z.AI's fast multimodal MoE model with a 1M-token context window, image input, reasoning, and tool calling". Roster field `experimental` is `true`; recorded as `preview`. | | `deepseek-v4-1-flash` | 1,048,576 | yes | 0.65 / 1.45 (0.13) | Roster field `experimental` is `true`; the chat models page shows the warning "this model is not yet fully productionized. Capacity and performance may change while we finish rolling it out." Recorded as `preview`. | Context and prices are the `context_window` and `pricing` fields of an unauthenticated `GET https://inference.tinfoil.sh/v1/models` call made 2026-09-29 (17 entries; the seven with type `chat` are the seven models above). The [chat models page](https://docs.tinfoil.sh/models/chat) gives the Context values in rounded form: "256K tokens" for `kimi-k3` and `gemma4-31b`, "131K tokens" for `gpt-oss-120b`, "128K tokens" for `llama3-3-70b`, and "1M tokens" for `glm-5-3`, `glm-5-3-flash` and `deepseek-v4-1-flash`. `maxOutputTokens` is unset in the catalog. `models.defaultContextWindow` (131,072) and `models.defaultMaxOutputTokens` (4,096) are placeholders the vendor does not publish. **Status:** `production` is recorded for `kimi-k3`, `gpt-oss-120b`, `gemma4-31b`, `llama3-3-70b` and `glm-5-3`, whose roster entries do not set `experimental`. `preview` is recorded for `glm-5-3-flash` and `deepseek-v4-1-flash`, whose roster entries set `experimental` to `true`. **Left out of the catalog:** the ten roster entries whose `type` is not `chat` — `gpt-oss-safeguard-120b` (safety), `pii-filter` (safety), `nomic-embed-text` (embedding), `doc-upload` (document), `voxtral-small-24b`, `whisper-large-v3-turbo`, `voxtral-mini-4b-realtime` (audio), `qwen3-tts`, `voxtral-tts` (tts) and `websearch` (tool). `gpt-oss-safeguard-120b`, `voxtral-small-24b` and `websearch` list `/v1/chat/completions` among their `endpoints`. **Fallback order** when the default is unavailable: `gpt-oss-120b` → `gemma4-31b` → `llama3-3-70b`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `gemma4-31b`. **Vision:** `vision: true` for `kimi-k3`, `gemma4-31b`, `glm-5-3-flash` and `deepseek-v4-1-flash`. The [image processing guide](https://docs.tinfoil.sh/guides/image-processing) names those four as supporting image inputs, the [vision models page](https://docs.tinfoil.sh/models/vision) lists them, and the roster reports `multimodal: true` for them. For `gpt-oss-120b` and `llama3-3-70b` the image processing guide says "Other models (Llama, GPT-OSS) are text-only and cannot process images."; `glm-5-3` has `multimodal: false` on the roster. No image request was sent. ### Reasoning effort Accepted `reasoning_effort` values per model, from the [reasoning guide](https://docs.tinfoil.sh/guides/reasoning): | Model | Supported values | | --------------------- | ---------------------------------------------------------- | | `kimi-k3` | `low`, `high`, `max` | | `deepseek-v4-1-flash` | `none`, `low`, `high`, `xhigh`, `max` | | `glm-5-3` | `low`, `high`, `max` | | `glm-5-3-flash` | `low`, `high`, `max` | | `gemma4-31b` | `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` | | `gpt-oss-120b` | `low`, `medium`, `high` | The same page says Kimi K3, GLM-5.3 and GLM-5.3 Flash always use reasoning and default to `max`, and that sending an unsupported value returns a `400` error. The [chat models page](https://docs.tinfoil.sh/models/chat) states that for GLM-5.3 and GLM-5.3 Flash reasoning tokens count toward `max_tokens`, so structured outputs and strict tool calls at the default effort need a generous `max_tokens` (around 20K) or a lower effort. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Tinfoil — **docs- and roster-verified, not live-verified**: | Probe | Result | | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Roster | unauthenticated `GET https://inference.tinfoil.sh/v1/models`, HTTP 200, 17 entries (7 with type `chat`), 2026-09-29 — a second GET the same day returned an identical body; no key used | | Billing | public page https://docs.tinfoil.sh/get-api-key, 2026-09-29: card details at checkout when no payment method is on file, "You’re only charged based on usage.", and the activation dialog "adds $1 in API credits to your account" | | Auth-failure shape | unauthenticated `GET https://inference.tinfoil.sh/v1/chat/completions`, 2026-09-29, returned HTTP 400 with `{"error":{"message":"Invalid request body: EOF.","type":"invalid_request_error","param":null,"code":"invalid_json"}}`; `errorRules` therefore use the codes and messages documented at https://docs.tinfoil.sh/sdk/error-handling (`invalid_api_key`, `insufficient_quota` on 402 and 429) | | Tools / structured output / stream | documented at https://docs.tinfoil.sh/guides/tool-calling and https://docs.tinfoil.sh/guides/structured-outputs; none was exercised live, no POST was sent, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=tinfoil` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | HTTP 402 (`insufficient_quota`) | The docs list message "You exceeded your current quota, please check your plan and billing details." and cause "The account or organization has no remaining balance or an inactive subscription" | Billing in the Tinfoil dashboard sidebar ([docs](https://docs.tinfoil.sh/get-api-key)) | | HTTP 429 (`insufficient_quota`) | A per-key cap. The docs list the messages "Spend limit reached for this API key.", "Input token limit reached for this API key." and "Output token limit reached for this API key." | The docs describe a 429 from a per-key cap as not transient, so retrying will not help, and say to raise or clear the cap with Update API Key or use a different key ([docs](https://docs.tinfoil.sh/sdk/error-handling)) | | HTTP 400 when a `reasoning_effort` is sent | The reasoning guide says accepted values differ by model and an unsupported value returns a `400` error | Use a value from the per-model table in [Reasoning effort](#reasoning-effort) | | Structured output ignored with tools attached | `structuredOutputWithTools` is `false` on this entry — untested combination | NeuroLink omits `response_format` automatically whenever tools are present, before sending | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Together AI Provider Guide # Together AI Provider Guide **Open-source LLMs at production scale via the Together gateway** ## Quick Start ### 1. Get an API Key [https://api.together.xyz/settings/api-keys](https://api.together.xyz/settings/api-keys) ### 2. Configure Environment ```bash TOGETHER_API_KEY=tgp_your-key TOGETHER_MODEL=meta-llama/Llama-3.3-70B-Instruct-Turbo ``` ### 3. Generate ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "together", input: { text: "Write a haiku about RAG pipelines." }, }); console.log(result.content); ``` --- ## Supported Models (sample) | Model ID | Notes | | ----------------------------------------------- | --------------------------- | | `meta-llama/Llama-3.3-70B-Instruct-Turbo` | Default; production quality | | `meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo` | Flagship size | | `meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo` | Mid-tier | | `deepseek-ai/DeepSeek-R1` | Reasoning model | | `Qwen/Qwen2.5-72B-Instruct-Turbo` | Qwen 2.5 flagship | Browse the full catalog: [https://docs.together.ai/docs/serverless-models](https://docs.together.ai/docs/serverless-models) --- ## CLI Usage ```bash pnpm run cli generate "Explain MoE routing" --provider together pnpm run cli generate "..." --provider together --model deepseek-ai/DeepSeek-R1 ``` --- ## Provider Aliases | Alias | Example | | ------------- | ------------------------ | | `together` | `--provider together` | | `together_ai` | `--provider together_ai` | --- ## Configuration Reference | Environment Variable | Required | Default | | -------------------- | -------- | ----------------------------------------- | | `TOGETHER_API_KEY` | Yes | — | | `TOGETHER_MODEL` | No | `meta-llama/Llama-3.3-70B-Instruct-Turbo` | | `TOGETHER_BASE_URL` | No | `https://api.together.xyz/v1` | --- ## Feature Support Matrix | Feature | Support | | ----------------- | ----------------- | | Text generation | Yes | | Streaming | Yes | | Tool calling | Yes (model-dep.) | | Structured output | Yes (model-dep.) | | Vision | Yes (Llama 3.2 V) | | Embeddings | Limited | --- ## See Also - [Fireworks Provider](/docs/getting-started/providers/fireworks) - [Groq Provider](/docs/getting-started/providers/groq) --- ## TypeSafe (Jev) Provider Guide # TypeSafe (Jev) Provider Guide **One of the providers that serve `decide` rather than `generate`/`stream`** — it returns typed, calibrated judgments and emits no text at all. The others are [Laya](/docs/getting-started/providers/laya) and [XOR](/docs/getting-started/providers/xor), open-weights models served from an endpoint you configure, and [SubQ](/docs/getting-started/providers/subq), [Perplexity](/docs/getting-started/providers/perplexity-decider), [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef), [OpenAI Decisions](/docs/getting-started/providers/openai-decisions) and [ScaleDown](/docs/getting-started/providers/scaledown), hosted APIs. When more than one is configured, TypeSafe is tried before the others. ## Quick Start ### 1. Get an API key Create one at [console.typesafe.ai/keys](https://console.typesafe.ai/keys). ### 2. Configure ```bash export TYPESAFE_API_KEY=apikey_... # enables TypeSafe export TYPESAFE_MODEL=jev-latest # optional export TYPESAFE_BASE_URL=https://api.typesafe.ai # optional ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.tryDecide({ state: ticketText, // a string OR structured JSON questions: { team: { type: "choice", instructions: "Which team should handle this?", criteria: { billing: "Payments, invoicing, refunds", technical: "Bugs, outages, integrations", sales: "Pricing, upgrades, new accounts", }, }, urgent: { type: "boolean", instructions: "Does this express urgency?" }, }, }); const team = result && readDecisionChoice(result.answers, "team"); if (team && team.confidence >= 0.7) { assignTo(team.choice); } else { assignToHumanTriage(); // low confidence is a signal, not an error } ``` `tryDecide()` returns `null` on any failure. Use `decide()` when you want the failure to surface; it throws a `ProviderError` whose `cause` carries a typed `kind`. ### From the CLI ```bash npx @juspay/neurolink decide "Refund request for a damaged item" \ --questions '{"urgent":{"type":"boolean","instructions":"Is this urgent?"}}' ``` `neurolink decide [state]` calls `decide()` under the hood and reads `TYPESAFE_API_KEY` from the environment like every other CLI command. See the [CLI command reference](/docs/cli/commands.md#decide). --- ## The degradation contract **Setting the key is the entire switch for TypeSafe, and removing it is a complete undo while no other decision provider is configured.** Every internal consumer of `decide` fails open: with no decision provider configured, model routing, context budgeting, relevance compaction, tool routing and RAG planning all behave exactly as they did before. Note that Perplexity's key is shared with its text provider, so a `PERPLEXITY_API_KEY` set for that provider also counts as a configured decision provider; see [One key, two providers](/docs/getting-started/providers/perplexity-decider#one-key-two-providers). The same goes for `CLOUDFLARE_API_KEY` with `CLOUDFLARE_ACCOUNT_ID`, which the Workers AI text provider reads too: set together they configure Cloudflare Clef, which ranks after TypeSafe, Laya, XOR, SubQ and Perplexity; see [One token, two providers](/docs/getting-started/providers/cloudflare-clef#one-token-two-providers). `OPENAI_API_KEY`, which the OpenAI chat provider reads too, configures OpenAI Decisions, which ranks after all of them but ScaleDown; see [One key, two providers](/docs/getting-started/providers/openai-decisions#one-key-two-providers). `SCALEDOWN_API_KEY` is ScaleDown's own and configures only it, as the last of the eight; see [ScaleDown](/docs/getting-started/providers/scaledown#when-neurolink-uses-it). There is no configuration in which a missing, invalid, slow or unreachable decision model changes NeuroLink's observable behaviour. A credential the service does not accept disables that provider instance rather than paying a round trip on every later call to be told so again. --- ## Two transports The same model is reachable two ways, and the choice is made once in the constructor. | | Direct | Vercel AI Gateway | | ------------------- | ------------------- | --------------------------------------------- | | Key | `TYPESAFE_API_KEY` | `AI_GATEWAY_API_KEY` | | Endpoint | `api.typesafe.ai` | `ai-gateway.vercel.sh/v4/ai/evaluation-model` | | Endpoint override | `TYPESAFE_BASE_URL` | `TYPESAFE_GATEWAY_URL` | | Model named in | request body | `ai-model-id` header | | Question vocabulary | `noul` | `boolean` | | `confidence` | on each answer | on `providerMetadata` | | Billed by | TypeSafe | Vercel | **Holding both keys keeps the direct transport**, so the confidence figures a host already sees do not shift underneath it when a second key appears. Force one with `TYPESAFE_TRANSPORT=direct|gateway` or `credentials.typesafe.transport`. Either endpoint can be moved without a release: `credentials.typesafe.baseURL` / `TYPESAFE_BASE_URL` for the direct one, `credentials.typesafe.gatewayURL` / `TYPESAFE_GATEWAY_URL` for the gateway route. ⚠️ **The gateway refuses every request — free credits included — until the Vercel team has a credit card on file**, returning `403 customer_verification_required`. That is an account state, not a bad key, and it arrives _before_ the model id is validated. Full detail, including the measured error table and why the distribution peak is not a substitute for the reported confidence, is in [The `decide` inference type](/docs/features/decide-inference-type#two-transports). --- ## What NeuroLink uses it for | Area | What the decision replaces | | ---------------------------------------------------------------- | --------------------------------------------------------------- | | [Model routing](/docs/features/classifier-router-jev-strategy) | difficulty + capabilities + risk + model pick in one round trip | | [Model catalogue](/docs/features/classifier-router-catalog) | one `choice` over the registry ranks all N candidates at once | | [Context budget](/docs/features/context-budget) | a rubric-placed scope reading lowers the compaction threshold | | [Relevance compaction](/docs/features/relevance-compaction) | per-message keep/drop, plus a gate on the generated summary | | [Tool / MCP routing](/docs/features/tool-routing-decision-model) | one `boolean` per server, replacing a 15s LLM call at ~400 ms | | [RAG retrieval](/docs/features/rag-retrieval-planning) | per-query `topK` / hybrid / graph / rerank planning | --- ## Limits and gotchas - **Two input ceilings**, both enforced by the service: `state` plus the longest single question ≈ **33,000 tokens**, and `state` plus _all_ questions ≈ **64,000**. Exceeding either returns `max_tokens_exceeded` **with no message at all** — the provider supplies a real sentence in its place. - **Batch, never fan out.** Latency is flat in question count but concurrent requests queue, so a second round trip costs far more than a hundred extra questions. - **A `boolean` carries no confidence of its own.** Use `decisionBooleanConfidence(p)` — distance from a coin flip, so 0.5 → 0 and 0/1 → 1. - **403 vs 401 are inverted** on the direct API, and from TypeSafe's own docs: a _missing_ `Authorization` header returns **403**, an _invalid_ key returns **401**. The gateway does not share this quirk. --- ## Troubleshooting | Symptom | Cause | Fix | | ------------------------------------ | --------------------------------------------------------------------- | ----------------------------------------------------------------------------- | | `tryDecide()` always returns `null` | No key, or the key was rejected once and the instance disabled itself | Check `TYPESAFE_API_KEY`; construct a new instance after fixing it | | `max_tokens_exceeded` | One of the two input ceilings | Shorten `state`, or split questions across calls — but prefer shrinking state | | `403 customer_verification_required` | Gateway transport, no card on the Vercel team | Add a payment method, or use the direct transport | | Routing never changes | A `modelPool` is configured, which owns selection outright | See [Provider Orchestration](/docs/features/provider-orchestration) | --- ## See also - [The `decide` inference type](/docs/features/decide-inference-type) — the full reference - [Model routing with a decision model](/docs/features/classifier-router-jev-strategy) - [Laya Provider Guide](/docs/getting-started/providers/laya) - [XOR Provider Guide](/docs/getting-started/providers/xor) - [Perplexity Decisions Provider Guide](/docs/getting-started/providers/perplexity-decider) - [Cloudflare Clef Provider Guide](/docs/getting-started/providers/cloudflare-clef) - [SubQ Provider Guide](/docs/getting-started/providers/subq) - [OpenAI Decisions Provider Guide](/docs/getting-started/providers/openai-decisions) - [ScaleDown Provider Guide](/docs/getting-started/providers/scaledown) - [Provider setup overview](/docs/getting-started/provider-setup) --- ## Umans AI Provider Guide # Umans AI Provider Guide Umans AI is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/umans-ai.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** Every field below comes from Umans AI's own public pages and > unauthenticated `GET` requests — no account was created and no API key was > used to build it. `evidence.liveMatrix` is `null` until someone runs the live > capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://app.umans.ai/register and create an account with Google or an email and password (already have one? sign in at https://app.umans.ai/login). Organizations are provisioned by Umans: email contact@umans.ai (https://app.umans.ai/offers/code/docs/orgs) 2. Open https://app.umans.ai/billing, go to Dashboard -> API Keys and generate a key; the docs say it is shown only once, so copy it immediately 3. Prepaid wallet, no free tier stated: top up before calling the API - the docs say a wallet with no credit (no paid top-up and no active promo grant) "does not serve until it has some", and promo credit serves only while it lasts (https://app.umans.ai/offers/code/docs) 4. Set `UMANS_AI_API_KEY` in your .env file ### 2. Configure ```bash export UMANS_AI_API_KEY=your-api-key export UMANS_AI_MODEL=umans-coder # optional — overrides the default model export UMANS_AI_BASE_URL=https://api.code.umans.ai/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "umans-ai", model: "umans-coder", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider umans-ai ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "umans-ai", credentials: { umansAi: { apiKey: process.env.UMANS_AI_API_KEY } }, }); ``` --- ## Billing Umans AI's pricing page (https://app.umans.ai/pricing) says "Pay per token. Top up, create a key, and go." and "every request debits exactly what the model used". The docs (https://app.umans.ai/offers/code/docs) say a wallet with no credit at all — no paid top-up and no active promo grant — "does not serve until it has some"; promo credit "serves while it lasts" and then the wallet suspends until a paid top-up. A funded wallet that drains to its tier's floor (a small negative allowance, $5 at Tiers 0-1) also suspends, and the docs call that "a stop, not a 429". No page states a free tier or standing free credits, so the entry records `no-free-tier`. The login page's "Sign up for free" link is about creating an account; it is not a stated free allowance. The docs document `GET /v1/usage` and a wallet-summary route on `app.umans.ai` for checking balance and spend. Both need a key; `/v1/usage` was called only without one, for the 401 probe under [Verification status](#verification-status). Request limits sit on top of the balance. The docs give each wallet tier a rolling five-hour request window and a concurrency cap: Tier 0 (first top-up) 2,000 requests and 4 in flight, Tier 1 ($50 lifetime top-up) 4,000 and 8, Tier 2 ($250) 8,000 and 12, Tier 3 ($1,000) 16,000 and 16. They say hard enforcement starts "around twice the stated number" and that each 429 lowers the account's priority for about 30 minutes. --- ## Models | Model | Context | Max output | Vision | $/M in · out (cache read) | Notes | | ------------------------------ | --------- | ---------- | ------ | ------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `umans-coder` ⭐ | 1,048,576 | 131,072 | yes | $0.15 / $0.50 ($0.03) | Default — the vendor's own default; routing alias that today points at GLM-5.3-Flash and can change without a new id. | | `umans-glm-5.3` | 1,048,576 | 131,072 | no | $1.40 / $4.40 ($0.26) | Fallback; Z.ai GLM 5.3, always thinks (reasoning cannot be turned off, dial low or high). | | `umans-deepseek-v4-flash-0731` | 1,048,576 | 393,216 | no | $0.14 / $0.28 ($0.028) | Fallback; the docs call it "The cheapest production model in the lineup". Thinks at low effort by default. | | `umans-kimi-k3` | 1,048,576 | 131,072 | yes | $3.00 / $15.00 ($0.30) | Fallback; Moonshot Kimi K3, native vision, reasoning at max by default, `none` turns it off. | | `umans-glm-5.3-flash` | 1,048,576 | 131,072 | yes | $0.15 / $0.50 ($0.03) | Z.ai GLM-5.3-Flash, native image and video understanding; the model `umans-coder` routes to today; `models.visionModel`. | | `umans-deepseek-v4.1-flash` | 1,048,576 | 393,216 | yes | $0.15 / $0.60 ($0.028) | DeepSeek V4.1 Flash, native image understanding; four reasoning modes, `high` by default; listed in the docs' Models table. | | `umans-flash` | 262,144 | 262,144 | yes | $0.15 / $1.00 ($0.05) | Qwen3.6-35B-A3B-FP8; the docs say to use it "not as a standalone coder"; counts as half a request against the tier window. | Context and per-model input and output prices come from an unauthenticated `GET https://api.code.umans.ai/v1/models` call made 2026-09-29 (10 models; 7 curated into this catalog). Max output and vision come from an unauthenticated `GET https://api.code.umans.ai/v1/models/info` call the same day — the docs describe that endpoint as returning "context windows, pricing, and capabilities" — as `max_completion_tokens` and `supports_vision`. The roster itself gives no price unit; the docs' Models section states "$… per 1M tokens" for the same figures on five of these models, and [the pricing page](https://app.umans.ai/pricing) states "USD per 1M tokens" for all six of its rows. Cache-read rates are not in the roster: they come from the [docs](https://app.umans.ai/offers/code/docs), [the organizations page](https://app.umans.ai/offers/code/docs/orgs) and the pricing page, and the pricing page states the alias rule for `umans-coder` ("an alias for this model today: same rates, routed automatically"). `umans-coder` is the default because it is the vendor's own: every curl example in the docs uses it and the docs' CLI launches it by default. The docs say it "routes to our current pick, which changes as we evaluate models", so its context, price and vision flag follow whatever it points at. The values above are what it reported on 2026-09-29. If you need a fixed model, name one of the other ids. `models.defaultContextWindow` (262,144) and `models.defaultMaxOutputTokens` (131,072) are the smallest context and max-output values among the seven catalog models, so a model id that is not in the catalog gets a figure no catalog model falls below. They are schema-required placeholders, not a vendor-stated general cap: no Umans page states one. **Reasoning levels** differ by model. From `/v1/models/info`: `umans-coder`, `umans-glm-5.3` and `umans-glm-5.3-flash` accept low, high and max and cannot turn reasoning off; `umans-kimi-k3`, `umans-deepseek-v4-flash-0731` and `umans-deepseek-v4.1-flash` accept none, low, high and max; `umans-flash` accepts none, low, medium and high. The docs say Kimi K3's sampling fields (`temperature`, `top_p`) are fixed server-side and the gateway removes them rather than failing the request. **Fallback order** when the default is unavailable: `umans-glm-5.3` → `umans-deepseek-v4-flash-0731` → `umans-kimi-k3`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `umans-deepseek-v4-flash-0731`, the vendor's lowest-priced production model and a text-only one. **Retired ids.** The docs say `umans-kimi-k2.7` and `umans-glm-5.2` were retired on September 10, 2026 and `umans-deepseek-v4-pro-0813` on September 14, 2026; requests pinned to them "keep routing for a short grace tail, then a final hard cutoff". They are not in this catalog. **Vision:** the docs limit a conversation to 20 images across all messages on `/v1/chat/completions`; past that "the request is rejected with a 400 before it reaches a model". Vision flags are the vendor's own `supports_vision` values, not an independent image probe. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Umans AI — **docs- and roster-verified, not live-verified**: | Probe | Result | | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /v1/models`, HTTP 200, 10 models, 2026-09-29 — no key used | | Billing | public docs and pricing pages describe a prepaid per-token wallet that "does not serve" without credit, and state no free tier, 2026-09-29 | | Auth-failure shape | unauthenticated `GET /v1/usage` returned HTTP 401 with `{"error":{"type":"authentication_error","message":"Missing API key"}}`. `GET /v1/chat/completions` answered 405 Method Not Allowed, and no POST was sent, so the chat-completions error body is unobserved. `errorRules` match the documented statuses (`401`, `429`) and the documented "Unknown model" text | | Tools / structured output | `supports_tools: true` on `/v1/models/info`; no page opened documents `response_format`. Neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Reasoning | `reasoning_effort` and `reasoning_content` are documented; NeuroLink's thinking-level mapping onto them was not run | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=umans-ai` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting | Symptom | Cause | Fix | | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Requests fail on every call, with no 429 | The wallet has no credit, or drained to its tier's floor; the docs call this "a stop, not a 429" | Top up at https://app.umans.ai/billing. The docs give no status code for it, so NeuroLink has no rule for it | | HTTP 401 | Key missing, expired or revoked, or set under the wrong variable name | Set `UMANS_AI_API_KEY`; generate a new key under Dashboard -> API Keys | | HTTP 400 `Unknown model` | The id does not exist; since September 2, 2026 an unknown id no longer runs on the default model | Use an id exactly as listed by `GET /v1/models`. Ids start with `umans-`; names like `gpt-4o` or `deepseek-v4-flash` are not valid | | HTTP 429 | The wallet tier's request window or concurrency limit was exceeded | Back off and retry — the docs call these 429s retryable — reduce parallel requests, or top up to raise the tier | | HTTP 400 on an image-heavy conversation | More than 20 images across the messages you resend | Keep only recent images and describe older ones in text | | Truncated answer, or no reasoning, with a small output cap | The docs say reasoning counts toward the output cap and thinking is turned off if the cap is too small for any meaningful reasoning | Raise the output cap. The docs name `max_completion_tokens` for this route; that field was not exercised through NeuroLink, so an output cap here is untested | | Structured output ignored with tools attached | `structuredOutputWithTools` is `false` on this entry — untested combination | NeuroLink omits `response_format` automatically whenever tools are present, before sending | | `umans-coder` behaves differently than before | It is a routing alias and the docs say its target changes | Name a fixed model id, or read the live target from `GET https://api.code.umans.ai/v1/models/info` | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Upstage Provider Guide # Upstage Provider Guide Upstage is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/upstage.json`) rather than hand-written code. That file is the source of truth for everything on this page. ## Quick Start ### 1. Get an API key 1. Visit: https://console.upstage.ai (Google OAuth works) 2. New accounts get a $10 sign-up credit — no payment method required 3. Create an API key under API Keys 4. Set `UPSTAGE_API_KEY` in your .env file ### 2. Configure ```bash export UPSTAGE_API_KEY=your-api-key export UPSTAGE_MODEL=solar-pro4 # optional — overrides the default model export UPSTAGE_BASE_URL=https://api.upstage.ai/v1 # optional — self-hosted or proxy ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "upstage", model: "solar-pro4", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider upstage ``` Per-request credentials work as they do for every provider: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "upstage", credentials: { upstage: { apiKey: process.env.UPSTAGE_API_KEY } }, }); ``` --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ------------------- | ------- | ------ | ------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `solar-pro4` ⭐ | 512K | no | $0.3 / $1.2 | Solar Pro 4; 512K context, up to 128K output tokens; agentic flagship for tool calling, terminal tasks and long-document reasoning | | `solar-pro4-260806` | 512K | no | $0.3 / $1.2 | Pinned dated snapshot of Solar Pro 4 (2026-08-06 build) — the id the solar-pro4 alias currently resolves to | | `solar-pro3` | 512K | no | $0.15 / $0.6 | Solar Pro 3; drop-in replacement for Solar Pro 2 with the same API interface, throughput and latency | | `solar-pro3-260323` | 512K | no | $0.15 / $0.6 | Pinned dated snapshot of Solar Pro 3 (2026-03-23 build) | | `solar-pro2` | 512K | no | $0.15 / $0.6 | Solar Pro 2; 31B-parameter model with an optional Reasoning Mode | | `solar-pro2-251215` | 512K | no | $0.15 / $0.6 | Pinned dated snapshot of Solar Pro 2 (2025-12-15 build) | | `solar-mini` | 512K | no | $0.15 / $0.15 | Solar Mini; small, fast model for lightweight reasoning and cost-efficient tasks | | `solar-mini-250422` | 512K | no | $0.15 / $0.15 | Pinned dated snapshot of Solar Mini (2025-04-22 build) | | `syn-pro` | 512K | no | — | Syn Pro; Upstage's Japan-focused LLM | | `syn-pro-251021` | 512K | no | — | Pinned dated snapshot of Syn Pro (2025-10-21 build) | **Fallback order** when the default is unavailable: `solar-pro3` → `solar-mini`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog records for Upstage: | Probe | Result | | --------------------- | -------------------------------------------------- | | Roster | authenticated GET /v1/models, HTTP 200, 2026-09-03 | | Auth rejection | HTTP 401 `invalid_api_key`, 2026-09-03 | | Live capability sweep | **not run** | > ⚠️ No live capability sweep is recorded for Upstage. The roster and auth > behaviour were verified against the real API on the date above, but the > capability flags come from the catalog declaration rather than from a > measured end-to-end run. Treat them as the provider's stated behaviour. --- ## Troubleshooting | Symptom | Cause | Fix | | ------------------------- | ----------------------------------- | ----------------------------------------------------------------- | | `Invalid Upstage API key` | `UPSTAGE_API_KEY` unset or wrong | Check the key at https://console.upstage.ai/api-keys | | Model not found | The roster changed since 2026-09-03 | Pick a current id; catalog providers retire models without notice | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Venice AI Provider Guide # Venice AI Provider Guide Venice AI is a **Tier-2 catalog provider**: its integration is one JSON file (`src/lib/providers/catalog/venice-ai.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** The catalog fields below were taken from Venice's own public pages and > unauthenticated GET requests to `/models`, `/models/traits` and > `/chat/completions` — no account was created and no API key was used to > build it. `evidence.liveMatrix` is > `null` until someone runs the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://venice.ai/settings/api and select Generate New API Key; the API key guide lists "Sign in to your Venice account." under Before you start (https://docs.venice.ai/guides/getting-started/generating-api-key) 2. Copy the key when it is shown — the API key guide states "Venice will show the full API key one time." (https://docs.venice.ai/guides/getting-started/generating-api-key) — and paste it without a Bearer prefix or quotes (https://docs.venice.ai/getting-started/quick-start) 3. Fund the account before calling models: the docs state "model requests will not succeed until the account can consume DIEM, bundled credits, or USD" (https://docs.venice.ai/guides/getting-started/generating-api-key); payment options are listed at https://docs.venice.ai/overview/pricing 4. Set `VENICE_AI_API_KEY` in your .env file (`VENICE_API_KEY`, the variable Venice's own docs use, is also read) ### 2. Configure ```bash export VENICE_AI_API_KEY=your-api-key export VENICE_AI_MODEL=zai-org-glm-5-2 # optional — overrides the default model export VENICE_AI_BASE_URL=https://api.venice.ai/api/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "venice-ai", model: "zai-org-glm-5-2", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider venice-ai ``` Per-request credentials work the same way as on the other catalog providers: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "venice-ai", credentials: { veniceAi: { apiKey: process.env.VENICE_AI_API_KEY } }, }); ``` --- ## Billing What the pages opened on 2026-09-29 say: - The [API key guide](https://docs.venice.ai/guides/getting-started/generating-api-key) says "You can create a key before funding the account, but model requests will not succeed until the account can consume DIEM, bundled credits, or USD." - The [pricing page](https://docs.venice.ai/overview/pricing) lists three payment options. The USD card says "Buy Venice credits with credit card. Credits never expire." The Stake DIEM card says "Each Diem = $1/day of credits that refresh daily." - Venice's [plan page](https://venice.ai/pricing) lists "API Access (pay with credits)" under the Free plan. - Venice's [API page](https://venice.ai/venice-api) shows the tag "Free tier, no card" in its hero section, and a Pay as you go card that lists "Add funds only when needed". The entry records `no-free-tier`, following the documented balance requirement in the first bullet. --- ## Models | Model | Context | Max output | Vision | $/M in · out (cache read) | Notes | | ----------------------- | --------- | ---------- | ------ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `zai-org-glm-5-2` ⭐ | 1,000,000 | 131,072 | no | $1.4 / $4.4 ($0.26) | NeuroLink default. Roster traits "default" and "function_calling_default"; the `/models/traits` GET returned "default":"zai-org-glm-5-2". | | `zai-org-glm-5` | 198,000 | 32,000 | no | $1 / $3.2 ($0.2) | Fallback. The quick-start page lists it with the text "Default model for most use cases". | | `zai-org-glm-5-1` | 200,000 | 80,000 | no | $1.54 / $4.84 ($0.286) | Fallback. The model in the reasoning-models examples. | | `deepseek-v4-pro-0813` | 1,000,000 | 32,768 | no | $1.65 / $4.95 ($0.165) | Fallback. Roster trait "default_code". | | `kimi-k3` | 1,000,000 | 131,072 | yes | $3.75 / $18.75 ($0.375) | Roster trait "default_reasoning". | | `kimi-k2-6` | 256,000 | 65,536 | yes | $0.75 / $3.5 ($0.16) | The quick-start page lists it with the text "Strong reasoning for more complex tasks". | | `qwen3-vl-235b-a22b` | 128,000 | 16,384 | yes | $0.21 / $1.9 ($0.1) | The model in the vision guide's examples; `models.visionModel`. | | `venice-uncensored-1-2` | 128,000 | 8,192 | yes | $0.2 / $0.9 | Roster trait "most_uncensored"; the quick-start page lists it with the text "Venice's uncensored model". | | `grok-4-7` | 500,000 | 200,000 | yes | $2.27 / $6.8 ($0.57) | Roster trait "most_intelligent". The pricing page has a further row labelled "↳ >200K Context" at $4.53 input and $13.60 output, which the flat prices here do not carry. | | `claude-opus-4-8` | 1,000,000 | 128,000 | yes | $6 / $30 ($0.6) | The quick-start page lists it with the text "High-intelligence model for complex tasks". Roster privacy "anonymized". | Context, max output, vision and prices come from an unauthenticated `GET https://api.venice.ai/api/v1/models` call made 2026-09-29 (126 text models total; 10 curated into this catalog; the roster's `e2ee-` ids are not in it). The input and output prices and the rounded context also appear on [the pricing page](https://docs.venice.ai/overview/pricing) and [the text-models page](https://docs.venice.ai/models/text); the pricing page shows cache-read prices rounded to two decimals. "Roster trait" means the id appears in the model's `traits` list on the roster; the [deprecations page](https://docs.venice.ai/overview/deprecations) lists the current trait mapping. The text-models page lists each model's Capabilities, for example "Function calling, Reasoning, Vision, Code" for `kimi-k3`. `models.defaultContextWindow` (128,000) and `models.defaultMaxOutputTokens` (4,096) are placeholders the vendor does not publish: Venice publishes context and max-output figures per model on the roster, not as a general default. **Fallback order** when the default is unavailable: `zai-org-glm-5` → `zai-org-glm-5-1` → `deepseek-v4-pro-0813`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `zai-org-glm-5-1`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Venice AI — **docs- and roster-verified, not live-verified**: | Probe | Result | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /models`, HTTP 200, 126 text models, 2026-09-29 — no key used | | Default model | unauthenticated `GET /models/traits`, HTTP 200, 2026-09-29 — returned `"default":"zai-org-glm-5-2"` | | Billing | public pages quoted in [Billing](#billing) above, 2026-09-29 — recorded as `no-free-tier` | | Auth-failure shape | an unauthenticated `GET /chat/completions` returned HTTP 404 with body `{"error":"Not found"}` on 2026-09-29; no request that fails authentication was made. `errorRules` use the statuses and messages listed on the [error-codes page](https://docs.venice.ai/api-reference/error-codes): 401, 402, 429, and the model-not-found messages ("Specified model not found", "Invalid model specified") | | Tools / structured output | documented on the function-calling and structured-responses guides linked above; neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=venice-ai` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting Each row is what a Venice page states; none was reproduced live. | Symptom | Cause | Fix | | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | HTTP 401 | The [API key guide](https://docs.venice.ai/guides/getting-started/generating-api-key) says a 401 with `AUTHENTICATION_FAILED` means the key itself was rejected, and lists a partial copy, a `Bearer` prefix or quotes captured into the value, or a stray space or newline as the usual causes | The [quick-start page](https://docs.venice.ai/getting-started/quick-start) says to paste the key exactly as Venice issued it, with no `Bearer` prefix, on a single line with no quotes | | HTTP 402 | The [error-codes page](https://docs.venice.ai/api-reference/error-codes) lists `INSUFFICIENT_BALANCE` and two per-key spend-limit codes under 402; the API key guide says that with a spend-limit code "the cause is the key's own limit rather than your account balance" | For `INSUFFICIENT_BALANCE` the error-codes page points to https://venice.ai/settings/api to add credits; for a spend-limit code the API key guide says to raise or remove the key's Epoch Consumption Limits at the same page | | HTTP 429 | `RATE_LIMIT_EXCEEDED` or `MODEL_OVERLOADED` on the error-codes page; the [rate-limiting page](https://docs.venice.ai/api-reference/rate-limiting) also lists two 30-second error budgets, 50 failed requests and 200 unsupported-feature requests, each returning 429 | The rate-limiting page says "Failed requests (500, 503, 429) should be retried with exponential backoff." and to check the `x-ratelimit-reset-requests` header for the time you can retry | | HTTP 504 on a long non-streaming request | `REQUEST_TIMEOUT` on the error-codes page | The error-codes page says to use the streaming API by setting `stream=true` for long-running non-streaming inference requests | | Model not found | `MODEL_NOT_FOUND` (404, "Specified model not found") or `INVALID_MODEL` (400, "Invalid model specified") on the error-codes page | Model ids are served by the unauthenticated `GET https://api.venice.ai/api/v1/models` ([List Models](https://docs.venice.ai/api-reference/endpoint/models/list)) | | Structured output ignored with tools attached | `structuredOutputWithTools` is `false` on this entry; the structured-responses guide says structured outputs are not compatible with parallel function calls | The generic provider suppresses `response_format` when tools are attached (the default for entries without `structuredOutputWithTools: true`) | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Vispark Provider Guide # Vispark Provider Guide Vispark is a **Tier-2 catalog provider**: its integration is one JSON file (`src/lib/providers/catalog/vispark.json`) rather than hand-written code. The catalog values on this page come from that file. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** The fields below come from the text of Vispark's public > site (https://lab.vispark.in/) and unauthenticated GET requests to > `https://api.lab.vispark.in/v1` — no account was created and no API key was > used to build it. `evidence.liveMatrix` is `null` until someone runs the live > capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://lab.vispark.in/profile and sign in — the playground text reads "Sign in to run this model.", and the site links the Vispark account system at https://account.vispark.in 2. Open API Keys in the profile sidebar (the panel is titled "API Keys" with the subtitle "Manage your API keys"), choose "Add Key" and complete the "Create New API Key" dialog 3. Authentication is HTTP Bearer: the OpenAI Compatibility panel says "Use your standard API Key as a Bearer Token." and shows `Authorization: Bearer `. The site's developer-guide text for the Vision model also lists "Endpoint: /model/text/vision" and "Authentication: X-API-Key: your_api_key_here", and the ephemeral-key panel "Using on Model Endpoints" shows an X-API-Key header and lists "POST /chat/completions" under "Supported endpoints:". Neither header scheme was exercised: no POST request was sent 4. Billing as the site shows it: the Account tab of the profile page has a "Buy More Units" panel with the strings "₹1 (INR) = 1 unit" and "$1 (USD) = ~95 units" 5. Set `VISPARK_API_KEY` in your .env file ### 2. Configure ```bash export VISPARK_API_KEY=your-api-key export VISPARK_MODEL=vispark/vision-large # optional — overrides the default model export VISPARK_BASE_URL=https://api.lab.vispark.in/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "vispark", model: "vispark/vision-large", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider vispark ``` Per-request credentials are passed like this: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "vispark", credentials: { vispark: { apiKey: process.env.VISPARK_API_KEY } }, }); ``` --- ## Billing The Account tab of https://lab.vispark.in/profile has a "Buy More Units" panel with the strings "₹1 (INR) = 1 unit" and "$1 (USD) = ~95 units", and the Insufficient Units dialog carries the text "~$0.01 = ₹1 = 1 unit." The Vision model's price text is quoted in [Models](#models). The `no-free-tier` value in the catalog is a schema placeholder, not a vendor statement. --- ## Models | Model | Context | Max output | Vision | $/M in · out | Notes | | ------------------------- | --------- | ---------- | ------ | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `vispark/vision-large` ⭐ | 1,000,000 | 65,536 | yes | $7.37 / $22.11 | NeuroLink default. Roster description: "Vision Large: India's most advanced foundational intelligence." The site's size entry reads "Slowest processing but highest intelligence and accuracy". | | `vispark/vision-medium` | 1,000,000 | 65,536 | yes | $4.21 / $12.63 | Fallback. Roster description: "Vision Medium: A versatile foundational model built for the world on Indian infrastructure." The site's size entry reads "Balanced processing speed with good intelligence". | | `vispark/vision-small` | 1,000,000 | 65,536 | yes | $1.05 / $3.16 | Fallback. Roster description: "Vision Small: India's fast and efficient foundational AI." The site's size entry reads "Fastest processing speed with basic intelligence". | Context, max output, prices and modalities come from an unauthenticated `GET https://api.lab.vispark.in/v1/models` call made 2026-09-29 (3 models; 3 in this catalog): `context_length` 1000000, `max_output_length` 65536, and `input_modalities` `text`, `image`, `audio`, `video`, `file` for the three models. The `$/M` figures are the roster's `pricing.prompt` and `pricing.completion` strings times 1,000,000 (`"0.00000737"` and `"0.00002211"` for `vispark/vision-large`, `"0.00000421"` and `"0.00001263"` for `vispark/vision-medium`, `"0.00000105"` and `"0.00000316"` for `vispark/vision-small`). The site's price text for the Vision sizes, from the script https://lab.vispark.in/assets/index-WmfFPhvJ.js that https://lab.vispark.in/ loads (retrieved 2026-09-29): | Size | Price text as the site shows it | | -------- | -------------------------------------------------------------------------- | | `small` | "₹10 input/₹30 output per 100k tokens. Minimum 600 input tokens charged." | | `medium` | "₹40 input/₹120 output per 100k tokens. Minimum 600 input tokens charged." | | `large` | "₹70 input/₹210 output per 100k tokens. Minimum 600 input tokens charged." | For `vispark/vision-small`, ₹10 per 100k input tokens is ₹100 per 1M, which at "$1 (USD) = ~95 units" is about $1.05, the roster's figure. **Vision:** the three models are `vision: true`. The roster lists `image` in `input_modalities`, and the site's playground text reads "Supports images, audio, video, and PDFs (max 25MB each)". The Vision model's Limitations text reads "Combined content: 980,000 tokens maximum". Each model's `status` in the JSON is `production`, a placeholder for a value the catalog schema requires; it is not a vendor statement. `models.defaultContextWindow` (128,000) and `models.defaultMaxOutputTokens` (16,384) are NeuroLink placeholders for model ids outside the catalog, not vendor figures. **Fallback order** when the default is unavailable: `vispark/vision-medium` → `vispark/vision-small`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `vispark/vision-small`. --- ## Vendor-stated error handling These lines are quoted from the Vision model's Limitations text on the site (script https://lab.vispark.in/assets/index-WmfFPhvJ.js, retrieved 2026-09-29). They are the vendor's wording, not NeuroLink behaviour, and the catalog's `errorRules` (401, 402, 429) carry them: - "Check HTTP status codes (200, 400, 401, 402, 429)" - "Handle rate limiting with exponential backoff" - "Validate API keys and sufficient units" - "API rate limit: 240 requests/minute" The site's script also uses "Insufficient units for this operation" as the fallback message for HTTP 402. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Vispark — **docs- and roster-verified, not live-verified**: | Probe | Result | | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /v1/models`, HTTP 200, 3 models, 2026-09-29 — no key used; `GET https://api.lab.vispark.in/models` returned the same body | | Billing | public script strings "₹1 (INR) = 1 unit" and "$1 (USD) = ~95 units" from the Buy More Units panel, 2026-09-29 | | Auth-failure shape | unauthenticated `GET https://api.lab.vispark.in/v1/chat/completions` returned HTTP 405 with an HTML body titled "405 Method Not Allowed"; no `authProbe` is recorded, and `errorRules` carry the status codes and sentences of the site's Limitations text | | Tools / structured output | the roster lists `tools`, `json_mode` and `structured_outputs` in `supported_features`, and the Vision entry reads "Supports Tool Calling and Continual Learning; updates weights in real-time."; none was exercised, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=vispark` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Voyage AI Provider Guide # Voyage AI Provider Guide **Top-tier RAG embeddings — text-only provider exposing `embed()` and `embedMany()` (chat / streaming intentionally not supported)** ## Quick Start ### 1. Get an API Key Sign up at [https://www.voyageai.com/](https://www.voyageai.com/) and create an API key at [https://dash.voyageai.com/api-keys](https://dash.voyageai.com/api-keys). ### 2. Configure Environment ```bash # Required VOYAGE_API_KEY=pa-... # Optional: override the default model (default: voyage-3.5) VOYAGE_MODEL=voyage-3-large # Optional: override the base URL # VOYAGE_BASE_URL=https://api.voyageai.com/v1 ``` ### 3. Generate Your First Embedding ```typescript const provider = await ProviderFactory.createProvider("voyage"); const vector = await provider.embed( "The quick brown fox jumps over the lazy dog", ); console.log(`Vector length: ${vector.length}`); // 1024 for voyage-3.5 ``` --- ## SDK Usage ### Single Embedding ```typescript const provider = await ProviderFactory.createProvider("voyage"); const vector = await provider.embed("Why is the sky blue?", "voyage-3.5"); // vector: number[] ``` ### Batch Embeddings ```typescript const provider = await ProviderFactory.createProvider("voyage"); const vectors = await provider.embedMany( ["Document 1 content...", "Document 2 content...", "Document 3 content..."], "voyage-3-large", ); // vectors: number[][] ``` ### Code Embeddings ```typescript const provider = await ProviderFactory.createProvider("voyage"); const codeVector = await provider.embed( `function fibonacci(n) { return n < 2 ? n : fibonacci(n-1) + fibonacci(n-2); }`, "voyage-code-3", ); ``` ### Per-Call Credentials ```typescript // createProvider(name, model, sdk, region, credentials) const provider = await ProviderFactory.createProvider( "voyage", undefined, undefined, undefined, { voyage: { apiKey: "user-specific-key" } }, ); const vector = await provider.embed("text"); ``` ### Use with NeuroLink RAG Voyage embeddings plug into NeuroLink's RAG pipeline. Configure the RAG embedder to use Voyage: ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "openai", // any chat-capable provider for the LLM half prompt: "What are the key features?", rag: { files: ["./docs/guide.md"], embedder: { provider: "voyage", model: "voyage-3.5" }, }, }); ``` --- ## CLI Usage Voyage is embedding-only — there is no `cli generate` flow because generate is a chat-completion path. Use the SDK directly, or use Voyage as the embedder behind a RAG-enabled `cli generate`: ```bash pnpm run cli generate "What does the README say?" \ --provider openai \ --rag-files ./README.md \ --rag-embedder voyage:voyage-3.5 ``` --- ## Provider Aliases | Alias | Example | | ----------- | ---------------------- | | `voyage` | `--provider voyage` | | `voyage-ai` | `--provider voyage-ai` | (Note: aliases are mostly relevant for RAG embedder routing; standalone chat use is not supported.) --- ## Configuration Reference | Environment Variable | Required | Default | Description | | -------------------- | -------- | ----------------------------- | ----------------------- | | `VOYAGE_API_KEY` | Yes | — | Voyage AI API key | | `VOYAGE_MODEL` | No | `voyage-3.5` | Default embedding model | | `VOYAGE_BASE_URL` | No | `https://api.voyageai.com/v1` | Base URL | --- ## Model Reference Per the [Voyage embeddings docs](https://docs.voyageai.com/docs/embeddings): | Model | Default dim | Tokens | Best For | | ----------------------- | ----------- | ------ | ------------------------------- | | `voyage-4` | 1024 | 32K | General-purpose, 4.x line | | `voyage-4-large` | 1024 | 32K | Flagship, highest quality (4.x) | | `voyage-4-lite` | 1024 | 32K | Smaller / cheaper (4.x) | | `voyage-code-4` | 1024 | 32K | Code retrieval (4.x) | | `voyage-3.5` | 1024 | 32K | General-purpose (default) | | `voyage-3.5-lite` | 1024 | 32K | Smaller / cheaper | | `voyage-3-large` | 1024 | 32K | Flagship; highest accuracy | | `voyage-code-3` | 1024 | 32K | Code retrieval | | `voyage-finance-2` | 1024 | 32K | Finance domain | | `voyage-law-2` | 1024 | 16K | Legal domain | | `voyage-multilingual-2` | unspecified | 32K | Cross-lingual | **Matryoshka flexible dimensions:** `voyage-4`, `voyage-4-large`, `voyage-4-lite`, `voyage-code-4`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-3-large`, and `voyage-code-3` all support flexible output dimensions of **256 / 512 / 1024 / 2048** via the `output_dimension` parameter on the Voyage API. The default (and what NeuroLink currently returns) is 1024. `voyage-finance-2`, `voyage-law-2`, and `voyage-multilingual-2` only emit the default dimension. See the FAQ below for how to request a smaller dimension explicitly. --- ## Feature Support Matrix | Feature | voyage-3.5 | voyage-3-large | voyage-code-3 | | --------------- | -------------------- | -------------- | ------------- | | Embeddings | Yes | Yes | Yes | | Single embed | Yes | Yes | Yes | | Batch embed | Yes (128 inputs/req) | Yes | Yes | | Text generation | No | No | No | | Streaming | No | No | No | | Tool calling | No | No | No | | Vision | No | No | No | --- ## Troubleshooting ### "Invalid Voyage AI API key" ```bash echo $VOYAGE_API_KEY export VOYAGE_API_KEY=pa-... ``` Get / rotate at [https://dash.voyageai.com/api-keys](https://dash.voyageai.com/api-keys). ### "Voyage AI rate limit exceeded" Voyage has per-minute and daily limits per tier. Free-tier is generous for development; production usage typically requires the paid tier. Implement exponential backoff or use `embedMany` (batched) instead of many single `embed` calls. ### "embed() / embedMany() not available" Voyage IS embedding-only — these methods work. If you see "not supported" errors, verify you're using `provider: "voyage"` and the API key is set. For chat / streaming on Voyage, you can't — pick a different provider (xAI / Groq / OpenAI / etc.). ### "voyage-3.5 returns 1024-dim, but I want 512" Use `voyage-3.5-lite` (native 512-dim) instead. Voyage doesn't currently expose a `dimensions` parameter on the standard models — pick the right model for the dimension you need. ### "How do I rerank with Voyage?" Voyage doesn't expose rerank through this provider class today. For reranking, use the Jina AI provider (see `src/lib/providers/jina.ts`) which exposes `rerank()` directly. --- ## See Also - Jina AI — sibling embedding-only provider with reranking support (no setup doc yet; see `src/lib/providers/jina.ts`) - [RAG Integration](/docs/features/rag) — how to use Voyage embeddings in the RAG pipeline - [Adding a new LLM provider](/docs/provider-integration/15-adding-llm-provider) — covers the embedding-only override pattern in §H --- **Need Help?** Open a [GitHub Discussion](https://github.com/juspay/neurolink/discussions) or [issue](https://github.com/juspay/neurolink/issues). --- ## Vultr Inference Provider Guide # Vultr Inference Provider Guide Vultr Inference is a **Tier-2 catalog provider**: it is served by NeuroLink's OpenAI-compatible chat-completions path, so its entire integration is one JSON file (`src/lib/providers/catalog/vultr-inference.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** The model data, endpoint and error statuses below come from > Vultr's public pages and unauthenticated GET requests, and no account was > created and no API key was used to build it. `billingPolicy`, each model's > `status` and the two `models.default*` values are required by the schema and > are not Vultr statements. `evidence.liveMatrix` is `null` until someone runs > the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://docs.vultr.com/products/compute/serverless-inference/provisioning and follow the Vultr Console steps: Products, Serverless, Inference, Add Serverless Inference, then provide a Label, "acknowledge the list of supported models and the charges note", and click Add Serverless Inference 2. Open the new subscription's management page and copy the API key from its overview page (https://docs.vultr.com/products/compute/serverless-inference/management/connection: "API key is necessary to send any request to the inference endpoints") 3. Charges: the provisioning page above lists the charges note among the items to acknowledge, and the FAQ (https://docs.vultr.com/products/compute/serverless-inference/faq) says the subscription's Usage tab shows "details on your current token usage, overage, and any associated costs" 4. Set `VULTR_INFERENCE_API_KEY` in your .env file (the authentication example on https://api.vultrinference.com/ writes `${VULTR_API_KEY}`, which NeuroLink does not read) The FAQ also says the key can be regenerated from the Overview page in the Vultr Console and that "This will invalidate the previous API key". ### 2. Configure ```bash export VULTR_INFERENCE_API_KEY=your-api-key export VULTR_INFERENCE_MODEL=glm-5.2 # optional — overrides the default model export VULTR_INFERENCE_BASE_URL=https://api.vultrinference.com/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "vultr-inference", model: "glm-5.2", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider vultr-inference ``` Per-request credentials: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "vultr-inference", credentials: { vultrInference: { apiKey: process.env.VULTR_INFERENCE_API_KEY }, }, }); ``` --- ## Models | Model | Context | Max output | Vision | $/M in · out | Notes | | ------------------------ | --------- | ---------- | ------ | ------------- | ---------------------------------------------------------------------------------------------------- | | `glm-5.2` ⭐ | 1,048,576 | 1,048,576 | yes | $0.75 / $3 | NeuroLink default; roster: "GLM-5.2 is Z.ai's flagship model for long-horizon tasks". | | `deepseek-v4.1-flash` | 1,048,576 | 1,048,576 | yes | $0.15 / $0.6 | Fallback; roster: "support for reasoning and tool calling". | | `qwen3.8-flash-next` | 262,144 | 262,144 | yes | $0.1 / $0.2 | Fallback; roster: "reasoning, and tool calling". | | `mimo-v2.6-flash-rl` | 1,048,576 | 1,048,576 | yes | $0.1 / $0.25 | Fallback; roster: "Supports reasoning and tool calling, served at FP8." | | `deepseek-v4-flash-0731` | 1,048,576 | 1,048,576 | yes | $0.1 / $0.25 | Roster: "DeepSeek's official V4 Flash release". | | `glm-5.3` | 1,048,576 | 1,048,576 | yes | $0.75 / $3 | Roster: "Served at NVFP4 across a 1M-token context." | | `glm-5.3-flash` | 1,048,576 | 1,048,576 | yes | $0.1 / $0.35 | Roster: "Z.ai's first natively multimodal GLM-5 model". | | `glm-5.x-menthol` | 202,752 | 202,752 | yes | $0.4 / $1.75 | Roster name "GLM 5"; "Z.ai's GLM-5, a 744B-parameter MoE flagship for agentic reasoning and coding". | | `laguna-s-2.1` | 1,048,576 | 1,048,576 | yes | $0.09 / $0.18 | Roster: "designed for agentic coding and long-horizon work". | | `mimo-v2.6-pro-rl` | 1,048,576 | 1,048,576 | yes | $0.4 / $0.8 | Roster: "Supports reasoning and tool calling, served at FP8." | | `minimax-m3` | 524,288 | 524,288 | yes | $0.2 / $0.9 | The roster description text says a 1M-token context; the max_context_length field says 524,288. | | `muse-glimmer-30b` | 131,072 | 131,072 | yes | $0.25 / $1 | Roster: "a dense multimodal model for reasoning, coding, and tool use". | Context, max output and prices come from the unauthenticated `GET https://api.vultrinference.com/v1/models` call made 2026-09-29 (24 entries; 12 curated into this catalog). Context is the text input `max_context_length`, max output is the output modality's `max_length`, and prices are the roster's `cost_usd` per token for the prompt and completion entries, multiplied by one million. `models.defaultContextWindow` (131,072) and `models.defaultMaxOutputTokens` (32,768) are placeholders for ids outside the catalog that the vendor does not publish: 131,072 is the context the roster lists for `muse-glimmer-30b`, and 32,768 is the default the chat-completions page shows for `max_completion_tokens`. Each model's `status` is `production`; the field is required by the schema and the value is not a Vultr statement. **Vision:** the roster lists `image` among the input modalities of the 12 catalogued models (sources `url` and `base64`; formats `image/png`, `image/jpeg`, `image/webp`, `image/gif`), hence `vision: true`. See **Message shape** under [Key Facts](#key-facts) for the request message schema. No image request was sent. **Fallback order** when the default is unavailable: `deepseek-v4.1-flash` → `qwen3.8-flash-next` → `mimo-v2.6-flash-rl`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `qwen3.8-flash-next`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Vultr Inference — **docs- and roster-verified, not live-verified**: | Probe | Result | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /v1/models`, HTTP 200, 24 models, 2026-09-29 — no key used | | Auth-failure shape | unauthenticated `GET /v1/models/all` returned 401 `{"message":"No API key provided"}` (the same body on `GET /v1/usage` and `GET /v1/models/glm-5.2`); the body carries no error code. The chat-completions reference lists 401 "Unauthorized" and 429 "Rate limit exceeded". `GET /v1/chat/completions` answered 404 and no POST was sent, so `errorRules` match the statuses `401` and `429` | | Billing | the provisioning page's Console steps say "acknowledge the list of supported models and the charges note"; the FAQ's Usage tab shows "details on your current token usage, overage, and any associated costs" — `billingPolicy` is the schema value `no-free-tier`, which is not a Vultr statement | | Tools / structured output | `tools` and `tool_calls` are documented in the chat-completions reference; `response_format` is not in its request schema. Neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=vultr-inference` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Documented error statuses The chat-completions reference at https://api.vultrinference.com/ lists these responses for `POST /chat/completions`, and says errors use OpenRouter's envelope, `{"error": {"code", "message", "type", "metadata": {"error_type"}}}`: | Status | Vultr's description | | ------ | ------------------------------------------------------------------------------------------- | | 400 | "Bad Request, including `context_length_exceeded`" | | 401 | "Unauthorized" | | 422 | "Validation Error"; the `reasoning_effort` description says "unsupported levels return 422" | | 429 | "Rate limit exceeded" | | 502 | "The model could not be reached" | | 504 | "The model timed out" | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Wafer Provider Guide # Wafer Provider Guide Wafer is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/wafer.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs- and roster-verified, not yet > live-verified.** The fields below come from Wafer's own public pages and > unauthenticated `GET` requests — no account was created and no API key was > used to build it. `evidence.liveMatrix` is `null` until someone runs the > live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://app.wafer.ai and sign in — the docs say "Sign in at app.wafer.ai to add credits and create an API key. Store your key securely." (https://docs.wafer.ai/serverless) 2. Add credits and create an API key — the docs say "Add credits, create an API key, and pay per token." (https://docs.wafer.ai/serverless) 3. Set `WAFER_API_KEY` in your .env file (the docs' Authentication row shows the `Authorization: Bearer` header) ### 2. Configure ```bash export WAFER_API_KEY=your-api-key export WAFER_MODEL=GLM-5.3 # optional — overrides the default model export WAFER_BASE_URL=https://pass.wafer.ai/v1 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "wafer", model: "GLM-5.3", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider wafer ``` Per-request credentials use the same shape as other NeuroLink providers: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "wafer", credentials: { wafer: { apiKey: process.env.WAFER_API_KEY } }, }); ``` --- ## Billing The docs page https://docs.wafer.ai/serverless says: "Access Wafer models through an OpenAI-compatible API. Add credits, create an API key, and pay per token." Wafer's information page https://www.wafer.ai/ai-info says: "Hosted open models through an OpenAI-compatible API, with usage billed per token. Customers add credits and create an API key in the Wafer app." The catalog's `billingPolicy` field takes one of `free-tier`, `free-with-card` or `no-free-tier`; the schema has no `unknown` value. The entry records `no-free-tier` as the schema's closest choice — it is not a Wafer statement. --- ## Models | Model | Context | Max output | Vision | $/M in · out (cache read) | Notes | | ----------------------------- | --------- | ---------- | ------ | ------------------------- | ------------------------------------------------------------------------------------------------------- | | `GLM-5.3` ⭐ | 1,048,576 | — | no | $0.29 / $4.40 ($0.2359) | NeuroLink default; the model in the docs' curl request examples. | | `DeepSeek-V4-Pro` | 1,048,576 | — | no | $0.40 / $4.20 ($0.32) | Fallback. | | `Kimi-K3` | 1,048,576 | 131,072 | yes | $1.44 / $9.00 ($0.30) | Fallback; roster `capabilities.vision: true`. | | `GLM-5.2` | 1,048,576 | — | no | $0.32 / $4.40 ($0.2599) | Fallback. | | `Qwen3.8-27B` | 262,144 | — | yes | $0.04 / $4.40 ($0.0342) | Roster `capabilities.vision: true`; `models.visionModel`. | | `GLM-5.3-Flash` | 1,048,576 | — | yes | $0.75 / $0.50 ($0.03) | Roster `capabilities.vision: true`; roster description ends "Available serverless to gateway partners." | | `DeepSeek-V4.1-Flash` | 1,048,576 | — | yes | $0.02 / $0.70 ($0.016) | Roster `capabilities.vision: true`. | | `DeepSeek-V4-Flash-0731-Fast` | 1,048,576 | — | no | $0.07 / $0.35 ($0.0531) | Roster-listed. | Context, max output, prices and vision come from an unauthenticated `GET https://pass.wafer.ai/v1/models` made 2026-09-29 (8 models; the 8 are in this catalog). The roster gives prices as integer cents per million tokens (`input_cents_per_million`, `output_cents_per_million`), shown above divided by 100. The cache-read figure uses `cache_read_microcents_per_million`, which carries more digits than the cents field (for `GLM-5.3`: 23,590,000 microcents, shown as $0.2359; the cents field reads 24). The roster lists `max_output_tokens: 131072` for `Kimi-K3`. The docs say "Use a model’s id in your requests." ([docs](https://docs.wafer.ai/serverless)) `models.defaultContextWindow` (128,000) and `models.defaultMaxOutputTokens` (16,384) are placeholders the vendor does not publish; they apply to a model id outside the catalog. Vision tags (`vision: true`) come from the roster's `capabilities.vision` and `supports_vision` fields, not from an image-input request — no key was used to send a real image. **Fallback order** when the default is unavailable: `DeepSeek-V4-Pro` → `Kimi-K3` → `GLM-5.2`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `Kimi-K3`. ### Roster descriptions The strings below are the `wafer.description` field of the roster entries, quoted as returned by `GET https://pass.wafer.ai/v1/models` on 2026-09-29. - `GLM-5.3`: "GLM-5.3 — Z.ai's flagship GLM-5.3 MoE (391B, NVFP4), self-hosted on the Wafer fleet with a 1M-token context window and frontier coding/agentic performance. Available serverless." - `DeepSeek-V4-Pro`: "DeepSeek-V4-Pro -- DeepSeek's V4 Pro MoE, self-hosted on the Wafer fleet with a 1M-token context window, reasoning-effort control and tool calling. Available serverless." - `Kimi-K3`: "Kimi K3 sparse MoE model, self-hosted on the Wafer fleet. Available serverless with a 1M-token context window and strong coding/agentic performance." - `GLM-5.2`: "GLM-5.2 — Z.ai's GLM-5.2 MoE (NVFP4), self-hosted on the Wafer fleet with a 1M-token context window, strong coding and reasoning, and tool calling. Available serverless." - `Qwen3.8-27B`: "Qwen3.8-27B -- Alibaba's dense 27B vision-language model, self-hosted on the Wafer fleet with a 262K-token context window, image and video input, reasoning-effort control and tool calling. Available serverless." - `GLM-5.3-Flash`: "GLM-5.3-Flash — Z.ai's fast GLM-5.3 MoE variant, self-hosted on the Wafer fleet with a 1M-token context window and strong coding/agentic performance. Available serverless to gateway partners." - `DeepSeek-V4.1-Flash`: "DeepSeek-V4.1-Flash — DeepSeek's V4.1 Flash MoE (552B total, 8B active for prefill / 16B for decode, 1M-token context), self-hosted on the Wafer fleet with reasoning-effort control and tool calling. Available serverless." - `DeepSeek-V4-Flash-0731-Fast`: "The same model served for high TPS." ### Roster `reasoning_effort` blocks The roster lists a `reasoning_effort` block on the 8 models (`control`, `efforts`, `default`). These are roster values; no request set an effort. | Model | `control` | `efforts` | `default` | | --------------------------------------------------------------------------------------- | --------------- | ---------------------------- | --------- | | `GLM-5.3`, `GLM-5.2`, `GLM-5.3-Flash`, `DeepSeek-V4-Pro`, `DeepSeek-V4-Flash-0731-Fast` | `system_prompt` | none, low, high, max | low | | `Kimi-K3` | `native_effort` | none, high, max | none | | `Qwen3.8-27B` | `native_effort` | none, low, medium, high, max | high | | `DeepSeek-V4.1-Flash` | `native_effort` | none, low, high, max | none | --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Wafer — **docs- and roster-verified, not live-verified**: | Probe | Result | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET https://pass.wafer.ai/v1/models`, HTTP 200, 8 models, 2026-09-29 — no key used | | Billing | https://docs.wafer.ai/serverless: "Add credits, create an API key, and pay per token." — recorded as `no-free-tier`, the schema's closest value (2026-09-29) | | Auth-failure shape | unauthenticated `GET https://pass.wafer.ai/v1/chat/completions` returned HTTP 401 with `error.type` `authentication_error` and `error.code` `missing_api_key`, 2026-09-29 (a GET; no POST was sent) — `errorRules` match status `401` | | Tools / structured output | roster `chat_completions` flags on the 8 models: `tools`, `tool_streaming`, `json_object`, `json_schema` and `tools_with_response_format` are `true`. These flags were not exercised with a request, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=wafer` with a real key and record the result. | Pages opened for this entry: https://www.wafer.ai/ai-info, https://docs.wafer.ai/serverless, https://docs.wafer.ai/serverless/zero-data-retention, https://www.wafer.ai/terms and https://app.wafer.ai. Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting | Symptom | Cause | Fix | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | | HTTP 401 `missing_api_key` | Wafer's response body reads: `Missing API key. Provide credentials via Authorization: Bearer or x-api-key: .` | Set `WAFER_API_KEY`; NeuroLink's Tier-2 wire format sends `Authorization: Bearer`, one of the two headers Wafer's message names | | Structured output ignored with tools attached | `structuredOutputWithTools` is `false` on this entry — no combined request was sent | NeuroLink omits `response_format` automatically whenever tools are present, before sending | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## W&B Inference Provider Guide # W&B Inference Provider Guide W&B Inference (the vendor's docs call it Serverless Inference) is a **Tier-2 catalog provider**: OpenAI-wire-compatible with no behavioural quirks, so its entire integration is one JSON file (`src/lib/providers/catalog/wandb-inference.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** The vendor's `GET /v1/models` needs a key (an unauthenticated > GET answers HTTP 401), so the model ids come from the vendor's public > [models page](https://docs.wandb.ai/inference/models) and the roster has not > been checked. No account was created and no API key was used to build this > entry. `evidence.liveMatrix` is `null` until someone runs the live capability > matrix with a real key (see [Verification status](#verification-status) > below). ## Quick Start ### 1. Get an API key 1. Visit: https://app.wandb.ai/login?signup=true and sign up for a W&B account ([prerequisites](https://docs.wandb.ai/inference/prerequisites)) 2. Create an API key: click your user profile icon, then User Settings, then Create new API key, and copy it immediately because W&B shows the full key once ([prerequisites](https://docs.wandb.ai/inference/prerequisites)); the [API reference](https://docs.wandb.ai/inference/api-reference) also names https://wandb.ai/settings 3. Project: the [prerequisites page](https://docs.wandb.ai/inference/prerequisites) lists a W&B project among the items you must have: "Create a project in your W&B account to track usage." The [chat completions reference](https://docs.wandb.ai/inference/api-reference/chat-completions) lists "Your W&B team and project: [YOUR-TEAM]/[YOUR-PROJECT] (optional)." 4. Credits: "Serverless Inference credits come with Free, Pro, and Academic plans for a limited time." Free accounts must activate pay-as-you-go inference on the Billing tab or upgrade to a paid plan when credits run out; the default cap for a Free account is $100/month ([usage limits](https://docs.wandb.ai/inference/usage-limits)) 5. Set `WANDB_INFERENCE_API_KEY` in your .env file ### 2. Configure ```bash export WANDB_INFERENCE_API_KEY=your-api-key export WANDB_INFERENCE_MODEL=openai/gpt-oss-120b # optional — overrides the default model export WANDB_INFERENCE_BASE_URL=https://api.inference.wandb.ai/v1 # optional — proxy or self-hosted gateway ``` The [chat completions reference](https://docs.wandb.ai/inference/api-reference/chat-completions) shows an optional team and project for usage tracking (`project="[YOUR-TEAM]/[YOUR-PROJECT]"` on the Python OpenAI client, or an `OpenAI-Project` header). The [API reference](https://docs.wandb.ai/inference/api-reference) says: "If you don’t specify these, W&B uses your default entity and the project name inference." The catalog schema has no field for extra request headers, so this entry does not send one. ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "wandb-inference", model: "openai/gpt-oss-120b", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider wandb-inference ``` Per-request credentials use the same shape as for the other catalog providers: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "wandb-inference", credentials: { wandbInference: { apiKey: process.env.WANDB_INFERENCE_API_KEY }, }, }); ``` --- ## Billing The [usage limits page](https://docs.wandb.ai/inference/usage-limits) says "Serverless Inference credits come with Free, Pro, and Academic plans for a limited time. Enterprise availability may vary." When credits run out, Free accounts "must activate pay-as-you-go inference on the **Billing** tab, or upgrade to a paid plan to continue using Serverless Inference", and the page adds "W&B requires prepayment for paid Inference access." Its account-tier table lists a default cap of $100/month for Free, $6,000/month for Pro and $700,000/year for Enterprise. Per-token prices are on the [pricing page](https://wandb.ai/site/pricing/tokens/), which links from the docs as `https://wandb.ai/site/pricing/inference`. The entry records `free-tier`. --- ## Models | Model | Context | Vision | $/M in · out | Notes | | ------------------------------------ | --------- | ------ | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `openai/gpt-oss-120b` ⭐ | 131,072 | no | $0.03 / $0.17 | NeuroLink default. "Efficient Mixture-of-Experts model designed for high-reasoning, agentic and general-purpose use cases." Reasoning page: "Always on". | | `deepseek-ai/DeepSeek-V4-Flash-0731` | 262,144 | no | $0.13 / $0.28 (cache hit $0.07) | "an MoE model great for coding, reasoning, and agentic workloads." | | `meta-llama/Llama-3.3-70B-Instruct` | 128,000 | no | $0.71 / $0.71 | "Multilingual model excelling in conversational tasks, detailed instruction-following, and coding." | | `openai/gpt-oss-20b` | 131,072 | no | $0.03 / $0.13 | "Lower latency Mixture-of-Experts model trained on OpenAI's Harmony response format with reasoning capabilities." Example model on the tool-calling, structured-output and JSON-mode pages. | | `meta-llama/Llama-3.1-8B-Instruct` | 131,072 | no | $0.22 / $0.22 | "Efficient conversational model optimized for responsive multilingual chatbot interactions." Model in the quick-start example on the Serverless Inference page. | | `zai-org/GLM-5.2` | 1,048,576 | no | $0.76 / $2.42 (cache hit $0.14) | "a Mixture-of-Experts language model featuring 40 billion activated parameters and a total of 744 billion parameters." | | `deepseek-ai/DeepSeek-V4-Pro-0813` | 1,048,576 | no | $1.31 / $3.96 (cache hit $0.044) | "a 1.6T-parameter MoE model excelling at advanced reasoning, coding, and complex agentic workloads." | | `google/gemma-4-26B-A4B-it` | 262,144 | yes | $0.10 / $0.30 (cache hit $0.05) | "a multimodal MoE model with LoRA support and function calling for agentic workflows." `models.visionModel`. | | `Qwen/Qwen3.8-27B` | 262,144 | yes | $0.40 / $3.00 (cache hit $0.15) | "a dense multimodal model suited for coding, research, vision, and long-running agent tasks." | | `moonshotai/Kimi-K2.6` | 262,144 | yes | $0.65 / $3.41 (cache hit $0.15) | "a multimodal Mixture-of-Experts language model featuring 32 billion activated parameters and a total of 1 trillion parameters." | | `deepseek-ai/DeepSeek-V4.1-Flash` | 1,048,576 | yes | $0.20 / $0.65 (cache hit $0.03) | "a multimodal MoE model for coding, reasoning, and agentic workloads with long contexts." | | `ibm-granite/granite-4.2-8b` | 131,072 | no | $0.10 / $0.15 (cache hit $0.05) | "an instruct model capable of enhanced tool calling, instruction following, and chat capabilities." | Context comes from the `contextWindow` field of the vendor's public catalog API, `GET https://trace.wandb.ai/inference/catalog/models` (called unauthenticated on 2026-09-29; the vendor's [Service API overview](https://docs.wandb.ai/weave/reference/service-api) gives `https://trace.wandb.ai` as the base URL, and the [endpoint page](https://docs.wandb.ai/weave/reference/service-api/inference/inference-catalog-models) says "This API is available without authentication."). The models page shows the same figures in rounded form, for example "262k". Prices come from the [pricing page](https://wandb.ai/site/pricing/tokens/), shown per 1 million tokens; its rows are named as on the models page, and a `-` in its cache hit column means no cache-hit price is recorded here. Notes quote the "Description" column of the [models page](https://docs.wandb.ai/inference/models), retrieved 2026-09-29. `models.defaultContextWindow` (128,000) and `models.defaultMaxOutputTokens` (8,192) are placeholders: the vendor does not publish a general default or a maximum output figure, and no per-model `maxOutputTokens` is set. **Fallback order** when the default is unavailable: `deepseek-ai/DeepSeek-V4-Flash-0731` → `meta-llama/Llama-3.3-70B-Instruct` → `openai/gpt-oss-20b` → `meta-llama/Llama-3.1-8B-Instruct` → `zai-org/GLM-5.2` → `deepseek-ai/DeepSeek-V4-Pro-0813` → `google/gemma-4-26B-A4B-it` → `Qwen/Qwen3.8-27B` → `moonshotai/Kimi-K2.6` → `deepseek-ai/DeepSeek-V4.1-Flash` → `ibm-granite/granite-4.2-8b`. **Vision:** `vision: true` marks the rows whose "Type" column on the models page reads "Text, Vision"; rows that read "Text" are `vision: false`. No image request was sent to confirm either. **Lifecycle:** the [lifecycle page](https://docs.wandb.ai/inference/lifecycle) defines "Generally available" as "The model is fully supported and recommended for use." and says requests to retired models "fail and return an `HTTP 404` status code." The 12 models in this catalog are rows of the models page's "Generally available models" table. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for W&B Inference — **docs-verified only, not live-verified**: | Probe | Result | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Roster | unauthenticated `GET https://api.inference.wandb.ai/v1/models` answered HTTP 401 on 2026-09-29, so the roster has not been checked; model ids are taken from the [models page](https://docs.wandb.ai/inference/models) (retrieved 2026-09-29) | | Public catalog cross-check | unauthenticated `GET https://trace.wandb.ai/inference/catalog/models` answered HTTP 200 with 47 models on 2026-09-29; the 12 catalog ids appear with `lifecycleStage` `general-availability`, and their `contextWindow` and price fields agree with the pricing page | | Billing | the usage limits page states credits "come with Free, Pro, and Academic plans for a limited time", 2026-09-29 | | Auth-failure shape | unauthenticated `GET /v1/models` and unauthenticated `GET /v1/chat/completions` both answered HTTP 401 with `{"error":{"code":"invalid_api_key","message":"Missing bearer authentication in header","type":"invalid_request_error"}}` on 2026-09-29. The `errorRules` for 402, 403, 404 and 429 follow the vendor's [support articles](https://docs.wandb.ai/support/inference); those responses were not observed | | Tools / structured output | documented on the tool-calling, structured-output and JSON-mode pages; neither was exercised live, and no combined tools+schema request was sent — `structuredOutputWithTools` stays `false` | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=wandb-inference` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting Each row restates a vendor [support article](https://docs.wandb.ai/support/inference). | Symptom | Cause (vendor) | Fix (vendor) | | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | HTTP 401 "Authentication failed" | An API key that is "invalid, expired, or revoked", or an incorrect W&B project entity name or project name ([401 article](https://docs.wandb.ai/support/inference/articles/api-error-code-401-authentication-failed)) | Regenerate the key from your W&B settings; check the project entity and name | | HTTP 402 "You exceeded your current quota" | No remaining credits, or the monthly spending cap was reached ([402 article](https://docs.wandb.ai/support/inference/articles/api-error-code-402-you-exceeded-your-cur)) | Check plan and billing details, get more credits, or increase limits | | HTTP 403 "Country, region, or territory not supported" | Access from an unsupported location, determined from the IP address of the request ([403 article](https://docs.wandb.ai/support/inference/articles/api-error-code-403-country-region-or-ter)) | Check the [geographic restrictions](https://docs.wandb.ai/inference/usage-limits#geographic-restrictions) | | HTTP 403 "The inference gateway is not enabled for your organization" | The organization has not enabled the inference gateway ([403 article](https://docs.wandb.ai/support/inference/articles/api-error-code-403-the-inference-gateway)) | Ask your organization's W&B administrator to enable it | | HTTP 404 | A model id that does not match an available model, or a model that was deprecated or removed ([404 article](https://docs.wandb.ai/support/inference/articles/api-error-code-404-model-not-found)) | Verify the id against the [models page](https://docs.wandb.ai/inference/models); ids are case-sensitive | | HTTP 400 or 422 | A parameter the model does not support, an out-of-range value, or a malformed `messages` payload ([422 article](https://docs.wandb.ai/support/inference/articles/api-error-code-422-invalid-request-parameters)) | Read the response body before changing the request | | HTTP 429 "Concurrency limit reached for requests" | Too many concurrent requests ([429 article](https://docs.wandb.ai/support/inference/articles/api-error-code-429-concurrency-limit-rea)) | Reduce concurrent requests; use exponential backoff when retrying | | HTTP 503 "The engine is currently overloaded" | High traffic ([503 article](https://docs.wandb.ai/support/inference/articles/api-error-code-503-the-engine-is-current)) | Retry after a short delay with exponential backoff | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [All providers](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- ## Whistle (Built-in Local STT) # Whistle — Built-in Local Speech-to-Text **Speech-to-text with no API key, no server and no native addon.** ------------ | -------------------------------------------------------- | | Provider name | `whistle` | | Size on disk | ~17.9 MB (engine 1 MB + model 16.9 MB) | | Credentials | none | | Languages | English, German, French, Spanish, Italian, Dutch, Polish | | Streaming | native (the engine's own streaming decoder) | | Word timestamps | yes, with a per-word probability | | Diarization | no | | Speed | ~0.5 s of CPU per 10 s of audio on one laptop core | | Licence | engine and model are Apache-2.0 | --- ## First use The first transcription downloads three files from pinned Hugging Face revisions, checks each against a SHA-256, and writes it atomically (temporary file, then rename), so an interrupted download never leaves a file that looks complete. Concurrent first calls share one download. Every later call reads the files from disk, and Whistle works fully offline from then on. | File | Source | | -------------- | ---------------------------------------------------------- | | `needle.js` | `Cactus-Compute/needle3` @ `2ae11323…`, `wasm/needle.js` | | `needle.wasm` | `Cactus-Compute/needle3` @ `2ae11323…`, `wasm/needle.wasm` | | `whistle.cact` | `Cactus-Compute/whistle` @ `b358ddad…`, `whistle.cact` | To warm up ahead of the first request (download, verify, start the worker): ```typescript await new WhistleSTT().warmUp(); ``` ### Where the files live The first of these that is set wins: 1. `credentials.stt.whistle.modelDir` 2. `NEUROLINK_WHISTLE_DIR` 3. `$NEUROLINK_MODEL_DIR/whistle` 4. `~/.neurolink/models/whistle` ### Air-gapped machines Set `NEUROLINK_WHISTLE_AUTO_DOWNLOAD=0` (or `credentials.stt.whistle.autoDownload: false`) to forbid the download. If a file is then missing, or does not match its hash, the call fails with an error that lists each of the three files, the exact path it must be placed at, and the URL to fetch it from. The same error is raised when the download is allowed but fails (offline, proxy, HTTP error). --- ## Usage ```typescript const neurolink = new NeuroLink(); const result = await neurolink.transcribe({ audio: await readFile("meeting.wav"), provider: "whistle", // optional when no other STT provider is configured language: "en", // or "auto" / omitted to detect wordTimestamps: true, }); console.log(result.text); console.log(result.words?.[0]); // { word, start, end, confidence } ``` ### Options | Option | Effect | | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `language` | `en de fr es it nl pl`, or a locale (`"de-DE"`). `"auto"`, omitted, or any other language lets the engine detect one of the seven. | | `wordTimestamps` | Return `words[]` with `start`/`end` (seconds) and `confidence`. | | `vocabulary` | Keyword biasing for names and jargon — **only** when `model: "whistle-keywords"` or `NEUROLINK_WHISTLE_KEYWORDS=1`. See below. | | `format` | Container hint for a buffer. WAV is recognised from its header whatever this says; `pcm16` means raw PCM16LE mono at `sampleRate`. | | `sampleRate` | Rate of `pcm16` input and of streamed frames. Default 16000. | ### Result - `text`, `language` (detected or requested), `duration` (seconds) - `confidence` — the mean per-word probability (`metadata.confidenceSource: "word_logprobs"`); 0 for empty text - `words` — when `wordTimestamps` is set - `metadata` — `provider: "whistle"`, `model: "whistle"`, `latency` (ms), `ttftMs`, `decodeTps`, `chunks` (how many ≤30 s passes the audio took) ### Keyword biasing The engine can favour given words and phrases, which helps with names and product terms. It is **opt-in** because the decoder can loop (repeat a phrase) when given a long list: enable it per call with `model: "whistle-keywords"`, or globally with `NEUROLINK_WHISTLE_KEYWORDS=1`. At most 32 entries are sent; keep the list short and specific. For larger dictionaries, use the dictionary/correction layer of `transcribe()` instead, which repairs the transcript after the fact. --- ## Long audio The engine reads at most 30 s per call. Longer audio is cut at the quietest 20 ms frame near every 24 s mark (searching ±3 s), each piece is transcribed in turn, and word times are shifted back onto the whole recording. Once a language is detected in the first piece it is held for the rest. One request may be up to one hour long. --- ## Streaming Whistle streams natively. `transcribeStream()` takes PCM16LE mono frames (at `sampleRate`, default 16 kHz, any frame size), feeds the engine about a second at a time, and yields: - a **final** segment whenever the engine commits words (two consecutive passes agreed on them), with word timings measured from the start of the stream — join the finals with a space for the transcript; - an **interim** segment carrying the unconfirmed tail whenever it changes. Each stream runs on a worker of its own, so it never interleaves with batch calls on the same handler. ```typescript const whistle = new WhistleSTT(); for await (const segment of whistle.transcribeStream(micFrames(), { language: "en", })) { if (segment.isFinal) process.stdout.write(segment.text + " "); } ``` --- ## Audio formats | Format | Decoded by | | --------------------------------------------------------------------- | -------------- | | WAV — 8/16/24/32-bit PCM, 32/64-bit float, any rate and channel count | Whistle itself | | raw `pcm16` | Whistle itself | | mp3, m4a, mp4, ogg, opus, webm, flac, mpeg | ffmpeg | Compressed formats need ffmpeg: `FFMPEG_PATH`, the optional `ffmpeg-static` package (`pnpm add ffmpeg-static`), or `ffmpeg` on `PATH`. Without one, the call fails with an error that names the formats Whistle can read by itself. --- ## Environment variables | Variable | Default | Meaning | | --------------------------------- | ------- | --------------------------------------------------------------- | | `NEUROLINK_WHISTLE_DIR` | — | Directory holding the three files | | `NEUROLINK_MODEL_DIR` | — | Parent directory for local models; Whistle uses `/whistle` | | `NEUROLINK_WHISTLE_AUTO_DOWNLOAD` | `1` | `0` forbids the first-use download | | `NEUROLINK_WHISTLE_KEYWORDS` | `0` | `1` enables keyword biasing from `vocabulary` | | `FFMPEG_PATH` | — | ffmpeg binary for compressed formats | --- ## Runtime behaviour - One warm worker thread per `WhistleSTT` instance holds the engine and the model (~0.2 s to start); requests are answered in order. The worker is unreferenced while idle, so it never keeps your process alive; call `dispose()` to stop it early. - If the worker crashes, the requests it held fail with an `STTError`, and the next call starts a fresh worker. --- ## Accuracy Whistle is a 17 MB model. It is accurate on clear speech in its seven languages, but it is **noticeably behind cloud engines** (Deepgram, ElevenLabs Scribe, Google, Azure) **and large Whisper-class models** on accents, background noise, overlapping speakers, rare names and domain jargon, and it does not diarize. It is a sensible default for development, offline use and privacy-sensitive audio; configure a cloud or self-hosted provider where accuracy matters, or add a dictionary and the correction layer of `transcribe()`. --- ## xAI Grok Provider Guide # xAI Grok Provider Guide **Text + vision generation with the Grok family through a single API** ## Quick Start ### 1. Get an API Key Sign up at [https://console.x.ai/](https://console.x.ai/) and create an API key under **API Keys**. ### 2. Configure Environment Add to your `.env` file: ```bash # Required XAI_API_KEY=your-xai-api-key # Optional: override the default model (default: grok-3) XAI_MODEL=grok-3 # Optional: override the base URL (default: https://api.x.ai/v1) # XAI_BASE_URL=https://api.x.ai/v1 ``` ### 3. Install NeuroLink ```bash npm install @juspay/neurolink # or pnpm add @juspay/neurolink ``` ### 4. Generate Your First Response ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "xai", input: { text: "Explain how transformers handle long-range dependencies." }, }); console.log(result.content); ``` --- ## Supported Models | Model ID | Family | Context | Vision | Notes | | ---------------------- | ------------- | ------- | ------ | -------------------------- | | `grok-3` | Grok 3 | 131K | No | Default; best reasoning | | `grok-3-mini` | Grok 3 Mini | 131K | No | Faster + cheaper Grok 3 | | `grok-2-latest` | Grok 2 | 131K | No | Previous flagship | | `grok-2-vision-latest` | Grok 2 Vision | 32K | Yes | Multimodal text + image | | `grok-beta` | Beta | 131K | No | Pre-release / experimental | Pass any model ID via `--model` (CLI) or `model:` (SDK). --- ## SDK Usage ### Basic Generation ```typescript const ai = new NeuroLink(); const result = await ai.generate({ provider: "xai", input: { text: "Write a TypeScript function to debounce an async function." }, }); console.log(result.content); ``` ### Vision Input (Grok 2 Vision) ```typescript const screenshot = readFileSync("./screenshot.png"); const result = await ai.generate({ provider: "xai", model: "grok-2-vision-latest", input: { text: "What's wrong with this UI?", images: [screenshot], }, }); ``` ### Streaming ```typescript const stream = await ai.stream({ provider: "xai", input: { text: "Explain how B-trees work, step by step." }, }); for await (const chunk of stream.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } ``` ### Tool Calling ```typescript const result = await ai.generate({ provider: "xai", input: { text: "What's the weather in San Francisco?" }, tools: { getWeather: { description: "Get current weather for a location", parameters: { location: { type: "string" } }, execute: async ({ location }) => { return `72°F sunny in ${location}`; }, }, }, }); ``` ### Per-Call Credential Override ```typescript const result = await ai.generate({ provider: "xai", input: { text: "Hello" }, credentials: { xai: { apiKey: "sk-user-specific-key" }, }, }); ``` --- ## CLI Usage ### Basic Commands ```bash # Generate with default model (grok-3) pnpm run cli generate "Explain quantum computing" --provider xai # Use an alias pnpm run cli generate "Hello" --provider grok # Use a specific model pnpm run cli generate "Solve this proof" --provider xai --model grok-3 # Vision pnpm run cli generate "Describe this image" --provider xai \ --model grok-2-vision-latest --image ./screenshot.png # Interactive loop pnpm run cli loop --provider xai ``` --- ## Provider Aliases | Alias | Example | | ------ | ----------------- | | `xai` | `--provider xai` | | `grok` | `--provider grok` | --- ## Configuration Reference | Environment Variable | Required | Default | Description | | -------------------- | -------- | --------------------- | ------------------------------- | | `XAI_API_KEY` | Yes | — | xAI API key | | `XAI_MODEL` | No | `grok-3` | Default model to use | | `XAI_BASE_URL` | No | `https://api.x.ai/v1` | Base URL (override for proxies) | --- ## Feature Support Matrix | Feature | grok-3 | grok-3-mini | grok-2-latest | grok-2-vision | grok-beta | | ----------------- | ------ | ----------- | ------------- | ------------- | --------- | | Text generation | Yes | Yes | Yes | Yes | Yes | | Streaming | Yes | Yes | Yes | Yes | Yes | | Tool calling | Yes | Yes | Yes | Yes | Yes | | Structured output | Yes | Yes | Yes | Yes | Yes | | Vision / images | No | No | No | Yes | No | | Embeddings | No | No | No | No | No | --- ## Troubleshooting ### "Invalid xAI API key" The `XAI_API_KEY` is missing or incorrect. ```bash echo $XAI_API_KEY export XAI_API_KEY=sk-... ``` Get or rotate keys at [https://console.x.ai/](https://console.x.ai/). ### "xAI rate limit exceeded" Too many requests in a short window. Implement exponential backoff or reduce concurrency. Free-tier limits are tight; consider upgrading at [https://console.x.ai/](https://console.x.ai/). ### "xAI account has insufficient quota" Top up at [https://console.x.ai/](https://console.x.ai/). ### "Model not found" Use one of the documented model IDs above. Custom fine-tunes are not exposed through the public API at this time. --- ## See Also - [Adding a new LLM provider](/docs/provider-integration/15-adding-llm-provider) — internal reference for the integration pattern this provider follows - [DeepSeek Provider](/docs/getting-started/providers/deepseek) — sibling OpenAI-compat provider with reasoning models - [Groq Provider](/docs/getting-started/providers/groq) — sibling OpenAI-compat provider with sub-100ms inference --- **Need Help?** Open a [GitHub Discussion](https://github.com/juspay/neurolink/discussions) or [issue](https://github.com/juspay/neurolink/issues). --- ## XOR Provider Guide # XOR Provider Guide **A provider of `decide`** — the same typed `boolean` / `choice` / `score` answers as [TypeSafe's Jev](/docs/getting-started/providers/typesafe) and [Laya](/docs/getting-started/providers/laya), plus `value` extraction and a `choice` with an `unknown` option, from Juspay's open-weights model, which also reads an image and an audio clip. It emits no text at all. ------------------ | --------------------------------------------------------------------------------------------- | | Inference type | `decide` only | | Model | `xor-latest` by default, `xor-omni` for media and `value`; `XOR_MODEL` sets your proxy's name | | Question types | `boolean`, `choice` (optionally with `unknown`), `score` and `value` | | Media | one image and one audio clip (first 30 seconds heard); no video; body at most 25 MB | | Input window | 120,000 estimated tokens of state on `xor-latest`, 28,000 on `xor-omni` | | Questions per request | 128 (`tryDecide()` splits more); a `choice` takes 2 to 64 options, a `score` 2 to 10 levels | | Endpoint | `/v1/decisions`; the base URL is required, with no default | | Precedence | used automatically only when TypeSafe and Laya are not configured | --- ## Quick Start ### 1. Get an endpoint and a key Run a deployment of XOR (see [huggingface.co/juspay/xor](https://huggingface.co/juspay/xor)), or use a LiteLLM proxy with a route to one. NeuroLink posts to `/v1/decisions`. The base URL is the origin of the deployment or of the proxy route, and a trailing `/v1` is accepted. It must be `https://`; `http://` is accepted only for `localhost`, `127.0.0.1` and `[::1]`, because every request carries the key and the state. A deployment reachable only over plain http inside a network needs an `https://` front, or a port-forward to `localhost`. On a LiteLLM proxy the key's team must be allowed the model you ask for (`xor-latest` by default, `xor-omni` for media); otherwise the proxy answers 403 `team_model_access_denied`. A proxy may serve XOR under a name of its own: set `XOR_MODEL` to that name. ### 2. Configure Both the base URL and the key are required. Set them in the environment: ```bash export XOR_BASE_URL=https://your-proxy.example.com # NeuroLink calls /v1/decisions export XOR_API_KEY=sk-... # the key your endpoint accepts export XOR_MODEL=xor-latest # optional; the default ``` or in the config passed to the SDK, exactly as for any other provider. Values passed per call override the constructor's, which override the environment: ```typescript const neurolink = new NeuroLink({ credentials: { xor: { baseURL: "https://your-proxy.example.com", apiKey: process.env.MY_XOR_KEY, }, }, }); ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.decide({ provider: "xor", state: "We were billed twice for March. Please refund it today.", questions: { team: { type: "choice", instructions: "Which team should handle this?", criteria: { billing: "Payments and refunds", technical: "Bugs", sales: "Pricing", }, }, urgent: { type: "boolean", instructions: "Is this urgent?" }, }, }); const team = readDecisionChoice(result.answers, "team"); ``` ### From the CLI The CLI reads the same environment variables: ```bash neurolink decide "We were billed twice for March." --provider xor \ --questions '{"urgent":{"type":"boolean","instructions":"Is this urgent?"}}' ``` --- ## Extracting values A `value` question pulls one typed field out of the state. `dtype` is `string` (the default), `int` or `float`, and an optional `pattern` is a regular expression the extracted text must match. A field the state does not hold comes back as `value: null` with `unknown: true`: ```typescript const result = await new NeuroLink().decide({ provider: "xor", model: "xor-omni", state: "Invoice INV-2024-0892 for 18,275.50 rupees, due on 15 September.", questions: { amount: { type: "value", dtype: "float", instructions: "Invoice amount?" }, ref: { type: "value", instructions: "Invoice reference?", pattern: "INV-[0-9]{4}-[0-9]{4}", }, phone: { type: "value", instructions: "Customer phone number?" }, }, }); readDecisionValue(result.answers, "amount"); // { value: 18275.5, confidence: 0.99, unknown: false } readDecisionValue(result.answers, "phone"); // { value: null, confidence: 0.82, unknown: true } ``` `xor-omni` answers `value`. When nobody chose a model — the call names none and `XOR_MODEL` is unset — a request with a `value` question goes to `xor-omni` directly and is checked against its 28,000-token window, since `xor-latest` cannot answer it (a LiteLLM gateway would hand it to `xor-omni` behind your back, past a window NeuroLink never checked). A model you name is always the one sent: asked of `xor-latest` explicitly, a gateway with that fallback still answers it, and a deployment without one refuses it with a 422 that arrives as `invalid_request`. Every other decision provider refuses a `value` question before any request. A `choice` with `unknown: true` adds an option named `unknown`, picked when none of the criteria fits; the answer then carries `unknown: true`. The 64-option cap counts it, and no option may itself be named `unknown`. --- ## Images, audio and video XOR reads **one image** and **one audio clip** alongside the `state`, through the `xor-omni` model. A request carrying either goes there by itself when nobody chose a model, as a `value` question does; name it (`model: "xor-omni"`, or `--model xor-omni` on the CLI) if `XOR_MODEL` points elsewhere. It does **not** read video: the gateway drops a video and the model answers without it (a solid red clip was answered exactly as garbage bytes were), so NeuroLink refuses one before any request rather than return a blind answer. TypeSafe, Laya, [SubQ](/docs/getting-started/providers/subq) and [ScaleDown](/docs/getting-started/providers/scaledown) do not read media, and [Perplexity](/docs/getting-started/providers/perplexity-decider), [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef) and [OpenAI Decisions](/docs/getting-started/providers/openai-decisions) read images only. ```typescript const neurolink = new NeuroLink(); // One image: a file path, a Buffer or a data: URL const photo = await neurolink.decide({ provider: "xor", model: "xor-omni", state: "A product photo from a listing.", images: [await readFile("./front.jpg")], questions: { color: { type: "choice", instructions: "What color is the product?", criteria: { red: "Mostly red", blue: "Mostly blue" }, }, }, }); const color = readDecisionChoice(photo.answers, "color"); console.log(photo.mediaBytes); // encoded size of the media sent // An audio clip; the state may be empty const call = await neurolink.decide({ provider: "xor", model: "xor-omni", state: "", audio: "./call.wav", questions: { language: { type: "choice", instructions: "Which language is spoken?", criteria: { english: "English", hindi: "Hindi" }, }, }, }); ``` From the CLI, pass `--image ` or `--audio `; with `--audio` the state may be left out: ```bash neurolink decide --provider xor --model xor-omni --audio ./call.wav \ --questions '{"language":{"type":"choice","instructions":"Which language is spoken?","criteria":{"english":"English","hindi":"Hindi"}}}' ``` The rules: - **One image and one audio clip** per request, in `images` and `audio`; a second image is refused before any request. - **Each is a Buffer, a local file path or a `data:` URL.** An `http(s)` URL is refused: NeuroLink does not fetch media for you. - **The type comes from the bytes, not the file extension**: PNG, JPEG, WebP and GIF images, and WAV, FLAC, Ogg (Vorbis or Opus) and MP3 audio, each of which was heard with speech in testing (English identified at 0.9999). An image goes to XOR as a `data:` URL and a clip as `{ data, format }`. An image costs about 600 input tokens whatever its resolution. - **The model hears the first 30 seconds of a clip**, at about 25 input tokens a second, and drops the rest without a word. A WAV, FLAC or Ogg (Opus or Vorbis) clip that runs longer is refused before any request, its length read from the file; an MP3's length is not read, so only its first 30 seconds count. **AAC/M4A is refused**: it was measured decoding to nothing while the request was still answered. A WAV without a complete `fmt` and `data` chunk is refused as well. - **The whole request body may be at most 25 MB** (the server's own cap is 24 MiB). The limit applies to the encoded body, so the base64 form counts. A file over the limit is refused from its size, before it is read. - **What can be checked locally is refused before any request**, as a non-retryable `invalid_request`: a missing file, a directory, an empty Buffer or file, bytes that are not a recognised image or clip, a remote URL or any other URL scheme, more than one image, a video, a clip that is too long, or a body over 25 MB. An image or clip with the right signature that the model cannot decode is sent, and the server's refusal (a 502 wrapping the backend's 400) comes back as `invalid_request`, not retried. - **The result carries `mediaBytes`**, the encoded size of the media sent. The `decide` spans carry `decision.images.count`, `decision.audio.count` and `decision.media.bytes`, and never any base64. --- ## When NeuroLink uses it Every built-in consumer of `decide` — model routing, relevance-driven compaction, tool routing and RAG planning — asks for the default decision provider. That is the first one that is configured, in the environment or in the `credentials` passed to the SDK, in the order TypeSafe, Laya, XOR, [SubQ](/docs/getting-started/providers/subq), [Perplexity](/docs/getting-started/providers/perplexity-decider), [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef), [OpenAI Decisions](/docs/getting-started/providers/openai-decisions), then [ScaleDown](/docs/getting-started/providers/scaledown). TypeSafe counts with either of its keys, `TYPESAFE_API_KEY` or `AI_GATEWAY_API_KEY`. Laya and XOR each count only with both their key and their base URL. SubQ counts with its key alone. Perplexity counts with its key alone, which is shared with Perplexity's text provider. Cloudflare Clef counts only with both `CLOUDFLARE_API_KEY` and `CLOUDFLARE_ACCOUNT_ID`, the same two variables the Workers AI text provider reads. OpenAI Decisions counts with its key alone, `OPENAI_API_KEY`, which the OpenAI chat provider reads too. ScaleDown counts with its key alone, `SCALEDOWN_API_KEY`, which no other provider reads. A caller can always name XOR with `provider: "xor"`. So: - **A TypeSafe key, or Laya's key and base URL, plus XOR's key and base URL:** built-in features use TypeSafe or Laya, in that order; XOR runs only where a caller asks for `provider: "xor"`. - **XOR's key and base URL, plus `SUBQ_API_KEY`:** built-in features use XOR; SubQ runs only where a caller asks for `provider: "subq"`. - **XOR's key and base URL, plus `SCALEDOWN_API_KEY`:** built-in features use XOR; ScaleDown runs only where a caller asks for `provider: "scaledown"`. - **XOR's key and base URL, plus a Perplexity key:** built-in features use XOR; Perplexity runs only where a caller asks for `provider: "perplexity-decider"`. - **XOR's key and base URL, plus `CLOUDFLARE_API_KEY` and `CLOUDFLARE_ACCOUNT_ID`:** built-in features use XOR; Cloudflare Clef runs only where a caller asks for `provider: "cloudflare-clef"`. - **Only XOR's key and base URL:** built-in features use XOR. - **An XOR key with no base URL:** XOR is not configured. Built-in features ignore it, and `provider: "xor"` fails with `XOR requires a base URL`. - **None of TypeSafe, Laya, XOR, SubQ, Perplexity, Cloudflare Clef, OpenAI Decisions or ScaleDown:** everything behaves exactly as it did without a decision model. --- ## Limits The figures below were measured through a LiteLLM gateway in October 2026. **Each model has its own window.** `xor-latest` read a needle at the end of 120,076 input tokens and refused 200,076 as longer than its 131,072-token context; `xor-omni` refuses past 32,768. NeuroLink allows 120,000 estimated tokens of state on `xor-latest` and 28,000 on `xor-omni` (and on any other model name), leaving room for the questions, an image and a clip, and refuses more before any network call, with `max_tokens_exceeded`. The size is an estimate, not XOR's tokenizer: about four characters per token for ASCII text, and one token per character for other scripts. It over-counts English prose, and under-counts dense JSON and digits, so a dense state estimated under the limit can still be longer than the server's context. A state near the limit can therefore still be refused by the server as too long. A 413, or a 5xx other than 503 whose message says the context was too long, arrives as `max_tokens_exceeded` and is not retried; every other reply is classified as in the Errors table below. Built-in consumers treat a refusal as "carry on as before". **A proxy may cap parallel requests.** On that route the key allowed 5 at a time. After a burst of rejected requests (403 and 422 replies), every request was answered 429 for about half an hour. That order was observed; the rejected requests were not confirmed as the cause. NeuroLink retries a 429 once. **128 questions per request.** The gateway refuses more, so `decide()` refuses a longer map before any request, and `tryDecide()` (what every built-in consumer uses) splits it into batches of 128 and joins the answers. A `choice` takes 2 to 64 options, counting `unknown` (64 plus `unknown` crashed the server with a 500), and a `score` 2 to 10 levels (the gateway refuses 11); past either cap the request is refused before any request, as `invalid_request`. Score levels must be strings, objects or lists: numbers are refused by the gateway. A level that is not a string comes back in the answer's `legend` as its JSON text. **The timeout grows with the state.** 5 seconds, plus 150 ms for every full 1,000 estimated tokens of state, because a 120,000-token state took about 18 seconds to answer. Override it per call with `timeoutMs`, or with `--timeout` on the CLI. --- ## Errors | Reply | Kind | Retried | | ------------------------------------------------------------ | --------------------------------------------------------- | --------- | | 401 | `authentication` — the provider instance stops retrying | no | | 403 / 402 | `invalid_request` — fixable; the instance is not disabled | no | | 413, or a 5xx other than 503 saying the context was exceeded | `max_tokens_exceeded` | no | | a 5xx wrapping the backend's 4xx (`backend 400: …`) | `invalid_request` — an image or clip it could not open | no | | any other 4xx (for example 422, 404) | `invalid_request` | no | | 429 | `rate_limit` | yes, once | | 503 | `overloaded` | yes, once | | other 5xx | `server` | yes, once | | state over the window (local) | `max_tokens_exceeded`, with no network call | no | | unusable media, or a question it cannot answer (local) | `invalid_request`, with no network call | no | | no base URL configured (local) | `invalid_request`, with no network call | no | A 403 or 402 is deliberately not `authentication`. On a LiteLLM proxy a 403 means the key's team does not allow the model you asked for (`team_model_access_denied`), and a 402 means the team has no budget. An admin can fix either, so the provider instance keeps working once it is fixed and is not disabled. A 401 does disable the instance: it stops sending requests after the first rejection, because a bad key does not fix itself. "Unusable media" covers a missing file, a directory, an empty Buffer or file, something that is not an image or a recognised clip, a remote URL, more than one image, any video, a clip over 30 seconds or in AAC/M4A, and a request body over 25 MB. "A question it cannot answer" is a choice or score past its cap, or a choice naming an option `unknown` beside `unknown: true`. A proxy's error text can echo the key and the request. Before a message reaches a log or an error, the provider removes the configured key, anything shaped like a LiteLLM key, long hex runs, embedded `data:` URLs, the request content pydantic quotes back (`input_value=…`) and LiteLLM's table of fallback model groups. --- ## Troubleshooting - **`XOR requires a base URL`** — set `XOR_BASE_URL`, or pass `credentials.xor.baseURL`. There is no default endpoint. - **`The XOR base URL must not carry credentials…`** — the base URL has a user name, a password, a query string or a fragment. Set it to the origin only, for example `https://your-proxy.example.com`, and give the key through `XOR_API_KEY` or `credentials.xor.apiKey`. - **`The XOR base URL must start with https:// or http://`** — the value has no scheme (for example `xor.internal:8080`) or uses another scheme. Add `https://`, or `http://` for a server on this machine. - **`The XOR base URL must use https:// unless it points at this machine`** — the value is an `http://` URL whose host is not `localhost`, `127.0.0.1` or `[::1]`. A plain-http request would send the key and the state unencrypted. Put an `https://` front on the deployment, or reach it through a port-forward to `localhost`. - **`XOR answered with a redirect`** — the endpoint replied 301, 302, 307 or 308. The provider does not follow it and does not retry. Set the base URL to the address the redirect leads to. - **`The XOR base URL is not a valid absolute URL`** — the value cannot be parsed as a URL. Set it to an absolute origin. - **`XOR requires an API key`** — set `XOR_API_KEY`, or pass `credentials.xor.apiKey`. - **A 401** — the endpoint rejected the key. The provider instance stops retrying after a rejection, so fix the key and construct a new one. - **A 403 with `team_model_access_denied`** — the LiteLLM proxy's team for this key does not allow the model you asked for (`XOR_MODEL`, or `xor-latest` by default; `xor-omni` for media). Add the model to the team; the instance works again without a restart. - **`max_tokens_exceeded`** — the state is over the model's window (120,000 estimated tokens on `xor-latest`, 28,000 on `xor-omni`), the request has more than 128 questions, or the state, the questions and the media together are more than the model's context. Shorten the state, or use `tryDecide()` to split the questions. - **`XOR cannot answer question "…"`** — a choice with more than 64 options (counting `unknown`), a score with more than 10 levels, or a choice naming an option `unknown` beside `unknown: true`. - **`XOR does not accept video`** — see [Images, audio and video](#images-audio-and-video). Send frames as images instead, one per request. - **Images seem to be ignored** — a deployment started without `OPENJEV_IMAGES=1` answers 200 and silently ignores images, and NeuroLink cannot detect that. Send a red image and a blue image and check that the two answers differ. - **Built-in routing never uses XOR** — a TypeSafe key, or Laya's key and base URL, is also set and takes precedence, or XOR has no base URL. --- ## See also - [TypeSafe (Jev) Provider Guide](/docs/getting-started/providers/typesafe) - [Laya Provider Guide](/docs/getting-started/providers/laya) - [Perplexity Decisions Provider Guide](/docs/getting-started/providers/perplexity-decider) - [Cloudflare Clef Provider Guide](/docs/getting-started/providers/cloudflare-clef) - [SubQ Provider Guide](/docs/getting-started/providers/subq) - [OpenAI Decisions Provider Guide](/docs/getting-started/providers/openai-decisions) - [ScaleDown Provider Guide](/docs/getting-started/providers/scaledown) - [The `decide` inference type](/docs/features/decide-inference-type) - [XOR on Hugging Face](https://huggingface.co/juspay/xor) --- ## Z.AI Provider Guide # Z.AI Provider Guide Z.AI is a **Tier-2 catalog provider**: OpenAI-wire-compatible, so its entire integration is one JSON file (`src/lib/providers/catalog/z-ai.json`) rather than hand-written code. That file is the source of truth for everything on this page. > **Verification status:** this entry is **docs-verified only, not yet > live-verified.** The vendor's `GET https://api.z.ai/api/paas/v4/models` needs > a key (it answers HTTP 401 without one), so the model ids come from Z.AI's > public docs and the roster has not been checked. No account was created and no > API key was used to build this entry. `evidence.liveMatrix` is `null` until > someone runs the live capability matrix with a real key (see > [Verification status](#verification-status) below). ## Quick Start ### 1. Get an API key 1. Visit: https://z.ai/manage-apikey/apikey-list — the [Quick Start](https://docs.z.ai/guides/overview/quick-start.md) says to access the Z.AI Open Platform (https://z.ai/model-api) and "Register or Login.", then to "Create an API Key" in the API Keys management page and "Copy your API Key for use." 2. Authentication is HTTP Bearer: the Introduction page (https://docs.z.ai/api-reference/introduction.md) shows the header Authorization: Bearer ZAI_API_KEY 3. Billing as the vendor states it: the Quick Start says to open the Billing Page (https://z.ai/manage-apikey/billing) "to top up if needed"; the pricing page (https://docs.z.ai/guides/overview/pricing.md) lists per-1M-token prices and reads "Free" for GLM-4.7-Flash, GLM-4.5-Flash and GLM-4.6V-Flash; the Errors page (https://docs.z.ai/api-reference/api-code.md) lists error 1113 as "Insufficient balance or no resource package. Please recharge." 4. Set `Z_AI_API_KEY` in your .env file ### 2. Configure ```bash export Z_AI_API_KEY=your-api-key export Z_AI_MODEL=glm-5.3 # optional — overrides the default model export Z_AI_BASE_URL=https://api.z.ai/api/paas/v4 # optional — proxy or self-hosted gateway ``` ### 3. Use it ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain context windows in one paragraph." }, provider: "z-ai", model: "glm-5.3", }); console.log(result.content); ``` ```bash # CLI npx @juspay/neurolink generate "Hello" --provider z-ai ``` Per-request credentials use the same shape as the other catalog providers: ```typescript await neurolink.generate({ input: { text: "Hello" }, provider: "z-ai", credentials: { zAi: { apiKey: process.env.Z_AI_API_KEY } }, }); ``` --- ## Billing The [Quick Start](https://docs.z.ai/guides/overview/quick-start.md) says to open the Billing Page (https://z.ai/manage-apikey/billing) "to top up if needed". The [pricing page](https://docs.z.ai/guides/overview/pricing.md) lists per-1M-token prices, and its Text Models and Vision Models tables read "Free" in the Input, Cached Input, Cached Input Storage and Output cells for GLM-4.7-Flash, GLM-4.5-Flash and GLM-4.6V-Flash. The [Errors page](https://docs.z.ai/api-reference/api-code.md) lists error 1113 (HTTP 429) as "Insufficient balance or no resource package. Please recharge." The catalog schema has no unknown billing value, so `billingPolicy` holds `free-tier`. It is a schema value, not a vendor statement of signup terms. --- ## Models | Model | Context | Max output | Vision | $/M in · out (cached) | Notes | | ---------------- | ------- | ---------- | ------ | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------- | | `glm-5.3` ⭐ | 1M | 128K | no | $1.4 / $4.4 ($0.26) | NeuroLink default. The GLM-5.3 page says "Z.ai's latest flagship model" and "text-only inputs". | | `glm-5.3-flash` | 1M | 128K | yes | $0.15 / $0.50 ($0.03) | NeuroLink vision model. Input Modality "Video / Image / Text / File". | | `glm-5.3-flashx` | 1M | 128K | yes | $0.37 / $1.25 ($0.075) | Input Modality "Video / Image / Text / File"; the page states an inference speed of 200 tokens/s for GLM-5.3-FlashX. | | `glm-5.2` | 1M | 128K | no | $1.4 / $4.4 ($0.26) | Positioning "Flagship Foundation Model"; Input Modalities "Text". | | `glm-5.1` | 200K | 128K | no | $1.4 / $4.4 ($0.26) | Positioning "Flagship Foundation Model"; Input Modalities "Text". | | `glm-5` | 200K | 128K | no | $1 / $3.2 ($0.2) | Positioning "Foundation Model"; Input Modalities "Text". | | `glm-4.7` | 200K | 128K | no | $0.6 / $2.2 ($0.11) | Input Modalities "Text". | | `glm-4.6` | 200K | 128K | no | $0.6 / $2.2 ($0.11) | Input Modalities "Text". | | `glm-4.5` | 128K | 96K | no | $0.6 / $2.2 ($0.11) | Input Modalities "Text"; the page says "GLM-4.5 has a total parameter count of 355B with 32B active parameters per forward pass". | | `glm-4.5-air` | 128K | 96K | no | $0.2 / $1.1 ($0.03) | Input Modalities "Text"; the page describes GLM-4.5-Air as having "106B total parameters and 12B active parameters". | | `glm-4.7-flashx` | 200K | 128K | no | $0.07 / $0.4 ($0.01) | Positioning "Lightweight, High-Speed,and Affordable"; Input Modalities "Text". | | `glm-4.7-flash` | 200K | 128K | no | Free (recorded as 0) | Positioning "Lightweight, Completely Free"; Input Modalities "Text". | Context, max output, positioning and modality values come from the model pages on docs.z.ai (`/guides/llm/glm-5.3.md`, `glm-5.2.md`, `glm-5.1.md`, `glm-5.md`, `glm-4.7.md`, `glm-4.6.md`, `glm-4.5.md` and `/guides/vlm/glm-5.3-flash.md`), retrieved 2026-09-29. Prices come from the [pricing page](https://docs.z.ai/guides/overview/pricing.md), retrieved 2026-09-29, per 1M tokens: the page prints display names such as GLM-5.3, and each row is matched to the model id of the same name. Model ids are copied from the [Chat Completion reference](https://docs.z.ai/api-reference/llm/chat-completion.md) enums. The catalog records the decimal forms of the labels the vendor prints (1M, 200K, 128K, 96K). Each model's `status` in the JSON is `production`, a placeholder for a value the catalog schema requires; it is not a vendor statement. `models.defaultContextWindow` (128000) and `models.defaultMaxOutputTokens` (16000) apply to model ids outside the catalog. They are placeholders the vendor does not publish: 128000 equals the Context Length label on the GLM-4.5 page and 16000 equals the maximum-output figure the Chat Completion reference gives for `GLM-4-32B-0414-128K`. **Fallback order** when the default is unavailable: `glm-5.2` → `glm-5.1` → `glm-5` → `glm-4.7` → `glm-4.6` → `glm-4.5` → `glm-4.5-air` → `glm-4.7-flashx` → `glm-4.7-flash` → `glm-5.3-flash` → `glm-5.3-flashx`. The runtime fallback model name the loader derives (`fallbacks[1]`) is `glm-5.1`. --- ## Verification status Tier-2 onboarding requires evidence before a provider is accepted, and `pnpm run verify:provider-onboarding` gates it in CI. This is what the catalog currently records for Z.AI — **docs-verified only, not live-verified**: | Probe | Result | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Roster | unauthenticated `GET /api/paas/v4/models` answers HTTP 401 without a key (2026-09-29), so model ids are taken from the Chat Completion reference; roster not verified | | Auth-failure shape | unauthenticated `GET /models` and `GET /chat/completions` each answered HTTP 401 with `{"error":{"code":"1001","message":"Authentication parameter not received in Header, unable to authenticate"}}` (2026-09-29), matching the error shape on the [Errors page](https://docs.z.ai/api-reference/api-code.md); `errorRules` carry the 401, 1113, 1211 and 429 rows | | Billing | public pages quoted under [Billing](#billing); no signup performed | | Tools / structured output | documented on the Function Calling, Thinking Mode and Structured Output pages; neither was exercised live, no POST request was sent, and no combined tools+schema request was sent, so `structuredOutputWithTools` stays `false`. The request fields NeuroLink's chat-completions client can add have not been exercised against Z.AI | | Live capability sweep | **not run.** `evidence.liveMatrix` is `null`. Before treating this provider as production-ready, run `npx tsx test/continuous-test-suite-provider-matrix.ts --provider=z-ai` with a real key and record the result. | Do not treat this entry as equivalent to a live-verified Tier-2 provider (e.g. FriendliAI, Novita AI) until that live matrix has been run and `evidence.liveMatrix` is filled in. --- ## Troubleshooting The rows below are the messages the vendor's [Errors page](https://docs.z.ai/api-reference/api-code.md) lists; NeuroLink's `errorRules` map them to error classes. | Symptom | What the Errors page says | | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | HTTP 401, `error.code` 1001 | "Authentication parameter not received in Header, unable to authenticate" | | HTTP 401, `error.code` 1000/1003/1005 | "Authentication Failed", "Authentication Token expired, please regenerate/obtain", "Need Two-Factor Authentication" | | HTTP 429, `error.code` 1113 | "Insufficient balance or no resource package. Please recharge." | | HTTP 400, `error.code` 1211 | "Unknown Model, please check the model code." | | HTTP 429, `error.code` 1302 | "Rate limit reached for requests" | | HTTP 429, `error.code` 1305 | "The service may be temporarily overloaded, please try again later" | --- ## See also - [Provider setup overview](/docs/getting-started/provider-setup) - [Providers index](/docs/getting-started/providers/) - [Tier-2 onboarding](/docs/provider-integration/tiers/tier-2-catalog-entry) — how this provider's JSON becomes a working integration - [Provider feature compatibility](/docs/reference/provider-feature-compatibility) --- # SDK Reference ## SDK Reference # SDK Reference The NeuroLink SDK provides a TypeScript-first programmatic interface for integrating AI capabilities into your applications. ## Overview The SDK is designed for: - **Web applications** (React, Vue, Svelte, Angular) - **Backend services** (Node.js, Express, Fastify) - **Serverless functions** (Vercel, Netlify, AWS Lambda) - **Desktop applications** (Electron, Tauri) ## Quick Start ```typescript const neurolink = new NeuroLink(); // Generate text const result = await neurolink.generate({ input: { text: "Write a haiku about programming" }, provider: "google-ai", }); console.log(result.content); ``` ```typescript // Auto-selects best available provider const provider = createBestAIProvider(); const result = await provider.generate({ input: { text: "Explain quantum computing" }, maxTokens: 500, temperature: 0.7, }); ``` ```typescript const stream = await neurolink.stream({ input: { text: "Tell me a long story" }, provider: "anthropic", }); for await (const chunk of stream.stream) { process.stdout.write(chunk.content); } ``` ## Documentation Sections - **[API Reference](/docs/sdk/api-reference)** — Complete TypeScript API documentation with interfaces, types, and method signatures. - **[Framework Integration](/docs/sdk/framework-integration)** — Integration guides for Next.js, SvelteKit, React, Vue, and other popular frameworks. - **[Custom Tools](/docs/sdk/custom-tools)** — How to create and register custom tools for enhanced AI capabilities. ## Core Architecture The SDK uses a **Factory Pattern** architecture that provides: - **Unified Interface**: Providers implement the same `AIProvider` interface - **Type Safety**: Full TypeScript support with IntelliSense - **Automatic Fallback**: Seamless provider switching on failures - **Built-in Tools**: 6 core tools available across supported providers ```typescript type AIProvider = { generate(options: TextGenerationOptions): Promise; stream(options: StreamOptions): Promise; supportsTools(): boolean; }; ``` ## Configuration The SDK automatically detects configuration from: ```typescript // Environment variables process.env.OPENAI_API_KEY; process.env.GOOGLE_AI_API_KEY; process.env.ANTHROPIC_API_KEY; // ... and more // Programmatic configuration const neurolink = new NeuroLink({ conversationMemory: { enabled: true }, enableOrchestration: true, observability: { langfuse: { enabled: true } }, }); ``` ## Advanced Features ### Auto Provider Selection {#auto-selection} NeuroLink automatically selects the best available AI provider based on your configuration: ```typescript // Automatically selects best available provider const provider = createBestAIProvider(); const result = await provider.generate({ input: { text: "Explain quantum computing" }, maxTokens: 500, temperature: 0.7, }); ``` **Selection Priority:** 1. OpenAI (most reliable) 2. Anthropic (high quality) 3. Google AI Studio (free tier) 4. Other configured providers **Custom Priority:** ```typescript // Create with fallback const { primary, fallback } = await AIProviderFactory.createProviderWithFallback( "bedrock", // Prefer Bedrock "openai", // Fall back to OpenAI ); ``` **Learn more:** [Provider Orchestration Guide](/docs/features/provider-orchestration) ### Analytics & Evaluation ```typescript const result = await neurolink.generate({ input: { text: "Generate a business proposal" }, enableAnalytics: true, // Track usage and costs enableEvaluation: true, // AI quality scoring }); console.log(result.analytics); // Usage data console.log(result.evaluation); // Quality scores ``` ### Custom Tools ```typescript // Register a single tool neurolink.registerTool("weatherLookup", { description: "Get current weather for a city", parameters: z.object({ city: z.string(), units: z.enum(["celsius", "fahrenheit"]).optional(), }), execute: async ({ city, units = "celsius" }) => { // Your implementation return { city, temperature: 22, units, condition: "sunny" }; }, }); // Register multiple tools - Object format neurolink.registerTools({ stockPrice: { description: "Get stock price", execute: async () => ({ price: 150.25 }), }, calculator: { description: "Calculate math", execute: async () => ({ result: 42 }), }, }); // Register multiple tools - Array format (Lighthouse compatible) neurolink.registerTools([ { name: "analytics", tool: { description: "Get analytics data", parameters: z.object({ merchantId: z.string(), dateRange: z.string().optional(), }), execute: async ({ merchantId, dateRange }) => { return { data: "analytics result" }; }, }, }, { name: "processor", tool: { description: "Process payments", execute: async () => ({ status: "processed" }), }, }, ]); ``` ### Context Integration ```typescript const result = await neurolink.generate({ input: { text: "Create a summary" }, context: { userId: "123", project: "Q1-report", department: "sales", }, }); ``` ## Framework Examples ```typescript // app/api/ai/route.ts export async function POST(request: Request) { const { prompt } = await request.json(); const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: prompt }, timeout: "2m", }); return Response.json({ text: result.content }); } ``` ```typescript // src/routes/api/ai/+server.ts export const POST: RequestHandler = async ({ request }) => { const { message } = await request.json(); const provider = createBestAIProvider(); const result = await provider.stream({ input: { text: message }, timeout: "2m", }); // Manually create ReadableStream from AsyncIterable const readable = new ReadableStream({ async start(controller) { try { for await (const chunk of result.stream) { if (chunk && typeof chunk === "object" && "content" in chunk) { controller.enqueue(new TextEncoder().encode(chunk.content)); } } controller.close(); } catch (error) { controller.error(error); } }, }); return new Response(readable, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", }, }); }; ``` ```typescript const app = express(); const neurolink = new NeuroLink(); app.post("/api/generate", async (req, res) => { const result = await neurolink.generate({ input: { text: req.body.prompt }, }); res.json({ content: result.content }); }); ``` ## Related Resources - **[Examples & Tutorials](/docs/)** - Practical implementation examples - **[Advanced Features](/docs/)** - MCP integration, analytics, streaming - **[Troubleshooting](/docs/reference/troubleshooting)** - Common issues and solutions --- ## API Reference # API Reference Complete reference for NeuroLink's TypeScript API. ## NeuroLink Class The `NeuroLink` class is the main entry point for all SDK functionality. ### Constructor: `new NeuroLink(config?)` Create a new NeuroLink instance with optional configuration for conversation memory, orchestration, HITL, and observability. ```typescript const neurolink = new NeuroLink(config?: NeurolinkConstructorConfig) ``` **Parameters:** ```typescript type NeurolinkConstructorConfig = { // Conversation Memory conversationMemory?: Partial; // See ConversationMemoryConfig for full options: // enabled: boolean // maxSessions?: number // enableSummarization?: boolean // tokenThreshold?: number // summarizationProvider?: string // summarizationModel?: string // redisConfig?: RedisStorageConfig // contextCompaction?: { enabled?, threshold?, enablePruning?, ... } // maxTurnsPerSession?: number // @deprecated - use tokenThreshold instead // Provider Orchestration enableOrchestration?: boolean; // Human-in-the-Loop safety features hitl?: HITLConfig; // Custom tool registry (advanced) toolRegistry?: MCPToolRegistry; // Observability (Langfuse; auto-enabled from LANGFUSE_PUBLIC_KEY + LANGFUSE_SECRET_KEY, `langfuse: false` disables) observability?: ObservabilityConfig; }; ``` **Examples:** ```typescript // Basic usage (no configuration) const neurolink = new NeuroLink(); // With Redis conversation memory const neurolinkWithMemory = new NeuroLink({ conversationMemory: { enabled: true, redisConfig: { host: "localhost", port: 6379, ttl: 7 * 24 * 60 * 60, // 7 days }, tokenThreshold: 100000, // Token threshold to trigger summarization }, }); // With HITL safety features const neurolinkWithHITL = new NeuroLink({ hitl: { enabled: true, dangerousActions: ["delete", "remove", "drop"], timeout: 30000, allowArgumentModification: true, }, }); // Complete configuration with all features const neurolinkComplete = new NeuroLink({ conversationMemory: { enabled: true, redisConfig: { host: "localhost", port: 6379 }, enableSummarization: true, }, enableOrchestration: true, hitl: { enabled: true, dangerousActions: ["delete", "remove", "drop"] }, observability: { langfuse: { publicKey: process.env.LANGFUSE_PUBLIC_KEY, secretKey: process.env.LANGFUSE_SECRET_KEY, }, }, }); ``` See also: - [Redis Conversation Export](/docs/features/conversation-history) - [Human-in-the-Loop (HITL)](/docs/features/hitl) - [Provider Orchestration](/docs/features/provider-orchestration) --------------- | ------------------------ | --------------------- | | OpenAI | Full Support | No limitations | | Anthropic | Full Support | No limitations | | Vertex AI (Gemini) | Use `disableTools: true` | Google API limitation | | Google AI Studio | Use `disableTools: true` | Google API limitation | | Vertex AI (Claude) | Full Support | Uses Anthropic models | | Azure OpenAI | Full Support | No limitations | | Bedrock | Full Support | No limitations | --- ### `stream(options)` Generate content with streaming responses. ```typescript async stream(options: StreamOptions): Promise ``` **Parameters:** ```typescript type StreamOptions = { input: { text: string }; output?: { format?: "text" | "structured" | "json"; streaming?: { chunkSize?: number; bufferSize?: number; enableProgress?: boolean; }; }; provider?: string; model?: string; temperature?: number; maxTokens?: number; timeout?: number | string; rag?: RAGConfig; // RAG pipeline config - pass files for automatic chunking and search }; ``` **Returns:** ```typescript type StreamResult = { stream: AsyncIterable; provider?: string; model?: string; // Usage and completion info usage?: TokenUsage; // Token usage statistics (prompt, completion, total) finishReason?: string; // Why generation stopped (e.g., "stop", "length", "tool-calls") // Tool integration toolCalls?: ToolCall[]; // Tool calls made during generation toolResults?: ToolResult[]; // Results from tool executions toolEvents?: AsyncIterable; // Real-time tool event stream toolExecutions?: ToolExecutionSummary[]; // Final summary of all tool executions toolsUsed?: string[]; // Names of tools used during generation // Stream metadata metadata?: { streamId?: string; startTime?: number; totalChunks?: number; estimatedDuration?: number; responseTime?: number; preliminaryTime?: number; // Time to first (preliminary) response fallback?: boolean; totalToolExecutions?: number; toolExecutionTime?: number; hasToolErrors?: boolean; }; // Analytics and evaluation (available after stream completion) analytics?: AnalyticsData | Promise; evaluation?: EvaluationData | Promise; // Workflow engine integration data workflow?: { originalResponse: string; processedResponse: string; ensembleResponses: Array; selectedModel: string; workflowId: string; workflowName: string; }; }; ``` **Example:** ```typescript const neurolink = new NeuroLink(); const result = await neurolink.stream({ input: { text: "Write a story about space exploration" }, provider: "openai", temperature: 0.8, }); for await (const chunk of result.stream) { process.stdout.write(chunk.content); } ``` --- ### Embeddings Generate embeddings directly via the provider's `embed()` and `embedMany()` methods. #### `provider.embed(text, modelName?)` Generate an embedding vector for a single text. ```typescript const provider = await ProviderFactory.createProvider("googleAiStudio"); const embedding = await provider.embed("Hello world"); // embedding: number[] (e.g., 768 dimensions) ``` #### `provider.embedMany(texts, modelName?)` Generate embedding vectors for multiple texts in a single batch. The AI SDK automatically handles chunking for models with batch limits. ```typescript const provider = await ProviderFactory.createProvider("openai"); const embeddings = await provider.embedMany([ "First document", "Second document", "Third document", ]); // embeddings: number[][] (e.g., 3 × 1536 dimensions) ``` **Supported providers and default models:** | Provider | Default Embedding Model | Env Override | | ---------------- | ------------------------------ | --------------------------- | | OpenAI | `text-embedding-3-small` | — | | Google AI Studio | `gemini-embedding-001` | `GOOGLE_AI_EMBEDDING_MODEL` | | Google Vertex | `text-embedding-004` | `VERTEX_EMBEDDING_MODEL` | | Amazon Bedrock | `amazon.titan-embed-text-v2:0` | — | --- ### RAG Integration Pass `rag: { files: [...] }` to `generate()` or `stream()` for automatic RAG pipeline setup: ```typescript const result = await neurolink.generate({ prompt: "What does this document say?", rag: { files: ["./docs/guide.md"], strategy: "markdown", // Optional topK: 5, // Optional }, }); ``` **`RAGConfig` Type:** | Property | Type | Default | Description | | ------------------- | ------------------ | ------------------------- | ----------------------- | | `files` | `string[]` | required | File paths to load | | `strategy` | `ChunkingStrategy` | auto-detected | Chunking strategy | | `chunkSize` | `number` | 1000 | Max chunk size | | `chunkOverlap` | `number` | 200 | Chunk overlap | | `topK` | `number` | 5 | Top results to retrieve | | `toolName` | `string` | `"search_knowledge_base"` | Tool name for AI | | `toolDescription` | `string` | auto-generated | Tool description | | `embeddingProvider` | `string` | generation provider | Embedding provider | | `embeddingModel` | `string` | provider default | Embedding model | **Exports:** ```typescript prepareRAGTool, type RAGConfig, type RAGPreparedTool, } from "@juspay/neurolink"; ``` --- ## MCP Server Management ### `addExternalMCPServer(serverId, config)` Programmatically add external MCP servers at runtime. Supports stdio, SSE, WebSocket, and HTTP transports. ```typescript async addExternalMCPServer( serverId: string, config: MCPServerInfo ): Promise> ``` **Examples:** ```typescript const neurolink = new NeuroLink(); // Add Bitbucket integration (stdio transport) await neurolink.addExternalMCPServer("bitbucket", { command: "npx", args: ["-y", "@nexus2520/bitbucket-mcp-server"], env: { BITBUCKET_USERNAME: "your-username", BITBUCKET_APP_PASSWORD: "your-app-password", }, }); // Add HTTP remote server with full configuration await neurolink.addExternalMCPServer("remote-api", { transport: "http", url: "https://api.example.com/mcp", headers: { Authorization: "Bearer YOUR_TOKEN", "X-Custom-Header": "value", }, httpOptions: { connectionTimeout: 30000, requestTimeout: 60000, idleTimeout: 120000, keepAliveTimeout: 30000, }, retryConfig: { maxAttempts: 3, initialDelay: 1000, maxDelay: 30000, backoffMultiplier: 2, }, rateLimiting: { requestsPerMinute: 60, maxBurst: 10, useTokenBucket: true, }, }); // Add HTTP server with OAuth 2.1 authentication await neurolink.addExternalMCPServer("oauth-api", { transport: "http", url: "https://api.enterprise.com/mcp", auth: { type: "oauth2", oauth: { clientId: "your-client-id", clientSecret: "your-client-secret", authorizationUrl: "https://auth.provider.com/authorize", tokenUrl: "https://auth.provider.com/token", redirectUrl: "http://localhost:8080/callback", scope: "mcp:read mcp:write", usePKCE: true, }, }, }); // Add SSE server await neurolink.addExternalMCPServer("sse-server", { transport: "sse", url: "https://api.example.com/mcp/sse", headers: { Authorization: "Bearer YOUR_TOKEN" }, }); ``` **Use Cases:** - External service integration (Bitbucket, Slack, Jira) - Custom tool development - Dynamic workflow configuration - Enterprise application toolchain management - Remote MCP server connectivity with authentication - OAuth 2.1 protected enterprise APIs --- ### `getMCPStatus()` Get current MCP server status and statistics. ```typescript async getMCPStatus(): Promise ``` **Example:** ```typescript const status = await neurolink.getMCPStatus(); console.log(`Total servers: ${status.totalServers}`); console.log(`Available: ${status.availableServers}`); console.log(`Total tools: ${status.totalTools}`); ``` --- ## Conversation History Management ### Currently Available Methods #### `getConversationHistory(sessionId)` Retrieve the complete conversation history for a specific session. ```typescript async getConversationHistory(sessionId: string): Promise ``` **Parameters:** | Parameter | Type | Description | | ----------- | -------- | -------------------------------------- | | `sessionId` | `string` | The session ID to retrieve history for | **Returns:** ```typescript // Array of ChatMessage objects in chronological order type ChatMessage = { role: "user" | "assistant" | "system"; content: string; }; ``` **Example:** ```typescript const neurolink = new NeuroLink({ conversationMemory: { enabled: true, redisConfig: { host: "localhost", port: 6379 }, // omit for in-memory }, }); // Retrieve conversation history const history = await neurolink.getConversationHistory("session-abc123"); console.log(`Total messages: ${history.length}`); for (const message of history) { console.log(`[${message.role}]: ${message.content.substring(0, 50)}...`); } // Export to JSON file writeFileSync("conversation.json", JSON.stringify(history, null, 2)); ``` --- #### `clearConversationSession(sessionId)` Clear conversation history for a specific session. ```typescript async clearConversationSession(sessionId: string): Promise ``` **Parameters:** | Parameter | Type | Description | | ----------- | -------- | ----------------------- | | `sessionId` | `string` | The session ID to clear | **Returns:** `boolean` - `true` if session was cleared, `false` if session didn't exist. **Example:** ```typescript // Clear a specific session const cleared = await neurolink.clearConversationSession("session-abc123"); if (cleared) { console.log("Session cleared successfully"); } else { console.log("Session not found"); } ``` --- #### `clearAllConversations()` Clear all conversation history across all sessions. ```typescript async clearAllConversations(): Promise ``` **Example:** ```typescript // Clear all conversation history await neurolink.clearAllConversations(); console.log("All conversations cleared"); ``` --- ### Planned Features > **Planned Feature** > > The advanced `exportConversationHistory()` method with filtering, format options, and metadata is planned for a future release. > Currently, use `getConversationHistory(sessionId)` to retrieve conversation data and process it as needed. The following advanced export capabilities are planned: ```typescript // PLANNED - Not yet available type ExportOptions = { sessionId: string; // Session ID to export format?: "json" | "csv"; // Default: 'json' includeMetadata?: boolean; // Default: true startTime?: Date; // Filter: export from this time endTime?: Date; // Filter: export until this time }; type ConversationHistory = { sessionId: string; userId?: string; createdAt: string; updatedAt: string; turns: Array; metadata?: { provider?: string; model?: string; totalTurns: number; toolsUsed?: string[]; }; }; ``` > **Planned Feature** > > The `getActiveSessions()` method to list all active conversation sessions is planned for a future release. **Workaround:** For now, track session IDs in your application when creating conversations: ```typescript // Track sessions manually const activeSessions: string[] = []; // When starting a conversation const sessionId = `session-${Date.now()}`; activeSessions.push(sessionId); // Retrieve history for all tracked sessions for (const sessionId of activeSessions) { const history = await neurolink.getConversationHistory(sessionId); await saveToDatabase(sessionId, history); } ``` --- ## Using Timeouts NeuroLink supports flexible timeout configuration for all AI operations: ```typescript const neurolink = new NeuroLink(); // Numeric milliseconds const result1 = await neurolink.generate({ input: { text: "Write a story" }, provider: "openai", timeout: 30000, // 30 seconds }); // Human-readable formats const result2 = await neurolink.generate({ input: { text: "Complex calculation" }, provider: "openai", timeout: "2m", // 2 minutes }); // Streaming with longer timeout const stream = await neurolink.stream({ input: { text: "Generate long content" }, provider: "openai", timeout: "5m", // 5 minutes for streaming }); ``` **Supported Timeout Formats:** - Milliseconds: `5000`, `30000` - Seconds: `'30s'`, `'1.5s'` - Minutes: `'2m'`, `'0.5m'` - Hours: `'1h'`, `'0.5h'` --- ## thinkingLevel Option The `thinkingLevel` option controls reasoning depth for Gemini 3 models, enabling more thorough analysis for complex tasks. ```typescript const neurolink = new NeuroLink(); // Low thinking - fast responses for simple tasks const quickResult = await neurolink.generate({ input: { text: "What is 2 + 2?" }, provider: "google-ai", model: "gemini-3-pro", thinkingLevel: "low", }); // Medium thinking - balanced reasoning (default behavior) const balancedResult = await neurolink.generate({ input: { text: "Explain the concept of recursion in programming" }, provider: "google-ai", model: "gemini-3-pro", thinkingLevel: "medium", }); // High thinking - deep reasoning for complex problems const deepResult = await neurolink.generate({ input: { text: "Design a distributed caching system for a high-traffic e-commerce platform", }, provider: "google-ai", model: "gemini-3-pro", thinkingLevel: "high", }); console.log(deepResult.content); ``` **thinkingLevel Values:** | Level | Description | Use Case | | --------- | ------------------------------------- | --------------------------------------------- | | `minimal` | No extended reasoning, fastest | Simple lookups, direct answers | | `low` | Minimal reasoning, fast responses | Simple queries, factual lookups | | `medium` | Balanced reasoning depth | General tasks, explanations, code generation | | `high` | Deep reasoning with extended analysis | Complex problems, architecture design, proofs | **Note:** The `thinkingLevel` option is only supported by Gemini 3 models (`gemini-3-flash`, `gemini-3-pro`). When used with other providers or models, it will be ignored. --- ## Usage Examples ### Basic Text Generation ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Write a haiku about coding" }, provider: "openai", model: "gpt-4o", }); console.log(result.content); ``` ### Multimodal with Images ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Describe what you see in this image", images: ["path/to/image.jpg"], // Local path or URL }, provider: "openai", model: "gpt-4o", maxTokens: 500, }); ``` ### Office Document Analysis ```typescript const neurolink = new NeuroLink(); // Analyze Word document (converted to Markdown before it reaches the model) const result = await neurolink.generate({ input: { text: "Summarize this document", files: ["report.docx"], }, provider: "openai", }); // Analyze one sheet of an Excel workbook, rendered as a markdown table const data = await neurolink.generate({ input: { text: "What are the top products by revenue?", files: ["sales-data.xlsx"], }, provider: "openai", officeOptions: { sheetName: "Sales", formatStyle: "markdown" }, }); // Summarize a presentation (slide text, tables, and speaker notes) const deck = await neurolink.generate({ input: { text: "Summarize each slide", files: ["quarterly-review.pptx"], }, provider: "openai", }); // Mixed file types with auto-detection const analysis = await neurolink.generate({ input: { text: "Compare all documents", files: ["report.docx", "data.xlsx", "chart.png", "notes.pdf"], }, provider: "openai", }); ``` ### Provider Fallback with Orchestration ```typescript const neurolink = new NeuroLink({ enableOrchestration: true, // Enables smart model routing via ModelRouter }); // Will automatically fallback if primary provider fails const result = await neurolink.generate({ input: { text: "Complex reasoning task" }, // No provider specified - uses orchestration }); console.log(`Used provider: ${result.provider}`); ``` --- ## Enterprise Configuration Interfaces ### `NeuroLinkConfig` Main configuration interface for enterprise features: ```typescript type NeuroLinkConfig = { providers: ProviderConfig; performance: PerformanceConfig; analytics: AnalyticsConfig; backup: BackupConfig; validation: ValidationConfig; }; ``` ### `ExecutionContext` Rich context interface for all MCP operations: ```typescript type ExecutionContext = { sessionId?: string; userId?: string; aiProvider?: string; permissions?: string[]; cacheOptions?: CacheOptions; fallbackOptions?: FallbackOptions; metadata?: Record; priority?: "low" | "normal" | "high"; timeout?: number; retries?: number; correlationId?: string; requestId?: string; userAgent?: string; clientVersion?: string; environment?: string; }; ``` ### `ToolInfo` Comprehensive tool metadata interface: ```typescript type ToolInfo = { name: string; description?: string; serverId?: string; category?: string; version?: string; parameters?: unknown; capabilities?: string[]; lastUsed?: Date; usageCount?: number; averageExecutionTime?: number; }; ``` ### `ConfigUpdateOptions` Flexible configuration update options: ```typescript type ConfigUpdateOptions = { createBackup?: boolean; validateBeforeUpdate?: boolean; mergeStrategy?: "replace" | "merge" | "deep-merge"; backupRetention?: number; onValidationError?: (errors: ValidationError[]) => void; onBackupCreated?: (backupPath: string) => void; }; ``` ### `McpRegistry` Registry interface with optional methods for maximum flexibility: ```typescript type McpRegistry = { registerServer?( serverId: string, config?: unknown, context?: ExecutionContext, ): Promise; executeTool?( toolName: string, args?: unknown, context?: ExecutionContext, ): Promise; listTools?(context?: ExecutionContext): Promise; getStats?(): Record; unregisterServer?(serverId: string): Promise; getServerInfo?(serverId: string): Promise; }; ``` --- ## Supported Providers and Models ### OpenAI Models ```typescript type OpenAIModel = | "gpt-4o" // Previous generation multimodal model | "gpt-4o-mini" // Default - cost-effective variant | "gpt-4-turbo"; // High-performance model ``` ### Amazon Bedrock Models ```typescript type BedrockModel = | "claude-3-7-sonnet" // Default - Latest Claude model | "claude-3-5-sonnet" // Previous generation | "claude-3-haiku"; // Fast, lightweight model ``` **Note:** Bedrock requires full inference profile ARNs in environment variables. ### Google Vertex AI Models ```typescript type VertexModel = | "gemini-2.5-flash" // Default - Fast, efficient | "claude-sonnet-4@20250514"; // High-quality reasoning ``` ### Google AI Studio Models ```typescript type GoogleAIModel = | "gemini-2.5-pro" // Default - Latest Gemini Pro | "gemini-2.5-flash"; // Fast, efficient responses ``` ### Gemini 3 Models (Preview) Google's latest generation Gemini models with enhanced reasoning capabilities and extended thinking support. ```typescript type Gemini3Model = | "gemini-3-flash-preview" // Fast, efficient with thinking support (default) | "gemini-3-pro-preview"; // Advanced reasoning with maximum thinking depth ``` **Model Variants:** | Model | Best For | Thinking Default | Speed | | ------------------------ | --------------------------- | ---------------- | ------- | | `gemini-3-flash-preview` | Fast tasks, simple queries | `low` | Fastest | | `gemini-3-pro-preview` | Complex reasoning, analysis | `high` | Slower | ### Azure OpenAI Models ```typescript type AzureModel = string; // Deployment-specific models // Common deployments: // - 'gpt-4o' (default) // - 'gpt-4-turbo' // - 'gpt-35-turbo' ``` ### Anthropic Models ```typescript type AnthropicModel = | "claude-3-5-sonnet" | "claude-3-opus" | "claude-3-sonnet" | "claude-3-haiku"; ``` ### Mistral AI Models ```typescript type MistralModel = | "mistral-tiny" | "mistral-small" // Default | "mistral-medium" | "mistral-large"; ``` ### Ollama Models ```typescript type OllamaModel = string; // Any locally installed model // Popular models: // - 'llama2' (default) // - 'codellama' // - 'mistral' // - 'vicuna' ``` ### LiteLLM Models ```typescript type LiteLLMModel = string; // Uses provider/model format // Popular models: // - 'openai/gpt-4o' (default: openai/gpt-4o-mini) // - 'anthropic/claude-3-5-sonnet' // - 'google/gemini-2.0-flash' // - 'mistral/mistral-large' // - 'meta/llama-3.1-70b' // Note: Requires LiteLLM proxy server configuration ``` --- ## Environment Configuration ### Required Environment Variables ```typescript // OpenAI OPENAI_API_KEY: string // Amazon Bedrock AWS_ACCESS_KEY_ID: string AWS_SECRET_ACCESS_KEY: string AWS_REGION?: string // Default: 'us-east-2' AWS_SESSION_TOKEN?: string // For temporary credentials BEDROCK_MODEL?: string // Inference profile ARN // Google Vertex AI (choose one authentication method) GOOGLE_APPLICATION_CREDENTIALS?: string // Method 1: File path GOOGLE_SERVICE_ACCOUNT_KEY?: string // Method 2: JSON string GOOGLE_AUTH_CLIENT_EMAIL?: string // Method 3a: Individual vars GOOGLE_AUTH_PRIVATE_KEY?: string // Method 3b: Individual vars GOOGLE_VERTEX_PROJECT: string // Required for all methods GOOGLE_VERTEX_LOCATION?: string // Default: 'us-east5' // Google AI Studio GOOGLE_AI_API_KEY: string // API key from AI Studio // Anthropic ANTHROPIC_API_KEY?: string // Direct Anthropic API // Azure OpenAI AZURE_OPENAI_API_KEY?: string // Azure OpenAI API key AZURE_OPENAI_ENDPOINT?: string // Azure OpenAI endpoint AZURE_OPENAI_DEPLOYMENT_ID?: string // Deployment ID // Hugging Face HUGGINGFACE_API_KEY: string // HF token from huggingface.co HUGGINGFACE_MODEL?: string // Default: 'Qwen/Qwen2.5-72B-Instruct' // Ollama (Local) OLLAMA_BASE_URL?: string // Default: 'http://localhost:11434' OLLAMA_MODEL?: string // Default: 'llama2' // Mistral AI MISTRAL_API_KEY: string // API key from mistral.ai MISTRAL_MODEL?: string // Default: 'mistral-small' // LiteLLM (100+ Models via Proxy) LITELLM_BASE_URL?: string // Default: 'http://localhost:4000' LITELLM_API_KEY?: string // Default: 'sk-anything' LITELLM_MODEL?: string // Default: 'openai/gpt-4o-mini' ``` ### Optional Configuration Variables ```typescript // Provider preferences DEFAULT_PROVIDER?: 'auto' | 'openai' | 'bedrock' | 'vertex' | 'anthropic' | 'azure' | 'google-ai' | 'huggingface' | 'ollama' | 'mistral' | 'litellm' FALLBACK_PROVIDER?: 'openai' | 'bedrock' | 'vertex' | 'anthropic' | 'azure' | 'google-ai' | 'huggingface' | 'ollama' | 'mistral' | 'litellm' // Feature toggles ENABLE_FALLBACK?: 'true' | 'false' // Debugging NEUROLINK_DEBUG?: 'true' | 'false' LOG_LEVEL?: 'error' | 'warn' | 'info' | 'debug' ``` --- ## Type Definitions ### Core Types ```typescript type ProviderName = | "openai" | "bedrock" | "vertex" | "anthropic" | "azure" | "google-ai" | "huggingface" | "ollama" | "mistral" | "litellm"; type GenerateOptions = { input: { text: string }; provider?: ProviderName | string; model?: string; temperature?: number; // 0.0 to 1.0, default: 0.7 maxTokens?: number; // Default: 1000 systemPrompt?: string; // System message schema?: any; // For structured output timeout?: number | string; // Timeout in ms or human-readable format disableTools?: boolean; // Disable tool usage enableAnalytics?: boolean; // Enable usage analytics enableEvaluation?: boolean; // Enable AI quality scoring context?: Record; // Custom context for analytics thinkingLevel?: "minimal" | "low" | "medium" | "high"; // Gemini 3 models }; type GenerateResult = { content: string; provider: string; model: string; usage?: TokenUsage; responseTime?: number; // Milliseconds analytics?: { provider: string; model: string; tokens: { input: number; output: number; total: number }; cost?: number; responseTime: number; context?: Record; }; evaluation?: { relevanceScore: number; // 1-10 scale accuracyScore: number; // 1-10 scale completenessScore: number; // 1-10 scale overallScore: number; // 1-10 scale alertLevel?: string; // 'none', 'low', 'medium', 'high' reasoning?: string; // AI reasoning for the evaluation }; }; type TokenUsage = { promptTokens: number; completionTokens: number; totalTokens: number; }; ``` ### Office Document Types Office documents (DOCX, PPTX, XLSX) have no input field of their own. They travel in `input.files` like any other file, and NeuroLink turns them into text for the prompt, so they work with every provider: ```typescript /** * File types the detector recognises. Office documents are "docx", "pptx" * and "xlsx". */ type FileType = | "csv" | "image" | "pdf" | "audio" | "video" | "archive" | "text" | "svg" | "docx" | "pptx" | "xlsx" | "unknown"; /** * Options for Office documents, passed as `officeOptions` on generate() * and stream(). Only `sheetName` and `formatStyle` are read, both for XLSX. */ type OfficeProcessorOptions = { /** Restrict the workbook to this sheet; an unknown name lists the sheets that exist */ sheetName?: string; /** How sheets are rendered: tab-separated preview (default), CSV, a markdown table, or row objects */ formatStyle?: "raw" | "csv" | "markdown" | "json"; }; ``` The exported type also declares `format`, `extractTextOnly`, `maxSizeMB`, `includeMetadata`, `processAllSheets`, and `includeSlideNotes`; nothing reads them today. See the [Office Documents guide](/docs/features/office-documents) for what the model receives for each format, including DOCX metrics, PPTX tables and speaker notes, and the placeholder note that replaces content a reader cannot extract (legacy `.doc`/`.xls`/`.ppt`, corrupt, or password-protected files). --- ## Error Handling ### Error Types ```typescript class AIProviderError extends Error { provider: string; originalError?: Error; } class TimeoutError extends AIProviderError { // Thrown when operation exceeds specified timeout timeout: number; // Timeout in milliseconds operation?: string; // Operation that timed out (e.g., 'generate', 'stream') } class ConfigurationError extends AIProviderError { // Thrown when provider configuration is invalid } class AuthenticationError extends AIProviderError { // Thrown when authentication fails } class RateLimitError extends AIProviderError { // Thrown when rate limits are exceeded retryAfter?: number; // Seconds to wait before retrying } class QuotaExceededError extends AIProviderError { // Thrown when usage quotas are exceeded } ``` ### Error Handling Patterns ```typescript AIProviderError, ConfigurationError, AuthenticationError, RateLimitError, TimeoutError, } from "@juspay/neurolink"; const neurolink = new NeuroLink(); try { const result = await neurolink.generate({ input: { text: "Hello" }, provider: "openai", timeout: "30s", }); } catch (error) { if (error instanceof TimeoutError) { console.error(`Operation timed out after ${error.timeout}ms`); console.error(`Provider: ${error.provider}, Operation: ${error.operation}`); } else if (error instanceof ConfigurationError) { console.error("Provider not configured:", error.message); } else if (error instanceof AuthenticationError) { console.error("Authentication failed:", error.message); } else if (error instanceof RateLimitError) { console.error(`Rate limit exceeded. Retry after ${error.retryAfter}s`); } else if (error instanceof AIProviderError) { console.error(`Provider ${error.provider} failed:`, error.message); } else { console.error("Unexpected error:", error); } } ``` --- ## Built-in Tools Every NeuroLink instance automatically includes these tools: ```typescript type BuiltInTools = { getCurrentTime: { description: "Get the current date and time"; parameters: { timezone?: string }; }; readFile: { description: "Read contents of a file"; parameters: { path: string }; }; listDirectory: { description: "List contents of a directory"; parameters: { path: string }; }; calculateMath: { description: "Perform mathematical calculations"; parameters: { expression: string }; }; writeFile: { description: "Write content to a file"; parameters: { path: string; content: string }; }; searchFiles: { description: "Search for files by pattern"; parameters: { pattern: string; path?: string }; }; }; ``` **Example with Tools:** ```typescript const neurolink = new NeuroLink(); // Tools are used automatically when appropriate const result = await neurolink.generate({ input: { text: "What time is it?" }, provider: "openai", }); // Result will use getCurrentTime tool automatically // Disable tools if needed const resultNoTools = await neurolink.generate({ input: { text: "What time is it?" }, provider: "openai", disableTools: true, }); // Result will use training data instead of real-time tools ``` --- ## Provider Tool Support Status | Provider | Tool Support | Notes | | ------------ | ------------ | ---------------------------------------------------- | | OpenAI | Full | All tools work correctly | | Google AI | Full | Excellent tool execution | | Anthropic | Full | Reliable tool usage | | Azure OpenAI | Full | Same as OpenAI | | Mistral | Full | Good tool support | | HuggingFace | Partial | Model sees tools but may describe instead of execute | | Vertex AI | Partial | Tools available but may not execute | | Ollama | Limited | Requires specific models like gemma3n | | Bedrock | Full\* | Requires valid AWS credentials | --- ## Context Compaction Methods for managing conversation context size within model token limits. Requires conversation memory to be enabled. ### `compactSession(sessionId, config?)` Manually trigger the full 5-stage context compaction pipeline for a session. The pipeline stages are: (0) Relevance drop — needs a decision provider, skipped without one, (1) Tool output pruning, (2) File read deduplication, (3) LLM summarization, (4) Sliding window truncation. ```typescript async compactSession( sessionId: string, config?: CompactionConfig ): Promise ``` **Parameters:** | Parameter | Type | Description | | ----------- | ------------------- | ------------------------------------------------------------------ | | `sessionId` | `string` | The session ID to compact | | `config` | `CompactionConfig?` | Optional overrides for summarization provider, model, and behavior | **Returns:** `CompactionResult | null` — `null` if no conversation memory is configured or the session is empty. ```typescript type CompactionResult = { compacted: boolean; // Whether compaction was performed messages: ChatMessage[]; // The compacted messages originalTokens?: number; // Token count before compaction compactedTokens?: number; // Token count after compaction }; ``` **Example:** ```typescript const neurolink = new NeuroLink({ conversationMemory: { enabled: true }, }); const result = await neurolink.compactSession("session-123", { provider: "openai", summarizationProvider: "openai", summarizationModel: "gpt-4o-mini", }); if (result?.compacted) { console.log( `Compacted from ${result.originalTokens} to ${result.compactedTokens} tokens`, ); } ``` --- ### `getContextStats(sessionId, provider?, model?)` Get context usage statistics for a session, including token counts and whether compaction is needed. ```typescript async getContextStats( sessionId: string, provider?: string, model?: string ): Promise ``` **Parameters:** | Parameter | Type | Description | | ----------- | --------- | ------------------------------------------------------------- | | `sessionId` | `string` | The session ID to inspect | | `provider` | `string?` | Provider name for context window lookup (default: `"openai"`) | | `model` | `string?` | Model name for context window lookup | **Returns:** Stats object or `null` if conversation memory is not configured or the session is empty. **Example:** ```typescript const stats = await neurolink.getContextStats( "session-123", "openai", "gpt-4o", ); if (stats) { console.log( `Token usage: ${stats.estimatedInputTokens}/${stats.availableInputTokens}`, ); console.log(`Usage ratio: ${(stats.usageRatio * 100).toFixed(1)}%`); console.log(`Messages: ${stats.messageCount}`); if (stats.shouldCompact) { console.log("Context is approaching limit — compaction recommended"); } } ``` --- ### `needsCompaction(sessionId, provider?, model?)` Synchronously check if a session's context exceeds the compaction threshold (80% of the model's context window by default). ```typescript needsCompaction( sessionId: string, provider?: string, model?: string ): boolean ``` **Parameters:** | Parameter | Type | Description | | ----------- | --------- | ------------------------------------------------------------- | | `sessionId` | `string` | The session ID to check | | `provider` | `string?` | Provider name for context window lookup (default: `"openai"`) | | `model` | `string?` | Model name for context window lookup | **Returns:** `boolean` — `true` if the session should be compacted, `false` otherwise (also returns `false` if memory is not configured or session does not exist). **Example:** ```typescript if ( neurolink.needsCompaction("session-123", "anthropic", "claude-3-5-sonnet") ) { await neurolink.compactSession("session-123", { provider: "anthropic" }); } ``` --- ## Lifecycle Methods for gracefully releasing resources held by a NeuroLink instance. ### `shutdown()` Gracefully shut down all NeuroLink resources. Flushes and shuts down OpenTelemetry, closes external MCP server connections, and releases conversation memory resources (e.g., Redis connections). ```typescript async shutdown(): Promise ``` **Example:** ```typescript const neurolink = new NeuroLink(); // ... use neurolink ... // Graceful shutdown before process exit await neurolink.shutdown(); ``` --- ### `dispose()` Full resource disposal. Performs everything `shutdown()` does, plus removes all event listeners, clears circuit breakers, purges internal caches and maps, and resets initialization state. Use this when you are completely done with the instance, especially in test environments where multiple NeuroLink instances are created. ```typescript async dispose(): Promise ``` **Example:** ```typescript const neurolink = new NeuroLink(); try { const result = await neurolink.generate({ input: { text: "Hello" }, provider: "openai", }); } finally { // Full cleanup — prevents resource leaks in tests await neurolink.dispose(); } ``` --- ## Event System `NeuroLink` emits events throughout the generation and streaming lifecycle through a `TypedEventEmitter`. `NeuroLink` does not extend `EventEmitter` itself, so there is no `neurolink.on()`: get the emitter with `getEventEmitter()`, subscribe with `on()` and unsubscribe with `off()`. ```typescript const neurolink = new NeuroLink(); const emitter = neurolink.getEventEmitter(); emitter.on("generation:start", (data) => { console.log("Generation started"); }); emitter.on("tool:end", (data) => { console.log("Tool execution finished"); }); emitter.on("stream:chunk", (data) => { // Received a streaming chunk }); ``` ### Core Events | Event | Emitted When | | ------------------ | ------------------------------------ | | `generation:start` | A `generate()` call begins | | `generation:end` | A `generate()` call completes | | `stream:start` | A `stream()` call begins | | `stream:chunk` | A new chunk arrives during streaming | | `stream:end` | Streaming completes normally | | `stream:complete` | Stream fully consumed | | `stream:error` | An error occurs during streaming | | `tool:start` | A tool execution begins | | `tool:end` | A tool execution completes | | `response:start` | A provider response begins | | `response:end` | A provider response completes | ### MCP Server Events | Event | Emitted When | | -------------------------------- | ----------------------------------------- | | `externalMCP:serverConnected` | An external MCP server connects | | `externalMCP:serverDisconnected` | An external MCP server disconnects | | `externalMCP:serverFailed` | An external MCP server connection fails | | `externalMCP:toolDiscovered` | A new tool is discovered on an MCP server | | `externalMCP:toolRemoved` | A tool is removed from an MCP server | | `externalMCP:serverAdded` | A new MCP server registration is added | | `externalMCP:serverRemoved` | An MCP server registration is removed | ### Conversation Memory Events | Event | Emitted When | | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `conversation:titleGenerated` | A new Redis-backed conversation's title is stored (see [Conversation Memory](/docs/memory/conversation#title-generation-events)) | ### Other Events | Event | Emitted When | | ---------------------- | ----------------------------------- | | `tools-register:start` | Tool registration process begins | | `tools-register:end` | Tool registration process completes | | `connected` | Connection established | | `message` | General message event | | `error` | An error occurs | | `log` | A log message is emitted | | `log-event` | A structured log event is emitted | **TypedEventEmitter Interface:** ```typescript type TypedEventEmitter = { on( event: K, listener: (...args: unknown[]) => void, ): TypedEventEmitter; off( event: K, listener: (...args: unknown[]) => void, ): TypedEventEmitter; emit(event: K, ...args: unknown[]): boolean; removeAllListeners( event?: K, ): TypedEventEmitter; listenerCount(event: K): number; listeners( event: K, ): Array void>; }; ``` --- ## Related Features - [Human-in-the-Loop (HITL)](/docs/features/hitl) - Mark tools with `requiresConfirmation: true` - [Guardrails Middleware](/docs/features/guardrails) - Set `middleware` per call, in `new NeuroLink({ middleware })` or with `configureGlobalMiddleware()`; add `badWords` or `modelFilter` to filter - [Conversation History](/docs/features/conversation-history) - Use `getConversationHistory()` method - [Multimodal Chat](/docs/features/multimodal-chat) - Use `images` array in `generate()` options - [Auto Evaluation](/docs/features/auto-evaluation) - Enable with `enableEvaluation: true` - [CLI Loop Sessions](/docs/features/cli-loop-sessions) - Interactive mode with persistent state - [Provider Orchestration](/docs/features/provider-orchestration) - Set `enableOrchestration: true` - [Regional Streaming](/docs/features/regional-streaming) - Use `region` parameter in `generate()` - [Office Documents](/docs/features/office-documents) - Use the `files` array (or `--file`) for DOCX, PPTX, XLSX - [PDF Support](/docs/features/pdf-support) - Use `pdfFiles` array for PDF documents - [CSV Support](/docs/features/csv-support) - Use `csvFiles` array for spreadsheet data - [CLI Commands Reference](/docs/cli/commands) - CLI equivalents for all SDK methods - [Configuration Guide](/docs/deployment/configuration) - Environment variables and config files - [Troubleshooting](/docs/reference/troubleshooting) - Common SDK issues and solutions --- [Back to Main README](/docs/) | [Next: Visual Demos](/docs/visual-demos) --- ## Advanced SDK Features # Advanced SDK Features Advanced features and capabilities of the NeuroLink SDK. ## Streaming Use `stream()` for incremental token delivery: ```typescript const neurolink = new NeuroLink(); const stream = await neurolink.stream({ input: { text: "Write a story" }, provider: "openai", }); for await (const chunk of stream) { process.stdout.write(chunk.text ?? ""); } ``` ## Structured Output Use `schema` with a Zod schema to get typed JSON responses: ```typescript const RecipeSchema = z.object({ name: z.string(), ingredients: z.array(z.string()), steps: z.array(z.string()), }); const result = await neurolink.generate({ input: { text: "Give me a pancake recipe" }, schema: RecipeSchema, output: { format: "json" }, provider: "openai", }); // result.content is typed as { name: string; ingredients: string[]; steps: string[] } ``` > **Note:** Google Gemini models cannot combine tools and JSON schema output simultaneously. Pass `disableTools: true` when using `schema` with Vertex AI or Google AI Studio. ## Conversation Memory Enable conversation memory for stateful multi-turn interactions: ```typescript const neurolink = new NeuroLink({ conversationMemory: { enabled: true, store: "redis", // or "memory" for development maxTurnsPerSession: 50, }, }); const sessionId = "session-abc-123"; // First turn await neurolink.generate({ input: { text: "My name is Alice" }, context: { sessionId }, }); // Second turn - remembers context const result = await neurolink.generate({ input: { text: "What is my name?" }, context: { sessionId }, }); ``` ## Thinking Level Control extended thinking for supported models (Anthropic Claude, Gemini 2.5+): ```typescript const result = await neurolink.generate({ input: { text: "Solve this complex reasoning problem..." }, provider: "anthropic", thinkingLevel: "high", // "minimal" | "low" | "medium" | "high" }); ``` ## Embeddings Generate vector embeddings for text. `NeuroLink` has no `embed()` of its own: the embedding methods live on the provider instance (see the [embeddings guide](/docs/features/embeddings)): ```typescript const provider = await ProviderFactory.createProvider("openai"); // Single text const embedding = await provider.embed("Hello world"); // Multiple texts const embeddings = await provider.embedMany([ "First text", "Second text", "Third text", ]); ``` ## RAG Integration Pass files directly to `generate()` or `stream()` for retrieval-augmented generation: ```typescript const result = await neurolink.generate({ prompt: "What are the key features described in the docs?", rag: { files: ["./docs/guide.md", "./docs/api.md"], strategy: "markdown", chunkSize: 512, topK: 5, }, }); ``` ## External MCP Servers Add external tool servers using the Model Context Protocol: ```typescript // stdio transport (local server) await neurolink.addExternalMCPServer("github", { command: "npx", args: ["-y", "@modelcontextprotocol/server-github"], transport: "stdio", env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN }, }); // HTTP transport (remote server) await neurolink.addExternalMCPServer("remote-api", { transport: "http", url: "https://api.example.com/mcp", headers: { Authorization: "Bearer YOUR_TOKEN" }, timeout: 15000, }); ``` ## Multimodal Input Pass images and files alongside text: ```typescript const result = await neurolink.generate({ input: { text: "Describe this image", images: [readFileSync("./photo.png"), "https://example.com/image.jpg"], }, provider: "google-ai", }); ``` ## Context Compaction Configure automatic context window management for long conversations: ```typescript const neurolink = new NeuroLink({ conversationMemory: { enabled: true, enableSummarization: true, contextCompaction: { enabled: true, threshold: 0.8, // trigger at 80% of context window enablePruning: true, enableDeduplication: true, enableSlidingWindow: true, }, summarizationProvider: "vertex", summarizationModel: "gemini-2.5-flash", }, }); ``` ## Observability Integrate with Langfuse for tracing and monitoring: ```typescript const neurolink = new NeuroLink({ observability: { langfuse: { publicKey: process.env.LANGFUSE_PUBLIC_KEY, secretKey: process.env.LANGFUSE_SECRET_KEY, }, }, }); const result = await setLangfuseContext( { userId: "user-123", sessionId: "session-456", traceName: "chat-completion", }, async () => { return await neurolink.generate({ input: { text: "Hello" }, }); }, ); ``` ## Related Documentation - [API Reference](/docs/sdk/api-reference) -- SDK method signatures and options - [Configuration Guide](/docs/deployment/configuration) -- Environment setup - [Multimodal Chat](/docs/features/multimodal-chat) -- Images, PDFs, CSV, and more - [RAG Processing](/docs/tutorials/rag) -- Chunking, hybrid search, and reranking --- ## SDK Custom Tools Guide # SDK Custom Tools Guide Build powerful AI applications by extending NeuroLink with your own custom tools. ## Overview NeuroLink's SDK allows you to register custom tools programmatically, giving your AI assistants access to any functionality you need. All registered tools work seamlessly with the built-in tool system across all supported providers. ### Key Features - ✅ **Type-Safe**: Full TypeScript support with Zod schema validation - ✅ **Provider Agnostic**: Works with all providers that support tools - ✅ **Easy Integration**: Simple API for tool registration - ✅ **Async Support**: All tools run asynchronously - ✅ **Error Handling**: Graceful error handling built-in ## Quick Start ### Basic Tool Registration ```typescript const neurolink = new NeuroLink(); // Register a simple tool neurolink.registerTool("greetUser", { description: "Generate a personalized greeting", parameters: z.object({ name: z.string().describe("User name"), language: z.enum(["en", "es", "fr", "de"]).default("en"), }), execute: async ({ name, language }) => { const greetings = { en: `Hello, ${name}!`, es: `¡Hola, ${name}!`, fr: `Bonjour, ${name}!`, de: `Hallo, ${name}!`, }; return { greeting: greetings[language] }; }, }); // AI will now use your tool const result = await neurolink.generate({ input: { text: "Greet John in Spanish" }, }); // AI calls: greetUser({ name: "John", language: "es" }) // Returns: "¡Hola, John!" ``` ## ⚠️ Common Mistakes ### ❌ Using `schema` instead of `parameters` ```typescript // WRONG - will throw validation error neurolink.registerTool("badTool", { description: "This will fail", schema: { // ❌ Should be 'parameters' type: "object", properties: { value: { type: "string" } }, }, execute: async (args) => args, }); ``` ### ❌ Using plain JSON schema as `parameters` ```typescript // WRONG - will throw validation error neurolink.registerTool("badTool", { description: "This will also fail", parameters: { // ❌ Should be Zod schema type: "object", properties: { value: { type: "string" } }, }, execute: async (args) => args, }); ``` ### ✅ Correct Zod Schema Format ```typescript // CORRECT - works perfectly neurolink.registerTool("goodTool", { description: "This works correctly", parameters: z.object({ // ✅ Zod schema value: z.string(), }), execute: async (args) => args, }); ``` ## SimpleTool Interface All custom tools implement the `SimpleTool` interface: ```typescript type SimpleTool = { description: string; // What the tool does parameters?: ZodSchema; // Input validation schema execute: (args: T) => Promise; // Tool implementation }; ``` ### Interface Components - **description**: Clear, actionable description that helps the AI understand when to use the tool - **parameters**: Optional Zod schema for validating inputs (highly recommended) - **execute**: Async function that implements the tool's logic ## ️ Registration Methods ### Register Single Tool ```typescript neurolink.registerTool(name: string, tool: SimpleTool): void ``` ### Register Multiple Tools ```typescript neurolink.registerTools(tools: Record): void ``` ### Get Custom Tools ```typescript // Get custom tools registered via registerTool() const customTools = neurolink.getCustomTools(); // Returns Map // Get all available tools (async - includes built-in, custom, and MCP tools) const allTools = await neurolink.getAllAvailableTools(); // Returns ToolInfo[] ``` ## Common Use Cases ### 1. API Integration ```typescript neurolink.registerTool("weatherLookup", { description: "Get current weather for any city", parameters: z.object({ city: z.string().describe("City name"), country: z.string().optional().describe("Country code (ISO 2-letter)"), units: z.enum(["celsius", "fahrenheit"]).default("celsius"), }), execute: async ({ city, country, units }) => { const response = await fetch( `https://api.weather.com/v1/current?city=${city}&country=${country || ""}&units=${units}`, { headers: { "API-Key": process.env.WEATHER_API_KEY } }, ); const data = await response.json(); return { city, temperature: data.temp, condition: data.condition, humidity: data.humidity, units, }; }, }); ``` ### 2. Database Operations ```typescript neurolink.registerTool("userLookup", { description: "Find user information by email or ID", parameters: z.object({ identifier: z.string().describe("Email address or user ID"), fields: z .array(z.string()) .optional() .describe("Specific fields to return"), }), execute: async ({ identifier, fields }) => { const db = getDatabase(); const query = identifier.includes("@") ? { email: identifier } : { id: identifier }; const user = await db.users.findOne(query); if (!user) { return { error: "User not found" }; } // Return only requested fields if specified if (fields && fields.length > 0) { return fields.reduce((acc, field) => { acc[field] = user[field]; return acc; }, {}); } return user; }, }); ``` ### 3. Data Processing ```typescript neurolink.registerTool("analyzeSentiment", { description: "Analyze sentiment of text using ML model", parameters: z.object({ text: z.string().describe("Text to analyze"), language: z.string().default("en").describe("Language code"), detailed: z.boolean().default(false).describe("Include detailed analysis"), }), execute: async ({ text, language, detailed }) => { const sentimentModel = await loadSentimentModel(language); const result = await sentimentModel.analyze(text); if (detailed) { return { sentiment: result.sentiment, score: result.score, emotions: result.emotions, keywords: result.keywords, confidence: result.confidence, }; } return { sentiment: result.sentiment, score: result.score, }; }, }); ``` ### 4. File Operations ```typescript neurolink.registerTool("processSpreadsheet", { description: "Process Excel/CSV files with various operations", parameters: z.object({ filePath: z.string().describe("Path to spreadsheet file"), operation: z.enum(["summarize", "filter", "pivot", "chart"]), options: z.record(z.any()).optional(), }), execute: async ({ filePath, operation, options = {} }) => { const workbook = await loadSpreadsheet(filePath); switch (operation) { case "summarize": return { sheets: workbook.sheetNames, totalRows: workbook.getTotalRows(), columns: workbook.getColumns(), summary: workbook.generateSummary(), }; case "filter": const filtered = workbook.filter(options.criteria); return { matchingRows: filtered.length, data: filtered, }; case "pivot": return workbook.createPivotTable( options.rows, options.columns, options.values, ); case "chart": const chartData = workbook.prepareChartData( options.type, options.series, ); return { chartData, recommendation: suggestChartType(chartData) }; } }, }); ``` ### 5. External Service Integration ```typescript neurolink.registerTools({ sendEmail: { description: "Send email via SMTP", parameters: z.object({ to: z.string().email(), subject: z.string(), body: z.string(), cc: z.array(z.string().email()).optional(), attachments: z.array(z.string()).optional(), }), execute: async ({ to, subject, body, cc, attachments }) => { const mailer = getMailer(); const result = await mailer.send({ to, subject, body, cc, attachments: attachments ? await Promise.all(attachments.map(loadAttachment)) : undefined, }); return { messageId: result.messageId, status: "sent", timestamp: new Date().toISOString(), }; }, }, scheduleCalendarEvent: { description: "Create calendar event", parameters: z.object({ title: z.string(), startTime: z.string().datetime(), duration: z.number().describe("Duration in minutes"), attendees: z.array(z.string().email()).optional(), location: z.string().optional(), description: z.string().optional(), }), execute: async (params) => { const calendar = getCalendarService(); const event = await calendar.createEvent({ ...params, endTime: addMinutes(params.startTime, params.duration), }); return { eventId: event.id, eventLink: event.htmlLink, status: "created", }; }, }, }); ``` ## Best Practices ### 1. Clear Descriptions Make tool descriptions specific and actionable: ```typescript // ❌ Bad description: "Database tool"; // ✅ Good description: "Search customer database by name, email, or order ID"; ``` ### 2. Parameter Validation Always use Zod schemas for type safety: ```typescript // ❌ Bad - No validation parameters: undefined, execute: async (args: any) => { // Risky - args could be anything } // ✅ Good - Full validation parameters: z.object({ userId: z.string().uuid(), action: z.enum(['view', 'edit', 'delete']), reason: z.string().min(10).optional() }), execute: async ({ userId, action, reason }) => { // Type-safe with validated inputs } ``` ### 3. Error Handling Handle errors gracefully: ```typescript execute: async (args) => { try { const result = await riskyOperation(args); return { success: true, data: result }; } catch (error) { // Return error info instead of throwing return { success: false, error: error.message, code: error.code || "UNKNOWN_ERROR", }; } }; ``` A returned error is classified as a failure everywhere the SDK reports one, exactly as a thrown error is. A result is error-shaped when it carries `isError: true` (the MCP convention), a non-null `error` field (`{ error: "User not found" }`), or a `status` of `"error"` / `"failed"` / `"failure"` / `"fail"`. Such a call emits `tool:end` with `success: false` and the error text, is stored in session memory as `success: false`, replays on later turns as `[called → error]`, and is reported with `isError: true` in `result.toolExecutions`. The model still receives the full object you returned — classification only affects telemetry and memory, never what the model sees. ### 4. Async Operations All execute functions must return promises: ```typescript // ❌ Bad - Synchronous execute: (args) => { return { result: "data" }; }; // ✅ Good - Asynchronous execute: async (args) => { const result = await fetchData(args); return { result }; }; ``` ### 5. Tool Naming Use clear, consistent naming: ```typescript // ❌ Bad naming neurolink.registerTool('tool1', { ... }); neurolink.registerTool('doStuff', { ... }); neurolink.registerTool('x', { ... }); // ✅ Good naming neurolink.registerTool('searchProducts', { ... }); neurolink.registerTool('calculateShipping', { ... }); neurolink.registerTool('updateInventory', { ... }); ``` ## Testing Your Tools ### Unit Testing ```typescript describe("weatherLookup tool", () => { it("should return weather data for valid city", async () => { const tool = { description: "Get weather data", parameters: z.object({ city: z.string(), }), execute: async ({ city }) => { // Mock implementation for testing return { city, temperature: 22, condition: "sunny", }; }, }; const result = await tool.execute({ city: "London" }); expect(result).toHaveProperty("temperature"); expect(result.city).toBe("London"); }); }); ``` ### Integration Testing ```typescript describe("Custom tools integration", () => { let neurolink: NeuroLink; beforeEach(() => { neurolink = new NeuroLink(); neurolink.registerTool("testTool", { description: "Test tool for integration testing", parameters: z.object({ input: z.string() }), execute: async ({ input }) => ({ output: input.toUpperCase() }), }); }); it("should use custom tool in generation", async () => { const result = await neurolink.generate({ input: { text: "Use the test tool with input 'hello'" }, provider: "google-ai", }); expect(result.content).toContain("HELLO"); }); }); ``` ## Debugging Tools ### Enable Debug Mode ```bash export NEUROLINK_DEBUG=true ``` ### Log Tool Execution ```typescript neurolink.registerTool("debuggedTool", { description: "Tool with debug logging", parameters: z.object({ data: z.any() }), execute: async (args) => { console.log("[Tool] Executing with args:", args); try { const result = await processData(args); console.log("[Tool] Success:", result); return result; } catch (error) { console.error("[Tool] Error:", error); throw error; } }, }); ``` ## Advanced Patterns ### Tool Composition ```typescript // Base tools const baseTools = { fetchData: { description: "Fetch data from API", execute: async ({ endpoint }) => { const response = await fetch(endpoint); return response.json(); }, }, transformData: { description: "Transform data format", execute: async ({ data, format }) => { return transform(data, format); }, }, }; // Composed tool neurolink.registerTool("fetchAndTransform", { description: "Fetch data and transform it", parameters: z.object({ endpoint: z.string().url(), format: z.enum(["json", "csv", "xml"]), }), execute: async ({ endpoint, format }) => { const data = await baseTools.fetchData.execute({ endpoint }); return baseTools.transformData.execute({ data, format }); }, }); ``` ### Tool Middleware ```typescript // Wrap tools with middleware function withRateLimit(tool: SimpleTool, limit: number): SimpleTool { const rateLimiter = new RateLimiter(limit); return { ...tool, execute: async (args) => { await rateLimiter.acquire(); return tool.execute(args); }, }; } // Register with rate limiting neurolink.registerTool( "limitedApi", withRateLimit( { description: "Rate-limited API call", execute: async (args) => callExpensiveAPI(args), }, 10, ), // 10 calls per minute ); ``` ### Dynamic Tool Registration ```typescript // Register tools based on configuration async function registerDynamicTools(config: ToolConfig[]) { const tools: Record = {}; for (const toolConfig of config) { tools[toolConfig.name] = { description: toolConfig.description, parameters: createZodSchema(toolConfig.parameters), execute: createExecutor(toolConfig), }; } neurolink.registerTools(tools); } // Load from configuration const toolConfigs = await loadToolConfigs(); await registerDynamicTools(toolConfigs); ``` ### Forcing a Tool Call `toolChoice` tells the model whether it must call a tool on a step: | Value | Effect | | --------------------------------- | ------------------------------------------------ | | `"auto"` (default) | The model decides whether and which tool to call | | `"none"` | No tool calls on any step | | `"required"` | The model must call at least one tool | | `{ type: "tool", toolName: "x" }` | The model must call the named tool | A forced choice (`"required"` or a named tool) is applied only to the first `toolChoiceSteps` steps of the tool loop — **default 1** — after which the model is free to answer. Holding a forced choice on every step would compel a tool call on every step, and the turn could only end when `maxSteps` ran out. `"auto"` and `"none"` are applied unchanged on every step. ```typescript // Force `lookup_order` once, then let the model answer from the result. const result = await neurolink.generate({ input: { text: "Where is order 4471?" }, toolChoice: { type: "tool", toolName: "lookup_order" }, }); // Demand a tool on the first two steps, e.g. a search followed by a fetch. await neurolink.generate({ input: { text: "Summarise today's release notes" }, toolChoice: "required", toolChoiceSteps: 2, }); ``` For anything finer, `prepareStep` runs before every step and may return a `toolChoice` for that step, which takes precedence over `toolChoiceSteps`: ```typescript await neurolink.generate({ input: { text: "Plan, then execute" }, prepareStep: async ({ stepNumber, steps }) => { if (stepNumber === 0) { return { toolChoice: { type: "tool", toolName: "make_plan" } }; } if (steps.at(-1)?.toolCalls.some((c) => c.toolName === "make_plan")) { return { toolChoice: "required" }; } return { toolChoice: "auto" }; }, }); ``` `prepareStep` receives `{ stepNumber, steps, maxSteps, model }`, where `steps` holds one record per completed step (its text, tool calls — with `input` already parsed into an object — tool results, finish reason and usage, including prompt-cache tokens where the provider reports them). Only the returned `toolChoice` is honoured; the legacy `model` and `experimental_activeTools` / `activeTools` fields are accepted for source compatibility but ignored, and their presence is logged once as a warning — use `toolFilter` / `excludeTools` to scope tools. A hook that throws is logged and that step falls back to the `toolChoice` / `toolChoiceSteps` rule; a hook still pending when the turn is aborted or times out is released with the abort. Both `toolChoice` and `prepareStep` apply to `stream()` as well. Vertex, Google AI Studio and Bedrock do not honour `toolChoice` at all today. SageMaker honours `tools`, `toolChoice` and `prepareStep` on `generate()` only: its `stream()` sends the prompt without tools. ## Performance Considerations ### 1. Timeout Handling ```typescript execute: async (args) => { const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error("Tool timeout")), 30000), ); const operation = performOperation(args); return Promise.race([operation, timeout]); }; ``` ### 2. Caching ```typescript const cache = new Map(); execute: async (args) => { const cacheKey = JSON.stringify(args); if (cache.has(cacheKey)) { return cache.get(cacheKey); } const result = await expensiveOperation(args); cache.set(cacheKey, result); return result; }; ``` ### 3. Batch Operations ```typescript neurolink.registerTool("batchProcess", { description: "Process multiple items efficiently", parameters: z.object({ items: z.array(z.any()), operation: z.string(), }), execute: async ({ items, operation }) => { // Process in parallel with concurrency limit const results = await pLimit(5)( items.map((item) => () => processItem(item, operation)), ); return { processed: results.length, results, }; }, }); ``` ## Security Considerations ### Input Sanitization ```typescript parameters: z.object({ sqlQuery: z .string() .max(1000) .refine( (query) => !query.match(/DROP|DELETE|TRUNCATE/i), "Destructive operations not allowed", ), }); ``` ### Permission Checking ```typescript execute: async (args, context) => { // Check permissions before execution if (!hasPermission(context.user, "database.write")) { return { error: "Insufficient permissions" }; } return performDatabaseOperation(args); }; ``` ### Rate Limiting ```typescript const userLimits = new Map(); execute: async (args, context) => { const userId = context.user?.id || "anonymous"; const userCalls = userLimits.get(userId) || 0; if (userCalls >= 100) { return { error: "Rate limit exceeded" }; } userLimits.set(userId, userCalls + 1); // Reset counters periodically setTimeout(() => userLimits.delete(userId), 3600000); return performOperation(args); }; ``` ## Complete Example Here's a complete example combining multiple concepts: ```typescript const neurolink = new NeuroLink(); // Define a comprehensive customer service tool set neurolink.registerTools({ searchCustomer: { description: "Search for customer by various criteria", parameters: z.object({ query: z.string(), searchBy: z.enum(["email", "name", "phone", "orderId"]), limit: z.number().min(1).max(50).default(10), }), execute: async ({ query, searchBy, limit }) => { const db = getDatabase(); const results = await db.customers.search({ [searchBy]: query, limit, }); return { found: results.length, customers: results.map((c) => ({ id: c.id, name: c.name, email: c.email, totalOrders: c.orderCount, memberSince: c.createdAt, })), }; }, }, getOrderHistory: { description: "Get order history for a customer", parameters: z.object({ customerId: z.string().uuid(), status: z .enum(["all", "pending", "completed", "cancelled"]) .default("all"), limit: z.number().default(10), }), execute: async ({ customerId, status, limit }) => { const orders = await fetchOrders(customerId, { status, limit }); return { customerId, orderCount: orders.length, orders: orders.map((o) => ({ orderId: o.id, date: o.createdAt, status: o.status, total: o.total, items: o.items.length, })), }; }, }, processRefund: { description: "Process refund for an order", parameters: z.object({ orderId: z.string().uuid(), amount: z.number().positive(), reason: z.string().min(10), notify: z.boolean().default(true), }), execute: async ({ orderId, amount, reason, notify }) => { // Validate order exists and is refundable const order = await getOrder(orderId); if (!order) { return { success: false, error: "Order not found" }; } if (order.status !== "completed") { return { success: false, error: "Only completed orders can be refunded", }; } if (amount > order.total) { return { success: false, error: "Refund amount exceeds order total" }; } // Process refund const refund = await processPaymentRefund({ orderId, amount, reason, }); // Send notification if (notify) { await sendRefundNotification(order.customerId, refund); } return { success: true, refundId: refund.id, amount: refund.amount, status: "processed", }; }, }, }); // Now you can use natural language to access these tools const result = await neurolink.generate({ input: { text: "Find all orders for customer john@example.com and process a $50 refund for their most recent completed order due to damaged item", }, provider: "openai", }); // The AI will: // 1. Call searchCustomer({ query: "john@example.com", searchBy: "email" }) // 2. Call getOrderHistory({ customerId: , status: "completed" }) // 3. Call processRefund({ orderId: , amount: 50, reason: "damaged item" }) ``` ## MCP Server Integration Beyond simple tool registration, NeuroLink SDK supports adding complete MCP (Model Context Protocol) servers for more complex tool ecosystems. ### Adding In-Memory MCP Servers ```typescript // Add a complete MCP server with multiple related tools await neurolink.addInMemoryMCPServer("hr-management", { server: { title: "HR Management Server", description: "Comprehensive HR tools for employee management", tools: { createEmployee: { description: "Create a new employee record with full details", execute: async (params: { name: string; department: string; role: string; salary: number; startDate: string; }) => { return { success: true, data: { employeeId: `EMP-${Date.now()}`, name: params.name, department: params.department, role: params.role, salary: params.salary, startDate: params.startDate, status: "active", createdAt: new Date().toISOString(), }, }; }, }, calculateSalary: { description: "Calculate total salary including bonuses and deductions", execute: async (params: { baseSalary: number; bonuses: number; deductions: number; taxRate: number; }) => { const grossSalary = params.baseSalary + params.bonuses - params.deductions; const netSalary = grossSalary * (1 - params.taxRate); return { success: true, data: { baseSalary: params.baseSalary, bonuses: params.bonuses, deductions: params.deductions, grossSalary, taxAmount: grossSalary * params.taxRate, netSalary, calculatedAt: new Date().toISOString(), }, }; }, }, getEmployeeStats: { description: "Get comprehensive employee statistics and analytics", execute: async (params: { department?: string; role?: string }) => { // Simulated analytics data return { success: true, data: { totalEmployees: 150, byDepartment: { engineering: 60, sales: 35, marketing: 25, hr: 15, finance: 15, }, averageSalary: 75000, averageTenure: "2.5 years", openPositions: 8, lastUpdated: new Date().toISOString(), }, }; }, }, }, }, category: "hr-management", metadata: { version: "1.0.0", author: "Your Company", description: "Complete HR management solution", }, }); ``` ### Advanced MCP Server Examples #### 1. Data Analytics Server ```typescript await neurolink.addInMemoryMCPServer("analytics-server", { server: { title: "Data Analytics Server", description: "Advanced data processing and analytics tools", tools: { analyzeDataset: { description: "Perform statistical analysis on datasets", execute: async (params: { data: number[]; analysisType: "descriptive" | "correlation" | "regression"; }) => { const { data, analysisType } = params; switch (analysisType) { case "descriptive": const sum = data.reduce((a, b) => a + b, 0); const mean = sum / data.length; const sortedData = [...data].sort((a, b) => a - b); const median = sortedData[Math.floor(data.length / 2)]; const variance = data.reduce((acc, val) => acc + Math.pow(val - mean, 2), 0) / data.length; const stdDev = Math.sqrt(variance); return { success: true, data: { count: data.length, sum, mean, median, min: Math.min(...data), max: Math.max(...data), variance, standardDeviation: stdDev, range: Math.max(...data) - Math.min(...data), }, }; case "correlation": // Simplified correlation analysis return { success: true, data: { correlationMatrix: "Generated correlation matrix", strongCorrelations: [], analysisNote: "Correlation analysis completed", }, }; default: return { success: false, error: "Unknown analysis type" }; } }, }, generateReport: { description: "Generate comprehensive data reports with visualizations", execute: async (params: { title: string; data: any[]; reportType: "summary" | "detailed" | "executive"; }) => { return { success: true, data: { reportId: `RPT-${Date.now()}`, title: params.title, type: params.reportType, dataPoints: params.data.length, sections: [ "Executive Summary", "Key Metrics", "Detailed Analysis", "Recommendations", ], generatedAt: new Date().toISOString(), status: "completed", }, }; }, }, }, }, }); ``` #### 2. Workflow Automation Server ```typescript await neurolink.addInMemoryMCPServer("workflow-server", { server: { title: "Workflow Automation Server", description: "Tools for creating and managing automated workflows", tools: { createWorkflow: { description: "Create a new automated workflow with multiple steps", execute: async (params: { name: string; steps: Array; triggers: string[]; }) => { return { success: true, data: { workflowId: `WF-${Date.now()}`, name: params.name, steps: params.steps, triggers: params.triggers, status: "created", nextExecution: null, createdAt: new Date().toISOString(), }, }; }, }, executeWorkflow: { description: "Execute a workflow with specific input data", execute: async (params: { workflowId: string; inputData: any; executionMode: "test" | "production"; }) => { return { success: true, data: { executionId: `EXE-${Date.now()}`, workflowId: params.workflowId, mode: params.executionMode, status: "running", progress: 0, startedAt: new Date().toISOString(), estimatedCompletion: new Date(Date.now() + 300000).toISOString(), // 5 minutes }, }; }, }, getWorkflowStatus: { description: "Get current status and progress of workflow execution", execute: async (params: { workflowId: string }) => { return { success: true, data: { workflowId: params.workflowId, status: "in-progress", currentStep: "Data Processing", stepsCompleted: 3, totalSteps: 8, progress: 37.5, timeElapsed: "2m 15s", estimatedTimeRemaining: "3m 45s", lastUpdated: new Date().toISOString(), }, }; }, }, }, }, }); ``` #### 3. Content Generation Server ```typescript await neurolink.addInMemoryMCPServer("content-server", { server: { title: "Content Generation Server", description: "Advanced content creation and management tools", tools: { generateSampleText: { description: "Generate sample text content for testing and development", execute: async (params: { topic: string; length: "short" | "medium" | "long"; style: "formal" | "casual" | "technical"; }) => { const samples = { short: `A brief overview of ${params.topic}. This content covers essential information in a ${params.style} style.`, medium: `This is a comprehensive introduction to ${params.topic}. Written in a ${params.style} style, it covers fundamental concepts, practical applications, and key considerations for understanding ${params.topic} in various contexts.`, long: `This extensive exploration of ${params.topic} provides detailed analysis written in a ${params.style} style. The content examines multiple perspectives, methodologies, and real-world applications related to ${params.topic}. By thoroughly investigating various aspects and implications, readers gain comprehensive understanding of ${params.topic} and its significance across different fields and industries.`, }; return { success: true, data: { text: samples[params.length], topic: params.topic, length: params.length, style: params.style, wordCount: samples[params.length].split(" ").length, characterCount: samples[params.length].length, generatedAt: new Date().toISOString(), }, }; }, }, analyzeContent: { description: "Analyze text content for various metrics and insights", execute: async (params: { text: string; analysisTypes: Array; }) => { const results: any = {}; params.analysisTypes.forEach((type) => { switch (type) { case "sentiment": const positiveWords = ["good", "great", "excellent", "amazing"]; const negativeWords = ["bad", "terrible", "awful", "poor"]; const words = params.text.toLowerCase().split(" "); const positive = words.filter((w) => positiveWords.includes(w), ).length; const negative = words.filter((w) => negativeWords.includes(w), ).length; results.sentiment = { score: positive - negative, sentiment: positive > negative ? "positive" : negative > positive ? "negative" : "neutral", confidence: Math.min( (Math.abs(positive - negative) / words.length) * 10, 1, ), }; break; case "readability": const sentences = params.text.split(/[.!?]+/).length; const wordCount = params.text.split(" ").length; const avgWordsPerSentence = wordCount / sentences; results.readability = { wordCount, sentenceCount: sentences, avgWordsPerSentence, readabilityLevel: avgWordsPerSentence = {}; const meaningfulWords = params.text .toLowerCase() .replace(/[^\w\s]/g, "") .split(" ") .filter((w) => w.length > 3); meaningfulWords.forEach((word) => { wordFreq[word] = (wordFreq[word] || 0) + 1; }); results.keywords = Object.entries(wordFreq) .sort(([, a], [, b]) => b - a) .slice(0, 10) .map(([word, freq]) => ({ word, frequency: freq })); break; } }); return { success: true, data: { textLength: params.text.length, analysisTypes: params.analysisTypes, results, analyzedAt: new Date().toISOString(), }, }; }, }, }, }, }); ``` ### Mixed Tool Ecosystem Example ```typescript const neurolink = new NeuroLink(); // 1. Register simple custom tools (extending existing functionality) neurolink.registerTool( "enhancedCalculator", createTool({ description: "Enhanced calculator with scientific and financial functions", execute: (params: { expression: string; mode: "basic" | "scientific" | "financial"; }) => { if (params.mode === "scientific" && params.expression.includes("sqrt")) { const num = parseFloat( params.expression.replace("sqrt(", "").replace(")", ""), ); return { result: Math.sqrt(num), enhanced: true, mode: params.mode }; } if ( params.mode === "financial" && params.expression.includes("compound") ) { // Parse: compound(principal, rate, time) const match = params.expression.match( /compound\((\d+),\s*([\d.]+),\s*(\d+)\)/, ); if (match) { const [, principal, rate, time] = match.map(Number); const result = principal * Math.pow(1 + rate / 100, time); return { result, enhanced: true, mode: params.mode, calculation: "compound_interest", }; } } // Use a safe, restricted math expression evaluator for security // Requires: pnpm add mathjs const { create, addDependencies, subtractDependencies, multiplyDependencies, divideDependencies, powDependencies, sqrtDependencies, absDependencies, } from "mathjs"; // Create restricted math environment with only specific functions for security const dependencies = { addDependencies, subtractDependencies, multiplyDependencies, divideDependencies, powDependencies, sqrtDependencies, absDependencies, }; const math = create(dependencies, { matrix: "Array", number: "number", precision: 64, }); // Additional sanitization for basic mathematical expressions const sanitizedExpression = params.expression.replace( /[^0-9+\-*/().\s]/g, "", ); if (sanitizedExpression !== params.expression) { return { error: "Expression contains invalid characters", enhanced: false, mode: params.mode, }; } try { const result = math.evaluate(sanitizedExpression); return { result, enhanced: false, mode: params.mode }; } catch (error) { return { error: `Mathematical expression failed: ${error.message || "Invalid expression"}`, enhanced: false, mode: params.mode, }; } }, }), ); // 2. Add complete MCP servers (new functionality domains) await neurolink.addInMemoryMCPServer("business-intelligence", { server: { title: "Business Intelligence Server", tools: { generateKPIReport: { description: "Generate comprehensive KPI reports for business metrics", execute: async (params: { metrics: string[]; timeRange: string; department?: string; }) => { return { success: true, data: { reportId: `KPI-${Date.now()}`, metrics: params.metrics, timeRange: params.timeRange, department: params.department || "All", kpis: { revenue: "$1.2M", growth: "+15%", customerSatisfaction: "94%", efficiency: "87%", }, trends: ["Revenue increasing", "Customer satisfaction stable"], recommendations: [ "Focus on efficiency improvements", "Expand successful programs", ], generatedAt: new Date().toISOString(), }, }; }, }, predictTrends: { description: "Predict business trends using historical data", execute: async (params: { dataPoints: number[]; predictionPeriod: number; algorithm: "linear" | "exponential" | "seasonal"; }) => { // Simplified prediction logic const trend = params.dataPoints[params.dataPoints.length - 1] > params.dataPoints[0] ? "upward" : "downward"; const avgGrowth = (params.dataPoints[params.dataPoints.length - 1] - params.dataPoints[0]) / params.dataPoints.length; return { success: true, data: { algorithm: params.algorithm, trend, predictedGrowth: avgGrowth, confidence: 0.85, predictions: Array.from( { length: params.predictionPeriod }, (_, i) => params.dataPoints[params.dataPoints.length - 1] + avgGrowth * (i + 1), ), generatedAt: new Date().toISOString(), }, }; }, }, }, }, }); // 3. Use the mixed ecosystem const comprehensiveResult = await neurolink.generate({ input: { text: `Calculate compound interest for $10000 at 5% for 3 years, then generate a KPI report for revenue metrics over the last quarter, and predict trends for the next 6 months using the data points [100, 120, 115, 130, 125, 140]`, }, provider: "google-ai", maxTokens: 2000, }); // The AI will automatically: // 1. Use enhancedCalculator for compound interest: compound(10000, 5, 3) // 2. Use generateKPIReport for business metrics // 3. Use predictTrends for forecasting // 4. Synthesize all results into a comprehensive response console.log("AI Response:", comprehensiveResult.content); console.log("Tools Used:", comprehensiveResult.toolsUsed); ``` ### Tool Discovery and Management ```typescript // Get comprehensive view of all available tools const allTools = await neurolink.getAllAvailableTools(); // Group tools by source const toolsBySource = allTools.reduce( (acc, tool) => { const source = tool.serverId || "unknown"; acc[source] = (acc[source] || 0) + 1; return acc; }, {} as Record, ); console.log("Tool ecosystem summary:"); console.log("• Total tools available:", allTools.length); console.log("• Tools by source:", toolsBySource); // Get custom tools registered via registerTool() const customTools = neurolink.getCustomTools(); console.log("• Custom tools registered:", customTools.size); // Get in-memory MCP servers added via addInMemoryMCPServer() const mcpServers = neurolink.getInMemoryServers(); console.log("• In-memory MCP servers:", mcpServers.size); // Execute tools from any source using unified API const timeResult = await neurolink.executeTool("getCurrentTime"); const calculationResult = await neurolink.executeTool("enhancedCalculator", { expression: "compound(5000, 4.5, 2)", mode: "financial", }); const reportResult = await neurolink.executeTool("generateKPIReport", { metrics: ["revenue", "growth"], timeRange: "Q1-2024", }); console.log("Tool execution results:"); console.log("• Built-in tool:", timeResult.data.time); console.log("• Custom tool:", calculationResult.result); console.log("• MCP server tool:", reportResult.data.reportId); ``` ### Adding Remote HTTP MCP Servers Connect to remote MCP servers via HTTP transport with authentication, retry, and rate limiting: ```typescript const neurolink = new NeuroLink(); // Add HTTP MCP server with full configuration await neurolink.addExternalMCPServer("remote-api", { transport: "http", url: "https://api.example.com/mcp", headers: { Authorization: "Bearer YOUR_API_TOKEN", "X-Custom-Header": "value", }, httpOptions: { connectionTimeout: 30000, requestTimeout: 60000, idleTimeout: 120000, keepAliveTimeout: 30000, }, retryConfig: { maxAttempts: 3, initialDelay: 1000, maxDelay: 30000, backoffMultiplier: 2, }, rateLimiting: { requestsPerMinute: 60, maxBurst: 10, useTokenBucket: true, }, }); // Add HTTP server with OAuth 2.1 await neurolink.addExternalMCPServer("oauth-api", { transport: "http", url: "https://api.enterprise.com/mcp", auth: { type: "oauth2", oauth: { clientId: "your-client-id", clientSecret: "your-client-secret", authorizationUrl: "https://auth.provider.com/authorize", tokenUrl: "https://auth.provider.com/token", redirectUrl: "http://localhost:8080/callback", scope: "mcp:read mcp:write", usePKCE: true, }, }, }); // Use the remote server's tools in AI generation const result = await neurolink.generate({ input: { text: "Use the remote API to perform analysis" }, provider: "google-ai", }); ``` **HTTP Configuration Options:** | Option | Type | Description | | -------------- | ------ | ------------------------------------------- | | `transport` | string | Must be `"http"` for HTTP transport | | `url` | string | Remote MCP endpoint URL | | `headers` | object | Custom HTTP headers | | `httpOptions` | object | Connection timeout settings | | `retryConfig` | object | Retry with exponential backoff | | `rateLimiting` | object | Rate limiting configuration | | `auth` | object | Authentication (OAuth 2.1, Bearer, API Key) | See [MCP HTTP Transport Guide](/docs/mcp/http-transport) for complete documentation. ### Best Practices for MCP Integration #### 1. Organize Tools by Domain ```typescript // Group related tools into themed MCP servers await neurolink.addInMemoryMCPServer("user-management", { server: { title: "User Management Server", tools: { createUser: { /* ... */ }, updateUser: { /* ... */ }, deleteUser: { /* ... */ }, getUserProfile: { /* ... */ }, }, }, }); await neurolink.addInMemoryMCPServer("order-processing", { server: { title: "Order Processing Server", tools: { createOrder: { /* ... */ }, updateOrderStatus: { /* ... */ }, calculateShipping: { /* ... */ }, processPayment: { /* ... */ }, }, }, }); ``` #### 2. Consistent Error Handling ```typescript execute: async (params) => { try { const result = await performOperation(params); return { success: true, data: result, }; } catch (error) { return { success: false, error: error.message, code: error.code || "OPERATION_FAILED", timestamp: new Date().toISOString(), }; } }; ``` #### 3. Comprehensive Metadata ```typescript await neurolink.addInMemoryMCPServer("server-id", { server: { title: "Human-Readable Server Name", description: "Detailed description of server purpose", tools: { /* ... */ }, }, category: "business-logic", // Group similar servers metadata: { version: "2.1.0", author: "Your Team", lastUpdated: "2024-01-15", documentation: "https://docs.yourcompany.com/mcp-servers", supportContact: "support@yourcompany.com", }, }); ``` ## Additional Resources - [API Reference - NeuroLink Class](/docs/sdk/api-reference) - [MCP Integration Guide](/docs/mcp/integration) - [Provider Tool Support](/docs/) - [Test Examples](/docs/development/testing) - [MCP SDK Integration Proof Tests](/docs/development/testing) - [Real AI-MCP Integration Demo](/docs/development/testing) --- **Start building powerful AI applications with custom tools and MCP servers today! ** --- ## SDK Custom Tools This page has moved to [SDK Custom Tools Guide](/docs/sdk/custom-tools-guide). --- ## ️ Framework Integration Guide # ️ Framework Integration Guide NeuroLink integrates seamlessly with popular web frameworks. Here are complete examples for common use cases. ## SvelteKit Integration ### API Route (`src/routes/api/chat/+server.ts`) ```typescript export const POST: RequestHandler = async ({ request }) => { try { const { message } = await request.json(); const provider = createBestAIProvider(); const result = await provider.stream({ input: { text: message }, temperature: 0.7, maxTokens: 1000, }); // Manually create ReadableStream from AsyncIterable const readable = new ReadableStream({ async start(controller) { try { for await (const chunk of result.stream) { if (chunk && typeof chunk === "object" && "content" in chunk) { controller.enqueue(new TextEncoder().encode(chunk.content)); } } controller.close(); } catch (error) { controller.error(error); } }, }); return new Response(readable, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", }, }); } catch (error) { return new Response(JSON.stringify({ error: error.message }), { status: 500, headers: { "Content-Type": "application/json" }, }); } }; ``` ### Svelte Component (`src/routes/chat/+page.svelte`) ```svelte let message = ''; let response = ''; let isLoading = false; async function sendMessage() { if (!message.trim()) return; isLoading = true; response = ''; try { const res = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message }) }); if (!res.body) throw new Error('No response'); const reader = res.body.getReader(); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; response += decoder.decode(value, { stream: true }); } } catch (error) { response = `Error: ${error.message}`; } finally { isLoading = false; } } {isLoading ? 'Sending...' : 'Send'} {#if response} {response} {/if} .chat { max-width: 600px; margin: 2rem auto; padding: 1rem; } input { width: 70%; padding: 0.5rem; border: 1px solid #ccc; border-radius: 4px; } button { width: 25%; padding: 0.5rem; margin-left: 0.5rem; background: #007acc; color: white; border: none; border-radius: 4px; cursor: pointer; } button:disabled { opacity: 0.5; cursor: not-allowed; } .response { margin-top: 1rem; padding: 1rem; background: #f5f5f5; border-radius: 4px; white-space: pre-wrap; } ``` ### Environment Configuration ```bash # .env OPENAI_API_KEY="sk-your-key" AWS_ACCESS_KEY_ID="your-aws-key" AWS_SECRET_ACCESS_KEY="your-aws-secret" # Add other provider keys as needed ``` ### Dynamic Model Integration (v1.8.0+) #### Smart Model Selection API Route ```typescript export const POST: RequestHandler = async ({ request }) => { try { const { message, useCase, optimizeFor } = await request.json(); const factory = new AIProviderFactory(); // Use dynamic model selection based on use case const provider = await factory.createProvider({ provider: "auto", capability: useCase === "vision" ? "vision" : "general", optimizeFor: optimizeFor || "quality", // 'cost', 'speed', or 'quality' }); const result = await provider.stream({ input: { text: message }, temperature: 0.7, maxTokens: 1000, }); // Manually create ReadableStream from AsyncIterable const readable = new ReadableStream({ async start(controller) { try { for await (const chunk of result.stream) { if (chunk && typeof chunk === "object" && "content" in chunk) { controller.enqueue(new TextEncoder().encode(chunk.content)); } } controller.close(); } catch (error) { controller.error(error); } }, }); return new Response(readable, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", "X-Model-Used": result.model, "X-Provider-Used": result.provider, }, }); } catch (error) { return new Response(JSON.stringify({ error: error.message }), { status: 500, headers: { "Content-Type": "application/json" }, }); } }; ``` #### Cost-Optimized Component ```svelte let message = ''; let response = ''; let isLoading = false; let optimizeFor = 'quality'; // 'cost', 'speed', 'quality' let useCase = 'general'; // 'general', 'vision', 'code' let modelUsed = ''; let providerUsed = ''; async function sendMessage() { if (!message.trim()) return; isLoading = true; response = ''; try { const res = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message, useCase, optimizeFor }) }); // Extract model and provider info from headers modelUsed = res.headers.get('X-Model-Used') || ''; providerUsed = res.headers.get('X-Provider-Used') || ''; if (!res.body) throw new Error('No response'); const reader = res.body.getReader(); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; response += decoder.decode(value, { stream: true }); } } catch (error) { response = `Error: ${error.message}`; } finally { isLoading = false; } } Use Case: General Coding Vision Optimize For: Quality Speed Cost {isLoading ? 'Sending...' : 'Send'} {#if response} Model: {modelUsed} | Provider: {providerUsed} {response} {/if} .smart-chat { max-width: 700px; margin: 2rem auto; padding: 1rem; } .options { display: flex; gap: 1rem; margin-bottom: 1rem; } .options label { display: flex; flex-direction: column; gap: 0.25rem; } .options select { padding: 0.25rem; border: 1px solid #ccc; border-radius: 4px; } .model-info { font-size: 0.8rem; color: #666; margin-bottom: 0.5rem; font-family: monospace; } .content { white-space: pre-wrap; } ``` ## Next.js Integration ### App Router API (`app/api/ai/route.ts`) ```typescript export async function POST(request: NextRequest) { try { const { prompt, ...options } = await request.json(); const provider = createBestAIProvider(); const result = await provider.generate({ input: { text: prompt }, temperature: 0.7, maxTokens: 1000, ...options, }); return NextResponse.json({ text: result.text, provider: result.provider, usage: result.usage, }); } catch (error) { return NextResponse.json({ error: error.message }, { status: 500 }); } } // Streaming endpoint export async function PUT(request: NextRequest) { try { const { prompt } = await request.json(); const provider = createBestAIProvider(); const result = await provider.stream({ input: { text: prompt }, }); // Manually create ReadableStream from AsyncIterable const readable = new ReadableStream({ async start(controller) { try { for await (const chunk of result.stream) { if (chunk && typeof chunk === "object" && "content" in chunk) { controller.enqueue(new TextEncoder().encode(chunk.content)); } } controller.close(); } catch (error) { controller.error(error); } }, }); return new Response(readable, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", }, }); } catch (error) { return NextResponse.json({ error: error.message }, { status: 500 }); } } ``` ### React Component (`components/AIChat.tsx`) ```typescript 'use client'; type AIResponse = { text: string; provider: string; usage?: { promptTokens: number; completionTokens: number; totalTokens: number; }; } export default function AIChat() { const [prompt, setPrompt] = useState(''); const [result, setResult] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(''); const generate = async () => { if (!prompt.trim()) return; setLoading(true); setError(''); setResult(null); try { const response = await fetch('/api/ai', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt }) }); const data = await response.json(); if (response.ok) { setResult(data); } else { setError(data.error || 'An error occurred'); } } catch (err) { setError(err instanceof Error ? err.message : 'Network error'); } finally { setLoading(false); } }; const handleKeyPress = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); generate(); } }; return ( AI Chat with NeuroLink setPrompt(e.target.value)} onKeyPress={handleKeyPress} placeholder="Enter your prompt here..." className="flex-1 p-3 border border-gray-300 rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-blue-500" rows={3} /> {loading ? 'Generating...' : 'Generate'} {error && ( Error: {error} )} {result && ( Response: {result.text} Provider: {result.provider} {result.usage && ( Tokens: {result.usage.totalTokens} )} )} ); } ``` ### Streaming Component (`components/AIStreamChat.tsx`) ```typescript 'use client'; export default function AIStreamChat() { const [prompt, setPrompt] = useState(''); const [response, setResponse] = useState(''); const [loading, setLoading] = useState(false); const streamGenerate = async () => { if (!prompt.trim()) return; setLoading(true); setResponse(''); try { const res = await fetch('/api/ai', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt }) }); if (!res.body) throw new Error('No response stream'); const reader = res.body.getReader(); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value, { stream: true }); setResponse(prev => prev + chunk); } } catch (error) { setResponse(`Error: ${error.message}`); } finally { setLoading(false); } }; return ( Streaming AI Chat setPrompt(e.target.value)} placeholder="Enter your prompt..." className="flex-1 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" /> {loading ? ' Streaming...' : '▶️ Stream'} {response && ( Streaming Response: {response} {loading && ▋} )} ); } ``` ## Express.js Integration ### Basic Server Setup ```typescript const app = express(); app.use(express.json()); // Simple generation endpoint app.post("/api/generate", async (req, res) => { try { const { prompt, options = {} } = req.body; const provider = createBestAIProvider(); const result = await provider.generate({ input: { text: prompt }, ...options, }); res.json({ success: true, text: result.text, provider: result.provider, usage: result.usage, }); } catch (error) { res.status(500).json({ success: false, error: error.message, }); } }); // Streaming endpoint app.post("/api/stream", async (req, res) => { try { const { prompt } = req.body; const provider = createBestAIProvider(); const result = await provider.stream({ input: { text: prompt }, }); res.setHeader("Content-Type", "text/plain"); res.setHeader("Cache-Control", "no-cache"); for await (const chunk of result.stream) { if (chunk && typeof chunk === "object" && "content" in chunk) { res.write(chunk.content); } } res.end(); } catch (error) { res.status(500).json({ error: error.message }); } }); // Provider status endpoint app.get("/api/status", async (req, res) => { const providers = ["openai", "bedrock", "vertex"]; const status = {}; for (const providerName of providers) { try { const provider = AIProviderFactory.createProvider(providerName); const start = Date.now(); await provider.generate({ input: { text: "test" }, maxTokens: 1, }); status[providerName] = { available: true, responseTime: Date.now() - start, }; } catch (error) { status[providerName] = { available: false, error: error.message, }; } } res.json(status); }); app.listen(9876, () => { console.log("Server running on http://localhost:9876"); }); ``` ### Advanced Express Integration with Middleware ```typescript const app = express(); app.use(express.json()); // Middleware for AI provider app.use("/api/ai", (req, res, next) => { req.aiProvider = createBestAIProvider(); next(); }); // Rate limiting middleware const rateLimitMap = new Map(); app.use("/api/ai", (req, res, next) => { const ip = req.ip; const now = Date.now(); const requests = rateLimitMap.get(ip) || []; // Allow 10 requests per minute const recentRequests = requests.filter((time) => now - time = 10) { return res.status(429).json({ error: "Rate limit exceeded" }); } recentRequests.push(now); rateLimitMap.set(ip, recentRequests); next(); }); // Batch processing endpoint app.post("/api/ai/batch", async (req, res) => { try { const { prompts, options = {} } = req.body; if (!Array.isArray(prompts) || prompts.length === 0) { return res.status(400).json({ error: "Prompts array required" }); } const results = []; for (const prompt of prompts) { try { const result = await req.aiProvider.generate({ input: { text: prompt }, ...options, }); results.push({ success: true, ...result }); } catch (error) { results.push({ success: false, error: error.message }); } // Add delay to prevent rate limiting if (results.length setTimeout(resolve, 1000)); } } res.json({ results }); } catch (error) { res.status(500).json({ error: error.message }); } }); ``` ## Fastify Integration Fastify is a high-performance web framework for Node.js. NeuroLink integrates smoothly with Fastify's async-first architecture. ### Basic Server Setup ```typescript const fastify = Fastify({ logger: true }); // Simple generation endpoint fastify.post("/api/generate", async (request, reply) => { try { const { prompt, options = {} } = request.body as { prompt: string; options?: Record; }; const provider = createBestAIProvider(); const result = await provider.generate({ input: { text: prompt }, ...options, }); return { success: true, text: result.text, provider: result.provider, usage: result.usage, }; } catch (error) { reply.status(500); return { success: false, error: error instanceof Error ? error.message : "Unknown error", }; } }); // Streaming endpoint fastify.post("/api/stream", async (request, reply) => { try { const { prompt } = request.body as { prompt: string }; const provider = createBestAIProvider(); const result = await provider.stream({ input: { text: prompt }, }); reply.raw.writeHead(200, { "Content-Type": "text/plain", "Cache-Control": "no-cache", Connection: "keep-alive", }); for await (const chunk of result.stream) { if (chunk && typeof chunk === "object" && "content" in chunk) { reply.raw.write(chunk.content); } } reply.raw.end(); } catch (error) { reply.status(500); return { error: error instanceof Error ? error.message : "Unknown error" }; } }); // Provider status endpoint fastify.get("/api/status", async () => { const providers = ["openai", "bedrock", "vertex"]; const status: Record = {}; for (const providerName of providers) { try { const provider = AIProviderFactory.createProvider(providerName); const start = Date.now(); await provider.generate({ input: { text: "test" }, maxTokens: 1, }); status[providerName] = { available: true, responseTime: Date.now() - start, }; } catch (error) { status[providerName] = { available: false, error: error instanceof Error ? error.message : "Unknown error", }; } } return status; }); // Start server const start = async () => { try { await fastify.listen({ port: 9876, host: "0.0.0.0" }); console.log("Server running on http://localhost:9876"); } catch (err) { fastify.log.error(err); process.exit(1); } }; start(); ``` For a complete Fastify integration guide with hooks, plugins, and advanced patterns, see the [Fastify Integration Guide](/docs/sdk/framework-integration). ## NestJS Integration NestJS is an enterprise-grade Node.js framework built with TypeScript, featuring decorators, dependency injection, and a modular architecture. NeuroLink integrates naturally with NestJS patterns. ### NeuroLink Module and Service ```typescript // neurolink.module.ts @Global() @Module({ providers: [NeuroLinkService], exports: [NeuroLinkService], }) export class NeuroLinkModule {} ``` ```typescript // neurolink.service.ts @Injectable() export class NeuroLinkService implements OnModuleInit { private provider: ReturnType; onModuleInit() { this.provider = createBestAIProvider(); } async generate(prompt: string, options = {}) { const result = await this.provider.generate({ input: { text: prompt }, ...options, }); return { text: result.text, provider: result.provider, usage: result.usage, }; } async *stream(prompt: string, options = {}) { const result = await this.provider.stream({ input: { text: prompt }, ...options, }); for await (const chunk of result.stream) { if (chunk && typeof chunk === "object" && "content" in chunk) { yield chunk.content; } } } } ``` ```typescript // ai.controller.ts @Controller("api/ai") export class AIController { constructor(private readonly neurolink: NeuroLinkService) {} @Post("generate") async generate(@Body() body: { prompt: string; options?: object }) { return this.neurolink.generate(body.prompt, body.options); } @Post("stream") async stream(@Body() body: { prompt: string }, @Res() res: Response) { res.setHeader("Content-Type", "text/plain"); res.setHeader("Cache-Control", "no-cache"); for await (const chunk of this.neurolink.stream(body.prompt)) { res.write(chunk); } res.end(); } } ``` [Full NestJS Guide](/docs/sdk/nestjs-integration) ## React Hook (Universal) ### Custom Hook for AI Generation ```typescript type AIOptions = { temperature?: number; maxTokens?: number; provider?: string; systemPrompt?: string; } type AIResult = { text: string; provider: string; usage?: { promptTokens: number; completionTokens: number; totalTokens: number; }; } export function useAI(apiEndpoint = '/api/ai') { const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [result, setResult] = useState(null); const generate = useCallback(async ( prompt: string, options: AIOptions = {} ) => { if (!prompt.trim()) { setError('Prompt is required'); return null; } setLoading(true); setError(null); setResult(null); try { const response = await fetch(apiEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt, ...options }) }); if (!response.ok) { throw new Error(`Request failed: ${response.statusText}`); } const data = await response.json(); if (data.error) { throw new Error(data.error); } setResult(data); return data.text; } catch (err) { const message = err instanceof Error ? err.message : 'Unknown error'; setError(message); return null; } finally { setLoading(false); } }, [apiEndpoint]); const clear = useCallback(() => { setResult(null); setError(null); }, []); return { generate, loading, error, result, clear }; } // Usage example function MyComponent() { const { generate, loading, error, result } = useAI('/api/ai'); const handleGenerate = async () => { const text = await generate("Explain React hooks", { temperature: 0.7, maxTokens: 500, provider: 'openai' }); if (text) { console.log('Generated:', text); } }; return ( {loading ? 'Generating...' : 'Generate'} {error && Error: {error}} {result && ( {result.text} Provider: {result.provider} )} ); } ``` ### Streaming Hook ```typescript export function useAIStream(apiEndpoint = "/api/ai/stream") { const [streaming, setStreaming] = useState(false); const [content, setContent] = useState(""); const [error, setError] = useState(null); const stream = useCallback( async (prompt: string) => { if (!prompt.trim()) return; setStreaming(true); setContent(""); setError(null); try { const response = await fetch(apiEndpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt }), }); if (!response.body) { throw new Error("No response stream"); } const reader = response.body.getReader(); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value, { stream: true }); setContent((prev) => prev + chunk); } } catch (err) { setError(err instanceof Error ? err.message : "Stream error"); } finally { setStreaming(false); } }, [apiEndpoint], ); const clear = useCallback(() => { setContent(""); setError(null); }, []); return { stream, streaming, content, error, clear, }; } ``` ## Vue.js Integration ### Vue 3 Composition API ```typescript // composables/useAI.ts export function useAI() { const loading = ref(false); const error = ref(null); const result = ref(""); const generate = async (prompt: string, options = {}) => { if (!prompt.trim()) return; loading.value = true; error.value = null; result.value = ""; try { const response = await fetch("/api/ai", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt, ...options }), }); const data = await response.json(); if (data.error) { throw new Error(data.error); } result.value = data.text; } catch (err) { error.value = err instanceof Error ? err.message : "Unknown error"; } finally { loading.value = false; } }; const clear = () => { result.value = ""; error.value = null; }; return { loading: computed(() => loading.value), error: computed(() => error.value), result: computed(() => result.value), generate, clear, }; } ``` ### Vue Component ```vue AI Chat with NeuroLink {{ loading ? "Generating..." : "Generate" }} Error: {{ error }} Response: {{ result }} const prompt = ref(""); const { loading, error, result, generate } = useAI(); const handleGenerate = async () => { if (!prompt.value.trim()) return; await generate(prompt.value, { temperature: 0.7, maxTokens: 500, }); prompt.value = ""; }; .ai-chat { max-width: 600px; margin: 0 auto; padding: 2rem; } .input-group { display: flex; gap: 1rem; margin: 1rem 0; } textarea { flex: 1; min-height: 100px; padding: 0.5rem; border: 1px solid #ccc; border-radius: 4px; } button { padding: 0.5rem 1rem; background: #42b883; color: white; border: none; border-radius: 4px; cursor: pointer; } button:disabled { opacity: 0.5; cursor: not-allowed; } .error { padding: 1rem; background: #fee; border: 1px solid #fcc; border-radius: 4px; color: #c00; } .result { padding: 1rem; background: #f9f9f9; border-radius: 4px; margin-top: 1rem; } ``` ## Environment Configuration for All Frameworks ### Environment Variables ```bash # .env (for all frameworks) OPENAI_API_KEY="sk-your-openai-key" AWS_ACCESS_KEY_ID="your-aws-access-key" AWS_SECRET_ACCESS_KEY="your-aws-secret-key" GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json" # Optional configurations NEUROLINK_DEBUG="false" DEFAULT_PROVIDER="auto" ENABLE_FALLBACK="true" ``` ### Framework-Specific Configuration #### Next.js (`next.config.js`) ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { env: { OPENAI_API_KEY: process.env.OPENAI_API_KEY, // Don't expose AWS keys to client }, experimental: { serverComponentsExternalPackages: ["@juspay/neurolink"], }, }; module.exports = nextConfig; ``` #### SvelteKit (`vite.config.ts`) ```typescript export default defineConfig({ plugins: [sveltekit()], define: { // Only expose public env vars to client "process.env.PUBLIC_APP_NAME": JSON.stringify(process.env.PUBLIC_APP_NAME), }, }); ``` ## Deployment Considerations ### Vercel Deployment ```bash # Add environment variables in Vercel dashboard # or use vercel.json { "env": { "OPENAI_API_KEY": "@openai-api-key", "AWS_ACCESS_KEY_ID": "@aws-access-key-id", "AWS_SECRET_ACCESS_KEY": "@aws-secret-access-key" } } ``` ### Docker Deployment ```dockerfile FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . RUN npm run build # Set environment variables ENV OPENAI_API_KEY="" ENV AWS_ACCESS_KEY_ID="" ENV AWS_SECRET_ACCESS_KEY="" EXPOSE 3000 CMD ["npm", "start"] ``` --- [← Back to Main README](/docs/) | [Next: Provider Configuration →](/docs/getting-started/provider-setup) --- ## NestJS Integration Guide # NestJS Integration Guide **Build enterprise-grade AI applications with NestJS and NeuroLink** ## Quick Start ### 1. Create New NestJS Project ```bash npm install -g @nestjs/cli nest new my-ai-service cd my-ai-service npm install @juspay/neurolink dotenv class-validator class-transformer @nestjs/config ``` ### 2. Configure Environment ```bash # .env OPENAI_API_KEY=sk-your-openai-key ANTHROPIC_API_KEY=sk-ant-your-anthropic-key JWT_SECRET=your-super-secret-jwt-key API_KEY=your-api-key-for-clients PORT=3000 ``` ### 3. Generate Module and Controller ```bash nest generate module neurolink nest generate service neurolink nest generate controller ai ``` --- ## Module Setup ### NeuroLink Module (Dynamic) ```typescript // src/neurolink/neurolink.module.ts @Global() @Module({}) export class NeuroLinkModule { static forRoot(): DynamicModule { return { module: NeuroLinkModule, imports: [ConfigModule], providers: [NeuroLinkService], exports: [NeuroLinkService], }; } static forRootAsync(options: { imports?: any[]; useFactory: (...args: any[]) => Promise | any; inject?: any[]; }): DynamicModule { return { module: NeuroLinkModule, imports: [...(options.imports || []), ConfigModule], providers: [ { provide: "NEUROLINK_OPTIONS", useFactory: options.useFactory, inject: options.inject || [], }, NeuroLinkService, ], exports: [NeuroLinkService], }; } } ``` ### NeuroLink Service (@Injectable) ```typescript // src/neurolink/neurolink.service.ts Injectable, OnModuleInit, OnModuleDestroy, Logger, Inject, Optional, } from "@nestjs/common"; @Injectable() export class NeuroLinkService implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(NeuroLinkService.name); private ai: NeuroLink; constructor( private configService: ConfigService, @Optional() @Inject("NEUROLINK_OPTIONS") private options?: any, ) {} async onModuleInit() { this.ai = new NeuroLink({ providers: this.options?.providers || [ { name: "openai", config: { apiKey: this.configService.get("OPENAI_API_KEY") }, }, { name: "anthropic", config: { apiKey: this.configService.get("ANTHROPIC_API_KEY") }, }, ], }); this.logger.log("NeuroLink service initialized"); } async onModuleDestroy() { await this.ai.dispose(); this.logger.log("NeuroLink resources cleaned up"); } async generate( prompt: string, options?: { provider?: string; model?: string; temperature?: number }, ) { return this.ai.generate({ input: { text: prompt }, provider: options?.provider, model: options?.model, temperature: options?.temperature, }); } async generateStream( prompt: string, options?: { provider?: string; model?: string }, ) { const result = await this.ai.stream({ input: { text: prompt }, provider: options?.provider, model: options?.model, }); return result.stream; } async chat( messages: Array, options?: { provider?: string }, ) { return this.ai.generate({ input: { messages }, provider: options?.provider, }); } } ``` --- ## Controller Implementation ### AI Controller with Decorators ```typescript // src/ai/ai.controller.ts Controller, Post, Get, Body, Res, HttpCode, HttpStatus, UseGuards, UseInterceptors, UsePipes, ValidationPipe, Logger, } from "@nestjs/common"; @Controller("api/ai") @UseGuards(JwtAuthGuard) @UseInterceptors(RateLimitInterceptor) @UsePipes(new ValidationPipe({ transform: true, whitelist: true })) export class AIController { private readonly logger = new Logger(AIController.name); constructor(private readonly neuroLinkService: NeuroLinkService) {} @Post("generate") @HttpCode(HttpStatus.OK) async generate(@Body() dto: GenerateDto) { this.logger.log(`Generate request: ${dto.prompt.substring(0, 50)}...`); const result = await this.neuroLinkService.generate(dto.prompt, { provider: dto.provider, model: dto.model, temperature: dto.temperature, }); return { success: true, data: { text: result.text, usage: result.usage } }; } @Post("chat") @HttpCode(HttpStatus.OK) async chat(@Body() dto: ChatDto) { const result = await this.neuroLinkService.chat(dto.messages, { provider: dto.provider, }); return { success: true, data: { text: result.text, usage: result.usage } }; } @Post("stream") async stream(@Body() dto: StreamDto, @Res() res: Response) { res.setHeader("Content-Type", "text/event-stream"); res.setHeader("Cache-Control", "no-cache"); res.setHeader("Connection", "keep-alive"); try { const stream = await this.neuroLinkService.generateStream(dto.prompt, { provider: dto.provider, model: dto.model, }); for await (const chunk of stream) { if ("content" in chunk && chunk.content) res.write(`data: ${JSON.stringify({ text: chunk.content })}\n\n`); } res.write("data: [DONE]\n\n"); } catch (error) { res.write(`data: ${JSON.stringify({ error: error.message })}\n\n`); } res.end(); } @Get("health") @HttpCode(HttpStatus.OK) healthCheck() { return { status: "healthy", timestamp: new Date().toISOString() }; } } ``` --- ## DTOs and Validation ### Generate DTO with class-validator ```typescript // src/ai/dto/generate.dto.ts IsString, IsNotEmpty, IsOptional, IsNumber, Min, Max, MaxLength, IsIn, } from "class-validator"; export class GenerateDto { @IsString() @IsNotEmpty({ message: "Prompt is required" }) @MaxLength(100000) @Transform(({ value }) => value?.trim()) prompt: string; @IsOptional() @IsString() @IsIn(["openai", "anthropic", "google-ai", "mistral", "bedrock"]) provider?: string; @IsOptional() @IsString() model?: string; @IsOptional() @IsNumber() @Min(0) @Max(2) temperature?: number; @IsOptional() @IsNumber() @Min(1) @Max(128000) maxTokens?: number; } ``` ### Chat DTO with Nested Validation ```typescript // src/ai/dto/chat.dto.ts IsArray, IsString, IsNotEmpty, IsOptional, ValidateNested, ArrayMinSize, IsIn, } from "class-validator"; class MessageDto { @IsString() @IsIn(["user", "assistant", "system"]) role: "user" | "assistant" | "system"; @IsString() @IsNotEmpty() content: string; } export class ChatDto { @IsArray() @ArrayMinSize(1) @ValidateNested({ each: true }) @Type(() => MessageDto) messages: MessageDto[]; @IsOptional() @IsString() provider?: string; @IsOptional() @IsString() model?: string; } ``` ### Stream DTO ```typescript // src/ai/dto/stream.dto.ts IsString, IsNotEmpty, IsOptional, IsNumber, Min, Max, MaxLength, } from "class-validator"; export class StreamDto { @IsString() @IsNotEmpty() @MaxLength(100000) @Transform(({ value }) => value?.trim()) prompt: string; @IsOptional() @IsString() provider?: string; @IsOptional() @IsString() model?: string; @IsOptional() @IsNumber() @Min(0) @Max(2) temperature?: number; } ``` --- ## Authentication ### API Key Guard ```typescript // src/auth/guards/api-key.guard.ts Injectable, CanActivate, ExecutionContext, UnauthorizedException, } from "@nestjs/common"; @Injectable() export class ApiKeyGuard implements CanActivate { constructor(private configService: ConfigService) {} canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); const apiKey = request.headers["x-api-key"] as string; if (!apiKey) throw new UnauthorizedException("API key is required"); const validApiKey = this.configService.get("API_KEY"); if (apiKey !== validApiKey) throw new UnauthorizedException("Invalid API key"); return true; } } ``` ### JWT Auth Guard with @UseGuards ```typescript // src/auth/guards/jwt-auth.guard.ts Injectable, CanActivate, ExecutionContext, UnauthorizedException, } from "@nestjs/common"; export const IS_PUBLIC_KEY = "isPublic"; @Injectable() export class JwtAuthGuard implements CanActivate { constructor( private configService: ConfigService, private reflector: Reflector, ) {} async canActivate(context: ExecutionContext): Promise { const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [ context.getHandler(), context.getClass(), ]); if (isPublic) return true; const request = context.switchToHttp().getRequest(); const authHeader = request.headers.authorization; if (!authHeader?.startsWith("Bearer ")) { throw new UnauthorizedException("Authentication required"); } try { const token = authHeader.substring(7); const secret = this.configService.get("JWT_SECRET"); request["user"] = jwt.verify(token, secret); return true; } catch { throw new UnauthorizedException("Invalid or expired token"); } } } ``` ### Public Decorator ```typescript // src/auth/decorators/public.decorator.ts export const Public = () => SetMetadata(IS_PUBLIC_KEY, true); ``` --- ## Rate Limiting ### Custom RateLimitInterceptor ```typescript // src/common/interceptors/rate-limit.interceptor.ts Injectable, NestInterceptor, ExecutionContext, CallHandler, HttpException, HttpStatus, } from "@nestjs/common"; @Injectable() export class RateLimitInterceptor implements NestInterceptor { private store = new Map(); private readonly limit = 100; private readonly windowMs = 60000; intercept(context: ExecutionContext, next: CallHandler): Observable { const request = context.switchToHttp().getRequest(); const response = context.switchToHttp().getResponse(); const key = request["user"]?.sub || request.ip; const now = Date.now(); let entry = this.store.get(key); if (!entry || now > entry.resetTime) { entry = { count: 0, resetTime: now + this.windowMs }; } entry.count++; this.store.set(key, entry); response.setHeader("X-RateLimit-Limit", this.limit); response.setHeader( "X-RateLimit-Remaining", Math.max(0, this.limit - entry.count), ); if (entry.count > this.limit) { throw new HttpException( { message: "Rate limit exceeded" }, HttpStatus.TOO_MANY_REQUESTS, ); } return next.handle(); } } ``` ### Using @nestjs/throttler ```bash npm install @nestjs/throttler ``` ```typescript // src/app.module.ts @Module({ imports: [ ThrottlerModule.forRoot([ { name: "short", ttl: 1000, limit: 3 }, { name: "medium", ttl: 10000, limit: 20 }, { name: "long", ttl: 60000, limit: 100 }, ]), ], providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }], }) export class AppModule {} ``` --- ## Response Caching ### CacheInterceptor with @nestjs/cache-manager ```bash npm install @nestjs/cache-manager cache-manager cache-manager-redis-yet ``` ```typescript // src/common/interceptors/cache.interceptor.ts Injectable, NestInterceptor, ExecutionContext, CallHandler, Inject, } from "@nestjs/common"; @Injectable() export class CacheInterceptor implements NestInterceptor { constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {} async intercept( context: ExecutionContext, next: CallHandler, ): Promise> { const request = context.switchToHttp().getRequest(); if (request.method !== "GET" || request.body?.temperature !== 0) { return next.handle(); } const cacheKey = this.generateKey(request); const cached = await this.cacheManager.get(cacheKey); if (cached) return of(cached); return next.handle().pipe( tap((response) => { if (response && !response.error) { this.cacheManager.set(cacheKey, response, 300000); } }), ); } private generateKey(request: Request): string { const hash = crypto .createHash("sha256") .update(JSON.stringify({ url: request.url, body: request.body })) .digest("hex"); return `ai:cache:${hash}`; } } ``` --- ## Streaming Responses ### SSE with @Sse() Decorator ```typescript // src/ai/ai-stream.controller.ts Controller, Post, Body, Sse, MessageEvent, UseGuards, Logger, } from "@nestjs/common"; @Controller("api/ai") @UseGuards(JwtAuthGuard) export class AIStreamController { private readonly logger = new Logger(AIStreamController.name); constructor(private readonly neuroLinkService: NeuroLinkService) {} @Post("stream/sse") @Sse() streamSSE(@Body() dto: StreamDto): Observable { const subject = new Subject(); this.processStream(dto, subject).catch((error) => { subject.next({ data: { error: error.message }, type: "error" }); subject.complete(); }); return subject.asObservable(); } private async processStream(dto: StreamDto, subject: Subject) { const stream = await this.neuroLinkService.generateStream(dto.prompt, { provider: dto.provider, model: dto.model, }); subject.next({ data: { status: "started" }, type: "start" }); let tokenCount = 0; for await (const chunk of stream) { if ("content" in chunk && chunk.content) { tokenCount++; subject.next({ data: { text: chunk.content, index: tokenCount }, type: "token", }); } } subject.next({ data: { status: "completed", totalTokens: tokenCount }, type: "complete", }); subject.complete(); } } ``` --- ## Exception Filters ### AIExceptionFilter with @Catch() ```typescript // src/common/filters/ai-exception.filter.ts ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus, Logger, } from "@nestjs/common"; @Catch() export class AIExceptionFilter implements ExceptionFilter { private readonly logger = new Logger(AIExceptionFilter.name); catch(exception: Error, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const request = ctx.getRequest(); const { statusCode, code, message } = this.handleException(exception); this.logger.error( `${request.method} ${request.url} - ${statusCode}: ${message}`, exception.stack, ); response.status(statusCode).json({ success: false, error: { code, message }, meta: { timestamp: new Date().toISOString(), path: request.url }, }); } private handleException(exception: Error) { if (exception instanceof HttpException) { const status = exception.getStatus(); const response = exception.getResponse(); return { statusCode: status, code: this.getErrorCode(status), message: typeof response === "string" ? response : (response as any).message, }; } const message = exception.message?.toLowerCase() || ""; if (message.includes("rate limit")) { return { statusCode: 429, code: "RATE_LIMIT_ERROR", message: "Rate limit exceeded", }; } if (message.includes("api key") || message.includes("unauthorized")) { return { statusCode: 401, code: "PROVIDER_AUTH_ERROR", message: "Provider authentication failed", }; } return { statusCode: 500, code: "INTERNAL_ERROR", message: "An unexpected error occurred", }; } private getErrorCode(status: number): string { const codes: Record = { 400: "BAD_REQUEST", 401: "UNAUTHORIZED", 429: "RATE_LIMITED", 500: "INTERNAL_ERROR", }; return codes[status] || "UNKNOWN_ERROR"; } } ``` --- ## Production Patterns ### Health Check Module ```bash npm install @nestjs/terminus ``` ```typescript // src/health/health.controller.ts HealthCheckService, HealthCheck, MemoryHealthIndicator, } from "@nestjs/terminus"; @Controller("health") export class HealthController { constructor( private health: HealthCheckService, private memory: MemoryHealthIndicator, ) {} @Get() @Public() @HealthCheck() check() { return this.health.check([ () => this.memory.checkHeap("memory_heap", 500 * 1024 * 1024), ]); } @Get("live") @Public() liveness() { return { status: "ok", timestamp: new Date().toISOString() }; } } ``` ### Graceful Shutdown ```typescript // src/main.ts async function bootstrap() { const logger = new Logger("Bootstrap"); const app = await NestFactory.create(AppModule); app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true })); app.useGlobalFilters(new AIExceptionFilter()); app.enableShutdownHooks(); app.enableCors(); const port = process.env.PORT || 3000; await app.listen(port); logger.log(`Application running on port ${port}`); } bootstrap(); ``` --- ## Monitoring and Logging ### nestjs-pino for Structured Logging ```bash npm install nestjs-pino pino-http pino-pretty ``` ```typescript // src/app.module.ts @Module({ imports: [ LoggerModule.forRoot({ pinoHttp: { level: process.env.NODE_ENV === "production" ? "info" : "debug", transport: process.env.NODE_ENV !== "production" ? { target: "pino-pretty", options: { colorize: true } } : undefined, redact: ["req.headers.authorization", "req.headers['x-api-key']"], }, }), ], }) export class AppModule {} ``` ### Prometheus with @willsoto/nestjs-prometheus ```bash npm install @willsoto/nestjs-prometheus prom-client ``` ```typescript // src/common/metrics/metrics.module.ts PrometheusModule, makeCounterProvider, makeHistogramProvider, } from "@willsoto/nestjs-prometheus"; @Module({ imports: [ PrometheusModule.register({ path: "/metrics", defaultMetrics: { enabled: true }, }), ], providers: [ makeCounterProvider({ name: "ai_requests_total", help: "Total AI requests", labelNames: ["provider", "status"], }), makeHistogramProvider({ name: "ai_request_duration_seconds", help: "AI request duration", labelNames: ["provider"], buckets: [0.1, 0.5, 1, 2, 5, 10], }), ], exports: [PrometheusModule], }) export class MetricsModule {} ``` --- ## Best Practices Follow these best practices when building NestJS AI applications: - **Use Dependency Injection** - Inject NeuroLinkService instead of creating instances directly. This enables testing and lifecycle management. - **Implement Lifecycle Hooks** - Use `OnModuleInit` for initialization and `OnModuleDestroy` for cleanup to ensure proper resource management. - **Validate All Inputs** - Use DTOs with class-validator decorators and apply ValidationPipe globally to catch invalid requests early. - **Centralize Error Handling** - Use exception filters to handle AI provider errors consistently across all endpoints. - **Monitor Everything** - Implement Prometheus metrics for requests, latency, and errors. Use structured logging for debugging. --- ## Deployment ### Dockerfile ```dockerfile FROM node:20-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build FROM node:20-alpine AS production WORKDIR /app COPY --from=builder /app/dist ./dist COPY --from=builder /app/node_modules ./node_modules COPY --from=builder /app/package*.json ./ RUN addgroup -g 1001 -S nodejs && adduser -S nestjs -u 1001 USER nestjs ENV NODE_ENV=production PORT=3000 EXPOSE 3000 HEALTHCHECK --interval=30s --timeout=10s CMD wget --spider http://localhost:3000/health/live || exit 1 CMD ["node", "dist/main.js"] ``` ### docker-compose.yml ```yaml version: "3.8" services: app: build: . ports: - "3000:3000" environment: - NODE_ENV=production - JWT_SECRET=${JWT_SECRET} - API_KEY=${API_KEY} - OPENAI_API_KEY=${OPENAI_API_KEY} - REDIS_HOST=redis depends_on: - redis restart: unless-stopped redis: image: redis:7-alpine ports: - "6379:6379" volumes: - redis_data:/data restart: unless-stopped volumes: redis_data: ``` ### Production Checklist ```markdown ## Security - [ ] API keys in environment variables - [ ] Strong JWT secret - [ ] CORS configured properly - [ ] Rate limiting enabled - [ ] Input validation on all endpoints ## Performance - [ ] Response caching with Redis - [ ] Appropriate timeouts - [ ] Memory limits configured ## Reliability - [ ] Health checks implemented - [ ] Graceful shutdown handlers - [ ] Error handling for all AI providers ## Monitoring - [ ] Prometheus metrics exposed - [ ] Structured logging configured - [ ] Alerting rules defined ``` --- ## Related Documentation - [Express.js Integration Guide](/docs/sdk/framework-integration) - Lightweight REST API setup - [Next.js Integration Guide](/docs/guides/frameworks/nextjs) - Full-stack React applications - [Streaming Guide](/docs/advanced/streaming) - SSE and WebSocket streaming - [API Reference](/docs/sdk/api-reference) - Complete SDK documentation --- ## Need Help? - **Documentation**: [https://neurolink.dev/docs](https://neurolink.dev/docs) - **GitHub Issues**: [https://github.com/juspay/neurolink/issues](https://github.com/juspay/neurolink/issues) - **Discord Community**: [https://discord.gg/neurolink](https://discord.gg/neurolink) --- # CLI ## CLI Command Reference # CLI Command Reference The NeuroLink CLI mirrors the SDK. Every command shares consistent options and outputs so you can prototype in the terminal and port the workflow to code later. ## Install or Run Ad-hoc ```bash # Run without installation npx @juspay/neurolink --help # Install globally npm install -g @juspay/neurolink # Local project dependency npm install @juspay/neurolink ``` ## Command Map | Command | Description | Example | | ---------------------- | ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | | `generate` / `gen` | One-shot content generation with optional multimodal input. | `npx @juspay/neurolink generate "Draft release notes" --image ./before.png` | | `stream` | Real-time streaming output with tool support. | `npx @juspay/neurolink stream "Narrate sprint demo" --enableAnalytics` | | `decide [state]` | Typed, calibrated judgements from a decision model (no free text). | `npx @juspay/neurolink decide "Refund request" --questions '{"urgent":{"type":"boolean","instructions":"Is this urgent?"}}'` | | `transcribe ` | Audio to text; local engine by default, dictionary and correction. | `npx @juspay/neurolink transcribe meeting.wav --format srt` | | `batch` | Process multiple prompts from a file. | `npx @juspay/neurolink batch prompts.txt --format json` | | `loop` | Interactive session with persistent variables & memory. | `npx @juspay/neurolink loop --auto-redis` | | `auth ` | Manage provider authentication (API key or OAuth). | `npx @juspay/neurolink auth login anthropic --method oauth` | | `setup` / `s` | Guided provider onboarding and validation. | `npx @juspay/neurolink setup --provider openai` | | `status` | Health check for configured providers. | `npx @juspay/neurolink status --verbose` | | `get-best-provider` | Show the best available AI provider. | `npx @juspay/neurolink get-best-provider --format json` | | `models list` | Inspect available models and capabilities. | `npx @juspay/neurolink models list --capability vision` | | `config ` | Initialise, validate, export, or reset configuration. | `npx @juspay/neurolink config validate` | | `memory ` | View, export, or clear conversation history. | `npx @juspay/neurolink memory history NL_x3yr --format json` | | `mcp ` | Manage Model Context Protocol servers/tools. | `npx @juspay/neurolink mcp list` | | `ollama ` | Manage Ollama local AI models. | `npx @juspay/neurolink ollama list-models` | | `sagemaker ` | Manage Amazon SageMaker endpoints and models. | `npx @juspay/neurolink sagemaker status` | | `server ` | Manage NeuroLink HTTP server | `npx @juspay/neurolink server start --port 3000` | | `serve` | Start server in foreground mode | `npx @juspay/neurolink serve --port 3000` | | `proxy ` | Manage the Claude multi-account proxy and its local telemetry. | `npx @juspay/neurolink proxy telemetry setup` | | `rag ` | RAG document processing (chunk, index, query). | `npx @juspay/neurolink rag chunk ./docs/guide.md` | | `workflow ` | Manage and execute AI workflows. | `npx @juspay/neurolink workflow list` | | `observability` | Observability and telemetry management (aliases: `obs`, `otel`). | `npx @juspay/neurolink observability status` | | `telemetry` | Telemetry and exporter management (alias: `tel`). | `npx @juspay/neurolink telemetry status` | | `docs` | Start the NeuroLink documentation MCP server. | `npx @juspay/neurolink docs --transport http --port 3001` | | `validate` | Alias for `config validate`. | `npx @juspay/neurolink validate` | | `completion` | Generate shell completion script. | `npx @juspay/neurolink completion > ~/.neurolink-completion.sh` | ## Primary Commands ### `generate ` {#generate} ```bash npx @juspay/neurolink generate "Summarise design doc" \ --provider google-ai --model gemini-2.5-pro \ --image ./screenshots/ui.png --enableAnalytics --enableEvaluation ``` Key flags: - `--provider`, `-p` – provider slug (default `auto`). - `--model`, `-m` – model name for the chosen provider. - `--image`, `-i` – attach one or more image files/URLs for multimodal prompts. - `--pdf` – attach one or more PDF files for document analysis. - `--csv`, `-c` – attach one or more CSV files for data analysis. - `--file` – attach any supported file type, auto-detected. Covers Office documents (Word `.docx`, Excel `.xlsx`/`.xls`, PowerPoint `.pptx`, RTF, OpenDocument), **audio** (`.mp3`, `.wav`, `.m4a`, … — transcribed automatically), **video** (`.mp4`, `.webm`, `.mov`, `.mkv` — Gemini providers receive the clip itself, up to 14 MB; every other provider receives keyframes plus metadata and any embedded subtitles), archives, JSON, YAML, XML, HTML, SVG, Markdown, and 50+ code languages. Repeatable. Not available on `batch`, where it would collide with the prompts-file positional — use `generate` or `stream`. - `--temperature`, `-t` – creativity (default `0.7`). - `--maxTokens`, `--max` – response limit (default `1000`). - `--system`, `-s` – system prompt. - `--format`, `-f`, `--output-format` – `text` (default), `json`, or `table`. With `json`, stdout carries only the JSON result; debug and info logs go to stderr, so the output stays parseable even with `--debug`. - `--output`, `-o` – write response to file. - `--imageOutput`, `--image-output` – custom path for generated image (default: `generated-images/image-.png`). - `--enableAnalytics` / `--enableEvaluation` – capture metrics & quality scores. - `--evaluationDomain` – domain hint for the judge model. - `--domainAware` – use domain-aware evaluation (default `false`). - `--context` – JSON string appended to analytics/evaluation context. - `--domain`, `-d` – domain type for specialized processing: `healthcare`, `finance`, `analytics`, `ecommerce`, `education`, `legal`, `technology`, `generic`, `auto`. - `--disableTools` – bypass MCP tools for this call. - `--timeout` – seconds before aborting the request (default `120`). - `--region`, `-r` – Vertex AI region (e.g., `us-central1`, `europe-west1`, `asia-northeast1`). - `--debug`, `-v`, `--verbose` – verbose logging and full JSON payloads. - `--quiet`, `-q` – suppress non-essential output (default `true`). **CSV Options:** - `--csvMaxRows` – maximum number of CSV rows to process — a positive integer in the range `1`–`100000` (default `1000`). Invalid values are rejected with a clear error. - `--csvFormat` – CSV output format: `raw` (default), `markdown`, `json`. Large local `--image`/`--csv`/`--pdf`/`--video` files emit a soft-limit size warning (they are not rejected) so slow processing or token/size blowups aren't a surprise. **Video Input (Analysis):** - `--video` – attach video file for analysis (MP4, WebM, MOV, AVI, MKV). - `--video-frames` – number of frames to extract (default: chosen from the video's duration, capped at 100). - `--video-quality` – frame quality 1–100 (default `80`). - `--video-format` – frame format: `jpeg` (default) or `png`. - `--transcribe-audio` – extract and transcribe audio from video (default `false`). **Text-to-Speech (TTS):** - `--tts` – enable text-to-speech output (default `false`). - `--ttsProvider` – TTS provider: `google-ai`, `vertex`, `openai-tts`, `elevenlabs`, `azure-tts`, `fish-audio`, `cartesia` (overrides `--provider` for speech synthesis; default auto-selects from configured credentials). The CLI always speaks the model's reply (`tts.mode: "response"`); see [TTS](/docs/features/tts) for the SDK's `direct` / `response` modes and `tts.sanitize`. - `--ttsVoice` – TTS voice to use (e.g., `en-US-Neural2-C`, `Rachel` for ElevenLabs). - `--ttsFormat` – audio output format: `mp3` (default), `wav`, `ogg`, `opus`, `m4a`, `flac`, `webm`, `mp4`, `mpeg`, `mpga`. On ElevenLabs `ogg`/`opus` produce Ogg/Opus at 48 kHz (`opus_48000_64`); `wav` is raw PCM. - `--ttsSpeed` – speaking rate 0.25–4.0 (default `1.0`). ElevenLabs accepts 0.7–1.2 and clamps anything outside with a warning. - `--ttsQuality` – audio quality level: `standard` (default) or `hd`. - `--ttsOutput` – save TTS audio to file (supports absolute and relative paths). - `--ttsPlay` – auto-play generated audio (default `false`). **Speech-to-Text (STT):** - `--stt` – enable speech-to-text transcription of input audio (default `false`). - `--sttProvider` – STT provider: `whisper`, `deepgram`, `google-stt`, `azure-stt`, `elevenlabs-stt` (aliases `scribe`, `elevenlabs`; default auto-selects from configured credentials). - `--input-audio` – path to input audio file for STT transcription. Implies `--stt`. - `--sttLanguage` – audio language code for STT (e.g., `en-US`, `es-ES`). **Extended Thinking:** - `--thinking`, `--think` – enable extended thinking/reasoning capability (default `false`). - `--thinkingBudget` – token budget for extended thinking (5000–100000, default `10000`). Supported by Anthropic Claude and Gemini 2.5+ models. - `--thinkingLevel` – thinking level for extended reasoning (Anthropic Claude, Gemini 2.5+, Gemini 3): `minimal`, `low`, `medium`, `high`. **Anthropic Subscription Options:** - `--auth-method` – authentication method: `api-key` or `oauth`. Overrides auto-detection. - `--subscription-tier` – subscription tier: `free`, `pro`, `max`, `max_5`, `max_20`, or `api`. Overrides auto-detection from token/env. - `--enable-beta` – enable Anthropic beta features (experimental capabilities, computer use, etc.). Default `false`. ```bash # Generate with explicit subscription tier npx @juspay/neurolink generate "Explain quantum computing" \ --provider anthropic --subscription-tier pro # Generate with OAuth auth method npx @juspay/neurolink generate "Write a poem" \ --provider anthropic --authMethod oauth --enableBeta # Stream with max tier npx @juspay/neurolink stream "Tell me a story" \ --provider anthropic --subscriptionTier max ``` **File Input Examples:** ```bash # Attach multiple file types npx @juspay/neurolink generate "Analyze this data" \ --file ./report.xlsx \ --file ./config.yaml \ --file ./diagram.svg # Mix file types with images and PDFs npx @juspay/neurolink generate "Compare architecture" \ --file ./main.ts \ --pdf ./spec.pdf \ --image ./screenshot.png ``` See [File Processors Guide](/docs/features/file-processors) for all 17+ supported file types. **Video Generation (Veo 3.1):** - `--outputMode` – output mode: `text` (default) or `video`. - `--image` – path to input image file (required for video generation, e.g., ./input.jpg). - `--videoOutput`, `-vo` – path to save generated video file. - `--videoResolution` – `720p` or `1080p` (default `720p`). - `--videoLength` – duration: `4`, `6`, or `8` seconds (default `4`). - `--videoAspectRatio` – `9:16` (portrait) or `16:9` (landscape, default `16:9`). - `--videoAudio` – include synchronized audio (default `true`). **Note:** Video generation requires Vertex AI provider (`vertex`) and Veo 3.1 model (`veo-3.1`). The provider auto-switches to Vertex when `--outputMode video` is specified. Supported image formats: PNG, JPEG, WebP (max 20MB). **Presentation Generation (PPT):** - `--outputMode ppt` – switch to presentation generation mode. Alternatively, any `--ppt*` flag automatically activates PPT mode. - `--pptPages`, `--pages` – number of slides to generate (5-50, default `10` when PPT mode is enabled). - `--pptTheme` – presentation theme/style: `modern`, `corporate`, `creative`, `minimal`, `dark` (default: AI selects based on topic). - `--pptAudience` – target audience: `business`, `students`, `technical`, `general` (default: AI selects based on topic). - `--pptTone` – presentation tone: `professional`, `casual`, `educational`, `persuasive` (default: AI selects based on topic). - `--pptOutput`, `--po` – path to save generated PPTX file (e.g., `./output.pptx`). - `--pptAspectRatio` – slide aspect ratio: `16:9` or `4:3` (default: `16:9` when PPT mode is enabled). - `--pptNoImages` – disable AI image generation for slides (default `false`). ```bash # Generate a presentation npx @juspay/neurolink generate "Quarterly business review for Q4 2025" \ --outputMode ppt --pptPages 15 --pptTheme corporate --pptOutput ./q4-review.pptx # Generate with audience and tone npx @juspay/neurolink generate "Introduction to machine learning" \ --pptPages 20 --pptAudience students --pptTone educational --pptOutput ./ml-intro.pptx # Minimal presentation without AI images npx @juspay/neurolink generate "Project status update" \ --outputMode ppt --pptNoImages --pptOutput ./status.pptx ``` `gen` is a short alias with the same options. ### `stream ` {#stream} ```bash npx @juspay/neurolink stream "Walk through the timeline" \ --provider openai --model gpt-4o --enableEvaluation ``` `stream` shares the same flags as `generate` and adds chunked output for live UIs. Evaluation results are emitted after the stream completes when `--enableEvaluation` is set. ### `decide [state]` {#decide} Get typed, calibrated judgements from a decision model — the `decide` inference type, alongside `generate` and `stream`. Takes one `state` plus a map of named typed questions and prints one answer per question; there is no free text anywhere in the response. ```bash # State as a positional argument npx @juspay/neurolink decide "Refund request for a damaged item" \ --questions '{"urgent":{"type":"boolean","instructions":"Is this urgent?"}}' # State and questions from files, raw JSON output npx @juspay/neurolink decide --state-file ticket.json \ --questions-file questions.json --format json # Ask about an image (XOR, Perplexity, Cloudflare Clef and OpenAI Decisions read images); repeat --image for several npx @juspay/neurolink decide "What color is this?" --provider xor --model xor-omni \ --image ./photo.png \ --questions '{"color":{"type":"choice","instructions":"What color is the image?","criteria":{"red":"red","blue":"blue"}}}' # Ask about an audio clip (XOR); the state may be left out npx @juspay/neurolink decide --provider xor --model xor-omni --audio ./call.wav \ --questions '{"lang":{"type":"choice","instructions":"Which language is spoken?","criteria":{"english":"English","hindi":"Hindi"}}}' # Extract a typed value (XOR) npx @juspay/neurolink decide "Invoice INV-2024-0892 for 18,275 rupees" --provider xor --model xor-omni \ --questions '{"amount":{"type":"value","dtype":"int","instructions":"Invoice amount?"}}' ``` | Option | Description | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `state` | The content to judge, as a positional argument (or use `--state-file`). | | `--state-file ` | Path to a file holding the state (plain text or JSON). | | `--questions ` | Inline JSON map of questions. Exactly one of this or `--questions-file`. | | `--questions-file ` | Path to a JSON file holding the questions map. | | `--provider ` | Decision provider to use: `typesafe`, `laya`, `xor`, `subq`, `perplexity-decider`, `cloudflare-clef`, `openai-decisions` or `scaledown`. Defaults to the first configured, in that order (TypeSafe, Laya, XOR, SubQ, Perplexity, Cloudflare Clef, OpenAI Decisions, ScaleDown). | | `--model ` | Overrides the provider's configured model for this call. | | `--image ` | An image for the model to read, as a file path or a `data:` URL. Repeat the flag for several (Perplexity and OpenAI Decisions take up to 8, Cloudflare Clef up to 4, XOR 1). | | `--video ` | One video for the model to read (MP4, MOV or WebM), as a file path or a `data:` URL. No shipped provider reads video, so every one refuses it before any request. | | `--audio ` | One audio clip for the model to hear (WAV, FLAC, Ogg or MP3; XOR, which hears the first 30 seconds), as a file path or a `data:` URL. With it, the state may be left out. | | `--timeout ` | Timeout in milliseconds, used as given. Perplexity's default is 10 seconds plus 100 ms a question; raise it for a state of more than about 100,000 real tokens. Cloudflare Clef's default is 5 seconds. | | `--format text\|json`, `-f` | Output format (default: `text`). With `json`, stdout carries only the result. | | `--debug`, `-v` | Debug logging; written to stderr when `--format json` is used. | Each question is one of `boolean`, `choice`, `score` or `value` (`value` on XOR only); `--questions`/`--questions-file` is validated before any provider work, so a malformed payload fails fast with no network call. A provider error prints one line that keeps the provider's own detail, such as which field was rejected. Credentials are env-only, exactly like every other CLI command: TypeSafe reads `TYPESAFE_API_KEY` (or `AI_GATEWAY_API_KEY` for the Vercel AI Gateway route), Laya reads `LAYA_API_KEY` and `LAYA_BASE_URL` (required: Laya has no built-in endpoint), XOR reads `XOR_API_KEY` and `XOR_BASE_URL` (required: XOR has no built-in endpoint), SubQ reads `SUBQ_API_KEY` alone (it has a hosted endpoint; `SUBQ_BASE_URL` can name another origin) and is tried after XOR, ahead of the three providers whose keys are shared with text providers, and Perplexity reads `PERPLEXITY_API_KEY` alone (it has a hosted endpoint; `PERPLEXITY_DECIDER_BASE_URL` can name another origin), from the environment. `PERPLEXITY_API_KEY` is also the Perplexity text provider's key, so setting it for that provider configures `decide` too, tried after TypeSafe, Laya, XOR and SubQ. Cloudflare Clef reads `CLOUDFLARE_API_KEY` and `CLOUDFLARE_ACCOUNT_ID`, both required (it has a hosted endpoint; `CLOUDFLARE_CLEF_BASE_URL` can name another base, and `CLOUDFLARE_CLEF_MODEL` picks `clef` or `clef-flash`). They are also the Cloudflare Workers AI text provider's variables, so setting them for that provider configures `decide` too, tried after TypeSafe, Laya, XOR, SubQ and Perplexity. OpenAI Decisions reads `OPENAI_API_KEY` alone (it has a hosted endpoint; `OPENAI_DECISIONS_BASE_URL` can name another origin and `OPENAI_DECISIONS_MODEL` the model, `gpt-6-luna` by default), and that is also the OpenAI chat provider's key, so setting it for chat configures `decide` too, tried after all of those but ScaleDown, and the built-in features then make paid decision calls, unless `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL` names a host other than `https://api.openai.com` (a gateway's key is not used by default; `--provider openai-decisions` still uses it); see [its guide](/docs/getting-started/providers/openai-decisions.md#one-key-two-providers). ScaleDown reads `SCALEDOWN_API_KEY` alone (it has a hosted endpoint; `SCALEDOWN_BASE_URL` can name an origin or an origin with a path prefix and `SCALEDOWN_MODEL` the model, `classify-1` by default), sends it in an `x-api-key` header, and is tried last; no other provider reads that key, so setting it can only be meant for ScaleDown, but any earlier provider that is also configured is used first; see [its guide](/docs/getting-started/providers/scaledown). ScaleDown reads text only: the state is sent as a string (a string unchanged, anything else as its JSON text) and a blank one is refused with no network call. The Workers AI endpoint ignored state text past about 2,048 tokens without an error until 2026-10-04 and read far more on 2026-10-07 (hosted service or model: unknown), so NeuroLink now refuses a state it estimates at more than 16,000 tokens with no network call; see [its guide](/docs/getting-started/providers/cloudflare-clef.md#limits). Media is checked before any request: an `http(s)` URL, a missing or empty file, a file that is not an image or a video, more than 8 images (4 for Cloudflare Clef, 1 for XOR) and a request body over the provider's limit (25 MB for XOR, 32 MiB for Perplexity and for OpenAI Decisions, 256,000 bytes for Cloudflare Clef) are refused with no network call, TypeSafe, Laya, SubQ and ScaleDown refuse media outright, OpenAI Decisions refuses `--video` (and takes up to 8 images, NeuroLink's own allowance), Perplexity refuses `--video`, any image that is not PNG, JPEG or WebP, and any image over 2,048 tiles of 32 × 32 pixels (a larger one stalls the API for about a minute before it answers 504), and Cloudflare Clef refuses `--video` and any image that is not PNG, JPEG or WebP. XOR refuses `--video` (its gateway drops a video, so an answer would be blind), an audio clip it would not hear in full (a WAV, FLAC or Ogg clip over 30 seconds) and AAC/M4A audio. See [The `decide` inference type](/docs/features/decide-inference-type) for the full concept and the SDK equivalent. ### `transcribe ` {#transcribe} Turn audio into text — the `transcribe` inference type. Pass a file, or `-` to read the audio from stdin. With no STT provider configured, the built-in local engine (Whistle) runs on this machine with no key; set `NEUROLINK_STT_PROVIDER` (and that provider's key) to use another one. ```bash # Plain transcription with the default engine npx @juspay/neurolink transcribe meeting.wav # Repair names the engine mis-hears, guarded by the decision model, then an LLM rewrite npx @juspay/neurolink transcribe call.mp3 \ --term "Acme|akmee,ack me|the company name" --correct # Dictionary from a file, rewrite on a chosen text model, Indic words in Latin letters npx @juspay/neurolink transcribe standup.m4a --dictionary terms.json \ --rewrite-provider --rewrite-model --transliterate latin # Subtitles from word timings npx @juspay/neurolink transcribe talk.wav --word-timestamps --format srt > talk.srt # Live text from a file or a pipe, through transcribeStream() cat clip.wav | npx @juspay/neurolink transcribe - --stream ``` | Option | Description | | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `file` | Audio file (WAV, MP3, M4A, OGG/Opus, WebM, FLAC, MP4, raw PCM16), or `-` for stdin. | | `--provider ` | STT provider. Default: `NEUROLINK_STT_PROVIDER`, then the first configured one, then the local engine. | | `--model ` | Model of that provider. Default: `NEUROLINK_STT_MODEL` (only when the provider also came from the environment). | | `--language ` | Language code, or `auto` to let the engine detect it. Default: `NEUROLINK_STT_LANGUAGE`, else `auto`. | | `--diarize` | Label speakers, on providers that diarize. | | `--word-timestamps` | Request word-level timings. | | `--prompt ` | Context prompt for engines that bias on one; dictionary terms are appended. | | `--dictionary ` | JSON array of `{ "term", "heardAs", "meaning" }` entries. | | `--term "Term\|heard,as\|meaning"` | One dictionary entry inline; repeatable. Only the term is required. | | `--correct` | Run the correction layer: dictionary repairs (each one checked with the decision model when one is configured) and an LLM rewrite. | | `--rewrite-provider ` | Text provider for the rewrite. Turns correction on. | | `--rewrite-model ` | Model for the rewrite. Turns correction on. | | `--no-rewrite` | Dictionary-only correction, no LLM. | | `--transliterate latin\|native` | How Indic-script words are written: `latin` the way people type them (the default), `native` keeps the script. Never a translation. Turns correction on. | | `--second-opinion ` | A second STT engine on the same audio; the rewrite reconciles the two transcripts. Turns correction on. | | `--fallback ` | STT provider for audio the primary engine cannot read (an unsure language or no text). | | `--context ` | Who is talking and about what, for the engines, the guard and the rewrite. | | `--stream` | Decode the file to 16 kHz mono PCM16 and run it through `transcribeStream()`: live interim text, then finals and corrections. Non-WAV input needs ffmpeg. | | `--format text\|json\|srt\|vtt`, `-f` | Output (default `text`). `json` prints the full result (one event per line with `--stream`); `srt`/`vtt` build cues from segments, else from word timings. | | `--timeout ` | Whole-call timeout. | | `--quiet`, `-q` | Print only the text. | | `--debug`, `-v` | Debug logging; written to stderr when `--format json` is used. | The text output is the transcript followed by one dim line: the engine (and whether the fallback ran), the language and whether the engine was sure of it, the audio length, the time each layer took and what it did. In `--stream` mode a terminal shows the current utterance updating in place, and each final (and its correction) as its own line; when stdout is not a terminal, every event is a line. On failure the command exits 1 with the provider's message and the STT providers that are configured. Credentials are env-only, as for every other command. See [The `transcribe` inference type](/docs/features/transcribe) for the SDK, the server routes and the correction layer. ### `batch ` {#batch} Process multiple prompts from a file in sequence. ```bash # Process prompts from a file npx @juspay/neurolink batch prompts.txt # Export results as JSON npx @juspay/neurolink batch questions.txt --format json # Use Vertex AI with 2s delay between requests npx @juspay/neurolink batch tasks.txt -p vertex --delay 2000 # Save results to file npx @juspay/neurolink batch batch.txt --output results.json ``` `batch` shares the same flags as `generate`. The input file should contain one prompt per line. Results are returned as an array of `{ prompt, response }` objects. A default 1-second delay is applied between requests; override with `--delay `. ### `loop` **Interactive session mode** with persistent state, conversation memory, and session variables. Perfect for iterative workflows and experimentation. ```bash # Start loop with Redis-backed conversation memory npx @juspay/neurolink loop --enable-conversation-memory --auto-redis # Start loop without Redis auto-detection npx @juspay/neurolink loop --enable-conversation-memory --no-auto-redis # Force start a new conversation (skip selection menu) npx @juspay/neurolink loop --new # Resume a specific conversation by session ID npx @juspay/neurolink loop --resume abc123def456 # List available conversations and exit npx @juspay/neurolink loop --list-conversations # Use in-memory storage only npx @juspay/neurolink loop --no-auto-redis ``` **Loop-specific flags:** | Flag | Alias | Type | Default | Description | | ------------------------------ | ----- | ------- | ------- | ----------------------------------------------------- | | `--enable-conversation-memory` | | boolean | true | Enable conversation memory for the loop session | | `--max-sessions` | | number | 50 | Maximum number of conversation sessions to keep | | `--max-turns-per-session` | | number | 20 | Maximum turns per conversation session | | `--auto-redis` | | boolean | true | Automatically use Redis if available | | `--resume` | `-r` | string | | Directly resume a specific conversation by session ID | | `--new` | `-n` | boolean | | Force start a new conversation (skip selection menu) | | `--list-conversations` | `-l` | boolean | | List available conversations and exit | | `--compact-threshold` | | number | 0.8 | Context compaction trigger threshold (0.0–1.0) | | `--disable-compaction` | | boolean | false | Disable automatic context compaction | **Key capabilities:** - Run any CLI command without restarting session - Persistent session variables: `set provider openai`, `set temperature 0.9` - Conversation memory: AI remembers previous turns within session - Redis auto-detection: Automatically connects if `REDIS_URL` is set - Export session history as JSON for analytics - Automatic context compaction when usage exceeds threshold **Session management commands (inside loop):** | Command | Description | | ------------------- | ------------------------------------------------------------ | | `help` | Show all available loop mode commands and standard CLI help. | | `set ` | Set a session variable. Use `set help` for available keys. | | `get ` | Show current value of a session variable. | | `unset ` | Remove a session variable. | | `show` | Display all currently set session variables. | | `clear` | Reset all session variables. | | `exit` | Exit loop session. Aliases: `quit`, `:q`. | **Settable session variables (via `set`):** | Variable | Type | Description | Allowed Values | | --------------------- | ------- | ---------------------------------------------------------- | ---------------------------------------------------------------------- | | `provider` | string | The AI provider to use. | `openai`, `anthropic`, `google-ai`, `vertex`, `bedrock`, `azure`, etc. | | `model` | string | The specific model to use from the provider. | Any valid model name | | `temperature` | number | Controls randomness of the output (e.g., 0.2, 0.8). | | | `maxTokens` | number | The maximum number of tokens to generate. | | | `output` | string | AI response format value. | `text`, `json`, `structured`, `none` | | `systemPrompt` | string | The system prompt to guide the AI's behavior. | | | `timeout` | number | Timeout for the generation request in milliseconds. | | | `disableTools` | boolean | Disable all tool usage for the AI. | | | `maxSteps` | number | Maximum number of tool execution steps. | | | `enableAnalytics` | boolean | Enable or disable analytics for responses. | | | `enableEvaluation` | boolean | Enable or disable AI-powered evaluation of responses. | | | `evaluationDomain` | string | Domain expertise for evaluation. | | | `toolUsageContext` | string | Context about tools/MCPs used in the interaction. | | | `enableSummarization` | boolean | Enable automatic conversation summarization. | | | `thinking` | boolean | Enable extended thinking/reasoning capability. | | | `thinkingBudget` | number | Token budget for thinking (Anthropic models: 5000–100000). | | | `thinkingLevel` | string | Thinking level (Anthropic Claude, Gemini 2.5+, Gemini 3). | `minimal`, `low`, `medium`, `high` | **Context Budget Warnings:** During a loop session, NeuroLink monitors context window usage after each generation command: - **60% used (gray):** A subtle status line is shown: `Context: 62% used`. - **80% used (yellow):** A prominent warning with token counts is shown: ``` Context usage: 83% of window (12,450 / 15,000 tokens) Auto-compaction will trigger to preserve conversation quality. ``` When `--disable-compaction` is not set, the system automatically compacts the context to free up space while preserving conversation quality. See the complete guide: [CLI Loop Sessions](/docs/features/cli-loop-sessions) ### `auth ` {#auth} Manage authentication with AI providers. Supports traditional API key authentication and OAuth 2.1 with PKCE for Claude subscription plans (Pro/Max). ```bash # Interactive login (prompts for authentication method) npx @juspay/neurolink auth login anthropic # Login with a specific method npx @juspay/neurolink auth login anthropic --method api-key npx @juspay/neurolink auth login anthropic --method oauth npx @juspay/neurolink auth login anthropic --method create-api-key # Check authentication status for all providers npx @juspay/neurolink auth status # Check status for a specific provider npx @juspay/neurolink auth status anthropic # Refresh expired OAuth tokens npx @juspay/neurolink auth refresh anthropic # Clear stored credentials npx @juspay/neurolink auth logout anthropic ``` **Subcommands:** | Subcommand | Description | | -------------------- | -------------------------------------------------- | | `login ` | Authenticate with an AI provider | | `logout ` | Clear stored credentials for a provider | | `status [provider]` | Show authentication status (all providers if none) | | `refresh ` | Manually refresh OAuth tokens for a provider | **Login flags:** | Flag | Alias | Type | Default | Description | | ------------------- | ----- | ------- | ------- | -------------------------------------------------------------- | | `--method` | `-m` | string | | Authentication method: `api-key`, `oauth`, or `create-api-key` | | `--non-interactive` | | boolean | `false` | Skip interactive prompts (requires environment variables) | **Shared flags:** | Flag | Alias | Type | Default | Description | | ---------- | ----- | ------- | ------- | ----------------------------- | | `--format` | | string | `text` | Output format: `text`, `json` | | `--quiet` | `-q` | boolean | `false` | Suppress non-essential output | | `--debug` | | boolean | `false` | Enable debug output | **Authentication methods:** - **`api-key`** -- Traditional API key authentication. Prompts for your Anthropic API key and stores it in the project `.env` file. Best for API-billed usage. - **`oauth`** -- Direct OAuth 2.1 with PKCE. Opens a browser for Claude subscription (Pro/Max) authorization. Tokens are stored securely in `~/.neurolink/` and auto-refreshed. Experimental. - **`create-api-key`** -- OAuth-based API key creation (recommended for Claude Pro/Max). Authenticates via OAuth, then creates a standard API key through the Anthropic console. Combines the convenience of OAuth login with standard API key compatibility. **Supported providers:** `anthropic` **Status output:** `auth status` displays the authentication method, subscription tier (free/pro/max/api), token expiry, and refresh token availability for each configured provider. Use `--format json` for machine-readable output. **Examples (local development):** ```bash # Interactive authentication (choose method via prompt) pnpm run cli -- auth login anthropic # Authenticate using OAuth for Claude Pro/Max subscription pnpm run cli -- auth login anthropic --method oauth # Create an API key via OAuth (recommended for Claude Pro/Max) pnpm run cli -- auth login anthropic --method create-api-key # Use a traditional API key pnpm run cli -- auth login anthropic --method api-key # Non-interactive login (reads ANTHROPIC_API_KEY from environment) pnpm run cli -- auth login anthropic --method api-key --non-interactive # Show status for all providers pnpm run cli -- auth status # Show status as JSON (for scripting) pnpm run cli -- auth status --format json # Refresh expired OAuth tokens pnpm run cli -- auth refresh anthropic # Clear all stored credentials for Anthropic pnpm run cli -- auth logout anthropic ``` **Credential storage:** - API keys are saved to the project `.env` file as `ANTHROPIC_API_KEY`. - OAuth tokens are stored in `~/.neurolink/-credentials.json` with restricted file permissions. - The `logout` subcommand clears both stored credentials and offers to remove the key from `.env`. See also: [Claude Subscription Guide](/docs/features/claude-subscription) | [Provider Setup Guide](/docs/getting-started/provider-setup) ### `setup` **Interactive provider configuration wizard** that guides you through API key setup, credential validation, and recommended model selection. ```bash # Launch interactive setup wizard npx @juspay/neurolink setup # Show all available providers npx @juspay/neurolink setup --list # Configure a specific provider npx @juspay/neurolink setup --provider openai npx @juspay/neurolink setup --provider bedrock npx @juspay/neurolink setup --provider google-ai ``` **What the wizard does:** 1. **Prompts for API keys** – Securely collects credentials 2. **Validates authentication** – Tests connection to provider 3. **Writes `.env` file** – Safely stores credentials (creates if missing) 4. **Recommends models** – Suggests best models for your use case 5. **Shows example commands** – Quick-start examples to try immediately **Supported providers:** OpenAI, Anthropic, Google AI, Vertex AI, Bedrock, Azure, Hugging Face, Ollama, Mistral, and more. See also: [Provider Setup Guide](/docs/getting-started/provider-setup) ### `status` ```bash npx @juspay/neurolink status --verbose ``` Displays provider availability, authentication status, recent error summaries, and response latency. ### `models` Manage and discover AI models across all providers. ```bash # List all models for a provider npx @juspay/neurolink models list --provider google-ai # Filter by capability npx @juspay/neurolink models list --capability vision --format table ``` **Subcommands:** | Subcommand | Description | | -------------------- | ---------------------------------------------------- | | `list` | List available models with filtering options | | `search [query]` | Search models by capabilities, use case, or features | | `best` | Get the best model recommendation for your use case | | `resolve ` | Resolve model aliases and find exact model names | | `compare ` | Compare multiple models side by side | | `stats` | Show model registry statistics and insights | **Global models options:** | Option | Type | Default | Description | | ---------- | ------- | ------- | ----------------------------------------- | | `--format` | string | `table` | Output format: `table`, `json`, `compact` | | `--output` | string | | Save output to file | | `--quiet` | boolean | `false` | Suppress non-essential output | | `--debug` | boolean | `false` | Enable debug output | #### `models list` ```bash npx @juspay/neurolink models list [options] ``` | Option | Type | Default | Description | | -------------- | ------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `--provider` | string | | Filter by AI provider | | `--category` | string | | Filter by model category: `general`, `coding`, `creative`, `vision`, `reasoning` | | `--capability` | array | | Filter by required capabilities: `vision`, `functionCalling`, `codeGeneration`, `reasoning`, `multimodal`, `streaming`, `jsonMode` | | `--deprecated` | boolean | `false` | Include deprecated models | ```bash npx @juspay/neurolink models list --provider openai npx @juspay/neurolink models list --capability vision npx @juspay/neurolink models list --category coding ``` #### `models search [query]` Search models by capabilities, use case, or features. ```bash npx @juspay/neurolink models search [query] [options] ``` | Option | Type | Default | Description | | --------------- | ------ | ------- | ------------------------------------------------------------------------------------------------------------------------- | | `--use-case` | string | | Filter by primary use case: `coding`, `creative`, `analysis`, `conversation`, `reasoning`, `translation`, `summarization` | | `--max-cost` | number | | Maximum cost per 1K tokens (USD) | | `--min-context` | number | | Minimum context window size (tokens) | | `--max-context` | number | | Maximum context window size (tokens) | | `--performance` | string | | Required performance level: `fast`, `medium`, `slow`, `high`, `low` | ```bash npx @juspay/neurolink models search vision npx @juspay/neurolink models search --use-case coding --max-cost 0.01 npx @juspay/neurolink models search --min-context 100000 ``` #### `models best` Get the best model recommendation for your use case. ```bash npx @juspay/neurolink models best [options] ``` | Option | Type | Description | | ---------------------------- | ------- | -------------------------------------------- | | `--coding` | boolean | Optimize for code generation and programming | | `--creative` | boolean | Optimize for creative writing and content | | `--analysis` | boolean | Optimize for data analysis and research | | `--conversation` | boolean | Optimize for conversational interactions | | `--reasoning` | boolean | Optimize for logical reasoning tasks | | `--translation` | boolean | Optimize for language translation | | `--summarization` | boolean | Optimize for text summarization | | `--cost-effective` | boolean | Prioritize cost-effectiveness | | `--high-quality` | boolean | Prioritize output quality over cost | | `--fast` | boolean | Prioritize response speed | | `--require-vision` | boolean | Require vision/image processing capability | | `--require-function-calling` | boolean | Require function calling capability | | `--exclude-providers` | array | Exclude specific providers | | `--prefer-local` | boolean | Prefer local/offline models | ```bash npx @juspay/neurolink models best --coding npx @juspay/neurolink models best --cost-effective --require-vision npx @juspay/neurolink models best --fast --exclude-providers ollama ``` #### `models resolve ` Resolve model aliases and find exact model names. ```bash npx @juspay/neurolink models resolve [options] ``` | Option | Type | Default | Description | | --------- | ------- | ------- | --------------------------------------- | | `--fuzzy` | boolean | `true` | Enable fuzzy matching for partial names | ```bash npx @juspay/neurolink models resolve claude-latest npx @juspay/neurolink models resolve gpt4 npx @juspay/neurolink models resolve fastest ``` #### `models compare ` Compare multiple models side by side. ```bash npx @juspay/neurolink models compare ``` ```bash npx @juspay/neurolink models compare gpt-4o claude-3.5-sonnet gemini-2.5-pro npx @juspay/neurolink models compare fastest cheapest best-coding ``` #### `models stats` Show model registry statistics and insights. ```bash npx @juspay/neurolink models stats [options] ``` | Option | Type | Default | Description | | ------------ | ------- | ------- | ---------------------------------------- | | `--detailed` | boolean | `false` | Show detailed statistics with breakdowns | ```bash npx @juspay/neurolink models stats npx @juspay/neurolink models stats --detailed ``` ### `config` Manage persistent configuration stored in the NeuroLink config directory. ```bash npx @juspay/neurolink config init npx @juspay/neurolink config validate npx @juspay/neurolink config export --format json > neurolink-config.json ``` ### `memory` **Manage conversation history** stored in Redis. View, export, or clear session data for analytics and debugging. ```bash # List all active sessions npx @juspay/neurolink memory list # View session statistics npx @juspay/neurolink memory stats # View conversation history (text format) npx @juspay/neurolink memory history # Export session as JSON (Q4 2025 - for analytics) npx @juspay/neurolink memory export --session-id --format json > session.json # Export all sessions npx @juspay/neurolink memory export-all --output ./exports/ # Delete a single session npx @juspay/neurolink memory clear # Delete all sessions npx @juspay/neurolink memory clear-all ``` **Export formats:** - `json` – Structured data with metadata, timestamps, token counts - `csv` – Tabular format for spreadsheet analysis **Note:** Requires Redis-backed conversation memory. Set `REDIS_URL` environment variable. See the complete guide: [Redis Conversation Export](/docs/features/conversation-history) ### `mcp` Manage Model Context Protocol servers and tools. Supports stdio, SSE, WebSocket, and HTTP transports. ```bash # List registered servers/tools npx @juspay/neurolink mcp list # Auto-discover MCP servers from config files npx @juspay/neurolink mcp discover # Install popular MCP servers npx @juspay/neurolink mcp install filesystem npx @juspay/neurolink mcp install github # Add custom servers with different transports npx @juspay/neurolink mcp add myserver "python server.py" --transport stdio npx @juspay/neurolink mcp add webserver "node server.js" --transport sse # Test server connectivity npx @juspay/neurolink mcp test myserver # Remove a server npx @juspay/neurolink mcp remove myserver ``` **MCP Command Options (`mcp add`):** | Option | Description | | ------------- | --------------------------------------------------- | | `--transport` | Transport type: `stdio`, `http`, `sse`, `websocket` | | `--args` | Command arguments (array) | | `--env` | Environment variables (JSON string) | **HTTP Transport Features:** - Custom headers for authentication (Bearer tokens, API keys) - Configurable timeouts and connection options - Automatic retry with exponential backoff - Rate limiting to prevent API throttling - OAuth 2.1 support with PKCE See [MCP HTTP Transport Guide](/docs/mcp/http-transport) for complete configuration options. ### `batch` See [`batch `](#batch) above. ### `get-best-provider` Show the best available AI provider based on current configuration and availability. ```bash # Get best available provider npx @juspay/neurolink get-best-provider # Get provider as JSON npx @juspay/neurolink get-best-provider --format json # Just the provider name npx @juspay/neurolink get-best-provider --quiet ``` ### `ollama ` Manage Ollama local AI models. Requires Ollama to be installed on the local machine. ```bash # List installed models npx @juspay/neurolink ollama list-models # Download a model npx @juspay/neurolink ollama pull llama3 # Remove a model npx @juspay/neurolink ollama remove llama3 # Check Ollama service status npx @juspay/neurolink ollama status # Start/stop Ollama service npx @juspay/neurolink ollama start npx @juspay/neurolink ollama stop # Interactive Ollama setup npx @juspay/neurolink ollama setup ``` **Subcommands:** | Subcommand | Description | | ---------------- | ---------------------------- | | `list-models` | List installed Ollama models | | `pull ` | Download an Ollama model | | `remove ` | Remove an Ollama model | | `status` | Check Ollama service status | | `start` | Start Ollama service | | `stop` | Stop Ollama service | | `setup` | Interactive Ollama setup | ### `sagemaker ` Manage Amazon SageMaker AI models and endpoints. ```bash # Check SageMaker configuration and connectivity npx @juspay/neurolink sagemaker status # Test connectivity to an endpoint npx @juspay/neurolink sagemaker test my-endpoint # List available endpoints npx @juspay/neurolink sagemaker list-endpoints # Show current SageMaker configuration npx @juspay/neurolink sagemaker config # Interactive setup npx @juspay/neurolink sagemaker setup # Validate configuration and credentials npx @juspay/neurolink sagemaker validate # Run performance benchmark npx @juspay/neurolink sagemaker benchmark my-endpoint ``` **Subcommands:** | Subcommand | Description | | ---------------------- | ------------------------------------------------ | | `status` | Check SageMaker configuration and connectivity | | `test ` | Test connectivity to a SageMaker endpoint | | `list-endpoints` | List available SageMaker endpoints | | `config` | Show current SageMaker configuration | | `setup` | Interactive SageMaker configuration setup | | `validate` | Validate SageMaker configuration and credentials | | `benchmark ` | Run performance benchmark against endpoint | ### `completion` Generate a shell completion script for bash. ```bash # Generate shell completion npx @juspay/neurolink completion # Save completion script npx @juspay/neurolink completion > ~/.neurolink-completion.sh # Enable completions (bash) source ~/.neurolink-completion.sh ``` Add the completion script to your shell profile for persistent completions. --- ## `serve` Start the NeuroLink HTTP server in foreground mode. ### Usage ```bash neurolink serve [options] ``` ### Options | Option | Alias | Type | Default | Description | | ------------- | ----- | ------- | ------- | -------------------------------------------------------- | | `--port` | `-p` | number | 3000 | Port to listen on | | `--host` | `-H` | string | 0.0.0.0 | Host to bind to | | `--framework` | `-f` | string | hono | Web framework: hono, express, fastify, koa | | `--basePath` | | string | /api | Base path for all routes | | `--cors` | | boolean | true | Enable CORS | | `--rateLimit` | | number | 100 | Rate limit (requests per 15-minute window, 0 to disable) | | `--swagger` | | boolean | false | Enable Swagger UI and OpenAPI endpoints | | `--watch` | `-w` | boolean | false | Enable watch mode | | `--config` | `-c` | string | | Path to config file | ### Swagger/OpenAPI Endpoints When `--swagger` is enabled, these endpoints become available: | Endpoint | Description | | ----------------------- | ---------------------------------------- | | `GET /api/openapi.json` | OpenAPI 3.1 specification in JSON format | | `GET /api/openapi.yaml` | OpenAPI 3.1 specification in YAML format | | `GET /api/docs` | Interactive Swagger UI documentation | > **Note:** Disable with `--no-swagger` in production to avoid exposing API structure. ### Examples ```bash # Start with defaults neurolink serve # Start on specific port with Express neurolink serve --port 8080 --framework express # Start with custom config file neurolink serve --config ./server.config.json ``` --- ## `server ` Manage NeuroLink HTTP server for exposing AI agents as REST APIs. ### Subcommands | Subcommand | Description | | ---------- | ----------------------------------- | | `start` | Start the HTTP server in background | | `stop` | Stop the running server | | `status` | Show server status | | `routes` | List all registered routes | | `config` | Show or modify server configuration | | `openapi` | Generate OpenAPI specification | --- ### `server start` Start the HTTP server in background mode. ```bash neurolink server start [options] ``` | Option | Alias | Type | Default | Description | | ------------- | ----- | ------- | ------- | -------------------------------------------------------- | | `--port` | `-p` | number | 3000 | Port to listen on | | `--host` | `-H` | string | 0.0.0.0 | Host to bind to | | `--framework` | `-f` | string | hono | Framework: hono, express, fastify, koa | | `--basePath` | | string | /api | Base path for all routes | | `--cors` | | boolean | true | Enable CORS | | `--rateLimit` | | number | 100 | Rate limit (requests per 15-minute window, 0 to disable) | **Examples:** ```bash # Start with defaults neurolink server start # Start on port 8080 with Express neurolink server start -p 8080 --framework express ``` --- ### `server stop` Stop a running background server. ```bash neurolink server stop [options] ``` | Option | Type | Default | Description | | --------- | ------- | ------- | ------------------------------------------- | | `--force` | boolean | false | Force stop even if server is not responding | **Examples:** ```bash # Stop gracefully neurolink server stop # Force stop neurolink server stop --force ``` --- ### `server status` Show server status information. ```bash neurolink server status [options] ``` | Option | Type | Default | Description | | ---------- | ------ | ------- | ------------------------- | | `--format` | string | text | Output format: text, json | **Examples:** ```bash # Text output neurolink server status # JSON output for scripting neurolink server status --format json ``` --- ### `server routes` List all registered server routes. ```bash neurolink server routes [options] ``` | Option | Type | Default | Description | | ---------- | ------ | ------- | ------------------------------------------------------------ | | `--format` | string | table | Output format: text, json, table | | `--group` | string | all | Filter by route group: agent, tool, mcp, memory, health, all | | `--method` | string | all | Filter by HTTP method: GET, POST, PUT, DELETE, PATCH, all | **Examples:** ```bash # List all routes in table format neurolink server routes # List only agent routes neurolink server routes --group agent # List all POST endpoints as JSON neurolink server routes --method POST --format json ``` --- ### `server config` Show or modify server configuration. ```bash neurolink server config [options] ``` | Option | Type | Default | Description | | ---------- | ------- | ------- | -------------------------------------- | | `--get` | string | | Get a specific config value | | `--set` | string | | Set a config value (format: key=value) | | `--reset` | boolean | false | Reset configuration to defaults | | `--format` | string | text | Output format: text, json | **Examples:** ```bash # Show all configuration neurolink server config # Get specific value neurolink server config --get defaultPort # Set a value neurolink server config --set defaultPort=8080 # Reset to defaults neurolink server config --reset ``` --- ### `server openapi` Generate OpenAPI specification. ```bash neurolink server openapi [options] ``` | Option | Alias | Type | Default | Description | | ------------ | ----- | ------ | ------- | ------------------------- | | `--output` | `-o` | string | stdout | Output file path | | `--format` | | string | json | Output format: json, yaml | | `--basePath` | | string | /api | Base path for all routes | | `--title` | | string | | API title | | `--version` | | string | | API version | **Examples:** ```bash # Generate to stdout neurolink server openapi # Save to file neurolink server openapi -o openapi.json # Generate YAML format neurolink server openapi --format yaml -o openapi.yaml ``` ## proxy \ Manage the Claude multi-account proxy server and the local OpenObserve stack used for proxy observability. ```bash # Start the proxy on the default port npx @juspay/neurolink proxy start # Check live proxy status npx @juspay/neurolink proxy status --format json # Bring up OpenObserve + OTEL collector + dashboard npx @juspay/neurolink proxy telemetry setup ``` **Subcommands:** | Subcommand | Description | | -------------------- | -------------------------------------------------------------------------- | | `start` | Start the Claude multi-account proxy in the foreground | | `status` | Show live proxy status, including attempts vs completed requests | | `telemetry ` | Manage the local OpenObserve stack and maintained dashboard for the proxy | | `setup` | One-command onboarding: auth + service install + Claude Code configuration | | `install` | Install the proxy as a persistent background service | | `uninstall` | Remove the persistent background service | ### proxy start ```bash npx @juspay/neurolink proxy start npx @juspay/neurolink proxy start --port 8080 --strategy fill-first npx @juspay/neurolink proxy start --config ./proxy-config.yaml --env-file ./proxy.env ``` | Option | Alias | Type | Default | Description | | ------------------- | ----- | ------- | -------------------------------- | --------------------------------------------------------- | | `--port` | `-p` | number | `55669` | Port to listen on | | `--host` | `-H` | string | `127.0.0.1` | Host to bind to | | `--strategy` | `-s` | string | `fill-first` | Account selection strategy: `fill-first` or `round-robin` | | `--health-interval` | | number | `30` | Health check interval in seconds | | `--config` | `-c` | string | `~/.neurolink/proxy-config.yaml` | Path to proxy config file | | `--env-file` | | string | | Path to proxy provider env file | | `--passthrough` | | boolean | `false` | Transparent forwarding: no retry, rotation, or polyfill | | `--debug` | `-d` | boolean | `false` | Enable debug output | | `--quiet` | `-q` | boolean | `false` | Suppress non-essential output | ### proxy status ```bash npx @juspay/neurolink proxy status npx @juspay/neurolink proxy status --format json ``` | Option | Alias | Type | Default | Description | | ---------- | ----- | ------- | ------- | ------------------------------- | | `--format` | | string | `text` | Output format: `text` or `json` | | `--quiet` | `-q` | boolean | `false` | Suppress non-essential output | ### proxy telemetry \ Manage the repo-owned local OpenObserve stack in `scripts/observability/`. ```bash npx @juspay/neurolink proxy telemetry setup npx @juspay/neurolink proxy telemetry status npx @juspay/neurolink proxy telemetry logs ``` | Action | Description | | ------------------ | ----------------------------------------------------------------------- | | `setup` | Start OpenObserve + OTEL collector and import the maintained dashboard | | `start` | Start the local telemetry stack without re-importing the dashboard | | `stop` | Stop the local telemetry stack | | `status` | Show local stack health and endpoint info | | `logs` | Follow OpenObserve and collector logs | | `import-dashboard` | Re-import the dashboard and dedupe older dashboards with the same title | | Option | Alias | Type | Default | Description | | --------- | ----- | ------- | ------- | ---------------------------------------------------- | | `--quiet` | `-q` | boolean | `false` | Suppress the local CLI spinner and delegate directly | ### proxy setup ```bash npx @juspay/neurolink proxy setup npx @juspay/neurolink proxy setup --no-service npx @juspay/neurolink proxy setup --port 9000 --method oauth ``` | Option | Alias | Type | Default | Description | | -------------- | ----- | ------- | ------- | -------------------------------------------------------- | | `--port` | `-p` | number | `55669` | Proxy port | | `--method` | | string | `oauth` | Auth method: `oauth` or `api-key` | | `--no-service` | | boolean | `false` | Skip service installation and start in foreground | | `--env-file` | | string | | Path to proxy provider env file to persist for the proxy | ### proxy install ```bash npx @juspay/neurolink proxy install npx @juspay/neurolink proxy install --port 9000 --host 0.0.0.0 ``` | Option | Alias | Type | Default | Description | | ------------ | ----- | ------ | ----------- | ------------------------------------------------------------ | | `--port` | `-p` | number | `55669` | Proxy port | | `--host` | | string | `127.0.0.1` | Proxy host | | `--env-file` | | string | | Path to proxy provider env file to persist for the service | | `--config` | | string | | Path to proxy routing config file to persist for the service | ### proxy uninstall ```bash npx @juspay/neurolink proxy uninstall ``` For the full operational guide, routing model, and the maintained OpenObserve dashboard, see [Claude Proxy](/docs/features/claude-proxy) and [Claude Proxy Observability](/docs/features/claude-proxy-observability). ## Global Flags (available on every command) | Flag | Alias | Default | Description | | --------------------------- | ----------------------- | ------- | ------------------------------------------------------------------------- | | `--provider` | `-p` | `auto` | AI provider to use (auto-selects best available). | | `--model` | `-m` | | Specific model to use. | | `--temperature` | `-t` | `0.7` | Creativity level (0.0 = focused, 1.0 = creative). | | `--maxTokens` | `--max` | `1000` | Maximum tokens to generate. | | `--system` | `-s` | | System prompt to guide AI behavior. | | `--format` | `-f`, `--output-format` | `text` | Output format: `text`, `json`, `table`. | | `--output` | `-o` | | Save output to file. | | `--configFile ` | | | Use a specific configuration file. | | `--dryRun` | | `false` | Generate without calling providers (returns mocked analytics/evaluation). | | `--noColor` | | `false` | Disable ANSI colours. | | `--delay ` | | | Delay between batched operations. | | `--domain ` | `-d` | | Domain type for specialized processing and optimization. | | `--toolUsageContext ` | | | Describe expected tool usage for better evaluation feedback. | | `--debug` | `-v`, `--verbose` | `false` | Enable debug mode with verbose output. | | `--quiet` | `-q` | `true` | Suppress non-essential output. | | `--timeout` | | `120` | Maximum execution time in seconds. | | `--disableTools` | | `false` | Disable MCP tool integration. | | `--enableAnalytics` | | `false` | Enable usage analytics collection. | | `--enableEvaluation` | | `false` | Enable AI response quality evaluation. | | `--region` | `-r` | | Vertex AI region (e.g., `us-central1`). | ## JSON-Friendly Automation - `--format json` returns structured output including analytics, evaluation, tool calls, and response metadata. - Combine with `--enableAnalytics --enableEvaluation` to capture usage costs and quality scores in automation pipelines. - Use `--output ` to persist raw responses alongside JSON logs. ## rag \ Document processing and RAG pipeline commands. | Subcommand | Description | | ---------- | ------------------------------------------- | | `chunk` | Chunk a document using a specified strategy | | `index` | Index documents into a vector store | | `query` | Query indexed documents | ### rag chunk Chunk a document file into smaller pieces for RAG processing. ```bash neurolink rag chunk [options] ``` | Option | Alias | Type | Default | Description | | ------------ | ----- | ------- | ----------- | --------------------------------------------------- | | `--strategy` | `-s` | string | `recursive` | Chunking strategy | | `--maxSize` | `-m` | number | `1000` | Maximum chunk size | | `--overlap` | `-o` | number | `200` | Overlap between chunks | | `--format` | `-f` | string | `text` | Output format: `text`, `json`, `table` | | `--output` | | string | stdout | Output file path | | `--extract` | `-e` | boolean | `false` | Extract metadata (title, summary, keywords) via LLM | | `--provider` | `-p` | string | | Provider for semantic chunking/metadata extraction | | `--model` | | string | | Model for semantic chunking/metadata extraction | | `--verbose` | `-v` | boolean | `false` | Enable verbose output | **Chunking Strategies:** `character`, `recursive`, `sentence`, `token`, `markdown`, `html`, `json`, `latex`, `semantic`, `semantic-markdown` **Examples:** ```bash # Default chunking neurolink rag chunk ./docs/guide.md # Markdown-aware chunking with JSON output neurolink rag chunk ./docs/guide.md --strategy markdown --format json # Custom size and overlap neurolink rag chunk ./docs/guide.md --maxSize 512 --overlap 50 --output chunks.json # Extract metadata with LLM neurolink rag chunk ./docs/guide.md --extract --provider openai --verbose ``` ### rag index Index a document for semantic search with vector embeddings. ```bash neurolink rag index [options] ``` | Option | Alias | Type | Default | Description | | ------------- | ----- | ------- | ----------- | ----------------------- | | `--indexName` | `-n` | string | filename | Name for the index | | `--strategy` | `-s` | string | auto-detect | Chunking strategy | | `--maxSize` | `-m` | number | `1000` | Maximum chunk size | | `--overlap` | `-o` | number | `200` | Overlap between chunks | | `--provider` | `-p` | string | auto | Provider for embeddings | | `--model` | | string | | Model for embeddings | | `--graph` | `-g` | boolean | `false` | Build Graph RAG index | | `--verbose` | `-v` | boolean | `false` | Enable verbose output | **Examples:** ```bash # Index a document with default settings neurolink rag index ./docs/guide.md # Index with a custom name and Graph RAG neurolink rag index ./docs/guide.md --indexName my-docs --graph # Index with specific provider and verbose output neurolink rag index ./docs/api.md --provider openai --verbose ``` ### rag query Query indexed documents using vector, hybrid, or Graph RAG search. ```bash neurolink rag query [options] ``` | Option | Alias | Type | Default | Description | | ------------- | ----- | ------- | ------- | -------------------------------------- | | `--indexName` | `-n` | string | | Name of the index to query | | `--topK` | `-k` | number | `5` | Number of results to return | | `--hybrid` | `-h` | boolean | `false` | Use hybrid search (vector + BM25) | | `--graph` | `-g` | boolean | `false` | Use Graph RAG search | | `--provider` | `-p` | string | auto | Provider for embeddings | | `--model` | | string | | Model for embeddings | | `--format` | `-f` | string | `text` | Output format: `text`, `json`, `table` | | `--verbose` | `-v` | boolean | `false` | Enable verbose output | **Examples:** ```bash # Basic vector search neurolink rag query "How does authentication work?" # Hybrid search with more results neurolink rag query "API endpoints" --hybrid --topK 10 # Graph RAG search with JSON output neurolink rag query "architecture overview" --graph --format json # Query a specific index neurolink rag query "chunking strategies" --indexName my-docs --verbose ``` ### RAG Flags on generate/stream RAG can also be used directly with `generate` and `stream` commands via `--rag-files`: ```bash neurolink generate "What is this about?" --rag-files ./docs/guide.md neurolink stream "Summarize" --rag-files ./docs/a.md ./docs/b.md --rag-top-k 10 ``` | Flag | Type | Default | Description | | --------------------- | -------- | ------------- | ----------------------------------- | | `--rag-files` | string[] | - | File paths to load for RAG context | | `--rag-strategy` | string | auto-detected | Chunking strategy for RAG documents | | `--rag-chunk-size` | number | 1000 | Maximum chunk size in characters | | `--rag-chunk-overlap` | number | 200 | Overlap between adjacent chunks | | `--rag-top-k` | number | 5 | Number of top results to retrieve | --- ## workflow \ Manage and execute AI workflows (consensus, fallback, adaptive, multi-judge). ```bash # List available predefined workflows npx @juspay/neurolink workflow list # Show details of a specific workflow npx @juspay/neurolink workflow info consensus-3 # Execute a workflow with a prompt npx @juspay/neurolink workflow execute consensus-3 "Compare approaches to caching" ``` **Subcommands:** | Subcommand | Description | | ------------------------- | ----------------------------------- | | `list` | List available predefined workflows | | `info ` | Show details of a workflow | | `execute ` | Execute a workflow with a prompt | **`workflow execute` flags:** | Option | Type | Default | Description | | ------------ | ------- | ------- | --------------------------------- | | `--provider` | string | | Override AI provider | | `--model` | string | | Override model name | | `--timeout` | number | | Execution timeout in milliseconds | | `--verbose` | boolean | `false` | Enable verbose output | **Examples:** ```bash # Execute with provider override npx @juspay/neurolink workflow execute adaptive-quality "Deep analysis of microservices" \ --provider openai --model gpt-4o --verbose # Execute with timeout npx @juspay/neurolink workflow execute fallback-fast "Translate to Spanish" --timeout 30000 ``` --- ## observability \ Observability and telemetry management. Aliases: `obs`, `otel`. ```bash # Show telemetry and observability status npx @juspay/neurolink observability status # Show metrics summary npx @juspay/neurolink obs metrics --detailed # Show cost breakdown npx @juspay/neurolink observability costs --by-model ``` **Subcommands:** | Subcommand | Alias | Description | | ---------- | ------ | --------------------------------------- | | `status` | | Show telemetry and observability status | | `metrics` | | Show metrics summary | | `costs` | `cost` | Show cost breakdown | **Shared flags (all subcommands):** | Option | Alias | Type | Default | Description | | ---------- | ----- | ------- | ------- | -------------------------------------- | | `--format` | `-f` | string | `text` | Output format: `text`, `json`, `table` | | `--quiet` | `-q` | boolean | `false` | Minimal output | **`metrics` flags:** | Option | Alias | Type | Default | Description | | ------------ | ----- | ------- | ------- | ------------------------------------------- | | `--detailed` | `-d` | boolean | `false` | Show detailed metrics including percentiles | **`costs` flags:** | Option | Alias | Type | Default | Description | | --------------- | ----- | ------- | ------- | ------------------------------- | | `--by-model` | `-m` | boolean | `true` | Show cost breakdown by model | | `--by-provider` | `-p` | boolean | `true` | Show cost breakdown by provider | --- ## telemetry \ Telemetry management. Alias: `tel`. Tracing is configured through `LANGFUSE_*` environment variables. ```bash # Show telemetry status and health npx @juspay/neurolink telemetry status # Flush pending spans to exporters npx @juspay/neurolink telemetry flush # Show token usage and cost statistics npx @juspay/neurolink telemetry stats --detailed ``` **Subcommands:** | Subcommand | Aliases | Description | | ---------- | ------- | ------------------------------------ | | `status` | | Show telemetry status and health | | `flush` | | Flush all pending spans | | `stats` | | Show token usage and cost statistics | **Shared flags (all subcommands):** | Option | Alias | Type | Default | Description | | ---------- | ----- | ------- | ------- | -------------------------------------- | | `--format` | `-f` | string | `text` | Output format: `text`, `json`, `table` | | `--quiet` | `-q` | boolean | `false` | Minimal output | **`flush` flags:** | Option | Alias | Type | Default | Description | | ----------- | ----- | ------ | ------- | ----------------------- | | `--timeout` | `-t` | number | `30000` | Timeout in milliseconds | **`stats` flags:** | Option | Alias | Type | Default | Description | | --------------- | ----- | ------- | ------- | -------------------------- | | `--detailed` | `-d` | boolean | `false` | Show detailed statistics | | `--by-model` | `-m` | boolean | `true` | Show breakdown by model | | `--by-provider` | `-p` | boolean | `true` | Show breakdown by provider | --- ## docs Start the NeuroLink documentation MCP server. ```bash # Start docs server with stdio transport (default) npx @juspay/neurolink docs # Start docs server with HTTP transport on custom port npx @juspay/neurolink docs --transport http --port 3001 ``` | Option | Alias | Type | Default | Description | | ------------- | ----- | ------ | ------- | ------------------------------------------------------ | | `--transport` | `-t` | string | `stdio` | Transport protocol: `stdio` (local) or `http` (remote) | | `--port` | `-p` | number | `3001` | Port for HTTP transport (ignored for stdio) | **Note:** Requires the docs site to be built first (`cd docs-site && pnpm build`). The server exposes documentation search and retrieval tools via MCP. --- ## Troubleshooting | Issue | Tip | | ---------------------------------- | -------------------------------------------------------------------------------------------------------- | | `Unknown argument` | Check spelling; run `command --help` for the latest options. | | CLI exits immediately | Upgrade to the newest release or clear old `neurolink` binaries on PATH. | | Provider shows as `not-configured` | Run `neurolink setup --provider ` or populate `.env`. | | Analytics/evaluation missing | Ensure both `--enableAnalytics`/`--enableEvaluation` and provider credentials for the judge model exist. | For advanced workflows (batching, tooling, configuration management) see the relevant guides in the documentation sidebar. --- ## Related Features **Q4 2025:** - [CLI Loop Sessions](/docs/features/cli-loop-sessions) – Persistent interactive mode with session management - [Redis Conversation Export](/docs/features/conversation-history) – Export session history via `memory export` - [Guardrails Middleware](/docs/features/guardrails) – Content filtering (the CLI reads `NEUROLINK_MIDDLEWARE_PRESET`; it has no word-list option) **Q3 2025:** - [Multimodal Chat](/docs/features/multimodal-chat) – Use `--image` flag with `generate` or `stream` - [Auto Evaluation](/docs/features/auto-evaluation) – Enable with `--enableEvaluation` - [Provider Orchestration](/docs/features/provider-orchestration) – Automatic fallback and routing **Documentation:** - [SDK API Reference](/docs/sdk/api-reference) – TypeScript API equivalents - [Configuration Guide](/docs/deployment/configuration) – Environment variables and config files - [Troubleshooting](/docs/reference/troubleshooting) – Detailed error solutions --- ## CLI Guide # CLI Guide The NeuroLink CLI provides a professional command-line interface for AI text generation, provider management, and workflow automation. ## Overview The CLI is designed for: - **Developers** who want to integrate AI into scripts and workflows - **Content creators** who need quick AI text generation - **System administrators** who manage AI provider configurations - **Researchers** who experiment with different AI models and providers ## Quick Reference ```bash # Text generation (primary commands) neurolink generate "Your prompt here" neurolink gen "Your prompt" # Short form # Real-time streaming neurolink stream "Tell me a story" # Provider management neurolink status # Check all providers neurolink provider status --verbose # Detailed diagnostics ``` ```bash # With analytics and evaluation neurolink generate "Write code" --enable-analytics --enable-evaluation # Custom provider and model neurolink gen "Explain AI" --provider openai --model gpt-4 # Batch processing from a file neurolink batch prompts.txt # Output to file neurolink generate "Documentation" --output result.md ``` ```bash # Built-in tools (working) neurolink generate "What time is it?" --debug # Disable tools neurolink generate "Pure text" --disable-tools # MCP server management neurolink mcp discover neurolink mcp list neurolink mcp install ``` ```bash # Start server in foreground neurolink serve --port 3000 --framework hono # Background server management neurolink server start --port 8080 neurolink server status neurolink server stop # Claude proxy + local telemetry neurolink proxy setup neurolink proxy status neurolink proxy telemetry setup neurolink proxy telemetry status # View and manage routes neurolink server routes neurolink server routes --group agent --format json # Configuration management neurolink server config neurolink server config --set defaultPort=8080 ``` ## Documentation Sections - **[Commands Reference](/docs/cli/commands)** — Complete reference for all CLI commands, options, and parameters with detailed explanations. - **[Examples](/docs/examples)** — Practical examples and common usage patterns for different scenarios and workflows. - **[Advanced Usage](/docs/advanced)** — Advanced features like batch processing, streaming, analytics, and custom configurations. - **[Claude Proxy](/docs/features/claude-proxy)** — Multi-account Claude proxy setup, lifecycle commands, routing, and local service management. - **[Claude Proxy Observability](/docs/features/claude-proxy-observability)** — Local OpenObserve stack setup, dashboard import, and how to read proxy logs, traces, and metrics. ## Installation The CLI requires no installation for basic usage: ```bash # Direct usage (recommended) npx @juspay/neurolink generate "Hello, AI" # Global installation (optional) npm install -g @juspay/neurolink neurolink generate "Hello, AI" ``` ## Configuration The CLI automatically loads configuration from: 1. **Environment variables** (`.env` file) 2. **Command-line options** 3. **Auto-detection** of available providers ```bash # Create .env file echo 'OPENAI_API_KEY="sk-your-key"' > .env echo 'GOOGLE_AI_API_KEY="AIza-your-key"' >> .env # Test configuration neurolink status ``` ## Interactive Features The CLI includes several interactive and automation features: :::tip[Auto-Provider Selection] NeuroLink automatically selects the best available provider based on configuration and performance. ::: :::info[Built-in Tools] All commands include 6 built-in tools by default: time, file operations, math calculations, and more. ::: :::note[Streaming Support] Real-time streaming displays results as they're generated, perfect for long-form content. ::: ## Integration The CLI works seamlessly with: - **Shell scripts** and automation - **CI/CD pipelines** for automated content generation - **Git hooks** for documentation updates - **Cron jobs** for scheduled AI tasks ## Getting Help ```bash # General help neurolink --help # Command-specific help neurolink generate --help neurolink mcp --help # Check provider status neurolink status --verbose ``` For troubleshooting, see our [Troubleshooting Guide](/docs/reference/troubleshooting) or [FAQ](/docs/reference/faq). --- ## Advanced CLI Usage # Advanced CLI Usage Power user features, optimization techniques, and advanced workflows for the NeuroLink CLI. ## Advanced Generation Techniques ### Multi-Provider Strategies ```bash # Provider fallback chain generate_with_fallback() { local prompt="$1" local providers=("google-ai" "openai" "anthropic") for provider in "${providers[@]}"; do if result=$(npx @juspay/neurolink gen "$prompt" --provider $provider 2>/dev/null); then echo "✅ Success with $provider" echo "$result" return 0 fi done echo "❌ All providers failed" return 1 } # Usage generate_with_fallback "Complex technical analysis" ``` ### Dynamic Provider Selection ```bash # Select provider based on task type select_provider_by_task() { local task_type="$1" case $task_type in "code") echo "anthropic" # Best for code analysis ;; "creative") echo "openai" # Best for creative content ;; "fast") echo "google-ai" # Fastest responses ;; *) echo "auto" # Let NeuroLink decide ;; esac } # Usage provider=$(select_provider_by_task "code") npx @juspay/neurolink gen "Write a Python class" --provider $provider ``` ## Analytics and Monitoring ### Advanced Analytics Usage ```bash # Context-aware analytics npx @juspay/neurolink gen "Design microservices architecture" \ --enable-analytics \ --context '{ "user_id": "dev123", "project": "ecommerce-platform", "team": "backend", "environment": "development", "session_id": "sess_456" }' \ --debug # Business intelligence tracking npx @juspay/neurolink gen "Create marketing strategy" \ --enable-analytics \ --enable-evaluation \ --evaluation-domain "Marketing Director" \ --context '{ "department": "marketing", "campaign": "Q1-launch", "budget": "high", "target_audience": "enterprise" }' \ --debug ``` ### Performance Monitoring ```bash # Provider performance comparison compare_providers() { local prompt="$1" local providers=("openai" "google-ai" "anthropic") echo " Comparing provider performance..." echo "Prompt: $prompt" echo for provider in "${providers[@]}"; do echo "Testing $provider..." start_time=$(date +%s%N) result=$(npx @juspay/neurolink gen "$prompt" \ --provider $provider \ --enable-analytics \ --debug 2>/dev/null) end_time=$(date +%s%N) duration=$(( (end_time - start_time) / 1000000 )) echo "✅ $provider: ${duration}ms" echo done } # Usage compare_providers "Explain quantum computing briefly" ``` ### Real-time Monitoring Dashboard ```bash #!/bin/bash # provider-dashboard.sh - Real-time provider monitoring monitor_providers() { while true; do clear echo " NeuroLink Provider Dashboard" echo "===============================" date echo # Check provider status status=$(npx @juspay/neurolink status --json 2>/dev/null) if [ $? -eq 0 ]; then echo " Provider Status:" echo "$status" | jq -r '.[] | " \(.name): \(.status) (\(.responseTime)ms)"' # Count working providers working=$(echo "$status" | jq '[.[] | select(.status == "working")] | length') total=$(echo "$status" | jq 'length') echo echo " Summary: $working/$total providers working" else echo "❌ Failed to get provider status" fi echo echo "Press Ctrl+C to exit" sleep 30 done } # Run monitoring monitor_providers ``` ## Configuration Management ### Advanced Configuration ```bash # Environment-specific configs setup_environment() { local env="$1" case $env in "development") export NEUROLINK_LOG_LEVEL="debug" export NEUROLINK_CACHE_ENABLED="false" export NEUROLINK_TIMEOUT="60000" ;; "staging") export NEUROLINK_LOG_LEVEL="info" export NEUROLINK_CACHE_ENABLED="true" export NEUROLINK_TIMEOUT="30000" ;; "production") export NEUROLINK_LOG_LEVEL="warn" export NEUROLINK_CACHE_ENABLED="true" export NEUROLINK_TIMEOUT="15000" export NEUROLINK_ANALYTICS_ENABLED="true" ;; esac echo "✅ Environment set to: $env" } # Usage setup_environment "production" npx @juspay/neurolink gen "Production prompt" ``` ### Dynamic Configuration ```bash # Load configuration from external source load_remote_config() { local config_url="$1" # Fetch configuration config=$(curl -s "$config_url") if [ $? -eq 0 ]; then # Export environment variables echo "$config" | jq -r 'to_entries[] | "export \(.key)=\(.value)"' | source /dev/stdin echo "✅ Configuration loaded from $config_url" else echo "❌ Failed to load configuration" return 1 fi } # Usage (example) # load_remote_config "https://config.company.com/neurolink.json" ``` ## Specialized Workflows ### Code Analysis Pipeline ```bash #!/bin/bash # code-analyzer.sh - Comprehensive code analysis analyze_codebase() { local project_path="$1" local output_dir="$2" mkdir -p "$output_dir" echo " Analyzing codebase at: $project_path" # Find code files find "$project_path" -name "*.ts" -o -name "*.js" -o -name "*.py" | while read file; do echo "Analyzing: $file" # Code review npx @juspay/neurolink gen " Perform comprehensive code review: 1. Code quality and best-practice adherence 2. Security vulnerabilities 3. Performance optimizations 4. Maintainability improvements File: $(basename $file) " --enable-evaluation \ --evaluation-domain "Senior Software Architect" \ --context "{\"file\":\"$file\",\"project\":\"$project_path\"}" \ > "$output_dir/review-$(basename $file).md" # Generate tests npx @juspay/neurolink gen " Generate comprehensive unit tests for this code. Include edge cases and error scenarios. File: $(basename $file) " --provider anthropic \ > "$output_dir/tests-$(basename $file).md" sleep 2 # Rate limiting done echo "✅ Analysis complete. Results in: $output_dir" } # Usage # analyze_codebase "./src" "./analysis-results" ``` ### Documentation Generation Pipeline ```bash #!/bin/bash # docs-generator.sh - Automated documentation generation generate_project_docs() { local project_path="$1" local docs_dir="$2" mkdir -p "$docs_dir" echo " Generating documentation for: $project_path" # API documentation npx @juspay/neurolink gen " Generate comprehensive API documentation for this project. Include: - Endpoint descriptions - Request/response examples - Authentication methods - Error codes and handling Project path: $project_path " --enable-analytics \ --context "{\"project\":\"$project_path\",\"type\":\"api-docs\"}" \ --max-tokens 2000 \ > "$docs_dir/api-reference.md" # User guide npx @juspay/neurolink gen " Create a comprehensive user guide for this project. Include: - Getting started - Installation instructions - Usage examples - Troubleshooting Project path: $project_path " --enable-evaluation \ --evaluation-domain "Technical Writer" \ --max-tokens 1500 \ > "$docs_dir/user-guide.md" # Developer guide npx @juspay/neurolink gen " Write a developer guide for contributing to this project. Include: - Development setup - Architecture overview - Coding standards - Testing guidelines Project path: $project_path " --provider anthropic \ --max-tokens 1500 \ > "$docs_dir/developer-guide.md" echo "✅ Documentation generated in: $docs_dir" } # Usage # generate_project_docs "./my-project" "./docs" ``` ## Batch Processing Optimization ### Parallel Processing ```bash # parallel-batch.sh - Optimized batch processing parallel_generate() { local prompts_file="$1" local max_jobs="${2:-4}" local output_dir="${3:-./results}" mkdir -p "$output_dir" echo " Processing prompts in parallel (max jobs: $max_jobs)" # Use GNU parallel for concurrent processing cat "$prompts_file" | parallel -j "$max_jobs" --line-buffer \ 'echo "Processing: {}" && npx @juspay/neurolink gen "{}" \ --enable-analytics \ --json > "'"$output_dir"'/result-{#}.json" && echo "✅ Completed: {}"' echo "✅ All prompts processed. Results in: $output_dir" } # Usage # parallel_generate "prompts.txt" 6 "./batch-results" ``` ### Smart Rate Limiting ```bash # rate-limited-batch.sh - Intelligent rate limiting smart_batch_process() { local prompts_file="$1" local provider="$2" local output_file="${3:-batch-results.json}" echo " Smart batch processing with $provider" # Determine optimal delay based on provider case $provider in "openai") delay=3000 # Conservative for OpenAI rate limits ;; "google-ai") delay=1000 # Google AI has generous limits ;; "anthropic") delay=2000 # Moderate delay for Claude ;; *) delay=2000 # Default safe delay ;; esac echo "Using ${delay}ms delay between requests" # Process with adaptive delay npx @juspay/neurolink batch "$prompts_file" \ --provider "$provider" \ --delay "$delay" \ --output "$output_file" \ --enable-analytics echo "✅ Batch processing complete" } # Usage # smart_batch_process "prompts.txt" "google-ai" "results.json" ``` ## Security and Compliance ### Secure API Key Management ```bash # secure-setup.sh - Secure configuration management setup_secure_environment() { local env="$1" # Use external secret management case $env in "aws") echo " Loading secrets from AWS Secrets Manager" export OPENAI_API_KEY=$(aws secretsmanager get-secret-value \ --secret-id openai-api-key \ --query SecretString --output text) export GOOGLE_AI_API_KEY=$(aws secretsmanager get-secret-value \ --secret-id google-ai-api-key \ --query SecretString --output text) ;; "azure") echo " Loading secrets from Azure Key Vault" export OPENAI_API_KEY=$(az keyvault secret show \ --name openai-key --vault-name my-vault \ --query value -o tsv) ;; "gcp") echo " Loading secrets from Google Secret Manager" export OPENAI_API_KEY=$(gcloud secrets versions access latest \ --secret="openai-api-key") ;; *) echo "❌ Unknown secret management system: $env" return 1 ;; esac echo "✅ Secure environment configured" } # Usage # setup_secure_environment "aws" ``` ### Audit Logging ```bash # audit-logger.sh - Comprehensive audit logging audit_generate() { local prompt="$1" local provider="$2" local user_id="${3:-unknown}" # Create audit log entry local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ") local session_id=$(uuidgen) echo " Audit Log Entry:" echo " Timestamp: $timestamp" echo " Session ID: $session_id" echo " User ID: $user_id" echo " Provider: $provider" echo " Prompt length: ${#prompt} characters" # Execute with audit context result=$(npx @juspay/neurolink gen "$prompt" \ --provider "$provider" \ --enable-analytics \ --context "{ \"audit\": { \"timestamp\": \"$timestamp\", \"session_id\": \"$session_id\", \"user_id\": \"$user_id\" } }" \ --debug) # Log the result echo "✅ Generation complete - Session: $session_id" echo "$result" # Store audit record echo "{ \"timestamp\": \"$timestamp\", \"session_id\": \"$session_id\", \"user_id\": \"$user_id\", \"provider\": \"$provider\", \"prompt_length\": ${#prompt}, \"status\": \"success\" }" >> audit.log } # Usage # audit_generate "Generate report" "openai" "user123" ``` ## Performance Optimization ### Caching Strategies ```bash # cache-manager.sh - Advanced caching for repeated prompts cached_generate() { local prompt="$1" local provider="$2" local cache_dir="${3:-.neurolink-cache}" mkdir -p "$cache_dir" # Create cache key local cache_key=$(echo -n "$prompt|$provider" | sha256sum | cut -d' ' -f1) local cache_file="$cache_dir/$cache_key.json" # Check cache if [ -f "$cache_file" ] && [ $(($(date +%s) - $(stat -c %Y "$cache_file"))) -lt 3600 ]; then echo " Cache hit for prompt" cat "$cache_file" | jq -r '.content' return 0 fi # Generate and cache echo " Generating and caching..." result=$(npx @juspay/neurolink gen "$prompt" \ --provider "$provider" \ --json) if [ $? -eq 0 ]; then echo "$result" > "$cache_file" echo "$result" | jq -r '.content' echo "✅ Result cached" else echo "❌ Generation failed" return 1 fi } # Usage # cached_generate "Explain caching" "openai" ".cache" ``` ### Connection Pooling ```bash # connection-pool.sh - Manage provider connections efficiently manage_provider_pool() { local action="$1" case $action in "warm-up") echo " Warming up provider connections..." # Pre-warm connections with simple prompts npx @juspay/neurolink gen "Hello" --provider openai & npx @juspay/neurolink gen "Hello" --provider google-ai & npx @juspay/neurolink gen "Hello" --provider anthropic & wait echo "✅ Provider pool warmed up" ;; "health-check") echo " Checking provider health..." npx @juspay/neurolink status --verbose ;; "reset") echo " Resetting provider connections..." # Implementation depends on your provider management echo "✅ Provider pool reset" ;; *) echo "Usage: manage_provider_pool {warm-up|health-check|reset}" ;; esac } # Usage # manage_provider_pool "warm-up" ``` ## Custom Tool Development ### MCP Server Integration ```bash # mcp-workflow.sh - Custom MCP server integration setup_custom_mcp() { local server_name="$1" local server_command="$2" echo " Setting up custom MCP server: $server_name" # Add server to configuration npx @juspay/neurolink mcp add "$server_name" "$server_command" # Test server connectivity if npx @juspay/neurolink mcp test "$server_name"; then echo "✅ MCP server $server_name is working" # List available tools echo "️ Available tools:" npx @juspay/neurolink mcp list --server "$server_name" else echo "❌ MCP server $server_name failed to start" return 1 fi } # Usage # setup_custom_mcp "filesystem" "npx @modelcontextprotocol/server-filesystem /" ``` ### Tool Chain Automation ```bash # tool-chain.sh - Automated tool chain execution execute_tool_chain() { local workflow_file="$1" echo "⚙️ Executing tool chain workflow: $workflow_file" # Read workflow configuration if [ ! -f "$workflow_file" ]; then echo "❌ Workflow file not found: $workflow_file" return 1 fi # Process each step jq -c '.steps[]' "$workflow_file" | while read step; do local tool=$(echo "$step" | jq -r '.tool') local prompt=$(echo "$step" | jq -r '.prompt') local params=$(echo "$step" | jq -r '.params // "{}"') echo " Executing step: $tool" # Execute tool via NeuroLink npx @juspay/neurolink gen "$prompt" \ --enable-analytics \ --context "$params" \ --debug echo "✅ Step completed: $tool" sleep 1 done echo "✅ Tool chain execution complete" } # Example workflow.json: # { # "steps": [ # { # "tool": "analyzer", # "prompt": "Analyze the codebase structure", # "params": {"path": "./src"} # }, # { # "tool": "documenter", # "prompt": "Generate API documentation", # "params": {"format": "markdown"} # } # ] # } # Usage # execute_tool_chain "workflow.json" ``` ## Metrics and Reporting ### Advanced Reporting ```bash # metrics-reporter.sh - Comprehensive metrics reporting generate_usage_report() { local period="${1:-daily}" local output_file="${2:-usage-report.md}" echo " Generating $period usage report..." # Analyze usage patterns npx @juspay/neurolink gen " Generate a comprehensive usage report based on these analytics: Period: $period Report type: Executive summary Include: - Usage trends and patterns - Provider performance comparison - Cost analysis and optimization recommendations - Key insights and recommendations Format as professional markdown report. " --enable-analytics \ --evaluation-domain "Data Analyst" \ --max-tokens 2000 \ > "$output_file" echo "✅ Usage report generated: $output_file" } # Usage # generate_usage_report "weekly" "weekly-report.md" ``` ## Specialized Use Cases ### CI/CD Integration ```bash # ci-cd-integration.sh - Advanced CI/CD workflows run_ai_quality_gate() { local commit_hash="$1" local threshold="${2:-8}" echo " Running AI quality gate for commit: $commit_hash" # Get changed files changed_files=$(git diff --name-only HEAD~1) # Analyze changes quality_score=$(npx @juspay/neurolink gen " Analyze these code changes for quality score (1-10): Commit: $commit_hash Changed files: $changed_files Evaluate: - Code quality and best-practice compliance - Test coverage adequacy - Documentation completeness - Security considerations Respond only with numeric score (1-10). " --enable-evaluation \ --evaluation-domain "Senior Code Reviewer" \ --max-tokens 10 | grep -o '[0-9]' | head -1) echo " Quality score: $quality_score/10" if [ "$quality_score" -ge "$threshold" ]; then echo "✅ Quality gate passed" exit 0 else echo "❌ Quality gate failed (score: $quality_score, threshold: $threshold)" exit 1 fi } # Usage in CI pipeline # run_ai_quality_gate "$GITHUB_SHA" 7 ``` ### Content Management System ```bash # cms-integration.sh - AI-powered content management manage_content() { local action="$1" local content_type="$2" local target="${3:-.}" case $action in "generate") echo " Generating $content_type content..." case $content_type in "blog-post") npx @juspay/neurolink gen " Write a professional blog post about AI development tools. Include: introduction, key benefits, use cases, conclusion. Target audience: Software developers and engineering managers. Tone: Professional but approachable. Length: 800-1000 words. " --enable-evaluation \ --evaluation-domain "Content Marketing Manager" \ > "$target/blog-post-$(date +%Y%m%d).md" ;; "documentation") npx @juspay/neurolink gen " Create comprehensive API documentation. Include: authentication, endpoints, examples, error handling. Format: OpenAPI 3.0 specification. " --provider anthropic \ > "$target/api-docs-$(date +%Y%m%d).yaml" ;; "social-media") npx @juspay/neurolink gen " Create 5 social media posts about AI automation. Platforms: Twitter, LinkedIn. Include relevant hashtags. Tone: Engaging and informative. " > "$target/social-content-$(date +%Y%m%d).txt" ;; esac ;; "review") echo " Reviewing existing content..." find "$target" -name "*.md" -o -name "*.txt" | while read file; do npx @juspay/neurolink gen " Review this content for: - Clarity and readability - Technical accuracy - SEO optimization - Engagement potential Provide specific improvement recommendations. " --enable-evaluation \ --evaluation-domain "Content Editor" \ > "${file%.md}-review.md" done ;; esac } # Usage # manage_content "generate" "blog-post" "./content" # manage_content "review" "" "./content" ``` This advanced CLI usage guide provides sophisticated patterns and techniques for power users who want to maximize the capabilities of NeuroLink CLI in production environments. ## Related Documentation - [CLI Commands Reference](/docs/cli/commands) - Complete command documentation - [CLI Examples](/docs/examples) - Practical usage examples - [Environment Variables](/docs/getting-started/environment-variables) - Configuration - [SDK Advanced Features](/docs/sdk/advanced-features) - Programmatic equivalents - [Troubleshooting](/docs/reference/troubleshooting) - Common issues --- ## CLI Examples # CLI Examples Practical examples and usage patterns for the NeuroLink CLI. ## Quick Start Examples ### Basic Text Generation ```bash # Simple generation npx @juspay/neurolink gen "Write a Python function to reverse a string" # With specific provider npx @juspay/neurolink gen "Explain quantum computing" --provider google-ai # Creative writing with high temperature npx @juspay/neurolink gen "Write a short poem about AI" --temperature 0.9 ``` ### Provider Testing ```bash # Check all providers npx @juspay/neurolink status # Test specific provider npx @juspay/neurolink gen "Hello" --provider openai # Find best available provider npx @juspay/neurolink get-best-provider ``` ## Development Workflows ### Code Generation ```bash # Generate TypeScript interfaces npx @juspay/neurolink gen " Create TypeScript interfaces for: - User profile with id, name, email - API response with data, status, message " # Generate test cases npx @juspay/neurolink gen " Write Jest test cases for a function that calculates compound interest. Include edge cases and error handling. " --provider anthropic ``` ### Documentation Generation ```bash # Generate API documentation npx @juspay/neurolink gen " Create API documentation for a REST endpoint that: - Accepts POST requests to /api/users - Creates new user accounts - Returns user ID and status " --max-tokens 1000 # Generate README sections npx @juspay/neurolink gen " Write a 'Getting Started' section for a Node.js CLI tool that processes CSV files. Include installation and basic usage. " ``` ## Business Use Cases ### Content Creation ```bash # Marketing copy npx @juspay/neurolink gen " Write compelling product description for an AI development platform that supports multiple providers and has built-in tools. " --temperature 0.8 # Email templates npx @juspay/neurolink gen " Create a professional email template for announcing new API features to enterprise customers. " # Social media content npx @juspay/neurolink gen " Write 3 Twitter posts about AI automation benefits for software development teams. Keep under 280 characters each. " ``` ### Business Analysis ```bash # Market research npx @juspay/neurolink gen " Analyze the current trends in AI development tools. Focus on developer experience and enterprise adoption. " --provider anthropic --max-tokens 1500 # Competitive analysis npx @juspay/neurolink gen " Compare the advantages of multi-provider AI platforms versus single-provider solutions for enterprise use. " ``` ## Batch Processing ### Content Pipeline ```bash # Create prompts file cat > content-prompts.txt review-prompts.txt docs/api.md", "ai:test": "npx @juspay/neurolink status", "ai:review": "npx @juspay/neurolink gen 'Review this codebase for improvements' --provider anthropic" } } ``` ### GitHub Actions ```yaml name: AI Documentation on: [push] jobs: docs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Generate docs run: | npx @juspay/neurolink gen "Create changelog for latest changes" > CHANGELOG.md env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - name: Commit docs run: | git config --local user.email "action@github.com" git config --local user.name "GitHub Action" git add CHANGELOG.md git commit -m "Update AI-generated changelog" || exit 0 git push ``` ## Production Workflows ### Content Management ```bash # Daily content generation #!/bin/bash DATE=$(date +"%Y-%m-%d") # Generate daily summary npx @juspay/neurolink gen " Create a daily engineering summary for $DATE. Include: progress updates, blockers, next steps. " --enable-analytics > reports/daily-$DATE.md # Generate team updates npx @juspay/neurolink gen " Write team update email template for weekly standup. Include sections for achievements, challenges, goals. " > templates/weekly-update.md ``` ### Code Review Pipeline ```bash #!/bin/bash # AI-assisted code review # Get changed files files=$(git diff --name-only HEAD~1) # Review each file for file in $files; do if [[ $file == *.ts ]] || [[ $file == *.js ]]; then echo "Reviewing $file..." npx @juspay/neurolink gen " Review this code for: - Best practices - Security issues - Performance optimizations - Maintainability File: $file " --enable-evaluation \ --evaluation-domain "Senior Code Reviewer" \ > reviews/review-$(basename $file).md fi done ``` ### Monitoring and Alerts ```bash #!/bin/bash # Provider health monitoring status=$(npx @juspay/neurolink status --json) working=$(echo $status | jq '[.[] | select(.status == "working")] | length') total=$(echo $status | jq 'length') if [ $working -lt $total ]; then # Generate alert message alert=$(npx @juspay/neurolink gen " Create alert message: $working out of $total AI providers are working. Include impact assessment and recommended actions. " --max-tokens 200) # Send to monitoring system curl -X POST webhook-url -d "message=$alert" fi ``` ## Performance Optimization ### Provider Selection ```bash # Find fastest provider fastest=$(npx @juspay/neurolink get-best-provider --criteria speed) echo "Using fastest provider: $fastest" # Cost optimization cheapest=$(npx @juspay/neurolink models best --use-case cheapest) npx @juspay/neurolink gen "Budget-conscious prompt" --provider $cheapest # Quality optimization npx @juspay/neurolink gen "High-quality analysis needed" \ --provider anthropic \ --enable-evaluation \ --evaluation-domain "Expert Analyst" ``` ### Batch Optimization ```bash # Parallel processing with GNU parallel cat prompts.txt | parallel -j 4 npx @juspay/neurolink gen {} \ --provider openai \ --max-tokens 500 \ > results.txt # Rate-limited processing npx @juspay/neurolink batch prompts.txt \ --delay 5000 \ --provider google-ai \ --output batch-results.json ``` ## Error Handling ### Robust Scripts ```bash #!/bin/bash # Error-resistant AI generation generate_with_fallback() { local prompt="$1" local providers=("openai" "google-ai" "anthropic") for provider in "${providers[@]}"; do echo "Trying $provider..." if result=$(npx @juspay/neurolink gen "$prompt" --provider $provider 2>/dev/null); then echo "Success with $provider" echo "$result" return 0 else echo "Failed with $provider, trying next..." fi done echo "All providers failed" return 1 } # Usage generate_with_fallback "Write a summary of AI trends" ``` ### Timeout Handling ```bash # Long-running generation with timeout timeout 120s npx @juspay/neurolink gen " Generate comprehensive technical documentation for our API. Include: authentication, endpoints, examples, error codes. " --max-tokens 3000 || echo "Generation timed out" # Streaming with timeout timeout 60s npx @juspay/neurolink stream " Tell a long story about AI development " --provider openai || echo "Stream timed out" ``` ## Learning and Experimentation ### A/B Testing ```bash # Compare provider outputs prompt="Explain microservices architecture" echo "=== OpenAI ===" npx @juspay/neurolink gen "$prompt" --provider openai echo "=== Google AI ===" npx @juspay/neurolink gen "$prompt" --provider google-ai echo "=== Anthropic ===" npx @juspay/neurolink gen "$prompt" --provider anthropic ``` ### Temperature Experiments ```bash # Creative temperature range prompt="Write a creative product name for AI tools" for temp in 0.3 0.7 0.9; do echo "=== Temperature: $temp ===" npx @juspay/neurolink gen "$prompt" --temperature $temp echo done ``` ### Token Limit Testing ```bash # Test different response lengths prompt="Explain React hooks" for tokens in 100 500 1000; do echo "=== $tokens tokens ===" npx @juspay/neurolink gen "$prompt" --max-tokens $tokens echo done ``` ## Related Resources - [CLI Commands Reference](/docs/cli/commands) - Complete command documentation - [Advanced Usage](/docs/advanced) - Power user features - [Installation Guide](/docs/getting-started/installation) - Setup instructions - [Environment Variables](/docs/getting-started/environment-variables) - Configuration - [Troubleshooting](/docs/reference/troubleshooting) - Common issues --- # Features ## Feature Guides # Feature Guides Comprehensive guides for all NeuroLink features organized by category. Each guide includes setup, usage patterns, configuration, and troubleshooting. ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **[`decide` Inference Type](/docs/features/decide-inference-type)** | A third inference type alongside `generate`/`stream`: typed, calibrated `boolean`/`choice`/`score` judgments in one parallel pass — no text. ~400ms, ~$0.00002 per decision on TypeSafe; Perplexity adds about 65 ms for each further question, up to 128 (see [its guide](/docs/getting-started/providers/perplexity-decider.md#limits)); Cloudflare Clef takes up to 64 questions and about 2,048 tokens of state (see [its guide](/docs/getting-started/providers/cloudflare-clef.md#limits)). Providers: [TypeSafe Jev](/docs/getting-started/providers/typesafe); [Laya](/docs/getting-started/providers/laya), open-weights and self-hosted; [XOR](/docs/getting-started/providers/xor), Juspay's open-weights model that also reads an image and audio and extracts typed values; [SubQ](/docs/getting-started/providers/subq), a hosted API; [Perplexity](/docs/getting-started/providers/perplexity-decider), a hosted API that also reads images; [Cloudflare Clef](/docs/getting-started/providers/cloudflare-clef), hosted on Workers AI, which also reads images; [OpenAI Decisions](/docs/getting-started/providers/openai-decisions), OpenAI's Decisions API (public beta), which also reads images; and [ScaleDown](/docs/getting-started/providers/scaledown), a hosted API that reads text only. Fail-open: a no-op when no decision provider is configured (the credentials of Perplexity, Cloudflare Clef and OpenAI Decisions are shared with their text providers; ScaleDown's is its own). | | **[Model Routing with a Decision Model](/docs/features/classifier-router-jev-strategy)** | One round trip answers difficulty, capabilities, risk, context scope **and** the model pick, with asymmetric confidence bars (0.3 up / 0.6 down). | | **[Model Catalogue](/docs/features/classifier-router-catalog)** | Ranks the 64-model registry as an addition to a host-declared pool, never a replacement. One `choice` question ranks all N candidates. | | **[Context Budget](/docs/features/context-budget)** | A per-request compaction threshold derived from how much context the request actually needs. Only ever lowers the default, never raises it. | | **[Relevance Compaction](/docs/features/relevance-compaction)** | Stage 0 of the compaction pipeline: asks which earlier messages the current request still needs, plus a quality gate on the generated summary. | | **[Tool Routing with a Decision Model](/docs/features/tool-routing-decision-model)** | One calibrated yes/no per MCP server, dropping only on a confident "no" — replaces a 15s LLM call at ~400ms on TypeSafe. | | **[RAG Retrieval Planning](/docs/features/rag-retrieval-planning)** | Per-query `topK` breadth and whether to use hybrid / graph / rerank. Opt-in via `RAGPipeline`. | | **[Real-time Voice Services](/docs/features/real-time-services)** | Bidirectional realtime voice APIs — OpenAI Realtime and Gemini Live. Full-duplex audio streaming with tool calls, barge-in, and interruption. | | **[LiveKit Voice Agent](/docs/features/livekit-voice-agent)** | WebRTC voice agent using LiveKit for the real-time loop (transport, VAD, turn-taking, worker-per-call scaling) with NeuroLink as the brain (LLM, tools, memory). Cloud or self-hosted. | | **[Provider Fallback & Model Chains](/docs/features/provider-fallback)** | `providerFallback` callback + `modelChain` config (v9.58.0) — centralized multi-provider fallback policy for resilient AI workflows. | | **[Credential Validation](/docs/features/credential-validation)** | Pre-flight `sdk.checkCredentials()` API + typed `ModelAccessDeniedError` (v9.59.0) — actionable credential errors and validation before first call. | | **[AutoResearch](/docs/features/autoresearch)** | Autonomous AI experiment engine: proposes code changes, runs experiments, evaluates metrics, keeps improvements — runs unattended for hours. | | **[MCP Enhancements](/docs/features/mcp-enhancements)** | Advanced MCP features: ToolRouter, ToolCache, RequestBatcher, tool annotations, elicitation protocol, and custom MCP server creation. | | **[PPT Generation](/docs/features/ppt-generation)** | Generate professional PowerPoint presentations from text prompts with 35 slide types, 5 themes, and optional AI images. | | **[Video Generation](/docs/features/video-generation)** | Generate videos from text prompts using RunwayML (ML5, ML6 Turbo models). | | **[Image Generation with Gemini](/docs/features/image-generation)** | Native image generation using Gemini 2.0 Flash Experimental with imagen-3.0-generate-002 model. | | **[HTTP/Streamable HTTP Transport for MCP](/docs/mcp/http-transport)** | Connect to remote MCP servers via HTTP with authentication, rate limiting, retry support, and session management. | | **[Audio Input](/docs/features/audio-input)** | Real-time voice conversations with Gemini Live and audio streaming capabilities. | | **[Server Adapters](/docs/guides/server-adapters)** | Expose NeuroLink AI agents as HTTP APIs with Hono, Express, Fastify, and Koa. Production-ready with auth, rate limiting, and streaming. | | **[RAG Document Processing](/docs/tutorials/rag)** | Comprehensive document chunking (10 strategies), hybrid search (BM25 + vector), and reranking (5 types) for retrieval-augmented generation. | | **[Context Compaction](/docs/features/context-compaction)** | 5-stage context compaction pipeline with automatic budget management, per-provider token estimation, and non-destructive message tagging. | | **[Memory](/docs/features/memory)** | Per-user condensed memory that persists across conversations. LLM-powered condensation with S3, Redis, or SQLite storage backends. | | **[Claude Subscription Support](/docs/features/claude-subscription)** | Multiple authentication methods for Claude (API key, OAuth) with support for Free, Pro, Max, and API tiers. | | **[Client SDK](/docs/features/client-sdk)** | Type-safe HTTP, SSE, and WebSocket clients with React hooks and Vercel AI SDK adapter. | | **[Proxy Accounts Endpoint](/docs/features/proxy-accounts-endpoint)** | GET /accounts: one row per account joining status, quota, and per-account token totals and API-equivalent cost. | | **[Claude Proxy](/docs/features/claude-proxy)** | Multi-account Claude proxy with OAuth pooling, rate-limit failover, token refresh, and launchd daemon for crash recovery. | | **[Proxy Peer Sharing](/docs/features/proxy-peer-sharing)** | Lend unused pool capacity to a peer's proxy with reserve floors, window slices, NeuroCoins, and instant pause or revoke. | | **[Claude Proxy Observability](/docs/features/claude-proxy-observability)** | How to set up the local OpenObserve stack for the Claude proxy and read the dashboard for traffic health, failures, account routing, cache behavior, and trace drilldown. | | **[Authentication Providers](/docs/features/authentication-providers)** | Secure AI endpoints with 11 auth providers (Auth0, Clerk, Firebase, Supabase, Cognito, Keycloak, WorkOS, Better Auth, OAuth2, JWT, Custom) with RBAC, session management, and rate limiting. | **Q1 2026 Highlights:** - **AutoResearch**: Autonomous AI experiment engine inspired by Karpathy's autoresearch. Phase-gated tool access (9 phases), git-backed safety with automatic revert, deterministic metric evaluation via regex, TaskManager integration for continuous unattended research, 12 research tools, 10 typed events, and 9 CLI subcommands - **Authentication Providers**: Pluggable multi-provider authentication system with 11 providers, per-call token validation in generate/stream, composable middleware (auth + RBAC + rate limiting), in-memory and Redis session storage, AsyncLocalStorage context propagation, and CLI management commands - **MCP Enhancements**: Advanced MCP features including intelligent tool routing (round-robin, least-loaded, capability-based), result caching with LRU/FIFO/LFU eviction, request batching, tool annotations with safety levels, elicitation protocol for interactive input, MCPServerBase for custom servers, and multi-server management with load balancing - **PPT Generation**: Create AI-powered PowerPoint presentations with 35 slide types (title, content, charts, timelines, dashboards, composite layouts), 5 built-in themes, optional AI-generated images, and multi-provider support (Vertex, OpenAI, Anthropic, Google AI, Azure, Bedrock) - **Video Generation**: Create AI-generated videos with RunwayML integration supporting ML5 and ML6 Turbo models, customizable duration (5-10s), and watermark control - **Gemini Image Generation**: Native support for Google's imagen-3.0-generate-002 model through Gemini 2.0 Flash Experimental for high-quality image synthesis - **Remote MCP Servers**: HTTP/Streamable HTTP transport enables connecting to cloud-hosted MCP servers with Bearer token authentication, configurable rate limits, automatic retry with exponential backoff, and session management via `Mcp-Session-Id` header - **Audio Input**: Real-time voice conversations with Gemini Live API enabling bidirectional audio streaming for interactive voice-based AI experiences - **Server Adapters**: Deploy NeuroLink as production HTTP APIs with support for Hono (recommended), Express, Fastify, and Koa frameworks. Includes built-in authentication, rate limiting, caching, validation middleware, and SSE streaming support. - **RAG Document Processing**: Full-featured retrieval-augmented generation with 10 chunking strategies (character, recursive, sentence, token, markdown, html, json, latex, semantic, semantic-markdown), hybrid search combining BM25 and vector similarity, 5 reranking types (simple, LLM, batch, cross-encoder, Cohere), and a pluggable vector-store interface (in-memory store built in; bring your own adapter to connect external stores such as Pinecone, Weaviate, or Chroma). - **Claude Subscription Support**: Flexible authentication supporting API keys and OAuth for Claude Pro/Max subscribers, with model availability tracking and quota management --- ## Core Features (shipped 2025) | Feature | Description | | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | **[Image Generation](/docs/features/image-generation)** | Generate images from text prompts using Gemini models via Vertex AI or Google AI Studio. | | **[Enterprise HITL](/docs/features/enterprise-hitl)** | HITL design guide. Event-based tool approval works today; the rest is planned. | | **[Interactive CLI](/docs/cli)** | AI development environment with loop mode, session variables, and conversation memory. | | **[MCP Tools Showcase](/docs/features/mcp-tools-showcase)** | Complete guide to 6 built-in tools and connecting external MCP servers across 6 categories. | | **[Human-in-the-Loop (HITL)](/docs/features/hitl)** | Pause AI tool execution for user approval before risky operations like file deletion or API calls. | | **[Guardrails Middleware](/docs/features/guardrails)** | Content filtering, PII detection, and safety checks for AI outputs with zero configuration. | | **[Redis Conversation Export](/docs/features/conversation-history)** | Export complete session history as JSON for analytics, debugging, and compliance auditing. | | **[Context Compaction](/docs/features/context-compaction)** | Automatic conversation compression for long-running sessions to stay within token limits. | | **[LiteLLM Integration](/docs/getting-started/providers/litellm)** | Access 100+ AI models across a broad range of AI providers through unified LiteLLM routing interface. | | **[SageMaker Integration](/docs/getting-started/providers/sagemaker)** | Deploy and use custom-trained models on AWS SageMaker infrastructure with full control. | --- ## Earlier Core Features (shipped Q3 2025) | Feature | Description | | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | | **[Multimodal Chat Experiences](/docs/features/multimodal-chat)** | Stream text and images together with automatic provider fallbacks and format conversion. | | **[CSV File Support](/docs/features/csv-support)** | Process CSV files for data analysis with automatic format conversion. Works across supported providers. | | **[PDF File Support](/docs/features/pdf-support)** | Process PDF documents for visual analysis and content extraction. Native provider support. | | **[Office Documents](/docs/features/office-documents)** | Process DOCX, PPTX, XLSX files for document analysis. Native Bedrock, Vertex, Anthropic support. | | **[Auto Evaluation Engine](/docs/features/auto-evaluation)** | Automated quality scoring and metrics export for AI response validation using LLM-as-judge. | | **[CLI Loop Sessions](/docs/features/cli-loop-sessions)** | Persistent interactive mode with conversation memory and session state for prompt engineering. | | **[Regional Streaming Controls](/docs/features/regional-streaming)** | Region-specific model deployment and routing for compliance and latency optimization. | | **[Provider Orchestration Brain](/docs/features/provider-orchestration)** | Adaptive provider and model selection with intelligent fallbacks based on task classification. | --- ## Platform Capabilities at a Glance | Category | Features | Documentation | | ------------------------ | ------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | | **Provider unification** | Provider integrations with automatic failover, cost-aware routing, `providerFallback` policy, `modelChain` config | [Provider Setup](/docs/getting-started/provider-setup) | | **Multimodal pipeline** | Stream images + CSV data + PDF documents + Office files across providers with auto-detection for mixed file types. | [Multimodal Guide](/docs/features/multimodal-chat), [CSV Support](/docs/features/csv-support), [PDF Support](/docs/features/pdf-support), [Office Docs](/docs/features/office-documents) | | **Voice pipeline** | TTS (6 providers) + STT (4 providers) + realtime APIs (OpenAI Realtime, Gemini Live) | [TTS Guide](/docs/features/tts), [STT Guide](/docs/features/audio-input), [Realtime Services](/docs/features/real-time-services) | | **Quality & governance** | Auto-evaluation engine (14 scorers), guardrails middleware, HITL workflows, audit logging | [Auto Evaluation](/docs/features/auto-evaluation), [Guardrails](/docs/features/guardrails), [HITL](/docs/features/hitl) | | **Memory & context** | Per-user condensed memory (S3/Redis/SQLite), Redis session export, 5-stage context compaction | [Conversation Memory](/docs/memory/conversation), [Memory](/docs/features/memory), [Redis Export](/docs/features/conversation-history) | | **CLI tooling** | Loop sessions, setup wizard, config validation, Redis auto-detect, JSON output, TTS/STT flags | [CLI Loop](/docs/features/cli-loop-sessions), [CLI Commands](/docs/cli/commands) | | **Enterprise ops** | Claude proxy, OTLP observability, OpenObserve dashboard, regional routing, credential management | [Enterprise Proxy](/docs/deployment/enterprise-proxy), [Observability](/docs/observability/health-monitoring) | | **Tool ecosystem** | MCP auto discovery, LiteLLM hub access, SageMaker custom deployment, web search | [MCP Integration](/docs/mcp/integration), [MCP Catalog](/docs/guides/mcp/server-catalog) | --- ## AI Provider Integration NeuroLink supports **many AI providers** with unified API access: | Provider | Key Features | Free Tier | Tool Support | Status | Documentation | | --------------------- | ---------------------------------------- | ------------ | ------------ | ---------- | ----------------------------------------------------------------------------------------------------------- | | **OpenAI** | GPT-4o, GPT-4o-mini, o1 models | No | Full | Production | [Setup Guide](/docs/getting-started/provider-setup.md#openai) | | **Anthropic** | Claude 4.6, 4.5/4.0 Sonnet, Opus, Haiku | No | Full | Production | [Setup Guide](/docs/getting-started/provider-setup.md#anthropic), [Subscription Guide](/docs/features/claude-subscription) | | **Google AI** | Gemini 3 Flash/Pro, Gemini 2.5 Flash/Pro | Free Tier | Full | Production | [Setup Guide](/docs/getting-started/provider-setup.md#google-ai) | | **AWS Bedrock** | Claude, Titan, Llama, Nova | No | Full | Production | [Setup Guide](/docs/getting-started/provider-setup.md#bedrock) | | **Google Vertex** | Gemini via GCP | No | Full | Production | [Setup Guide](/docs/getting-started/provider-setup.md#vertex) | | **Azure OpenAI** | GPT-4, GPT-4o, o1 | No | Full | Production | [Setup Guide](/docs/getting-started/provider-setup.md#azure) | | **LiteLLM** | 100+ models unified | Varies | Full | Production | [Integration Guide](/docs/getting-started/providers/litellm) | | **AWS SageMaker** | Custom deployed models | No | Full | Production | [Integration Guide](/docs/getting-started/providers/sagemaker) | | **Mistral AI** | Mistral Large, Small | Free Tier | Full | Production | [Setup Guide](/docs/getting-started/provider-setup.md#mistral) | | **Hugging Face** | 100,000+ models | Free | Partial | Production | [Setup Guide](/docs/getting-started/provider-setup.md#huggingface) | | **Ollama** | Local models | Free (Local) | Partial | Production | [Setup Guide](/docs/getting-started/provider-setup.md#ollama) | | **OpenAI Compatible** | Any compatible endpoint | Varies | Full | Production | [Setup Guide](/docs/getting-started/provider-setup.md#openai-compatible) | | **OpenRouter** | 300+ models via unified API | Free Tier | Full | Production | [Setup Guide](/docs/getting-started/provider-setup.md#openrouter) | | **DeepSeek** | DeepSeek V3, R1 | No | Full | Production | [Setup Guide](/docs/getting-started/providers/deepseek) | | **NVIDIA NIM** | Llama 3.3 70B, 400+ catalog models | No | Full | Production | [Setup Guide](/docs/getting-started/providers/nvidia-nim) | | **LM Studio** | Any model loaded in LM Studio (local) | Free (Local) | Full | Production | [Setup Guide](/docs/getting-started/providers/lm-studio) | | **llama.cpp** | Any GGUF model via llama-server (local) | Free (Local) | Full | Production | [Setup Guide](/docs/getting-started/providers/llamacpp) | | **OpenAI TTS** | TTS-1, TTS-1-HD, GPT-4o Audio | No | N/A | Production | [Setup Guide](/docs/getting-started/providers/openai-tts) | | **ElevenLabs** | Multilingual v2, Turbo v2.5, Flash v2.5 | Free Tier | N/A | Production | [Setup Guide](/docs/getting-started/providers/elevenlabs) | | **Deepgram** | Nova-3, Nova-2, Enhanced (STT) | Free Tier | N/A | Production | [Setup Guide](/docs/getting-started/providers/deepgram) | | **Azure Speech** | Azure Cognitive Services TTS + STT | No | N/A | Production | [Setup Guide](/docs/getting-started/providers/azure-speech) | **[Provider Comparison Guide](/docs/reference/provider-comparison)** - Full feature matrix --- ## Advanced CLI Capabilities ### Interactive Setup Wizard NeuroLink includes a revolutionary **interactive setup wizard** that guides users through provider configuration in 2-3 minutes: ```bash # Launch interactive setup wizard npx @juspay/neurolink setup # Provider-specific guided setup npx @juspay/neurolink setup --provider openai npx @juspay/neurolink setup --provider bedrock ``` **Wizard Features:** - Secure credential collection with validation - Real-time authentication testing - Automatic `.env` file creation - Recommended model selection - Quick-start command examples - Interactive provider discovery ### 15+ CLI Commands Complete command-line toolkit for every workflow: | Command | Description | Key Features | | ---------------- | ------------------------ | ----------------------------------------- | | **generate/gen** | Text generation | Multimodal input, tool support, streaming | | **stream** | Real-time streaming | Live token output, evaluation | | **loop** | Interactive session | Persistent variables, conversation memory | | **setup** | Guided configuration | Provider wizard, validation | | **status** | Health monitoring | Provider health, latency checks | | **models list** | Model discovery | Capability filtering, availability | | **config** | Configuration management | Init, validate, export, reset | | **memory** | Conversation management | Export, import, stats, clear | | **mcp** | MCP server management | List, discover, connect, status | | **provider** | Provider operations | List, test, health dashboard | | **ollama** | Ollama management | Model download, list, remove | | **sagemaker** | SageMaker operations | Status, endpoint management | | **vertex** | Vertex AI operations | Auth status, quota checks | | **completion** | Shell completion | Bash and Zsh support | | **validate** | Config validation | Environment verification | ### Shell Integration **Bash and Zsh completions** for faster command-line workflows: ```bash # Install Bash completion neurolink completion bash >> ~/.bashrc # Install Zsh completion neurolink completion zsh >> ~/.zshrc ``` **Learn more:** [Complete CLI Reference](/docs/cli/commands) --- ## Built-in Tools & MCP Integration ### 8 Core Built-in Agent Tools Complete autonomous agent foundation with security and validation: | Tool | Function | Capabilities | Security | Status | | -------------------- | ------------------ | ------------------------------------------------- | ---------- | ------ | | `getCurrentTime` | Time access | Date/time with timezone support | Safe | Active | | `readFile` | File reading | Secure file system access with path validation | Sandboxed | Active | | `writeFile` | File writing | File creation and modification with safety checks | HITL | Active | | `listFiles` | Directory listing | Directory navigation and listing | Restricted | Active | | `createDirectory` | Directory creation | Directory creation with permission checks | Validated | Active | | `deleteFile` | File deletion | File and directory deletion with confirmation | HITL | Active | | `executeCommand` | Command execution | System command execution with safety limits | HITL | Active | | `websearchGrounding` | Web search | Google Vertex web search integration | API-based | Active | **Tool Management System:** - Dynamic tool registration and validation - Secure execution with sandboxing - Result processing and error recovery - Tool discovery and availability tracking **[Custom Tools Guide](/docs/sdk/custom-tools)** - Create your own tools --- ### Model Context Protocol (MCP) - Enterprise-Grade Ecosystem #### 5 Built-in MCP Servers NeuroLink includes **5 production-ready MCP servers** for enterprise agent deployment: | Server | Purpose | Tools Provided | Status | | ---------------- | ---------------------- | --------------------------------------- | ----------- | | **AI Core** | Provider orchestration | generate, select-provider, check-status | Operational | | **AI Analysis** | Analytics capabilities | analyze-usage, performance-metrics | Operational | | **AI Workflow** | Workflow automation | execute-workflow, batch-process | Operational | | **Direct Tools** | Agent integration | file-ops, web-search, execute | Operational | | **Utilities** | General utilities | time, calculations, formatting | Operational | #### Advanced MCP Infrastructure | Component | Capabilities | Status | | --------------------------- | ----------------------------------------- | ------ | | **Tool Registry** | Tool registration, execution, statistics | Active | | **External Server Manager** | Lifecycle management, health monitoring | Active | | **Tool Discovery Service** | Automatic tool discovery and registration | Active | | **MCP Factory** | Lighthouse-compatible server creation | Active | | **Flexible Tool Validator** | Universal safety validation | Active | | **Context Manager** | Rich context with 15+ fields | Active | | **Tool Orchestrator** | Sequential pipelines, error handling | Active | #### Lighthouse MCP Compatibility - **Factory Pattern**: `createMCPServer()` fully compatible with Lighthouse architecture - **Transport Mechanisms**: stdio, HTTP/Streamable HTTP, SSE, WebSocket support (99% compatibility) - **Tool Standards**: Full MCP specification compliance - **Context Passing**: Rich context with sessionId, userId, permissions (15+ fields) #### External MCP Servers Supported for extended functionality: **Categories:** - **Development**: GitHub, GitLab, filesystem access - **Databases**: PostgreSQL, MySQL, SQLite - **Cloud Storage**: Google Drive, AWS S3 - **Communication**: Slack, email - **And many more...** **Quick Example:** ```typescript // Add any MCP server dynamically await neurolink.addExternalMCPServer("github", { command: "npx", args: ["-y", "@modelcontextprotocol/server-github"], transport: "stdio", env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN }, }); // Tools automatically available to AI const result = await neurolink.generate({ input: { text: 'Create a GitHub issue titled "Bug in auth flow"' }, }); ``` **[MCP Integration Guide](/docs/mcp/integration)** - Setup and usage **[MCP Server Catalog](/docs/guides/mcp/server-catalog)** - Directory of 58+ community servers you can connect --- ## Developer Experience Features ### SDK Features | Feature | Description | Documentation | | --------------------------- | ------------------------------ | --------------------------------------------------- | | **Auto Provider Selection** | Intelligent provider fallback | [SDK Guide](/docs/sdk/index.md#auto-selection) | | **Streaming Responses** | Real-time token streaming | [Streaming Guide](/docs/advanced/streaming) | | **Conversation Memory** | Automatic context management | [Memory Guide](/docs/sdk/index.md#memory) | | **Full Type Safety** | Complete TypeScript types | [Type Reference](/docs/sdk/api-reference) | | **Error Handling** | Graceful provider fallback | [Error Guide](/docs/reference/troubleshooting) | | **Analytics & Evaluation** | Usage tracking, quality scores | [Analytics Guide](/docs/reference/analytics) | | **Middleware System** | Request/response hooks | [Middleware Guide](/docs/workflows/custom-middleware) | | **Framework Integration** | Next.js, SvelteKit, Express | [Framework Guides](/docs/sdk/framework-integration) | --- ### CLI Features | Feature | Description | Documentation | | ----------------------- | --------------------------------- | ----------------------------------------------- | | **Interactive Setup** | Guided provider configuration | [Setup Guide](/docs/) | | **Text Generation** | CLI-based generation | [Generate Command](/docs/cli/commands.md#generate) | | **Streaming** | Real-time streaming output | [Stream Command](/docs/cli/commands.md#stream) | | **Loop Sessions** | Persistent interactive mode | [Loop Sessions](/docs/features/cli-loop-sessions) | | **Provider Management** | Health checks and status | [CLI Guide](/docs/cli/commands) | | **Model Evaluation** | Automated testing | [Eval Command](/docs/cli/commands.md#eval) | | **MCP Management** | Server discovery and installation | [MCP CLI](/docs/cli/commands) | **15+ Commands** for every workflow - see [Complete CLI Reference](/docs/cli/commands) --- ## Smart Model Selection & Cost Optimization ### Cost Optimization Features - **Automatic Cost Optimization**: Selects cheapest models for simple tasks - **LiteLLM Model Routing**: Access 100+ models with automatic load balancing - **Capability-Based Selection**: Find models with specific features (vision, function calling) - **Intelligent Fallback**: Seamless switching when providers fail **CLI Examples:** ```bash # Cost optimization - automatically use cheapest model npx @juspay/neurolink generate "Hello" --optimize-cost # LiteLLM specific model selection npx @juspay/neurolink generate "Complex analysis" --provider litellm --model "anthropic/claude-3-5-sonnet" # Auto-select best available provider npx @juspay/neurolink generate "Write code" # Automatically chooses optimal provider ``` **Learn more:** [Provider Orchestration Guide](/docs/features/provider-orchestration) · [Classifier Router](/docs/features/classifier-router) — classify each request and route it to a cheaper or more capable model (and tool set) from a pool you define. --- ## Interactive Loop Mode NeuroLink features a powerful **interactive loop mode** that transforms the CLI into a persistent, stateful session. ### Key Capabilities - Run any CLI command without restarting session - Persistent session variables: `set provider openai`, `set temperature 0.9` - Conversation memory: AI remembers previous turns within session - Redis auto-detection: Automatically connects if `REDIS_URL` is set - Export session history as JSON for analytics ### Quick Start ```bash # Start loop with Redis-backed conversation memory npx @juspay/neurolink loop --enable-conversation-memory --auto-redis # Start loop without Redis auto-detection npx @juspay/neurolink loop --enable-conversation-memory --no-auto-redis ``` ### Example Session ```bash # Start the interactive session $ npx @juspay/neurolink loop neurolink » set provider google-ai ✓ provider set to google-ai neurolink » set temperature 0.8 ✓ temperature set to 0.8 neurolink » generate "Tell me a fun fact about space" The quietest place on Earth is an anechoic chamber at Microsoft's headquarters... # Exit the session neurolink » exit ``` **[Complete Loop Guide](/docs/features/cli-loop-sessions)** - Full documentation with all commands --- ## Enterprise & Production Features ### Production Capabilities | Feature | Description | Use Case | Documentation | | ---------------------------- | ----------------------------------- | ---------------------------- | ----------------------------------------------------------------- | | **Enterprise Proxy** | Corporate proxy support | Behind firewalls | [Proxy Setup](/docs/deployment/enterprise-proxy) | | **Redis Memory** | Distributed conversation state | Multi-instance deployment | [Redis Guide](/docs/getting-started/provider-setup.md#redis) | | **Cost Optimization** | Automatic cheapest model selection | Budget control | [Cost Guide](/docs/cookbook/cost-optimization) | | **Multi-Provider Failover** | Automatic provider switching | High availability | [Failover Guide](/docs/guides/enterprise/multi-provider-failover) | | **Telemetry & Monitoring** | OpenTelemetry integration | Observability | [Observability Guide](/docs/observability/health-monitoring) | | **Security Hardening** | Credential management, auditing | Compliance | [Security Guide](/docs/guides/enterprise/compliance) | | **Custom Model Hosting** | SageMaker integration | Private models | [SageMaker Guide](/docs/getting-started/providers/sagemaker) | | **Load Balancing** | LiteLLM proxy integration | Scale & routing | [Load Balancing Guide](/docs/guides/enterprise/load-balancing) | | **Audit Trails** | Comprehensive logging | Compliance | [Audit Guide](/docs/guides/enterprise/audit-trails) | | **Configuration Management** | Environment & credential management | Multi-environment deployment | [Config Guide](/docs/deployment/configuration-management) | ### Advanced Security Features #### Human-in-the-Loop (HITL) Event-based approval for sensitive tool calls. The shipped configuration is `HITLConfig`: ```typescript const neurolink = new NeuroLink({ hitl: { enabled: true, dangerousActions: ["delete", "remove", "drop"], // Required; substring match on the tool name timeout: 30000, // Rejects if nobody answers (default) autoApproveOnTimeout: false, autoApproveExclusions: [], // Exact tool names never auto-approved on timeout auditLogging: true, // Logs each request and decision customRules: [], // { name, condition(toolName, args), requiresConfirmation, customMessage? } }, }); ``` **What ships today:** - Pause a tool call until your app answers over the SDK event emitter - Reject on timeout, or auto-approve with exclusions - `customRules` for conditional approval - A log entry for each request and decision (a log, not a compliance control) **Planned, not implemented:** an allow-list or deny-list policy, bulk approval, confidence thresholds, escalation and asynchronous review. See the [Enterprise HITL guide](/docs/features/enterprise-hitl) for the target design and [#752](https://github.com/juspay/neurolink/issues/752). #### Advanced Proxy Support Corporate network compatibility: | Proxy Type | Support | Features | | -------------------- | ------- | ---------------------------------------- | | **AWS Proxy** | Full | AWS-specific proxy configuration | | **HTTP/HTTPS Proxy** | Full | Proxy support across supported providers | | **No-Proxy Bypass** | Full | Bypass configuration and utilities | #### Enhanced Guardrails AI-powered content security: - **Content Filtering**: Automatic content screening - **Toxicity Detection**: Toxic content filtering - **PII Redaction**: Privacy protection and PII detection - **Custom Rules**: Configurable policy rules - **Security Reporting**: Detailed security event reporting ### Security & Compliance - Deployable within SOC 2 Type II environments — NeuroLink itself is not audited or certified - Deployable on ISO 27001-certified infrastructure — that certification is your infrastructure's, not NeuroLink's - GDPR-conscious data handling (EU-region providers selectable; you own compliance) - Deployable in HIPAA-aligned configurations — you are responsible for a compliant setup - Hardened OS verified (SELinux, AppArmor) - Zero credential logging - Encrypted configuration storage **[Enterprise Deployment Guide](/docs/guides/enterprise/multi-provider-failover)** - Complete production patterns --- ## Middleware & Extension System ### Advanced Middleware Architecture Pluggable request/response processing for custom workflows: #### Built-in Middleware | Middleware | Purpose | Features | Status | | ------------------- | --------------------------- | --------------------------------------------------- | ------ | | **Analytics** | Usage tracking & monitoring | Token counting, timing, performance metrics | Active | | **Guardrails** | Content security | Content policies, toxicity detection, PII filtering | Active | | **Auto Evaluation** | Quality scoring | LLM-as-judge, accuracy metrics, safety validation | Active | #### Middleware System Capabilities ```typescript // Middleware Configuration type MiddlewareFactoryOptions = { middleware?: NeuroLinkMiddleware[]; // Custom middleware registration enabledMiddleware?: string[]; // Selective activation disabledMiddleware?: string[]; // Selective deactivation middlewareConfig?: Record; // Per-middleware configuration preset?: string; // Preset configurations global?: { // Global settings maxExecutionTime?: number; continueOnError?: boolean; }; }; ``` **Middleware Features:** - Dynamic middleware registration - Pipeline execution with performance tracking - Runtime configuration changes - Error handling and graceful recovery - Priority-based execution order - Detailed execution statistics **[Custom Middleware Guide](/docs/workflows/custom-middleware)** - Build your own middleware --- ## Performance & Optimization ### Intelligent Cost Optimization - **Model Resolver**: Cost optimization algorithms and intelligent routing - **Performance Routing**: Speed-optimized provider selection - **Concurrent Initialization**: Reduced latency through parallel loading - **Caching Strategies**: Intelligent response and configuration caching ### Advanced SageMaker Features Beyond basic integration - enterprise-grade custom model deployment: | Feature | Description | Status | | ---------------------------- | ---------------------------------------------------- | ----------- | | **Adaptive Semaphore** | Dynamic concurrency control for optimal throughput | Implemented | | **Structured Output Parser** | Complex response parsing and validation | Implemented | | **Capability Detection** | Automatic endpoint capability discovery | Implemented | | **Batch Inference** | Efficient batch processing for high-volume workloads | Implemented | | **Diagnostics System** | Real-time endpoint monitoring and debugging | Implemented | ### Error Handling & Resilience Production-grade fault tolerance: - **MCP Circuit Breaker**: Fault tolerance with state management - **Error Hierarchies**: Comprehensive error types for HITL, providers, and MCP - **Graceful Degradation**: Intelligent fallback strategies - **Retry Logic**: Configurable retry with exponential backoff **[Performance Optimization Guide](/docs/deployment/performance)** - Complete optimization strategies --- ## Advanced Integrations | Integration | Description | | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | | **[LiteLLM Integration](/docs/getting-started/providers/litellm)** | Access 100+ models across a broad range of AI providers via LiteLLM routing with unified interface. | | **[SageMaker Integration](/docs/getting-started/providers/sagemaker)** | Deploy and call custom endpoints directly from NeuroLink CLI/SDK with full control. | | **[Memory](/docs/features/memory)** | Per-user condensed memory with S3/Redis/SQLite storage and LLM-powered condensation. | | **[Enterprise Proxy](/docs/deployment/enterprise-proxy)** | Configure outbound policies and compliance posture for corporate environments. | | **[Configuration Management](/docs/deployment/configuration-management)** | Manage environments, regions, and credentials safely across deployments. | --- ## Advanced Features | Feature | Description | | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | **[Factory Pattern Architecture](/docs/development/factory-architecture)** | Unified provider interface with automatic fallbacks and type-safe implementations. | | ️ **[Conversation Memory](/docs/memory/conversation)** | Deep dive into memory management and Redis integration. | | **[Custom Middleware](/docs/workflows/custom-middleware)** | Build request/response hooks for logging, filtering, and custom processing. | | ⚡ **[Performance Optimization](/docs/deployment/performance)** | Caching, connection pooling, and latency optimization strategies. | | **[Telemetry & Observability](/docs/observability/health-monitoring)** | OpenTelemetry integration for distributed tracing and monitoring. | | **[Testing Guide](/docs/development/testing)** | Provider-agnostic testing, mocking, and quality assurance strategies. | | **[Analytics & Evaluation](/docs/reference/analytics)** | Usage tracking, cost monitoring, and quality scoring for AI responses. | | ⚡ **[Streaming](/docs/advanced/streaming)** | Real-time token streaming with provider-specific optimizations. | | **[Thinking Configuration](/docs/features/thinking-configuration)** | Configure extended thinking levels for supported models (Anthropic, Gemini 2.5+). | | **[Structured Output](/docs/cookbook/structured-output)** | JSON schema-based structured output with provider-specific formatting. | | **[Text-to-Speech (TTS)](/docs/features/tts)** | Basic TTS support via Google Cloud TTS (Neural2, Wavenet, Standard voices). | --- ## See Also - **[Getting Started](/docs/)** - Quick start and installation - **[CLI Reference](/docs/cli/commands)** - Command-line interface documentation - **[SDK Reference](/docs/sdk/api-reference)** - TypeScript API documentation - **[Enterprise Guides](/docs/guides/enterprise/multi-provider-failover)** - Production deployment patterns - **[Tutorials](/docs/)** - Step-by-step implementation guides - **[Examples](/docs/)** - Real-world code samples --- ## Attachment Security # Attachment Security Every NeuroLink call that names a file path or a URL — `input.files`, `input.images`, `input.pdfFiles`, `rag.files`, `transcribe({ audio })`, Director Mode segment images, the RAG `WebLoader` — turns that string into bytes on the host that runs the SDK. This page describes what the SDK will and will not read on a caller's behalf, how to narrow it, and what changed. ## The policy One `attachments` option on the `NeuroLink` constructor governs all of those loaders. Every field also has an environment variable for deployments that cannot change constructor arguments (the CLI, containers); an explicit field wins over its variable. ```typescript const neurolink = new NeuroLink({ attachments: { // Directories a local path may resolve into. Unset = any readable file. allowedRoots: ["/srv/uploads"], // Accept http:// URLs. Default false. allowInsecureUrls: false, // Fetch loopback / RFC 1918 / link-local / cloud-metadata targets. Default false. allowPrivateNetwork: false, // Follow redirects (up to five hops, each re-checked). Default true. followRedirects: true, // Upper bound for any single attachment read or download, in bytes. maxBytes: 64 * 1024 * 1024, }, }); ``` | Field | Environment variable | Default | | --------------------- | ---------------------------------------------------------- | ------------------------ | | `allowedRoots` | `NEUROLINK_ATTACHMENT_ROOTS` (`:`- or `;`-separated paths) | unrestricted, warns once | | `allowInsecureUrls` | `NEUROLINK_ATTACHMENT_ALLOW_INSECURE_URLS=1` | `false` | | `allowPrivateNetwork` | `NEUROLINK_ATTACHMENT_ALLOW_PRIVATE_NETWORK=1` | `false` | | `followRedirects` | `NEUROLINK_ATTACHMENT_FOLLOW_REDIRECTS=0` to disable | `true` | | `maxBytes` | `NEUROLINK_ATTACHMENT_MAX_BYTES` | each loader's own cap | ## URLs A URL attachment is fetched the way the HTTP server already fetched one before this change: the host is resolved and every address it resolves to is checked against the private, loopback, link-local, CGNAT, multicast and cloud-metadata ranges (IPv4 and IPv6, every encoding of an IP literal); the connection is pinned to exactly those addresses, so a resolver that answers differently for the real request gains nothing; the body is counted as it streams and refused the moment it passes the cap. - **HTTPS only.** An `http://` URL is refused with a message that names `attachments.allowInsecureUrls`. Plain HTTP is the transport every loopback and link-local target answers on, and it carries any credential on the request in the clear. - **Public hosts only.** `http://127.0.0.1/`, `https://169.254.169.254/`, `https://10.0.0.5/` and a host name that resolves to any of those are refused unless `allowPrivateNetwork` is set. Even then the connection is still pinned. - **Redirects are re-validated per hop.** Each `Location` is checked exactly like the first URL, and the caller's headers (`authHeaders` on a processor) are sent to the first host only — a credential meant for one origin is never replayed to the one it redirects to. `followRedirects: false` refuses any 3xx outright, which is what the server's own download path does. - **Capped while streaming.** `transcribe()` from a URL, the `WebLoader`, and every image or file URL read at most their loader's cap (or `attachments.maxBytes`, when lower) and stop the transfer there. A refused URL in `input.images` is dropped with a warning, as a URL that failed to download always was; a refused URL in `input.files`, `rag.files` or `transcribe({ audio })` fails the call. ## Local paths A path is resolved to its real location (symlinks followed) and, when `allowedRoots` is set, refused unless that real path is inside one of the roots — so a symlink planted under a root cannot reach outside it. The file is then opened `O_NOFOLLOW` on that real path (a link swapped in after the check is refused by the kernel), must be a regular file (no FIFOs, devices or directories), and is read under the size cap through the same descriptor that was measured, so a file growing under the read is noticed rather than buffered. **Without roots the SDK reads any file the process can.** That is the pre-existing behaviour, kept for backward compatibility, and the SDK says so once per process: ``` [NeuroLink] Reading a local attached file with no attachment roots configured. Any readable file on this host can be attached by naming its path. If paths come from untrusted callers, set `attachments.allowedRoots` on the NeuroLink instance or the NEUROLINK_ATTACHMENT_ROOTS environment variable. ``` **A host that forwards strings from untrusted callers must set roots.** The HTTP server's own routes already refuse every path by default; the SDK now gives an embedding application the same control. A path outside the roots is refused before the file system is consulted, with the same error for a missing file and a forbidden one, so the refusal is not an oracle for which files exist. ## Temporary files Attachments the SDK persists for lazy reading, video frames, Whistle decode buffers and Director Mode clips are written into directories created with `mkdtemp` (mode `0700`) as files with mode `0600`, and removed on `clear()` / pipeline completion or at process exit. The local artifact store uses a per-user directory (`neurolink-artifacts-`) and refuses one that is a symlink or owned by another user. ## Archives and YAML - A ZIP whose central directory names the same member twice is reported, and only the first occurrence is read — the entry the listing described is the entry that is opened. With the shipped `adm-zip` such an archive is refused as corrupt. - A YAML document whose aliases expand far past its own size (a "billion laughs" file) is parsed as shared references, and its `asJson` rendering is bounded at the processor's byte limit: above it `asJson` is `null` and a warning says why, instead of the expansion being materialised. ## ffmpeg Every `ffmpeg` and `ffprobe` invocation the SDK makes passes `-nostdin -protocol_whitelist file,crypto,data` for its inputs, so a container or playlist that references another URL or file cannot make the decoder fetch it, whatever the installed build's defaults are. A caller-supplied file name contributes a temp-file suffix only when it is a known video extension, and a frame or subtitle extraction that times out kills the child instead of abandoning it. ## Breaking changes These defaults changed; each has an explicit switch. | Before | Now | Switch | | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | `http://` URLs in `input.images`, `input.files`, `transcribe`, `WebLoader` were fetched | refused | `attachments.allowInsecureUrls` / `NEUROLINK_ATTACHMENT_ALLOW_INSECURE_URLS=1` | | URLs on private, loopback or link-local hosts were fetched | refused | `attachments.allowPrivateNetwork` / `NEUROLINK_ATTACHMENT_ALLOW_PRIVATE_NETWORK=1` | | Redirects were followed to any target with the caller's headers | followed only to a target the policy allows, caller headers dropped per hop | `attachments.followRedirects: false` refuses them altogether | | A local path was read silently | still read, but a one-time warning names `attachments.allowedRoots` | set `allowedRoots` to make the warning go away and the boundary real | | Redis session/user ids were used as given | ids containing `:` `*` `?` `[` or a line break are refused | `NEUROLINK_REDIS_ALLOW_LEGACY_IDS=1` warns instead, while migrating | | Google Speech-to-Text sent the API key as `?key=` | sent as the `x-goog-api-key` header | none needed | | `.env` and `.env.backup.*` written by the CLI at the umask default | written `0600` | none needed | ## See also - [Multimodal input](/docs/features/multimodal) — images, PDFs, CSV, video - [Transcribe](/docs/features/transcribe) — `transcribe({ audio })` from a path or URL - [RAG](/docs/features/rag) — `rag.files` and the `WebLoader` - [Video Director Mode](/docs/features/video-director-mode) — segment images - [Environment variables](/docs/getting-started/environment-variables) --- ## Audio Input & Transcription Guide # Audio Input & Voice Conversations Guide NeuroLink provides comprehensive audio input capabilities, enabling real-time voice conversations with AI models. This guide covers currently available features, audio specifications, and upcoming enhancements. ## Overview ### Currently Available NeuroLink supports the following audio capabilities today: - **Real-time voice conversations** via Gemini Live (Google AI Studio) - **Text-to-Speech (TTS) output** via Google Cloud TTS, OpenAI TTS, ElevenLabs, and Azure TTS - **Speech-to-Text (STT)** via `generate()` and `stream()` options (Whisper/OpenAI STT, Google STT, Deepgram, Azure STT, ElevenLabs Scribe) - **WebSocket-based voice streaming** for web applications - **Bidirectional audio** - speak and hear AI responses in real-time ### Planned The following features are planned for future releases: - CLI commands: `neurolink audio transcribe`, `neurolink audio analyze`, `neurolink audio summarize` - CLI commands: `neurolink voice chat`, `neurolink voice demo` - Cross-provider audio support (Anthropic, AWS Transcribe still planned) - File-based audio input processing ----------------- | --------------- | ---------- | ---------------------------- | ---------------- | | **Google AI Studio** | Yes | Yes | Yes (via Google STT) | Production Ready | | **Google Vertex AI** | Planned | Yes | Yes (via Google STT) | Available | | **OpenAI** | Planned | Yes | Yes (via Whisper/OpenAI STT) | Available | | **Deepgram** | Planned | No | Yes (speaker labels) | Available | | **Azure** | Planned | Yes | Yes (via Azure STT) | Available | | **ElevenLabs** | No | Yes | Yes (Scribe, speaker labels) | Available | | **Self-hosted** | No | No | Yes (OpenAI-compatible) | Available | | **Anthropic** | Planned | Planned | Planned | Planned | | **AWS Bedrock** | Planned | Planned | Planned | Planned | **Supported Model for Real-time Voice:** | Model | Provider | Capabilities | | ---------------------------------------------- | --------- | -------------------------------- | | `gemini-2.5-flash-preview-native-audio-dialog` | Google AI | Bidirectional audio, low latency | --- ## Quick Start: Real-Time Voice (SDK) Real-time voice conversations are available through the SDK using Gemini Live's native audio dialog model. ### Prerequisites ```bash # Set your Google AI API key export GOOGLE_AI_API_KEY="your-api-key" # OR export GEMINI_API_KEY="your-api-key" ``` ### Basic Real-time Voice Streaming ```typescript const neurolink = new NeuroLink(); // Create an async iterator for audio frames // This example uses a hypothetical audio source async function* getAudioFrames(): AsyncIterable { // Your audio capture logic here // Each frame should be PCM16LE mono at 16kHz // Recommended frame size: 20-60ms of audio while (capturing) { const frame = await captureAudioFrame(); yield frame; } } // Stream with real-time audio input const result = await neurolink.stream({ provider: "google-ai", model: "gemini-2.5-flash-preview-native-audio-dialog", input: { audio: { frames: getAudioFrames(), sampleRateHz: 16000, // Input sample rate (default: 16000) encoding: "PCM16LE", // Encoding format (default: PCM16LE) }, }, disableTools: true, // Required for Phase 1 audio streaming }); // Process audio responses for await (const event of result.stream) { if (event.type === "audio") { // Handle audio output chunk // Output is PCM16LE mono at 24kHz const audioData = event.audio.data; playAudio(audioData); } } ``` ### Complete Voice Session Example ```typescript const neurolink = new NeuroLink(); async function startVoiceSession() { // Audio frame queue management const frameQueue: Buffer[] = []; let isSessionActive = true; // Create async iterator from queue const audioFramesIterator: AsyncIterable = { [Symbol.asyncIterator]() { return { async next() { if (!isSessionActive) { return { value: undefined, done: true }; } // Wait for frames to be available while (frameQueue.length === 0 && isSessionActive) { await new Promise((resolve) => setTimeout(resolve, 10)); } if (frameQueue.length > 0) { return { value: frameQueue.shift()!, done: false }; } return { value: undefined, done: true }; }, }; }, }; // Start the streaming session const streamResult = await neurolink.stream({ provider: "google-ai", model: "gemini-2.5-flash-preview-native-audio-dialog", input: { audio: { frames: audioFramesIterator, sampleRateHz: 16000, encoding: "PCM16LE", }, }, disableTools: true, }); // Function to add captured audio to queue function onAudioCaptured(pcmBuffer: Buffer) { frameQueue.push(pcmBuffer); } // Function to signal end of input (flush) function flushAudio() { // Push a zero-length buffer as flush signal frameQueue.push(Buffer.alloc(0)); } // Process responses for await (const event of streamResult.stream) { if (event.type === "audio") { // Output audio data: PCM16LE, 24kHz, mono handleAudioOutput(event.audio.data); } } isSessionActive = false; } function handleAudioOutput(audioBuffer: Buffer) { // Play or process the audio response // Sample rate: 24000 Hz // Format: PCM16LE mono playAudioBuffer(audioBuffer); } ``` --- ## Quick Start: TTS Integration NeuroLink provides Text-to-Speech output via Google Cloud TTS. TTS can be combined with any text generation. ### CLI Usage ```bash # Generate text and convert to speech neurolink generate "Hello, world!" \ --provider google-ai \ --tts-voice en-US-Neural2-C # Save audio to file neurolink generate "Welcome to NeuroLink" \ --provider google-ai \ --tts-voice en-US-Neural2-C \ --tts-output welcome.mp3 # Customize voice parameters neurolink generate "This is a test" \ --provider google-ai \ --tts-voice en-US-Wavenet-D \ --tts-speed 1.2 \ --tts-pitch 2.0 \ --tts-format mp3 \ --tts-output test.mp3 # Synthesize AI response (not input text) neurolink generate "Tell me a joke" \ --provider google-ai \ --tts-voice en-US-Neural2-C \ --tts-use-ai-response \ --tts-output joke.mp3 ``` ### SDK Usage ```typescript const neurolink = new NeuroLink(); // Basic TTS const result = await neurolink.generate({ input: { text: "Hello, world!" }, provider: "google-ai", tts: { enabled: true, voice: "en-US-Neural2-C", format: "mp3", play: true, // Auto-play in CLI }, }); // Save TTS audio if (result.audio?.buffer) { writeFileSync("output.mp3", result.audio.buffer); console.log(`Audio saved: ${result.audio.size} bytes`); } // Advanced TTS with AI response synthesis const aiResponse = await neurolink.generate({ input: { text: "Explain quantum computing briefly" }, provider: "google-ai", tts: { enabled: true, useAiResponse: true, // Synthesize AI's response voice: "en-US-Wavenet-D", format: "mp3", speed: 0.9, pitch: -2.0, }, }); console.log("Text:", aiResponse.content); console.log("Audio size:", aiResponse.tts?.size, "bytes"); ``` For comprehensive TTS documentation, see the [TTS Integration Guide](/docs/features/tts). --- ## Voice Demo Example NeuroLink includes a complete voice demo application demonstrating real-time bidirectional audio conversations. ### Location ``` examples/voice-demo/ server.mjs # WebSocket server with NeuroLink integration public/ index.html # Web interface client.js # Browser audio capture and playback ``` ### Running the Demo ```bash # Navigate to the project root cd /path/to/neurolink # Build the SDK first pnpm run build # Set your API key export GOOGLE_AI_API_KEY="your-api-key" # Run the demo server node examples/voice-demo/server.mjs ``` The demo will: 1. Start a WebSocket server on port 5175 (or next available port) 2. Open your browser automatically to the demo interface 3. Allow you to speak and receive real-time AI audio responses ### Demo Architecture ``` Browser (client.js) | | WebSocket (ws://localhost:5175/ws) | v Server (server.mjs) | | neurolink.stream() | v Gemini Live API | | PCM16LE audio chunks | v Server -> Browser -> Audio playback ``` ### Key Code from Voice Demo Server ```typescript // From examples/voice-demo/server.mjs const streamResult = await neurolink.stream({ provider: "google-ai", model: process.env.GEMINI_MODEL || "gemini-2.5-flash-preview-native-audio-dialog", input: { audio: { frames: framesFromClient, // sampleRateHz defaults to 16000 // encoding defaults to 'PCM16LE' }, }, disableTools: true, // Required for audio streaming }); // Stream audio responses back to client for await (const ev of streamResult.stream) { if (ev.type === "audio") { // Send raw PCM16LE bytes back to the client ws.send(ev.audio.data, { binary: true }); } } ``` --- ## Speaker Labels (Diarization) Ask for speaker labels with `speakerDiarization: true` (the documented alias `diarization: true` works too). Providers that diarize: `deepgram`, `google-stt`, `elevenlabs-stt` (Scribe), and any OpenAI-compatible endpoint that labels its segments (see the next section). Whatever the provider, the result has the same shape: ```typescript const result = await neurolink.generate({ input: { text: "" }, stt: { enabled: true, audio: meetingBuffer, provider: "elevenlabs-stt", speakerDiarization: true, speakerCount: 3, // optional hint }, }); for (const turn of result.transcription?.segments ?? []) { console.log(`[${turn.startTime}s] ${turn.speaker}: ${turn.text}`); } console.log(result.transcription?.speakers); // ["Speaker 0", "Speaker 1", "Speaker 2"] ``` - `segments[]` is a list of **speaker turns**: consecutive words from one speaker, with `speaker`, `startTime`, `endTime` and `text`. - `speakers[]` lists the distinct labels in order of first appearance. - Providers that label words rather than segments (Deepgram, Google, Scribe) have their turns derived by `STTProcessor`, so callers never see the per-provider difference. A provider that returns its own speaker-labelled segments (the diarization sidecar) is passed through untouched. - CLI: `neurolink generate --stt --input-audio meeting.wav --stt-provider elevenlabs-stt --stt-diarize`. **ElevenLabs Scribe** (`elevenlabs-stt`, alias `scribe`) shares `ELEVENLABS_API_KEY` with the TTS handler. It detects the language itself, transcribes code-switched speech (Hinglish comes back romanized unless a `language: "hi"` hint asks for Devanagari), and accepts audio or video containers. Options: `model` (`scribe_v2` default), `tagAudioEvents`. ## Self-hosted STT (OpenAI-compatible endpoints) The `whisper` handler talks to any server that implements OpenAI's `/audio/transcriptions` — vLLM serving an ASR model such as Qwen3-ASR, LiteLLM, or NeuroLink's diarization sidecar (NVIDIA Nemotron-3 diarization in front of a local ASR). Point it at the server and pass the model name per call: ```bash OPENAI_STT_BASE_URL=http://spark:8006/v1 # the server's /v1 root OPENAI_STT_API_KEY=dummy # keyless local server OPENAI_STT_TIMEOUT_MS=600000 # whole meetings take minutes ``` ```typescript const result = await neurolink.generate({ input: { text: "" }, stt: { enabled: true, audio: meetingBuffer, provider: "whisper", model: "qwen3-asr-diarized", speakerDiarization: true, // sent as diarize=true to compatible servers only timeoutMs: 600_000, }, }); ``` Or construct the handler directly when several endpoints coexist: ```typescript STTProcessor.registerHandler( "spark-asr", new OpenAISTT("dummy", "http://spark:8004/v1"), ); ``` `diarize` and `max_speakers` (from `speakerCount`) are only sent to non-OpenAI endpoints, because OpenAI's own API rejects unknown fields. A `speaker` on a returned segment, and a top-level `speakers[]`, are surfaced as-is. ## Audio Specifications ### Input Audio Format | Parameter | Value | Notes | | --------------- | ------------------- | ------------------------------------ | | **Encoding** | PCM16LE | 16-bit signed integer, little-endian | | **Sample Rate** | 16,000 Hz | 16 kHz mono | | **Channels** | 1 (mono) | Stereo not supported in Phase 1 | | **Frame Size** | 20-60ms recommended | ~320-960 samples per frame | | **Byte Order** | Little-endian | Intel/ARM standard | ### Output Audio Format | Parameter | Value | Notes | | --------------- | ------------- | ------------------------------------ | | **Encoding** | PCM16LE | 16-bit signed integer, little-endian | | **Sample Rate** | 24,000 Hz | 24 kHz mono | | **Channels** | 1 (mono) | Single channel output | | **Byte Order** | Little-endian | Intel/ARM standard | ### Converting Audio Formats **From Float32 to PCM16LE (for input):** ```javascript function floatTo16BitPCM(float32Array) { const length = float32Array.length; const buffer = new ArrayBuffer(length * 2); const view = new DataView(buffer); for (let i = 0; i ; /** * Input sample rate in Hz * @default 16000 */ sampleRateHz?: number; /** * Audio encoding format * @default "PCM16LE" */ encoding?: "PCM16LE"; /** * Number of audio channels * Phase 1 only supports mono * @default 1 */ channels?: 1; }; ``` ### AudioChunk Audio output chunk received from streaming responses. ```typescript type AudioChunk = { /** * Raw audio data buffer (PCM16LE format) */ data: Buffer; /** * Sample rate of the audio data * Gemini typically outputs at 24000 Hz */ sampleRateHz: number; /** * Number of audio channels (typically 1 for mono) */ channels: number; /** * Audio encoding format */ encoding: "PCM16LE"; }; ``` ### StreamOptions with Audio ```typescript type StreamOptions = { input: { text: string; audio?: AudioInputSpec; // Optional audio input // ... other input options }; provider: string; model?: string; disableTools?: boolean; // Required true for audio streaming // ... other options }; ``` ### Stream Result Events ```typescript // Stream yields different event types type StreamEvent = | { content: string } // Text chunk | { type: "audio"; audio: AudioChunk } // Audio chunk | { type: "image"; imageOutput: { base64: string } }; // Image output // Usage for await (const event of result.stream) { if ("content" in event) { // Text content console.log(event.content); } else if (event.type === "audio") { // Audio data playAudio(event.audio.data); } } ``` ### AudioContent (File-based - Future) For file-based audio input (planned feature). ```typescript type AudioContent = { type: "audio"; data: Buffer | string; // Buffer, base64, URL, or file path mediaType?: | "audio/mpeg" // MP3 | "audio/wav" // WAV | "audio/ogg" // OGG | "audio/webm" // WebM | "audio/aac" // AAC | "audio/flac" // FLAC | "audio/mp4"; // M4A metadata?: { filename?: string; duration?: number; // in seconds sampleRate?: number; channels?: number; transcription?: string; // Pre-existing transcription }; }; ``` --- ## Roadmap ### Phase 1 (Current) - Real-time voice with Gemini Live - Bidirectional audio streaming via SDK - Voice demo example application - TTS output integration ### Phase 2 (Planned) - **CLI Voice Commands** ```bash # Start interactive voice chat neurolink voice chat --provider google-ai # Launch voice demo server neurolink voice demo --port 5175 ``` - **Audio Transcription** ```bash # Transcribe audio file neurolink audio transcribe recording.mp3 --provider openai # Analyze audio content neurolink audio analyze podcast.mp3 --prompt "Summarize key points" ``` ### Phase 3 (Partially Available) - **Speech-to-Text via `generate()` / `stream()`** — Available now via the `stt` option. There is no standalone `neurolink.transcribe()` method; STT is integrated directly into `generate()` and `stream()`: ```typescript const result = await neurolink.generate({ input: { text: "Respond to the audio" }, provider: "vertex", stt: { enabled: true, provider: "google-stt", audio: audioBuffer, language: "en-US", }, }); console.log("Transcription:", result.transcription?.text); console.log("AI Response:", result.content); ``` **CLI equivalent:** ```bash neurolink generate "Respond to the audio" \ --provider vertex \ --stt \ --stt-provider google-stt \ --input-audio recording.wav ``` **Available STT providers:** `whisper` / `openai-stt`, `google-stt`, `deepgram`, `azure-stt`, `elevenlabs-stt` (aliases `scribe`, `elevenlabs`) **CLI STT flags:** `--stt`, `--stt-provider `, `--input-audio `, `--stt-language ` - **Cross-provider Audio Support** - Anthropic voice capabilities — Planned - AWS Transcribe — Planned - **File-based Audio Input** ```typescript const result = await neurolink.generate({ input: { text: "Analyze this audio file", audioFiles: ["./meeting.mp3"], }, provider: "openai", }); ``` --- ## Environment Setup ### Required Environment Variables ```bash # For Google AI Studio (Gemini Live) export GOOGLE_AI_API_KEY="your-api-key" # OR export GEMINI_API_KEY="your-api-key" # For TTS (Google Cloud) export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json" # OR use the same GOOGLE_AI_API_KEY with Cloud TTS API enabled ``` ### API Key Configuration For Gemini Live and TTS to work with an API key: 1. Go to Google Cloud Console > APIs & Services > Credentials 2. Create or select your API key 3. Under "API restrictions", enable: - **Generative Language API** (for Gemini) - **Cloud Text-to-Speech API** (for TTS output) --- ## Troubleshooting ### Common Issues | Issue | Cause | Solution | | --------------------------- | ------------------------ | -------------------------------------------------- | | **No audio output** | Missing API key | Set `GOOGLE_AI_API_KEY` or `GEMINI_API_KEY` | | **"disableTools required"** | Tools enabled with audio | Add `disableTools: true` to stream options | | **Choppy audio playback** | Buffer underrun | Increase buffer size or frame rate | | **Wrong sample rate** | Mismatched audio context | Use 16kHz input, 24kHz output contexts | | **WebSocket disconnects** | Network timeout | Implement reconnection logic | | **"Model not found"** | Invalid model name | Use `gemini-2.5-flash-preview-native-audio-dialog` | ### Audio Quality Issues **Clipping/Distortion:** - Ensure input samples are normalized to [-1, 1] range - Check gain levels before PCM conversion **Echo/Feedback:** - Mute microphone during AI audio playback - Implement voice activity detection (VAD) **Latency:** - Use smaller frame sizes (20ms) - Process audio in real-time, avoid buffering - Use WebSocket for low-latency transport ### Debug Mode Enable debug logging to troubleshoot audio issues: ```bash export NEUROLINK_DEBUG=true ``` ```typescript const neurolink = new NeuroLink({ debug: true, }); ``` --- ## Related Features **Audio & Voice:** - [TTS Integration Guide](/docs/features/tts) - Complete Text-to-Speech documentation - [Video Generation](/docs/features/video-generation) - AI-powered video with audio - [PPT Generation](/docs/features/ppt-generation) - AI-powered PowerPoint presentations **Multimodal Capabilities:** - [Multimodal Guide](/docs/features/multimodal) - Images, PDFs, CSV inputs - [PDF Support](/docs/features/pdf-support) - Document processing **Advanced Features:** - [Streaming](/docs/advanced/streaming) - Stream AI responses in real-time - [Provider Orchestration](/docs/features/provider-orchestration) - Multi-provider failover **Documentation:** - [CLI Commands](/docs/cli/commands) - Complete CLI reference - [SDK API Reference](/docs/sdk/api-reference) - Full API documentation - [Troubleshooting](/docs/reference/troubleshooting) - Extended error catalog --- ## Summary NeuroLink's audio input capabilities provide: **Currently Available:** - Real-time voice conversations via Gemini Live - Bidirectional audio streaming (speak and hear) - TTS output via Google Cloud, OpenAI TTS, ElevenLabs, and Azure TTS - STT via `generate({ stt: { ... } })` — Whisper/OpenAI STT, Google STT, Deepgram, Azure STT, ElevenLabs Scribe - Voice demo example application - PCM16LE audio format support **Planned:** - CLI voice commands (`voice chat`, `audio transcribe`) - Anthropic and AWS Transcribe audio support - File-based audio processing **Next Steps:** 1. Set up [environment variables](#environment-setup) 2. Try the [voice demo](#voice-demo-example) application 3. Integrate [real-time voice](#quick-start-real-time-voice-sdk) in your SDK code 4. Explore [TTS output](/docs/features/tts) for text-to-speech 5. Check [troubleshooting](#troubleshooting) if you encounter issues --- ## Authentication Providers # Authentication Providers > **Status**: Stable | **Availability**: SDK + CLI + Server ## Overview NeuroLink ships with a pluggable authentication system that validates tokens, manages sessions, and enforces role-based access control (RBAC) across your AI endpoints. Rather than forcing a single auth solution, NeuroLink supports 11 providers through a unified interface so you can use the same identity platform your application already relies on. Key capabilities: - **Token validation** -- verify JWTs and opaque tokens from any supported provider - **Session management** -- in-memory or Redis-backed session storage with auto-refresh - **RBAC enforcement** -- role and permission checks with hierarchical wildcard support - **Per-call authentication** -- validate tokens on every `generate()` or `stream()` call - **Middleware pipeline** -- composable auth, RBAC, and rate-limiting middleware for server routes - **AsyncLocalStorage context** -- access the authenticated user from anywhere in the request lifecycle without explicit parameter passing - **CLI management** -- list providers, validate tokens, and check health from the command line ## Quick Start ### SDK -- Constructor Auth Config Pass authentication configuration in the `NeuroLink` constructor. The provider is lazily initialized on first use. ```typescript const neurolink = new NeuroLink({ auth: { type: "auth0", config: { domain: "your-tenant.auth0.com", clientId: "your-client-id", audience: "https://api.example.com", }, }, }); ``` ### SDK -- Per-Call Token Validation When an auth provider is configured, pass `auth: { token }` to `generate()` or `stream()` to validate the caller's token before the AI request executes. Validated user identity is automatically injected into the request context. ```typescript const result = await neurolink.generate({ input: { text: "Summarize the quarterly report" }, auth: { token: bearerToken }, }); // Streaming with auth const stream = await neurolink.stream({ input: { text: "Explain this chart" }, auth: { token: bearerToken }, }); ``` ### SDK -- Pre-Validated Request Context If your server has already validated the user, pass `requestContext` instead. When both `auth.token` and `requestContext` are provided, token-derived identity fields take precedence to prevent privilege escalation. ```typescript const result = await neurolink.generate({ input: { text: "Generate report" }, requestContext: { userId: "user-123", userEmail: "alice@example.com", userRoles: ["analyst"], }, }); ``` ### Server Middleware Protect HTTP routes with composable middleware. ```typescript createAuthMiddleware, createRBACMiddleware, createRateLimitByUserMiddleware, } from "@juspay/neurolink"; // 1. Authentication middleware const auth = await createAuthMiddleware({ provider: "auth0", providerConfig: { type: "auth0", domain: "your-tenant.auth0.com", clientId: "your-client-id", }, publicRoutes: ["/health", "/public/*"], }); // 2. RBAC middleware const rbac = createRBACMiddleware({ roles: ["admin", "analyst"], permissions: ["generate:execute"], }); // 3. Rate limiting by user const rateLimit = createRateLimitByUserMiddleware({ maxRequests: 100, windowMs: 60_000, roleLimits: { premium: 500, admin: 1000 }, skipRoles: ["super-admin"], }); ``` ## Provider Support | Provider | Type | JWT Validation | Session Mgmt | RBAC | Health Check | Aliases | | ----------- | ------------- | -------------- | ------------ | ---- | ------------ | --------------------------------- | | Auth0 | `auth0` | Yes | Yes | Yes | Yes | `auth0-jwt`, `auth0-oauth` | | Clerk | `clerk` | Yes | Yes | Yes | Yes | `clerk-jwt` | | Firebase | `firebase` | Yes | Yes | Yes | Yes | `firebase-auth` | | Supabase | `supabase` | Yes | Yes | Yes | Yes | `supabase-auth` | | AWS Cognito | `cognito` | Yes | Yes | Yes | Yes | `aws-cognito`, `amazon-cognito` | | Keycloak | `keycloak` | Yes | Yes | Yes | Yes | `keycloak-oidc` | | WorkOS | `workos` | Yes | Yes | Yes | Yes | `workos-sso`, `work-os` | | Better Auth | `better-auth` | Yes | Yes | Yes | Yes | `betterauth`, `better_auth` | | OAuth2 | `oauth2` | Yes | Yes | Yes | Yes | `oauth`, `oidc`, `openid-connect` | | JWT | `jwt` | Yes | Yes | Yes | Yes | `jwt-auth`, `jwt-token` | | Custom | `custom` | Yes | Yes | Yes | Yes | `custom-auth` | All providers implement the `AuthProvider` interface, ensuring a consistent API regardless of which identity platform you choose. ## SDK API ### Constructor Configuration The `auth` field in `NeurolinkConstructorConfig` accepts several forms: ```typescript // Form 1: Typed provider config (recommended) new NeuroLink({ auth: { type: "auth0", config: { domain: "...", clientId: "..." }, }, }); // Form 2: Direct AuthProvider instance const provider = await AuthProviderFactory.create("clerk", { type: "clerk", secretKey: process.env.CLERK_SECRET_KEY!, }); new NeuroLink({ auth: provider }); // Form 3: Wrapped provider instance new NeuroLink({ auth: { provider: myAuthProviderInstance } }); ``` The `NeuroLinkAuthConfig` union type supports all 11 provider types with their specific config shapes: | Config Type | Required Fields | | ------------------------------------- | ------------------------------------------ | | `{ type: "auth0"; config: ... }` | `domain`, `clientId` | | `{ type: "clerk"; config: ... }` | `secretKey` | | `{ type: "firebase"; config: ... }` | `projectId` | | `{ type: "supabase"; config: ... }` | `url`, `anonKey` | | `{ type: "cognito"; config: ... }` | `userPoolId`, `clientId`, `region` | | `{ type: "keycloak"; config: ... }` | `serverUrl`, `realm`, `clientId` | | `{ type: "workos"; config: ... }` | `apiKey`, `clientId` | | `{ type: "better-auth"; config: ...}` | `secret`, `baseUrl` | | `{ type: "oauth2"; config: ... }` | `clientId`, `authorizationUrl`, `tokenUrl` | | `{ type: "jwt"; config: ... }` | `secret` or `publicKey` | | `{ type: "custom"; config: ... }` | `validateToken` function | ### `setAuthProvider(config)` Set or change the authentication provider at runtime. ```typescript // Pass a typed config await neurolink.setAuthProvider({ type: "supabase", config: { url: process.env.SUPABASE_URL!, anonKey: process.env.SUPABASE_ANON_KEY!, }, }); // Or pass a pre-created provider instance await neurolink.setAuthProvider(myAuthProvider); ``` ### `getAuthProvider()` Get the currently configured authentication provider, or `undefined` if none is set. ```typescript const provider = neurolink.getAuthProvider(); if (provider) { const health = await provider.healthCheck(); console.log("Auth provider healthy:", health.healthy); } ``` ### `setAuthContext(context)` Set the current authentication context for request handling. Useful when integrating with server frameworks that have already authenticated the user. ```typescript neurolink.setAuthContext({ user: { id: "user-123", roles: ["admin"], permissions: ["*"] }, headers: {}, authenticatedAt: new Date(), provider: "auth0", }); ``` ### `generate()` / `stream()` Auth Options Both `generate()` and `stream()` accept `auth` and `requestContext` options: | Option | Type | Description | | ---------------- | ------------------------- | ---------------------------------------------------- | | `auth.token` | `string` | Raw token validated by the configured auth provider | | `requestContext` | `Record` | Pre-validated user context (userId, userRoles, etc.) | When `auth.token` is provided: 1. NeuroLink calls `authProvider.authenticateToken(token)` with a 5-second timeout 2. If invalid, an `InvalidTokenError` is thrown 3. If valid, `userId`, `userEmail`, and `userRoles` are merged into the request context 4. Token-derived identity fields take precedence over `requestContext` to prevent privilege escalation ## CLI Usage The `auth` command provides subcommands for managing authentication: ```bash # List available auth providers neurolink auth providers neurolink auth providers --format json neurolink auth providers --format table # Validate a token against a provider neurolink auth validate --provider auth0 --domain your-tenant.auth0.com --client-id your-id neurolink auth validate --provider clerk --secret-key sk_test_xxx neurolink auth validate --provider jwt --secret your-jwt-secret # Check provider health neurolink auth health --provider auth0 --domain your-tenant.auth0.com --client-id your-id neurolink auth health --provider supabase --url https://xxx.supabase.co --anon-key xxx # Anthropic OAuth management neurolink auth login anthropic neurolink auth logout anthropic neurolink auth status anthropic neurolink auth refresh anthropic ``` ### Environment Variable Configuration Provider configuration can be supplied via environment variables instead of CLI flags: | Provider | Environment Variables | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------ | | Auth0 | `AUTH0_DOMAIN`, `AUTH0_CLIENT_ID`, `AUTH0_AUDIENCE` | | Clerk | `CLERK_SECRET_KEY`, `CLERK_PUBLISHABLE_KEY` | | Supabase | `SUPABASE_URL`, `SUPABASE_ANON_KEY`, `SUPABASE_JWT_SECRET` | | Firebase | `FIREBASE_PROJECT_ID`, `FIREBASE_API_KEY` | | WorkOS | `WORKOS_API_KEY`, `WORKOS_CLIENT_ID` | | Better Auth | `BETTER_AUTH_SECRET`, `BETTER_AUTH_BASE_URL` | | OAuth2 | `OAUTH2_CLIENT_ID`, `OAUTH2_CLIENT_SECRET`, `OAUTH2_AUTHORIZATION_URL`, `OAUTH2_TOKEN_URL`, `OAUTH2_USERINFO_URL`, `OAUTH2_JWKS_URL` | | Cognito | `COGNITO_USER_POOL_ID`, `COGNITO_CLIENT_ID`, `COGNITO_REGION` (or `AWS_REGION`) | | Keycloak | `KEYCLOAK_REALM`, `KEYCLOAK_SERVER_URL`, `KEYCLOAK_CLIENT_ID` | | JWT | `JWT_SECRET`, `JWT_PUBLIC_KEY`, `JWT_ISSUER`, `JWT_AUDIENCE` | ## Configuration Reference ### Provider-Specific Configs #### Auth0 ```typescript { type: "auth0", config: { domain: "your-tenant.auth0.com", // Required clientId: "your-client-id", // Required clientSecret: "your-client-secret", // Optional, for backend ops audience: "https://api.example.com", // Optional, API identifier scope: "openid profile email", // Optional claimsNamespace: "https://myapp/", // Optional, custom claims prefix managementApi: { // Optional clientId: "mgmt-client-id", clientSecret: "mgmt-secret", }, }, } ``` #### Clerk ```typescript { type: "clerk", config: { secretKey: "sk_test_xxx", // Required publishableKey: "pk_test_xxx", // Optional jwtKey: "your-jwt-key", // Optional, for local validation jwksUrl: "https://...", // Optional, JWKS endpoint override allowedOrigins: ["https://app.com"], // Optional }, } ``` #### Firebase ```typescript { type: "firebase", config: { projectId: "your-project-id", // Required apiKey: "your-api-key", // Optional serviceAccount: { // Optional clientEmail: "...", privateKey: "...", }, rolesClaimKey: "roles", // Optional, custom claims key permissionsClaimKey: "perms", // Optional }, } ``` #### Supabase ```typescript { type: "supabase", config: { url: "https://xxx.supabase.co", // Required anonKey: "eyJ...", // Required serviceRoleKey: "eyJ...", // Optional, for backend ops jwtSecret: "your-jwt-secret", // Optional }, } ``` #### AWS Cognito ```typescript { type: "cognito", config: { userPoolId: "us-east-1_xxx", // Required clientId: "your-client-id", // Required region: "us-east-1", // Required clientSecret: "...", // Optional customAttributes: ["department"], // Optional }, } ``` #### Keycloak ```typescript { type: "keycloak", config: { serverUrl: "https://keycloak.example.com", // Required realm: "my-realm", // Required clientId: "my-app", // Required clientSecret: "...", // Optional verifyToken: true, // Optional (default: true) }, } ``` #### WorkOS ```typescript { type: "workos", config: { apiKey: "sk_test_xxx", // Required clientId: "client_xxx", // Required organizationId: "org_xxx", // Optional, for multi-tenant }, } ``` #### Better Auth ```typescript { type: "better-auth", config: { secret: "your-secret", // Required baseUrl: "https://auth.example.com", // Required databaseUrl: "postgresql://...", // Optional socialProviders: { // Optional github: { clientId: "...", clientSecret: "..." }, google: { clientId: "...", clientSecret: "..." }, }, }, } ``` #### OAuth2 ```typescript { type: "oauth2", config: { clientId: "your-client-id", // Required authorizationUrl: "https://auth.example.com/authorize", // Required tokenUrl: "https://auth.example.com/token", // Required clientSecret: "...", // Optional userInfoUrl: "https://auth.example.com/userinfo", // Optional jwksUrl: "https://auth.example.com/.well-known/jwks.json", // Optional scopes: ["openid", "profile"], // Optional redirectUrl: "http://localhost:3000/callback", // Optional usePKCE: true, // Optional }, } ``` #### JWT ```typescript { type: "jwt", config: { secret: "your-hmac-secret", // Required (or publicKey) publicKey: "-----BEGIN PUBLIC KEY-----...", // Required (or secret) algorithms: ["HS256"], // Optional issuer: "https://auth.example.com", // Optional audience: "https://api.example.com", // Optional }, } ``` #### Custom ```typescript { type: "custom", config: { validateToken: async (token, context) => { // Your custom validation logic const user = await myAuthService.verify(token); return { valid: !!user, user: user ? { id: user.id, email: user.email, roles: user.roles, permissions: user.permissions, } : undefined, }; }, getUser: async (userId) => { /* Optional */ }, createSession: async (user, context) => { /* Optional */ }, }, } ``` ### Base Provider Config All providers share these base configuration fields: | Field | Type | Default | Description | | ----------------- | ------------------------- | ------- | --------------------------------------- | | `required` | `boolean` | `true` | Whether authentication is mandatory | | `debug` | `boolean` | `false` | Enable debug logging | | `tokenValidation` | `TokenValidationConfig` | -- | Token issuer, audience, clock tolerance | | `tokenExtraction` | `TokenExtractionStrategy` | Bearer | Where to find the token in requests | | `session` | `SessionConfig` | -- | Session storage and duration | | `rbac` | `RBACConfig` | -- | Role hierarchy and permissions | | `cache` | `AuthCacheConfig` | -- | Token validation result caching | ### Token Extraction Strategy Configure where and how tokens are extracted from requests: ```typescript { tokenExtraction: { // Default: Authorization: Bearer fromHeader: { name: "Authorization", scheme: "Bearer" }, // Or from a cookie fromCookie: { name: "session_token" }, // Or from a query parameter fromQuery: { name: "access_token" }, // Or a custom extraction function custom: (context) => context.headers["x-api-key"] ?? null, }, } ``` ## Middleware ### Authentication Middleware Create middleware that validates tokens and attaches user context to requests. ```typescript const authMiddleware = await createAuthMiddleware({ provider: "auth0", providerConfig: { type: "auth0", domain: "your-tenant.auth0.com", clientId: "your-client-id", }, publicRoutes: ["/health", "/public/*"], optional: false, tokenExtraction: { fromHeader: { name: "Authorization", scheme: "Bearer" }, }, onAuthenticated: async (context) => { console.log("Authenticated:", context.user.id); }, onError: async (error, context) => { console.error("Auth error:", error.message); }, }); // Use in request handler const result = await authMiddleware(requestContext); if (result.proceed) { console.log("User:", result.context?.user); } else { console.log("Error:", result.error?.statusCode, result.error?.message); } ``` ### RBAC Middleware Enforce role and permission requirements after authentication. ```typescript const rbacMiddleware = createRBACMiddleware({ roles: ["admin", "moderator"], // User must have at least one permissions: ["generate:execute"], // User must have all requireAllRoles: false, // Default: any role matches superAdminRoles: ["super-admin"], // Bypass all checks roleHierarchy: { // Role inheritance admin: ["moderator", "viewer"], moderator: ["viewer"], }, rolePermissions: { // Role-to-permission mapping admin: ["generate:execute", "admin:read", "admin:write"], moderator: ["generate:execute", "admin:read"], }, custom: async (user, context) => { // Custom authorization return user.organizationId === "org-123"; }, onDenied: async (result, context) => { console.log("Access denied:", result.reason); }, }); ``` ### Combined Auth + RBAC Middleware ```typescript const protectedRoute = await createProtectedMiddleware({ auth: { provider: "clerk", providerConfig: { type: "clerk", secretKey: process.env.CLERK_SECRET_KEY! }, publicRoutes: ["/health"], }, rbac: { roles: ["admin"], permissions: ["admin:write"], }, }); const result = await protectedRoute(requestContext); ``` ### Express-Compatible Middleware ```typescript const middleware = await createExpressAuthMiddleware({ provider: "jwt", providerConfig: { type: "jwt", secret: process.env.JWT_SECRET!, issuer: "https://auth.example.com", }, }); // Use with Express app.use(middleware); // req.user and req.authContext are available in routes ``` ### Rate Limiting by User Apply per-user rate limits with role-based differentiation and memory or Redis storage. ```typescript createRateLimitByUserMiddleware, createRateLimitStorage, } from "@juspay/neurolink"; // Memory storage (single instance) const rateLimiter = createRateLimitByUserMiddleware({ maxRequests: 100, windowMs: 60_000, roleLimits: { premium: 500, admin: 1000 }, skipRoles: ["super-admin"], message: "Rate limit exceeded. Please try again later.", }); // Redis storage (distributed) const redisStorage = createRateLimitStorage({ type: "redis", redis: { url: "redis://localhost:6379", prefix: "myapp:ratelimit:" }, }); const distributedLimiter = createRateLimitByUserMiddleware( { maxRequests: 100, windowMs: 60_000 }, redisStorage, ); ``` ## Session Management Sessions are managed through the `SessionManager` class with pluggable storage backends. ### In-Memory Sessions Default for single-instance deployments. Sessions are lost on restart. ```typescript const sessions = new SessionManager({ storage: "memory", duration: 3600, // 1 hour in seconds autoRefresh: true, // Refresh sessions near expiration refreshThreshold: 300, // Refresh when { // These work anywhere in the call stack const user = getCurrentUser(); const session = getCurrentSession(); if (isAuthenticated()) { console.log("User:", user?.email); } // Throws if not authenticated const ctx = requireAuth(); // Throws if user lacks permission requirePermission("admin:write"); // Boolean checks if (hasRole("admin") && hasPermission("reports:generate")) { await generateReport(); } }); ``` For environments where `AsyncLocalStorage` is not available, use the `AuthContextHolder`: ```typescript globalAuthContext.set(authenticatedContext); const user = globalAuthContext.getUser(); globalAuthContext.clear(); ``` ## Error Handling All auth errors extend `AuthError` with typed subclasses for different failure modes: | Error Class | Use Case | HTTP Status | | ------------------------------ | -------------------------------- | ----------- | | `AuthenticationFailedError` | Invalid credentials or token | 401 | | `MissingTokenError` | No token provided | 401 | | `InvalidTokenError` | Malformed or unverifiable token | 401 | | `TokenExpiredError` | Token has expired | 401 | | `InsufficientPermissionsError` | User lacks required permissions | 403 | | `SessionNotFoundError` | Session ID does not exist | 401 | | `SessionExpiredError` | Session has expired | 401 | | `UserNotFoundError` | User not found in provider | 404 | | `ProviderInitializationError` | Provider setup failed | 500 | | `InvalidConfigurationError` | Missing or invalid config fields | 500 | | `ProviderAPIError` | Provider API returned an error | 502 | | `AuthRateLimitError` | Too many auth attempts | 429 | ### Error Codes | Code | Meaning | | -------- | ------------------------ | | AUTH-001 | Invalid token | | AUTH-002 | Expired token | | AUTH-003 | Invalid credentials | | AUTH-004 | Invalid signature | | AUTH-005 | Missing token | | AUTH-006 | Token decode failed | | AUTH-007 | JWKS fetch failed | | AUTH-008 | Session not found | | AUTH-009 | Session expired | | AUTH-010 | Session revoked | | AUTH-011 | Insufficient permissions | | AUTH-012 | Insufficient roles | | AUTH-013 | Access denied | | AUTH-014 | Provider error | | AUTH-015 | Configuration error | | AUTH-016 | Rate limited | | AUTH-017 | User not found | | AUTH-018 | User disabled | | AUTH-019 | Email not verified | | AUTH-020 | MFA required | ### Type Guards ```typescript isAuthError, isAuthenticationError, isPermissionError, isTokenError, isSessionError, } from "@juspay/neurolink"; try { await neurolink.generate({ input: { text: "Hello" }, auth: { token: expiredToken }, }); } catch (error) { if (isTokenError(error)) { // InvalidTokenError | TokenExpiredError | MissingTokenError console.log("Token problem:", error.message); } else if (isPermissionError(error)) { console.log("Missing:", error.missingPermissions); } else if (isAuthError(error)) { console.log("Auth error from provider:", error.provider); } } ``` ## Auth Events Auth providers emit events you can subscribe to for logging or monitoring: ```typescript const provider = neurolink.getAuthProvider(); if (provider && "on" in provider) { provider.on("auth:login", (user) => { console.log("User logged in:", user.id); }); provider.on("auth:unauthorized", (context, reason) => { console.warn("Unauthorized:", reason); }); provider.on("auth:error", (error, context) => { console.error("Auth error:", error.message); }); } ``` ## Best Practices 1. **Always validate tokens server-side.** Never trust client-provided identity claims without `auth: { token }` validation. 2. **Use RBAC for fine-grained control.** Define role hierarchies and permission mappings rather than checking roles directly in application code. 3. **Use Redis sessions in production.** In-memory sessions are suitable for development but are lost on restart and do not work across multiple instances. 4. **Leverage AsyncLocalStorage context.** Use `runWithAuthContext` and `getCurrentUser()` instead of passing user objects through every function parameter. 5. **Set token extraction strategy explicitly.** The default (`Authorization: Bearer`) works for most APIs, but configure cookie or custom extraction for browser-based flows. 6. **Handle token expiration gracefully.** Catch `TokenExpiredError` and return a response that tells the client to refresh. 7. **Use rate limiting per user.** Apply `createRateLimitByUserMiddleware` to prevent abuse while giving premium users higher limits. 8. **Keep secrets in environment variables.** Never hard-code client secrets, JWT secrets, or service account keys in source code. ## Key Files | File | Purpose | | -------------------------------------------- | ------------------------------------------------------- | | `src/lib/auth/AuthProviderFactory.ts` | Factory for creating auth provider instances | | `src/lib/auth/AuthProviderRegistry.ts` | Registry for provider metadata and discovery | | `src/lib/auth/authProvider.ts` | `BaseAuthProvider` abstract class | | `src/lib/auth/authContext.ts` | AsyncLocalStorage context propagation | | `src/lib/auth/authErrors.ts` | Typed error hierarchy | | `src/lib/auth/sessionManager.ts` | Session storage (memory + Redis) | | `src/lib/auth/middleware/AuthMiddleware.ts` | Auth and RBAC middleware factories | | `src/lib/auth/middleware/rateLimitByUser.ts` | Per-user rate limiting middleware | | `src/lib/auth/providers/auth0.ts` | Auth0 provider implementation | | `src/lib/auth/providers/clerk.ts` | Clerk provider implementation | | `src/lib/auth/providers/firebase.ts` | Firebase provider implementation | | `src/lib/auth/providers/supabase.ts` | Supabase provider implementation | | `src/lib/auth/providers/CognitoProvider.ts` | AWS Cognito provider implementation | | `src/lib/auth/providers/KeycloakProvider.ts` | Keycloak provider implementation | | `src/lib/auth/providers/workos.ts` | WorkOS provider implementation | | `src/lib/auth/providers/betterAuth.ts` | Better Auth provider implementation | | `src/lib/auth/providers/oauth2.ts` | OAuth2/OIDC provider implementation | | `src/lib/auth/providers/jwt.ts` | JWT provider implementation | | `src/lib/auth/providers/custom.ts` | Custom provider implementation | | `src/lib/auth/index.ts` | Module exports | | `src/lib/types/authTypes.ts` | All auth type definitions | | `src/lib/types/configTypes.ts` | `NeuroLinkAuthConfig` union type | | `src/lib/neurolink.ts` | `setAuthProvider()`, `getAuthProvider()`, per-call auth | | `src/cli/commands/authProviders.ts` | CLI auth command handlers | | `src/cli/factories/authCommandFactory.ts` | CLI auth command builder | ## See Also - [Auth Architecture Guide](/docs/advanced/auth-architecture) -- factory + registry pattern, request flow, and integration points - [Server Adapters](/docs/guides/server-adapters) -- deploying NeuroLink as an HTTP API with auth middleware - [Observability Guide](/docs/observability/health-monitoring) -- tracing authenticated requests with Langfuse context - [SDK API Reference](/docs/sdk/api-reference) -- complete SDK reference --- ## Client SDK # Client SDK > **Since**: v9.30.0 | **Status**: Stable | **Availability**: SDK ## Overview The NeuroLink Client SDK provides type-safe libraries for accessing NeuroLink APIs from JavaScript and TypeScript applications. It is designed for frontend apps, backend services, and full-stack frameworks alike. **Key capabilities:** - **HTTP Client** -- Type-safe request/response with automatic retries, middleware, and request cancellation - **Streaming** -- Real-time token streaming via Server-Sent Events (SSE) and WebSocket transports - **React Integration** -- Ready-made hooks (`useChat`, `useAgent`, `useWorkflow`, `useVoice`, `useStream`, `useTools`) with a context provider - **Vercel AI SDK Compatibility** -- Drop-in `LanguageModelV1` adapter for `generateText` and `streamText` - **Authentication** -- API key, Bearer token, OAuth2 client-credentials, and JWT token management - **Interceptors & Middleware** -- Composable middleware for logging, retry, rate limiting, caching, and error handling ## Quick Start ```typescript const client = createClient({ baseUrl: "https://api.neurolink.example.com", apiKey: process.env.NEUROLINK_API_KEY, }); // Generate text const result = await client.generate({ input: { text: "Explain TCP in two sentences" }, provider: "openai", model: "gpt-4o", }); console.log(result.data.content); // Stream text await client.stream( { input: { text: "Tell me a story" }, provider: "anthropic", model: "claude-sonnet-4-6", }, { onText: (text) => process.stdout.write(text), onDone: (res) => console.log("\nTokens:", res.usage), }, ); ``` ## HTTP Client ### `createClient(config)` Creates a `NeuroLinkClient` instance. This is the primary entry point for all API interactions. ### ClientConfig | Field | Type | Required | Description | | --------- | ------------------------ | -------- | ----------------------------------------------------------- | | `baseUrl` | `string` | Yes | Base URL for the NeuroLink API | | `apiKey` | `string` | No | API key sent in `X-API-Key` header | | `token` | `string` | No | Bearer token sent in `Authorization` header | | `timeout` | `number` | No | Default request timeout in ms (default: 30000) | | `headers` | `Record` | No | Default headers included in every request | | `retry` | `RetryConfig` | No | Retry configuration for failed requests | | `debug` | `boolean` | No | Enable debug logging | | `fetch` | `typeof fetch` | No | Custom fetch implementation for non-browser environments | | `wsUrl` | `string` | No | WebSocket URL override (defaults to ws/wss version of base) | ### Making Requests The client exposes typed methods for each API surface -- `generate`, `stream`, `executeAgent`, `streamAgent`, `executeWorkflow`, `listTools`, `listProviders`, `listAgents`, and more: ```typescript // Text generation const gen = await client.generate({ input: { text: "Write a haiku about coding" }, provider: "openai", model: "gpt-4o", temperature: 0.7, }); console.log(gen.data.content); // Agent execution const agent = await client.executeAgent({ agentId: "customer-support", input: "I need help with my order", sessionId: "user-123", }); // List tools, providers, agents const tools = await client.listTools({ category: "data" }); const providers = await client.listProviders(); ``` Every response is wrapped in `ApiResponse ); } ``` ### useChat Build chat interfaces with streaming, message history, and tool call support: ```tsx function ChatComponent() { const { messages, input, handleInputChange, handleSubmit, isLoading, error, stop, reload, setMessages, } = useChat({ agentId: "my-agent", sessionId: "user-session-1", onFinish: (message) => console.log("Done:", message.content), onError: (err) => console.error(err), }); return ( {messages.map((m) => ( {m.role}: {m.content} ))} Send {isLoading && Stop} ); } ``` ### useAgent Execute agents with session continuity: ```tsx function AgentPanel() { const { execute, stream, isLoading, isStreaming, result, error, abort } = useAgent({ agentId: "customer-support", onResponse: (result) => console.log("Agent replied:", result.content), onToolCall: (toolCall) => console.log("Tool used:", toolCall), }); return ( execute("Help me with my order")}> Ask Agent {isLoading && Thinking...} {result && {result.content}} {error && {error.message}} ); } ``` ### Additional Hooks | Hook | Purpose | Key Returns | | ------------- | ------------------------------------------ | ------------------------------------------------------ | | `useWorkflow` | Execute and monitor workflow runs | `execute`, `resume`, `cancel`, `status`, `result` | | `useVoice` | Voice input/output with speech recognition | `startListening`, `speak`, `transcript`, `isListening` | | `useStream` | Low-level streaming control | `start`, `stop`, `text`, `events`, `isStreaming` | | `useTools` | Browse and execute tools | `tools`, `execute`, `refresh`, `isLoading` | --- ## Vercel AI SDK Compatibility The AI SDK adapter (`NeuroLinkLanguageModel`) exposes a `doGenerate` / `doStream` pair that returns the **`LanguageModelV1` result shape** (`text`, `finishReason`, `usage.promptTokens`). It does not declare a `specificationVersion` and does not implement the `LanguageModelV2` / `V3` contract that `ai` v5+ requires (`content` parts, `usage.inputTokens`), so with a current `ai` release it needs a shim rather than being passed to `generateText` directly. NeuroLink itself has no dependency on `ai`. ### Recommended: use the HTTP client directly The supported client surface does not require a Vercel model adapter: ```typescript const client = createClient({ baseUrl: "https://api.neurolink.example.com", apiKey: process.env.NEUROLINK_API_KEY, }); const result = await client.generate({ provider: "openai", input: { text: "Explain recursion in one sentence" }, }); console.log(result.data.content); ``` `createNeuroLinkProvider` and `createNeuroLinkModel` remain exported for legacy callers, but their handles must not be passed directly to a modern Vercel `generateText` or `streamText` call. No V2/V3 conversion shim is supplied by these helpers. Importing either helper successfully does not establish that protocol compatibility. ### Server-Side Streaming Response Use `createStreamingResponse` in Next.js API routes or server actions to return an AI SDK-compatible SSE stream: ```typescript export async function POST(req: Request) { const { prompt } = await req.json(); return createStreamingResponse({ baseUrl: process.env.NEUROLINK_URL!, apiKey: process.env.NEUROLINK_API_KEY!, input: { text: prompt }, provider: "openai", model: "gpt-4o", }); } ``` --- ## Authentication The Client SDK supports multiple authentication strategies, from simple API keys to automatic OAuth2 token refresh. ### API Key The simplest approach -- pass the key in the client config: ```typescript const client = createClient({ baseUrl: "https://api.neurolink.example.com", apiKey: process.env.NEUROLINK_API_KEY, }); ``` Or use the middleware for more control: ```typescript const client = createClient({ baseUrl: "https://api.neurolink.example.com" }); client.use(createApiKeyMiddleware("your-api-key", "X-Custom-Key")); ``` ### Bearer Token ```typescript createClient, createBearerTokenMiddleware, } from "@juspay/neurolink/client"; const client = createClient({ baseUrl: "https://api.neurolink.example.com" }); client.use(createBearerTokenMiddleware(sessionToken)); ``` ### OAuth2 Client Credentials `OAuth2TokenManager` handles token acquisition, caching, and automatic refresh: ```typescript createClient, OAuth2TokenManager, createTokenManagerMiddleware, } from "@juspay/neurolink/client"; const tokenManager = new OAuth2TokenManager({ tokenUrl: "https://auth.example.com/oauth/token", clientId: "your-client-id", clientSecret: "your-client-secret", scope: "api:read api:write", }); const client = createClient({ baseUrl: "https://api.neurolink.example.com" }); client.use(createTokenManagerMiddleware(tokenManager)); ``` For automatic retry on 401 with token refresh: ```typescript client.use(createAuthWithRetryMiddleware(tokenManager)); ``` ### JWT Token Management `JWTTokenManager` manages JWT lifecycle with a custom refresh function: ```typescript JWTTokenManager, createTokenManagerMiddleware, } from "@juspay/neurolink/client"; const tokenManager = new JWTTokenManager({ token: initialJWT, expiresAt: Date.now() + 3600000, refreshFn: async () => { const res = await fetch("/api/auth/refresh", { method: "POST", credentials: "include", }); const data = await res.json(); return { accessToken: data.token, expiresIn: data.expiresIn, tokenType: "Bearer", }; }, }); client.use(createTokenManagerMiddleware(tokenManager)); ``` The SDK also exports JWT helpers: `decodeJWTPayload`, `isJWTExpired`, `getJWTExpiry`, and `getApiKeyFromEnv`. --- ## Interceptors & Middleware Interceptors are middleware functions you register with `client.use()`. The SDK ships several built-in interceptors and a composition utility. ### Built-in Interceptors | Interceptor | Purpose | | ------------------------------------ | --------------------------------------- | | `createLoggingInterceptor` | Request/response logging with redaction | | `createRetryInterceptor` | Exponential backoff retry | | `createRateLimitInterceptor` | Token-bucket rate limiting | | `createCacheInterceptor` | In-memory response caching | | `createTimeoutInterceptor` | Per-request timeout enforcement | | `createErrorHandlerInterceptor` | Centralized error handling/reporting | | `createRequestTransformInterceptor` | Modify requests before sending | | `createResponseTransformInterceptor` | Modify responses before returning | ### composeMiddleware Combine multiple middleware into a single unit: ```typescript composeMiddleware, createLoggingInterceptor, createRetryInterceptor, createRateLimitInterceptor, } from "@juspay/neurolink/client"; client.use( composeMiddleware( createLoggingInterceptor({ logRequest: true, logResponse: true }), createRetryInterceptor({ maxAttempts: 3, initialDelayMs: 1000, backoffMultiplier: 2, }), createRateLimitInterceptor({ maxRequests: 100, windowMs: 60000, strategy: "queue", }), ), ); ``` ### conditionalMiddleware Apply middleware only when a condition is met: ```typescript conditionalMiddleware, createLoggingInterceptor, } from "@juspay/neurolink/client"; client.use( conditionalMiddleware( (request) => request.url.includes("/api/agents"), createLoggingInterceptor({ logBody: true }), ), ); ``` --- ## Error Handling The Client SDK provides a structured error hierarchy rooted in `NeuroLinkError`. Every error carries a `code`, optional `status`, and `retryable` flag. ### Error Hierarchy | Class | Code | Typical Cause | | --------------------- | ------------------------- | --------------------------------- | | `NeuroLinkError` | varies | Base class for all SDK errors | | `HttpError` | mapped from status | HTTP 4xx/5xx responses | | `RateLimitError` | `RATE_LIMITED` | 429 Too Many Requests | | `ValidationError` | `VALIDATION_ERROR` | 400 with validation details | | `AuthenticationError` | `UNAUTHORIZED` | 401 invalid credentials | | `AuthorizationError` | `FORBIDDEN` | 403 insufficient permissions | | `NotFoundError` | `NOT_FOUND` | 404 resource not found | | `NetworkError` | `NETWORK_ERROR` | Connection failures | | `TimeoutError` | `TIMEOUT` | Request exceeded timeout | | `ConnectionError` | `CONNECTION_REFUSED` | Server unreachable | | `AbortError` | `ABORT_ERROR` | Request cancelled via signal | | `ConfigurationError` | `CONFIGURATION_ERROR` | Invalid client configuration | | `StreamError` | `STREAM_ERROR` | Stream processing failure | | `ProviderError` | `PROVIDER_ERROR` | Upstream AI provider error | | `ContextLengthError` | `CONTEXT_LENGTH_EXCEEDED` | Input exceeds model context | | `ContentFilterError` | `CONTENT_FILTERED` | Response blocked by safety filter | ### Error Handling Pattern ```typescript try { const result = await client.generate({ input: { text: "Hello" }, provider: "openai", }); console.log(result.data.content); } catch (error) { if (isNeuroLinkError(error)) { console.error( `[${error.code}] ${error.message} (retryable: ${error.retryable})`, ); if (isRetryableError(error)) { // Safe to retry this request } } } ``` ### Utility Functions | Function | Description | | ------------------------- | --------------------------------------------------- | | `isRetryableError(error)` | Returns `true` if the error is safe to retry | | `isNeuroLinkError(error)` | Type guard for `NeuroLinkError` instances | | `isApiError(error)` | Type guard for `ApiError` objects | | `mapStatusToErrorCode(s)` | Maps HTTP status to `ErrorCode` constant | | `createErrorFromResponse` | Creates typed error from an API error response | | `createErrorFromNative` | Wraps a native `Error` in the appropriate SDK class | --- ## Best Practices 1. **Reuse client instances** -- create one `NeuroLinkClient` and share it; the client manages middleware state internally. 2. **Set reasonable timeouts** -- the default is 30 s; streaming and agent tasks may need higher values via `RequestOptions`. 3. **Compose middleware** -- use `composeMiddleware` instead of many individual `client.use()` calls for clarity. 4. **Use `createNeuroLinkProvider` for AI SDK projects** -- it auto-infers providers from model IDs. 5. **Handle errors at the right level** -- `createErrorHandlerInterceptor` for telemetry, `try/catch` for business logic. 6. **Leverage `isRetryableError`** -- check before implementing custom retry logic. 7. **Scope React providers** -- place `` at the highest needed point, but below your auth boundary. 8. **Use `AbortSignal` for cancellation** -- pass `AbortController.signal` via `RequestOptions` and clean up on unmount. 9. **Cache read-heavy endpoints** -- `createCacheInterceptor` works well for `listTools` and `listProviders`. 10. **Protect secrets in the browser** -- never embed raw API keys client-side; use a proxy or `OAuth2TokenManager`. --- ## See Also - [Streaming Guide](/docs/advanced/streaming) -- Server-side streaming with the NeuroLink SDK - [Server Adapters](/docs/guides/server-adapters) -- Expose NeuroLink as HTTP APIs - [MCP Integration](/docs/mcp/integration) -- Tool orchestration - [Getting Started](/docs/) -- Installation and setup --- ## Auto Evaluation Engine # Auto Evaluation Engine NeuroLink provides an automated quality gate that scores every response using an LLM-as-judge pipeline. Scores, rationales, and severity flags are surfaced in both CLI and SDK workflows so you can monitor drift and enforce minimum quality thresholds. ## What It Does - Generates a structured evaluation payload (`result.evaluation`) for every call with `enableEvaluation: true`. - Calculates relevance, accuracy, completeness, and an overall score (1–10) using a RAGAS-style rubric. - Supports retry loops: re-ask the provider when the score falls below your threshold. - Emits analytics-friendly JSON so you can pipe results into dashboards. ## Quick Start ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain quantum computing" }, enableEvaluation: true, evaluationDomain: "science", }); console.log(result.evaluation); // { relevance: 9.0, accuracy: 8.5, completeness: 8.0, overall: 8.5, isPassing: true, ... } ``` :::warning[LLM Costs] Evaluation uses additional AI calls to the judge model (default: `gemini-2.5-flash`). Each evaluated response incurs extra API costs. For high-volume production workloads, consider sampling (e.g., evaluate 10% of requests) or disabling evaluation after quality stabilizes. ::: ## Usage Examples ```typescript // Enable orchestration for automatic provider/model selection const neurolink = new NeuroLink({ enableOrchestration: true }); const result = await neurolink.generate({ // Task classifier analyzes prompt to determine best provider input: { text: "Create quarterly performance summary" }, enableEvaluation: true, // Enable LLM-as-judge quality scoring evaluationDomain: "Enterprise Finance", // Provide domain context to shape evaluation rubric factoryConfig: { enhancementType: "domain-configuration", // Apply domain-specific prompt enhancements domainType: "finance", }, }); // Check if response passes the configured quality threshold if (result.evaluation && !result.evaluation.isPassing) { console.warn("Quality gate failed", result.evaluation.details?.message); } ``` ```bash # Baseline quality check npx @juspay/neurolink generate "Draft onboarding email" --enableEvaluation # Combine with analytics for observability dashboards npx @juspay/neurolink generate "Summarise release notes" \ --enableEvaluation --enableAnalytics --format json # Domain-aware evaluations shape the rubric npx @juspay/neurolink generate "Refactor this API" \ --enableEvaluation --evaluationDomain "Principal Engineer" # Fail the command if the score dips below 7 (set env variable first) NEUROLINK_EVALUATION_THRESHOLD=7 npx @juspay/neurolink generate "Write compliance summary" \ --enableEvaluation ``` ``` Evaluation Summary - Overall: 8.6/10 (Passing threshold: 7) - Relevance: 9.0 - Accuracy: 8.5 - Completeness: 8.0 - Reasoning: Response covers all requested sections with correct policy references. ``` ## Streaming with Evaluation ```typescript const stream = await neurolink.stream({ input: { text: "Walk through the incident postmortem" }, enableEvaluation: true, // (1)! }); let final; for await (const chunk of stream) { if (chunk.evaluation) { // (2)! final = chunk.evaluation; // (3)! } } console.log(final?.overallScore); // (4)! ``` 1. Evaluation works in streaming mode 2. Evaluation payload arrives in final chunks 3. Capture the evaluation object 4. Access overall score (1-10) and sub-scores ## Configuration Options | Option | Where | Description | | ------------------------------------- | -------------------------------- | ------------------------------------------------------------------ | | `enableEvaluation` | CLI flag / request option | Turns the middleware on for this call. | | `evaluationDomain` | CLI flag / request option | Provides context to the judge model (e.g., `"Healthcare"`). | | `NEUROLINK_EVALUATION_THRESHOLD` | Env variable / loop session var | Minimum passing score; failures trigger retries or errors. | | `NEUROLINK_EVALUATION_MODEL` | Env variable / middleware config | Override the default judge model (defaults to `gemini-2.5-flash`). | | `NEUROLINK_EVALUATION_PROVIDER` | Env variable | Force the judge provider (`google-ai` by default). | | `NEUROLINK_EVALUATION_RETRY_ATTEMPTS` | Env variable | Number of re-evaluation attempts before surfacing failure. | | `NEUROLINK_EVALUATION_TIMEOUT` | Env variable | Millisecond timeout for judge requests. | | `offTopicThreshold` | Middleware config | Score below which a response is flagged as off-topic. | | `highSeverityThreshold` | Middleware config | Score threshold for triggering high-severity alerts. | Set global defaults by exporting environment variables in your `.env`: ```bash NEUROLINK_EVALUATION_PROVIDER="google-ai" NEUROLINK_EVALUATION_MODEL="gemini-2.5-flash" NEUROLINK_EVALUATION_THRESHOLD=7 NEUROLINK_EVALUATION_RETRY_ATTEMPTS=2 NEUROLINK_EVALUATION_TIMEOUT=15000 ``` > Loop sessions respect these values. Inside `neurolink loop`, use `set NEUROLINK_EVALUATION_THRESHOLD 8` or `unset NEUROLINK_EVALUATION_THRESHOLD` to adjust the gate on the fly. ## Best Practices :::tip[Cost Optimization] Only enable evaluation when needed: during prompt engineering, quality regression testing, or high-stakes production calls. For routine operations, disable evaluation and rely on [Analytics](/docs/reference/analytics) for zero-cost observability. ::: - Pair evaluation with analytics to track cost vs. quality trends. - Lower the threshold during experimentation, then tighten once prompts stabilise. - Register a custom `onEvaluationComplete` handler to forward scores to BI systems. - Exclude massive prompts from evaluation when latency matters; analytics is zero-cost without evaluation. ## Troubleshooting | Issue | Fix | | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------- | | `Evaluation model not configured` | Ensure judge provider API keys are present or set `NEUROLINK_EVALUATION_PROVIDER`. | | CLI exits with failure | Lower `NEUROLINK_EVALUATION_THRESHOLD` or configure the middleware with `blocking: false`. | | Evaluation takes too long | Reduce `NEUROLINK_EVALUATION_RETRY_ATTEMPTS` or switch to a smaller judge model (e.g., `gemini-2.5-flash-lite`). | | Off-topic false positives | Increase `offTopicThreshold` to a lower score (e.g., 3). | | JSON output missing evaluation block | Confirm `--format json` and `--enableEvaluation` are both set. | ## Related Features **Q4 2025 Features:** - [Guardrails Middleware](/docs/features/guardrails) – Combine evaluation with content filtering for comprehensive quality control **Q3 2025 Features:** - [Multimodal Chat](/docs/features/multimodal-chat) – Evaluate vision-based responses - [CLI Loop Sessions](/docs/features/cli-loop-sessions) – Set evaluation threshold in loop mode **Documentation:** - [Analytics Guide](/docs/reference/analytics) – Track evaluation metrics over time - [SDK API Reference](/docs/sdk/api-reference) – Evaluation options - [Troubleshooting](/docs/reference/troubleshooting) – Common evaluation issues --- ## AutoResearch - Autonomous AI Experiment Engine # AutoResearch - Autonomous AI Experiment Engine ## Overview AutoResearch is an autonomous experiment loop that proposes code changes, executes experiments, evaluates results against a deterministic metric, and keeps or discards each change — running unattended for hours. Inspired by Karpathy's autoresearch concept, it lets an AI agent continuously improve a program by iterating on code, measuring outcomes, and git-committing improvements. The system is available as both an **SDK API** and **CLI commands**, and integrates with NeuroLink's existing **TaskManager** for scheduled, long-running research sessions. - **Phase-gated tool access** — The AI only sees tools relevant to its current phase, preventing premature actions - **Git-backed safety** — Every candidate change is committed to a branch; failed experiments are reverted automatically - **Deterministic evaluation** — Metrics are parsed from experiment output via regex, not LLM judgment - **Two execution paths** — Run a single cycle interactively (`run-once`) or schedule continuous research via TaskManager (`start`) - **10 typed events** — Full observability into the experiment lifecycle via NeuroLink's event emitter ## Core Concepts ### Research Program A Markdown document (`program.md` by default) that describes the research objective, constraints, and evaluation criteria. The AI reads this to understand what it should optimize and how. ### Phases AutoResearch operates as a state machine with 9 phases. Each phase gates which tools the AI can use: | Phase | Description | Tools Available | Forced Tool | | -------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | --------------------------- | | **bootstrap** | Read the program and understand the codebase | `research_get_context`, `research_read_file`, `research_checkpoint` | `research_get_context` | | **baseline** | Run the experiment to establish a baseline | `research_run_experiment`, `research_parse_log`, `research_record`, `research_accept`, `research_checkpoint` | `research_run_experiment` | | **propose** | Propose a code change based on context | `research_get_context`, `research_read_file` | `research_get_context` | | **edit** | Write the proposed changes to mutable files | `research_read_file`, `research_write_candidate`, `research_diff` | — | | **commit** | Git-commit the candidate change | `research_commit_candidate` | `research_commit_candidate` | | **run** | Execute the experiment | `research_run_experiment` | `research_run_experiment` | | **evaluate** | Parse the log and inspect failures | `research_parse_log`, `research_inspect_failure` | `research_parse_log` | | **record** | Record the result to results.tsv | `research_record`, `research_checkpoint` | `research_record` | | **accept_or_revert** | Keep the change or revert to the last good commit | `research_accept`, `research_revert`, `research_checkpoint` | — | After `accept_or_revert`, the loop returns to `propose` for the next experiment cycle. ### Metric A quantitative measure extracted from experiment output using a regex pattern. You configure: - **name** — Human-readable metric name (e.g., `val_bpb`, `accuracy`) - **direction** — Whether `lower` or `higher` is better - **pattern** — Regex with one capture group to extract the numeric value from stdout/stderr ### Memory Metric (Optional) A secondary metric (e.g., `peak_vram_mb`) tracked for informational purposes but not used for accept/reject decisions. ### Mutable vs Immutable Paths - **mutablePaths** — Files the AI is allowed to modify (e.g., `["train.py"]`) - **immutablePaths** — Files the AI can read but must never modify (e.g., `["prepare.py", "program.md"]`) ### State Research state is persisted to `.autoresearch/state.json` and includes the current phase, branch name, accepted commit, baseline/best metrics, run count, and keep count. This enables resuming interrupted sessions. --- ## Architecture Follows NeuroLink's established **Factory + Registry** pattern with dedicated subsystems for each concern. ### Directory Structure ``` src/lib/autoresearch/ index.ts # Public exports (via @juspay/neurolink/autoresearch) config.ts # resolveConfig() + validateConfig() worker.ts # ResearchWorker — main orchestrator stateStore.ts # ResearchStateStore — state persistence repoPolicy.ts # RepoPolicy — git branch/commit/revert operations runner.ts # ExperimentRunner — subprocess execution resultRecorder.ts # ResultRecorder — TSV result logging summaryParser.ts # parseExperimentSummary() — log parsing promptCompiler.ts # PromptCompiler — system prompt generation phasePolicy.ts # Phase-gated tool access rules tools.ts # createResearchTools() — 12 tool definitions errors.ts # AutoresearchError + error codes src/lib/types/ autoresearchTypes.ts # All type definitions (251 lines) src/lib/tasks/ autoresearchTaskExecutor.ts # TaskManager integration + phase advancement src/cli/commands/ autoresearch.ts # CLI: `neurolink autoresearch` ``` ### Component Diagram ``` NeuroLink | ┌────────────┴────────────┐ v v ResearchWorker TaskManager (run-once path) (scheduled path) | | v v ┌───────┴───────┐ autoresearchTaskExecutor | | | v v v PhasePolicy PromptCompiler ResearchWorker (cached) | | | v v v ResearchTools SystemPrompt generate() + phase advance | ├── RepoPolicy ──── git operations (branch, commit, revert) ├── ExperimentRunner ── subprocess (runCommand) ├── ResultRecorder ──── results.tsv └── ResearchStateStore ── .autoresearch/state.json ``` ### How It Fits Into NeuroLink AutoResearch integrates at two levels: 1. **Direct SDK usage** — Import `ResearchWorker` from `@juspay/neurolink/autoresearch` and call `runExperimentCycle()` directly 2. **TaskManager integration** — The `autoresearchTaskExecutor` routes scheduled tasks to `ResearchWorker`, advancing phases after each `generate()` call --- ## Type Definitions ```typescript // ── Metric Configuration ───────────────────────────────── type MetricDirection = "lower" | "higher"; type MetricConfig = { name: string; direction: MetricDirection; pattern: string; // regex with one capture group }; type MemoryMetricConfig = { name: string; pattern: string; }; // ── Research Configuration ─────────────────────────────── type ResearchConfig = { repoPath: string; programPath: string; // Default: "program.md" mutablePaths: string[]; immutablePaths: string[]; resultsPath: string; // Default: "results.tsv" statePath: string; // Default: ".autoresearch/state.json" runCommand: string; logPath: string; // Default: "run.log" metric: MetricConfig; memoryMetric?: MemoryMetricConfig; timeoutMs: number; // Default: 600_000 (10 minutes) branchPrefix: string; // Default: "autoresearch/" provider?: string; model?: string; maxExperiments?: number; thinkingLevel?: ThinkingLevel; // Default: "medium" }; // ── Experiment Phase ───────────────────────────────────── type ExperimentPhase = | "bootstrap" | "baseline" | "propose" | "edit" | "commit" | "run" | "evaluate" | "record" | "accept_or_revert"; // ── Research State (persisted to .autoresearch/state.json) ── type ResearchState = { branch: string; acceptedCommit: string | null; baselineMetric: number | null; bestMetric: number | null; candidateCommit: string | null; runCount: number; keepCount: number; lastStatus: ExperimentStatus | null; currentPhase: ExperimentPhase; tag: string; startedAt: string; updatedAt: string; lastSummary?: ExperimentSummary | null; }; // ── Experiment Results ─────────────────────────────────── type ExperimentStatus = "keep" | "discard" | "crash" | "timeout"; type ExperimentSummary = { crashed: boolean; timedOut: boolean; metric: number | null; memoryValue: number | null; trainingSeconds: number | null; rawTail: string; }; type ExperimentRecord = { commit: string; metric: number | null; memoryGb: number | null; status: ExperimentStatus; description: string; timestamp: string; }; type ExperimentStats = { total: number; keepCount: number; discardCount: number; crashCount: number; timeoutCount: number; keepRate: number; bestMetric: number | null; bestCommit: string | null; }; // ── Worker Configuration ───────────────────────────────── type ResearchWorkerConfig = Omit, "repoPath" | "mutablePaths" | "runCommand" | "metric" > & { repoPath: string; mutablePaths: string[]; runCommand: string; metric: MetricConfig; }; // ── Phase Tool Policy ──────────────────────────────────── type PhaseToolPolicy = { activeTools: string[]; forcedTool?: string; }; ``` --- ## SDK API ### Direct Usage (ResearchWorker) For full control, import `ResearchWorker` from the `@juspay/neurolink/autoresearch` subpath export: ```typescript resolveConfig, validateConfig, ResearchWorker, } from "@juspay/neurolink/autoresearch"; const neurolink = new NeuroLink({ provider: "google-vertex", model: "gemini-2.5-flash", }); const config = resolveConfig({ repoPath: "/path/to/my-project", mutablePaths: ["train.py"], immutablePaths: ["prepare.py", "program.md"], runCommand: "python3 train.py", metric: { name: "val_bpb", direction: "lower", pattern: "^val_bpb:\\s+([\\d.]+)", }, timeoutMs: 120_000, }); validateConfig(config); const worker = new ResearchWorker(config); const state = await worker.initialize("experiment-apr8"); // Run a single experiment cycle const result = await worker.runExperimentCycle("Try reducing learning rate"); console.log(`Status: ${result.status}, Metric: ${result.metric}`); // Run multiple cycles for (let i = 0; i { console.log(`New best: ${payload.newBest} (commit: ${payload.commit})`); }); neurolink .getEventEmitter() .on("autoresearch:experiment-completed", (payload) => { console.log(`Experiment ${payload.runCount}: ${payload.status}`); }); // Manage lifecycle await neurolink.tasks.pause(task.id); await neurolink.tasks.resume(task.id); await neurolink.tasks.delete(task.id); ``` --- ## CLI Commands All CLI commands are under the `neurolink autoresearch` namespace. ### Initialize a Research Session ```bash neurolink autoresearch init /path/to/repo \ --tag "experiment-apr8" \ --target "train.py" \ --immutable "prepare.py,program.md" \ --run-command "python3 train.py" \ --metric-name val_bpb \ --metric-pattern "^val_bpb:\\s+([\\d.]+)" \ --metric-direction lower \ --timeout 600 \ --provider google-vertex \ --model gemini-2.5-flash ``` This creates `.autoresearch/state.json` and `.autoresearch/config.json` in the repo and creates a git branch (`autoresearch/`). ### Check Status ```bash neurolink autoresearch status # Current directory neurolink autoresearch status /path/to/repo # Specific repo neurolink autoresearch status --format json # JSON output ``` ### View Results ```bash neurolink autoresearch results # Table format (last 20) neurolink autoresearch results --last 50 # More results neurolink autoresearch results --format json # JSON output neurolink autoresearch results --format text # Plain text ``` ### Run a Single Experiment ```bash neurolink autoresearch run-once # Current directory neurolink autoresearch run-once /path/to/repo # Specific repo neurolink autoresearch run-once --description "Try Adam optimizer" ``` ### Start Scheduled Research (via TaskManager) ```bash # 300 seconds between ticks, stop after 100 experiments neurolink autoresearch start /path/to/repo --interval 300 --max-runs 100 ``` > **Two-step process:** `neurolink autoresearch start` saves an autoresearch task to the task store but does **not** begin execution by itself. You must separately start the task worker with `neurolink task start` to begin processing scheduled tasks. The task worker picks up saved tasks and executes experiment cycles on the configured interval. ### Manage Scheduled Tasks ```bash neurolink autoresearch pause # Pause a running task neurolink autoresearch resume # Resume a paused task neurolink autoresearch stop # Stop and cancel a task ``` > **Note:** These commands update the task's stored status in the task store (e.g., marking it as paused or cancelled). They do not directly signal a running task worker process. The task worker checks stored status before each cycle and will honor the updated state on its next tick. ### Reset State ```bash neurolink autoresearch reset # Current directory neurolink autoresearch reset /path/to/repo ``` This deletes the entire `.autoresearch/` directory (state, config, and all local artifacts). The git branch and committed experiment code on that branch are preserved. --- ## Research Tools AutoResearch registers 12 tools that the AI uses during experiment cycles. Tool availability is gated by the current phase. | Tool | Description | | --------------------------- | -------------------------------------------------------- | | `research_get_context` | Read the research program, current state, and results | | `research_read_file` | Read a file from the repository (respects path policies) | | `research_write_candidate` | Write changes to a mutable file | | `research_diff` | Show the git diff of pending changes | | `research_commit_candidate` | Git-commit the current candidate changes | | `research_run_experiment` | Execute the run command and capture output | | `research_parse_log` | Parse experiment output for metrics | | `research_inspect_failure` | Inspect why an experiment crashed or timed out | | `research_record` | Record an experiment result to results.tsv | | `research_accept` | Accept the current candidate (update accepted commit) | | `research_revert` | Revert to the last accepted commit | | `research_checkpoint` | Save current state to disk | --- ## Events AutoResearch emits events via NeuroLink's `TypedEventEmitter`. Subscribe to these for monitoring, alerting, or integration. ```typescript // Session lifecycle neurolink.getEventEmitter().on("autoresearch:initialized", (payload) => { // { tag, branch, config: { repoPath, runCommand, metric, timeoutMs } } }); neurolink.getEventEmitter().on("autoresearch:resumed", (payload) => { // { tag, branch, runCount, currentPhase } }); // Phase progression neurolink.getEventEmitter().on("autoresearch:phase-changed", (payload) => { // { from, to, runCount, tag } }); // Experiment lifecycle neurolink.getEventEmitter().on("autoresearch:experiment-started", (payload) => { // { tag, runCount, description } }); neurolink .getEventEmitter() .on("autoresearch:experiment-completed", (payload) => { // { tag, runCount, status, metric, commit, description, durationMs } }); // Metric tracking neurolink.getEventEmitter().on("autoresearch:metric-improved", (payload) => { // { tag, previousBest, newBest, commit, direction, runCount } }); // Git operations neurolink.getEventEmitter().on("autoresearch:revert", (payload) => { // { tag, targetCommit, reason, runCount } }); neurolink.getEventEmitter().on("autoresearch:revert-failed", (payload) => { // { tag, targetCommit, error, runCount } }); // State persistence neurolink.getEventEmitter().on("autoresearch:state-updated", (payload) => { // { tag, phase, runCount, keepCount, bestMetric } }); // Errors neurolink.getEventEmitter().on("autoresearch:error", (payload) => { // { tag, error, code?, phase?, runCount? } }); ``` --- ## Artifacts AutoResearch produces the following files in the repository: | Path | Description | | ----------------------------- | -------------------------------------------------- | | `.autoresearch/state.json` | Current research state (phase, metrics, run count) | | `.autoresearch/config.json` | Persisted configuration from `init` | | `.autoresearch/runs.jsonl` | JSONL audit log of all experiment records | | `results.tsv` | Tab-separated experiment results log | | `run.log` | Stdout/stderr from the last experiment run | | `autoresearch/` (branch) | Git branch containing all experiment commits | ### results.tsv Format ``` commit val_bpb memory_gb status description a1b2c3d 1.234 2.1 keep Reduced learning rate to 1e-4 d4e5f6a 1.256 2.3 discard Added dropout layer ``` > **Note:** The second column header is the metric name from your config (e.g., `val_bpb`, `accuracy`). The header is generated dynamically as `commit\t{metric.name}\tmemory_gb\tstatus\tdescription`. --- ## Configuration Reference ### ResearchConfig Fields | Field | Type | Default | Description | | ---------------- | -------------------- | ---------------------------- | -------------------------------------- | | `repoPath` | `string` | **required** | Absolute path to the git repository | | `programPath` | `string` | `"program.md"` | Research program document path | | `mutablePaths` | `string[]` | **required** | Files the AI can modify | | `immutablePaths` | `string[]` | `[]` | Files the AI can read but not modify | | `resultsPath` | `string` | `"results.tsv"` | Path for the results log | | `statePath` | `string` | `".autoresearch/state.json"` | Path for persisted state | | `runCommand` | `string` | **required** | Command to run the experiment | | `logPath` | `string` | `"run.log"` | Path for experiment stdout/stderr | | `metric` | `MetricConfig` | **required** | Primary metric configuration | | `memoryMetric` | `MemoryMetricConfig` | `undefined` | Optional secondary metric | | `timeoutMs` | `number` | `600_000` (10 min) | Per-experiment timeout in milliseconds | | `branchPrefix` | `string` | `"autoresearch/"` | Git branch prefix | | `provider` | `string` | SDK default | AI provider override | | `model` | `string` | SDK default | Model override | | `maxExperiments` | `number` | `undefined` (unlimited) | Maximum experiment count | | `thinkingLevel` | `ThinkingLevel` | `"medium"` | Thinking level for LLM calls | ### MetricConfig Fields | Field | Type | Description | | ----------- | --------------------- | -------------------------------------------------- | | `name` | `string` | Human-readable metric name | | `direction` | `"lower" \| "higher"` | Whether lower or higher values are better | | `pattern` | `string` | Regex with exactly one capture group for the value | --- ## Troubleshooting ### Experiment stuck in bootstrap phase The AI's first action in bootstrap is forced to `research_get_context`. If the program file doesn't exist or is empty, the AI has no context to work with. Ensure `program.md` exists in the repo with a clear research objective. ### Metric not being parsed Verify your regex pattern matches the experiment output. Test it: ```bash echo "val_bpb: 1.234" | grep -oP "^val_bpb:\s+([\d.]+)" ``` The pattern must have exactly one capture group. Common issue: escaping `\d` — in CLI flags and JSON, you need `\\d`. ### Experiments timing out Increase `timeoutMs` (default: 600,000ms / 10 minutes). For long-running training scripts, set appropriately: ```bash neurolink autoresearch init /repo --timeout 3600 # 1 hour ``` ### Git revert failures AutoResearch requires a clean working tree for reverts. If you have uncommitted changes outside mutable paths, commit or stash them first. ### State file corruption If `.autoresearch/state.json` becomes invalid, use `reset` to clear it: ```bash neurolink autoresearch reset /path/to/repo ``` Then re-initialize with `init`. Your git branch and committed experiments are preserved. --- ## FAQ **Q: What providers work with AutoResearch?** A: Any provider supported by NeuroLink. The AI needs tool-calling capability, so use models that support function calling (GPT-4o, Claude Sonnet, Gemini Flash/Pro, etc.). **Q: Can I use AutoResearch with Python/ML training scripts?** A: Yes — that's the primary use case. Set `runCommand` to your training script and configure the metric pattern to parse your output format. **Q: How does the AI decide what to change?** A: The AI reads the research program (`program.md`), the current code, and past experiment results. It proposes changes based on this context, using its understanding of the domain. The quality of your program document directly affects the quality of proposals. **Q: What happens if the experiment crashes?** A: The crash is detected via non-zero exit code or output parsing. The result is recorded as `crash` status, the candidate is reverted, and the loop continues with a new proposal. **Q: Can I run AutoResearch on a remote server?** A: Yes. Use the TaskManager integration with BullMQ (Redis) for scheduled runs. The repo must be accessible on the machine running NeuroLink. **Q: How do I stop a running experiment?** A: For `run-once`: Ctrl+C. For scheduled tasks: `neurolink autoresearch stop ` or `await neurolink.tasks.delete(taskId)`. **Q: Is there a limit on experiment count?** A: Set `maxExperiments` in config or `--max-runs` in CLI. Without a limit, research continues indefinitely until manually stopped. **Q: Can multiple AutoResearch sessions run on the same repo?** A: Not recommended. Each session operates on its own git branch, but concurrent filesystem operations on the same repo can conflict. Use separate working directories or git worktrees for parallel sessions. **Q: Does AutoResearch work with `structuredOutput`?** A: No. AutoResearch uses tool calling (function calling) which is mutually exclusive with `structuredOutput` JSON schemas on Gemini providers. This is an API limitation, not a bug. --- ## The model catalogue # The model catalogue The [classifier router](/docs/features/classifier-router) has always routed across a `pool` you declare — the set of models you are willing to be billed for is not something NeuroLink can invent. The catalogue is an opt-in way to widen that pool: it builds candidates from the model registry, intersected with the credentials this host actually holds, and hands them to the [`jev` strategy](/docs/features/classifier-router-jev-strategy) as one `choice` question. **The registry is 64 models across 7 providers** (openai 21, anthropic 19, azure 7, ollama 6, bedrock 5, mistral 4, google-ai 2), with 132 aliases on top of those 64 ids — only a subset of the providers NeuroLink can call. The catalogue is strictly an _addition_ to a declared pool, never a replacement for one: a host routing over LiteLLM, OpenRouter, an OpenAI-compatible endpoint, or anything self-hosted still declares those members by hand, and `enrichCandidate` ranks declared and catalogue members together on one scale rather than sorting them into separate buckets. Enabling `catalog` widens the pool for the 7 providers it knows; it does not make the rest of the registered providers appear. **The degradation contract.** `catalog.enabled` defaults to unset, and `buildModelCatalog()` returns `[]` when it is. Nothing about routing changes until you turn it on: the declared `pool` remains the only source of candidates. ```typescript const nl = new NeuroLink({ classifierRouter: { enabled: true, classifier: "auto", pool: [], // no hand-declared members — the catalogue is the whole pool catalog: { enabled: true, maxModels: 120, // default minContextWindow: 0, // default: keep all providers: ["openai", "anthropic", "azure"], // omit for every reachable provider the registry covers }, }, }); ``` A declared `pool` and an enabled `catalog` combine: declared members win on a duplicate `id` (or `provider/model` when no `id` is set), so a hand-declared override always beats the catalogue's own entry for the same model. ## Building the routable pool `buildModelCatalog()` starts from every model the registry knows and removes: - deprecated models, unless `includeDeprecated: true` - providers this host has no reachable credentials for (see below) - providers not in `catalog.providers`, when that list is set - models whose context window is below `catalog.minContextWindow` **Reachability is deliberately permissive**, in two directions. A provider whose credentials resolve through an external chain — Bedrock's AWS default chain, Vertex's several auth paths — is kept even though no single env var proves it is configured; a local runtime with no credential at all (Ollama, LM Studio) is likewise kept. What this actually filters out is the common case: a cloud provider with one named API-key env var that is simply unset. The worst case of being too permissive is a candidate that fails at call time and falls back, which the router already handles. What is left is capped to `maxModels` (default **120**) by a tier-neutral merit score — `tierScore(model, "moderate")` — so a truncated list, if there is one, keeps the models most likely to be broadly useful rather than whichever the registry happened to list first. **The default never truncates today**: the whole registry is 64 models, well under the cap. `maxModels` is a guard against a future registry that outgrows what a single question can carry, not a limit anyone is currently hitting. ## One line per model Each surviving model becomes a `ClassifierCandidate` and `renderCandidate()` turns it into one terse line for `jev`'s `criteria` map. The order and the precedence are both deliberate: 1. **`description` always renders first**, when present. 2. **`tiers`**, when declared, renders next as `intended for trivial/simple tasks` — the host's most direct statement of where a model belongs. 3. **Context window and capability flags always render.** These are facts about the model ("accepts images", "128K context"), not opinions about how good it is, so nothing suppresses them. 4. **Declared `cost`/`quality` replace the registry's own opinion, rather than sitting beside it.** When either is set, the line adds `capability N (higher is more capable)` / `relative cost N (lower is cheaper)` and _suppresses_ the registry's price, speed bucket, quality bucket, and "strong at …" use-case scores entirely. When neither is set, the registry fills all of that in exactly as it always did. Two real renders, from the same model, show the difference: ``` # No declared cost/quality — the registry fills in: GPT-4 Omni Mini; 128K context; 0.01c per 1K in; fast speed; high quality; supports vision, tools, reasoning, code, multimodal; strong at coding, analysis, conversation, reasoning, translation, summarization # Declared quality: 2, cost: 1 — the registry's opinion is suppressed: Cheap and fast; rote edits and simple lookups; 128K context; capability 2 (higher is more capable); relative cost 1 (lower is cheaper); supports vision, tools, reasoning, code, multimodal ``` **This precedence exists because the registry's opinion used to win, and a live measurement showed it silently overriding the host's own routing intent.** A pool member declared exactly the second line above — an explicit statement that this model is for rote work — but the registry rates the same underlying model highly on general benchmarks, so the old rendering appended its own "high quality" and "strong at coding, analysis, reasoning" on top. Five registry clauses against one line of host prose, and the host lost: a hard concurrency-bug task routed to the cheap model in 5 of 8 runs, because the model-pick question asks for "the cheapest one that can still complete this request correctly" and had just been told the cheap one was high quality and strong at reasoning. The declared `quality: 2` never reached the model at all — only `description` did. After the fix, the same 15-prompt suite (trivial/simple/conversational/hard/expert) routed 15/15 to the intended pool member, and the hard prompt went 8/8 to the capable model (previously 3/8). **Every catalogue-built candidate takes the "declared" branch, not just hand-written ones.** `buildModelCatalog()` fills in `cost` and `quality` for every model it selects (mapped from the registry's own bucket — `high` becomes `3`, for instance), and that happens _before_ the merged pool reaches `renderCandidate()`. So the richer registry-style line above (real price, speed bucket, quality bucket, "strong at …") is only ever reached by a **hand-declared** member that leaves both `cost` and `quality` unset. A model sourced from the catalogue always renders with the terse `capability N` / `relative cost N` phrasing — never with the registry's own use-case scores. Rendering is terse on purpose regardless of which branch it takes: this text is multiplied by the candidate count inside a single question, and that question — the model-choice `criteria` map — is what competes with the request for the [~33K state-plus-longest-question ceiling](/docs/features/decide-inference-type#limits-and-gotchas). At roughly 40 tokens per line there is ample headroom: the ceiling holds hundreds of rendered models, not the 64 the registry currently has to offer. Only use-cases scoring 8 or higher out of 10 are surfaced as "strong at" — mediocre scores are omitted rather than diluting the line. **`member.cost` is a relative scale, never a currency.** A host writing `cost: 20` to mean "the expensive one in my pool" is not read as $20 per 1K tokens — that would be three orders of magnitude off real pricing. Only `inputCostPer1K`, the registry's own field, is ever multiplied by 100 and rendered in cents. The one wrinkle: because `buildModelCatalog()` seeds a catalogue candidate's "relative cost" from the registry's real price sum rather than a small integer, its rendered value can look like `relative cost 0.00074` — correct (never mistaken for a dollar figure), just a smaller number than a hand-declared `cost: 1` would suggest at a glance. This doesn't affect ranking: the deterministic fallback score (below) normalizes price on its own scale, independently of what `renderCandidate()` prints. ## A `choice` over N models is a ranking of N Because `readDecisionChoice` returns every option's probability, one `choice` question over the whole catalogue doesn't just name a winner — it ranks all N candidates by how likely each is to be the right pick. This is what makes picking from up to `maxModels` (120 by default; the whole registry today is 64) a single request rather than N binary questions. ## Deterministic fallback ranking Every other `decide` consumer in this codebase falls back to _what the code already did_. There was no prior "pick from the whole registry" behaviour to fall back to, so the catalogue needed its own: `rankCatalogue()` runs whenever no decision provider is configured, the call fails, or the difficulty tier's own top-of-pool choice is what's needed (`selectModels()` always computes it, even when `jev`'s pick clears its bar, as the fallback list that ships alongside the winner). The ranking is `tierScore()` — a deterministic formula per difficulty: ``` merit = suitability * 0.5 + quality * 0.35 + speed * 0.15 score = merit - priceFactor * tierCostWeight ``` `suitability` reads the registry's own 1–10 score for the dimension that tier cares about (`conversation` for trivial/simple, `coding` for moderate, `reasoning` for hard/expert). `tierCostWeight` is what makes this a real ranker rather than a sort by price: at `trivial` it is `1` (the cheapest adequate model wins outright), at `expert` it is `0.05` (price is nearly irrelevant). This never consults the network and is the ordering the decision model's own pick is compared against when deciding whether it clears its bar. ## Context-window filtering Nothing in routing read `maxContextTokens` before this. Two independent checks now do: - **`rankCatalogue()`** filters candidates whose `contextWindow` is below the request's estimated input tokens, applied only when it would leave something behind (an empty result falls back to the unfiltered pool rather than routing nowhere). - **The classifier's own pick is separately vetoed.** Even when `jev` picks a model directly, `fitsRequest()` checks whether that specific model's window can hold the request. If it can't, the pick is dropped **regardless of confidence** — this is a hard provider error, not a degraded answer, because an oversized request against a real model puts that model into `ModelPool`'s permanent (10-year) cooldown. A wrong guess here is not "less accurate," it is unrecoverable for the life of the process. ## What this is bad at - **Registry quality is coarse, and the catalogue path never shows its own work.** Auto-enriched `quality` is a 3-bucket scale (`high`/`medium`/`low`) before `buildModelCatalog()` turns it into `1`/`2`/`3`; two "high" models cannot be separated on capability alone. Worse for this page's topic: because the catalogue always populates `cost`/`quality`, its rendered line never shows the registry's own price, speed bucket, or "strong at …" scores — only the terse `capability N` / `relative cost N` form. Declare `tiers`/`quality` on a hand-declared pool member for finer control over the number itself; there is no way to get the richer rendering for a catalogue-sourced model. - **A catalogue candidate's "relative cost" is real pricing wearing a relative label.** `buildModelCatalog()` seeds it from `inputCostPer1K + outputCostPer1K` — a small decimal like `0.00074` — not a small integer a host would typically pick for a hand-declared `cost`. The number is still correct and still never rendered as currency, but it does not compare cleanly against a hand-declared member's `cost: 1` in the same pool, since one is a real price and the other is an arbitrary scale. - **Unknown-to-the-registry models rank on relative numbers, not real prices.** A model the registry doesn't know (self-hosted, brand-new) keeps whatever `cost`/`quality` the host declared, compared only against other declared values on the same relative scale — never rendered as a dollar figure it isn't. - **A wide catalogue is still one `choice` question, and the cap is hard, not smart, when it does bind.** Every model adds tokens to that single question; `maxModels` is the safeguard, and a model past it would simply never be offered rather than offered with lower priority. Today this is theoretical — the registry is 64 models against a default cap of 120, so nothing is dropped — but the mechanism has no ranking behavior for the day a registry does exceed it. - **Permissive reachability means occasional dead candidates.** A provider kept because its credentials resolve externally can still fail at call time if those credentials are actually absent; the router's existing fallback handles it, but the catalogue does not pre-verify reachability, only presence of a plausible credential path. - **It cannot see quota, rate limits, or account-level restrictions.** Only the registry's static metadata and this host's env vars are consulted. ## See also - [Classifier Router](/docs/features/classifier-router) - [Model routing with a decision model](/docs/features/classifier-router-jev-strategy) - [The `decide` inference type](/docs/features/decide-inference-type) --- ## Model routing with a decision model # Model routing with a decision model The [classifier router](/docs/features/classifier-router) has a `jev` strategy: one [decision-model](/docs/features/decide-inference-type) round trip answers difficulty, required capabilities, risk **and** the model pick simultaneously, with a calibrated confidence on each. This page is the strategy's own mechanics — `classifier-router.md` covers the router as a whole. **The degradation contract.** With no decision provider configured, `resolveStrategy()` resolves `auto` to `heuristic`, exactly as it always did. `classifyJev()` itself never throws: any failure, timeout, or malformed answer falls back to `classifyHeuristic()`. Configuring a decision provider (for example `TYPESAFE_API_KEY` or `AI_GATEWAY_API_KEY`) upgrades routing; it cannot make routing worse than before the key existed. The same holds for `PERPLEXITY_API_KEY`, which is also the Perplexity text provider's key, and for `CLOUDFLARE_API_KEY` with `CLOUDFLARE_ACCOUNT_ID`, which are also the Cloudflare Workers AI text provider's token and account id, and for `SUBQ_API_KEY`, and for `OPENAI_API_KEY`, which is also the OpenAI chat provider's key (for a host with only that key `auto` now resolves to `jev`, answered by OpenAI Decisions, the default decision provider when none ahead of it is configured, unless `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL` names a host other than `https://api.openai.com`, which makes it a gateway's key), and for `SCALEDOWN_API_KEY`, which is ScaleDown's own and counts by itself (with only that key `auto` resolves to `jev`, answered by ScaleDown). "Configured" counts the environment, the instance `credentials`, and the request's own per-call `credentials` — a host that holds no decision key but passes a tenant's `credentials: { laya }` on a `generate()` call routes that call with `jev`, and the decision goes to the tenant's account. ```typescript const nl = new NeuroLink({ classifierRouter: { enabled: true, classifier: "auto", // jev once a decision provider is configured pool: [ { provider: "vertex", model: "gemini-2.5-flash" }, { provider: "vertex", model: "gemini-2.5-pro" }, ], }, }); ``` ## What goes into the state `classifyJev()` sends the request truncated to 8000 characters, plus four signals the caller already has on hand: ```json { "request": "...", "estimated_input_tokens": 412, "has_tools_available": true, "request_includes_images": false, "caller_requested_thinking": "none" } ``` Alongside it, one batch asks: `difficulty` (a `choice` over the five tiers), `needs_vision` / `needs_tools` / `needs_reasoning` (`boolean`), `risky` (`boolean`), `context` (a `score` — see [per-request context budget](/docs/features/context-budget)), and, only when the pool has more than one member, `model` (a `choice` over the pool, rendered by [the catalogue](/docs/features/classifier-router-catalog)). All of this rides in one request. On TypeSafe that takes ~400ms, because latency is flat in question count; on Perplexity each further question adds about 65 ms, up to 128 (see [its guide](/docs/getting-started/providers/perplexity-decider.md#limits)); on Cloudflare Clef a small request took 0.3 to 1.0 s on 2026-10-03 (see [its guide](/docs/getting-started/providers/cloudflare-clef.md#latency-and-the-timeout)). See [the batching rule](/docs/features/decide-inference-type#the-one-rule-batch-never-fan-out). NeuroLink refuses a state it estimates at more than 16,000 tokens (about 60,000 characters of prose) with `max_tokens_exceeded`, to keep Clef inside what it was seen to read in full and inside a timeout a fail-open consumer can afford. A longer request is refused there, and the heuristic classifier's tier stands, as it does on any failure. ## The difficulty rubric Five tiers, ordered easiest to hardest, worded about the shape of the work — the model is never told a provider or model name: | Tier | Criterion | | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `trivial` | Mechanical and local: rename a symbol, fix a typo, add an import, run one named command, or answer something already stated. | | `simple` | A small localised change or a direct factual answer. One file, one obvious approach. | | `moderate` | Ordinary engineering: implement a well-specified change across a few files, write tests, fix a clearly described bug, review a small diff. | | `hard` | Deep reasoning: architecture and design, debugging a failure whose cause is unknown, security analysis, concurrency, cross-system refactors. | | `expert` | Frontier-level work: ambiguous requirements, novel design with no established pattern, or analysis where a wrong answer is costly and hard to detect. | ## Asymmetric confidence bars, and why they differ A verdict harder than the neutral tier (`moderate`) spends **more** if wrong; a verdict easier than neutral spends **less** if wrong. Those are not the same mistake: - Routing a simple task to an expensive model wastes money. Cheap to be wrong about, so the bar to route **up** is low: `minUpgradeConfidence` defaults to **0.3**. - Routing a hard task to a weak model produces a wrong answer. Expensive to be wrong about, so the bar to route **down** is high: `minDowngradeConfidence` defaults to **0.6**. Below the applicable bar, the difficulty verdict is discarded and the heuristic classifier's tier stands instead — not a downgraded `jev` answer, the ordinary zero-cost fallback. One case skips both bars: a `risky` reading above 0.7 forces the tier to at least `hard`, unconditionally. Risk can only ever raise the tier, never lower one, and it is not itself gated by confidence. ### Ask about the act, not the subject The risk question is not "does this touch production, money, or credentials": > Carrying out this request would itself change production, move real money, > expose credentials, or alter data that cannot be restored. Writing or testing > code that deals with such things, without running it against the real system, > does not count. The naive phrasing was tried first and scored high on ordinary code that merely _concerns_ those things — "add a refund endpoint that calls Stripe" — which would have escalated every such request to the most expensive tier. The second sentence is what separates writing the code from running it against something real. ## The model pick faces a bar too — but a different one When the pool has more than one member, `jev` is also asked to choose directly: _"Which of these models is the cheapest one that can still complete this request correctly?"_ — over [the rendered candidate lines](/docs/features/classifier-router-catalog#one-line-per-model). That pick is reported with its own confidence, separate from the difficulty confidence, and the router decides which bar applies: ```ts const pickedCost = this.metaFor(picked).cost ?? NEUTRAL; const topCost = this.metaFor(tierTop).cost ?? NEUTRAL; const bar = pickedCost < topCost ? (this.config.minDowngradeConfidence ?? 0.6) // cheaper than the tier's own choice : (this.config.minUpgradeConfidence ?? 0.3); // costlier than the tier's own choice ``` Picking something **costlier** than what the difficulty tier would have picked on its own risks only spending more than necessary, so it clears the low upgrade bar. Picking something **cheaper** risks handing the task to a model that cannot do it, so it must clear the high downgrade bar. Agreeing with the tier needs no bar at all. If the pick fails its bar, it is dropped — logged as "classifier pick dropped — below its bar" — and the tier's own ranked list is used instead. This is a genuinely different question from the difficulty asymmetry above: that one asks whether the _tier_ is trustworthy; this one asks whether the _specific model choice_, once a tier is settled, is trustworthy — and the two can point in opposite directions (a confident-enough "hard" verdict whose model pick still misses its own, stricter bar). A pick that cannot physically hold the request is not gated at all — it is dropped outright, regardless of confidence, because that is a hard provider error rather than a degraded answer: see [the catalogue's context-window filtering](/docs/features/classifier-router-catalog#context-window-filtering). The `llm` strategy's picks are exempt from both bars: it reports no confidence for its pick, so a bar would either always pass or always fail. Its picks are honoured exactly as they were before `jev` existed — imposing a bar here would silently change an unrelated, already-shipped strategy. ## What this is bad at - **It cannot tell you why.** The `reason` field is a debug string built from the numbers, not an explanation the model gave. If you need an auditable rationale for a routing decision, this is the wrong tool. - **A close call still routes somewhere.** A 0.29 upgrade verdict and a 0.61 downgrade verdict are both one hundredth of a point from the bar, and both fall all the way back to the heuristic tier rather than to "the second most likely tier." There is no partial credit. - **The risk question is a single boolean.** It cannot express "risky, but only mildly" — anything past 0.7 jumps straight to `hard`, whatever the actual severity. - **It shares the base model's general limits.** Literal reading, no arithmetic, and state relevance affecting accuracy all apply here exactly as described in [what `decide` is bad at](/docs/features/decide-inference-type#what-it-is-bad-at). - **The pool still has to exist.** `jev` chooses among what you declared (or what [the catalogue](/docs/features/classifier-router-catalog) built); it cannot invent a model you have no credentials for. ## See also - [The `decide` inference type](/docs/features/decide-inference-type) - [Classifier Router](/docs/features/classifier-router) - [The model catalogue](/docs/features/classifier-router-catalog) - [Per-request context budget](/docs/features/context-budget) --- ## Classifier Router # Classifier Router > **Status**: Stable | **Availability**: SDK + CLI | **Opt-in** (disabled by default) ## Overview The **Classifier Router** lets NeuroLink decide, per request, **which model to use** (and, optionally, **which tools to expose**) from a pool you declare — routing hard/complex tasks to more capable models and easy tasks to cheaper, faster ones. You give it a pool of models; it classifies the incoming prompt and switches to the best one transparently before the call runs. ``` ┌─────────────── classifier router ───────────────┐ generate() → │ classify difficulty → pick model + tools → │ → chosen model runs └──────────────────────────────────────────────────┘ ``` It is **opt-in** (`classifierRouter.enabled` defaults to `false`), **fails open** (any classifier/selection error leaves the call exactly as it would have been), and is fully **backward compatible** — a default `new NeuroLink()` is unchanged. Typical use cases: - **Cost optimization** — send `"hi"` to a cheap model and a multi-step architecture question to a powerful one, automatically. - **Latency optimization** — keep simple turns on fast models. - **Custom / self-hosted fleets** — route across LiteLLM, OpenAI-compatible, or Ollama models that aren't in any registry. - **Per-difficulty tool scoping** — expose fewer tools for trivial tasks. ## How it works Each request flows through two stages: 1. **Classify** — produce a difficulty bucket (`trivial | simple | moderate | hard | expert`) plus optional `requiredCapabilities` and tool hints. Four strategies: - `auto` (default): resolves to `jev` when a decision provider is configured (`TYPESAFE_API_KEY` or `AI_GATEWAY_API_KEY`, `LAYA_API_KEY` with `LAYA_BASE_URL`, `XOR_API_KEY` with `XOR_BASE_URL`, `SUBQ_API_KEY`, `PERPLEXITY_API_KEY`, `CLOUDFLARE_API_KEY` with `CLOUDFLARE_ACCOUNT_ID`, `OPENAI_API_KEY`, or `SCALEDOWN_API_KEY`), and `heuristic` otherwise. Setting a key therefore upgrades routing with no code change; without one, behaviour is exactly as it was. `PERPLEXITY_API_KEY` is also the Perplexity text provider's key, so it counts here too, and `CLOUDFLARE_API_KEY` with `CLOUDFLARE_ACCOUNT_ID` are also the Cloudflare Workers AI text provider's token and account id, so they count here as well; `OPENAI_API_KEY` is also the OpenAI chat provider's key, so for a host with only that key `auto` now resolves to `jev`, answered by OpenAI Decisions, the default decision provider when none ahead of it is configured (a paid call, though routing still falls back to the heuristic on any failure), unless `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL` names a host other than `https://api.openai.com`: that key is taken to be a gateway's and `auto` stays on `heuristic`. `SCALEDOWN_API_KEY` is ScaleDown's own key and counts by itself: with only that key `auto` resolves to `jev`, answered by ScaleDown (also a paid call, with the same fallback). The gate counts the credentials given to the `NeuroLink` constructor, the environment and the request's own per-call credentials, so a `credentials.subq.apiKey` (or `credentials.laya`, `credentials.xor`, `credentials.perplexityDecider`, `credentials.cloudflareClef`, `credentials.openaiDecisions`, `credentials.scaledown` and the other decision providers' slices) passed on a single call can make `auto` pick `jev` rather than `heuristic`, but it adds a provider and does not pin one. The decision goes to that account only when no decision provider ahead of it in the order is configured; otherwise it goes to the first one that is. - `heuristic`: zero-cost keyword/length scoring of the prompt text. No LLM call, fully deterministic, provider-agnostic. - `llm`: a cheap "classifier model" reads the prompt and returns a difficulty — and, when given your pool, **picks a model directly** by id. - `jev`: [a decision model](/docs/features/decide-inference-type) (the first configured decision provider, in the order TypeSafe's Jev, Laya, XOR, SubQ, Perplexity, Cloudflare Clef, OpenAI Decisions, ScaleDown) answers difficulty, required capabilities **and** the model pick in one request, with a confidence for each answer. On TypeSafe's Jev that request takes ~400 ms and the confidence is _calibrated_; the [Perplexity guide](/docs/getting-started/providers/perplexity-decider) gives its latency and the confidence it reports, and the [Cloudflare Clef guide](/docs/getting-started/providers/cloudflare-clef) gives its latency and its state limit (16,000 estimated tokens, so a longer prompt is refused and the heuristic stands). Verdicts that miss the applicable confidence bar (`minUpgradeConfidence` 0.3 to route up, `minDowngradeConfidence` 0.6 to route down) fall through to the heuristic rather than acting on a guess. See [the `decide` inference type](/docs/features/decide-inference-type). 2. **Select** — turn that into a concrete `{ provider, model, region }` from your `pool`, optionally narrowing `tools`. The router runs **before** the provider/model is constructed (it reuses the same pre-call seam as `requestRouter`). It is skipped when the caller pinned both `provider` and `model`, or when a [`modelPool`](/docs/features/provider-orchestration) is configured (the pool owns selection). ## Quick start (heuristic, SDK) ```typescript const nl = new NeuroLink({ classifierRouter: { enabled: true, classifier: "heuristic", // default — no LLM cost pool: [ { provider: "vertex", model: "gemini-2.5-flash" }, // cost/quality auto-enriched { provider: "vertex", model: "gemini-2.5-pro" }, ], }, }); await nl.generate({ input: { text: "hi" } }); // → routed to gemini-2.5-flash await nl.generate({ input: { text: "Design a fault-tolerant multi-region event architecture and justify the consistency trade-offs.", }, }); // → routed to gemini-2.5-pro ``` ## Defining "which model for which case" The router resolves a model using the **first** of these that applies: | # | Mechanism | How you define it | Best for | | --- | ---------------------- | ---------------------------------------------------------------------------------- | ------------------------------------- | | 1 | **LLM direct pick** | `classifier: "llm"` + a `description` on each pool member | Custom/registry-less models; smartest | | 2 | **`tierMap`** | Explicit `difficulty → members` map | Full, deterministic control | | 3 | **Per-member `tiers`** | `tiers: ["hard","expert"]` on a member | Simple, explicit, generic | | 4 | **Metadata scoring** | `cost` / `quality` per member (declared, or auto-enriched from the model registry) | Known models with comparable metadata | > When two members can't be separated (e.g. equal declared quality, or the model registry only knows both as "high" quality), the router keeps the declared pool order. For reliable hard-vs-easy separation, prefer mechanisms 1–3, or give members distinct `quality` values. ### Metadata scoring rules - `trivial` / `simple` → cheapest first (`cost` ascending) - `moderate` → best `quality − cost` - `hard` / `expert` → most capable first (`quality` descending) Members may declare `cost` (relative, lower = cheaper) and `quality` (relative, higher = more capable). If omitted, NeuroLink tries to enrich them from its model registry; if the model is unknown (e.g. a custom LiteLLM endpoint), use mechanisms 1–3 instead. ## Custom & self-hosted models (LiteLLM, OpenAI-compatible, Ollama) These models aren't in any registry, so define routing explicitly — both approaches are fully generic: **Heuristic + `tiers` (deterministic, no LLM cost):** ```typescript new NeuroLink({ classifierRouter: { enabled: true, classifier: "heuristic", pool: [ { provider: "litellm", model: "my-fast-endpoint", tiers: ["trivial", "simple", "moderate"], }, { provider: "litellm", model: "my-strong-endpoint", tiers: ["hard", "expert"], }, ], }, }); ``` **LLM picks per-prompt from plain-English descriptions (most flexible):** ```typescript new NeuroLink({ classifierRouter: { enabled: true, classifier: "llm", classifierModel: { provider: "litellm", model: "cheap-classifier-model" }, pool: [ { provider: "litellm", model: "my-fast-endpoint", description: "cheap & fast; greetings, simple lookups, short Q&A", }, { provider: "litellm", model: "my-strong-endpoint", description: "powerful reasoning; complex multi-step analysis, architecture, hard math/code", }, ], }, }); ``` The classifier model is shown each candidate's `id` (defaults to `provider/model`) and description, and returns the best `id` for the prompt. An invalid or absent pick falls back to difficulty-based selection; any classifier failure falls back to the heuristic. ## Narrowing tools per difficulty Filter the tool set per difficulty with `toolDirectives` (and/or let the LLM classifier suggest tools). `toolFilter` is an allowlist; `excludeTools` is a denylist — both are enforced by the provider before the model call. ```typescript new NeuroLink({ classifierRouter: { enabled: true, pool: [...], toolDirectives: { trivial: { toolFilter: [] }, // no tools for trivial turns expert: { excludeTools: ["delete_resource"] }, }, }, }); ``` ## CLI usage ```bash # Heuristic routing across a pool (inline JSON or a file path) neurolink generate "hi" \ --classifier-router \ --classifier-pool '[{"provider":"vertex","model":"gemini-2.5-flash","tiers":["trivial","simple","moderate"]},{"provider":"vertex","model":"gemini-2.5-pro","tiers":["hard","expert"]}]' # LLM classifier picks the model per prompt (descriptions drive the choice) neurolink generate "Design a multi-region architecture" \ --classifier-router \ --classifier-strategy llm \ --classifier-model-provider vertex --classifier-model-name gemini-2.5-flash \ --classifier-pool ./pool.json ``` | Flag | Description | | --------------------------------------- | ------------------------------------------------------- | | `--classifier-router` | Enable the classifier router. | | `--classifier-strategy` | `auto` (default), `heuristic`, `llm` or `jev`. | | `--classifier-min-upgrade-confidence` | Confidence needed to route UP (`jev`; 0.3). | | `--classifier-min-downgrade-confidence` | Confidence needed to route DOWN (`jev`; 0.6). | | `--classifier-model-provider` | Provider for the LLM classifier model (`strategy=llm`). | | `--classifier-model-name` | Model name for the LLM classifier model. | | `--classifier-model-region` | Region for the LLM classifier model. | | `--classifier-pool` | JSON file path or inline JSON array of pool members. | | `--classifier-timeout` | LLM classifier hard timeout (ms). | > CLI flags cover the common case (strategy, classifier model, pool). For `tierMap` and `toolDirectives`, use the SDK config. ## Configuration reference ```typescript type ClassifierRouterConfig = { enabled: boolean; // master switch; false/absent → router never built classifier?: "auto" | "heuristic" | "llm" | "jev"; // default: "auto" minUpgradeConfidence?: number; // route UP ("jev"); default 0.3 minDowngradeConfidence?: number; // route DOWN ("jev"); default 0.6 classifierModel?: { provider?: string; model?: string; region?: string; temperature?: number; }; // for "llm" pool: ClassifierRouterPoolMember[]; // the available base tierMap?: Partial>; toolDirectives?: Partial >; timeoutMs?: number; // LLM classifier hard timeout (default 8000) catalog?: ClassifierCatalogConfig; // widen pool with registry models this host has credentials for; off by default contextBudget?: boolean; // ask the classifier how much context is needed and lower compaction threshold; default true for a decision-model strategy }; type ClassifierRouterPoolMember = { provider: string; model?: string; region?: string; id?: string; // stable id for LLM selection (default `provider/model`) description?: string; // drives LLM selection tiers?: ClassifierDifficulty[]; // restrict member to these difficulties cost?: number; // relative cost (lower = cheaper) quality?: number; // relative quality (higher = more capable) capabilities?: string[]; // e.g. ["vision","tools","reasoning"] weight?: number; // tiebreak }; ``` ## Precedence & interactions Model selection resolves in this order: **caller-pinned `provider`+`model`** > **classifierRouter** > **`requestRouter`** > legacy `enableOrchestration`. The classifier marks the request so the downstream selectors stand down. - **`modelPool`** — when a `modelPool` is configured the classifier stands down (the pool owns selection); use one or the other for model choice. - **`toolRouting`** — the dedicated tool-routing feature still applies; classifier `toolDirectives` are additive. ## Caveats - **Registry quality is coarse.** Auto-enrichment maps a model to a 3-bucket quality (`high/medium/low`), so two "high" models can't be separated on capability alone — declare `quality`/`tiers`/`tierMap` or use the LLM pick for reliable hard-vs-easy routing. - **LLM classifier latency/cost.** The `llm` strategy adds one cheap call per uncached turn; prefer a small, fast, non-Gemini model and use `heuristic` where determinism matters. - **Jev confidence is a gate, not a score.** Unlike the `llm` strategy — whose self-reported confidence defaults to a hard-coded `0.7` when the model omits it — `jev` returns the confidence the decision provider reports (calibrated, on TypeSafe's Jev) rather than a constant, which is what makes `minConfidence` meaningful. The two bars differ because the mistakes cost differently: spending more on a wrong guess wastes money, spending less produces a wrong answer. Set either above 1 to force the heuristic while leaving the strategy configured. - **Gemini tools + JSON schema.** The classifier call uses a schema with tools disabled, so the Gemini exclusivity rule doesn't apply to it; when routing a tools + structured-output request, prefer a non-Gemini target model. - **Prompt privacy (`llm` and `jev`).** Both strategies send a truncated copy of the prompt off-machine — to the classifier model, or to the configured decision provider — so the same data-handling and retention considerations as any provider call apply. `heuristic` keeps classification fully in-process (no prompt leaves your environment); prefer it where that matters, and note that `auto` selects `jev` as soon as a decision provider's key is present, including a `PERPLEXITY_API_KEY` set only for the Perplexity text provider, a `CLOUDFLARE_API_KEY` and `CLOUDFLARE_ACCOUNT_ID` set only for the Cloudflare Workers AI text provider, or an `OPENAI_API_KEY` set only for the OpenAI chat provider. ## See also - [Provider Orchestration & Model Pool](/docs/features/provider-orchestration) - [Provider Fallback](/docs/features/provider-fallback) - [Per-Request Credentials](/docs/features/per-request-credentials) - [Model routing with a decision model](/docs/features/classifier-router-jev-strategy) - [The model catalogue](/docs/features/classifier-router-catalog) --- ## Claude Proxy Architecture # Claude Proxy Architecture ## 1. System Overview The Claude proxy is a local HTTP server that sits between Claude Code and the Anthropic API. It provides multi-account rotation, automatic token refresh, rate-limit handling with exponential backoff, and optional model translation to non-Anthropic providers. ### Two operational modes | Mode | When | What happens | | --------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Passthrough** | Target provider is `anthropic` (or `null`) | The request body is forwarded byte-for-byte to `api.anthropic.com` via plain `fetch()` with client headers forwarded. No parsing, no tool injection, no SDK involvement. | | **Translation** | Target provider is anything else (e.g. `vertex`, `openai`) | The Claude-format request is parsed by `parseClaudeRequest()`, routed through `ctx.neurolink.stream()` / `ctx.neurolink.generate()`, and the NeuroLink response is serialized back to Claude SSE format via `ClaudeStreamSerializer`. | Passthrough exists because Claude Code sends complex bodies (multi-turn conversations, tool definitions, thinking blocks, context management betas) that would be lossy to parse and re-serialize. The proxy's job for Claude-to-Claude is purely auth and account management. ### How it fits into NeuroLink The proxy is started via the CLI (`neurolink proxy start`) and creates a Hono HTTP server. It registers routes from `createClaudeProxyRoutes()` and injects a live `NeuroLink` SDK instance into the request context for translation-mode and fallback paths. MCP initialization is explicitly skipped (`NEUROLINK_SKIP_MCP=true`) because tools come from Claude Code, not from MCP servers. ## 3. Account Management ### Account loading priority Accounts are loaded in the `POST /v1/messages` handler on every request (not cached across requests), in this order: 1. **TokenStore compound keys** (`anthropic:`) — The primary source. `tokenStore.listProviders()` returns all stored keys; those starting with `anthropic:` are loaded via `tokenStore.loadTokens(key)`. Each yields `{ accessToken, refreshToken, expiresAt }`. 2. **Legacy credentials file** (`~/.neurolink/anthropic-credentials.json`) — Only checked when zero compound keys exist. Reads `creds.oauth.accessToken` directly from JSON. 3. **Environment variable** (`ANTHROPIC_API_KEY`) — Only used when no OAuth accounts were found at all. Creates a single `api_key`-type account. ### Account selection: strategy-driven with fill-first default The request handler supports two real account-selection strategies: - **`fill-first` (default)** — always begin with the current primary account and stay on it until it cools down or fails. - **`round-robin`** — rotate the starting account on each request, then try the remaining accounts sequentially. Expired accounts are pruned at startup via `tokenStore.pruneExpired()` (one-time). Accounts that are persisted as disabled (via `tokenStore.isDisabled()`) are skipped. Expired tokens with a refresh token get one refresh attempt at startup; on failure, the account is disabled until re-authentication. The CLI `--strategy` flag and the proxy config `routing.strategy` field both map directly to this account ordering logic. There are only two supported values today: `fill-first` and `round-robin`. ### Per-status cooldowns | HTTP Status | Cooldown | Behavior | | ------------------------------------ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | **429** (rate limit) | Exponential backoff (see below) | Continue to next account | | **401/402/403** (auth failure) | 5 minutes (`AUTH_COOLDOWN_MS`) | Attempt token refresh first (up to 5 retries); if all fail, cooldown and continue. After 15 consecutive refresh failures, account permanently disabled. | | **404** (not found) | None | Return error immediately (no failover) | | **5xx, 52x** (transient) | None | Rotate immediately to next account | | **Network error** (ECONNRESET, etc.) | None | Rotate immediately to next account | ### Exponential backoff formula (429s) ``` backoffMs = min(baseCooldown * 2^level, 10 minutes) ``` Where: - `baseCooldown` = `Retry-After` header value (parsed as seconds or HTTP date), or 1 second if absent (`RATE_LIMIT_BACKOFF_BASE_MS`) - `level` = number of consecutive 429s for that account (incremented per 429, reset to 0 on success) - Cap = 10 minutes (`RATE_LIMIT_BACKOFF_CAP_MS = 10 * 60 * 1000 ms`) The `Retry-After` header is parsed two ways: as an integer (seconds) or as an HTTP date string. ### Account runtime state Each account has in-memory runtime state (`RuntimeAccountState`): | Field | Type | Purpose | | ---------------------------- | --------- | ----------------------------------------------------- | | `coolingUntil` | `number?` | Timestamp when cooldown expires | | `backoffLevel` | `number` | Current exponential backoff level (resets on success) | | `consecutiveRefreshFailures` | `number` | Cumulative token refresh failures across requests | | `permanentlyDisabled` | `boolean` | Account disabled until re-authentication | | `lastToken` | `string?` | Last known access token (for change detection) | | `lastRefreshToken` | `string?` | Last known refresh token (for change detection) | When an account's token material changes (e.g., user re-authenticates), all runtime state is reset, and a permanently disabled account is re-enabled automatically. ### Token refresh: two triggers 1. **Per-request refresh** (claudeProxyRoutes.ts, before each `fetch()`) — Checks if `oauth.expiresAt `** — Wrapped in a `ReadableStream` and returned with SSE headers (translation streaming). - **Object with `httpStatus`** — Returned as JSON with that status code. - **Object with `type: "error"`** — Status mapped via `mapClaudeErrorTypeToStatus()`. --- ## 6. OAuth Cloaking (oauthFetch.ts) **Important:** The proxy passthrough path does NOT use `createOAuthFetch()`. It uses plain `fetch()` with manually constructed headers (client headers forwarded, auth overridden, oauth beta ensured). The `oauthFetch.ts` module is used only by the direct NeuroLink Anthropic provider for SDK usage. `createOAuthFetch()` is a factory that returns a custom `fetch` function. It has two modes controlled by the `skipBodyTransform` parameter: ### Direct mode (`skipBodyTransform = false`) Used by the NeuroLink Anthropic provider for direct SDK usage. Full cloaking: - All passthrough modifications, plus: - Sets `User-Agent` to `CLAUDE_CLI_USER_AGENT` - Adds the full Claude-Code beta set, including `oauth-2025-04-20`, `claude-code-20250219`, `context-management-2025-06-27`, `prompt-caching-scope-2026-01-05`, `advanced-tool-use-2025-11-20`, and `effort-2025-11-24` - Adds identity headers: `anthropic-dangerous-direct-browser-access`, `x-app: cli` - Adds Stainless SDK headers (`x-stainless-runtime`, `x-stainless-lang`, `x-stainless-os`, `x-stainless-arch`, `x-stainless-package-version`, `x-stainless-retry-count`, `x-stainless-timeout`) - **Body modifications:** - Injects a deterministic Claude-Code-shaped billing header block into the system prompt so prompt caching remains stable - Injects agent identity block: `"You are a Claude agent, built on Anthropic's Claude Agent SDK."` - Injects `metadata.user_id` as a JSON string with `device_id`, `account_uuid`, and `session_id` - Prefixes tool names with `mcp_` when `enableMcpPrefix` is true - Disables `thinking` when `tool_choice.type` is `"any"` or `"tool"` - Injects W3C trace headers and `x-claude-code-session-id` when the proxy owns the request shape ### MCP prefix handling When `enableMcpPrefix` is true, the outbound request has all tool names prefixed with `mcp_`. The response stream is then post-processed: a `TransformStream` with a carry buffer (24 bytes) replaces `"name": "mcp_..."` patterns back to `"name": "..."` to strip the prefix from returned tool calls. ### Why cloaking exists The Anthropic OAuth API requires specific headers and body structures (billing header, user ID, beta flags) that differ from the standard API-key flow. Cloaking makes NeuroLink requests indistinguishable from official Claude CLI requests, which is required for OAuth + tools to work correctly. Extracting this into `oauthFetch.ts` benefits both the proxy passthrough path and the direct SDK Anthropic provider. --- ## 7. Fail-Open Guard The fail-open guard is a detached child process spawned by `proxy.ts` at startup via `spawnFailOpenGuard()`. It runs as a hidden CLI command (`neurolink proxy guard`). ### Behavior 1. Polls the proxy's `/health` endpoint every `pollIntervalMs` (default: 1 second) with a 1.5-second timeout. 2. Tracks consecutive unhealthy responses (counter resets on any healthy response). 3. Also checks if the parent process (proxy) is still running via `process.kill(pid, 0)`. ### Trigger conditions The guard takes action when either: - The parent process has exited AND the health endpoint is not responding (another proxy has not taken over). - The health endpoint has been consecutively unhealthy for `failureThreshold` checks (default: 5) while the parent still exists. ### Action taken 1. Removes `ANTHROPIC_BASE_URL` and `ENABLE_TOOL_SEARCH` from `~/.claude/settings.json` (only if the URL matches the expected proxy URL — does not clobber a different proxy). 2. Clears the proxy state file if the recorded PID is no longer running. ### Why it exists Without the guard, if the proxy crashes, Claude Code would keep trying to route requests to the dead proxy URL. The guard ensures Claude Code falls back to direct Anthropic API access automatically, preventing a stuck state. --- ## 8. Design Decisions ### WHY passthrough over NeuroLink for Claude targets Claude Code sends complex request bodies: multi-turn conversations with interleaved tool use/result blocks, thinking blocks, context management betas, system prompts with cache control, image blocks, and tool definitions with complex JSON schemas. Parsing this into NeuroLink's internal format and re-serializing would be lossy (losing features like `prompt-caching-scope`, thinking configuration, exact tool schemas). Passthrough preserves byte-level fidelity. ### WHY strategy-driven account selection Most Claude Code usage benefits from identity stability, so `fill-first` is the default. It keeps one account "hot" until rate limits or auth failures force rotation. `round-robin` is still available when a deployment wants to spread traffic more evenly across accounts. ### WHY cloaking is in oauthFetch.ts The cloaking logic (billing headers, fake user IDs, Stainless headers) is needed both by the proxy passthrough path and by the direct NeuroLink Anthropic provider. Extracting it into a shared module avoids duplication. The `skipBodyTransform` flag allows the same factory to serve both use cases with different levels of body modification. ### WHY MCP is skipped for proxy The proxy sets `NEUROLINK_SKIP_MCP=true` before creating the NeuroLink instance. Tools come from Claude Code (the client sends tool definitions in the request body). Initializing MCP servers would add startup latency, consume resources, and potentially conflict with tools the client already manages. ### WHY tools are passed through in translation/fallback mode When falling back to non-Anthropic providers, the proxy passes tools, thinking configuration, and conversation history through to `ctx.neurolink.stream()` with `maxSteps: 1`. This enables fallback providers to see the full request context and produce tool_use blocks if supported. The `maxSteps: 1` limit prevents the proxy from running a multi-step agent loop (that is Claude Code's responsibility). Tool schemas are wrapped via NeuroLink's own `jsonSchema()` (`src/lib/utils/tool.ts`) to ensure compatibility across providers. --- ## 9. Component Diagram ``` proxy.ts (CLI command) │ ├── Creates NeuroLink instance (NEUROLINK_SKIP_MCP=true) ├── Loads the first last-known-good runtime config generation ├── Watches proxy config + proxy env files (debounced; SIGHUP supported) ├── Atomically publishes immutable routing snapshots for new requests ├── Initializes requestLogger + usageStats + OpenTelemetry (OTLP traces/metrics/logs) ├── Builds Hono app │ │ │ ├── /v1/messages ─→ claudeProxyRoutes.ts (POST) │ ├── /v1/models ─→ claudeProxyRoutes.ts (GET) │ ├── /v1/messages/count_tokens ─→ claudeProxyRoutes.ts (POST) │ ├── /health ─→ inline handler │ └── /status ─→ inline handler (imports usageStats) │ ├── Starts @hono/node-server on host:port ├── Spawns fail-open guard (detached child process) ├── Auto-configures ~/.claude/settings.json (ANTHROPIC_BASE_URL + ENABLE_TOOL_SEARCH) ├── Reactive token refresh (per-request + on-401) ├── Log rotation (startup + hourly: 7 days, 500 MB cap) ├── Summary logs to ~/.neurolink/logs/proxy-*.jsonl ├── Attempt logs to ~/.neurolink/logs/proxy-attempts-*.jsonl ├── Debug index to ~/.neurolink/logs/proxy-debug-*.jsonl ├── Redacted body artifacts to ~/.neurolink/logs/bodies/YYYY-MM-DD//*.json.gz ├── OTel flush + shutdown on exit └── Graceful shutdown (SIGTERM/SIGINT → clear settings, close server) proxyTracer.ts ├── Creates request-level OTel span (receive → end) ├── Creates per-retry upstream spans ├── Records token usage, cost, rate-limit attributes └── Writes traceId/spanId into request log entry sseInterceptor.ts ├── Zero-overhead TransformStream (taps SSE without buffering) ├── Extracts token counts, model, content blocks, stop reason └── Resolves telemetry promise on stream end claudeProxyRoutes.ts │ ├── Passthrough path (isClaudeTarget): │ ├── tokenStore.ts ─ load compound keys (anthropic:) │ ├── anthropic-credentials.json ─ legacy fallback │ ├── ANTHROPIC_API_KEY env ─ last resort │ ├── tokenRefresh.ts logic ─ inline refresh (1 hour buffer + on-401 x5) │ ├── plain fetch() ─ direct HTTP to api.anthropic.com (client headers forwarded) │ ├── accountQuota.ts ─ parse unified-5h/7d quota headers │ └── Bootstrap retry ─ verify first stream chunk │ ├── Translation path (!isClaudeTarget): │ ├── claudeFormat.ts ─ parseClaudeRequest() + ClaudeStreamSerializer │ ├── ctx.neurolink.stream() ─ NeuroLink SDK │ └── SSE keep-alives ─ 15s interval │ ├── Fallback path (all accounts exhausted): │ ├── modelRouter.ts ─ getFallbackChain() │ ├── claudeFormat.ts ─ parse + serialize │ └── ctx.neurolink.stream() ─ with tools, thinking, conversationMessages │ └── Error helpers: ├── isInvalidRequestError() ├── isTransientHttpFailure() ├── isRetryableNetworkError() └── parseClaudeErrorBody() oauthFetch.ts (shared module) │ ├── createOAuthFetch() factory │ ├── skipBodyTransform=true ─ proxy passthrough (headers only) │ └── skipBodyTransform=false ─ direct SDK (full cloaking) │ ├── Billing header injection ├── Claude-Code-shaped metadata.user_id generation (cached and reused per seed) ├── Stainless SDK header spoofing └── MCP tool prefix/strip (carry-buffer stream transform) Supporting modules: ├── modelRouter.ts ─ resolve() model → { provider, model } ├── claudeFormat.ts ─ Claude API ↔ NeuroLink format conversion ├── requestLogger.ts ─ Request summaries, attempt logs, OTLP log export, debug body capture ├── usageStats.ts ─ In-memory per-account stats (resets on restart) ├── tokenRefresh.ts ─ Shared refresh logic (needsRefresh, refreshToken, persistTokens) ├── accountQuota.ts ─ Parse unified-5h/7d quota headers, debounced persistence ├── proxyConfig.ts ─ YAML/JSON config loader with env var interpolation └── tokenStore.ts ─ Multi-provider token persistence (~/.neurolink/tokens.json) Peer sharing (see /docs/features/proxy-peer-sharing): ├── shareGate.ts ─ Inbound gate; refusal contract (x-neurolink-grant-*) ├── shareGrants.ts ─ Grant store, token minting/hashing, hot reload on mtime ├── sharePolicy.ts ─ Pure admission evaluation; account scoping and slicing ├── shareLedger.ts ─ NeuroCoins (hold → settle) and per-window buckets ├── shareContext.ts ─ AsyncLocalStorage grant scope + rate/concurrency counters ├── shareLease.ts ─ HMAC-signed leases for complete mode ├── shareProvisioning.ts ─ Split-PKCE challenge/code exchange (lender side) ├── shareAudit.ts ─ Usage-drift reconciliation and auto-pause ├── shareSigning.ts ─ The one HMAC: canonicalise, sign, constant-time verify ├── shareReceipts.ts ─ Signed settlement statements and reciprocal netting ├── shareNotes.ts ─ Transferable coin notes and their spent-set ├── shareListener.ts ─ The gate-only second listener and its supervisor ├── residentGrants.ts ─ Borrower side of a complete share; heartbeats ├── peerStore.ts ─ Borrower's peer list, priorities, per-reason cooldowns └── peerTransport.ts ─ Raw Anthropic passthrough forward to a lender ``` --- ## 10. File Reference | File | Lines | Purpose | | -------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `src/cli/commands/proxy.ts` | ~varies | CLI commands: `proxy start`, `proxy status`, `proxy telemetry`, `proxy guard`, `proxy setup`, `proxy install`, `proxy uninstall` | | `src/lib/server/routes/claudeProxyRoutes.ts` | ~1047 | Route handlers: `/v1/messages`, `/v1/models`, `/v1/messages/count_tokens` | | `src/lib/proxy/oauthFetch.ts` | ~383 | OAuth fetch wrapper with cloaking (passthrough + direct modes) | | `src/lib/proxy/modelRouter.ts` | ~57 | Model name resolution and fallback chain | | `src/lib/proxy/claudeFormat.ts` | ~varies | Claude API format parser, response serializer, SSE state machine | | `src/lib/proxy/requestLogger.ts` | ~varies | Request summaries, attempt logs, OTLP log export, debug logging, and log rotation | | `src/lib/proxy/rawStreamCapture.ts` | ~varies | Lossless raw stream capture for debugging streaming request/response IO | | `src/lib/proxy/accountQuota.ts` | ~110 | Quota header parsing (unified-5h, unified-7d) and persistence | | `src/lib/proxy/usageStats.ts` | ~60+ | In-memory per-account usage statistics | | `src/lib/proxy/tokenRefresh.ts` | ~53 | Token refresh helpers (needsRefresh, refreshToken, persistTokens) | | `src/lib/proxy/proxyConfig.ts` | ~varies | YAML/JSON config loader with `${VAR}` interpolation | | `src/cli/commands/auth.ts` | ~1991 | CLI commands: `auth login`, `auth list`, `auth remove`, `auth logout`, `auth status`, `auth refresh`, `auth cleanup`, `auth enable` | | `src/lib/auth/tokenStore.ts` | ~varies | Multi-provider token persistence with XOR obfuscation | | `src/lib/auth/anthropicOAuth.ts` | ~varies | OAuth 2.0 PKCE flow, constants (USER_AGENT, MCP_TOOL_PREFIX) | | `src/lib/proxy/shareGate.ts` | ~varies | Inbound peer-sharing gate and the `x-neurolink-grant-*` refusal contract | | `src/lib/proxy/sharePolicy.ts` | ~varies | Pure admission evaluation: reserve floor, slice ceilings, spillover, scope | | `src/lib/proxy/shareLedger.ts` | ~varies | NeuroCoin hold/settle and per-window consumption buckets | | `src/lib/proxy/shareLease.ts` | ~varies | HMAC-signed leases; the offline-grace contract for complete shares | | `src/lib/proxy/shareProvisioning.ts` | ~varies | Split-PKCE provisioning: challenge in, single-use code out | | `src/lib/proxy/peerTransport.ts` | ~varies | Forwarding a borrowed request to a lender and reading its refusal | | `src/lib/proxy/shareReceipts.ts` | ~varies | Signed settlement statements, and the reciprocal netting built on them | | `src/lib/proxy/shareNotes.ts` | ~varies | Transferable coin notes: issue, inspect, redeem-once | | `src/lib/proxy/shareListener.ts` | ~varies | The gate-only listener that follows the grant file | --- ## Claude Proxy Configuration Reference # Claude Proxy Configuration Reference This document is the authoritative reference for every configurable aspect of the NeuroLink Claude proxy. It covers CLI flags, the YAML config file schema, environment variables, auto-configured Claude Code settings, and all file locations. ---------------------- | ----- | --------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `--port` | `-p` | `number` | `55669` | Port to listen on. | | `--share-port` | | `number` | `--port` + 1 | Gate-only listener port for peer sharing (see below). | | `--host` | `-H` | `string` | `127.0.0.1` | Host/IP to bind to. A non-loopback host is refused unless `--inbound-token`, `NEUROLINK_PROXY_REQUIRE_GRANT=1` or `--allow-unauthenticated` is set. | | `--inbound-token` | | `string` | | Bearer every caller must present (`x-neurolink-inbound-token` or `Authorization: Bearer`). Also `NEUROLINK_PROXY_INBOUND_TOKEN`. | | `--allow-unauthenticated` | | `boolean` | `false` | Start a non-loopback listener with no inbound authentication; logs a warning. | | `--strategy` | `-s` | `string` | `fill-first` | Account selection strategy. Choices: `fill-first`, `round-robin`. | | `--health-interval` | | `number` | `30` | Health check interval in seconds. | | `--quiet` | `-q` | `boolean` | `false` | Suppress non-essential output (banner, status messages). | | `--debug` | `-d` | `boolean` | `false` | Enable debug output (stack traces on errors, verbose logging). | | `--config` | `-c` | `string` | `~/.neurolink/proxy-config.yaml` | Path to proxy config file (YAML or JSON). | | `--env-file` | | `string` | | Path to .env file for provider API keys (overrides cwd .env). | | `--passthrough` | | `boolean` | `false` | Transparent forwarding: no retry, rotation, or polyfill. | **Examples:** ```bash # Start with defaults (port 55669, fill-first strategy) neurolink proxy start # Custom port and explicit round-robin strategy neurolink proxy start -p 8080 -s round-robin # Start with 60-second health checks, debug output neurolink proxy start --health-interval 60 --debug # Use a custom config file neurolink proxy start --config /path/to/my-proxy.yaml ``` #### The share listener `proxy start` runs a **second, gate-only listener** whenever this node has at least one active share grant. It serves the same routes on a different port and refuses every request that carries no valid share token; the main port keeps serving the operator's own untokened client exactly as before. Which port a request arrived on is decided by the accepting socket, so nothing a client sends can move it across. That is the reason for a second port rather than an origin check: cloudflared and every reverse proxy connect from `127.0.0.1`, so tunnelled traffic is indistinguishable from local traffic by address alone. | Behaviour | Detail | | ------------------- | ------------------------------------------------------------------------------------------------ | | Port | `--share-port`, else `NEUROLINK_PROXY_SHARE_PORT`, else main port + 1 | | Lifecycle | Comes up on the first active grant, closes when the last is revoked — no restart on either edge | | Poll interval | 15s against the grant file | | Bind failure | Logged once and retried; never fatal. Set `--share-port` to move it | | Rolling replacement | The incoming worker loses the bind until the outgoing one drains, then takes it on the next poll | | Disable | `NEUROLINK_PROXY_SHARE_LISTENER=0` | `neurolink proxy expose` picks this port automatically. Expose it, not the main one. ### `neurolink proxy status` Show the current proxy status. | Flag | Alias | Type | Default | Description | | ---------- | ----- | --------- | ------- | --------------------------------------- | | `--format` | | `string` | `text` | Output format. Choices: `text`, `json`. | | `--quiet` | `-q` | `boolean` | `false` | Suppress non-essential output. | **Examples:** ```bash # Human-readable status neurolink proxy status # Machine-readable JSON (for scripts) neurolink proxy status --format json ``` **JSON output shape** (when `--format json`): ```json { "running": true, "pid": 12345, "port": 55669, "host": "127.0.0.1", "strategy": "fill-first", "startTime": "2025-03-22T10:00:00.000Z", "uptime": 3600000, "url": "http://127.0.0.1:55669", "autoUpdateEnabled": true, "updaterPid": 12346, "updaterRunning": true, "latestVersion": "9.88.9", "pendingRestartVersion": null, "lastUpdateFailure": null, "fallbackChain": [{ "provider": "google-ai", "model": "gemini-2.5-pro" }], "stats": { "totalAttempts": 42, "totalAttemptErrors": 5, "totalRequests": 31, "totalSuccess": 29, "totalErrors": 2, "totalRateLimits": 3, "totalTransientRateLimits": 2, "totalQuotaRateLimits": 1 } } ``` `totalRequests`, `totalSuccess`, and `totalErrors` are final request outcomes. `totalAttempts`, `totalAttemptErrors`, and the rate-limit counters describe upstream attempts, including retries that later recovered. Per-account `requests`, `success`, and `errors` use the same final-outcome semantics; `attemptErrors` and the rate-limit fields remain attempt-level diagnostics. ### `neurolink proxy telemetry ` Manage the repo-owned local OpenObserve stack and the maintained proxy dashboard. | Action | Description | | ------------------ | ----------------------------------------------------------------------- | | `setup` | Start OpenObserve + OTEL collector and import the maintained dashboard | | `start` | Start the local telemetry stack without re-importing the dashboard | | `stop` | Stop the local telemetry stack | | `status` | Show local stack health and endpoint info | | `logs` | Follow OpenObserve and collector logs | | `import-dashboard` | Re-import the dashboard and dedupe older dashboards with the same title | | Flag | Alias | Type | Default | Description | | --------- | ----- | --------- | ------- | ------------------------------------------------- | | `--quiet` | `-q` | `boolean` | `false` | Suppress the local CLI spinner before delegating. | **Examples:** ```bash neurolink proxy telemetry setup neurolink proxy telemetry status neurolink proxy telemetry logs ``` ### `neurolink proxy setup` One-command setup: login + install proxy service + configure Claude Code. | Flag | Alias | Type | Default | Description | | -------------- | ----- | --------- | ------- | --------------------------------------------------- | | `--port` | `-p` | `number` | `55669` | Proxy port. | | `--method` | | `string` | `oauth` | Authentication method. Choices: `oauth`, `api-key`. | | `--no-service` | | `boolean` | `false` | Skip launchd install, just start foreground. | | `--env-file` | | `string` | | Path to a proxy provider env file to persist. | **Examples:** ```bash # Full setup with defaults (OAuth login, port 55669, launchd service) neurolink proxy setup # Setup on a custom port neurolink proxy setup -p 9000 # Login + start foreground (no auto-restart service) neurolink proxy setup --no-service ``` **What `proxy setup` does:** 1. Checks for existing authenticated accounts in the TokenStore. 2. Falls back to the legacy `~/.neurolink/anthropic-credentials.json` file. 3. If no valid accounts are found, runs the OAuth login flow. 4. Installs as macOS launchd service (auto-restart on crash/reboot) and configures Claude Code. Use `--no-service` for foreground start. ### `neurolink proxy guard` (hidden) Internal fail-open guard process. Spawned only by a foreground `proxy start`; launchd-managed proxies leave restart ownership entirely to launchd. The guard reverts stale Claude Code settings only after its parent is confirmed dead and never restarts or signals a live proxy. A launchd installation uses a separate updater-only worker which never changes client settings. | Flag | Type | Default | Description | | --------------------- | --------- | ------------ | ------------------------------------------------------------ | | `--host` | `string` | `127.0.0.1` | Proxy host to monitor. | | `--port` | `number` | `55669` | Proxy port to monitor. | | `--parent-pid` | `number` | _(required)_ | PID of the parent proxy process. | | `--max-wait-ms` | `number` | `0` | Maximum monitoring duration (0 = indefinite). | | `--failure-threshold` | `number` | `5` | Consecutive health check failures before triggering cleanup. | | `--poll-interval-ms` | `number` | `1000` | Interval between health checks in milliseconds. | | `--quiet` | `boolean` | `true` | Suppress output (guards are silent by default). | You should never need to run this command manually. ### `neurolink proxy install` Install the proxy as a persistent macOS launchd service. The service auto-starts on login and auto-restarts on crash (5-second throttle). Currently macOS-only. | Flag | Alias | Type | Default | Description | | ------------ | ----- | -------- | ----------- | ------------------------------------------------------------- | | `--port` | `-p` | `number` | `55669` | Proxy port. | | `--host` | | `string` | `127.0.0.1` | Proxy host/IP to bind to. | | `--env-file` | | `string` | | Path to provider env file to persist for the service. | | `--config` | | `string` | | Path to proxy routing config file to persist for the service. | **Examples:** ```bash # Install with defaults (port 55669) neurolink proxy install # Install on custom port neurolink proxy install -p 9000 ``` **What it does:** 1. Writes a launchd plist to `~/Library/LaunchAgents/com.neurolink.proxy.plist`. 2. Loads the service via `launchctl load`. 3. The service runs `neurolink proxy start --port --host --quiet` and persists any `--env-file` / `--config` values into the managed service definition. 4. Logs go to `~/.neurolink/logs/proxy-launchd-stdout.log` and `proxy-launchd-stderr.log`. **Management:** ```bash # Start/stop manually launchctl start com.neurolink.proxy launchctl stop com.neurolink.proxy # Remove entirely neurolink proxy uninstall ``` ### `neurolink proxy uninstall` Remove the proxy launchd background service. Unloads the service and deletes the plist file. Currently macOS-only. No flags. **Examples:** ```bash neurolink proxy uninstall ``` ### `neurolink auth cleanup` Remove expired and disabled accounts from the token store. | Flag | Type | Default | Description | | --------- | --------- | ------- | -------------------------------------------------- | | `--force` | `boolean` | `false` | Skip confirmation when removing disabled accounts. | **Examples:** ```bash # Interactive cleanup (prompts before removing disabled accounts) neurolink auth cleanup # Force cleanup without confirmation neurolink auth cleanup --force ``` **What it does:** 1. Prunes expired entries that have no refresh token. 2. Finds permanently disabled entries (e.g., accounts that failed refresh). 3. Prompts for confirmation before removing disabled accounts (unless `--force`). ### `neurolink auth enable` Re-enable a previously disabled account so it can be used by the proxy pool again. | Argument | Type | Required | Description | | ----------- | -------- | -------- | ----------------------------------------------------- | | `` | `string` | **Yes** | Account key to re-enable (e.g., `anthropic:1-VjRIq`). | **Examples:** ```bash # Re-enable a disabled account neurolink auth enable anthropic:1-VjRIq ``` Run `neurolink auth list` to see all accounts and their current status. ### `neurolink auth set-primary` Designate the proxy's primary (home) Anthropic account by email/label. Writes `routing.primary-account` to the proxy config YAML; a running proxy watching that exact file applies it automatically. With quota routing enabled (the default), primary is the ranking's final tiebreaker, not tried first, unless `routing.prefer-primary` is also set; it is tried first unconditionally only when quota routing is disabled, and under `round-robin` it is used as the home reference. Does **not** touch the token store and does **not** require re-OAuthing any account. | Argument | Type | Required | Description | | ---------- | -------- | -------- | ------------------------------------------------------------------------- | | `` | `string` | **Yes** | Email/label of the Anthropic account to make primary. | | `--config` | `string` | No | Path to the proxy config file. Default: `~/.neurolink/proxy-config.yaml`. | If the email is not currently authenticated in the token store, the command still writes the field and prints a warning — the setting activates automatically once the account is added via `auth login --add`. For a running proxy, the command reports whether it watches the edited path, watches a different path, or predates hot-reload support. **Examples:** ```bash # Make alice@example.com primary in the default config neurolink auth set-primary alice@example.com # Use a non-default config path neurolink auth set-primary alice@example.com --config ./proxy.yaml ``` > Note: writing YAML uses `js-yaml.dump`, which does not preserve comments. The command prints a warning before writing if the existing file contains comments. JSON config paths preserve everything except whitespace. ### `neurolink auth get-primary` Show the proxy's currently configured primary account (and whether it is authenticated). | Argument | Type | Required | Description | | ---------- | -------- | -------- | ------------------------------------------------------------------------- | | `--config` | `string` | No | Path to the proxy config file. Default: `~/.neurolink/proxy-config.yaml`. | **Examples:** ```bash neurolink auth get-primary ``` Output (when configured and authenticated): ``` Configured primary: alice@example.com Status: authenticated (anthropic:alice@example.com present in token store) Source: /Users/.../.neurolink/proxy-config.yaml ``` ### `neurolink auth clear-primary` Remove `routing.primary-account` (and `routing.primaryAccount`) from the proxy config. A running proxy watching that file reverts to insertion-order fallback on its next valid configuration generation. | Argument | Type | Required | Description | | ---------- | -------- | -------- | ------------------------------------------------------------------------- | | `--config` | `string` | No | Path to the proxy config file. Default: `~/.neurolink/proxy-config.yaml`. | **Examples:** ```bash neurolink auth clear-primary ``` Idempotent — clearing when no primary is configured prints `No primary account was configured.` and exits 0. ### `neurolink proxy share ` Lender-side controls for peer sharing. Conceptual documentation lives in [Proxy peer sharing](/docs/features/proxy-peer-sharing); this is the flag reference. Actions: `create`, `provision`, `url`, `list`, `status`, `pause`, `resume`, `revoke`, `topup`, `set`, `link`, `rotate`, `level`, `note`, `notes`, `receipts`, `delete`. | Argument | Type | Description | | ------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--peer` | `string` | Borrower label, or a grant id. Required by everything but `list`, `status`, `url`, `note` and `notes` — the coin-note actions are issued against the node, not a peer. | | `--preset` | `string` | `spare` (default), `spillover`, `metered`, `open`. Fills the gate set; every field stays overridable by an explicit flag. | | `--level` | `string` | `live` (default) or `complete`. | | `--ledger` | `string` | `coins` or `unlimited`. Implied `coins` when `--coins` is given. | | `--coins` | `number` | Starting balance for a metered grant. With `topup`, the amount to add; with `set`, the absolute balance. | | `--refill` | `string` | Standing allowance, e.g. `100/week` or `50/session`. Applied at the first borrowed request after the period elapses, not on a timer. | | `--max-slice` | `string` | Ceiling as a percent of the **pool**: `20`, or `5h=20,7d=15`. Consumption is summed across the grant's reachable accounts and divided by their count. | | `--max-slice-per-account` | `string` | The same ceiling applied to each account independently. Opt-in; the pre-pool behaviour. | | `--reserve` | `string` | Headroom floor the borrower may never eat into: `30`, or `5h=30,7d=20`. Per-account by design. | | `--spillover` | `string` | Use-it-or-lose-it window: `12h\` records one, `share url get` prints the bare value (exit 1 when unset), `share url clear` forgets it, and a bare `share url` reports the current value. ### `neurolink proxy peer ` Borrower-side controls. Actions: `add`, `request`, `sync`, `receipts`, `net`, `redeem`, `list`, `status`, `test`, `remove`, `pause`, `resume`, `set`. | Argument | Type | Description | | ------------------ | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `--name` | `string` | Local name for the lender. Required by everything but `list` and `sync`. | | `--link` | `string` | Share link from the lender: `neurolink://share/#`. The token rides in the fragment, which is never transmitted to the host. | | `--url` | `string` | Lender's proxy address, when adding by hand instead of by link. | | `--token` | `string` | Share token, when adding by hand. | | `--priority` | `number` | Lower is tried first. Default `100`. | | `--claim` | `boolean` | With `peer request`: collect a code the lender has authorized, and exchange it locally. | | `--label` | `string` | Local account label for a provisioned credential. Default `-shared`. | | `--note` | `string` | Free-text note kept with the peer. | | `--receipt-secret` | `string` | Secret this lender signs receipts with, when adding a peer by hand instead of from a link. | | `--reciprocal` | `string` | With `peer net`: label of the grant you issued to the same person. Defaults to the peer's own name. | | `--coin-note` | `string` | With `peer redeem`: the coin note to present. | | `--check` | `boolean` | With `peer redeem`: ask the issuer about the note without spending it. | | `--json` | `boolean` | Emit JSON instead of formatted text. | | `--dev` | `boolean` | Use the isolated dev-mode state directory. | ### `neurolink proxy expose` Publish this proxy over a Cloudflare tunnel, refusing to do so while the gate is off. | Argument | Type | Description | | --------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `--port` | `number` | Local port to expose. No default — omit it and the gate-only share listener is picked, falling back to the running proxy's port. | | `--host` | `string` | Local host to expose. Default `127.0.0.1`. | | `--named` | `string` | Named tunnel to run instead of a quick tunnel. Quick-tunnel URLs change on restart and rot every peer entry. | | `--force` | `boolean` | Publish anyway when the gate probe says the proxy answers untokened requests. Publishes your subscription to anyone who finds the URL. | --- ## 2. Config File (`~/.neurolink/proxy-config.yaml`) The proxy loads its configuration from a YAML (or JSON) file. The default location is `~/.neurolink/proxy-config.yaml`. Override it with `--config`. ### Runtime Reload Semantics The running proxy watches the resolved config path and proxy env path. Changes are debounced, parsed, validated, and converted into a complete immutable routing snapshot before one pointer swap publishes the next generation. Each request captures one generation, so a reload never changes model routing, fallback order, or account eligibility midway through that request. The following values reload without restarting: - `routing.strategy`, unless `--strategy` supplied a fixed CLI override - model mappings, fallback chain, auto fallback, per-account admission, and passthrough models - primary account and account allowlist - quota routing, session soft limit, and reset tolerance - env interpolation used by those routing fields - `NEUROLINK_PROXY_QUOTA_ROUTING`, `NEUROLINK_PROXY_SESSION_SOFT_LIMIT`, and `NEUROLINK_PROXY_SESSION_RESET_TOLERANCE_MS` from the proxy env file Malformed, invalid, or deleted previously observed files do not partially apply. The last-known-good generation remains active, and `/status` exposes `config.generation`, `config.lastReloadError`, and `config.consecutiveFailures`. `neurolink proxy status` presents the same information. `SIGHUP` requests an immediate reload; normal edits need no signal. Listener address, port, passthrough mode, keep-alive dispatcher settings, telemetry initialization, and executable code remain startup concerns. Those require process replacement; editing their env values is intentionally not presented as a successful hot reload. YAML parsing uses `js-yaml` when available; otherwise falls back to `JSON.parse`. ### Environment Variable Interpolation All string values support `${VAR_NAME}` and `${VAR_NAME:-default}` syntax for environment variable resolution: ```yaml accounts: anthropic: - name: production apiKey: "${ANTHROPIC_API_KEY}" # resolved from env - name: backup apiKey: "${BACKUP_KEY:-sk-fallback-123}" # with default value ``` Resolution order: 1. Look up `VAR_NAME` in `process.env`. 2. If not found, use the `:-default` value when present. 3. If no default, the literal `${VAR_NAME}` token is preserved (validation will catch missing keys). ### Full Schema ```yaml # --------------------------------------------------------------------------- # Top-level fields # --------------------------------------------------------------------------- # Schema version (optional, default: 1) version: 1 # Default provider applied when not specified per-account (optional) defaultProvider: "anthropic" # Default base URL applied to accounts that omit baseUrl (optional) defaultBaseUrl: "https://api.anthropic.com" # --------------------------------------------------------------------------- # accounts (REQUIRED) # --------------------------------------------------------------------------- # Map of provider names to arrays of account configurations. # At least one provider with at least one account is required. accounts: anthropic: - name: "personal-pro" # Human-readable label (default: "unnamed") apiKey: "${ANTHROPIC_KEY_1}" # API key or OAuth token (REQUIRED, non-empty) baseUrl: "https://api.anthropic.com" # Base URL override (optional) orgId: "org-abc123" # Organization ID (optional) weight: 2 # Weight for weighted round-robin (default: 1) enabled: true # Whether this account is active (default: true) rateLimit: 60 # Max requests per minute (optional) metadata: # Arbitrary metadata (optional) tier: "pro" notes: "Main account" - name: "team-max" apiKey: "${ANTHROPIC_KEY_2}" weight: 3 enabled: true # --------------------------------------------------------------------------- # routing (optional) # --------------------------------------------------------------------------- # Controls model mapping, fallback chains, and routing strategy. # Accepts both camelCase and kebab-case keys for YAML-friendliness. routing: # Account selection strategy: "round-robin" | "fill-first" strategy: "fill-first" # Quota-aware ordering controls for fill-first. Accounts with session # headroom are ordered by soonest weekly expiry; a session at the soft limit # is temporarily demoted until its 5h window resets. Environment variables # with matching names take precedence when present in the proxy env file. quota-routing: true session-soft-limit: 0.97 session-reset-tolerance-ms: 900000 # Optional bound for concurrent upstream requests per OAuth account. Omit # this key for unlimited admission. When set, requests try another eligible # account first, then queue only if all are full. Valid range is 1 through 20. # A value outside that range — a non-integer, 0, or 21+ — is rejected with a # warning and leaves admission unlimited; it is NOT clamped to the nearest # bound, so a typo here silently removes the cap rather than tightening it. # max-inflight-per-account: 2 # Primary (home) account: under fill-first without quota routing this account # is tried first. With quota routing enabled it is only the final tie-break # in the ranking order below, unless prefer-primary (below) is set, in which # case it is tried first whenever usable and not session-saturated. Under # round-robin it sets the starting offset when account membership changes. # Resolved per-request to a stable token-store key (anthropic:); a # numeric index is never persisted, so reordering accounts in the token # store is irrelevant. When omitted the proxy falls back to insertion-order # index 0. Accepts: primary-account (kebab) or primaryAccount (camel). # Manage via: # neurolink auth set-primary # neurolink auth get-primary # neurolink auth clear-primary primary-account: "alice@example.com" # Account routing policies (all optional; every default reproduces today's # exact behavior). See "Account Routing Policies" below for precedence, # interaction notes, and hot-reload semantics. Ignored under round-robin. # Accepts kebab-case or camelCase for every key here. # # Ordering of usable accounts under quota routing: "expiry-first" (default, # unchanged) or "headroom-first" (ranks by highest min(1 - sessionUsed, # 1 - weeklyUsed) ahead of weekly reset). account-ranking: "expiry-first" # If primary-account is usable and not session-saturated, try it before the # ranking order (default: false). prefer-primary: false # Keep a Claude Code session on the Anthropic account that served it, while # that account stays usable and not session-saturated (default: false). # Turning this off or on at runtime clears all existing bindings. session-affinity: false # How long an idle session binding survives, in ms (default: 3600000; # valid range 60000-86400000). Only meaningful when session-affinity is on. session-affinity-idle-ttl-ms: 3600000 # For an unbound request: if the account that would otherwise be tried # first already has this many requests in flight, try the next account # below that count that is usable and not session-saturated instead # (default: 0, meaning off; valid range 0-100). Only has an effect below # max-inflight-per-account's cap, or when no cap is set. spill-inflight: 0 # Optional hard boundary for Anthropic credential discovery. Entries may be # labels/emails or full anthropic: keys. An empty list denies all. # Hidden legacy/env credentials require explicit legacy-default/env entries. # Omit the key to remove the restriction; an explicit null is rejected. # Accepts: account-allowlist (kebab) or accountAllowlist (camel). account-allowlist: - "alice@example.com" # Model mappings: remap incoming model names to different provider/model pairs # Accepts: model-mappings (kebab) or modelMappings (camel) model-mappings: - from: "claude-sonnet-4-20250514" # Model name sent by Claude Code to: "gemini-2.5-pro" # Target model name provider: "google-ai" # Target provider (default: "anthropic") - from: "claude-3-haiku-20240307" to: "gpt-4o-mini" provider: "openai" # Fallback chain: when all Claude accounts are exhausted, try these in order # Accepts: fallback-chain (kebab) or fallbackChain (camel) fallback-chain: - provider: "google-ai" model: "gemini-2.5-pro" - provider: "openai" model: "gpt-4o" # Disabled by default. Set true only when it is acceptable for a request to # use an unspecified provider selected by the translation layer after the # configured fallback chain is exhausted. It is skipped when any account # returned a rate limit; that case still returns 429. auto-fallback: false # Passthrough models: model IDs that skip routing and go directly to Anthropic # Accepts: passthrough-models (kebab) or passthroughModels (camel) passthrough-models: - "claude-sonnet-4-20250514" - "claude-3-5-sonnet-20241022" - "claude-3-haiku-20240307" # --------------------------------------------------------------------------- # cloaking (optional) # --------------------------------------------------------------------------- # Cloaking pipeline for making proxy requests indistinguishable from # genuine Claude Code sessions. cloaking: # Mode: "auto" | "always" | "never" # auto - apply cloaking only to OAuth accounts (default behavior) # always - apply to all accounts (OAuth and API key) # never - disable all cloaking plugins mode: "auto" plugins: # Strip proxy-revealing headers (x-forwarded-for, via, etc.) headerScrubber: true # Generate consistent session identities per account (1-hour TTL) sessionIdentity: true # Inject Claude Code session context into system prompt (OAuth only) systemPromptInjector: true # Zero-width character insertion into sensitive words wordObfuscator: enabled: true words: # Custom words to obfuscate - "proxy" - "neurolink" - "load balancer" - "round-robin" - "failover" - "multi-account" # TLS fingerprint mimicry (stub/placeholder -- not yet implemented) tlsFingerprint: enabled: false ``` ### Field Reference Table #### Top-Level Fields | Field | Type | Default | Required | Description | | ----------------- | --------------------------- | -------- | -------- | --------------------------------------------------------- | | `version` | `number` | `1` | No | Config schema version. | | `defaultProvider` | `string` | _(none)_ | No | Default provider name applied to accounts that omit it. | | `defaultBaseUrl` | `string` | _(none)_ | No | Default base URL applied to accounts that omit `baseUrl`. | | `accounts` | `Record` | _(none)_ | **Yes** | Map of provider names to account arrays. | | `routing` | `RoutingConfig` | _(none)_ | No | Routing strategy, model mappings, and fallback chain. | | `cloaking` | `CloakingConfig` | _(none)_ | No | Cloaking pipeline configuration. | #### Account Fields | Field | Type | Default | Required | Description | | ----------- | ------------------------- | ----------- | -------- | ------------------------------------------------------------------------ | | `name` | `string` | `"unnamed"` | No | Human-readable account label. | | `apiKey` | `string` | _(none)_ | **Yes** | API key or OAuth token. Supports `${ENV_VAR}` interpolation. | | `baseUrl` | `string` | _(none)_ | No | Override the provider's API base URL. | | `orgId` | `string` | _(none)_ | No | Organization ID (e.g., OpenAI organizations). | | `weight` | `number` | `1` | No | Weight for weighted round-robin selection. Higher weight = more traffic. | | `enabled` | `boolean` | `true` | No | Whether this account is active. Disabled accounts are skipped. | | `rateLimit` | `number` | _(none)_ | No | Maximum requests per minute for this account. | | `metadata` | `Record` | _(none)_ | No | Arbitrary metadata (tier info, notes, tags). | #### Routing Fields | Field | Type | Default | Required | Description | | ----------------------------------------------------------- | ------------------------------------ | -------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `strategy` | `"round-robin" \| "fill-first"` | _(none)_ | No | Account selection strategy. `round-robin` rotates across accounts. `fill-first` uses one account until exhausted. | | `primary-account` / `primaryAccount` | `string` | _(none)_ | No | Email/label of the Anthropic account to treat as primary (home). With quota routing enabled, primary is only the final tie-break in the ranking order, unless `prefer-primary` is set, in which case it is tried first whenever it's usable and not session-saturated. It is tried first unconditionally only when quota routing is disabled. Resolved per-request to `anthropic:`; falls back to insertion-order index 0 when absent or when the configured account isn't currently authenticated. Manage via `neurolink auth set-primary `. | | `account-ranking` / `accountRanking` | `"expiry-first" \| "headroom-first"` | `expiry-first` | No | Ordering of usable accounts under quota routing. `expiry-first` is the existing comparator (soonest weekly reset, then other tie-breakers), unchanged. `headroom-first` ranks by highest headroom — `min(1 - sessionUsed, 1 - weeklyUsed)` — ahead of weekly reset. Ignored under `strategy: round-robin`. | | `prefer-primary` / `preferPrimary` | `boolean` | `false` | No | If the configured `primary-account` is usable and not session-saturated, it is tried before the ranking order (after any active session-affinity binding). Ignored under `strategy: round-robin`. | | `session-affinity` / `sessionAffinity` | `boolean` | `false` | No | Sticky sessions: a Claude Code session is bound to the Anthropic account that serves it and stays there while that account is usable and not session-saturated; a request that never tried the bound account (e.g. past `max-inflight-per-account`) keeps the binding. Otherwise, even if the bound account failed it, the session re-binds to the account that serves it; Codex/Vertex fallback or a peer borrow never re-binds. Ignored under `strategy: round-robin` and with one enabled account. Turning it off or on at runtime clears all bindings. | | `session-affinity-idle-ttl-ms` / `sessionAffinityIdleTtlMs` | `integer`, 60000–86400000 | `3600000` | No | How long a session binding survives without a served request before it's dropped (the prompt cache is assumed cold by then). Only meaningful when `session-affinity` is on. | | `spill-inflight` / `spillInflight` | `integer`, 0–100 | `0` (off) | No | For a request with no active session-affinity binding: if the account that would otherwise be tried first already has this many requests in flight, try the next account below that count that is usable and not session-saturated instead. Only affects unbound requests; never splits a bound session. Effective only below `max-inflight-per-account`'s cap (or when no cap is set) — that cap applies to every account regardless of `spill-inflight`. Ignored under `strategy: round-robin`. | | `account-allowlist` / `accountAllowlist` | `string[]` | _(none)_ | No | Allowed Anthropic account labels/keys. When present, unlisted TokenStore, legacy, and environment credentials are excluded before loading or refresh. Empty denies all; absent is unrestricted. An explicit `null` is rejected; omit the key to remove the restriction. Special fallback labels are `legacy-default` and `env`. | | `model-mappings` / `modelMappings` | `ModelMapping[]` | `[]` | No | Array of model-to-model remapping rules. | | `fallback-chain` / `fallbackChain` | `FallbackEntry[]` | `[]` | No | Ordered list of alternative providers to try when primary accounts are exhausted. | | `auto-fallback` / `autoFallback` | `boolean` | `false` | No | Allows a translation-layer-selected fallback provider after configured fallbacks fail. Keep disabled to restrict requests to explicit accounts and fallback entries. | | `max-inflight-per-account` / `maxInflightPerAccount` | `integer` | _(unlimited)_ | No | Optional maximum concurrent upstream requests per OAuth account, from 1 through 20. When omitted, every request is admitted immediately. When set, requests prefer an available ordered account before queueing. Any value outside the range — non-integer, `0`, or `21`+ — is discarded with a warning and admission stays **unlimited**; values are never clamped to the nearest bound. | | `passthrough-models` / `passthroughModels` | `string[]` | `[]` | No | Model IDs that bypass routing and go directly to Anthropic. | | `quota-routing` / `quotaRouting` | `boolean` | `true` | No | Enables weekly-expiry-first quota ordering for fill-first with multiple accounts. Accounts at the session soft limit are temporarily demoted until their 5h window resets. The environment override takes precedence. | | `session-soft-limit` / `sessionSoftLimit` | `number` | `0.97` | No | Session utilization in `(0, 1]` at which quota routing proactively demotes an account. | | `session-reset-tolerance-ms` / `sessionResetToleranceMs` | `integer` | `900000` | No | Positive reset-time bucket width used when session reset time breaks a weekly-expiry tie and when saturated accounts are ordered by recovery time. | | `use-overage` / `useOverage` | `"auto" \| "always" \| "never"` | `auto` | No | Whether an account may keep serving on paid extra usage once its subscription window is spent. `auto` follows what Anthropic reports per account; `never` parks the account at the subscription limit so the pool never spends credits; `always` keeps serving whenever the provider permits it. Only `never` overrides the provider — nothing here enables extra usage Anthropic has disabled. Manage via `neurolink auth overage`. | For `fallback-chain`/`fallbackChain`, `quota-routing`/`quotaRouting`, `use-overage`/`useOverage`, `auto-fallback`/`autoFallback`, `max-inflight-per-account`/`maxInflightPerAccount`, `session-soft-limit`/`sessionSoftLimit`, and `session-reset-tolerance-ms`/`sessionResetToleranceMs`: an explicit `null` under either spelling means "unset" — the field's default applies as if the key were omitted, but a warning is logged. An empty YAML value (`use-overage:`) is `null`. A non-null value under one spelling is still used even when the other spelling is `null`. The five newer routing policy keys (`account-ranking` through `spill-inflight`) differ on purpose: an explicit `null` there is rejected — see [Validation Rules](#validation-rules). `account-allowlist`/`accountAllowlist` is the exception: an explicit `null` under either spelling is rejected, because a reload must never silently turn a restricted allowlist into an unrestricted one. This includes an empty YAML value (`account-allowlist:`). Omit the key to remove the restriction. #### ModelMapping Fields | Field | Type | Default | Required | Description | | ---------- | -------- | ------------- | -------- | ------------------------------------------------ | | `from` | `string` | `""` | Yes | Incoming model name (what Claude Code requests). | | `to` | `string` | `""` | Yes | Target model name at the destination provider. | | `provider` | `string` | `"anthropic"` | No | Target provider to route to. | #### FallbackEntry Fields | Field | Type | Default | Required | Description | | ---------- | -------- | ------- | -------- | -------------------------------------------- | | `provider` | `string` | `""` | Yes | Provider name (e.g., `google-ai`, `openai`). | | `model` | `string` | `""` | Yes | Model to use at that provider. | #### Cloaking Fields | Field | Type | Default | Description | | -------------------------------- | ------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------ | | `mode` | `"auto" \| "always" \| "never"` | `"auto"` | `auto` applies cloaking only to OAuth accounts. `always` applies to all. `never` disables all plugins. | | `plugins.headerScrubber` | `boolean` | `false` | Strip proxy-revealing headers (x-forwarded-for, via, sec-ch-\*, etc.). | | `plugins.sessionIdentity` | `boolean` | `false` | Generate consistent user_id/session_id per account with 1-hour TTL. | | `plugins.systemPromptInjector` | `boolean` | `false` | Inject Claude Code session context (IDE metadata, timestamps) into system prompt. OAuth accounts only. | | `plugins.wordObfuscator.enabled` | `boolean` | `false` | Insert zero-width characters into sensitive words to defeat string matching. | | `plugins.wordObfuscator.words` | `string[]` | `["proxy", "neurolink", ...]` | Words to obfuscate. Defaults include: proxy, neurolink, load balancer, round-robin, failover, multi-account. | | `plugins.tlsFingerprint.enabled` | `boolean` | `false` | TLS fingerprint mimicry. Currently a stub/placeholder (no-op). | ### Validation Rules The config loader validates the following: - `accounts` must be present and be a non-array object. - Each provider key in `accounts` must map to an array. - Each account must have a non-empty string `apiKey`. - If `version` is present, it must be a number. - `routing.account-allowlist` must be an array of non-empty strings when present. An explicit `null` counts as present and is rejected, whichever spelling carries it, including when the other spelling holds an array. - `routing.quota-routing` must be a boolean when present. - `routing.auto-fallback` must be a boolean when present. - `routing.max-inflight-per-account` must be an integer from 1 through 20 when present. - `routing.session-soft-limit` must be a number in `(0, 1]` when present. - `routing.session-reset-tolerance-ms` must be a positive integer when present. - `routing.use-overage` must be `auto`, `always`, or `never` (case-insensitive) when present. - `routing.account-ranking` must be `expiry-first` or `headroom-first` when present. - `routing.prefer-primary` must be a boolean when present. - `routing.session-affinity` must be a boolean when present. - `routing.session-affinity-idle-ttl-ms` must be an integer from 60000 through 86400000 when present. - `routing.spill-inflight` must be an integer from 0 through 100 when present. - For those five routing policy keys, an explicit `null` counts as present and is rejected, whichever spelling (kebab-case or camelCase) carries it. - Plaintext API keys (not using `${ENV_VAR}` references) trigger a warning. An absent default config is optional. An existing config that cannot be read or validated fails proxy startup; it is never ignored in favor of unrestricted routing. A value that fails any check above rejects the whole config, never just that key: at startup the proxy does not start, and on a hot reload the last-known-good generation stays active. ### Account Routing Policies The five keys above (`account-ranking`, `prefer-primary`, `session-affinity`, `session-affinity-idle-ttl-ms`, `spill-inflight`) all default to today's exact behavior — `expiry-first` ranking, no affinity, no primary preference, no spill — and are validated and hot-reloaded through the same runtime config snapshot as every other routing key. **`strategy: round-robin` ignores all five keys.** They apply only under `fill-first` with more than one enabled account. **`NEUROLINK_PROXY_QUOTA_ROUTING=off` disables quota-based ranking, but `session-affinity`, `prefer-primary` and `spill-inflight` still apply.** Turning off quota routing removes the expiry/headroom ordering step, so `account-ranking` has no effect; it does not disable sticky sessions, the primary preference or spill, which then work on the configured account order. **Precedence.** After unusable accounts are removed, the order a request tries is: 1. the session's bound account, when `session-affinity` is on and that account is usable and not session-saturated; 2. the configured `primary-account`, when `prefer-primary` is on and it is usable and not session-saturated; 3. the remaining accounts in `account-ranking` order. Spill only changes which account is tried first, and only for requests without an active session-affinity binding — it never re-orders or moves a request that is already bound to an account. Its target must be usable and not session-saturated, like every step above; when no account under the threshold qualifies, nothing spills. **Binding.** A served request binds its session to the Anthropic account that served it. The existing binding is kept only when that request never tried the bound account and the bound account is still usable and not session-saturated — a request that overflowed the bound account's `max-inflight-per-account` cap onto another account keeps the session on its warm prompt cache. A bound account that was tried and failed in the same request loses the session to the account that served it, even if its cooldown has already lapsed by the time the response starts. A Codex or Vertex fallback, a peer borrow, or an error response never binds. **Failure mode.** If ranking, affinity or spill throws, the request uses the pre-policy order (plain `expiry-first` under quota routing) and the routing decision records `routing_policy_error`. If the binding step after a served response throws, the session binds to the serving account and the response is unaffected. Each such error is logged once per call site and distinct error (its name and message; the 32 most recent are remembered), not once per worker, so a later, unrelated failure still reaches the log. **`spill-inflight` and `max-inflight-per-account`.** `max-inflight-per-account` is a single cap applied to every account; `spill-inflight` reroutes an unbound request away from an account that has reached its own threshold. As a result, `spill-inflight` only has an observable effect when it is set to a value **below** the `max-inflight-per-account` cap, or when no cap is configured at all — a `spill-inflight` at or above the cap never triggers, because `max-inflight-per-account` already stops admission first. **Paid overage.** An account that may spend paid extra usage (see `use-overage`) is never marked session-saturated, so `session-affinity` and `prefer-primary` keep a session on it while it spends overage, even when other accounts still have free subscription headroom. If that matters, set `use-overage: never` alongside `session-affinity: true`. **Hot reload.** Disabling `session-affinity` clears all existing session bindings, and re-enabling it clears them again, so it always starts from an empty binding store — including a binding recorded by a request that was already in flight when affinity was turned off. Every other policy key takes effect on the next request under the new config generation. **Observability.** `GET /status` reports the active policy (`policy`: the current `account-ranking`, `prefer-primary`, `session-affinity`, `session-affinity-idle-ttl-ms`, and `spill-inflight` values) and the number of currently bound sessions (`boundSessions`); bindings idle for longer than `session-affinity-idle-ttl-ms` are not counted. --- ## 3. Environment Variables | Variable | Purpose | Used By | | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | | `ANTHROPIC_API_KEY` | Anthropic API key. Used as a fallback credential when no OAuth accounts are found. | Proxy routes, Anthropic provider | | `ANTHROPIC_OAUTH_TOKEN` | OAuth access token for Anthropic (alternative to stored tokens). | Anthropic provider, providerConfig | | `CLAUDE_OAUTH_TOKEN` | Alias for `ANTHROPIC_OAUTH_TOKEN`. Checked as a fallback. | Anthropic provider, providerConfig | | `NEUROLINK_SKIP_MCP` | Set to `"true"` to skip MCP server initialization. Automatically set by `proxy start` (tools come from Claude Code, not local MCP servers). | `NeuroLink` constructor | | `NEUROLINK_LOG_LEVEL` | Log level for the NeuroLink logger. Values: `error`, `warn`, `info`, `debug`. | Logger utility | | `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP HTTP endpoint for proxy telemetry export. Written automatically to `~/.neurolink/.env` by `neurolink proxy telemetry setup`. Example: `http://localhost:14318`. | Proxy OTEL init (`initializeProxyOpenTelemetry`) | | `NEUROLINK_PROXY_TRACE_BODY_LOGGING` | Opt-in: set to `true` to record request and response bodies on proxy traces, as observation input and output and as raw body span events. Off by default. `NEUROLINK_RECORD_INPUTS=false` still keeps request bodies out. See [Observability: Proxy](/docs/features/observability#proxy). | Proxy tracer (`proxyTracer.ts`) | | `NEUROLINK_ENV_FILE` | Path to a `.env` file the proxy should load at startup. Overrides the default `~/.neurolink/.env` auto-load. | `proxyEnv.ts` (`resolveProxyEnvFile`) | | `NEUROLINK_PROXY_AUTO_UPDATE` | Automatic package updates for launchd installations. Enabled by default; set to `0`, `off`, or `false` to disable. Updates use the package manager owning the running install and restart only after all requests and streams are idle. | Dedicated launchd updater worker | | `NEUROLINK_PROXY_REQUIRE_GRANT` | Gate the **main** port too, refusing any request without a valid share token — including the operator's own client. One of the three things that permit a non-loopback bind. Also redacts account identity on `/status`. Values: `1`, `true`, `on`, `yes`. Startup-only. | Peer-sharing gate (`shareGate.ts`) | | `NEUROLINK_PROXY_INBOUND_TOKEN` | Bearer every inbound caller must present, as `x-neurolink-inbound-token` or `Authorization: Bearer `; compared in constant time. Required by `/status`, `/limits` and `/accounts` as well. Permits a non-loopback bind. Read by the CLI listener and by the SDK route factories (`createClaudeProxyRoutes`, `createCodexProxyRoutes`). Startup-only. | Inbound trust (`inboundAuth.ts`) | | `NEUROLINK_PROXY_ALLOW_UNAUTHENTICATED` | `1` lets `proxy start`/`install` bind a non-loopback host with no inbound authentication (an authenticating reverse proxy in front). Logs a warning. Startup-only. | Inbound trust (`inboundAuth.ts`) | | `NEUROLINK_PROXY_MAX_ACCOUNTS_PER_REQUEST` | How many pooled accounts one inbound request may be tried against, on both engines. Default `3`; `0` removes the cap. Read per request. | Account loops (`claudeProxyRoutes.ts`, `codexProxyRoutes.ts`) | | `NEUROLINK_PROXY_SHARE_PORT` | Port for the gate-only share listener. Default: main port + 1. `--share-port` wins over this. | Share listener (`shareListener.ts`) | | `NEUROLINK_PROXY_SHARE_LISTENER` | Set to `0`, `off`, `false` or `no` to suppress the share listener entirely, whatever grants exist. | Share listener (`shareListener.ts`) | | `NEUROLINK_PROXY_MAX_REQUEST_BODY_BYTES` | Request body ceiling for every POST route, replacing the per-route limits in [Request body limits](#request-body-limits). A byte count or a size such as `64mb`. Larger is `413` before parsing and before the share gate. An invalid value is ignored with a warning. Startup-only. | Request body bound (`requestBodyLimit.ts`) | | `NEUROLINK_PROXY_QUOTA_ROUTING` | Quota-aware fill-first ordering. Enabled by default; set to `0`, `off`, or `false` to disable. Reloads from the proxy env file at runtime. | Runtime routing configuration | | `NEUROLINK_PROXY_SESSION_SOFT_LIMIT` | Session utilization threshold in `(0, 1]`; defaults to `0.97`. Reloads from the proxy env file at runtime. | Runtime routing configuration | | `NEUROLINK_PROXY_SESSION_RESET_TOLERANCE_MS` | Positive reset-time bucket width in milliseconds; defaults to `900000`. Reloads from the proxy env file at runtime. | Runtime routing configuration | | `NEUROLINK_PROXY_SESSION_SECRET` | Optional secret used to produce stable, non-reversible lifecycle session hashes. When unset, the proxy creates a random mode-`0600` installation key in the log directory and reuses it across restarts. Changing this value intentionally starts a new correlation domain. | Lifecycle metadata logger | | `NEUROLINK_PACKAGE_MANAGER_PATH` | Optional absolute path to the npm or pnpm executable used by the updater. The candidate is still rejected unless its writable global root owns the running NeuroLink installation. | Dedicated launchd updater worker | | `NEUROLINK_PACKAGE_MANAGER` | Optional `npm` or `pnpm` type for `NEUROLINK_PACKAGE_MANAGER_PATH`. When omitted, the updater infers the type from the executable name. | Dedicated launchd updater worker | | `NEUROLINK_PNPM_PATH` | Legacy pnpm-specific updater override. Prefer `NEUROLINK_PACKAGE_MANAGER_PATH` for new installations. | Dedicated launchd updater worker | ### Request body limits The proxy reads a POST body before it can parse the model or check a share token, so the body is bounded first. Each route has a request size limit, taken from its API's documentation where the API states one; a larger body is answered `413` with `error.type` `request_too_large`, before the body is parsed and before the share gate runs. Limits are binary megabytes, a little above the documented figures, so the upstream stays the one to refuse a borderline request. | Route | Limit | Source | | -------------------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `POST /v1/messages`, `POST /v1/messages/count_tokens`, `/peer/*` endpoints | 32 MiB | Messages API and Token Counting API maximum request size, 32 MB: [platform.claude.com/docs/en/api/errors#request-size-limits](https://platform.claude.com/docs/en/api/errors#request-size-limits). The peer endpoints have no upstream and use the same value. | | `POST /v1beta/models/:model` (Gemini) | 100 MiB | Inline data, "100 MB per request or payload": [ai.google.dev/gemini-api/docs/file-input-methods](https://ai.google.dev/gemini-api/docs/file-input-methods) | | `POST /v1/chat/completions`, `POST /backend-api/codex/responses` | 64 MiB | A local cap. OpenAI documents no general request-body limit: the only per-request payload figure is "Up to 512 MB total payload per request" for image inputs ([developers.openai.com/api/docs/guides/images-vision](https://developers.openai.com/api/docs/guides/images-vision)), and file inputs are limited to 50 MB combined. The Codex route has no documentation of its own. | `NEUROLINK_PROXY_MAX_REQUEST_BODY_BYTES`, when set, replaces all of these with one value for every route, higher or lower. A request that the proxy forwards to an upstream is still subject to that upstream's own limit: an OpenAI-compatible request routed to a Claude account is checked again against the Messages limit on the way through. A body is held in memory while it is read, about four times its size at peak (measured: a 99 MiB body raised the proxy's resident memory by about 430 MiB), which is why the OpenAI and Codex routes are capped at 64 MiB rather than at the 512 MB image figure. A client that sends more raises the variable; a host with little memory can set it lower. ### Proxy Env File Resolution Order When the proxy starts, it loads env vars from a `.env` file using this priority: 1. `--env-file ` CLI flag — explicit path, required to exist. 2. `NEUROLINK_ENV_FILE=` environment variable — explicit path, required to exist. 3. `~/.neurolink/.env` — loaded automatically if the file exists (created by `neurolink proxy telemetry setup`). 4. Nothing — proxy starts without extra env vars; telemetry remains disabled unless env vars are already set in the shell, and the proxy emits a startup log explaining how to enable it unless output is suppressed. The `--env-file` flag is baked into the launchd plist by `proxy install`, so the service always loads from the same file across reboots. The three runtime routing variables above and routing interpolation are reread transactionally; other env settings remain startup-only. **Priority for Anthropic credentials** (checked in order by the proxy routes): 1. **TokenStore compound keys** -- `anthropic:` entries in `~/.neurolink/tokens.json`. 2. **Legacy credentials file** -- `~/.neurolink/anthropic-credentials.json` (only if no compound keys exist). 3. **`ANTHROPIC_API_KEY` env var** -- Only if no Anthropic TokenStore entries or legacy credential are present. `routing.account-allowlist` filters these sources before loading or refresh. Legacy and environment fallbacks are never activated merely because existing TokenStore accounts are disabled, cooling, or unavailable. --- ## 4. Claude Code Settings When the proxy starts, it automatically writes to `~/.claude/settings.json`: ```json { "env": { "ANTHROPIC_BASE_URL": "http://127.0.0.1:55669", "ENABLE_TOOL_SEARCH": "true" } } ``` | Key | Value | Description | | -------------------- | ---------------------- | --------------------------------------------------------------------------- | | `ANTHROPIC_BASE_URL` | `http://:` | Tells Claude Code to route all Anthropic API requests through the proxy. | | `ENABLE_TOOL_SEARCH` | `"true"` | Enables tool search in Claude Code (required for full proxy compatibility). | **Lifecycle:** - **On `proxy start`** -- Both keys are written (or merged into existing settings). - **On `proxy stop` (Ctrl+C / SIGTERM)** -- Both keys are removed. Other env keys in the settings file are preserved. - **Fail-open guard** -- A foreground proxy's detached guard removes stale settings only after confirming its parent died and no replacement is healthy. launchd-managed proxies do not spawn this cleanup guard; they use a separate updater-only worker. - **Safety** -- If the `ANTHROPIC_BASE_URL` has been changed to a different value (e.g., another proxy), the cleanup will not overwrite it. After starting the proxy, restart Claude Code for the new settings to take effect. --- ## 5. File Locations All NeuroLink proxy files are stored under `~/.neurolink/` (with `0o700` directory permissions). | File | Permissions | Description | | ------------------------------------------------------------ | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `~/.neurolink/tokens.json` | `0o600` | **TokenStore** -- Multi-provider OAuth token storage. Stores tokens keyed by `provider:label` (e.g., `anthropic:personal`). XOR-obfuscated by default (not plaintext). | | `~/.neurolink/anthropic-credentials.json` | `0o600` | **Legacy credentials** -- Single-account OAuth tokens. Used as a fallback when no compound keys exist in `tokens.json`. Updated on token refresh (pre-request or on-401). | | `~/.neurolink/proxy-config.yaml` | user default | **Proxy config** -- YAML/JSON configuration file. Loaded and watched by `proxy start` (default path, overridable with `--config`). Valid routing changes publish a new runtime generation. | | `~/.neurolink/.env` | `0o600` | **Proxy env file** — Auto-loaded and watched by the proxy. Runtime routing variables and routing interpolation reload transactionally; startup-only variables do not. Created by `neurolink proxy telemetry setup`. Override with `--env-file` or `NEUROLINK_ENV_FILE`. | | `~/.neurolink/proxy-state.json` | `0o600` | **Proxy state** -- Runtime state persisted by the running proxy (PID, listener, strategy, fallback chain, account allowlist, config path/generation/reload error, and supervisor PIDs). Used by `proxy status`, auth config commands, and the fail-open guard. | | `~/.neurolink/logs/proxy-YYYY-MM-DD.jsonl` | `0o600` | **Request summary logs** -- One JSONL entry per completed proxied request. Includes requestId, method, path, model, status, account label, response time, token usage, and trace correlation fields. | | `~/.neurolink/logs/proxy-attempts-YYYY-MM-DD.jsonl` | `0o600` | **Attempt logs** -- One JSONL entry per upstream attempt. Useful for retry, failover, and cooldown debugging without inflating request totals. | | `~/.neurolink/logs/proxy-debug-YYYY-MM-DD.jsonl` | `0o600` | **Debug index logs** -- Redacted body-capture index rows with phase, headers, status, duration, and the stored body artifact path. | | `~/.neurolink/logs/bodies/YYYY-MM-DD//*.json.gz` | `0o600` | **Body artifacts** -- Compressed redacted request and response bodies captured for debugging. | | `~/.neurolink/account-quotas.json` | `0o600` | **Account quotas** -- Cached quota/utilization data from Anthropic's `unified-5h` and `unified-7d` rate-limit headers. Flushed to disk every 5 seconds. | | `~/.neurolink/account-cooldowns.json` | `0o600` | **Account cooldowns** -- Extend-only rate-limit and transient-auth recovery timestamps. Persisted atomically so a proxy restart cannot immediately retry a known-exhausted account. | | `~/.claude/settings.json` | user default | **Claude Code settings** -- Auto-configured with `ANTHROPIC_BASE_URL` and `ENABLE_TOOL_SEARCH` when the proxy starts. Cleaned up on shutdown. | ### Peer-sharing state Written only once this node lends or borrows capacity — see [Proxy peer sharing](/docs/features/proxy-peer-sharing). All follow the same `0o600` + atomic-rename discipline as the files above. In `--dev` mode they resolve under `/.neurolink-dev/` instead. | File | Owner | Description | | -------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `~/.neurolink/proxy-grants.json` | lender | **Share grants** -- One record per borrower: hashed token (`sha256(salt + secret)`; the token itself is never stored), level, state, entitlement and the full gate set. Also holds this node's recorded `publicUrl`. Re-read when its mtime moves, so `share pause` lands without a restart. | | `~/.neurolink/proxy-share-ledger.json` | lender | **Coin ledger and window buckets** -- Settled coin spend and request counts per `grantId\|accountKey`, plus how much of each 5h/7d window a grant has taken, keyed by that window's reset timestamp so a rollover starts fresh. In-flight holds are memory-only. | | `~/.neurolink/proxy-share-audit.json` | lender | **Drift audit** -- Last utilization observation per complete-mode grant, the consecutive-drift streak and the auto-pause marker. Cleared by `share resume`; deleted with the grant. | | `~/.neurolink/proxy-share-provisioning.json` | lender | **Split-PKCE requests** -- A borrower's outstanding code challenge, its 15-minute expiry, and (between authorization and the single claim that consumes it) the authorization code. Never a verifier, never a token. | | `~/.neurolink/proxy-peers.json` | borrower | **Peers** -- Lender name, URL, share token, priority, per-reason cooldown, last observed grant status, and any outstanding provisioning verifier. | | `~/.neurolink/proxy-resident-grants.json` | borrower | **Resident grants** -- The signed lease governing each credential a lender provisioned here, its lease secret, last heartbeat and unreported spend. | | `~/.neurolink/proxy-share-receipts.json` | lender | **Receipts** -- The last 500 signed settlement statements per grant, each carrying the usage its charge was computed from, plus the cumulative coins forgiven by reciprocal netting. | | `~/.neurolink/proxy-share-notes.json` | issuer | **Coin notes** -- Every transferable note this node minted, and which have been redeemed, by which grant and when. The spent-set is the replay protection. | ### TokenStore Details The `tokens.json` file uses this internal structure (after deobfuscation): ```json { "version": "2.0", "lastModified": 1711100000000, "providers": { "anthropic:personal": { "tokens": { "accessToken": "...", "refreshToken": "...", "expiresAt": 1711103600000, "tokenType": "Bearer", "scope": "..." }, "createdAt": 1711100000000, "lastAccessed": 1711100000000 }, "anthropic:team": { "tokens": { "...": "..." }, "createdAt": 1711100000000, "lastAccessed": 1711100000000 } } } ``` The `TokenStore` class options: - `encryptionEnabled` (default: `true`) -- XOR obfuscation with a machine-derived key. - `customStoragePath` -- Override the default `~/.neurolink/tokens.json` path. Tokens are automatically refreshed 1 hour before expiration when a `TokenRefresher` function is registered. --- ## 6. Model Mapping Examples Model mappings let you reroute specific model requests to different providers. The proxy's `ModelRouter` checks mappings in this order: 1. **Explicit mapping** -- If the requested model has a `from` match in `model-mappings`, use the corresponding `to`/`provider`. 2. **Gemini prefix** -- If the requested model starts with `gemini-`, route to Vertex by default. 3. **Passthrough list** -- If the model is in `passthrough-models`, route to Anthropic. 4. **Claude prefix** -- Any model starting with `claude-` is routed to Anthropic. 5. **Unknown model** -- Returns `provider: null` (the proxy will reject non-Claude models unless routing is configured). ### Example: Route Haiku to a Cheaper Provider ```yaml routing: model-mappings: - from: "claude-3-haiku-20240307" to: "gpt-4o-mini" provider: "openai" ``` Claude Code requests `claude-3-haiku-20240307` but the proxy sends the request to OpenAI's `gpt-4o-mini` instead, translating the request format via `neurolink.generate()`. ### Example: Use Gemini for All Sonnet Requests ```yaml routing: model-mappings: - from: "claude-sonnet-4-20250514" to: "gemini-2.5-pro" provider: "google-ai" - from: "claude-3-5-sonnet-20241022" to: "gemini-2.5-flash" provider: "google-ai" ``` ### Example: Passthrough Specific Models ```yaml routing: passthrough-models: - "claude-sonnet-4-20250514" - "claude-3-opus-20240229" model-mappings: - from: "claude-3-haiku-20240307" to: "gemini-2.5-flash" provider: "google-ai" ``` Here, Sonnet 4 and Opus requests go directly to Anthropic (passthrough), while Haiku requests are redirected to Gemini. ### Example: No Routing (Pure Multi-Account Pool) Omit the `routing` section entirely. All requests pass through to Anthropic using the configured accounts with the proxy's default `fill-first` strategy: ```yaml accounts: anthropic: - name: "account-1" apiKey: "${ANTHROPIC_KEY_1}" - name: "account-2" apiKey: "${ANTHROPIC_KEY_2}" - name: "account-3" apiKey: "${ANTHROPIC_KEY_3}" ``` --- ## 7. Fallback Chain Examples The fallback chain is tried in order when all primary Claude accounts are exhausted (rate-limited, errored, or cooling down). Each entry specifies a provider and model. The proxy translates the Claude-format request into the target provider's format. Codex entries use the native pooled Codex Responses transport; other providers use `neurolink.generate()` or `neurolink.stream()`. ### Example: Codex with Extra High reasoning ```yaml routing: fallback-chain: - provider: codex model: gpt-6-astra reasoning-effort: xhigh ``` Authenticate a Codex account with `neurolink auth login codex` before using this fallback. `reasoning-effort` (or `reasoningEffort`) is optional and supported only on `codex` fallback entries. It is sent as `reasoning.effort` for both streaming and non-streaming Claude requests. Omit it to use the upstream model's default. Accepted values are `none`, `minimal`, `low`, `medium`, `high`, `xhigh` (Extra High), and `max`; availability depends on the selected Codex model. Invalid values or use on another provider fail configuration validation. Changes reload with the routing config, and an invalid reload keeps the previous working configuration. ### Example: Gemini then OpenAI ```yaml routing: fallback-chain: - provider: "google-ai" model: "gemini-2.5-pro" - provider: "openai" model: "gpt-4o" ``` Request flow: 1. Try Claude accounts with the configured strategy (`fill-first` by default) plus retry/failover. 2. If all exhausted, try Google AI Studio with `gemini-2.5-pro`. 3. If that also fails, try OpenAI with `gpt-4o`. ### Example: Multiple Gemini Tiers ```yaml routing: fallback-chain: - provider: "google-ai" model: "gemini-2.5-pro" - provider: "google-ai" model: "gemini-2.5-flash" - provider: "openai" model: "gpt-4o-mini" ``` Falls back through progressively cheaper models. ### Example: Vertex AI as Primary Fallback (Enterprise) ```yaml routing: fallback-chain: - provider: "google-vertex" model: "gemini-2.5-pro" - provider: "amazon-bedrock" model: "anthropic.claude-3-5-sonnet-20241022-v2:0" ``` Uses enterprise-grade providers (Vertex AI, Bedrock) as fallbacks. Requires the corresponding provider credentials to be configured in environment variables. ### Example: Full Multi-Tier Setup ```yaml version: 1 accounts: anthropic: - name: "pro-personal" apiKey: "${CLAUDE_PRO_KEY}" weight: 1 - name: "max-team" apiKey: "${CLAUDE_MAX_KEY}" weight: 3 routing: strategy: "fill-first" passthrough-models: - "claude-sonnet-4-20250514" model-mappings: - from: "claude-3-haiku-20240307" to: "gemini-2.5-flash" provider: "google-ai" fallback-chain: - provider: "google-ai" model: "gemini-2.5-pro" - provider: "openai" model: "gpt-4o" cloaking: mode: "auto" plugins: headerScrubber: true sessionIdentity: true systemPromptInjector: true wordObfuscator: enabled: true words: - "proxy" - "neurolink" ``` This configuration: - Pools two Claude accounts with 1:3 weighting (Max gets 3x traffic). - Passes Sonnet 4 requests directly to Anthropic. - Redirects Haiku requests to Gemini Flash. - Falls back to Gemini Pro, then GPT-4o when Claude accounts are exhausted. - Applies cloaking to OAuth accounts (header scrubbing, session identity, system prompt injection, word obfuscation). --- ## Proxy Endpoints For reference, the running proxy exposes these HTTP endpoints: | Method | Path | Description | | ------ | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `POST` | `/v1/messages` | Anthropic-compatible chat completions (main endpoint). | | `GET` | `/v1/models` | List available models. | | `POST` | `/v1/messages/count_tokens` | Token counting endpoint. | | `GET` | `/health` | Health check. Returns `{ status, strategy, uptime }`. | | `GET` | `/status` | Detailed status with per-account stats, total attempts, completed requests, and error rates, plus the active routing policy (`policy`) and bound-session count (`boundSessions`; see [Account Routing Policies](#account-routing-policies)). On a gated proxy, account identity is released only to a caller holding the update-control token. | | `GET` | `/limits` | Fresh per-account limits from Anthropic's usage API. `?account=` for one, `?snapshot=true` for stored state. Operator-only: refused for borrowed traffic. | | `GET` | `/peer/handshake` | Peer protocol version, capabilities and grant state. Authenticated by share token; touches no account. | | `GET` | `/peer/limits` | What the calling grant may still do: remaining coins, slice left, whether anything can serve it. Carries no account identity. | | `POST` | `/peer/provision` | Lodge a split-PKCE code challenge (complete shares). | | `GET` | `/peer/provision` | Collect the authorization code the lender produced. Single-use. | | `POST` | `/peer/heartbeat` | Complete-share check-in: report spend, receive a refreshed lease or a stop. Authenticated by the grant's lease secret. | | `GET` | `/peer/receipts` | Signed statements of what this grant was charged. `?since=` for the ones not yet collected. | | `POST` | `/peer/net` | Settle one round of reciprocal netting. The claim is signed with the grant's receipt secret. | | `POST` | `/peer/note` | Check a transferable coin note, or redeem it into this grant's balance. A check needs only the note; redeeming needs a grant to credit. | The `/peer/*` routes sit outside the request gate: they consume no capacity, and running them through it would spend the grant's rate allowance on calls that exist to ask whether spending is possible. Each authenticates itself. --- ## Log Rotation Log files (`proxy-*.jsonl`, `proxy-attempts-*.jsonl`, `proxy-debug-*.jsonl`) and old body-capture directories are automatically cleaned up to prevent unbounded growth. | Parameter | Value | Description | | ---------------- | ---------------- | ---------------------------------------------------------- | | Max age | 7 days | Files older than 7 days are deleted | | Max total size | 500 MB | If remaining files exceed 500 MB, oldest are deleted first | | Cleanup triggers | Startup + hourly | Runs once at proxy start, then every 60 minutes | The `cleanupLogs()` function performs two passes: 1. **Age pass** -- delete all files with `mtime` older than the cutoff. 2. **Size pass** -- if remaining files exceed the size limit, delete oldest first until under the cap. Log rotation is non-fatal. If cleanup fails, the proxy continues operating normally. --- ## Rate Limit Headers from Anthropic The proxy captures and uses Anthropic's quota headers for per-account utilization tracking: | Header | Format | Description | | -------------------------------------------- | --------------- | -------------------------------------- | | `anthropic-ratelimit-unified-5h-utilization` | float (0.0-1.0) | 5-hour rolling session utilization | | `anthropic-ratelimit-unified-5h-status` | string | Session status (e.g., `ok`, `warning`) | | `anthropic-ratelimit-unified-5h-reset` | integer (epoch) | When the 5-hour window resets | | `anthropic-ratelimit-unified-7d-utilization` | float (0.0-1.0) | 7-day rolling weekly utilization | | `anthropic-ratelimit-unified-7d-status` | string | Weekly status | | `anthropic-ratelimit-unified-7d-reset` | integer (epoch) | When the 7-day window resets | | `anthropic-ratelimit-fallback-percentage` | float | Fallback percentage threshold | | `anthropic-ratelimit-overage-status` | string | Overage status | These headers are parsed by `parseQuotaHeaders()` in `accountQuota.ts` and cached in memory with debounced persistence to `~/.neurolink/account-quotas.json`. The `neurolink auth list` command displays per-account 5h and 7d utilization when available. --- ## Token Refresh The proxy coordinates background, pre-request, and on-401 refresh paths: 1. **Background check** — One non-overlapping cycle runs every 30 seconds and considers only allowed, enabled accounts within 5 minutes of expiry. 2. **Pre-request check** — Before each request, if `expiresAt <= now + 5 minutes`, refresh inline via `POST https://api.anthropic.com/v1/oauth/token` (fallback: `https://console.anthropic.com/v1/oauth/token`). 3. **On-401 retry** — If Anthropic returns a 401, refresh and retry within the bounded account retry budget before rotating. Concurrent callers sharing a rotating refresh token reuse one in-flight result. `400`, `401`, `403`, and `404` refresh responses are credential rejections and disable the account until explicit login. Network failures, refresh `429`s, and `5xx` responses are transient and receive a bounded auth cooldown. Automatic token persistence preserves manual disable metadata. --- ## Claude Proxy Observability # Claude Proxy Observability This guide explains how to read the OpenObserve dashboard used to operate the NeuroLink Claude proxy. ## Source Of Truth - Dashboard definition: `docs/assets/dashboards/neurolink-proxy-observability-dashboard.json` - Live dashboard title: `NeuroLink Proxy Observability` - Default time range: `Last 30 minutes` ## First-Time Local Setup For a fresh local setup, use the NeuroLink-owned helper in `scripts/observability/` instead of borrowing telemetry files from another repo. If you do not already have the CLI installed, install it first: ```bash pnpm add -g @juspay/neurolink # or npm install -g @juspay/neurolink ``` Then continue with the setup steps below. 1. Optional: copy `scripts/observability/proxy-observability.env.example` to `scripts/observability/proxy-observability.env` only if your local ports or credentials need to differ from the defaults. 2. Start the local OpenObserve stack and import the dashboard: ```bash neurolink proxy telemetry setup ``` The setup command starts OpenObserve and the OTEL collector, imports the pre-built dashboard, and automatically writes `OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:` (default: `14318`, configurable via `NEUROLINK_OTLP_HTTP_PORT`) into `~/.neurolink/.env`. The proxy reads that file on every start, so no manual `export` is required. The collector uses a dedicated port set (`14317`/`14318`/`14333`) to avoid collisions with other local OTEL stacks. If you overrode ports in `proxy-observability.env`, the correct endpoint is printed by the setup command and written to `~/.neurolink/.env` automatically. 1. Start the proxy: ```bash neurolink proxy start # or, if installed as a launchd service: launchctl start com.neurolink.proxy ``` Data begins flowing immediately. No environment variable export needed. > **How the env file is picked up:** The proxy auto-loads `~/.neurolink/.env` on every start (whether run manually, via `proxy install`, or as a launchd service). You can also point the proxy at a different file with `--env-file ` or by setting `NEUROLINK_ENV_FILE`. See the [config reference](/docs/features/claude-proxy-config-reference#3-environment-variables) for the full resolution order. Useful follow-up commands: ```bash neurolink proxy telemetry start neurolink proxy telemetry stop neurolink proxy telemetry status neurolink proxy telemetry logs neurolink proxy telemetry import-dashboard ``` Repo-local shortcuts are also available: ```bash pnpm run proxy:observability:setup pnpm run proxy:observability:status ``` ### What Is Portable vs Instance-Specific Portable: - The dashboard query logic - The stream names listed below - The proxy log and trace fields used for correlation - The helper scripts under `scripts/observability/` Instance-specific: - OpenObserve URL, login, ports, container names, and volume names - Compose project name if you intentionally want multiple local stacks in parallel - Dashboard IDs and owners assigned by the target OpenObserve instance at import time - The process manager used to run the proxy locally, such as `launchd` on macOS The helper `scripts/observability/import-openobserve-dashboard.mjs` strips `dashboardId`, `owner`, and `created` from the checked-in JSON before importing it, so the repo file can be reused on a different machine without editing those fields first. ### Active OpenObserve Streams Use these streams when validating or updating the dashboard: - Logs: `neurolink_proxy` - Traces: `neurolink_proxy` - Metrics: `proxy_requests_total`, `proxy_errors_total`, `proxy_retries_total`, `proxy_request_duration_ms_sum`, `proxy_request_body_bytes_sum`, `proxy_cost_usd_total`, `proxy_tokens_cache_read`, `proxy_tokens_cache_creation` Do not point dashboard panels at the stale log stream `neurolink_proxy_logs` unless it has been intentionally revalidated. ### OTel Queries And Coverage Use the same OTel pipeline for application logs, request/attempt metadata, redacted bodies, lifecycle evidence and traces. Set `NEUROLINK_PROXY_LOG_SINK=otel` to disable proxy application disk logging. See [OTel logging](/docs/proxy-otel-logging) for limits, native backend discovery, correlation and the maintained coverage matrix. ```bash neurolink proxy telemetry doctor --format json neurolink proxy telemetry query --since 2026-09-15T00:00:00Z --kind request_final neurolink proxy telemetry query --since 2026-09-15T00:00:00Z --kind attempt ``` These commands read stored OTLP telemetry using OpenObserve's search API. OTLP itself is an export protocol, not a query language. The doctor also reads runtime and collector diagnostics, makes no model calls and returns nonzero for missing, stale, partial or corrupt evidence. A green report covers its requested interval and explicitly bounded samples; it is not a guarantee of universal delivery. `telemetry logs` remains the Compose service-output command, while `telemetry query` reads application telemetry and also works with the native stack. ### Historical File Families And Query Rules The paths below apply to file mode and old archives; they are not the source for new OTel-only traffic. - `~/.neurolink/logs/proxy-YYYY-MM-DD.jsonl` holds final request summaries. These are the rows the dashboard is built around. - `~/.neurolink/logs/proxy-attempts-YYYY-MM-DD.jsonl` holds per-upstream-attempt diagnostics. Rate-limited attempts include `retryable`, `rateLimitKind`, and `cooldownReason` so transient admission throttles are distinguishable from exhausted quota windows. Use this file when retries or account rotation need debugging. - `~/.neurolink/logs/proxy-debug-YYYY-MM-DD.jsonl` is the redacted index for captured request and response bodies. - `~/.neurolink/logs/bodies/YYYY-MM-DD//*.json.gz` stores the corresponding redacted body artifacts. - In OpenObserve, body captures arrive in the same `neurolink_proxy` log stream with `event.name=proxy.body_capture`, so request panels must filter to request-summary rows, for example `http_method IS NOT NULL`. - In OTel-only mode attempts use `proxy.record_kind=attempt`; final request counts must filter `proxy.record_kind=request_final`. Lifecycle, body and delivery diagnostics must not inflate those counts. File-mode attempt archives remain available for offline reconstruction. ### Deterministic Request Reconstruction When body capture is enabled, export one request and its upstream attempts without contacting the proxy or provider: ```bash neurolink proxy replay export \ --request-id \ --output replay.json ``` Use `--attempt ` to select a specific upstream attempt and `--logs-dir ` for a non-default log directory. The command verifies that every compressed artifact remains inside the managed body directory and matches the SHA-256 value in its debug index. The generated bundle is deterministic, redacted, written with `0o600` permissions, and reports missing phases, missing artifacts, and truncation instead of presenting partial evidence as complete. Credentials are never included in a replay bundle. To perform a direct comparison, inject each redacted header from a named environment variable and explicitly permit network execution: ```bash export ANTHROPIC_AUTHORIZATION='Bearer ...' neurolink proxy replay compare \ --bundle replay.json \ --output comparison.json \ --execute \ --header-env authorization=ANTHROPIC_AUTHORIZATION ``` The direct response is bounded and redacted using the same rules as proxy body logging. The comparison records status, content type, body hash, JSON shape, time to headers, and total duration. Redirects are not followed. HTTPS is required except for loopback fixture testing. A truncated or body-redacted request requires a complete `--body-file` override before execution. ## What This Dashboard Should Answer Use the dashboard to answer seven operational questions: 1. Is proxy traffic flowing right now? 2. Are users seeing failures, rate limits, or overloaded responses? 3. Is latency degrading for everyone, or only for a specific model or account? 4. Is fill-first routing concentrating traffic on one account as expected? 5. Are OTEL metrics still exporting correctly, or are logs and metrics diverging? 6. Is prompt cache reuse healthy, or are we paying too much cache creation cost? 7. Which traces should you open when you need request-level debugging? ## How To Read Each Tab ### Traffic & Health Read this tab first. - `Requests in Range` tells you whether volume changed. - `Failed Request Share` gives the top-line user-facing reliability signal. - `Mean Request Latency (s)` tells you whether users are feeling slowness. - `Overloaded Responses` helps separate provider saturation from generic failures. - `Request Trend` and `Requests by Model` explain whether a spike or a model mix shift caused the change. ### Failures & Rate Limits Use this tab when reliability drops. - `429 Rate-Limit Responses` means account or upstream rate pressure. - `Failures by HTTP Status` separates auth issues (`401` and `403`), rate limits (`429`), and transient upstream failures (`5xx`). - `Failures by Account / Route` shows whether one account or fallback route is poisoning the pool. - `Failure Trend` tells you whether the issue is a short burst or a sustained incident. ### Latency & Throughput Use this tab to judge user experience and saturation. - `P95 Request Latency (s)` is the best early warning signal for degraded UX. - `Throughput Trend` paired with `Latency Trend` tells you whether higher traffic is driving slower responses. - `Mean Latency by Model (s)` and `Mean Latency by Account / Route (s)` isolate whether the slowdown is model-specific or account-specific. ### Accounts & Routing Use this tab to understand fill-first routing behavior. - `Requests on Busiest Account / Route` should usually be high because the proxy intentionally fills one account before rotating. - `Accounts / Routes Used` shows whether the pool is spreading traffic or mostly staying on one account. - `Failure Share by Account / Route` tells you whether one account or fallback route should be re-authenticated, disabled, or investigated. - `Tokens by Account / Route (k)` helps explain quota pressure and uneven load. - When `account_name` is empty, these panels fall back to `account_type` so non-Anthropic routes do not appear as blank pseudo-accounts. ### Telemetry Cross-Check Use this tab to validate the OTEL export path itself. - These panels are shown as per-window OTEL deltas, not raw cumulative counter values. - `Metric Requests in Range`, `Metric Errors in Range`, and `Metric Retries in Range` should broadly agree with the earlier log-derived charts. - If `Metric Request Trend (5m)` is flat while `Request Trend (5m)` is moving, the metrics pipeline is broken or delayed. - If costs or request body volume stop moving here while logs keep arriving, OTEL metrics are unhealthy even if log export still works. ### Tokens, Cache & Cost Use this tab to understand workload mix and cache behavior. - `Prompt Tokens (M)` is prompt-side volume in millions: uncached input plus cache writes plus cache reads. - `Cached Prompt Tokens Reused (M)` is actual cache reuse. These tokens were read from an existing prompt cache entry. - `Cached Prompt Tokens Written (M)` is cache population. These tokens were written into a new cache entry on that request and can be reused by later requests. - `Cache Reuse Ratio` is reused cache tokens divided by newly written cache tokens. Values above `1` mean reuse is outpacing cache writes. - `Mean Total Tokens per Request` is average prompt-side plus output token volume per request, shown as raw tokens. - `Input vs Output Tokens per Request (5m)` compares average input and output tokens per request as raw tokens, which is easier to read than total prompt-side volume when cache reuse is large. - `Cache Reuse vs Cache Write Trend (5m, M)` keeps cache movement on its own scale so cache traffic does not flatten the input/output chart. - `Token Volume by Model (M)` tells you which model families are driving token volume. - `Top Sessions by Token Volume (M)` helps identify unusually heavy sessions for trace drilldown. - `Input vs Output Tokens by Account / Route` shows raw token totals by real account or fallback route, with internal final rows excluded. ### Trace Drilldown Use this tab after you know there is a problem and need request-level evidence. - `Slowest Operations by Mean Duration` is the best starting point for deep latency debugging. - `Span Status Mix` tells you whether failures are surfacing in traces as well as logs. - `Span Volume by Operation` and `Trace Volume Trend` help confirm whether the trace pipeline matches traffic volume. ## Key Correlation Fields These fields matter most when moving between logs, metrics, and traces: - `_timestamp`: event time in OpenObserve - `request_id`: request-level correlation key in proxy logs - `trace_id`: cross-signal trace correlation key - `span_id`: specific span correlation key - `event.name`: distinguishes request summaries from `proxy.body_capture` debug events in the shared OpenObserve log stream - `account_name`: which account handled the request - `ai_model`: which model served the request - `ai_input_tokens`: prompt/input tokens - `ai_output_tokens`: completion/output tokens - `ai_cache_creation_tokens`: tokens spent creating cache entries - `ai_cache_read_tokens`: tokens served from cache When a caller injects `traceparent` plus `x-neurolink-session-id` / `x-neurolink-user-id` / `x-neurolink-conversation-id`, the proxy attaches its spans to that upstream trace and preserves session-level attribution across SDK and proxy telemetry. Request and response bodies are recorded on traces only when `NEUROLINK_PROXY_TRACE_BODY_LOGGING=true`, the same opt-in as before the Langfuse migration. The prompt and answer of a translated request follow the same opt-in. Upstream error text is recorded without it, as before the migration, with credentials redacted and the text capped, and header values are recorded as received, except those of credential headers, which read `[REDACTED]`. See [Observability: Proxy](/docs/features/observability#proxy) for how `mask`, `redactIO` and `NEUROLINK_RECORD_INPUTS` apply to them. `ai_cache_creation_tokens` means prompt tokens written into a new cache entry. `ai_cache_read_tokens` means prompt tokens reused from an existing cache entry. All latency and duration panels are shown in whole seconds for faster scanning. Counts and token-heavy charts default to whole numbers when practical, while ratios, costs, and million/MB rollups are capped at two decimals. ## Common Interpretation Patterns - Rising `Failed Request Share` with flat traffic usually means a real reliability regression, not just more volume. - Rising `429 Rate-Limit Responses` with high load on one account usually means the pool is exhausting the primary account as designed. - Log traffic moving while the telemetry tab is flat means the OTEL metrics path needs attention. - Rising `Cache Creation Tokens` without matching `Cache Read Tokens` means prompt reuse is weak or the cache is still warming. - A slow chart on the latency tab plus the same operation on the trace tab gives you the fastest path to a concrete trace investigation. ## Request telemetry and evidence quality Use `neurolink proxy analyze --since 1h --format json` to reconcile retained request, attempt, lifecycle, and capture-index records. Read `dataQuality` before interpreting success rates or latency. The analyzer does not require captured prompt or response bodies. A client request has one generated `requestId`. Internal Codex fallback attempts retain their own ID plus `parentRequestId`, model, account, and `reasoningEffort`. The final Claude record retains the configured `fallbackPlan`; attempt records show which entries were actually tried. This evidence survives body retention. ### Completion and timing | Field | What it establishes | | ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | `responseStatus` on a lifecycle terminal | HTTP status committed by the adapter; a stream can still fail after HTTP 200 | | `finalStatus`, `terminalOutcome`, `outcomeSource` | Route outcome, joined before terminal publication; `unknown` means final evidence was unavailable | | `transportOutcome` | EOF, bodyless response, read error, or cancellation observed by the response adapter | | `telemetryStatus` | Whether terminal bookkeeping completed, timed out, failed, or lacked a final record; separate from the provider error | | `latencyMs.firstChunk` | First body chunk, including SSE control events | | `latencyMs.firstUsefulOutput` | First nonempty text or tool-argument delta parsed at the proxy; excludes thinking and control events | | `latencyMs.terminal` | Adapter terminal time, captured before waiting for bookkeeping or log writes | Anthropic streams require `message_stop`; native Codex streams require `response.completed`. In-band error events, incomplete responses, and EOF without the expected completion event are failures even if HTTP 200 was already sent. An unterminated SSE event is not dispatched completion evidence. Native Codex cancellation after the adapter observed the chunk containing a completion event counts as completed; a close before completion remains a cancellation. Provider error codes are retained in metadata, and a failed stream enriches its original attempt instead of inventing a new upstream call. Timing and byte counts describe observation at the proxy, not proof that the remote client received or consumed every byte. Useful-output timestamps use the worker's wall clock; lifecycle elapsed times use a monotonic clock. Requests with no useful output do not contribute a zero-latency sample. ### Storage health `GET /status` exposes `observability.lifecycle` and `observability.requestLogs`. The latter has independent `requests`, `attempts`, and `debug` sinks. For each metadata sink: ```text attempted = written + pending + inFlight + dropped + unconfirmedWrites ``` `written` means the append promise completed. `pending` means queued; `inFlight` means an append still owns its destination. The per-sink queue admits up to 4,096 queued or active records; further records increment `dropped`. `writeTimeouts` diagnoses slow appends and overlaps these states. A timeout never replays an append or forgets the underlying operation. Metadata writes are serialized per file within each worker. Lifecycle appends retry only destination-open failures that cannot have written any bytes. Other failed appends increment `unconfirmedWrites`: they may have written a prefix and are never replayed. Queue drops and definite exhausted write failures are exposed separately. A bounded shutdown flush may fail while writes remain pending; a successful flush alone does not prove that every record was written. Check drop and uncertainty counters too. When lifecycle logging is enabled, the HTTP adapter confirms the admission append before dispatching upstream. It waits for that record, not for all later traffic, with a two-second deadline. Failure returns HTTP 503 with local error code `PROXY_TELEMETRY_UNAVAILABLE`; it does not send an unrecorded provider request. A timed-out append can still complete later and is never replayed. Explicitly disabling logging disables this barrier. Confirmed appends survive serving-process death, but these files have no per-record `fsync` or transaction across log files. Power loss, retention, disk failure, and unconfirmed terminal tails remain possible. Counters are worker-local and reset on restart. They do not prove delivery to an OTEL collector or OpenObserve. Exporter/backend health must be checked separately. ### Reconciliation limits The analyzer deduplicates lifecycle `(processInstanceId, sequence)` identities before aggregating outcomes and latency. Conflicting duplicate payloads remain visible in `conflictingLifecycleDuplicates`, and affected requests are excluded from lifecycle latency samples. Repeated `(requestId, attempt)` records are merged, preserving failure evidence. Legacy `:codex-fallback` IDs are joined to their parents. `finalOutcomeConflicts` counts lifecycle/final disagreements. Final request failures override an old lifecycle success; a lifecycle success with no final record becomes `unknown`. `acceptedWithoutFinal` and `terminalWithoutFinal` report missing evidence, which can include active requests, interrupted workers, retention, or storage loss. They are not automatically provider failures. Token counting (`POST /v1/messages/count_tokens`) and model discovery (`GET /v1/models`, `GET /backend-api/codex/models`) have HTTP terminal outcomes without model final records. The analyzer identifies these as `lifecycle.auxiliaryRequests` and excludes them from missing-final counts. Their transport errors and unsuccessful HTTP statuses remain failures. They do not contribute model successes to `requests.success`. The time filter admits events in the selected window and follows already accepted requests through later retained lifecycle, attempt, and final records. Consequently, a request started near the window boundary can finish after `--until`. The observed ranges show that retained follow-up. Sequence gaps only measure gaps across the selected sequence span for each worker, including intervening retained events belonging to requests outside the time window. Excluding those requests from the outcome cohort does not create a sequence gap. The audit cannot identify missing prefixes, suffixes, or an entire missing worker. Stream `completeWindow` fields indicate temporal coverage, not proof of lossless collection. Historical final records without protocol evidence retain their reported outcome; this analysis cannot retrospectively certify completion or reconstruct discarded error causes. ### Worker incidents and host pressure The launchd supervisor writes `proxy-supervisor-YYYY-MM-DD.jsonl` independently of serving workers. The bounded recent-event ring is a status summary; the journal retains activation, failures, rejected connections, and actual worker exits past that ring. Exit records include the worker process-instance ID learned at readiness, PID, generation, version, exit code and signal. Supervisor actions are recorded separately from observed exits. Startup permits up to 120 seconds for a candidate; an existing worker keeps serving while its replacement starts. `lifecycle.unconfirmedAtWorkerExit` joins durable admissions without transport terminals to actual worker exits by process-instance ID. This establishes missing completion evidence at exit, not proof that the provider failed or that the client received nothing. A final provider record alone cannot prove client delivery. Older workers that do not report an instance ID remain unclassified. Every ten seconds, enabled journals record `runtime_sample`: actual sample duration, process CPU as a percentage of one core, RSS, heap, event-loop delay p99/max, host one-minute load average, and available CPU parallelism. Delayed sampling includes the extended interval. `proxy analyze` reports maxima in `runtime`; host load is never interpreted as a request count or a provider rate limit. Compare these samples with admission, first-output and attempt timings in the same interval. Socket offer and commit each get their own deadline. An offer timeout cancels an uncommitted connection. A commit timeout closes only that connection, whose dispatch is uncertain, and requests a replacement before draining existing streams. Neither path kills a serving worker because one handoff failed, and neither replays the socket. Replacements remain bounded by the existing candidate/draining limits and one-minute stall cooldown. Actual worker exits use the normal recovery backoff. ### Bounded body capture Bulk body serialization, redaction, hashing, compression and artifact writes run in a separate worker thread. The queue admits at most 64 captures and 32 MiB of estimated clone data with a 20-second deadline. OTel-only mode permits one entry to use the 32 MiB pool; file mode retains a 16 MiB per-entry ceiling. The estimate accounts for UTF-16 strings and object traversal without serializing on the serving thread. Oversized or unsupported values are explicitly rejected. Redacted bodies retain an 8 MiB OTel-only cap or a 1 MiB file cap. Stream captures retain at most 1 MiB per observer within a separate 16 MiB aggregate byte pool; indexes flag truncated prefixes. Borrowed traffic excludes body capture. See [OTel logging](/docs/proxy-otel-logging) for delivery and supervisor verification. `observability.requestLogs.bodyCapture` reconciles: ```text attempted = completed + failed + rejected + pending ``` Debug indexes include `bodyWriteFailed`, `captureError`, `captureQueueWaitMs`, and `captureProcessingMs`. Queue rejection and worker errors never fall back to bulk serialization on the serving thread. A worker crash can leave an orphan artifact; it does not turn a missing index into a successful capture. Regular retention cleans both indexed and orphan artifacts. OTLP body chunks remain compatible with existing dashboards. Chunk construction uses byte slices, emission yields between groups, and exporter batches are limited to 64 records (approximately 1 MiB of body text). OTLP remains a separate, best-effort export; local append counters do not certify backend delivery. Native Codex final errors retain the final attempt's transport code and account. Only explicit pre-connect transport failures may rotate automatically. EPIPE, socket resets and generic timeouts can occur after POST dispatch, so they are terminal instead of silently replaying potentially executed work. Request-log shutdown uses a 30-second flush budget, covering the body worker's 20-second deadline plus index and export publication. Storage failures can still leave explicitly unconfirmed writes after that deadline. Existing log directories are hardened to mode `0700` before lifecycle recording is enabled; failure keeps admission required and rejects dispatch with `PROXY_TELEMETRY_UNAVAILABLE`. Current-day supervisor journals are protected by the same retention rule as other active metadata logs. Sensitive JSON keys are redacted at every nesting level regardless of whether their values are strings, numbers, arrays, or objects. --- ## Claude Proxy Troubleshooting # Claude Proxy Troubleshooting This guide covers every issue encountered during development and real-world usage of the NeuroLink Claude proxy. For general proxy documentation, see [Claude Proxy](/docs/features/claude-proxy). ## Common Issues ### 1. "API Error: 400 invalid_request_error: Error" **Cause:** An OAuth token was sent without the required cloaking headers (billing header, `user_id` in metadata). This only happens when making bare `curl` requests through the proxy -- Claude Code includes its own cloaking automatically. **Fix:** Always connect to the proxy via Claude Code, not bare HTTP clients. The proxy's cloaking pipeline is designed to complement Claude Code's own request format. If you are testing with `curl`, the proxy will still work for the `/health`, `/status`, and `/v1/models` endpoints, but `/v1/messages` requires a properly formed Claude Code request or a valid API key account. ### 3. "context_management: Extra inputs are not permitted" **Cause:** Missing beta headers in the upstream request to Anthropic, specifically `prompt-caching-scope-2026-01-05`. Without this header, Anthropic rejects fields that Claude Code includes in its requests. **Fix:** The proxy now forwards Claude Code's exact beta headers to Anthropic. Ensure you are running the latest build: ```bash pnpm run build:cli ``` If the error persists, verify the beta headers in debug logs: ```bash NEUROLINK_LOG_LEVEL=debug neurolink proxy start # Look for: [proxy] beta headers: oauth-2025-04-20, claude-code-20250219, ... ``` --- ### 4. First request takes 30 seconds **Cause:** MCP server initialization. If `~/.mcp-config.json` or the project's `.mcp.json` references external MCP servers (filesystem, github-copilot, etc.), NeuroLink tries to connect to all of them on the first request. **Fix:** The proxy sets `NEUROLINK_SKIP_MCP=true` internally to skip MCP initialization. If you are still experiencing slow first requests: 1. Verify you are starting the proxy via `neurolink proxy start` (not running NeuroLink directly). 2. Check that the `NEUROLINK_SKIP_MCP` environment variable is not being overridden. 3. If using a custom config, ensure it does not reference MCP servers. --- ### 5. "OAuth token has expired" **Cause:** The token expired and the auto-refresh mechanism did not trigger in time. This can happen if the proxy was stopped and restarted after a long period, or if the system clock drifted. **Fix:** Re-authenticate: ```bash neurolink auth login anthropic --method oauth ``` The proxy has two layers of token refresh to prevent this: 1. **Pre-request check** (1-hour buffer) -- refreshes before each request if the token expires soon. 2. **401 auto-refresh + retry** -- on a 401 response, refreshes and retries up to 5 times. If this error occurs repeatedly, check that your system clock is accurate (`date` should match real time). --- ### 6. "accounts disabled until re-authentication" **Cause:** All accounts have been permanently disabled because their OAuth refresh tokens are expired or invalid. This happens after 15 consecutive refresh failures on an account. The proxy persists this state to disk via `tokenStore.markDisabled()`, so it survives restarts. **Fix:** Re-authenticate the affected accounts: ```bash # Re-login to reset the disabled state neurolink auth login anthropic --method oauth # For labeled accounts neurolink auth login anthropic --method oauth --add --label work ``` After re-authentication, the proxy detects the changed token material and automatically re-enables the account (clears `permanentlyDisabled`, resets `consecutiveRefreshFailures`). --- ### 7. Token refresh rate limited **Cause:** Too many refresh attempts in a short period. Anthropic's OAuth server rate-limits token refresh requests. **Fix:** Wait 30 seconds, then re-login: ```bash # Wait, then re-authenticate neurolink auth login anthropic --method oauth ``` If you see this error, it likely means multiple proxy instances are running or a manual refresh was triggered concurrently. Check for duplicate instances: ```bash neurolink proxy status # If stale, clean up: rm ~/.neurolink/proxy-state.json ``` --- ### 8. Claude Code not connecting to proxy **Symptoms:** Claude Code makes requests directly to `api.anthropic.com` instead of through the proxy. **Diagnosis:** ```bash # Check if ANTHROPIC_BASE_URL is configured cat ~/.claude/settings.json | python3 -m json.tool # Should include: "ANTHROPIC_BASE_URL": "http://127.0.0.1:55669" ``` **Fix:** 1. Run `neurolink proxy setup` which auto-configures `~/.claude/settings.json`. 2. Or manually add the env var to `~/.claude/settings.json`: ```json { "env": { "ANTHROPIC_BASE_URL": "http://127.0.0.1:55669" } } ``` 3. **Restart Claude Code** after setting the env var. Claude Code reads settings on startup, not dynamically. --- ### 9. Streaming response shows as raw bytes **Cause:** An earlier version of the Hono handler re-encoded the `ReadableStream` as a byte array instead of passing it through as a raw SSE stream. **Fix:** This is fixed in the current version. The proxy returns a raw `Response` object for streaming requests, preserving the SSE format. If you encounter this, rebuild: ```bash pnpm run build:cli ``` --- ### 10. Tools not working / "0 chunks" **Cause:** An earlier architecture had NeuroLink merging 68+ MCP tools with the client's tools, causing tool name conflicts and prefixing issues. Tool definitions were being modified or dropped in the merge. **Fix:** This is fixed in the current version. The proxy uses **passthrough mode** for Claude-to-Claude requests: the raw request body is forwarded directly to Anthropic without any parsing, tool merging, or reconstruction. Tool definitions pass through exactly as Claude Code sent them. If you are seeing tool issues: 1. Verify the proxy is in passthrough mode (check logs for `[proxy] POST /v1/messages` -- passthrough requests do not show "translation" in the log). 2. Ensure you are targeting a Claude model (passthrough is only for `claude-*` models). 3. Check that `NEUROLINK_SKIP_MCP=true` is set (prevents MCP tool injection). --- ### 11. Account not rotating on 429 **Cause:** The proxy uses **fill-first** routing by design. It keeps sending requests to one account until that account is rate-limited, then switches to the next. **This is expected behavior.** Fill-first is optimal for Anthropic because: - Anthropic's prompt caching is tied to the account/session. Spreading requests across accounts reduces cache hit rates. - Fill-first maximizes the benefit of each account's rate-limit window before moving on. On a 429, the proxy applies exponential backoff to the current account (1s, 2s, 4s, 8s, ... up to 10 minutes) and immediately tries the next non-cooling account. To verify rotation is working: ```bash NEUROLINK_LOG_LEVEL=debug neurolink proxy start # Watch for: # [proxy] account=secondary (oauth) ``` --- ### 12. "400 invalid_image_reference" or "invalid_image_data" when sending an image **Cause:** A request to a translated route (`/v1/chat/completions`, Gemini `generateContent`, or `/v1/messages` routed to a non-Anthropic provider) was refused locally, before any provider was contacted, for one of two reasons. - `invalid_image_reference`: the image was named as a local file path, an `http://` URL, an empty URL or another scheme, or (Gemini) raw base64 in `inlineData.data` was sent without an `image/` `mimeType`, or with a length or `=` padding that is not valid base64. The proxy resolves image references before the SDK sees them. It accepts `data:` URIs and public `https://` URLs, plus a Claude `base64` source and Gemini raw base64 with an `image/` `mimeType`, both of which it converts to a `data:` URI first. The answer is identical whether or not the file exists, and it never echoes the path. - `invalid_image_data`: the reference was acceptable, but the bytes behind it are not a recognised image. The proxy decodes every `data:` image (and every download) and reads its file signature; it does not trust the declared type. Text, a path, a page of HTML, a PDF, SVG, a payload too short to hold a complete recognised signature, an empty one (a `data:` URI with nothing after the comma, a Claude `base64` source or a Gemini `inlineData` of an image type whose `data` is empty or absent), and a `data:` URI that is not `;base64` all land here. Only the leading signature is checked, so an image cut off after a complete signature is not refused here. An empty slot is refused, never dropped: the request is not sent on without the picture. A Gemini `inlineData.data` that is a path made only of base64 characters (`/var/tmp/photo`) is the usual surprise: it is taken for base64, decodes to text, and is refused as data instead of being forwarded for the provider to fail on. **Fix:** Send the image inline as a `data:` URI (a Claude `base64` source is converted for you), or host it at a public `https://` URL that answers without a redirect. A Gemini client may send `inlineData.data` as raw base64 (standard or URL-safe) next to a `mimeType` such as `image/png`: the proxy converts it to a `data:` URI. For `invalid_image_reference`, check `inlineData.mimeType`: it must be an `image/` type with no space, comma or semicolon, and audio, PDF and untyped parts are not translated. Then check `data` itself: a length one character over a multiple of four, or `=` padding that does not match the length, is refused rather than forwarded. For `invalid_image_data`, send the image's own bytes, base64-encoded, not a file name or markup: the formats accepted are PNG, JPEG, WebP, GIF, HEIC, HEIF, AVIF, BMP, TIFF, ICO and JPEG 2000 (convert an SVG to PNG first). Of these, PNG, JPEG, WebP and GIF reach the provider as they are. The other seven are converted to PNG by the SDK when `sharp` or `ffmpeg` can read the file, and otherwise they are sent unchanged under their detected type, which every provider but Google (for HEIC and HEIF) then refuses: if an accepted BMP, TIFF, AVIF, ICO, JPEG 2000, HEIC or HEIF image comes back from a non-Google provider as an error, look for `Could not transcode` in the proxy's log and install a full `ffmpeg` build (or set `FFMPEG_PATH` to one); HEIC needs one that can decode HEVC. A wrong declared type is not a problem: the provider is sent the type the bytes have, and the correction is logged at debug level. `image_url_unfetchable` means an `https://` URL was refused (a private or non-public address, a redirect, an error status, or larger than the size limit while downloading); an `https://` URL that downloads fine but serves a page or text is `invalid_image_data`. `image_input_too_large` means more than 20 images, a `data:` URI longer than 50 MB, or `data:` URIs together longer than 100 MB. The limits count the URI string as sent, base64 included, not the decoded picture, so an image of about 37 MB already fills one. See [Image references on translated requests](/docs/features/claude-proxy#image-references-on-translated-requests). --- ## Debugging ### Enable debug logging ```bash NEUROLINK_LOG_LEVEL=debug neurolink proxy start ``` This outputs detailed information for every request: ``` [proxy] POST /v1/messages -> model=claude-opus-4-6 stream tools=109 [proxy] -> account=1-Tq78E (oauth) [proxy] # Grafana: Explore → Tempo → Search by traceId ``` ### Check debug logs Full request/response debug logs (complete headers and body summaries) are written to a separate file: ```bash # View today's debug log cat ~/.neurolink/logs/proxy-debug-$(date +%Y-%m-%d).jsonl | python3 -m json.tool # Search for a specific request ID grep "abc-123" ~/.neurolink/logs/proxy-debug-$(date +%Y-%m-%d).jsonl | python3 -m json.tool ``` Debug log entries include: request headers, request body summary (model, max_tokens, message count, tool count, thinking config), response status, response headers, response body (first 2000 chars on errors), and duration. **Log rotation:** Log files are automatically cleaned up at startup and hourly. Files older than 7 days are deleted. If remaining files exceed 500 MB total, the oldest are deleted until under the limit. ### Check account status ```bash # List all authenticated accounts neurolink auth list # Show proxy status (PID, uptime, strategy, accounts, cooldowns) neurolink proxy status # Machine-readable status neurolink proxy status --format json # Direct HTTP status check curl http://127.0.0.1:55669/status ``` ### Check Claude Code connection ```bash # Verify settings.json has the proxy URL cat ~/.claude/settings.json | python3 -m json.tool # Expected output includes: # "env": { # "ANTHROPIC_BASE_URL": "http://127.0.0.1:55669" # } ``` ### Test proxy endpoints directly ```bash # Health check (is the proxy running?) curl http://127.0.0.1:55669/health # Detailed status (accounts, cooldowns, uptime) curl http://127.0.0.1:55669/status # List available models curl http://127.0.0.1:55669/v1/models ``` ### Verify token validity ```bash # Check token expiry times neurolink auth status anthropic # Force a manual refresh neurolink auth refresh anthropic # Re-authenticate if refresh fails neurolink auth login anthropic --method oauth ``` ## Architecture Notes for Debugging Understanding the proxy's architecture helps diagnose issues faster. ### Passthrough mode (Claude to Claude) In `--passthrough` mode the proxy does not parse, modify, or reconstruct the request body and relays the caller's own `Authorization` / `x-api-key`. On the default OAuth pool path it does rewrite the body: `system` is normalised (a non-Claude-Code client's system prompt is relocated into the message stream behind the compiled-in billing and agent blocks), `metadata.user_id` is replaced with the account's Claude Code identity, and content is normalised (`polyfillOAuthBody`, `relocateClientSystemIntoMessages`). In both modes only allow-listed protocol headers travel upstream: - `Authorization: Bearer ` (for OAuth accounts) - `x-api-key: ` (for API key accounts) - `anthropic-beta` from the client, limited to the proxy's own beta set unless the client is Claude Code (session header and `claude-cli/` user-agent) - `user-agent`, `x-app`, `x-stainless-*`, `anthropic-version`, `accept*`, `content-type`; everything else (`x-neurolink-*`, trace context, `cf-*`, `x-forwarded-*`, cookies) is dropped - Snapshot headers applied only for OAuth accounts (User-Agent, Stainless SDK headers), captured from a genuine Claude Code client **When to suspect passthrough issues:** If the request works with one account but not another, the issue is likely account-specific (expired token, wrong permissions, billing). ### Translation mode (Claude to other provider) Full request parsing and format conversion through `neurolink.stream()`. The Claude Messages API request is converted to NeuroLink's internal format, sent to the target provider (Gemini, OpenAI, etc.), and the response is serialized back to Claude SSE format. **When to suspect translation issues:** If the error only occurs with non-Claude models or when the fallback chain activates. Check that the target provider's API key is configured and the model name is valid. ### Token lifecycle ``` Per-request check (1-hour buffer before expiry) | v Send request to Anthropic | v If 401 -> auto-refresh token -> retry up to 5 times | v All retries 401 -> 5min cooldown -> next account ``` ### Account selection (fill-first) ``` Request arrives | v Find first non-cooling account (in priority order) | v Send request | |-- 200 OK -> return response |-- 429 -> exponential backoff on this account -> try next account |-- 401 (OAuth) -> refresh token -> retry up to 5x |-- 401 (API key) -> 5-min cooldown -> try next account |-- 5xx -> no cooldown -> rotate immediately | v All accounts exhausted -> walk fallback chain | v All fallbacks exhausted -> return 429 with Retry-After header ``` ### Exponential backoff progression For repeated 429 errors on the same account: | Backoff Level | Cooldown Duration | | ------------- | ----------------- | | 0 | 1 second | | 1 | 2 seconds | | 2 | 4 seconds | | 3 | 8 seconds | | 4 | 16 seconds | | 5 | 32 seconds | | ... | ... | | Max | 10 minutes (cap) | The backoff level resets to zero on a successful request. ## Quick Reference | Symptom | Likely Cause | First Step | | ------------------------------- | ------------------------------------ | ----------------------------------------------- | | 400 invalid_request_error | Missing cloaking (bare curl) | Use Claude Code, not curl | | credit balance too low | API key with no credits in pool | Remove `ANTHROPIC_API_KEY` or add credits | | Extra inputs not permitted | Missing beta headers | Rebuild with `pnpm run build:cli` | | Slow first request (30s) | MCP server init | Verify `NEUROLINK_SKIP_MCP=true` | | Token expired | Auto-refresh missed | `neurolink auth login anthropic --method oauth` | | Refresh rate limited | Too many refresh attempts | Wait 30s, then re-login | | Accounts disabled until re-auth | Expired refresh tokens (15 failures) | `neurolink auth login anthropic --method oauth` | | Claude Code bypassing proxy | `ANTHROPIC_BASE_URL` not set | `neurolink proxy setup`, restart Claude Code | | Raw bytes in stream | Old build with Hono encoding bug | Rebuild with `pnpm run build:cli` | | Tools broken / 0 chunks | MCP tool merging (old build) | Rebuild; verify passthrough mode in logs | | No account rotation | Fill-first is working as designed | Check debug logs for 429 + rotation | --- ## Claude Proxy # Claude Proxy NeuroLink includes a Claude-API-compatible proxy server that sits between Claude Code and Anthropic. It pools multiple Claude accounts, handles rate-limit failover automatically, refreshes OAuth tokens on demand before they expire, and falls back to other providers when all Claude accounts are exhausted. ## Overview ### Why use the proxy? Claude Code supports only one Anthropic account at a time. If you hit a rate limit, you wait. If your token expires mid-session, you re-authenticate manually. The NeuroLink proxy solves these problems: - **Multi-account pooling** -- Combine multiple Claude Pro/Max subscriptions for higher aggregate throughput. - **Automatic token refresh** -- OAuth tokens are refreshed before they expire (pre-request check + 401 retry). - **Rate-limit failover** -- When one account hits a 429, the proxy immediately tries the next account with exponential backoff. - **Multi-provider fallback** -- When all Claude accounts are exhausted, requests are routed to alternative providers (Gemini, OpenAI, etc.) through NeuroLink's provider layer. - **Transparent to Claude Code** -- Set `ANTHROPIC_BASE_URL` and Claude Code works normally. The proxy auto-configures this on start. ### How it works at a glance ``` Claude Code | | POST /v1/messages v NeuroLink Proxy (localhost:55669) | |-- Passthrough mode (Claude -> Claude): raw body forwarding |-- Translation mode (Claude -> Other): through neurolink.generate()/stream() v Anthropic API / Google AI / OpenAI / ... ``` ## Quick Start If you do not already have the CLI installed, install it first: ```bash pnpm add -g @juspay/neurolink # or npm install -g @juspay/neurolink ``` Then continue with the proxy setup steps below. ### One-command setup ```bash neurolink proxy setup ``` This command: 1. Checks for existing authenticated accounts 2. Runs OAuth login if no valid accounts exist 3. Installs the proxy as a **launchd service** (macOS) that auto-restarts on crash or reboot 4. Auto-configures Claude Code to use the proxy Use `--no-service` to skip service installation and start the proxy in the foreground instead: ```bash neurolink proxy setup --no-service ``` ### Manual setup ```bash # Step 1: Authenticate with Anthropic via OAuth neurolink auth login anthropic --method oauth # Step 2: (Optional) Add more accounts for pooling neurolink auth login anthropic --method oauth --add --label work neurolink auth login anthropic --method oauth --add --label personal # Step 3: (Optional) Start the local OpenObserve stack and import the dashboard # (auto-writes OTEL_EXPORTER_OTLP_ENDPOINT to ~/.neurolink/.env) neurolink proxy telemetry setup # Step 4: Start the proxy neurolink proxy start # Step 5: Restart Claude Code to pick up the new ANTHROPIC_BASE_URL ``` For deployments that require an outbound HTTP proxy, set `HTTPS_PROXY` and/or `HTTP_PROXY` in the environment of the `neurolink proxy` process before starting it. `ALL_PROXY` is used when no scheme-specific proxy is set, and `NO_PROXY` bypasses the proxy for matching hosts. These settings cover Anthropic, Codex, and Vertex passthrough forwards, OAuth requests, and quota polling. When a configured proxy fails, these requests fail instead of retrying directly. ### Restart the serving worker ```bash neurolink proxy restart --check neurolink proxy restart ``` `restart` starts a replacement worker while the existing worker continues serving. The supervisor switches new connections only after the replacement acknowledges readiness and activation, then lets requests on the previous worker finish. You do not need to run the check separately: `restart` includes it. The command verifies admission, worker identity/version, socket-transfer counters and preservation of request-log disk/OTel settings. It does not generate a model request. A failed candidate has a 120-second readiness limit; the serving worker is retained. Concurrent restarts, pending updates and additional restarts while an older worker is still draining are refused. A disconnected terminal does not cancel the supervisor-owned operation or close admission. Use `--format json` for scripts. Exit zero means the check or activation was verified. `activated_unverified` means the replacement activated but a subsequent check failed; inspect `neurolink proxy status` before another operation. A lost control connection leaves the outcome unknown, rather than triggering a forced service restart. The JSON contract is `CliProxyRestartOutput`: an authenticated supervisor result or `{ "ok": false, "phase": "unverified", "message": "..." }` when the CLI cannot receive or authenticate that result. The latter exits nonzero and deliberately omits supervisor/worker fields that could not be verified. It does not mean the replacement failed or was rolled back. Control-server errors after binding are reported through the supervisor logger without stopping the serving listener. This requires a running supervisor that advertises restart-control support. Older supervisors must first receive a separately planned service activation; installing a newer CLI alone does not add the capability to an existing process. The command refuses an unsupported supervisor without signalling it. The listener and supervisor remain running, so this command does not apply changed launchd stdout/stderr destinations or replace supervisor/updater code. Those need a service activation with its own interruption budget. `proxy install` is service setup, not a routine restart command. The restart command does not rewrite the launcher, environment, routing configuration or update history. Local OTel initialization is checked; collector/backend delivery still needs telemetry verification. ## How It Works ### Request Flow Every request from Claude Code flows through the proxy in one of two modes: **Passthrough mode** (Claude to Claude): The request body is forwarded directly to `api.anthropic.com` with only the authentication headers modified. This preserves multi-turn conversation history, thinking content, cache control, and tool definitions exactly as Claude Code sent them. No lossy conversion through an intermediate format. **Translation mode** (Claude to other provider): When model routing directs a request to a non-Anthropic provider, the proxy parses the Claude Messages API request into NeuroLink's internal format, calls `neurolink.generate()` or `neurolink.stream()`, and serializes the result back into Claude Messages API format (including SSE streaming events). For streaming, the proxy emits SSE keep-alive comments (`: keep-alive`) every 15 seconds during idle periods to prevent connection timeouts. ### Trace And Session Context If the caller sends W3C trace headers (`traceparent`, `tracestate`) or NeuroLink session headers (`x-neurolink-session-id`, `x-neurolink-user-id`, `x-neurolink-conversation-id`), the proxy links its spans to the caller trace and preserves that session/user/conversation context in proxy traces and logs. ### Token Management The proxy uses three coordinated token refresh paths: 1. **Background check** -- Every 30 seconds, one non-overlapping maintenance cycle checks allowed, enabled accounts. 2. **Pre-request check** -- A request refreshes an OAuth token when it is within 5 minutes of expiry. 3. **401 retry** -- An unexpected Anthropic 401 triggers refresh and bounded retry before account rotation. Refresh calls sharing the same rotating refresh token are serialized and reuse the winning result. Credential rejection responses (`400`, `401`, `403`, or `404`) disable the account until explicit login; network errors, refresh-endpoint `429`s, and `5xx` responses apply a bounded 30-second to 5-minute auth cooldown instead. Automatic token saves preserve an operator-disabled account's metadata. Refreshed TokenStore and legacy credentials are persisted with `0o600` permissions using serialized atomic snapshot writes. ### Multi-Account Routing When multiple accounts are available, the proxy uses **fill-first** routing: 1. Use the first non-cooling account for every request. 2. On a 429, classify the authoritative quota window, persist its cooldown, and try the next account. 3. Continue until a request succeeds or all accounts are exhausted. 4. If all accounts are exhausted, walk the fallback chain (alternative providers). 5. If all fallbacks fail, return a 429 with a `Retry-After` header indicating the earliest account recovery time. If every account has a known future cooldown, the proxy does not call any of them again. Cooldowns survive restarts in `~/.neurolink/account-cooldowns.json`. Account sources are checked in priority order: 1. **TokenStore** compound keys (e.g., `anthropic:work`, `anthropic:personal`) -- from `neurolink auth login --label` 2. **Legacy credentials file** (`~/.neurolink/anthropic-credentials.json`) -- only if no TokenStore accounts exist 3. **Environment variable** (`ANTHROPIC_API_KEY`) -- only if no other accounts exist #### Designating a primary (home) account By default the "first" account is the first key in token-store insertion order. To override this without re-OAuthing or editing the obfuscated token store (`~/.neurolink/tokens.json` is XOR-obfuscated, not encrypted — treat the file as a secret), set `routing.primary-account` in the proxy config. The proxy resolves the email to a stable token-store key per request, so the choice survives account additions/removals and only takes effect when that account is currently authenticated: ```bash neurolink auth set-primary alice@example.com neurolink proxy status # Config: generation N curl http://127.0.0.1:55669/status # stats.primaryAccount.label = alice@example.com ``` After a 429 cools off, traffic returns to the configured primary (not literal index 0). When the configured account is missing or disabled, the proxy logs a warning while loading the configuration and falls back to insertion-order index 0. See the [config reference](/docs/features/claude-proxy-config-reference#neurolink-auth-set-primary) for the full CLI surface (`set-primary` / `get-primary` / `clear-primary`). #### Restricting eligible accounts `primary-account` controls ordering; it is not a security or isolation boundary. To ensure the proxy can use only an explicit set of Anthropic credentials, configure `routing.account-allowlist`: ```yaml routing: primary-account: primary@example.com account-allowlist: - primary@example.com ``` Entries accept an email/label or a full `anthropic:` key and are matched case-insensitively. When the field is present, unlisted TokenStore accounts are excluded before token loading or refresh. The legacy credential and `ANTHROPIC_API_KEY` fallback are also denied unless explicitly listed as `legacy-default` or `env`, and neither hidden fallback is considered while any Anthropic TokenStore entry exists. An empty list denies all Anthropic credentials; an absent field preserves unrestricted account discovery. ### Fallback Chain When all Claude accounts are rate-limited, the proxy walks the fallback chain defined in the config file. Each fallback entry specifies a provider and model: ```yaml routing: fallback-chain: - provider: google-ai model: gemini-3-flash-preview - provider: openai model: gpt-4o ``` Fallback requests go through NeuroLink's `stream()` pipeline (translation mode), which handles the format conversion to and from the target provider's API. Tools, thinking configuration, and conversation history from the original request are passed through to the fallback provider. ## Configuration ### Proxy config file The proxy loads configuration from `~/.neurolink/proxy-config.yaml` by default (override with `--config`). The file supports YAML or JSON format with environment variable interpolation. The running proxy watches this file and its resolved proxy env file. Valid routing edits are published atomically for new requests; in-flight requests keep their original generation. Invalid or deleted observed files are rejected and the last-known-good generation remains active. ```yaml # ~/.neurolink/proxy-config.yaml version: 1 # Account definitions (alternative to neurolink auth login) accounts: anthropic: - name: primary apiKey: ${ANTHROPIC_API_KEY_PRIMARY} - name: secondary apiKey: ${ANTHROPIC_API_KEY_SECONDARY} weight: 2 rateLimit: 100 # Routing configuration routing: strategy: fill-first # or round-robin quota-routing: true session-soft-limit: 0.97 session-reset-tolerance-ms: 900000 primary-account: primary@example.com account-allowlist: - primary@example.com # Model mappings: remap incoming model names to different providers model-mappings: - from: claude-sonnet-4-20250514 to: gemini-3-pro-preview provider: google-ai # Fallback chain: try these when all Claude accounts are exhausted fallback-chain: - provider: google-ai model: gemini-3-flash-preview - provider: openai model: gpt-4o # Models that always go to Anthropic (skip routing logic) passthrough-models: - claude-opus-4-20250514 - claude-sonnet-4-5-20250929 # Cloaking configuration (request transformation for OAuth) cloaking: mode: auto # "auto" | "always" | "never" plugins: {} ``` When routing is enabled, any requested model that starts with `gemini-` is treated as a Vertex target by default unless an explicit `model-mappings` rule overrides it. ### Environment variable interpolation String values in the config file support `${VAR_NAME}` and `${VAR_NAME:-default}` syntax: ```yaml accounts: anthropic: - name: primary apiKey: ${ANTHROPIC_KEY_1} - name: fallback apiKey: ${ANTHROPIC_KEY_2:-sk-ant-fallback-key} ``` ### Account configuration options | Field | Type | Default | Description | | ----------- | ------- | ------- | ------------------------------------------ | | `name` | string | unnamed | Human-readable label for the account | | `apiKey` | string | -- | API key or token (supports `${ENV_VAR}`) | | `baseUrl` | string | -- | Override the provider endpoint URL | | `orgId` | string | -- | Organization ID (e.g., for OpenAI orgs) | | `weight` | number | 1 | Weight for weighted round-robin selection | | `enabled` | boolean | true | Whether this account is active | | `rateLimit` | number | -- | Max requests per minute for this account | | `metadata` | object | -- | Arbitrary metadata attached to the account | ### Server options | Option | Default | Description | | -------- | -------------------------------- | ------------------- | | `port` | 55669 | Port to listen on | | `host` | 127.0.0.1 | Host to bind to | | `config` | `~/.neurolink/proxy-config.yaml` | Path to config file | ### Inbound authentication Every request the proxy serves spends one of the pooled subscriptions, so the proxy decides at start-up whether anything authenticates its callers: - **Loopback (`127.0.0.1`, `localhost`, `::1`) binds always start.** The only callers are processes on this machine. - **Any other `--host` is refused** unless one of these is in place: - an **inbound token** — `--inbound-token ` or `NEUROLINK_PROXY_INBOUND_TOKEN`. Every caller must then send it as `x-neurolink-inbound-token: ` or `Authorization: Bearer ` (the proxy replaces `Authorization` upstream, so an Anthropic SDK client can simply use the token as its `ANTHROPIC_AUTH_TOKEN`). A request carrying a share token is judged by the share gate instead. `/health` stays open; `/peer/*` authenticates itself; `/internal/update-control` has its own token. - the **share gate** — `NEUROLINK_PROXY_REQUIRE_GRANT=1`, which refuses any request without a valid share token (including the operator's own client). - `--allow-unauthenticated` (or `NEUROLINK_PROXY_ALLOW_UNAUTHENTICATED=1`), which records that an authenticating reverse proxy sits in front. The proxy starts and logs a warning. `GET /limits`, `GET /accounts` and `GET /status` are operator surfaces: they name every account (an email for an OAuth account) with its quota and spend. They are refused to borrowers and, when an inbound token is configured, to any caller without it. Other inbound-trust guarantees, regardless of bind address: - Only protocol headers travel upstream (`content-type`, `accept*`, `anthropic-version`, `anthropic-beta`, `user-agent`, `x-app`, `x-stainless-*`, `x-claude-code-session-id`, …). `x-neurolink-*`, `traceparent`/`tracestate`/`baggage`, `cf-*`, `x-forwarded-*`, `x-real-ip`, `via`, `forwarded`, cookies and hop-by-hop headers never reach Anthropic. - A client may only add `anthropic-beta` values the proxy would send itself, unless it is Claude Code (both `x-claude-code-session-id` and a `claude-cli/` user-agent). A rejected client-supplied beta never re-ranks the pool. - One request is tried against at most `NEUROLINK_PROXY_MAX_ACCOUNTS_PER_REQUEST` accounts (default 3; `0` removes the cap). - The per-account header snapshot (`~/.neurolink/header-snapshots/`) is captured only from Claude Code itself, never from a borrowed request, and holds only the identity tuple (device id, session id, normalised billing header). The agent `system` block is compiled in and never taken from a request; a snapshot written by an earlier release that carries one is rewritten without it on first load. ## CLI Commands ### `neurolink proxy setup` One-command onboarding: checks for existing accounts, runs OAuth login if needed, installs the proxy as a persistent service, and configures Claude Code. ```bash neurolink proxy setup # Full setup: login + install as launchd service (macOS) neurolink proxy setup --no-service # Login + start foreground (no auto-restart) neurolink proxy setup -p 9000 # Setup on custom port ``` ### `neurolink proxy install` Install the proxy as a persistent macOS launchd service. The service auto-restarts on crash (5-second throttle interval) and starts on login. ```bash neurolink proxy install # Install with defaults (port 55669) neurolink proxy install --port 9000 # Install on custom port neurolink proxy install --host 0.0.0.0 --inbound-token "$(openssl rand -hex 32)" # All interfaces, callers must present the token ``` A non-loopback `--host` without `--inbound-token`, `NEUROLINK_PROXY_REQUIRE_GRANT=1` or `--allow-unauthenticated` is refused — see [Inbound authentication](#inbound-authentication). The token is persisted into the service's environment (the plist is `0600`). ```bash ``` **Options:** | Flag | Alias | Default | Description | | -------- | ----- | --------- | ----------------- | | `--port` | `-p` | 55669 | Port to listen on | | `--host` | `-H` | 127.0.0.1 | Host to bind to | ### `neurolink proxy uninstall` Remove the launchd service. Stops the proxy if it is running and deletes the launchd plist. ```bash neurolink proxy uninstall ``` ### `neurolink proxy start` Start the proxy server. ```bash neurolink proxy start # Default: port 55669, fill-first neurolink proxy start -p 8080 -s fill-first # Custom port and strategy neurolink proxy start --config ./my-proxy.yaml # Custom config file neurolink proxy start --debug # Enable debug logging neurolink proxy start --quiet # Suppress non-essential output neurolink proxy start --passthrough # Transparent forwarding (no retry/rotation) neurolink proxy start --env-file ./proxy.env # Load provider keys from dedicated file ``` **Options:** | Flag | Alias | Default | Description | | ------------------------- | ----- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `--port` | `-p` | 55669 | Port to listen on | | `--host` | `-H` | 127.0.0.1 | Host to bind to. Non-loopback needs `--inbound-token`, `NEUROLINK_PROXY_REQUIRE_GRANT=1` or `--allow-unauthenticated` | | `--inbound-token` | | | Bearer every caller must present (`x-neurolink-inbound-token` or `Authorization: Bearer`); also `NEUROLINK_PROXY_INBOUND_TOKEN` | | `--allow-unauthenticated` | | false | Bind a non-loopback host with no inbound authentication (an authenticating reverse proxy must sit in front) | | `--strategy` | `-s` | fill-first | Account selection strategy (`fill-first` or `round-robin`) | | `--health-interval` | | 30 | Health check interval (seconds) | | `--config` | `-c` | `~/.neurolink/proxy-config.yaml` | Config file path | | `--quiet` | `-q` | false | Suppress output | | `--debug` | `-d` | false | Enable debug output | | `--passthrough` | | false | Transparent forwarding (no retry, rotation, or polyfill) | | `--env-file` | | | Path to .env file for provider API keys | **Strategy choices:** `round-robin`, `fill-first` ### `neurolink proxy status` Show proxy status, including PID, uptime, strategy, fallback chain, and per-account usage statistics fetched from the live `/status` endpoint. Status output now distinguishes total upstream attempts from completed requests, so retry-heavy incidents are easier to spot. ```bash neurolink proxy status # Human-readable text output neurolink proxy status --format json # Machine-readable JSON ``` ### `neurolink proxy telemetry ` Manage the local OpenObserve stack and the maintained proxy dashboard from the CLI. ```bash neurolink proxy telemetry setup # Start OpenObserve + OTEL collector and import dashboard neurolink proxy telemetry start # Start the local telemetry stack only neurolink proxy telemetry stop # Stop the local telemetry stack neurolink proxy telemetry status # Show local stack health neurolink proxy telemetry logs # Follow OpenObserve + collector logs neurolink proxy telemetry import-dashboard # Re-import the dashboard without restarting containers ``` These commands use the repo-owned assets under `scripts/observability/` and the dashboard JSON at `docs/assets/dashboards/neurolink-proxy-observability-dashboard.json`. ### `neurolink proxy analyze` Read the proxy's own request and attempt logs and report what actually happened: per-account success and failure counts, retry-recovered requests, terminal error categories, and routing decisions. ```bash neurolink proxy analyze # summarise the retained window neurolink proxy analyze --logs-dir # a specific log directory ``` Reported counts are bounded by log retention. When the request and attempt windows are not comparable, the command says so rather than printing a recovered-after-retry figure it cannot stand behind. ### `neurolink proxy replay ` Reconstruct a captured request for debugging, or send it directly upstream to compare proxied and direct behaviour. ```bash neurolink proxy replay export --request-id --output bundle.json neurolink proxy replay compare --bundle bundle.json --execute ``` `compare` reaches a provider, so it requires the explicit `--execute` flag. Captured bodies are redacted; supply `--body-file` when a full body is needed, and `--header-env` to inject a credential from an environment variable rather than a literal. ### `neurolink proxy share ` Lend spare pool capacity to a peer, with the terms enforced on every request. See [Proxy Peer Sharing](/docs/features/proxy-peer-sharing) for the full guide. ```bash neurolink proxy share url https://proxy.example.com # record this node's address neurolink proxy share url # show it neurolink proxy share url get # bare value, for scripts neurolink proxy share url --clear # forget it neurolink proxy share create --peer --preset spare neurolink proxy share list | status [--peer ] neurolink proxy share pause --peer # stops at their next request neurolink proxy share resume --peer neurolink proxy share set --peer --reserve 40 --max-slice 5h=15 neurolink proxy share topup --peer --coins 200 neurolink proxy share rotate --peer # new token, same controls neurolink proxy share revoke --peer neurolink proxy share delete --peer neurolink proxy share level --peer --to complete neurolink proxy share provision --peer --from-account neurolink proxy share provision --peer --code # finish it neurolink proxy share receipts --peer # what you charged them neurolink proxy share note --coins 200 --ttl 30d # mint a transferable note neurolink proxy share notes # notes minted, and spent ``` `share provision` is a **split-PKCE** flow: the borrower runs `neurolink proxy peer request` first and keeps the verifier, you authorize in your browser and relay a single-use code. You never hold a token for the credential you mint. See [Proxy peer sharing](/docs/features/proxy-peer-sharing). Controls, all applied together: | Flag | Meaning | | ---------------------------------------------- | ------------------------------------------------------------- | | `--reserve 30` | Keep 30% headroom on **each** account for yourself | | `--max-slice 20` | Borrower may take at most 20% of the **pool**, however spread | | `--max-slice-per-account 20` | Apply that ceiling to each account independently instead | | `--spillover 12h\` | Restrict which of your accounts are lendable | | `--rate 20/min --concurrency 2` | Request and in-flight ceilings | | `--schedule 21-9` | Hours the share is open (wraps midnight) | | `--expires 7d` | Grant lifetime | | `--ledger coins --coins 500 --refill 100/week` | Meter it instead of leaving it open | Presets fill these in: `spare` (reserve + pool slice), `spillover`, `metered`, `open`. Any explicit flag overrides the preset. ### `neurolink proxy peer ` Borrow capacity from someone else's pool. Peers are consulted **only after every local account is spent**, ahead of the provider fallback chain. ```bash neurolink proxy peer add --name --link "neurolink://share/...#" neurolink proxy peer add --name --url https://proxy.example.com --token neurolink proxy peer request --name # ask to be provisioned neurolink proxy peer request --name --claim # collect and install neurolink proxy peer list | status [--json] neurolink proxy peer test --name # free reachability probe neurolink proxy peer sync [--name ] # force a check-in neurolink proxy peer receipts --name # check what you were charged neurolink proxy peer net --name # net reciprocal use neurolink proxy peer redeem --name --coin-note neurolink proxy peer set --name --priority 5 neurolink proxy peer pause | resume | remove --name ``` ### `neurolink proxy expose` Publish this node through a `cloudflared` tunnel, for operators without an address of their own. With no `--port` it picks the gate-only **share listener** — the port that requires a grant on every request — and refuses to open a tunnel to anything that serves untokened requests. ```bash neurolink proxy expose # the share listener neurolink proxy expose --port 3000 # or a port you name neurolink proxy expose --named # stable URL across restarts ``` The share listener starts on its own once at least one grant is active, on `--share-port` (default: proxy port + 1). Your own client keeps using the main port untokened. If you already front the proxy with your own domain, skip this and record the address with `neurolink proxy share url ` instead. ### `neurolink auth login anthropic` Authenticate with Anthropic. Supports multi-account pooling via `--add --label`. ```bash # Interactive (prompts for method) neurolink auth login anthropic # OAuth (for Claude Pro/Max subscription) neurolink auth login anthropic --method oauth # API key neurolink auth login anthropic --method api-key # Create API key via OAuth (Claude Pro/Max) neurolink auth login anthropic --method create-api-key # Add a second account with a label neurolink auth login anthropic --method oauth --add --label work neurolink auth login anthropic --method oauth --add --label personal # Non-interactive mode (requires environment variables) neurolink auth login anthropic --method api-key --non-interactive ``` **Options:** | Flag | Alias | Default | Description | | ------------------- | ----- | ------- | ------------------------------------------------------------ | | `--method` | `-m` | -- | Auth method: `api-key`, `oauth`, `create-api-key` | | `--add` | | false | Add as additional account to the pool (instead of replacing) | | `--label` | | -- | Human-readable label for this account (used with `--add`) | | `--non-interactive` | | false | Skip interactive prompts (requires environment variables) | | `--format` | | text | Output format: `text` or `json` | | `--debug` | | false | Enable debug output | ### `neurolink auth list` List all authenticated accounts with status, including the account email address (resolved via OAuth token exchange), token expiry, and per-account quota utilization (5-hour and 7-day windows). ```bash neurolink auth list # Text output neurolink auth list --format json # JSON output neurolink auth list --debug # Include debug details ``` ### `neurolink auth status` Show authentication status for a specific provider (or all providers if omitted). ```bash neurolink auth status # Show all providers neurolink auth status anthropic # Show Anthropic only neurolink auth status --format json # JSON output ``` ### `neurolink auth refresh` Manually refresh OAuth tokens. ```bash neurolink auth refresh anthropic ``` ### `neurolink auth cleanup` Remove accounts from the token store whose credentials no longer work. ```bash neurolink auth cleanup # Interactive: prompts before removing neurolink auth cleanup --force # Remove without prompting ``` Only accounts the proxy gave up on are deleted — expired entries with no refresh token, and accounts disabled for `missing_refresh_token`, `refresh_invalid` or `refresh_failed`. An account you disabled yourself, or one blocked by an organization policy, still holds a valid login, so cleanup keeps it and tells you to use `auth enable` or `auth remove` instead. ### `neurolink auth enable` / `neurolink auth disable` Take an account out of the proxy pool, or put it back. Disabling keeps the credentials; the proxy re-reads the token store on every request, so it takes effect on the next one without a restart. ```bash neurolink auth disable anthropic:work --reason "org disabled oauth" neurolink auth enable anthropic:work ``` The proxy also disables an account automatically when Anthropic refuses it on an organization entitlement policy (`403 permission_error`), after rotating the request to a healthy account. Re-enable it once an admin restores access. ### `neurolink auth cooldown [account]` Inspect or release the per-account cooldowns the proxy persists after rate limits and auth failures. `action` is `list` or `clear`. ```bash neurolink auth cooldown list neurolink auth cooldown clear anthropic:work neurolink auth cooldown clear --all ``` A running proxy caches cooldowns for its process lifetime, so restart it for a clear to take effect on an instance that is already serving. ### `neurolink auth overage [action]` Show or set whether the pool may keep serving on paid extra usage once an account's subscription window is spent. Writes `routing.use-overage` to the proxy config, which a running proxy picks up automatically. `action` is `status` (the default), `auto`, `always` or `never`. ```bash neurolink auth overage # current policy and per-account status neurolink auth overage auto|always|never neurolink auth overage never # stop at the subscription limit ``` Only `never` overrides the provider. Nothing here can enable extra usage that Anthropic reports as disabled — `status` names the reason when it is, for example `org_level_disabled`. ### `neurolink auth set-primary` / `get-primary` / `clear-primary` Pin routing to a preferred account, read the current pin, or remove it. The primary is a preference, not a guarantee: a saturated or cooling primary is still passed over. ```bash neurolink auth set-primary neurolink auth get-primary neurolink auth clear-primary ``` ### `neurolink auth health` Report per-account credential health — token validity, expiry, disabled state and the reason for it. ```bash neurolink auth health neurolink auth health --format json ``` ### `neurolink auth logout ` / `neurolink auth remove ` `logout` clears stored tokens for a provider but keeps the account entry. `remove` deletes the entry entirely. ```bash neurolink auth logout anthropic neurolink auth remove anthropic ``` ### `neurolink auth validate ` Check a token against the provider without storing it — useful when diagnosing whether a credential or the routing around it is at fault. ```bash neurolink auth validate ``` ### `neurolink auth providers` List the providers the auth subsystem supports and which of them have stored credentials. ```bash neurolink auth providers ``` ## Multi-Account Setup ### Adding multiple accounts Each `neurolink auth login --add --label ` creates a separate account entry in the TokenStore (`~/.neurolink/tokens.json`): ```bash # Account 1: personal Claude Max neurolink auth login anthropic --method oauth --add --label personal # Account 2: work Claude Max neurolink auth login anthropic --method oauth --add --label work # Account 3: API key for fallback neurolink auth login anthropic --method api-key --add --label api ``` ### How accounts are selected The proxy discovers accounts in this order: 1. Compound keys from TokenStore (e.g., `anthropic:personal`, `anthropic:work`) 2. Legacy credentials file (if no compound keys exist) 3. `ANTHROPIC_API_KEY` environment variable (if no other accounts exist) When `routing.account-allowlist` is configured, this discovery happens only within the allowed set. A disabled or unavailable TokenStore account does not cause the proxy to activate a legacy file or environment key while TokenStore entries still exist. Within the account pool, the proxy uses **fill-first** routing: it always tries the first non-cooling account and only switches on failure. This avoids unnecessary identity switches that could confuse Claude Code's session state. ### Model-scoped weekly limits Some plans cap a specific model separately from the overall weekly window — a Fable-only weekly allowance, for instance. Anthropic reports that cap as its own header family (`anthropic-ratelimit-unified-7d_oi-*`), sent **only** on responses for the model it applies to, so the proxy learns about it from live traffic rather than needing a refresh. Routing treats a spent model-scoped cap as per-model, never per-account: - An account whose cap for the requested model is spent is skipped for **that model only**. It stays fully available for every other model, and no cooldown is set — cooling is account-wide and would wrongly withhold a healthy account. - Among accounts that do have headroom, the one closest to spending its allowance is preferred, so the pool finishes an allowance rather than spreading across all of them. This rung only applies when both candidates report a window for the model. - If **every** account has spent the cap, the request is not attempted. The client gets a `429` naming the model, the real reset time, and that other models remain available — switch model, or add an account with headroom. - A scoped window older than the quota freshness budget is ignored, so stale or mis-parsed data can never take the pool down. Routing falls back to attempting the request. `neurolink auth list` shows any scoped window under its account, and `GET /limits` returns the full `windows[]` array. ### Cooldown and backoff When an account encounters an error, it enters a cooldown period based on the error type: | Failure | Cooldown | Behavior | | --------------------------------------------------------------- | -------------------------------------------------- | ------------------------------------------------ | | Authoritative unified, 5-hour, or 7-day rejection | Upstream reset or `Retry-After`, capped per reason | Persist cooldown and rotate immediately | | Transient burst 429, as a status or as the stream's first event | Upstream delay, capped at 15 minutes | At most 2 same-account retries, then rotate | | Refresh credential rejection (`400`/`401`/`403`/`404`) | Disabled until explicit login | Rotate without retrying an invalid refresh token | | Refresh network, `429`, or `5xx` | 30 seconds to 5 minutes | Persist auth cooldown and rotate | | Upstream `5xx` or network error | Bounded same-account retries | Rotate after retry budget | Cooldown updates are extend-only: a late concurrent response cannot shorten a longer known reset window. The one exception is a transient burst. When a same-account retry is served, the burst is over, so its cooldown is lifted and the session's next request stays on that account instead of moving away and losing its prompt cache. An exhaustion cooldown recorded in the meantime is left in place. Each cooldown is also capped by what its reason can mean — a `session` cooldown describes a 5-hour window, so it can never run for days no matter what reset the upstream reports. The cap is applied when the cooldown is written and again when it is read back from disk, so an entry written by an older build heals itself on load and logs that it did: ``` [proxy] cooldown clamp: anthropic:work session entry healed from 206.0h to 5.3h — the stored wait exceeded what "session" can mean ``` Use `neurolink auth cooldown list` to see what is currently parked, and `neurolink auth cooldown clear ` to release one. ## Error Handling The proxy classifies upstream errors and applies different strategies: ### 429 Rate Limit - Treat top-level `anthropic-ratelimit-unified-status: rejected` as authoritative, even if sub-windows still say `allowed`. - Prefer the rejected 5-hour or 7-day reset and otherwise use `Retry-After`. - Persist the cooldown and rotate immediately for authoritative exhaustion. - Return the earliest recovery timestamp without another upstream request when all accounts are cooling. ### 401/402/403 Authentication Errors - **OAuth accounts with refresh token:** Serialize refresh, persist the new rotating token, and retry. A rejected refresh credential disables the account until re-authentication; transient refresh infrastructure errors cool and rotate. - **OAuth accounts without refresh token:** Disable until re-authentication and rotate. - **API key accounts:** Rotate after authentication failure. ### 400/422 Request Shape Error - Detected via HTTP 422 status or `invalid_request_error` error type in the response body. - No retry or failover. These are client-side errors (malformed request, invalid parameters). - Return the error body directly to Claude Code. ### 400 Refused Image Reference - A translated request (OpenAI, Gemini, or Claude routed to another provider) named an image the proxy will not resolve: a local path, an `http://` URL, another scheme, an `https://` URL that could not be fetched safely, an empty URL, or (Gemini) raw base64 whose `mimeType` is not an `image/` type; or it carried image bytes that are not a recognised image: text, a path, a page, SVG, an empty (or absent) payload, or one too short to hold a complete recognised signature. - Answered locally before any provider is contacted, with code `invalid_image_reference`, `invalid_image_data`, `image_url_unfetchable` or `image_input_too_large`. No retry and no fallback. - See [Image references on translated requests](#image-references-on-translated-requests). ### 404 Not Found - Typically means the model is not available for this account. - No cooldown applied. - Return the error body immediately to the client (no failover to next account). ### 5xx / Transient Server Error - Transient errors (408, 500, 502, 503, 504, and Cloudflare 520-526/529). - Also matches `400` responses with `api_error` or `overloaded_error` types that wrap transient HTML content (e.g., Cloudflare error pages). - Apply bounded same-account retries, then rotate to the next account. ### All Accounts Exhausted When every account is in a cooling state: 1. Walk the fallback chain (if configured). 2. Each fallback uses NeuroLink's `stream()` pipeline with the specified provider/model. 3. If all fallbacks also fail, return a 429 with `Retry-After` set to the earliest account recovery time. ### Bootstrap Retry (Streaming) For streaming requests, the proxy reads the first chunk from the upstream response before forwarding it to the client. If the first chunk is empty (indicating a failed stream), the proxy retries with the next account. This prevents Claude Code from receiving an empty SSE stream. ## Auto-Configuration ### Claude Code integration Foreground `proxy start` and explicit `proxy setup` configure `~/.claude/settings.json`: ```json { "env": { "ANTHROPIC_BASE_URL": "http://127.0.0.1:55669", "ENABLE_TOOL_SEARCH": "true" } } ``` When the proxy stops (Ctrl+C or SIGTERM), it removes these entries from the settings file. This means Claude Code automatically routes through the proxy when it is running and goes direct when it is not. **Note:** You must restart Claude Code after starting or stopping the proxy for the settings change to take effect. Managed service restarts and rolling upgrades preserve existing client settings. They do not reapply routing or replace user edits. Run `neurolink proxy setup` when you want to configure clients explicitly, including after a standalone service installation. ### Proxy state file The proxy persists its running state to `~/.neurolink/proxy-state.json` so that `neurolink proxy status` can report on it and `neurolink proxy start` can detect an already-running instance. The state includes PID, port, host, strategy, start time, fallback chain, enforced account allowlist, and the optional foreground fail-open guard PID. ### Fail-open guard A foreground proxy spawns one detached `neurolink proxy guard` that removes stale Claude Code settings after confirming its parent process has died. A launchd-managed proxy keeps restart ownership in launchd and starts a separate updater-only worker. Automatic package updates are enabled by default and can be disabled with `NEUROLINK_PROXY_AUTO_UPDATE=off` (also accepts `0` or `false`). The worker validates the global package root and executable directory and requires the package manager that owns the running installation. Rolling installations activate and health-check the new serving worker first. If the parent supervisor still reports the older version, the updater waits for a two-minute idle window, applies a bounded admission drain, and asks launchd to refresh the supervisor. Success requires both worker and supervisor to report the new version from a new parent process. The drain automatically expires if the updater disappears, and refresh failures retain the installed version for retry instead of repeatedly reinstalling it. Legacy services wait for every request and stream before their direct launchd restart. Post-install executable validation uses bounded retries, and the proxy supervises and replaces an updater worker that exits unexpectedly. Installed-but-not-running versions and stage-specific update failures remain persisted in `~/.neurolink/update-state.json`. Updater diagnostics are sent through the configured proxy log sink and exposed in `neurolink proxy status`. ## Architecture ### Endpoints | Method | Path | Description | | ------ | --------------------------- | --------------------------------------- | | POST | `/v1/messages` | Claude Messages API (main endpoint) | | GET | `/v1/models` | List available Claude models | | POST | `/v1/messages/count_tokens` | Token counting | | GET | `/health` | Health check (status, strategy, uptime) | | GET | `/status` | Detailed proxy status | ### Passthrough mode (Claude to Claude) When the target provider is `anthropic` (the default for any `claude-*` model), the proxy operates in passthrough mode: 1. Load allowed, enabled TokenStore accounts. Consider legacy or environment credentials only when no Anthropic TokenStore entries exist and the source is allowed. 2. Select the first non-cooling account according to the active routing strategy. With the default `fill-first` strategy, this is always the current primary account until it cools down. 3. Auto-refresh the token if expiring within 5 minutes, sharing one in-flight refresh for concurrent requests. 4. Forward the raw request body via plain `fetch()` to `https://api.anthropic.com/v1/messages?beta=true`. 5. Set authentication headers (`Authorization: Bearer` for OAuth, `x-api-key` for API keys). 6. Forward client headers as-is, preserving Claude Code's own request shape, then merge in required OAuth betas and trace headers when absent. The proxy extracts incoming `traceparent` and `x-neurolink-*` headers and injects outbound trace context plus `x-claude-code-session-id` when needed. 7. For streaming: verify the first chunk (bootstrap retry), then forward the stream. For non-streaming: return JSON. This mode preserves the exact request format that Claude Code expects, including thinking blocks, cache control headers, and multi-turn tool use conversations. Rate-limit headers from Anthropic are passed through to the client — see [Limit response headers](#limit-response-headers) below. ### Limit response headers Every proxy response — streaming, non-streaming, and errors including 429 — carries the account's limit state. There are two layers. **Verbatim passthrough.** Anthropic's own `anthropic-ratelimit-*` headers and `retry-after` are forwarded unchanged. This is deliberate: a proxied response looks identical to a direct one, so a client needs only a single parser for both. Which family is present depends on the serving account: | Account type | Headers | Semantics | | -------------------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | OAuth / subscription | `anthropic-ratelimit-unified-5h-*`, `-7d-*`, `-status`, `-overage-status` | **Utilization** (0.0-1.0 of capacity _used_) plus a reset epoch. Anthropic publishes no absolute remaining count for subscription windows. | | API key | `anthropic-ratelimit-requests-remaining`/`-limit`, `anthropic-ratelimit-tokens-remaining`/`-limit` | Absolute remaining counts. | **NeuroLink additions** (`x-neurolink-*`) carry what only the proxy knows: | Header | Meaning | | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `x-neurolink-quota-source` | `live` (parsed from this response), `snapshot` (last known reading for the account), or `none` (no Anthropic account served it). Always present. | | `x-neurolink-account` / `-account-type` | Which account served the request, and whether it is `oauth` or `api_key`. | | `x-neurolink-served-by` | `anthropic`, or the fallback provider name when routing fell through. | | `x-neurolink-quota-session-left-pct` / `-weekly-left-pct` | Derived headroom, `(1 - utilization) × 100`. Omitted when `quota-source` is `none`. | | `x-neurolink-quota-session-resets-in` / `-weekly-resets-in` | Seconds until the window resets. | | `x-neurolink-quota-session-status` / `-weekly-status` / `-unified-status` | `allowed`, `throttled`, or `rejected`. | | `x-neurolink-account-cooling-until` / `-cooling-reason` | Set when the serving account is in a cooldown window. | | `x-neurolink-pool-available` / `-pool-cooling` / `-pool-best-session-left` | Account-pool headroom — how many accounts are usable and the best remaining capacity among them. | > **`quota-source` matters.** When a fallback provider serves the request, or Anthropic returns no quota headers, the proxy reports `none` and omits the headroom figures rather than echoing a stale snapshot. Treat `snapshot` as "last known", not "current". Account labels are frequently email addresses and are emitted as-is to the operator's own clients; they are stripped from borrowed responses and from borrowers' error messages. The proxy binds to `127.0.0.1` by default and refuses any other bind address unless an inbound token, the share gate or `--allow-unauthenticated` is configured — see [Inbound authentication](#inbound-authentication). **Consuming from the SDK.** The Anthropic provider parses these headers on every request in both auth modes and surfaces them on `result.limits` and `result.analytics.limits`, logs one line per request (escalating to WARN below 15% session headroom or on a `throttled`/`rejected` status), and sets `neurolink.claude.quota.*` span attributes alongside `gen_ai.usage.*`. This works without the proxy too — direct subscription traffic returns the same unified headers. ```typescript const result = await neurolink.generate({ prompt: "...", provider: "anthropic", }); console.log(result.limits?.rateLimit.sessionLeftPct); // e.g. 58 console.log(result.limits?.quotaSource); // "live" console.log(result.limits?.account); // set only when routed through the proxy ``` ### Translation mode (Claude to other provider) When model routing directs to a non-Anthropic provider: 1. Parse the Claude request using `parseClaudeRequest()` -- extracts prompt, system prompt, images, tools, thinking config, and conversation history. The thinking `type` field is handled adaptively: both `"enabled"` (fixed budget) and `"adaptive"` (auto budget, mapped to `thinkingLevel: "medium"`) are supported. 2. Call `neurolink.stream()` with the target provider and model. Tools and conversation messages from the original request are passed through (not disabled). 3. For streaming: use `ClaudeStreamSerializer` to emit Claude-compatible SSE events (`message_start`, `content_block_start`, `content_block_delta`, `content_block_stop`, `message_delta`, `message_stop`). 4. For non-streaming: collect all text from the stream and call `serializeClaudeResponse()` to build a Claude Messages API response. If the translated response model differs from the requested model, the proxy records that as a model-substitution metric (`proxy_model_substitution_total`) and adds the requested vs actual model attributes to the trace. ### Image references on translated requests Translation mode serves three request formats, and each carries images in its own slot: | Format | Endpoint | Image slot | | ------ | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | OpenAI | `POST /v1/chat/completions` | `image_url.url` of the latest user turn | | Gemini | `POST /v1beta/models/:generateContent`, `:streamGenerateContent` | `inlineData` of the final turn, only when that turn has the `user` role (`data`, `mimeType`); a request that ends with a `model` turn sends no images, and earlier turns contribute text only | | Claude | `POST /v1/messages` (routed or falling back to another provider) | `source` of an image block of the latest user turn (`url`, or `base64` `data` and `media_type`) | The SDK resolves an image string by itself (an `http(s)` URL is fetched, anything else naming an existing file is read from disk), which is right for a program naming its own files and wrong for a request that arrived over a socket. So the proxy resolves every reference first and hands the SDK nothing but images it checked: | Reference | What the proxy does | | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data:` URI | Decoded strictly and checked: the payload must be base64 and its bytes must be a recognised image (see below). It is forwarded as `data:;base64,`. The client's string length counts against the limits below. | | Claude `base64` source (`source.type: "base64"`) | Converted to a `data:;base64,` URI (`image/png` when `media_type` is absent) and then handled as one: the converted string's length counts against the limits below. | | Gemini `inlineData` raw base64 with an `image/*` `mimeType` | Wrapped into a `data:;base64,` URI (as standard, padded base64) and then handled as one. See below. | | `https://` URL | Downloaded by the proxy: redirects are refused, the resolved address must be public, and the size is capped. The downloaded bytes must be a recognised image too, or the URL is refused. | | `http://` URL | Refused. Nothing is fetched. | | Local path, `file://` or any other scheme | Refused. The file system is not touched, so a path that exists and one that does not get the same answer. | | Empty image slot | Refused, never skipped: see [Empty image slots](#empty-image-slots). | #### What counts as an image, and the type it is sent with An inline image is judged by its bytes, never by what the client called it. The proxy decodes the payload strictly (an alphabet, length or `=` padding that no decoder takes is refused; the URL-safe alphabet and missing padding are rewritten to padded standard base64) and reads the file signature from its first bytes. A recognised image is forwarded as `data:;base64,`, and the type comes from the bytes: a JPEG labelled `image/png`, `image/jpg` or even `application/octet-stream` reaches the provider as `image/jpeg`. A correction is logged at debug level, not warn. Header parameters (`data:image/png;charset=utf-8;base64,...`) are dropped. | Format | Types it is recognised as | What the provider receives | | ------------------------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | PNG, JPEG, WebP, GIF | `image/png`, `image/jpeg`, `image/webp`, `image/gif` | The same bytes under the type they have. Every vision provider takes them as they are. | | HEIC, HEIF | `image/heic`, `image/heif` | A PNG when the SDK can convert the file, otherwise the original bytes under the detected type. Google takes HEIC and HEIF as they are, so for Google the second outcome works; every other provider refuses it. | | AVIF, BMP, TIFF, ICO, JPEG 2000 | `image/avif`, `image/bmp`, `image/tiff`, `image/x-icon`, `image/jp2` | A PNG when the SDK can convert the file, otherwise the original bytes under the detected type, which no provider takes. | The proxy only recognises these formats by their signature; the conversion is the SDK's, and it is not tied to a provider: HEIC and HEIF are converted for Google as well. The SDK reads the file with `sharp` (an optional dependency; it covers TIFF and AVIF) and then with `ffmpeg`, the bundled build first and a system `ffmpeg` after it. BMP, ICO and JPEG 2000 need `ffmpeg`, and HEIC needs an `ffmpeg` that can decode HEVC, which in practice means a system one: the bundled build leaves HEVC out. When none of them can read the file (no decoder installed, a corrupt file, or one that takes longer than the conversion timeout), the SDK logs a warning and sends the original bytes with the detected type instead of failing, so the provider's own refusal is what the client sees. Install a full `ffmpeg` (or point `FFMPEG_PATH` at one) to make these formats work for providers that do not take them. Anything else is refused: text, a path, HTML, PDF, ZIP, a non-image ISO-BMFF file such as MP4, NUL bytes, a signature cut short (a PNG that stops after four bytes), an empty payload, and SVG. SVG is markup with no file signature, no provider takes it, and the proxy does not hand client markup to the SDK's rasteriser. The check reads the file signature; it does not decode the picture, so a body that is corrupt after a valid signature is the provider's to refuse. BMP and ICO are held to their next header field as well, so text that merely begins `BM` is not a bitmap. A request may carry at most 20 images, each at most 50 MB and all together at most 100 MB (the limits the agent routes use). A `data:` URI is charged its string length, as the client sent it, when the request is read; an `https://` image is measured as it downloads, against 50 MB and against what is left of the 100 MB. There is no allowed-directories setting: the proxy listens on loopback without credentials by default, and the share port admits any holder of a share token, so a path allow-list would still hand the operator's disk to every caller. Behind `HTTPS_PROXY` / `ALL_PROXY` the download goes through that proxy, which resolves the host name, so only the URL text is checked. #### Empty image slots An image slot that carries nothing is still an image slot. The proxy refuses it instead of leaving it out, so a request that names a picture and supplies none is never sent upstream as though no picture had been attached. Each format spells "no bytes" its own way, and the answer depends on whether the slot is a payload or a URL: | Format | Empty image slot | Answer | | ------ | ------------------------------------------------------------------------------------ | ------------------------- | | OpenAI | `image_url.url` empty or absent | `invalid_image_reference` | | OpenAI | A `data:` URI with no payload (`data:image/png;base64,`) | `invalid_image_data` | | Claude | A `base64` source whose `data` is empty or absent (with or without `media_type`) | `invalid_image_data` | | Claude | A `url` source whose `url` is empty or absent | `invalid_image_reference` | | Gemini | An `inlineData` with an `image/` `mimeType` whose `data` is empty or absent | `invalid_image_data` | Left out as before, because there is nothing to call an image by: a Gemini part with no `inlineData`, or one that declares no `image/` type and carries no `data`; and a Claude image block whose source is neither `base64` nor `url`. Only the images of the latest user turn are read, so an empty image in an earlier turn is not looked at. A refused reference answers `400` before anything is sent upstream or any stream starts, in the client's own error format, with one of these codes. The answer never echoes the reference, the data or any server path, and no fallback provider is tried because every one would refuse the same request. | Code | Meaning | | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `invalid_image_reference` | An unaccepted form: a local path, an `http://` URL, another scheme, an empty URL, or (Gemini) raw base64 that was never wrapped because its `mimeType` is missing, malformed or not an image, or its length or padding is impossible. | | `invalid_image_data` | A `data:` image, or an `https://` download, whose bytes are not a recognised image: not base64, empty (including a Claude `base64` source or a Gemini image `inlineData` with no `data`), too short to hold a complete recognised signature, text, a page, SVG, or any other format listed above as refused. A `data:` URI that is not `;base64` also. Only the leading signature is checked, so an image cut off after it is not refused here. | | `image_url_unfetchable` | An `https://` URL that could not be fetched safely: a private or non-public address, a redirect, an error status, or larger than the size limit while downloading. | | `image_input_too_large` | More than 20 images, a `data:` URI longer than 50 MB, or `data:` URIs together longer than 100 MB (the URI string as sent, not the decoded image). | | Format | Refusal body | | ------ | -------------------------------------------------------------------------------------------------------------------- | | OpenAI | `{"error": {"type": "invalid_request_error", "message": "...", "code": "invalid_image_reference"}}` | | Claude | `{"type": "error", "error": {"type": "invalid_request_error", "message": "...", "code": "invalid_image_reference"}}` | | Gemini | `{"error": {"code": 400, "status": "INVALID_ARGUMENT", "message": "...", "reason": "invalid_image_reference"}}` | Requests with a `claude-*` model on the passthrough path are forwarded to Anthropic as sent, so their image sources are fetched (or rejected) by Anthropic and the proxy resolves nothing. Gemini clients that follow Google's wire format send `inlineData.data` as raw base64 with the type in a sibling `inlineData.mimeType`, and the proxy accepts that form: when `mimeType` is an `image/` type (no space, comma or semicolon) and `data` is base64 in the standard or URL-safe alphabet, it is wrapped into `data:;base64,` before the checks above (a URL-safe alphabet or missing padding is rewritten to padded standard base64), so the limits count the wrapped string, 22 characters longer than `data` for `image/png`. The declared `mimeType` is then only a hint: the type the provider receives is the one the bytes have. Raw base64 whose `mimeType` is missing, malformed or not an image (audio and PDF parts are not translated) answers `400 invalid_image_reference`, and the answer does not echo the type or the data. So does raw base64 that no decoder would take: a length one character over a multiple of four (after any `=`), or `=` padding that is not the amount the length calls for. Such a value is not wrapped, so it never reaches the provider. A `data` value that is not base64 is judged as the reference it names: a `data:` URI is checked as above, an `https://` URL is downloaded, and a path is refused. A path that happens to be made only of base64 characters, with a length that passes the check above, is taken for bytes like any other base64, and since the bytes it decodes to are not an image it answers `400 invalid_image_data`. Either way the file system is not touched. ### OAuth cloaking For OAuth-authenticated requests, the proxy applies transformations to make requests appear as standard Claude CLI traffic: - **User-Agent**: `claude-cli/2.1.87 (external, sdk-cli)` - **Beta headers**: `oauth-2025-04-20`, `claude-code-20250219`, `interleaved-thinking-2025-05-14`, `context-management-2025-06-27`, `prompt-caching-scope-2026-01-05`, `advanced-tool-use-2025-11-20`, `effort-2025-11-24` - **Identity headers**: `x-app: cli`, `anthropic-dangerous-direct-browser-access: true` - **Stainless SDK headers**: `x-stainless-runtime`, `x-stainless-lang`, `x-stainless-os`, etc. - **Billing header**: Injected into the system prompt as a deterministic Claude-Code-shaped billing block so prompt caching stays stable across requests - **User ID**: `metadata.user_id` is a JSON string with `device_id`, `account_uuid`, and `session_id`, cached per account/token seed and reused across requests - **Trace linkage**: outbound requests include W3C trace headers and a stable `x-claude-code-session-id` when the proxy owns the request shape The `CloakingPipeline` supports three modes: | Mode | Behavior | | -------- | ------------------------------------------------ | | `auto` | Apply cloaking only for OAuth accounts (default) | | `always` | Apply cloaking for all accounts | | `never` | Skip all cloaking | ### Cloaking plugins The pipeline runs plugins in `order` field order: - **HeaderScrubber** -- Removes or modifies headers that reveal proxy usage - **SessionIdentity** -- Generates Claude-Code-shaped identity metadata with stable `device_id` and `account_uuid` - **SystemPromptInjector** -- Adds billing and agent block to system prompts - **TlsFingerprint** -- TLS fingerprint matching - **WordObfuscator** -- Obfuscates identifiable patterns ### Request logging The proxy writes four complementary log families under `~/.neurolink/logs/`: - `proxy-YYYY-MM-DD.jsonl` -- final request summaries used for request counts, status trends, token totals, and dashboard panels - `proxy-attempts-YYYY-MM-DD.jsonl` -- per-upstream-attempt diagnostics for retries, failover, and rate-limit debugging - `proxy-debug-YYYY-MM-DD.jsonl` -- redacted body-capture index rows with phase, headers, file path, and response metadata - `bodies/YYYY-MM-DD//*.json.gz` -- the corresponding redacted request and response body artifacts, stored compressed with `0o600` permissions Final request summaries include request ID, method, path, model, account label, response status, response time, token usage, and `traceId` / `spanId` for trace correlation. Debug body captures are also emitted to OTLP logs as `event.name=proxy.body_capture`. > **Redaction:** Sensitive headers and common JSON secret keys (`authorization`, `access_token`, `refresh_token`, `api_key`, etc.) are redacted before debug artifacts are written locally or emitted to OTLP. ### Log rotation Log files are automatically cleaned up on two triggers: - **At startup** -- deletes files older than 7 days, then trims remaining files if total size exceeds 500 MB (oldest first). - **Hourly** -- repeats the same cleanup during proxy runtime. This prevents unbounded log growth without requiring external cron jobs. ### Usage statistics In-memory per-account statistics track: - Final completed, successful, and failed request counts - Upstream attempts and failed attempts, including authentication retries, network failures, and retries that later recovered - Transient-throttle and exhausted-quota attempt counts - Current account cooling state Final request counters add up across accounts and match proxy-wide completed, success, and error totals. Attempt counters are intentionally separate because one final request can make several attempts or rotate accounts. Statistics reset on proxy restart. Access them via the `/status` endpoint or `neurolink proxy status`. ## Comparison with CLIProxyAPI | Feature | NeuroLink Proxy | CLIProxyAPI (Go) | | ----------------------- | --------------------------------- | -------------------- | | Language | TypeScript (Node.js) | Go | | Multi-account pooling | Yes (fill-first + failover) | Yes (round-robin) | | OAuth token refresh | 2-layer (pre-request + 401 retry) | Single refresh | | Multi-provider fallback | Yes (any NeuroLink provider) | No | | Model mapping/routing | Yes (YAML config) | No | | Anti-detection/cloaking | Plugin pipeline | Built-in | | SDK integration | Full NeuroLink SDK access | Standalone binary | | Config format | YAML/JSON with env vars | TOML | | Installation | `npm install @juspay/neurolink` | Standalone binary | | Claude Code integration | Auto-configures settings.json | Manual setup | | Streaming | SSE passthrough + bootstrap retry | SSE passthrough | | Token storage | TokenStore (multi-provider) | Single-provider file | ## Key Files | File | Purpose | | --------------------------------------------------------------------- | ------------------------------------------------------------------------ | | `src/cli/commands/proxy.ts` | CLI commands: start, status, telemetry, setup, install, uninstall | | `src/lib/server/routes/claudeProxyRoutes.ts` | Claude API route handlers (passthrough + translation) | | `src/lib/proxy/modelRouter.ts` | Model name resolution and fallback chain | | `src/lib/proxy/claudeFormat.ts` | Request parser, response serializer, SSE state machine | | `src/lib/proxy/oauthFetch.ts` | OAuth fetch wrapper with cloaking | | `src/lib/proxy/proxyConfig.ts` | YAML/JSON config loader with env var interpolation | | `src/lib/proxy/requestLogger.ts` | JSONL request logging, OTLP log emission, and debug body capture storage | | `src/lib/proxy/rawStreamCapture.ts` | Lossless raw stream capture for debugging streaming request/response IO | | `src/lib/proxy/usageStats.ts` | In-memory per-account statistics | | `src/lib/proxy/tokenRefresh.ts` | Shared token refresh helpers (needsRefresh, refreshToken, persistTokens) | | `src/lib/proxy/accountQuota.ts` | Quota header parsing (unified-5h, unified-7d) and persistence | | `src/lib/proxy/cloaking/index.ts` | CloakingPipeline orchestrator | | `src/lib/proxy/cloaking/types.ts` | Cloaking plugin interface and context types | | `src/lib/auth/tokenStore.ts` | Multi-provider OAuth token storage | | `src/lib/auth/anthropicOAuth.ts` | Anthropic OAuth 2.0 + PKCE flow | | `src/lib/auth/accountPool.ts` | Account pool management | | `src/cli/commands/auth.ts` | Auth CLI commands: login, logout, list, status, refresh, cleanup, enable | | `src/cli/factories/authCommandFactory.ts` | Auth command builder with subcommands | | `src/lib/types/subscriptionTypes.ts` | Subscription tier, auth, and routing types | | `scripts/observability/manage-local-openobserve.sh` | Local OpenObserve lifecycle helper for `proxy telemetry` | | `docs/assets/dashboards/neurolink-proxy-observability-dashboard.json` | Maintained dashboard source-of-truth | ## Observability The proxy ships a local observability stack (OpenObserve + OTEL collector) with a pre-built dashboard covering traffic, failures, latency, account routing, token usage, and cost. ### Quick start ```bash # Start OpenObserve + OTEL collector, import dashboard, wire up endpoint neurolink proxy telemetry setup # Then start the proxy as normal — telemetry flows automatically neurolink proxy start ``` `telemetry setup` writes `OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:` (default: `14318`, configurable via `NEUROLINK_OTLP_HTTP_PORT`) into `~/.neurolink/.env`. The proxy reads that file on every start, including when running as a launchd service. **Dashboard:** `http://localhost:5080` — login `root@example.com` / `Complexpass#123` (default credentials, change in `scripts/observability/proxy-observability.env`). ### Useful commands | Command | Purpose | | -------------------------------------------- | ---------------------------------------------- | | `neurolink proxy telemetry setup` | Start stack + import dashboard + wire endpoint | | `neurolink proxy telemetry start` | Start stack without re-importing dashboard | | `neurolink proxy telemetry stop` | Stop the local stack | | `neurolink proxy telemetry status` | Show health and endpoint URLs | | `neurolink proxy telemetry logs` | Tail OpenObserve and collector logs | | `neurolink proxy telemetry import-dashboard` | Re-import the dashboard definition | When working from a repo checkout, the `pnpm run proxy:observability:*` scripts are equivalent shortcuts. The maintained dashboard definition lives in `docs/assets/dashboards/neurolink-proxy-observability-dashboard.json`. See [Claude Proxy Observability](/docs/features/claude-proxy-observability) for a full guide to reading the dashboard. ## Troubleshooting ### Proxy won't start: "already running" The proxy detected a running instance. Check status and stop the existing one: ```bash neurolink proxy status # If the reported PID is stale, remove the state file: rm ~/.neurolink/proxy-state.json neurolink proxy start ``` ### Claude Code not connecting through proxy 1. Verify the proxy is running: `neurolink proxy status` 2. Check `~/.claude/settings.json` has `ANTHROPIC_BASE_URL` set 3. Restart Claude Code after starting the proxy ### Token refresh failures If you see `refresh failed` in the logs: ```bash # Manually refresh neurolink auth refresh anthropic # Or re-login neurolink auth login anthropic --method oauth ``` ### All accounts rate-limited Check cooldown status and wait for recovery: ```bash neurolink proxy status --format json # Look at fallbackChain and uptime ``` Add more accounts to the pool to increase throughput: ```bash neurolink auth login anthropic --method oauth --add --label extra ``` ### Config file not loading Verify the config file exists and is valid YAML: ```bash cat ~/.neurolink/proxy-config.yaml # Or specify explicitly: neurolink proxy start --config /path/to/config.yaml ``` Unresolved `${VAR}` references in the config indicate missing environment variables. The proxy warns about plaintext API keys in config files -- use `${ENV_VAR}` references instead. --- ## Planned Future Features Features explored during the CLIProxyAPI comparison analysis and deferred for future implementation. ### OpenAI-Compatible Endpoint (`/v1/chat/completions`) **Priority: High** | **Complexity: Medium** Add an OpenAI-compatible API endpoint so any tool that speaks the OpenAI format (Cursor, Continue, Aider, Open Interpreter, etc.) can route through the proxy to Claude accounts. - **What exists:** the NeuroLink SDK already translates between all providers through its own native provider layer. The Claude proxy (`claudeFormat.ts` + `claudeProxyRoutes.ts`) is the production template. - **What's needed:** - `openaiFormat.ts` — parse OpenAI requests, serialize OpenAI responses, streaming SSE state machine (mirror of `claudeFormat.ts`) - `openaiProxyRoutes.ts` — `POST /v1/chat/completions`, `GET /v1/models`, `POST /v1/embeddings` endpoints - Route registration in `src/lib/server/routes/index.ts` with `openaiProxy: true` - **Key format differences:** OpenAI uses `choices[].message.content` vs Claude's `content[].text`, `finish_reason` inline vs `stop_reason`, system messages in the messages array vs top-level `system` field - **Account pool:** Shares the same OAuth account pool as the Claude proxy — all traffic pools across accounts with fill-first routing ### TLS Fingerprint Spoofing **Priority: Medium** | **Complexity: High** Bypass Cloudflare TLS fingerprinting on Anthropic OAuth endpoints. CLIProxyAPI uses `refraction-networking/utls` with `tls.HelloChrome_Auto` to impersonate Chrome's TLS handshake. - **Current status:** Switching refresh endpoint from `console.anthropic.com` to `api.anthropic.com` (lighter Cloudflare) resolved most issues. Revisit only if Cloudflare blocks resurface. - **Node.js options:** - `curl-impersonate` bindings via native module - `tls-client` npm package - Subprocess to `curl-impersonate` for OAuth operations only - **Scope:** Only needed for token exchange and refresh calls, not API requests (those use proper headers already) ### Management Dashboard **Priority: Low** | **Complexity: Medium** Web-based UI for monitoring proxy status, account health, quota utilization, and request logs. - **Data sources:** `~/.neurolink/account-quotas.json` (live quota), `~/.neurolink/logs/proxy-*.jsonl` (request logs), `~/.neurolink/tokens.json` (account status) - **Possible approach:** Lightweight Hono route serving a static HTML dashboard, reading from existing files - **CLIProxyAPI pattern:** Uses a management API (`/v0/management/auth-files`) for remote status — could expose similar endpoints ### WebSocket Relay **Priority: Low** | **Complexity: High** WebSocket-based connections for real-time bidirectional communication. - **Use cases:** Live dashboard updates, browser-based clients, streaming multiplexing - **Current need:** None — no consumer exists today - **CLIProxyAPI pattern:** Uses WebSocket for dynamically connecting providers (e.g., Gemini via WebSocket). Only relevant if we add browser-based provider injection. ### Hot-Reload of Config Files **Implemented** - **Credentials:** Accounts are loaded per request, and runtime state resets when credentials change. - **Routing config:** The config and proxy env files are polled with debouncing and SHA256 effective-config detection. Model mappings, fallback chain, passthrough models, strategy, primary account, account allowlist, and quota routing controls apply to the next request without a restart. - **Failure behavior:** Parse, validation, missing-file, and primary/allowlist conflicts leave the last-known-good generation active. `/status` and `neurolink proxy status` report the generation and last rejection. - **Manual trigger:** Send `SIGHUP` to request an immediate serialized reload. File watching remains the normal path. ### Quota-Aware Routing **Priority: Medium** | **Complexity: Low** Use captured quota data (`account-quotas.json`) to make smarter routing decisions. - **Current behavior:** Fill-first — exhausts one account before moving to the next on 429/401 - **Enhancement:** Check `sessionUsed` / `weeklyUsed` before routing. If the primary account is above the `fallbackPercentage` threshold (50%), proactively switch to the next account before hitting a hard 429 - **Data available:** All quota headers are already captured and stored per-account ### Per-Model Account Restrictions **Priority: Low** | **Complexity: Low** Allow configuring which accounts can use which models. - **Use case:** Account A has Max subscription (can use Opus), Account B has Pro (Sonnet/Haiku only). Routing Opus requests to Account B wastes a round-trip on a guaranteed 403. - **CLIProxyAPI pattern:** Per-account `excluded-models` list with wildcard matching - **Implementation:** Add `excludedModels?: string[]` to account config, filter during account selection --- ## Claude Subscription Testing Guide # Claude Subscription Testing Guide This document provides comprehensive testing commands and examples for the Claude subscription feature in NeuroLink, covering API key authentication, OAuth authentication for Pro/Max subscribers, subscription tier validation, and beta features. ## 1. Prerequisites ### Environment Setup Before testing, ensure you have the required environment configured: ```bash # Navigate to project directory cd /path/to/neurolink # Install dependencies pnpm install # Build the project (SDK + CLI) pnpm run build # Or build CLI only for faster testing pnpm run build:cli ``` ### Required API Keys Depending on your testing scenario, you will need one of the following: | Authentication Method | Required Credential | Where to Get | | --------------------- | ------------------- | -------------------------------------------------------------------- | | API Key | `ANTHROPIC_API_KEY` | [console.anthropic.com](https://console.anthropic.com/settings/keys) | | OAuth (Pro/Max) | Claude subscription | [claude.ai](https://claude.ai) | ### Build Commands Reference ```bash # Full build (SDK + CLI) pnpm run build # CLI only (faster for testing CLI commands) pnpm run build:cli # Complete build with validation pnpm run build:complete # Type checking pnpm run check # Lint and format pnpm run lint && pnpm run format ``` ### OAuth Authentication (Pro/Max) #### Interactive Login ```bash # Start OAuth authentication flow pnpm run cli -- auth login anthropic # This will: # 1. Open your browser to Anthropic's OAuth page # 2. Request authorization for NeuroLink # 3. Store tokens securely after authorization ``` #### Explicit OAuth Method ```bash # Explicitly use OAuth method pnpm run cli -- auth login anthropic --method oauth # For non-interactive environments, API key method pnpm run cli -- auth login anthropic --method api-key ``` #### Check Authentication Status ```bash # Check status for Anthropic pnpm run cli -- auth status anthropic # Expected output for OAuth: # Anthropic [Authenticated] # Method: oauth # Subscription: pro # Token Expires: 2026-02-10T12:00:00 # Refresh Token: Available # Expected output for API key: # Anthropic [Authenticated] # Method: api-key ``` #### Token Management ```bash # Refresh OAuth tokens (usually automatic) pnpm run cli -- auth refresh anthropic # Logout / clear credentials pnpm run cli -- auth logout anthropic ``` --- ### Subscription Tiers The subscription tier affects which models are available and rate limits: | Tier | Models Available | Default Model | | -------- | --------------------------- | ------------------------- | | `free` | Haiku only | claude-3-5-haiku-20241022 | | `pro` | Haiku + Sonnet | claude-sonnet-4-20250514 | | `max` | All models (including Opus) | claude-opus-4-20250514 | | `max_5` | All models (5x usage) | claude-opus-4-20250514 | | `max_20` | All models (20x usage) | claude-opus-4-20250514 | | `api` | All models | claude-sonnet-4-20250514 | #### Testing with Subscription Tiers ```bash # Set subscription tier via environment variable export ANTHROPIC_SUBSCRIPTION_TIER="pro" # Free tier (Haiku only) export ANTHROPIC_SUBSCRIPTION_TIER="free" pnpm run cli -- generate "Hello" --provider anthropic # Uses: claude-3-5-haiku-20241022 # Pro tier (Haiku + Sonnet) export ANTHROPIC_SUBSCRIPTION_TIER="pro" pnpm run cli -- generate "Hello" --provider anthropic --model claude-sonnet-4-20250514 # Max tier (all models including Opus) export ANTHROPIC_SUBSCRIPTION_TIER="max" pnpm run cli -- generate "Complex task" --provider anthropic --model claude-opus-4-20250514 # API tier (direct API access - all models) export ANTHROPIC_SUBSCRIPTION_TIER="api" pnpm run cli -- generate "Hello" --provider anthropic --model claude-opus-4-20250514 ``` #### Model Access Validation ```bash # Attempting to use a model not available for tier will fall back to recommended model export ANTHROPIC_SUBSCRIPTION_TIER="free" pnpm run cli -- generate "Hello" --provider anthropic --model claude-opus-4-20250514 # Warning: Model not available for subscription tier, using recommended model # Uses: claude-3-5-haiku-20241022 ``` --- ### Beta Features #### Extended Thinking Mode Extended thinking is supported by Claude Sonnet 4 and Claude Opus 4: ```bash # Enable extended thinking with thinking level pnpm run cli -- generate "Solve this complex mathematical proof..." \ --provider anthropic \ --model claude-sonnet-4-20250514 \ --thinking-level high # Thinking levels: minimal, low, medium, high pnpm run cli -- generate "Analyze this code for security issues" \ --provider anthropic \ --model claude-opus-4-20250514 \ --thinking-level medium ``` #### Streaming with Beta Features ```bash # Stream response with extended thinking pnpm run cli -- stream "Explain the theory of relativity step by step" \ --provider anthropic \ --model claude-sonnet-4-20250514 \ --thinking-level high ``` --- ## 3. SDK Testing ### Basic API Key Authentication ```typescript // Environment variable: ANTHROPIC_API_KEY const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Hello, Claude!" }, provider: "anthropic", model: "claude-3-5-sonnet-20241022", }); console.log(result.content); console.log("Input tokens:", result.usage?.inputTokens); console.log("Output tokens:", result.usage?.outputTokens); ``` ### OAuth Token Authentication ```typescript // Import from the main package entry point // Or when working within the codebase, use relative paths: // import { AnthropicProvider } from "../lib/providers/anthropic.js"; // Using OAuth token from environment // Set ANTHROPIC_OAUTH_TOKEN as JSON: {"accessToken": "...", "refreshToken": "..."} // Or as plain access token string // You can also instantiate the provider directly with config: // Note: AnthropicProvider is not a separate package export. // Import it via relative path within the codebase. const provider = new AnthropicProvider("claude-sonnet-4-20250514", undefined, { authMethod: "oauth", oauthToken: { accessToken: "your-oauth-access-token", refreshToken: "your-refresh-token", expiresAt: Date.now() + 3600000, // 1 hour from now (Unix milliseconds) }, subscriptionTier: "pro", }); // Check authentication method console.log("Auth method:", provider.getAuthMethod()); // "oauth" console.log("Subscription tier:", provider.getSubscriptionTier()); // "pro" ``` **Important:** The `expiresAt` field in `OAuthToken` uses Unix milliseconds (i.e., `Date.now()` scale), not Unix seconds. For example, 1 hour from now is `Date.now() + 3600000`. ### Subscription Tier Configuration ```typescript // Import from the codebase using relative paths (not package sub-path exports) isModelAvailableForTier, getDefaultModelForTier, getAvailableModelsForTier, } from "../../src/lib/models/anthropicModels.js"; // Check model availability for a tier const canUseOpus = isModelAvailableForTier("claude-opus-4-20250514", "pro"); console.log("Pro can use Opus:", canUseOpus); // false const canUseOpusMax = isModelAvailableForTier("claude-opus-4-20250514", "max"); console.log("Max can use Opus:", canUseOpusMax); // true // Get default model for tier const defaultFree = getDefaultModelForTier("free"); console.log("Free default:", defaultFree); // "claude-3-5-haiku-20241022" const defaultMax = getDefaultModelForTier("max"); console.log("Max default:", defaultMax); // "claude-opus-4-20250514" // Get all available models for a tier const proModels = getAvailableModelsForTier("pro"); console.log("Pro tier models:", proModels); // ["claude-3-haiku-20240307", "claude-3-5-haiku-20241022", // "claude-3-5-sonnet-20241022", "claude-3-5-sonnet-v2-20241022", // "claude-sonnet-4-20250514"] ``` ### Beta Features in SDK ```typescript // Create provider with beta features enabled (default) const provider = new AnthropicProvider("claude-opus-4-20250514", undefined, { enableBetaFeatures: true, subscriptionTier: "max", }); // Check if beta features are enabled console.log("Beta features:", provider.areBetaFeaturesEnabled()); // true // Get model capabilities (alias for getModelMetadata) const capabilities = provider.getModelCapabilities(); console.log( "Supports extended thinking:", capabilities?.supportsExtendedThinking, ); console.log("Supports vision:", capabilities?.supportsVision); // Use extended thinking via NeuroLink SDK const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Solve this complex problem with reasoning..." }, provider: "anthropic", model: "claude-opus-4-20250514", thinkingLevel: "high", }); console.log(result.content); ``` ### Model Access Validation in SDK ```typescript // Provider automatically validates model access based on tier const provider = new AnthropicProvider("claude-opus-4-20250514", undefined, { subscriptionTier: "pro", // Pro tier }); // This returns false - Opus not available for Pro const hasAccess = provider.validateModelAccess("claude-opus-4-20250514"); console.log("Pro has Opus access:", hasAccess); // false // Sonnet is available for Pro const hasSonnetAccess = provider.validateModelAccess( "claude-sonnet-4-20250514", ); console.log("Pro has Sonnet access:", hasSonnetAccess); // true ``` ### Usage Tracking ```typescript const provider = new AnthropicProvider(); // After making requests, check usage info const usage = provider.getUsageInfo(); if (usage) { console.log("Messages used:", usage.messagesUsed); console.log("Tokens used:", usage.tokensUsed); console.log("Input tokens:", usage.inputTokensUsed); console.log("Output tokens:", usage.outputTokensUsed); console.log("Rate limited:", usage.isRateLimited); console.log("Message quota %:", usage.messageQuotaPercent); console.log("Token quota %:", usage.tokenQuotaPercent); } // Check rate limit metadata from last response const metadata = provider.getLastResponseMetadata(); if (metadata?.rateLimit) { console.log("Requests remaining:", metadata.rateLimit.requestsRemaining); console.log("Tokens remaining:", metadata.rateLimit.tokensRemaining); } ``` --- ## 4. Credential & Subscription Tests ### Running the Tests Anthropic subscription scenarios — OAuth, API key, tier validation — are exercised by the `test:credentials` suite: ```bash # Run the credentials suite (includes Claude subscription scenarios) pnpm run test:credentials # Or run the underlying tsx file directly with extra logging DEBUG=1 pnpm exec tsx test/continuous-test-suite-credentials.ts ``` > **Note:** NeuroLink does not use vitest; all tests are tsx scripts orchestrated via the `continuous-test-suite-*.ts` files. There is no `test:coverage` / `test:integration` / `test:subscription` script — see [`test/TESTING_SCRIPTS.md`](https://github.com/juspay/neurolink/blob/main/test/TESTING_SCRIPTS.md) for the full list of available suites. ### Test Coverage The credentials suite (`test/continuous-test-suite-credentials.ts`) covers the scenarios below. The numbered list is illustrative of the OAuth/API-key/tier dimensions tested; consult the source for the authoritative inventory. #### 1. OAuth Flow Tests (21 tests) Tests the `AnthropicOAuth` class from `src/lib/auth/anthropicOAuth.ts`. | Sub-describe | Tests | What It Covers | | ---------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------- | | OAuth URL Generation with PKCE | 5 | Auth URL parameters, custom scopes, PKCE code challenge inclusion, unique state for CSRF, additional params | | Code Verifier/Challenge Generation | 2 | Cryptographic verifier uniqueness and length, S256 challenge generation and base64url encoding | | Token Exchange (Mocked HTTP) | 5 | Code-for-token exchange, error on failed exchange, empty code rejection, client secret inclusion, PKCE verify | | Token Refresh (Mocked HTTP) | 3 | Refresh token exchange, missing refresh token error, server error handling | | Token Validation | 4 | Valid token with details, expired token detection, empty token rejection, expiration buffer checking | Mock pattern: `vi.mock("open", ...)` for browser, global `fetch` replaced with `vi.fn()`. #### 2. Token Storage Tests (18 tests) Tests two storage implementations: - `InMemoryTokenStorage` from `src/lib/mcp/auth/tokenStorage.ts` (the MCP OAuth token storage) - `TokenStore` from `src/lib/auth/tokenStore.ts` (file-based multi-provider token store) | Sub-describe | Tests | What It Covers | | ------------------------------- | ----- | --------------------------------------------------------------------------------------------- | | Saving Tokens to Storage | 3 | Save to in-memory storage, update existing, handle multiple providers | | Loading Tokens from Storage | 4 | Null for non-existent, complete object retrieval, hasTokens check, list server IDs | | Clearing Tokens | 3 | Clear specific provider, clear all, handle non-existent gracefully | | Token Expiry Detection | 5 | Expired tokens, valid tokens, buffer time, tokens without expiration, calculateExpiresAt | | TokenStore (File-based Storage) | 4 | Default path (`.neurolink/tokens.json`), custom path, validation before save, token refresher | Mock pattern: `vi.mock("fs/promises", ...)` for file operations. **Note:** The `TokenStore` stores tokens at `~/.neurolink/tokens.json` (not `~/.config/neurolink/`). The `expiresAt` values throughout the codebase use Unix milliseconds (`Date.now()` scale). #### 3. Model Tier Access Tests (19 tests) Tests functions from `src/lib/models/anthropicModels.ts`. | Sub-describe | Tests | What It Covers | | ------------------------------- | ----- | -------------------------------------------------------------------------------------------- | | isModelAvailableForTier | 6 | Free (Haiku only), Pro (Haiku+Sonnet), Max (all), max_5/max_20 (all), API (all), invalid IDs | | getAvailableModelsForTier | 4 | Free returns 2 Haiku models, Pro includes Sonnet, Max returns all 7+, API matches Max | | getDefaultModelForTier | 4 | Free=Haiku, Pro=Sonnet 4, Max/max_5/max_20=Opus 4, API=Sonnet 4 | | Model Metadata and Capabilities | 4 | Metadata for Opus 4 and Haiku, undefined for unknown, minimum tier, validateModelAccess | | Tier Comparison | 1 | compareTiers ordering (free **Superseded — kept as a record of what this suite once covered.** > The mock-based vitest suite described below no longer exists. It mocked > `@ai-sdk/anthropic`, which is not a dependency any more, and it targeted > `src/lib/providers/anthropic.ts`, a path that no longer exists — the Anthropic > provider is now native, at `src/lib/providers/anthropic/client.ts`. Per > `CLAUDE.md` rule 15 the suites in `test/` are end-to-end: they construct > `NeuroLink` and call `generate()` / `stream()`, or drive the built CLI. Treat > the mock patterns in this section as history, not as a pattern to copy. Tested the `AnthropicProvider` class, then at `src/lib/providers/anthropic.ts`. | Sub-describe | Tests | What It Covers | | ---------------------------------------- | ----- | ----------------------------------------------------------------------------------- | | Provider Initialization with API Key | 4 | Valid API key init, default model, custom model, default "api" tier | | Provider Initialization with OAuth Token | 4 | JSON token parsing from env, plain string token, tier from scopes, default pro tier | | Beta Headers Inclusion | 2 | Beta header content verification, getAuthHeaders with beta features | | Model Access Validation | 1 | API tier has access to all models | | Backward Compatibility | 2 | Works with existing ANTHROPIC_API_KEY, isAvailable check | | Error Handling | 4 | Auth errors, rate limit errors, network errors (ECONNREFUSED), server errors (500) | | Usage Tracking | 1 | Initializes with zeroed usage info | Mock pattern (historical): `vi.mock("@ai-sdk/anthropic", ...)`, `vi.mock("../../src/lib/utils/providerConfig.js", ...)`, `vi.mock("fs", ...)` (sync fs operations mocked to prevent reading real `~/.neurolink/anthropic-credentials.json`). #### 5. Configuration Tests (11 tests) Tests environment variable detection, config loading, and credential handling. | Sub-describe | Tests | What It Covers | | ------------------------------ | ----- | ------------------------------------------------------------------------------------------ | | Environment Variable Detection | 7 | ANTHROPIC_API_KEY, ANTHROPIC_OAUTH_CLIENT_ID, ANTHROPIC_SUBSCRIPTION_TIER, ANTHROPIC_MODEL | | Config File Loading | 1 | createAnthropicOAuthConfig structure | | Default Values | 3 | OAuth endpoints (claude.ai/oauth/authorize), default scopes, default redirect URI | | Credential Masking | 2 | API key masking preserving prefix/suffix, short credential handling | #### 6. Rate Limit Header Parsing Tests (4 tests) Tests parsing of Anthropic rate limit response headers. | Sub-describe | Tests | What It Covers | | ------------------------ | ----- | ---------------------------------------------------------- | | Parse Rate Limit Headers | 4 | All headers, missing headers, retry-after, partial headers | The tests construct `Headers` objects manually and parse `anthropic-ratelimit-*` headers. #### 7. CLI Auth Command Tests (5 tests) Tests CLI-level authentication validation and status detection. | Sub-describe | Tests | What It Covers | | --------------------- | ----- | ---------------------------------------------------------------------- | | API Key Validation | 2 | Valid API key format (sk-ant- prefix, length > 20), invalid key format | | Auth Status Detection | 3 | API key presence, API key absence, model configuration | | Command Options | 2 | check-only mode, non-interactive mode | ### Writing New Tests When adding new tests to this file, follow these patterns from the existing test suite: #### Dynamic Imports All module imports inside test cases use dynamic `await import(...)` to get fresh module instances after environment variable changes: ```typescript it("should do something", async () => { process.env.ANTHROPIC_API_KEY = "sk-ant-test-key-12345678901234567890"; const { AnthropicProvider } = await import("../../src/lib/providers/anthropic.js"); const provider = new AnthropicProvider(); expect(provider).toBeDefined(); }); ``` #### Environment Variable Management Each describe block saves/restores `process.env`: ```typescript describe("My Tests", () => { let originalEnv: NodeJS.ProcessEnv; beforeEach(() => { originalEnv = { ...process.env }; vi.clearAllMocks(); }); afterEach(() => { process.env = originalEnv; vi.restoreAllMocks(); }); // tests here... }); ``` Provider Integration Tests also call `vi.resetModules()` in `beforeEach` to ensure fresh module loading. #### Mocked HTTP (fetch) For testing OAuth token exchange and refresh: ```typescript let mockFetch: Mock; beforeEach(() => { mockFetch = vi.fn(); global.fetch = mockFetch as unknown as typeof fetch; }); it("should exchange code for tokens", async () => { mockFetch.mockResolvedValueOnce({ ok: true, json: async () => ({ access_token: "test-access-token", token_type: "Bearer", expires_in: 3600, refresh_token: "test-refresh-token", }), } as Response); // ... test code }); ``` #### Global Mocks (top of file) The test file defines these top-level mocks that apply to all tests: ```typescript // Browser opening vi.mock("open", () => ({ default: vi.fn().mockResolvedValue(undefined), })); // Logger (silences output) vi.mock("../../src/lib/utils/logger.js", () => ({ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), always: vi.fn(), }, })); // Async fs operations vi.mock("fs/promises", () => ({ readFile: vi.fn(), writeFile: vi.fn(), mkdir: vi.fn(), unlink: vi.fn(), access: vi.fn(), chmod: vi.fn(), rename: vi.fn(), })); // Sync fs operations (prevents reading real credentials from disk) vi.mock("fs", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, existsSync: vi.fn(() => false), readFileSync: vi.fn(() => { throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT", }); }), }; }); // Proxy fetch vi.mock("../../src/lib/proxy/proxyFetch.js", () => ({ createProxyFetch: vi.fn(() => fetch), })); // Anthropic SDK vi.mock("@ai-sdk/anthropic", () => ({ createAnthropic: vi.fn(() => vi.fn(() => ({ modelName: "claude-3-5-sonnet-20241022", provider: "anthropic", })), ), })); // Provider config vi.mock("../../src/lib/utils/providerConfig.js", () => ({ validateApiKey: vi.fn(() => "sk-ant-test-key-valid"), createAnthropicConfig: vi.fn(() => ({ envVarName: "ANTHROPIC_API_KEY", providerName: "Anthropic", })), getProviderModel: vi.fn( (_envVar: string, defaultModel: string) => defaultModel, ), })); ``` ### Auto-Refresh Testing The `AnthropicProvider.refreshAuthIfNeeded()` method handles automatic OAuth token refresh. Key behaviors tested through the provider integration tests: - **Token expiry uses milliseconds:** `expiresAt` is compared against `Date.now()` (both in milliseconds). - **5-minute buffer:** Tokens are refreshed when they expire within 5 minutes (`5 * 60 * 1000` ms). - **In-place mutation:** The provider mutates the `oauthToken` object in-place so the `createOAuthFetch` closure picks up the new `accessToken` automatically. - **Disk persistence:** After refreshing, the new token is written to `~/.neurolink/anthropic-credentials.json`. - **Called before every request:** Both `generate()` and `executeStream()` call `refreshAuthIfNeeded()` before making API calls. The refresh flow in the provider calls `ANTHROPIC_TOKEN_URL` (`https://console.anthropic.com/v1/oauth/token`) with `grant_type=refresh_token`, `client_id`, and the refresh token. --- ## 5. Environment Variables Reference ### Authentication Variables | Variable | Description | Required | Example | | ----------------------- | ------------------------------- | --------- | ----------------------- | | `ANTHROPIC_API_KEY` | API key for API key auth | Yes\* | `sk-ant-api03-...` | | `ANTHROPIC_OAUTH_TOKEN` | OAuth token (JSON or string) | For OAuth | `{"accessToken":"..."}` | | `CLAUDE_OAUTH_TOKEN` | Alternative OAuth token env var | For OAuth | `access-token-string` | \*Required for API key authentication only. ### Configuration Variables | Variable | Description | Default | Example | | ----------------------------- | -------------------- | ---------------------------- | ---------------------------------------------- | | `ANTHROPIC_MODEL` | Default model to use | `claude-3-5-sonnet-20241022` | `claude-opus-4-20250514` | | `ANTHROPIC_SUBSCRIPTION_TIER` | Subscription tier | Auto-detected | `free`, `pro`, `max`, `max_5`, `max_20`, `api` | ### OAuth Configuration Variables | Variable | Description | Required | Example | | ------------------------------- | ------------------- | --------- | -------------------------------- | | `ANTHROPIC_OAUTH_CLIENT_ID` | OAuth client ID | For OAuth | `your-client-id` | | `ANTHROPIC_OAUTH_CLIENT_SECRET` | OAuth client secret | Optional | `your-secret` | | `ANTHROPIC_OAUTH_REDIRECT_URI` | OAuth redirect URI | Optional | `http://localhost:3000/callback` | ### Debug Variables | Variable | Description | Values | | --------------------- | ----------------- | -------------------------------- | | `NEUROLINK_DEBUG` | Enable debug mode | `true`, `false` | | `NEUROLINK_LOG_LEVEL` | Logging verbosity | `debug`, `info`, `warn`, `error` | ### Example .env File ```bash # API Key Authentication ANTHROPIC_API_KEY=sk-ant-api03-your-key-here # Optional Configuration ANTHROPIC_MODEL=claude-3-5-sonnet-20241022 ANTHROPIC_SUBSCRIPTION_TIER=api # Debugging NEUROLINK_DEBUG=true NEUROLINK_LOG_LEVEL=debug ``` --- ## 6. Model Availability by Tier ### Complete Model Matrix These are the models defined in the `AnthropicModel` enum in `src/lib/models/anthropicModels.ts`: | Model | ID | Free | Pro | Max | API | Extended Thinking | | -------------------- | ------------------------------- | ---- | --- | --- | --- | ----------------- | | Claude 3 Haiku | `claude-3-haiku-20240307` | Yes | Yes | Yes | Yes | No | | Claude 3.5 Haiku | `claude-3-5-haiku-20241022` | Yes | Yes | Yes | Yes | No | | Claude 3.5 Sonnet | `claude-3-5-sonnet-20241022` | No | Yes | Yes | Yes | No | | Claude 3.5 Sonnet V2 | `claude-3-5-sonnet-v2-20241022` | No | Yes | Yes | Yes | No | | Claude Sonnet 4 | `claude-sonnet-4-20250514` | No | Yes | Yes | Yes | Yes | | Claude 3 Opus | `claude-3-opus-20240229` | No | No | Yes | Yes | No | | Claude Opus 4 | `claude-opus-4-20250514` | No | No | Yes | Yes | Yes | **Note:** The `AnthropicModels` enum in `src/lib/constants/enums.ts` contains additional models (Claude 4.5 series, Claude 4.1, Claude 3.7 Sonnet) used by the main provider registry. The tier access model definitions in `src/lib/models/anthropicModels.ts` use a separate `AnthropicModel` enum. ### Default Models by Tier | Tier | Default Model | Reason | | ------- | --------------------------- | ----------------------------- | | Free | `claude-3-5-haiku-20241022` | Only Haiku available | | Pro | `claude-sonnet-4-20250514` | Best balance for Pro users | | Max | `claude-opus-4-20250514` | Full flagship access | | Max 5x | `claude-opus-4-20250514` | Same as Max | | Max 20x | `claude-opus-4-20250514` | Same as Max | | API | `claude-sonnet-4-20250514` | Best cost/performance balance | ### Beta Feature Headers The `AnthropicBetaFeature` enum (singular) in `src/lib/constants/enums.ts` defines: | Enum Value | Header Value | | ------------------------ | ---------------------------------------- | | `CLAUDE_CODE` | `claude-code-20250219` | | `INTERLEAVED_THINKING` | `interleaved-thinking-2025-05-14` | | `FINE_GRAINED_STREAMING` | `fine-grained-tool-streaming-2025-05-14` | The `AnthropicBetaFeatures` type (plural) in `src/lib/types/subscriptionTypes.ts` is a separate configuration interface with boolean flags for beta features like `computerUse`, `extendedThinking`, `promptCaching`, etc. ### Feature Availability | Feature | Free | Pro | Max | API | | ----------------- | ------- | --- | ------- | --- | | Basic Chat | Yes | Yes | Yes | Yes | | Vision/Images | Yes | Yes | Yes | Yes | | Tool Use | Limited | Yes | Yes | Yes | | Extended Thinking | No | Yes | Yes | Yes | | 200K Context | No | Yes | Yes | Yes | | Priority Access | No | Yes | Highest | N/A | | Streaming | Yes | Yes | Yes | Yes | --- ## 7. Troubleshooting ### Common Issues and Solutions #### Issue: "Invalid API key provided" **Symptoms:** ``` Error: Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable. ``` **Solutions:** ```bash # Verify API key format (should start with sk-ant-) echo $ANTHROPIC_API_KEY | head -c 10 # Expected: sk-ant-api # Check for whitespace echo "$ANTHROPIC_API_KEY" | cat -A # Look for trailing spaces or newlines # Re-export with fresh key export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here" ``` #### Issue: "OAuth token expired" **Symptoms:** ``` Error: OAuth token expired and no refresh token available. Please re-authenticate. ``` **Solutions:** ```bash # Try refreshing the token pnpm run cli -- auth refresh anthropic # If refresh fails, re-authenticate pnpm run cli -- auth login anthropic --method oauth ``` #### Issue: "Model not available for subscription tier" **Symptoms:** ``` Warning: Model not available for subscription tier, using recommended model ``` **Solutions:** ```bash # Check current subscription tier echo $ANTHROPIC_SUBSCRIPTION_TIER # Use a model available for your tier # Free tier: use Haiku models pnpm run cli -- generate "Hello" --provider anthropic --model claude-3-5-haiku-20241022 # Or upgrade your subscription tier export ANTHROPIC_SUBSCRIPTION_TIER="max" ``` #### Issue: "Rate limit exceeded" **Symptoms:** ``` Error: Anthropic rate limit exceeded. Please try again later. ``` **Solutions:** ```bash # Check rate limit status pnpm run cli -- auth status anthropic # Wait for rate limit reset (usually shown in error message) # Or upgrade to higher tier for increased limits ``` #### Issue: "OAuth callback never completes" **Solutions:** 1. Check browser extensions that might block redirects 2. Verify firewall allows localhost connections on the callback port (default: 8787) 3. Try a different browser 4. Check if the port is in use: `lsof -i :8787` ### Debug Mode Enable debug logging for detailed troubleshooting: ```bash # Enable debug mode export NEUROLINK_DEBUG=true export NEUROLINK_LOG_LEVEL=debug # Run command with debug output pnpm run cli -- generate "Hello" --provider anthropic # Debug output includes: # - Authentication method detection # - Model selection logic # - API request details # - Rate limit information ``` ### Validating Environment ```bash # Full environment validation pnpm run env:validate # Check specific configuration pnpm run cli -- auth status anthropic # Verify build is current pnpm run build:cli && pnpm run cli -- --version ``` ### Test Connection ```bash # Simple connectivity test pnpm run cli -- generate "ping" --provider anthropic --max-tokens 10 # Expected: Short response confirming connection works ``` --- ## 8. Key Source Files | File | Purpose | | ------------------------------------------- | ----------------------------------------------------------------------------- | | `test/continuous-test-suite-credentials.ts` | Credentials and subscription test suite (run via `pnpm run test:credentials`) | | `src/lib/providers/anthropic.ts` | AnthropicProvider with OAuth, tier, beta support | | `src/lib/auth/anthropicOAuth.ts` | AnthropicOAuth class, PKCE, token exchange/refresh | | `src/lib/auth/tokenStore.ts` | TokenStore class, file-based multi-provider storage | | `src/lib/mcp/auth/tokenStorage.ts` | InMemoryTokenStorage, isTokenExpired, calculateExpiresAt | | `src/lib/types/subscription.ts` | Type definitions (OAuthToken, ClaudeSubscriptionTier, etc.) | | `src/lib/models/anthropicModels.ts` | AnthropicModel enum, tier access, model metadata | | `src/lib/constants/enums.ts` | AnthropicModels enum, AnthropicBetaFeature enum | --- ## See Also - [Claude Subscription Support Overview](/docs/features/claude-subscription) - [Provider Setup Guide](/docs/getting-started/providers/anthropic) --- ## Claude Subscription Support # Claude Subscription Support NeuroLink provides flexible access to Anthropic's Claude models through multiple subscription tiers and authentication methods. This guide covers setup, configuration, and best practices for each tier. ## Overview Claude is available through different subscription tiers, each offering varying levels of access, rate limits, and model availability: | Tier | Access Method | Rate Limits | Best For | | -------- | ----------------- | ---------------- | --------------------------------------- | | **Free** | claude.ai account | Limited messages | Exploration, personal use | | **Pro** | OAuth + claude.ai | 5x Free tier | Professional use, higher volume | | **Max** | OAuth + claude.ai | Unlimited | Heavy production, no rate limit worries | | **API** | API Key | Pay-per-token | Production systems, programmatic access | ### Subscription Tiers The `ClaudeSubscriptionTier` type (defined in `src/lib/types/subscriptionTypes.ts`) supports these values: - `"free"` -- Free tier with basic access and limited usage - `"pro"` -- Professional tier with higher limits and priority access - `"max"` -- Maximum tier with highest limits (alias for max_5) - `"max_5"` -- Max 5x usage tier - `"max_20"` -- Max 20x usage tier - `"api"` -- Direct API access tier for developers and enterprises **Free Tier:** - Basic access to Claude via claude.ai - Limited message quota per day - Access to Claude 3 Haiku and Claude 3.5 Haiku models only - Good for exploring Claude's capabilities **Pro Subscription ($20/month):** - Higher usage limits than Free tier - Priority access during peak times - Access to Haiku and Sonnet model families (Claude 3 Haiku, Claude 3.5 Haiku, Claude 3.5 Sonnet, Claude 3.5 Sonnet V2, Claude Sonnet 4) - No access to Opus models **Max Subscription ($100/month):** - Highest usage limits - All models available, including Opus - Available in Max, Max 5x, and Max 20x usage multiplier variants **API Access (Pay-per-use):** - Direct programmatic access - No monthly subscription required - Pay only for tokens used - Full model selection (all models) - Production-ready SLAs ## Quick Start ```bash # 1. Set your Anthropic API key export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here" # 2. Run a prompt with the Anthropic provider npx @juspay/neurolink generate "Hello, Claude" --provider anthropic ``` For Claude Pro/Max subscribers who want to use their subscription quota instead of API billing: ```bash # Authenticate via OAuth (opens browser) npx @juspay/neurolink auth login anthropic --method oauth # Verify authentication npx @juspay/neurolink auth status anthropic ``` ## Authentication Methods NeuroLink supports two authentication methods for Claude access, defined by the `AnthropicAuthMethod` type: - `"api_key"` -- Traditional API key authentication - `"oauth"` -- OAuth 2.0 authentication for subscription-based access ### API Key Authentication (Recommended for Production) The standard method using Anthropic API keys. Best for: - Production deployments - Server-side applications - Predictable billing (pay-per-token) - Full API control ### OAuth Authentication (Claude Pro/Max) OAuth authentication allows you to use your existing Claude Pro or Max subscription through NeuroLink. This is ideal for: - Personal development using your existing Pro/Max subscription - CLI usage without additional API costs - Leveraging your subscription's included usage quota When you authenticate with OAuth, you are redirected to claude.ai to sign in with your Claude account. After authorizing, you receive an authorization code to paste back into the CLI. NeuroLink then securely stores your tokens for future requests. ## Setup Guide ### API Key Setup (Standard) #### Step 1: Get Your API Key 1. Visit [console.anthropic.com](https://console.anthropic.com) 2. Sign in or create an account 3. Navigate to **API Keys** section 4. Click **Create Key** 5. Copy your new API key (starts with `sk-ant-`) #### Step 2: Configure Environment Set the API key in your environment: ```bash # Required: Your Anthropic API key export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here" # Optional: Default model export ANTHROPIC_MODEL="claude-sonnet-4-20250514" ``` #### Step 3: Verify Configuration ```bash # Using the CLI pnpm run cli -- generate "Hello, Claude" --provider anthropic # Or use the installed binary neurolink generate "Hello, Claude" --provider anthropic ``` #### Step 4: SDK Usage ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain machine learning in simple terms" }, provider: "anthropic", model: "claude-sonnet-4-20250514", temperature: 0.7, maxTokens: 1000, }); console.log(result.content); ``` ### OAuth Setup (Claude Pro/Max) OAuth authentication allows you to use your Claude Pro or Max subscription through NeuroLink, leveraging your subscription quota instead of API billing. OAuth authentication is designed for personal and development use. For production deployments, use API key authentication for better reliability and SLA guarantees. #### Step 1: Start OAuth Authentication Use the CLI to initiate the OAuth flow: ```bash # Start OAuth authentication (interactive -- choose method) pnpm run cli -- auth login anthropic # Start OAuth authentication directly pnpm run cli -- auth login anthropic --method oauth # Or create an API key via OAuth (recommended for Pro/Max users) pnpm run cli -- auth login anthropic --method create-api-key ``` The CLI supports three authentication methods for Anthropic: | Method | Description | | ---------------- | -------------------------------------------------- | | `api-key` | Traditional API key authentication (pay-per-use) | | `oauth` | Direct OAuth for Claude Pro/Max subscriptions | | `create-api-key` | Create a real API key via OAuth using your account | #### Step 2: Authorize in Browser 1. Sign in to your Claude account in the browser (claude.ai) 2. Review the requested permissions 3. Click **Authorize** to grant access 4. **Copy the authorization code** shown on the page #### Step 3: Complete Authentication Paste the authorization code back into the CLI when prompted: ``` Paste the authorization code: ``` The CLI will exchange the code for tokens and store them securely. #### Step 4: Verify Authentication ```bash # Check authentication status pnpm run cli -- auth status # Check status for a specific provider pnpm run cli -- auth status anthropic # Output example: # Anthropic [Authenticated] # Method: oauth # Subscription: pro # Token Expires: 2026-02-10T12:00:00Z # Refresh Token: Available ``` #### Token Management OAuth tokens are managed automatically by NeuroLink: ```bash # View token information pnpm run cli -- auth status # Refresh tokens manually (usually automatic) pnpm run cli -- auth refresh anthropic # Revoke authentication pnpm run cli -- auth logout anthropic ``` **Token Storage Location:** Credentials are stored at `~/.neurolink/tokens.json` with `0o600` file permissions (via the `TokenStore` class). Legacy CLI-saved credentials may also exist at `~/.neurolink/anthropic-credentials.json`. The file format is: ```json { "type": "oauth", "oauth": { "accessToken": "...", "refreshToken": "...", "expiresAt": 1740000000000, "tokenType": "Bearer", "scope": "user:profile user:inference" }, "provider": "anthropic", "subscriptionTier": "pro", "createdAt": 1739000000000, "updatedAt": 1739000000000 } ``` Note: `expiresAt` is stored as Unix milliseconds (`Date.now()` scale), not seconds. The `TokenStore` class (at `src/lib/auth/tokenStore.ts`) provides multi-provider token storage with XOR-based obfuscation at `~/.neurolink/tokens.json`. #### SDK OAuth Usage To use OAuth authentication in the SDK, pass `authMethod: "oauth"` and an `oauthToken` object to the Anthropic provider constructor via the NeuroLink configuration: ```typescript const neurolink = new NeuroLink({ provider: "anthropic", model: "claude-sonnet-4-20250514", authMethod: "oauth", oauthToken: { accessToken: "your-access-token", refreshToken: "your-refresh-token", expiresAt: Date.now() + 3600000, // milliseconds (Date.now() scale) }, }); const result = await neurolink.generate({ prompt: "Hello, Claude!", }); ``` Alternatively, the provider auto-detects OAuth credentials from: 1. Stored credentials file (`~/.neurolink/tokens.json` or legacy `~/.neurolink/anthropic-credentials.json`) -- highest priority 2. Environment variables `ANTHROPIC_OAUTH_TOKEN` or `CLAUDE_OAUTH_TOKEN` If either source provides a valid OAuth token, the provider automatically switches to OAuth mode without any explicit `authMethod` configuration. #### AnthropicProvider Direct Usage For advanced use cases, you can instantiate `AnthropicProvider` directly with `AnthropicProviderConfig`: ```typescript const provider = new AnthropicProvider( "claude-sonnet-4-20250514", // model name undefined, // SDK instance (optional) { authMethod: "oauth", oauthToken: { accessToken: "your-token", refreshToken: "your-refresh-token", expiresAt: Date.now() + 3600000, }, subscriptionTier: "pro", enableBetaFeatures: true, // default: true }, ); ``` The `AnthropicProviderConfig` interface accepts: | Property | Type | Default | Description | | -------------------- | ------------------------ | ------------- | ---------------------------------------------- | | `authMethod` | `"api_key" \| "oauth"` | Auto-detected | Authentication method | | `subscriptionTier` | `ClaudeSubscriptionTier` | Auto-detected | Subscription tier for model access validation | | `enableBetaFeatures` | `boolean` | `true` | Include beta headers for experimental features | | `oauthToken` | `OAuthToken` | Auto-detected | OAuth token for OAuth authentication | | `apiKey` | `string` | From env | API key for API key authentication | ## Auto-Refresh Behavior The Anthropic provider automatically refreshes expired OAuth tokens before every `generate()` and `stream()` call via the `refreshAuthIfNeeded()` method. This happens transparently and requires no user intervention. **How auto-refresh works:** 1. Before each API call, the provider checks the `expiresAt` timestamp on the OAuth token 2. If the token is expired or within 5 minutes of expiring, a refresh is attempted 3. The refresh request is sent to `https://console.anthropic.com/v1/oauth/token` using the stored refresh token 4. The refreshed token is stored both in-memory (mutated in-place on the same object reference so the fetch wrapper picks it up) and persisted to `~/.neurolink/anthropic-credentials.json` 5. If no refresh token is available and the token is expired, an `AuthenticationError` is thrown The `createOAuthFetch()` function accepts a getter function `() => string` that is called on each request to retrieve the current access token. Since `refreshAuthIfNeeded()` mutates `oauthToken.accessToken` in-place (rather than replacing the object), the getter — `() => tokenRef.accessToken` — returns the refreshed value automatically on subsequent requests without needing to re-create the fetch wrapper. **Manual refresh via CLI:** ```bash pnpm run cli -- auth refresh anthropic ``` ## Configuration ### Environment Variables | Variable | Description | Default | Required | | ----------------------------- | ---------------------------------- | ---------------------------- | -------- | | `ANTHROPIC_API_KEY` | API key for authentication | -- | Yes\* | | `ANTHROPIC_MODEL` | Default model to use | `claude-3-5-sonnet-20241022` | No | | `ANTHROPIC_OAUTH_TOKEN` | OAuth token (JSON or plain string) | -- | No | | `CLAUDE_OAUTH_TOKEN` | OAuth token (fallback env var) | -- | No | | `ANTHROPIC_SUBSCRIPTION_TIER` | Explicit subscription tier | Auto-detected | No | \*Required for API key authentication. Not required when using OAuth. ### Subscription Tier Detection The provider detects the subscription tier in this priority order: 1. Explicit `subscriptionTier` passed in `AnthropicProviderConfig` 2. `ANTHROPIC_SUBSCRIPTION_TIER` environment variable (valid values: `free`, `pro`, `max`, `max_5`, `max_20`, `api`) 3. Inferred from OAuth token scopes (if present) 4. Default: `"pro"` when OAuth token is present, `"api"` when using API key ### CLI Options ```bash # Specify provider and model pnpm run cli -- generate "Your prompt" --provider anthropic --model claude-sonnet-4-20250514 # Set temperature and max tokens pnpm run cli -- generate "Your prompt" --provider anthropic --temperature 0.7 --max-tokens 2000 # Use streaming output pnpm run cli -- stream "Tell me a story" --provider anthropic # Specify auth method and subscription tier pnpm run cli -- generate "Your prompt" \ --provider anthropic \ --authMethod oauth \ --subscriptionTier pro ``` The CLI also supports `anthropic-subscription` as a provider alias that indicates subscription tier support. ## Beta Features Anthropic regularly releases new features in beta. NeuroLink includes beta headers automatically when `enableBetaFeatures` is true (the default). ### Beta Headers For API key authentication, the following beta headers are included: ``` anthropic-beta: claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14 ``` These correspond to the `AnthropicBetaFeature` enum values in `src/lib/constants/enums.ts`: | Enum Value | Header Value | | ------------------------ | ---------------------------------------- | | `CLAUDE_CODE` | `claude-code-20250219` | | `INTERLEAVED_THINKING` | `interleaved-thinking-2025-05-14` | | `FINE_GRAINED_STREAMING` | `fine-grained-tool-streaming-2025-05-14` | For OAuth authentication, the fetch wrapper uses different beta headers: ``` anthropic-beta: oauth-2025-04-20,interleaved-thinking-2025-05-14 ``` The `oauth-2025-04-20` header is required for OAuth-authenticated requests. The `claude-code-20250219` header is conditionally included only if the original request headers already contain it. ## Model Availability by Tier ### Model Access Matrix Model access is defined in `MODEL_TIER_ACCESS` in `src/lib/models/anthropicModels.ts`: | Model | Free | Pro | Max/Max_5/Max_20 | API | | ------------------------------------------------------ | ---- | --- | ---------------- | --- | | `claude-3-haiku-20240307` (Claude 3 Haiku) | Yes | Yes | Yes | Yes | | `claude-3-5-haiku-20241022` (Claude 3.5 Haiku) | Yes | Yes | Yes | Yes | | `claude-3-5-sonnet-20241022` (Claude 3.5 Sonnet) | No | Yes | Yes | Yes | | `claude-3-5-sonnet-v2-20241022` (Claude 3.5 Sonnet V2) | No | Yes | Yes | Yes | | `claude-sonnet-4-20250514` (Claude Sonnet 4) | No | Yes | Yes | Yes | | `claude-3-opus-20240229` (Claude 3 Opus) | No | No | Yes | Yes | | `claude-opus-4-20250514` (Claude Opus 4) | No | No | Yes | Yes | Key observations: - **Free** tier only gets Haiku models (Claude 3 Haiku and Claude 3.5 Haiku) - **Pro** tier gets Haiku and Sonnet models, but **not Opus** - **Max** tiers (max, max_5, max_20) and **API** have access to all models (wildcard `"*"`) ### Default Models by Tier Each tier has a recommended default model (from `DEFAULT_MODELS_BY_TIER`): | Tier | Default Model | | ------ | --------------------------- | | Free | `claude-3-5-haiku-20241022` | | Pro | `claude-sonnet-4-20250514` | | Max | `claude-opus-4-20250514` | | Max_5 | `claude-opus-4-20250514` | | Max_20 | `claude-opus-4-20250514` | | API | `claude-sonnet-4-20250514` | ### Model Tier Enforcement When the provider detects that the requested model is not available for the user's subscription tier, it automatically falls back to the recommended model for that tier and logs a warning: ```typescript // If a Pro user requests an Opus model: // - The provider logs a warning // - Falls back to claude-sonnet-4-20250514 (the Pro default) ``` You can validate model access programmatically: ```typescript isModelAvailableForTier, getRecommendedModelForTier, getModelCapabilities, ModelAccessError, } from "./lib/providers/anthropic.js"; // Check if a model is available const available = isModelAvailableForTier("claude-opus-4-20250514", "pro"); // Returns: false (Opus requires max or api tier) // Get recommended model for a tier const recommended = getRecommendedModelForTier("pro"); // Returns: "claude-sonnet-4-20250514" // Get model metadata const capabilities = getModelCapabilities("claude-sonnet-4-20250514"); // Returns: { displayName: "Claude Sonnet 4", contextWindow: 200000, maxOutputTokens: 64000, ... } ``` ### Choosing the Right Model ```typescript const neurolink = new NeuroLink(); // For quick, cost-effective responses (Free tier compatible) const quickResult = await neurolink.generate({ input: { text: "Summarize this text..." }, provider: "anthropic", model: "claude-3-5-haiku-20241022", }); // For balanced performance (Pro tier and above) const balancedResult = await neurolink.generate({ input: { text: "Analyze this code..." }, provider: "anthropic", model: "claude-sonnet-4-20250514", }); // For complex reasoning tasks (Max/API tier only) const complexResult = await neurolink.generate({ input: { text: "Solve this complex problem..." }, provider: "anthropic", model: "claude-opus-4-20250514", }); ``` ## Usage Tracking ### Rate Limit Tracking The Anthropic provider tracks rate limit information from API response headers. After each request, you can query usage info: ```typescript const provider = new AnthropicProvider("claude-sonnet-4-20250514"); const result = await provider.generate("Hello"); // Get usage information const usage = provider.getUsageInfo(); if (usage) { console.log("Requests made:", usage.requestCount); console.log("Tokens used:", usage.tokensUsed); console.log("Message quota %:", usage.messageQuotaPercent); console.log("Token quota %:", usage.tokenQuotaPercent); console.log("Rate limited:", usage.isRateLimited); } // Get last response metadata including rate limits const metadata = provider.getLastResponseMetadata(); if (metadata?.rateLimit) { console.log("Requests remaining:", metadata.rateLimit.requestsRemaining); console.log("Tokens remaining:", metadata.rateLimit.tokensRemaining); } ``` The `ClaudeUsageInfo` type tracks: | Field | Type | Description | | --------------------- | --------- | ---------------------------------------- | | `messagesUsed` | `number` | Messages sent in current period | | `messagesRemaining` | `number` | Messages remaining (-1 if unknown) | | `tokensUsed` | `number` | Total tokens consumed | | `tokensRemaining` | `number` | Tokens remaining (-1 if unknown) | | `inputTokensUsed` | `number` | Input/prompt tokens consumed | | `outputTokensUsed` | `number` | Output/response tokens consumed | | `requestCount` | `number` | Total API requests made | | `isRateLimited` | `boolean` | Whether currently rate limited | | `rateLimitExpiresAt` | `number?` | When rate limit expires (ms timestamp) | | `messageQuotaPercent` | `number` | Percentage of message quota used (0-100) | | `tokenQuotaPercent` | `number` | Percentage of token quota used (0-100) | ### Rate Limit Handling The provider automatically logs warnings when approaching rate limits: - When fewer than 5 requests remain in the current window - When token usage exceeds 90% of the token limit Rate limit information is parsed from these Anthropic response headers: - `anthropic-ratelimit-requests-limit` - `anthropic-ratelimit-requests-remaining` - `anthropic-ratelimit-requests-reset` - `anthropic-ratelimit-tokens-limit` - `anthropic-ratelimit-tokens-remaining` - `anthropic-ratelimit-tokens-reset` - `retry-after` ### Monitoring API Usage For API key authentication, monitor token usage from generate results: ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Your prompt" }, provider: "anthropic", }); // Access usage information from the result console.log("Input tokens:", result.usage?.inputTokens); console.log("Output tokens:", result.usage?.outputTokens); console.log("Total tokens:", result.usage?.totalTokens); ``` ## OAuth Implementation Details ### OAuth Flow NeuroLink's OAuth implementation follows the same approach used by the official Claude Code CLI. The `AnthropicOAuth` class in `src/lib/auth/anthropicOAuth.ts` implements: 1. **PKCE Flow (S256)**: Uses Proof Key for Code Exchange with SHA-256 code challenge method 2. **Authorization Endpoint**: `https://claude.ai/oauth/authorize` 3. **Token Endpoint**: `https://console.anthropic.com/v1/oauth/token` 4. **Redirect URI**: `https://console.anthropic.com/oauth/code/callback` 5. **Default Scopes**: `org:create_api_key`, `user:profile`, `user:inference` ### OAuth Constants Key constants from `src/lib/auth/anthropicOAuth.ts`: | Constant | Value | | ------------------------ | --------------------------------------------------- | | `CLAUDE_CODE_CLIENT_ID` | `9d1c250a-e61b-44d9-88ed-5944d1962f5e` | | `ANTHROPIC_AUTH_URL` | `https://claude.ai/oauth/authorize` | | `ANTHROPIC_TOKEN_URL` | `https://console.anthropic.com/v1/oauth/token` | | `ANTHROPIC_REDIRECT_URI` | `https://console.anthropic.com/oauth/code/callback` | | `CLAUDE_CLI_USER_AGENT` | `claude-cli/2.1.2 (external, cli)` | | `MCP_TOOL_PREFIX` | `mcp_` | ### API Request Requirements for OAuth When using OAuth tokens, the `createOAuthFetch()` wrapper automatically applies these transformations: ```typescript // Required headers applied by the OAuth fetch wrapper headers: { "Authorization": `Bearer ${accessToken}`, // NOT x-api-key "anthropic-beta": "oauth-2025-04-20,interleaved-thinking-2025-05-14", "User-Agent": "claude-cli/2.1.2 (external, cli)" } // URL modified for /v1/messages endpoint url: "https://api.anthropic.com/v1/messages?beta=true" ``` Additionally, the OAuth fetch wrapper: - Prefixes tool names with `mcp_` in outgoing requests (both tool definitions and `tool_use` blocks in messages) - Strips the `mcp_` prefix from tool names in streaming responses - Removes the `x-api-key` header (OAuth uses `Authorization: Bearer` instead) ### OAuthToken Type The `OAuthToken` type (from `src/lib/types/subscriptionTypes.ts`) used across the provider: ```typescript type OAuthToken = { accessToken: string; // Required: access token for API requests refreshToken?: string; // Optional: for obtaining new access tokens expiresAt?: number; // Optional: Unix milliseconds (Date.now() scale) tokenType?: string; // Optional: typically "Bearer" scopes?: string[]; // Optional: granted scopes }; ``` Note: `expiresAt` is stored in **milliseconds** (matching `Date.now()`), not seconds. ### Known Limitations OAuth tokens obtained through this flow may have model access restrictions enforced by Anthropic. Some users report that certain models return "This credential is only authorized for use with Claude Code" errors. **Current limitations observed:** | Model Family | OAuth Access | Notes | | ---------------- | ------------ | ------------------------------- | | Claude 3 Haiku | Works | Reliable access | | Claude 3.5 Haiku | Works | Reliable access | | Claude Sonnet 4 | Varies | May return authorization errors | | Claude Opus 4 | Varies | May return authorization errors | **Workarounds:** 1. **Use API Key Authentication**: For production use, API key authentication is more reliable 2. **Create API Key via OAuth**: Use `pnpm run cli -- auth login anthropic --method create-api-key` to create a real API key through `https://api.anthropic.com/api/oauth/claude_cli/create_api_key` (requires `org:create_api_key` scope) 3. **Use Haiku Models**: Haiku models appear to have more consistent OAuth access ## Troubleshooting ### Common Issues and Solutions #### Authentication Errors **Issue: "Invalid API key" error** ``` Error: Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable. ``` **Solution:** 1. Verify your API key starts with `sk-ant-` 2. Check for extra spaces or characters 3. Ensure the key is active in [console.anthropic.com](https://console.anthropic.com) ```bash # Verify environment variable is set correctly echo $ANTHROPIC_API_KEY | head -c 20 # Should output: sk-ant-api03-xxxx... ``` #### OAuth Token Expired **Issue: "OAuth token expired and no refresh token available" error** **Solution:** ```bash # Refresh the token pnpm run cli -- auth refresh anthropic # Or re-authenticate pnpm run cli -- auth login anthropic ``` Note: If a refresh token is available, the provider will automatically refresh expired tokens before each `generate()` or `stream()` call. Manual refresh is only needed if automatic refresh fails. #### Rate Limit Exceeded **Issue: "Rate limit exceeded" (429) errors** **Solution:** 1. For Free tier: Upgrade to Pro or Max for higher limits 2. For API: Request a rate limit increase from Anthropic 3. Monitor rate limit headers via `provider.getUsageInfo()` and `provider.getLastResponseMetadata()` #### Model Access Denied **Issue: Model falls back to a different model than requested** The provider logs a warning when the requested model is not available for the detected subscription tier and automatically falls back to the recommended model. To fix: 1. Check your subscription tier supports the model (see [Model Access Matrix](#model-access-matrix)) 2. Set the correct tier via `ANTHROPIC_SUBSCRIPTION_TIER` environment variable 3. For Opus models, a Max or API tier is required #### OAuth Callback Failure **Issue: OAuth callback never completes** **Solution:** 1. Ensure no browser extensions are blocking redirects 2. The CLI uses the code-based redirect flow (code is shown on the page for you to copy) 3. Try a different browser 4. Check the authorization code has not expired (codes are single-use and time-limited) ### Debugging Tips Enable debug logging for detailed information: ```bash # Enable debug mode export NEUROLINK_DEBUG=true # Or for verbose output export NEUROLINK_LOG_LEVEL=debug # Run your command pnpm run cli -- generate "Test prompt" --provider anthropic ``` The provider logs detailed debug information for: - Auth method detection - OAuth token refresh attempts - Rate limit warnings - Model tier fallback decisions ### Getting Help If issues persist: 1. Check the [NeuroLink troubleshooting guide](/docs/reference/troubleshooting) 2. Visit [Anthropic's documentation](https://docs.anthropic.com) 3. Open an issue on [GitHub](https://github.com/juspay/neurolink/issues) ## Best Practices ### Security - **Never commit API keys** to version control - Use environment variables or secrets management - Rotate API keys periodically - OAuth credentials are stored with `0o600` permissions in `~/.neurolink/` ```bash # Use .env file (not committed to git) echo "ANTHROPIC_API_KEY=sk-ant-..." >> .env # Add to .gitignore echo ".env" >> .gitignore ``` ### Cost Optimization 1. **Use Haiku for simple tasks**: Cheapest model, available on all tiers 2. **Set appropriate maxTokens**: Avoid unnecessary generation 3. **Monitor usage**: Check `provider.getUsageInfo()` for quota tracking ### Reliability 1. **Use timeouts**: Prevent hanging requests 2. **Consider fallbacks**: Configure alternative providers ```typescript // Configure with fallback to another provider const { primary, fallback } = await createAIProviderWithFallback( "anthropic", "openai", ); ``` ## Exported Types and Utilities ### From `src/lib/types/subscriptionTypes.ts` - `ClaudeSubscriptionTier` -- Union type: `"free" | "pro" | "max" | "max_5" | "max_20" | "api"` - `AnthropicAuthMethod` -- Union type: `"api_key" | "oauth"` - `OAuthToken` -- OAuth token structure with `accessToken`, `refreshToken?`, `expiresAt?`, `tokenType?`, `scopes?` - `AnthropicRateLimitInfo` -- Rate limit data parsed from response headers - `AnthropicResponseMetadata` -- Response metadata including rate limits, request ID, server timing - `ClaudeUsageInfo` -- Usage tracking with messages, tokens, quotas - `ClaudeQuotaInfo` -- Quota limits per tier - `SubscriptionFeatures` -- Per-tier feature capabilities - `AnthropicBetaFeatures` -- Beta feature flag configuration type ### From `src/lib/models/anthropicModels.ts` - `AnthropicModel` -- Enum of model identifiers - `MODEL_TIER_ACCESS` -- Model access by tier - `MODEL_METADATA` -- Model metadata (context window, capabilities, etc.) - `isModelAvailableForTier(model, tier)` -- Check model availability - `getAvailableModelsForTier(tier)` -- List all models for a tier - `getDefaultModelForTier(tier)` / `getRecommendedModelForTier(tier)` -- Get default model - `getModelMetadata(model)` / `getModelCapabilities(model)` -- Get model metadata - `validateModelAccess(model, tier)` -- Throws `ModelAccessError` if access denied - `getMinimumTierForModel(model)` -- Get minimum tier required - `ModelAccessError` -- Error class for denied model access ### From `src/lib/constants/enums.ts` - `ClaudeSubscriptionTier` enum (FREE, PRO, MAX, API) - `AnthropicAuthMethod` enum (API_KEY, OAUTH) - `AnthropicBetaFeature` enum (CLAUDE_CODE, INTERLEAVED_THINKING, FINE_GRAINED_STREAMING) - `TOKEN_EXPIRY_BUFFER_MS` -- 5-minute buffer constant (300000ms) ### From `src/lib/auth/index.ts` - `AnthropicOAuth` -- OAuth 2.0 flow implementation class - `TokenStore` / `tokenStore` -- Secure token storage - `OAuthError` and subclasses -- OAuth error types - `createAnthropicOAuth()` -- Factory function - `performOAuthFlow()` -- Complete OAuth flow helper - `startCallbackServer()` / `stopCallbackServer()` -- Local callback server ### From `src/lib/providers/anthropic.ts` - `AnthropicProvider` -- Provider class with OAuth support - `AnthropicProviderConfig` -- Configuration interface - `ANTHROPIC_BETA_HEADERS` -- Beta headers constant - Re-exports: `ModelAccessError`, `isModelAvailableForTier`, `getRecommendedModelForTier`, `getModelCapabilities` ## SDK Programmatic API ### OAuth Flow (Programmatic) Use the `AnthropicOAuth` class to run the OAuth 2.0 + PKCE flow programmatically: ```typescript // Create OAuth client with defaults (uses Claude Code's official client ID) const oauth = createAnthropicOAuth(); // Generate PKCE values const pkce = await AnthropicOAuth.generatePKCE(); // pkce = { codeVerifier: "...", codeChallenge: "..." } // Build authorization URL — user visits this in their browser const authUrl = oauth.generateAuthUrl({ codeChallenge: pkce.codeChallenge, state: pkce.codeVerifier, // state=verifier pattern (OpenCode convention) }); console.log("Visit:", authUrl); // After user authorizes, exchange the code for tokens const tokens = await oauth.exchangeCodeForTokens(code, pkce.codeVerifier); // tokens = { accessToken, tokenType, expiresAt (Date), refreshToken?, scopes[] } // Refresh when token expires const newTokens = await oauth.refreshAccessToken(tokens.refreshToken); // Validate a token const validation = await oauth.validateAccessToken(tokens.accessToken); // validation = { valid: true } or { valid: false, error: "..." } // Revoke a token await oauth.revokeToken(tokens.accessToken, "access_token"); ``` ### Token Store API The `defaultTokenStore` provides secure, file-based token persistence at `~/.neurolink/tokens.json`: ```typescript // Save tokens for a provider await defaultTokenStore.saveTokens("anthropic", { accessToken: "...", refreshToken: "...", expiresAt: Date.now() + 3600000, // Unix ms tokenType: "Bearer", }); // Load tokens (returns null if not found) const tokens = await defaultTokenStore.loadTokens("anthropic"); // Get valid token with auto-refresh (refreshes if expired) const validToken = await defaultTokenStore.getValidToken("anthropic"); // Check if tokens exist const hasTokens = await defaultTokenStore.hasTokens("anthropic"); // List providers with stored tokens const providers = await defaultTokenStore.listProviders(); // Clear tokens for a provider await defaultTokenStore.clearTokens("anthropic"); // Clear all stored tokens await defaultTokenStore.clearAllTokens(); // Register auto-refresh callback defaultTokenStore.setTokenRefresher("anthropic", async (refreshToken) => { const oauth = createAnthropicOAuth(); return await oauth.refreshAccessToken(refreshToken); }); ``` ### Model Tier Validation API Query model availability and tier access programmatically: ```typescript isModelAvailableForTier, getDefaultModelForTier, getAvailableModelsForTier, getMinimumTierForModel, getModelMetadata, validateModelAccess, compareTiers, } from "@juspay/neurolink"; // Check model availability for a tier isModelAvailableForTier("claude-opus-4-20250514", "pro"); // false isModelAvailableForTier("claude-opus-4-20250514", "max"); // true // Get recommended model for a tier getDefaultModelForTier("free"); // "claude-3-5-haiku-20241022" getDefaultModelForTier("pro"); // "claude-sonnet-4-20250514" getDefaultModelForTier("max"); // "claude-opus-4-20250514" // List all models for a tier getAvailableModelsForTier("pro"); // ["claude-3-haiku-20240307", "claude-3-5-haiku-20241022", "claude-sonnet-4-20250514", ...] // Find the minimum tier required for a model getMinimumTierForModel("claude-opus-4-20250514"); // "max" // Get model metadata (context window, capabilities, etc.) const meta = getModelMetadata("claude-sonnet-4-20250514"); // { contextWindow: 200000, maxOutputTokens: 64000, supportsVision: true, ... } // Compare tiers (returns -1, 0, or 1) compareTiers("pro", "max"); // -1 (pro ; getUsageInfo(): unknown; getLastResponseMetadata(): unknown; getAuthHeaders(): Record; }; const provider = (await ProviderFactory.createProvider( "anthropic", )) as unknown as ClaudeSubscriptionProvider; // Check subscription state provider.getSubscriptionTier(); // "pro" | "max" | "api" | ... provider.getAuthMethod(); // "oauth" | "api_key" provider.areBetaFeaturesEnabled(); // true | false // Validate model access before generation if (provider.validateModelAccess("claude-opus-4-20250514")) { // Model is available for the current tier } // Manual token refresh (usually automatic) await provider.refreshAuthIfNeeded(); // Usage tracking (populated after API calls) const usage = provider.getUsageInfo(); // { messagesUsed, tokensUsed, inputTokensUsed, outputTokensUsed, // lastRequestTokens, tokenQuotaPercent, ... } // Rate limit info from last response const metadata = provider.getLastResponseMetadata(); // { rateLimits: { requestsRemaining, tokensRemaining, ... }, requestId } // Get auth headers (for custom integrations) const headers = provider.getAuthHeaders(); // { "anthropic-beta": "...", "x-subscription-tier": "pro" } ``` ## See Also - [Provider Setup Guide](/docs/) - [Extended Thinking Configuration](/docs/features/thinking-configuration) - [MCP Integration Guide](/docs/mcp/integration) --- ## CLI Loop Sessions # CLI Loop Sessions `neurolink loop` delivers a persistent CLI workspace so you can explore prompts, tweak parameters, and inspect state without restarting the CLI. Session variables, Redis-backed history, and built-in help turn the CLI into a playground for prompt engineering and operator runbooks. ## Quick Start ```bash # Enter interactive loop mode with Anthropic as the default provider npx @juspay/neurolink loop --provider anthropic # Inside the loop, just type prompts: # ⎔ neurolink » explain quantum entanglement # ⎔ neurolink » now simplify that for a 10-year-old # ⎔ neurolink » exit ``` ## Why Loop Mode - **Stateful sessions** – keep provider/model/temperature context between commands. - **Memory on demand** – enable in-memory or Redis-backed conversation history per session. - **Fast iteration** – reuse the entire command surface (`generate`, `stream`, `memory`, etc.) without leaving the loop. - **Guided UX** – ASCII banner, inline help, and validation for every session variable. :::tip[Keyboard Shortcuts] Loop mode supports **tab completion** for commands and session variables, **arrow key history** for navigating previous commands, and **Ctrl+C** to cancel the current operation without exiting the loop. ::: ## Starting a Session ```bash # Default: in-memory session variables, Redis auto-detected when available npx @juspay/neurolink loop # Disable Redis auto-detection and stay in-memory npx @juspay/neurolink loop --no-auto-redis # Turn off memory entirely (prompt-by-prompt mode) npx @juspay/neurolink loop --enable-conversation-memory=false # Custom retention limits npx @juspay/neurolink loop --max-sessions 100 --max-turns-per-session 50 ``` ```typescript // Create a NeuroLink instance with session state const neurolink = new NeuroLink({ conversationMemory: { enabled: true, // (1)! store: "redis", // (2)! maxTurnsPerSession: 50, }, }); // Simulate loop-like behavior with persistent context const sessionId = "my-session-123"; // (3)! // First interaction const result1 = await neurolink.generate({ input: { text: "What is NeuroLink?" }, context: { sessionId }, // (4)! provider: "google-ai", enableEvaluation: true, }); // Second interaction - memory preserved const result2 = await neurolink.generate({ input: { text: "How do I enable HITL?" }, context: { sessionId }, // (5)! provider: "google-ai", }); console.log(result2.content); // AI remembers previous context ``` ## Session Commands Inside the loop prompt (`⎔ neurolink »`) you can manage context without leaving the session: | Command | Purpose | Example | | ---------------------- | ------------------------------------------------------- | ------------------------- | | `/help` | Show loop-specific commands plus full CLI help. | `/help` | | `/set ` | Persist a generation option (validated against schema). | `/set provider google-ai` | | `/get ` | Inspect the current value. | `/get provider` | | `/unset ` | Remove a single session variable. | `/unset temperature` | | `/show` | List all session variables. | `/show` | | `/clear` | Reset every session variable. | `/clear` | | `exit` / `quit` / `:q` | Leave loop mode. | `exit` | ### Common Variables - `provider` – any provider except `auto` (`/set provider google-ai`). - `model` – model slug from `models list` (`/set model gemini-2.5-pro`). - `temperature` – floating point number (`/set temperature 0.6`). - `enableEvaluation` / `enableAnalytics` – toggles for observability (`/set enableEvaluation true`). - `context` – JSON-encoded metadata (`/set context {"userId":"42"}`). - `NEUROLINK_EVALUATION_THRESHOLD` – dynamic quality gate (`/set NEUROLINK_EVALUATION_THRESHOLD 8`). > Type `/set help` in the loop to view every available key and its validation rules. ## Using CLI Commands in Loop Mode In loop mode, you can interact with the AI naturally by typing your prompts directly: ``` ⎔ neurolink » what are the seven wonders? ⎔ neurolink » explain quantum physics ⎔ neurolink » tell me a story about space exploration ``` To use other CLI commands explicitly, prefix them with a forward slash `/`: ``` ⎔ neurolink » /generate "Draft changelog from sprint notes" --enableEvaluation ⎔ neurolink » /batch file.txt ⎔ neurolink » /status --verbose ⎔ neurolink » /models list --capability vision ``` :::tip[Quick Reference] - **No prefix**: Streams a response to your prompt - **`/` prefix**: Executes CLI commands or session commands (e.g., `/help`, `/set`, `/generate`, `/batch`) - **`//` prefix**: Escape to stream prompts starting with `/` (e.g., `//what is /usr/bin?`) - **Exit commands**: `exit`, `quit`, or `:q` work without prefix to leave loop mode ::: Errors are handled gracefully; parsing issues surface inline without closing the loop. ## Conversation Memory & Redis Auto-Detect :::tip[Redis Persistence] When Redis is detected, loop sessions survive restarts. Exit the loop, close your terminal, and resume later with the same session ID to continue where you left off. Perfect for long-running prompt engineering workflows. ::: - By default the loop enables conversation memory (`--enable-conversation-memory=true`). - `--auto-redis` probes for a reachable Redis instance using existing environment variables (`REDIS_URL`, etc.). - When Redis is available you’ll see `✅ Using Redis for persistent conversation memory` in the banner. - History is segmented by generated session IDs and stored with tool transcripts. Manage history with standard CLI commands (inside or outside loop): ```bash # Overview of stored sessions npx @juspay/neurolink memory stats # Export a specific transcript as JSON npx @juspay/neurolink memory history NL_r1bd2 --format json > transcript.json # Clear loop history npx @juspay/neurolink memory clear NL_r1bd2 ``` ## Best Practices - Commit to a provider/model via `/set` at the start of a session to avoid noisy auto-routing during experiments. - Use `/set enableAnalytics true` and `/set enableEvaluation true` to apply observability globally. - Combine with the interactive setup wizard (`neurolink setup --list`) to configure credentials mid-session. - If you switch projects, run `/clear` or start a new loop to avoid leaking context. ## Troubleshooting | Symptom | Resolution | | ---------------------------------- | --------------------------------------------------------------------------------------- | | `A loop session is already active` | Use `exit` in the existing session or close the terminal tab before starting a new one. | | Redis warning but memory disabled | Ensure Redis credentials are valid or run with `--no-auto-redis`. | | Session variable rejected | Run `/set help` to check allowed values; booleans must be `true`/`false`. | | Commands exit unexpectedly | Update to the latest CLI so the session-aware error handler is included. | ## Related Features **Q4 2025 Features:** - [Redis Conversation Export](/docs/features/conversation-history) – Export loop session history as JSON for analytics **Q3 2025 Features:** - [Multimodal Chat](/docs/features/multimodal-chat) – Use images in loop sessions - [Auto Evaluation](/docs/features/auto-evaluation) – Enable quality scoring with `set enableEvaluation true` **Documentation:** - [CLI Commands](/docs/cli/commands) – Complete command reference - [Conversation Memory](/docs/memory/conversation) – Memory system deep dive --- ## Codex (ChatGPT) Support for NeuroLink Proxy # Codex (ChatGPT) Support for NeuroLink Proxy ## Status: Implemented — request path verified, quota path unverified Codex is supported as a **second subscription pool engine** alongside Claude. The proxy pools multiple ChatGPT accounts and rotates between them automatically, so you never have to switch accounts by hand when one hits its limit. Verified end-to-end against Codex CLI 0.144.4: a pooled request through the proxy authenticates with a pooled account, passes OpenAI's anti-abuse checks, and streams a live SSE response back from the ChatGPT backend. ## 2. Adding accounts Codex login works by **importing the credential the Codex CLI already holds**. Log into Codex normally, then import: ```bash codex login # sign in as account A neurolink auth login codex --label work # import it into the pool codex login # sign in as account B neurolink auth login codex --label personal # import that one too ``` Each import reads `~/.codex/auth.json`, decodes the account id / plan / email from the token, and stores it under a `codex:` key in `~/.neurolink/tokens.json`. If you omit `--label`, the account email is used. List the pool (Codex and Anthropic accounts appear together): ```bash neurolink auth list neurolink auth list --refresh # also fetch fresh usage windows ``` Remove Codex accounts: ```bash neurolink auth logout codex ``` > Only ChatGPT subscription login (`auth_mode: "chatgpt"`) can be pooled. An API-key Codex install is rejected with a clear message. --- ## 3. Client auto-configuration When `neurolink proxy start` runs (non-dev), it configures the Codex CLI the same way it configures Claude Code and OpenCode. It appends a marker-delimited block to `~/.codex/config.toml`: ```toml model_provider = "neurolink" # >>> neurolink-proxy (managed) >>> [model_providers.neurolink] name = "NeuroLink Proxy" base_url = "http://127.0.0.1:55669/backend-api/codex" wire_api = "responses" requires_openai_auth = true # ``` The proxy relays that upstream to `chatgpt.com/backend-api/codex/models` using a pooled account, forwarding the CLI's own query parameters. **It relays rather than synthesises**, unlike the Claude and OpenAI `/v1/models` routes, which build their lists locally from the model router. Which Codex models an account can reach is a property of that account — plan tier, rollout state — not something this proxy knows, so a locally-built list would be a guess that reads as authoritative. Two details matter to anyone touching it: - **`client_version` is required upstream.** Omit it and ChatGPT answers `400` with a pydantic `Field required` on `('query', 'client_version')`. The query is rebuilt from `ctx.query`; `ctx.path` carries no query string, and reading it from there drops the parameter silently. - **Discovery is side-effect free.** No cooldown is recorded and no quota is consumed, so the once-per-invocation refresh cannot influence routing for real traffic. A cooling account is still allowed to answer it — being rate-limited for completions does not make an account unable to say which models exist. Before this route existed the request 404'd, and the CLI printed `failed to refresh available models: unexpected status 404 Not Found` on every run before silently falling back to a default model — quietly ignoring the model the user had configured. --- ## 9. Outbound fallback (Codex request → Claude engine) ### Status: implemented, default OFF, request-shape verified only — see "Live validation" below Sections 1-8 above cover the **inbound** direction: a Codex CLI request served by the Codex/ChatGPT pool engine. This section covers the opposite direction — a native Codex `/backend-api/codex/responses` request that, when every Codex account is exhausted or otherwise ineligible, is **translated** into an Anthropic Messages request and served by either the Anthropic OAuth pool (via an in-process loopback, no extra network hop to this same proxy) or a Vertex-Claude passthrough account, then translated back into the Codex Responses wire shape the CLI expects. It is a third direction alongside the two-engine matrix in the rest of this document, not a replacement for either. ### 9.1 Enabling it The kill switch defaults to **off**. Nothing changes for an existing Codex pool setup until you opt in: ```yaml # proxy-config.yaml routing: codex-outbound-fallback-enabled: true # Ordered list of engines to try once Codex itself is exhausted; the first # entry with a healthy pooled account wins. At most 8 entries. codex-outbound-fallback-targets: - provider: anthropic model: claude-sonnet-4-5 - provider: vertex model: claude-sonnet-4-5 # Optional: remap a Codex-side model id to a different target-side model id # per target provider (falls back to the target's own `model` above when a # request's model has no matching entry). codex-outbound-fallback-model-mappings: - from: gpt-5-codex to: claude-opus-4-1 provider: anthropic ``` or via environment variable, which overrides the YAML key: ```bash NEUROLINK_PROXY_CODEX_OUTBOUND_FALLBACK=true ``` `codex-outbound-fallback-targets` is required (non-empty) for the fallback to ever fire — the kill switch alone is not enough. `provider` must be `anthropic` or `vertex`; up to 8 targets are accepted and validated at config-load time. With the flag off, or with no targets configured, an exhausted Codex request behaves exactly as it did before this feature existed: the same terminal `response.failed` SSE / `401` behaviour documented in section 6 above, byte- for-byte. **The `anthropic` target needs the CLI proxy's in-process loopback.** Dispatch to an `anthropic` target goes through an in-process loopback (`127.0.0.1:`, authorised by a server-minted single-use `x-neurolink-internal-request` token — `proxyActivity.ts` — which is what makes the crossing unforgeable; `internalDispatch` itself is just `app.fetch`, see §9.3) rather than a second network hop, and only `neurolink proxy start` (the CLI proxy command) wires that loopback through today. `createAllRoutes` / `registerAllRoutes` — the generic SDK route surface in `src/lib/server/routes/index.ts`, used when embedding the proxy routes in your own server — does **not** thread `loopbackPort`/`internalDispatch` into `createCodexProxyRoutes`, so enabling this feature there with an `anthropic` target configured cannot actually dispatch: route creation logs one warning and every such request falls through to the normal Codex-exhaustion behaviour in section 6, indistinguishable on the wire from the feature being off. A `vertex` target has no such gap — it dispatches over `executeVertexAnthropicFallback` regardless of which route surface created the routes. If you need the `anthropic` target from the SDK route surface, run the CLI proxy alongside your server, or wait for `loopbackPort`/`internalDispatch` to be threaded through `CreateRoutesOptions` (not yet implemented — see the doc comments on `createAllRoutes` and `CreateRoutesOptions.runtimeConfigProvider`). ### 9.2 When it triggers `attemptCodexOutboundFallback` (module-private in `codexProxyRoutes.ts`) is consulted only after every Codex account has been tried and failed, and only when all of the following hold, in this order — any one failing gate means "not attempted", and the request falls through to the normal Codex-exhaustion behaviour in section 6: 1. The inbound request is not itself already a fallback leg (see loop prevention below). 2. `runtimeConfigProvider` is configured (the proxy is running with the runtime-config feature enabled at all). 3. `classifyCodexOutboundFailure` judges the failure itself eligible — a total function, not a heuristic guess, over the terminal Codex failure class. 4. The kill switch (`codexOutboundFallbackEnabled`) is on. 5. `codexOutboundFallbackTargets` is non-empty. 6. The native Codex request body parses (`parseCodexNativeRequest`) — a request the translator cannot even parse is never a candidate. When the account loop runs out, the last attempt decides eligibility. A 401/403 across the whole pool is a Codex credential failure and falls back, as do 429 and 5xx. A content-policy or invalid-request error code (`classifyProxyFailureCode`), or any other 4xx, rejects the request itself: the pool ends the request on the account that received it, after exactly one upstream call, and returns the upstream status (see section 6), so such a request never reaches this point. The Anthropic loopback has a 5-minute timeout that covers the connection until its response headers arrive. After that the stream runs as long as the turn does; a client disconnect still ends it. ### 9.3 Loop prevention Two independent guards, so a defect in one does not remove the bound: - **Marker guard.** The moment every gate above has passed and a real dispatch attempt is about to begin, `codexProxyRoutes.ts` sets `ctx.metadata["neurolink.codexOutboundFallbackAttempted"] = true` on the request context. Gate 1 above checks this same key, so a request that has already crossed engines once can never be offered a second outbound-fallback attempt within the same client request. This is a single flag, not a per-target counter, because at most one crossing is ever allowed regardless of how many of the internal dispatch call sites reach this function. - **Depth bound.** `MAX_ENGINE_CROSSINGS = 1` (`codexOutboundFallback.ts`) states the invariant the marker guard enforces: the ordered sequence of engines serving any one client request has length ≤ 2 with no repeat — only `[codex]`, `[anthropic]`, `[codex,anthropic]`, `[anthropic,codex]` are possible. It is a documented constant, not a second runtime counter: the marker above is the only check that runs, and there is no `fallbackHopDepth` metadata key. A request that reaches this point already carrying a forged `codexOutboundFallbackAttempted`-shaped marker from outside is not trusted — the key lives on the server-side request context (`ctx.metadata`), not on anything the client can set on the wire, so there is no client-controlled way to spoof past gate 1. ### 9.4 What gets translated Request translation (`src/lib/proxy/codexOutboundFallback.ts`): - Codex `additional_tools` namespaces (`functions`, `collaboration`, …) are flattened into one Claude `tools` array, preserving declaration order — namespace order, then tool order within each namespace — never regrouped or resorted by tool kind. - A tool's kind (`function` vs `custom`) is read from the tool declaration's own `type` field, never inferred from which namespace it was declared under. - Function-tool JSON Schemas are dereferenced with `inlineJsonSchema`: plain, resolvable `$ref`/`$defs` (draft-07 `definitions` and 2020-12 `$defs`) are flattened into the inline schema and the pointer keys stripped entirely. A genuinely circular `$ref` degrades to `{type: "object"}` and is counted under the `circular_ref_flattened` degrade reason (see metrics below); a plain non-circular `$ref` is not. - Grammar/custom tools (Lark grammar, regex format) have no JSON Schema equivalent, so they are wrapped as a single `{input: string}` parameter, with the response mapped back to a `custom_tool_call` item. This is lossy and explicitly flagged in code, and is the shipped behavior — see "Sign-off status" below. - Reasoning effort (`minimal`/`low`/`medium`/`high`/`xhigh`/`max` on the Codex side) maps to an Anthropic thinking budget via `mapCodexReasoningToThinking`: low→4096, medium→8192, high→16384, xhigh→24576, max→32768, clamped to `[1024, max_tokens - 1024]`. Thinking is left off when `tool_choice` is forced, or when the immediately preceding assistant turn called a tool. - A non-object `function_call_output`/`custom_tool_call_output` argument falls back to `{input: raw}` in the translated history rather than failing the translation. Response translation (`codexResponsesFormat.ts` / `codexToAnthropicFallback.ts`) converts the Claude response — including SSE streaming — back into the Codex Responses wire shape the CLI expects, so a client cannot tell, from the wire alone, that its request was served by a different engine underneath. ### 9.5 Accounting A translated request is billed and recorded exactly like any other proxied request on the serving engine — the same OTel usage record, cache/reasoning buckets, and cost estimate described in [Usage accounting](#usage-accounting) (section 1) apply, attributed to the Anthropic or Vertex account that actually served it, not to a Codex account. There is no separate "fallback" ledger; look at the served-by account's own usage. The Codex route's final record names what served the turn: `provider`, `model`, `account` and `accountType` are the Claude target's, and `requestedModel` stays the Codex model the client asked for. With the Anthropic target, the loopback's own `/v1/messages` record owns the usage, and the Codex record points to it through `usageOwnerRequestId`, so the call is counted once. With Vertex there is no child record, so the Codex record carries the usage and is priced from the Vertex table. The translated request marks its stable prefix with a 1-hour cache TTL. 1-hour writes (`usage.cache_creation.ephemeral_1h_input_tokens`) are recorded as `cacheCreation1hTokens`, a subset of the cache-write total, and priced at 2x base input, Anthropic's 1-hour rate on every Claude model. The rest of the cache writes keep the 5-minute rate (1.25x). The token/cost metrics carry an `origin` attribute (`ProxyRequestOrigin`: `"native" | "codex-fallback"`), but **only when it is not `"native"`** — a plain Codex or Claude request emits the exact same label set it always has, with no `origin` key at all, so existing dashboards and alerts over these metrics are unaffected. Only a request actually served by this outbound-fallback path carries `origin="codex-fallback"`, set via `tracer.setRequestOrigin("codex-fallback")` once a target has been dispatched and will serve the turn (both the Anthropic-loopback and Vertex targets); a request whose every target fails keeps `"native"`. A Codex-outbound request served by a Vertex target is attributed as account `vertex/`, accountType `"vertex"` — the same shape the native Claude-to-Vertex fallback leg already reports, not a synthetic "codex" sentinel. ### 9.6 Metrics Two Codex-outbound-specific OTel counters, both emitted from `src/lib/proxy/proxyTracer.ts`: | Metric | Labels | Meaning | | ---------------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `proxy_codex_outbound_schema_degraded_total` | `{reason, toolName}` | A tool declaration's JSON Schema needed flattening or lost a feature on the way to a Claude tool. `reason` is one of `circular_ref_flattened` (a genuine cycle degraded to `{type:"object"}`) or `strict_mode_flag_dropped` (the Codex tool's `strict` flag has no Claude equivalent and was dropped). | | `proxy_codex_outbound_unsupported_field_total` | `{field}` | A Codex-outbound request field this repo cannot faithfully represent in the Claude request was dropped rather than failing the translation. | Every other proxy metric in the existing dashboard (`proxy_request_duration_ms`, `proxy_tokens_*`, `proxy_errors_total`, `proxy_fallback_attempts_total`, `proxy_fallback_success_total`, `proxy_fallback_failure_total`, …) also fires for a Codex-outbound-fallback request, on the serving engine, same as any other proxied call. **`proxy_cost_usd_total` is a cumulative counter, not a gauge.** Like every other `*_total` metric here, it is an OTel `Counter` — it only ever increases for the life of the process, and its value at any instant is the running sum since proxy start, not "cost since the last scrape" or "cost of the last request." Reading it as a point-in-time cost, or diffing two absolute reads without accounting for a process restart (which resets it to zero), produces a meaningless number. Compute a rate or a delta over the scrape interval when building a dashboard against it, and treat a lower absolute value after a restart as expected, not as a data-loss bug. ### 9.7 Sign-off status The following were flagged in the original design as behavior-changing choices needing product sign-off. All three were **signed off 2026-09-28** and ship as designed, not as placeholders awaiting approval: - The lossy grammar/custom-tool → single `{input: string}` parameter mapping (§9.4 above), with `custom_tool_call` on the way back. - The `{input: raw}` non-JSON-argument history fallback and its downstream effect on tool execution. - The reasoning-effort → thinking-budget table in §9.4 above. See `docs/superpowers/specs/2026-09-27-codex-outbound-fallback-design.md` for the full design record and rulings. ### 9.8 Live validation (after the Codex quota resets 2026-10-03) Everything above has been verified at the request/response **shape** level — translation correctness, config validation, metrics, loop-prevention logic — using synthetic and characterization fixtures (including a redacted real Codex CLI wire capture). None of it has been exercised against **live** Codex, Vertex or Anthropic traffic end to end, because the Codex account available to this work is quota-rejected until 2026-10-03. The validation plan's Part B live matrix (`stage-d-validation.md` §4) is the run to do once quota is back; its scenarios, unchanged from the plan: - [ ] **B1 — Cold start, single turn** (`gpt-5.6-sol` → Anthropic): if the Section-0 tool policy permits dispatch, `proxy_tokens_input` rises by roughly the translated prefix token count and `proxy_tokens_cache_creation` rises above 0; if the policy is fail-closed, a Codex-shaped diagnostic with no dispatch attempted is the correct, expected outcome — not a bug. - [ ] **B2 — Warm second turn, same session/account** (`gpt-5.6-sol` → Anthropic): confirm both turns were served by the same account (query `proxy_cost_usd_total`'s `account` label) before drawing any cache conclusion, then confirm `proxy_tokens_cache_read` rises by ≥80% of the prior turn's `cache_creation` delta with the second turn's own `cache_creation` delta near zero — the live proof that A.6's byte- stability requirement (already fixture-verified offline) holds against a real cache hop. - [ ] **B3 — Functions-namespace tool call** (`gpt-6-astra` → Anthropic): `read_file` alongside the ever-present `exec`/`request_review` collaboration tools; the client-visible stream carries a well-formed `function_call` the Codex CLI can execute, `proxy_fallback_success_total{provider='anthropic'}` increments by exactly 1, and there is no Anthropic 400 on the accompanying custom-tool schema. - [ ] **B4 — Parallel tool calls** (`gpt-6-astra` → Anthropic): both `function_call` items carry distinct `toolu_`-derived `call_id`s, and the real Codex CLI's next-turn `function_call_output` pair is accepted with no 400 — the live proof of the tool-id passthrough choice, and the check that would settle the design doc's `call_id` UNRESOLVED item. - [ ] **B5 — 6+ turn conversation crossing a fallback boundary mid-thread** (`gpt-5.6-terra` → Vertex): pre-boundary turns carry an Anthropic OAuth account, post-boundary turns a `vertex/` account shape, no protocol error at the boundary turn. - [ ] **B6 — Forced quota rejection** (`gpt-5.6-sol` → Anthropic): `proxy_fallback_attempts_total{provider='anthropic'}` increments; either success on the next leg, or a client-visible 429 that is still Codex-shaped, never a raw Anthropic error passed through. - [ ] **B7a/B7b — Mid-stream failure before/after first byte** (`gpt-5.6-terra` → Anthropic): B7a expects a clean fallback with no visible interruption; B7b expects the stream to terminate with an in-band Codex-shaped terminal frame, never a second provider's bytes appended to the same stream — the live proof of the commitment/loop- prevention rule (A.9/A.10). Also unresolved and needing this same live run to close (design doc §10, carried in `stage-d-validation.md` §6): - [ ] **UNRESOLVED-1 — reasoning wire shape**: the exact Codex Responses wire shape for a reasoning output item is not established anywhere in this repo's types, fixtures, or the redacted reference sample; settle it with a live capture of a real `reasoning.effort` turn (part of B1-B4 above). - [ ] **UNRESOLVED-2 — `call_id` server-side validation**: whether the real ChatGPT Codex backend validates `function_call.call_id` format server-side; the check that settles it is B4 above. - [ ] **UNRESOLVED-3 — §0 policy fail-closed vs. lossy**: whether the chosen `additional_tools.collaboration` policy is fail-closed or lossy in practice against a live backend — every one of B1-B7b inherently exercises this, since `exec` rides along on every real Codex request regardless of what the operator typed; a fail-closed observation on all seven is a valid, expected outcome under that policy, not a failure. Once Part B runs, Part C (`stage-d-validation.md` §5) — the red-green defect injection matrix — should also be run once, live, in addition to the offline runs already exercised by this stage's test suites, to confirm rows 5-8 (trigger-policy totality, loop prevention, commitment rule, and the `additional_tools.collaboration` mishandling case) fail the way the table predicts against a real backend, not only against fixtures. Until these run, treat the outbound-fallback feature as shape-verified and unit/characterization-tested, not production-validated — which is also why the kill switch defaults to off. --- ## Per-request context budget # Per-request context budget Context compaction has always triggered at a fixed 80% of the model's window. That number is now a default, not a constant: a per-request `compactionThreshold` option lowers it for requests that need less room, and the [classifier router's](/docs/features/classifier-router) `jev` strategy can fill it in automatically by asking how much of the conversation the request actually needs. **The degradation contract.** Every input here is optional. With no `compactionThreshold` passed and no classifier router configured, the effective threshold is exactly `0.8`, exactly as before — `resolveHistoryBudget()`'s scale factor is `compactionThreshold / 0.8`, so the default value reproduces the previous budget calculation to the token. ## Setting it directly ```typescript const nl = new NeuroLink(); await nl.generate({ input: { text: "Summarize this one file." }, compactionThreshold: 0.45, // this request needs very little history }); ``` CLI: `neurolink generate "..." --compaction-threshold 0.45` (existing flag, `description: "Fraction of the context window (0-1) at which history is compacted. Default 0.8."`). ## Letting the classifier fill it in When `classifierRouter.contextBudget` is enabled (default: **true** whenever the strategy resolves to a decision model; ignored by `heuristic`/`llm`), the same `jev` request that classifies difficulty also asks a `score` question: > How much of the earlier conversation does answering this request actually > require? against a four-level rubric: | Scope | Criterion | Threshold | | ------------------- | -------------------------------------------------------------------------------------------------- | --------- | | `current-message` | Self-contained. Earlier conversation would not change the answer. | 0.45 | | `recent-turns` | Needs the last few exchanges — a follow-up, a correction, a reference to something just discussed. | 0.60 | | `full-conversation` | Needs the whole conversation, including decisions and constraints established much earlier. | 0.75 | | `everything` | Needs the conversation and every document, file and tool result that has been gathered. | 0.80 | This is a rubric, not a token count, and deliberately so: a decision model places a request on an ordered scale reliably and reads digit strings as text, not quantities — asking "how many tokens does this need" would get an answer shaped like a guess at a number, not a calibrated judgement. The reading is used only above `MIN_CONTEXT_SCOPE_CONFIDENCE` (0.5); below that, `contextScope` is left `undefined` and the request falls back to the 0.8 default exactly as if the question had not been asked. The scope judgement is independent of the difficulty tier — a trivial request can still need the whole conversation, and an expert one can be entirely self-contained — so it is read and applied on its own, and survives every path on which the difficulty verdict itself is discarded by its confidence bar. `applyClassifierRouting()` then applies the derived threshold only when the **caller left `compactionThreshold` unset**: ```ts if ( decision.compactionThreshold !== undefined && options.compactionThreshold === undefined ) { options.compactionThreshold = decision.compactionThreshold; } ``` An explicit per-call value always wins. The classifier is filling in a default you didn't set, never overriding one you did. ## The one-directional invariant The mapping from scope to threshold **can only ever lower the 0.8 default, never raise it**, and this is enforced independently at two layers: 1. `contextScopeToThreshold()` clamps its result with `Math.min(0.8, ...)` before returning. 2. `ClassifierRouter.selectContextBudget()` re-checks the result and discards it unless `threshold < 0.8`. The reason this is a hard invariant rather than a tuning choice: shrinking a budget merely compacts a little earlier than strictly necessary — the model still answers correctly with slightly less history than it could have used. Growing one lets a request through that the provider then rejects with a context-window error, and `ModelPool` treats that as a **permanent (10-year) cooldown** — one optimistic guess retires the model for the life of the process. Getting this wrong in one direction is recoverable; getting it wrong in the other is not, so the code refuses to let a bug make that mistake even once. ## How the threshold changes the actual budget `resolveHistoryBudget()` is what the compactor targets — the model's available input space minus system prompt, current prompt, tool definitions and file attachments, all of which ride alongside history rather than being part of it. The per-request threshold scales that budget directly: ```ts const scale = Math.max( 0, Math.min(1, compactionThreshold / DEFAULT_COMPACTION_THRESHOLD), ); const factor = HISTORY_BUDGET_SAFETY_FACTOR * scale; // 0.95 * scale ``` With the default `0.8`, `scale` is exactly `1` and the budget is unchanged from before this option existed. A `0.4` threshold halves the history budget. The `0.95` safety factor is unrelated to this feature — it exists because token estimation is character-based and approximate, so the compactor always aims slightly under the true ceiling. ## What this is bad at - **It is a suggestion, not a measurement.** The rubric asks "how much would a human say this needs," not "how many tokens will this actually consume." A request correctly judged `recent-turns` can still occasionally need one detail from much earlier — the invariant above is what keeps that failure mode cheap (a slightly early compaction) rather than catastrophic. - **One judgement per request, not per turn of the conversation that follows.** If the classifier runs once per turn (which it does), the scope can change turn to turn, but there's no persistence of "this whole session is a `current-message` session" — a caller who wants that stability should pass `compactionThreshold` explicitly rather than rely on `auto`. - **It shares the base model's limits.** Everything in [what `decide` is bad at](/docs/features/decide-inference-type#what-it-is-bad-at) applies — including that irrelevant state costs accuracy, so a very long prompt slice can degrade the scope reading itself. - **No feedback loop.** If the classifier's `current-message` guess turns out wrong and the model asks a follow-up that needed history you already dropped, nothing here recovers that turn; the invariant only bounds the cost of the guess, it doesn't undo it. ## See also - [Model routing with a decision model](/docs/features/classifier-router-jev-strategy) - [Relevance-driven compaction](/docs/features/relevance-compaction) - [The `decide` inference type](/docs/features/decide-inference-type) --- ## Context Compaction # Context Compaction ## Overview NeuroLink's Context Compaction system automatically manages conversation context windows, preventing overflow errors and maintaining conversation quality as sessions grow longer. It runs transparently before every `generate()` and `stream()` call. Before each LLM call, the **Budget Checker** estimates the total input tokens needed (system prompt + conversation history + current prompt + tool definitions + file attachments) and compares them against the model's available context window. When usage exceeds the configured threshold (default: 80%), the **ContextCompactor** runs a 5-stage reduction pipeline: 0. **Relevance Drop** — Ask a decision model which earlier messages the current request still needs (needs a decision provider; skipped without one) 1. **Tool Output Pruning** — Replace old tool results with placeholders (cheapest, no LLM call) 2. **File Read Deduplication** — Keep only the latest read of each file (cheap, no LLM call) 3. **LLM Summarization** — Structured 10-section summary of older messages (expensive, requires LLM call) 4. **Sliding Window Truncation** — Remove oldest messages while preserving the first exchange (fallback, no LLM call) If a provider still returns a context overflow error after compaction, the system detects it across all supported providers and retries with aggressive compaction. ## SDK Configuration The full `contextCompaction` block lives inside `conversationMemory`: ```typescript const neurolink = new NeuroLink({ conversationMemory: { enabled: true, enableSummarization: true, summarizationProvider: "vertex", // Provider for summarization LLM calls summarizationModel: "gemini-2.5-flash", // Model for summarization LLM calls replayToolSteps: "marker", // How stored tool steps are replayed on later turns — see below contextCompaction: { enabled: true, // Enable auto-compaction (default: true when summarization enabled) threshold: 0.8, // Compaction trigger threshold, 0.0–1.0 (default: 0.80) enablePruning: true, // Enable Stage 1: tool output pruning (default: true) enableDeduplication: true, // Enable Stage 2: file read deduplication (default: true) enableSlidingWindow: true, // Enable Stage 4: sliding window fallback (default: true) maxToolOutputBytes: 50 * 1024, // Tool output max size in bytes (default: 51200) maxToolOutputLines: 2000, // Tool output max lines (default: 2000) fileReadBudgetPercent: 0.6, // File read budget as fraction of remaining context (default: 0.60) }, }, }); ``` | Field | Type | Default | Description | | ----------------------- | --------- | ----------------------------------- | ------------------------------------------------------ | | `enabled` | `boolean` | `true` (when summarization enabled) | Master switch for auto-compaction | | `threshold` | `number` | `0.80` | Usage ratio (0.0–1.0) that triggers compaction | | `enablePruning` | `boolean` | `true` | Enable Stage 1: tool output pruning | | `enableDeduplication` | `boolean` | `true` | Enable Stage 2: file read deduplication | | `enableSlidingWindow` | `boolean` | `true` | Enable Stage 4: sliding window truncation fallback | | `maxToolOutputBytes` | `number` | `51200` (50 KB) | Maximum tool output size in bytes before truncation | | `maxToolOutputLines` | `number` | `2000` | Maximum tool output lines before truncation | | `fileReadBudgetPercent` | `number` | `0.60` | Fraction of remaining context allocated for file reads | --- ## Environment Variables These environment variables configure conversation memory and summarization, which in turn affect compaction behavior: | Variable | Default | Description | | ---------------------------------- | --------------------------- | ----------------------------------------------------- | | `NEUROLINK_MEMORY_ENABLED` | `"false"` | Set to `"true"` to enable conversation memory | | `NEUROLINK_SUMMARIZATION_ENABLED` | `"true"` | Set to `"false"` to disable summarization | | `NEUROLINK_TOKEN_THRESHOLD` | auto (80% of model context) | Override token threshold for triggering summarization | | `NEUROLINK_SUMMARIZATION_PROVIDER` | `"vertex"` | Provider for summarization LLM calls | | `NEUROLINK_SUMMARIZATION_MODEL` | `"gemini-2.5-flash"` | Model for summarization LLM calls | | `NEUROLINK_MEMORY_MAX_SESSIONS` | `50` | Maximum number of sessions to keep in memory | Source: `src/lib/config/conversationMemory.ts` --- ## Replaying Tool Steps on Later Turns Every tool call a turn makes is stored in the session as a `tool_call` / `tool_result` pair — on both the in-memory and Redis backends, and for `generate()` as well as `stream()`. `replayToolSteps` decides how those rows reach the model on the session's later turns: | Mode | What the model sees on the next turn | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `"marker"` | **Default.** One compact line per call, folded into the assistant turn: `[called lookup_order → ok]`, `→ error` when the call threw, was rejected or returned an error-shaped result (`isError: true`, an `error` field, or a failing `status`), or `→ unknown` when the result was lost to compaction. | | `"full"` | The real tool call and its output, as tool-call / tool-result turns in the provider's own wire shape. A failed call's output carries the error text. | | `"off"` | Tool rows are dropped from the prompt; only the surface user / assistant text is replayed. | Set it on the instance, or per request (the request wins): ```typescript const neurolink = new NeuroLink({ conversationMemory: { enabled: true, replayToolSteps: "full" }, }); await neurolink.generate({ input: { text: "And which carrier?" }, context: { sessionId }, replayToolSteps: "marker", // this turn only }); ``` CLI loop sessions accept the same knob: `/set replayToolSteps full`. What to know before choosing `"full"`: - **Only paired rows are replayed.** A call whose result never arrived (or the reverse) is dropped, because Anthropic and OpenAI reject an orphaned tool call / result outright. When compaction or a history slice leaves a call without its result, the memory layer's pair repair fills the gap with a placeholder result: the marker then reads `→ unknown` and `"full"` replays the placeholder text (`[Tool result unavailable - conversation was compacted]`), never a fabricated outcome. A result whose call was lost is dropped altogether — the model never made that call. - **A request that declares no tools degrades `"full"` to `"marker"`.** With `disableTools: true`, or a `toolFilter` that removes every tool, Anthropic rejects a prompt that carries tool blocks without a `tools` field, so such a turn is sent with markers instead. - **Steps stay sequential.** `generate()` stores one batch per loop step and the rows carry `stepIndex`, so a `lookup` followed by a `send` built from its output replays as two steps, not one parallel call. - **Tokens.** Each replayed step costs its arguments and output on every later turn of the session. The replay reads the `tool_result` content as the memory layer returns it, so Stage 1 pruning and the Redis backend's `sendToolPreview` (`maxToolOutputBytes` / `maxToolOutputLines`) both apply before a result is replayed. - **Prompt caching.** On Anthropic the replayed blocks sit inside `messages`, ahead of the rolling history breakpoints, so a session that switches modes mid-way changes its cached prefix. Pick a mode per session, not per turn, when cache hits matter. - **Native replay is unchanged.** Claude-on-Vertex and Gemini already replay tool steps from the stored rows in their own wire shape and do not go through this option; it governs the direct Anthropic, OpenAI-compatible and SageMaker `generate()` / `stream()` paths. On Amazon Bedrock only a turn that carries images or files goes through the shared history builder (where `"full"` degrades to `"marker"`, since that path cannot carry tool turns); a text-only Bedrock turn sends the current prompt without stored history, so no mode applies to it. SageMaker's `stream()` sends no tools at all, so `tools`, `toolChoice` and `prepareStep` apply to its `generate()` only. - **Context budget.** Tool rows are stored at full size, but the budget check and the summarization trigger size them the way the chosen mode sends them — one line per call under `"marker"`, nothing under `"off"` — so the default mode no longer triggers summarization on tool output the model never receives. This covers every budget check on the `generate()` and `stream()` paths, including the post-compaction and post-truncation re-checks. It does **not** yet reach the compaction stages themselves: once compaction runs, Stage 1 pruning, Stage 3 summarization and Stage 4 truncation still measure tool rows at stored size, so under `"marker"` or `"off"` a stage may prune or summarize more history than the prompt would have carried. Threading the mode into the compactor is a follow-up. --- ## CLI Flags The `loop` command accepts compaction-specific flags: ```bash # Set a custom compaction threshold (0.0–1.0) neurolink loop --compact-threshold 0.70 # Disable automatic context compaction entirely neurolink loop --disable-compaction ``` | Flag | Type | Default | Description | | ---------------------- | --------- | ------- | ---------------------------------------------- | | `--compact-threshold` | `number` | `0.8` | Context compaction trigger threshold (0.0–1.0) | | `--disable-compaction` | `boolean` | `false` | Disable automatic context compaction | Source: `src/cli/factories/commandFactory.ts:1466-1475` --- ## Public API Methods ### `getContextStats(sessionId, provider?, model?)` Get context usage statistics for a session. Returns token counts, usage ratio, and whether compaction should trigger. **Signature:** ```typescript async getContextStats( sessionId: string, provider?: string, model?: string, ): Promise ``` Returns `null` if conversation memory is not enabled or the session has no messages. The `provider` defaults to `"openai"` if not specified. **Example:** ```typescript const stats = await neurolink.getContextStats( "session-1", "anthropic", "claude-sonnet-4-20250514", ); if (stats) { console.log(`Usage: ${(stats.usageRatio * 100).toFixed(0)}%`); console.log( `Tokens: ${stats.estimatedInputTokens} / ${stats.availableInputTokens}`, ); console.log(`Messages: ${stats.messageCount}`); console.log(`Needs compaction: ${stats.shouldCompact}`); } ``` Source: `src/lib/neurolink.ts:6624-6661` --- ### `compactSession(sessionId, config?)` Manually trigger context compaction for a session. Runs the full 5-stage pipeline. After compaction, tool pairs are automatically repaired via `repairToolPairs()`. **Signature:** ```typescript async compactSession( sessionId: string, config?: CompactionConfig, ): Promise ``` Returns `null` if conversation memory is not enabled or the session has no messages. **Example:** ```typescript const result = await neurolink.compactSession("session-1", { enablePrune: true, enableDeduplicate: true, enableSummarize: true, enableTruncate: true, // Stage 0 has no switch: it runs when a decision caller is injected and is // skipped when one is not, so there is no configuration in which it can // change behaviour on its own. pruneProtectTokens: 40_000, summarizationProvider: "vertex", summarizationModel: "gemini-2.5-flash", }); if (result?.compacted) { console.log(`Stages used: ${result.stagesUsed.join(", ")}`); console.log(`Tokens saved: ${result.tokensSaved}`); console.log(`Before: ${result.tokensBefore}, After: ${result.tokensAfter}`); } ``` Source: `src/lib/neurolink.ts:6591-6618` --- ### `needsCompaction(sessionId, provider?, model?)` Synchronous check of whether a session needs compaction. Uses `checkContextBudget()` internally with the default 80% threshold. **Signature:** ```typescript needsCompaction( sessionId: string, provider?: string, model?: string, ): boolean ``` Returns `false` if conversation memory is not enabled or the session doesn't exist. The `provider` defaults to `"openai"` if not specified. **Example:** ```typescript if ( neurolink.needsCompaction( "session-1", "anthropic", "claude-sonnet-4-20250514", ) ) { const result = await neurolink.compactSession("session-1"); console.log(`Saved ${result?.tokensSaved} tokens`); } ``` Source: `src/lib/neurolink.ts:6666-6692` --- ## Types Reference ### `CompactionStage` ```typescript type CompactionStage = "prune" | "deduplicate" | "summarize" | "truncate"; ``` ### `CompactionResult` Returned by `compactSession()` and `ContextCompactor.compact()`. ```typescript type CompactionResult = { compacted: boolean; // Whether any compaction was applied stagesUsed: CompactionStage[]; // Which stages were used (in order) tokensBefore: number; // Estimated tokens before compaction tokensAfter: number; // Estimated tokens after compaction tokensSaved: number; // tokensBefore - tokensAfter messages: ChatMessage[]; // The compacted message array }; ``` ### `CompactionConfig` Optional configuration passed to `compactSession()` or the `ContextCompactor` constructor. ```typescript type CompactionConfig = { enablePrune?: boolean; // Enable Stage 1 (default: true) enableDeduplicate?: boolean; // Enable Stage 2 (default: true) enableSummarize?: boolean; // Enable Stage 3 (default: true) enableTruncate?: boolean; // Enable Stage 4 (default: true) pruneProtectTokens?: number; // Recent tool output tokens to protect (default: 40,000) pruneMinimumSavings?: number; // Minimum tokens saved to declare pruning success (default: 20,000) pruneProtectedTools?: string[]; // Tool names that are never pruned (default: ["skill"]) summarizationProvider?: string; // Provider for summarization LLM (default: "vertex") summarizationModel?: string; // Model for summarization LLM (default: "gemini-2.5-flash") keepRecentRatio?: number; // Fraction of messages to keep unsummarized (default: 0.3) truncationFraction?: number; // Fraction of oldest messages to remove in Stage 4 (default: 0.5) provider?: string; // Provider name for token estimation multipliers (default: "") }; ``` Source: `src/lib/context/contextCompactor.ts:37-65` ### `BudgetCheckResult` Returned by `checkContextBudget()`. ```typescript type BudgetCheckResult = { withinBudget: boolean; // Whether the request fits within the context window estimatedInputTokens: number; // Estimated total input tokens availableInputTokens: number; // Available input tokens for this model usageRatio: number; // Usage ratio (0.0–1.0+) shouldCompact: boolean; // Whether auto-compaction should trigger breakdown: { systemPrompt: number; // Tokens from system prompt conversationHistory: number; // Tokens from conversation history currentPrompt: number; // Tokens from current user prompt toolDefinitions: number; // Tokens from tool definitions (content-based: JSON.stringify(tool).length / 4) fileAttachments: number; // Tokens from file attachments }; }; ``` ### `BudgetCheckParams` Parameters for `checkContextBudget()`. ```typescript type BudgetCheckParams = { provider: string; model?: string; maxTokens?: number; systemPrompt?: string; conversationMessages?: Array; currentPrompt?: string; toolDefinitions?: unknown[]; fileAttachments?: Array; compactionThreshold?: number; // 0.0–1.0, default: 0.80 }; ``` Source: `src/lib/context/budgetChecker.ts:18-54` --- ## The 5-Stage Pipeline The `ContextCompactor` runs stages sequentially. Each stage only runs if the previous stage didn't bring tokens below the target budget. | # | Stage | `CompactionStage` | Needs a decision model | | --- | ------------------------- | ----------------- | -------------------------------------- | | 0 | Relevance drop | `relevance` | **yes** — skipped entirely without one | | 1 | Tool output pruning | `prune` | no | | 2 | File read deduplication | `deduplicate` | no | | 3 | LLM summarization | `summarize` | no (its _gate_ uses one) | | 4 | Sliding window truncation | `truncate` | no | `result.stagesUsed` reports the ones that actually ran, in order. ### Stage 0: Relevance drop **File:** `src/lib/context/contextDecision.ts` Everything below Stage 0 is chronological: the pipeline's only notion of "droppable" is "old". Stage 0 is the one stage that asks what a message is _for_ — one boolean per message ("is this needed to answer the current request?") in a single batch. On TypeSafe that costs the same for 200 messages as for one because decision latency is flat in question count; on Perplexity each further question adds about 65 ms and a request takes at most 128 (see [its guide](/docs/getting-started/providers/perplexity-decider.md#limits)); on Cloudflare Clef a request takes at most 64 questions, which `tryDecide()` splits into batches of 64 (see [its guide](/docs/getting-started/providers/cloudflare-clef.md#limits)); OpenAI Decisions takes at most 200 questions (the figure in OpenAI's Python SDK; going over it was not tried against the live endpoint), which `tryDecide()` splits into batches of 200, so a 300-message set goes out as two requests, with the state sent on each (see [its guide](/docs/getting-started/providers/openai-decisions.md#what-is-sent-to-openai)); ScaleDown declares no question cap, and its maximum is not measured (see [its guide](/docs/getting-started/providers/scaledown.md#not-measured)). The 16,000-token refusal is Cloudflare Clef's own: NeuroLink refuses a state it estimates at more than 16,000 tokens (about 60,000 characters of prose) there, so a longer set of eligible messages gets a refusal and the stage is skipped, as on any failure. A provider that declares no state limit, ScaleDown included, is sent the whole state, which this stage bounds only at 300 messages of at most 1,200 characters each. It is **strictly additive**. With no decision provider configured the stage does not run, `stagesUsed` omits `relevance`, and the pipeline behaves exactly as the four-stage one always did. It is also bounded by `maxDropRatio` and walks oldest-first, so when the cap binds it spares the newest candidates — the same recency assumption every other stage makes. ### The summary gate Stage 3 used to accept **any non-empty string** as a summary. When a decision model is configured, the generated summary is now checked first ("does this preserve every decision and open question?") and a rejected summary leaves the messages untouched so a later stage can try instead. The rejection is recorded on the span as `compaction.stage3.summaryRejected`, because a gate that silently discarded work would be indistinguishable from one that never ran. Rejection is deliberately rare: the gate exists to catch a summary that lost a decision, not to second-guess wording. ### Stage 1: Tool Output Pruning **File:** `src/lib/context/stages/toolOutputPruner.ts` Walks messages backwards, protecting the most recent tool outputs, and replaces older tool results with `"[Tool result cleared]"`. ```typescript function pruneToolOutputs( messages: ChatMessage[], config?: PruneConfig, ): PruneResult; ``` **`PruneConfig`:** | Field | Type | Default | Description | | ---------------- | ---------- | ----------- | ----------------------------------------------------------- | | `protectTokens` | `number` | `40,000` | Token budget of recent tool outputs to protect from pruning | | `minimumSavings` | `number` | `20,000` | Minimum tokens that must be saved for pruning to be applied | | `protectedTools` | `string[]` | `["skill"]` | Tool names that are never pruned | | `provider` | `string` | — | Provider name for token estimation multiplier | **`PruneResult`:** ```typescript type PruneResult = { pruned: boolean; // Whether pruning was applied (savings >= minimumSavings) messages: ChatMessage[]; tokensSaved: number; }; ``` ### Stage 2: File Read Deduplication **File:** `src/lib/context/stages/fileReadDeduplicator.ts` Detects multiple reads of the same file path. Keeps only the latest read, replaces earlier reads with `"[File - refer to latest read below]"`. ```typescript function deduplicateFileReads(messages: ChatMessage[]): DeduplicationResult; ``` **`DeduplicationResult`:** ```typescript type DeduplicationResult = { deduplicated: boolean; // Whether dedup was applied (requires 30%+ savings) messages: ChatMessage[]; filesDeduped: number; // Number of unique files that had duplicates removed }; ``` File read detection uses the regex pattern: `/(?:read|reading|read_file|readFile|Read file|cat)\s+['"`]?([^\s'"`\n]+)/i` A 30% savings threshold (`DEDUP_THRESHOLD = 0.3`) must be met for deduplication to be applied. ### Stage 3: LLM Summarization **File:** `src/lib/context/stages/structuredSummarizer.ts` Uses the structured 10-section prompt to summarize older messages while keeping recent ones. Delegates to `generateSummary()` from the conversation memory system. ```typescript async function summarizeMessages( messages: ChatMessage[], config?: SummarizeConfig, ): Promise; ``` **`SummarizeConfig`:** | Field | Type | Default | Description | | ----------------- | ----------------------------------- | ------- | ------------------------------------------------------ | | `provider` | `string` | — | Provider for the summarization LLM call | | `model` | `string` | — | Model for the summarization LLM call | | `keepRecentRatio` | `number` | `0.3` | Fraction of messages to keep unsummarized (minimum: 4) | | `memoryConfig` | `Partial` | — | Memory config passed to `generateSummary()` | **`SummarizeResult`:** ```typescript type SummarizeResult = { summarized: boolean; messages: ChatMessage[]; // [summaryMessage, ...recentMessages] summaryText?: string; // Raw summary text }; ``` Behavior: - Will not summarize if there are 4 or fewer messages - Keeps at least 4 recent messages (or `keepRecentRatio` of total, whichever is greater) - Finds and incorporates any previous summary message for iterative merging - Summary message is inserted as a `system` role message with `metadata.isSummary = true` - If summarization fails (LLM error), the pipeline silently falls through to Stage 4 ### Stage 4: Sliding Window Truncation **File:** `src/lib/context/stages/slidingWindowTruncator.ts` Non-destructive fallback that removes the oldest messages from the middle of the conversation while always preserving the first user-assistant pair. ```typescript function truncateWithSlidingWindow( messages: ChatMessage[], config?: TruncationConfig, ): TruncationResult; ``` **`TruncationConfig`:** | Field | Type | Default | Description | | ---------- | -------- | ------- | ------------------------------------------------- | | `fraction` | `number` | `0.5` | Fraction of messages (after first pair) to remove | **`TruncationResult`:** ```typescript type TruncationResult = { truncated: boolean; messages: ChatMessage[]; // [firstPair..., truncationMarker, ...keptMessages] messagesRemoved: number; // Always an even number (maintains role alternation) }; ``` Behavior: - Will not truncate if there are 4 or fewer messages - Always preserves the first 2 messages (first user-assistant pair) - Removes an even number of messages to maintain role alternation - Inserts a `system` role truncation marker: `"[Earlier conversation history was truncated to fit within context limits]"` --- ## ChatMessage Compaction Fields The `ChatMessage` type has five fields used for non-destructive context management: ```typescript type ChatMessage = { // ... standard fields ... condenseId?: string; // UUID identifying this condensation group condenseParent?: string; // Points to the summary that replaces this message truncationId?: string; // UUID identifying this truncation group truncationParent?: string; // Points to the truncation marker that hides this message isTruncationMarker?: boolean; // Marks this message as a truncation boundary marker }; ``` | Field | Purpose | | -------------------- | ----------------------------------------------------------------------------- | | `condenseId` | Set on the summary message. Groups all messages that were condensed together. | | `condenseParent` | Set on original messages. Points to the `condenseId` of their summary. | | `truncationId` | Set on the truncation marker. Groups all messages hidden by this truncation. | | `truncationParent` | Set on original messages. Points to the `truncationId` of their marker. | | `isTruncationMarker` | `true` on the synthetic marker message inserted where messages were removed. | Messages with `condenseParent` or `truncationParent` are filtered out by `getEffectiveHistory()` but remain in storage for potential rewind. Source: `src/lib/types/conversation.ts:270-279` --- ## Non-Destructive History **File:** `src/lib/context/effectiveHistory.ts` Messages are tagged rather than deleted, allowing compaction to be unwound. ### `getEffectiveHistory(messages)` Returns only visible messages by filtering out those with `condenseParent` or `truncationParent`. ```typescript function getEffectiveHistory(messages: ChatMessage[]): ChatMessage[]; ``` ### `tagForCondensation(messages, fromIndex, toIndex, condenseId)` Tags messages in `[fromIndex, toIndex)` with a `condenseParent` pointing to `condenseId`. ```typescript function tagForCondensation( messages: ChatMessage[], fromIndex: number, toIndex: number, condenseId: string, ): ChatMessage[]; ``` ### `tagForTruncation(messages, fromIndex, toIndex, truncationId)` Tags messages in `[fromIndex, toIndex)` with a `truncationParent` pointing to `truncationId`. ```typescript function tagForTruncation( messages: ChatMessage[], fromIndex: number, toIndex: number, truncationId: string, ): ChatMessage[]; ``` ### `removeCondensationTags(messages, condenseId)` Removes `condenseParent` tags from messages matching `condenseId`, making them visible again. Also removes the summary message itself (matched by `condenseId` + `metadata.isSummary`). ```typescript function removeCondensationTags( messages: ChatMessage[], condenseId: string, ): ChatMessage[]; ``` ### `removeTruncationTags(messages, truncationId)` Removes `truncationParent` tags from messages matching `truncationId`, making them visible again. Also removes the truncation marker itself (matched by `truncationId` + `isTruncationMarker`). ```typescript function removeTruncationTags( messages: ChatMessage[], truncationId: string, ): ChatMessage[]; ``` --- ## Token Estimation **File:** `src/lib/utils/tokenEstimation.ts` Character-based token estimation with per-provider adjustment multipliers. Uses the same approach as Continue (GPT-tokenizer baseline + provider multipliers) without requiring a tokenizer dependency. ### Constants | Constant | Value | Description | | ------------------------- | ------ | ------------------------------------------------------ | | `CHARS_PER_TOKEN` | `4` | Characters per token for English text | | `CODE_CHARS_PER_TOKEN` | `3` | Characters per token for code | | `TOKEN_SAFETY_MARGIN` | `1.15` | Safety margin multiplier to avoid underestimation | | `TOKENS_PER_MESSAGE` | `4` | Message framing overhead in tokens (role + delimiters) | | `TOKENS_PER_CONVERSATION` | `24` | Conversation-level overhead in tokens | | `IMAGE_TOKEN_ESTIMATE` | `1024` | Flat token estimate for images | ### Provider Multipliers Applied on top of the base character estimate: | Provider | Multiplier | Notes | | ------------- | ---------- | --------------------------------------------- | | `anthropic` | `1.23` | Anthropic tokenizer produces ~23% more tokens | | `google-ai` | `1.18` | Google AI Studio | | `vertex` | `1.18` | Google Vertex AI | | `mistral` | `1.26` | Mistral / Codestral | | `openai` | `1.0` | Baseline (GPT-style) | | `azure` | `1.0` | Same tokenizer as OpenAI | | `bedrock` | `1.23` | Mostly Anthropic models | | `ollama` | `1.0` | | | `litellm` | `1.0` | | | `huggingface` | `1.0` | | | `sagemaker` | `1.0` | | ### Functions **`estimateTokens(text, provider?, isCode?)`** Estimate token count for a string. ```typescript function estimateTokens( text: string, provider?: string, isCode?: boolean, ): number; ``` Formula: `ceil(text.length / charsPerToken) * providerMultiplier * TOKEN_SAFETY_MARGIN` **`estimateMessagesTokens(messages, provider?)`** Estimate total token count for an array of messages, including per-message overhead and conversation-level overhead. ```typescript function estimateMessagesTokens( messages: Array, provider?: string, ): number; ``` **`truncateToTokenBudget(text, maxTokens, provider?)`** Truncate text to fit within a token budget. Tries to cut at sentence or word boundaries. Appends `"..."` if truncated. ```typescript function truncateToTokenBudget( text: string, maxTokens: number, provider?: string, ): { text: string; truncated: boolean }; ``` --- ## Context Window Registry **File:** `src/lib/constants/contextWindows.ts` ### Constants | Constant | Value | Description | | ------------------------------ | --------- | --------------------------------------------- | | `DEFAULT_CONTEXT_WINDOW` | `128,000` | Fallback when provider/model is unknown | | `MAX_DEFAULT_OUTPUT_RESERVE` | `64,000` | Maximum output reserve when maxTokens not set | | `DEFAULT_OUTPUT_RESERVE_RATIO` | `0.35` | Default output reserve as fraction of context | ### Functions **`getContextWindowSize(provider, model?)`** Resolve context window size. Priority: exact model match > provider `_default` > global `DEFAULT_CONTEXT_WINDOW`. Also supports partial model name prefix matching. ```typescript function getContextWindowSize(provider: string, model?: string): number; ``` **`getAvailableInputTokens(provider, model?, maxTokens?)`** Calculate available input tokens: `contextWindow - outputReserve`. ```typescript function getAvailableInputTokens( provider: string, model?: string, maxTokens?: number, ): number; ``` **`getOutputReserve(contextWindow, maxTokens?)`** Calculate output token reserve. Uses explicit `maxTokens` if provided, otherwise `min(MAX_DEFAULT_OUTPUT_RESERVE, contextWindow * DEFAULT_OUTPUT_RESERVE_RATIO)`. ```typescript function getOutputReserve(contextWindow: number, maxTokens?: number): number; ``` ### `MODEL_CONTEXT_WINDOWS` Complete per-provider, per-model context window registry: | Provider | Model | Context Window | | --------------- | ------------------------------------------- | -------------- | | **anthropic** | `_default` | 200,000 | | | `claude-opus-4-20250514` | 200,000 | | | `claude-sonnet-4-20250514` | 200,000 | | | `claude-3-7-sonnet-20250219` | 200,000 | | | `claude-3-5-sonnet-20241022` | 200,000 | | | `claude-3-5-haiku-20241022` | 200,000 | | | `claude-3-opus-20240229` | 200,000 | | | `claude-3-sonnet-20240229` | 200,000 | | | `claude-3-haiku-20240307` | 200,000 | | **openai** | `_default` | 128,000 | | | `gpt-4o` | 128,000 | | | `gpt-4o-mini` | 128,000 | | | `gpt-4-turbo` | 128,000 | | | `gpt-4` | 8,192 | | | `gpt-3.5-turbo` | 16,385 | | | `o1` | 200,000 | | | `o1-mini` | 128,000 | | | `o1-pro` | 200,000 | | | `o3` | 200,000 | | | `o3-mini` | 200,000 | | | `o4-mini` | 200,000 | | | `gpt-4.1` | 1,047,576 | | | `gpt-4.1-mini` | 1,047,576 | | | `gpt-4.1-nano` | 1,047,576 | | | `gpt-5` | 1,047,576 | | **google-ai** | `_default` | 1,048,576 | | | `gemini-2.5-pro` | 1,048,576 | | | `gemini-2.5-flash` | 1,048,576 | | | `gemini-2.0-flash` | 1,048,576 | | | `gemini-1.5-pro` | 2,097,152 | | | `gemini-1.5-flash` | 1,048,576 | | | `gemini-3-flash-preview` | 1,048,576 | | | `gemini-3-pro-preview` | 1,048,576 | | **vertex** | `_default` | 1,048,576 | | | `gemini-2.5-pro` | 1,048,576 | | | `gemini-2.5-flash` | 1,048,576 | | | `gemini-2.0-flash` | 1,048,576 | | | `gemini-1.5-pro` | 2,097,152 | | | `gemini-1.5-flash` | 1,048,576 | | **bedrock** | `_default` | 200,000 | | | `anthropic.claude-3-5-sonnet-20241022-v2:0` | 200,000 | | | `anthropic.claude-3-5-haiku-20241022-v1:0` | 200,000 | | | `anthropic.claude-3-opus-20240229-v1:0` | 200,000 | | | `anthropic.claude-3-sonnet-20240229-v1:0` | 200,000 | | | `anthropic.claude-3-haiku-20240307-v1:0` | 200,000 | | | `amazon.nova-pro-v1:0` | 300,000 | | | `amazon.nova-lite-v1:0` | 300,000 | | **azure** | `_default` | 128,000 | | | `gpt-4o` | 128,000 | | | `gpt-4o-mini` | 128,000 | | | `gpt-4-turbo` | 128,000 | | | `gpt-4` | 8,192 | | **mistral** | `_default` | 128,000 | | | `mistral-large-latest` | 128,000 | | | `mistral-medium-latest` | 32,000 | | | `mistral-small-latest` | 128,000 | | | `codestral-latest` | 256,000 | | **ollama** | `_default` | 128,000 | | **litellm** | `_default` | 128,000 | | **huggingface** | `_default` | 32,000 | | **sagemaker** | `_default` | 128,000 | --- ## Error Detection **File:** `src/lib/context/errorDetection.ts` Cross-provider regex patterns to detect context window overflow errors. ### `isContextOverflowError(error)` Returns `true` if the error matches any known context overflow pattern. ```typescript function isContextOverflowError(error: unknown): boolean; ``` Accepts `Error` objects, strings, or objects with `message`/`error` properties. Also inspects `error.cause` for nested errors. ### `getContextOverflowProvider(error)` Identifies which provider produced the context overflow error. ```typescript function getContextOverflowProvider(error: unknown): string | null; ``` Returns the provider name string or `null` if no match. ### Supported Provider Patterns | Provider | Error Patterns | | ------------ | ----------------------------------------------------------------------------------------- | | `openai` | `"This model's maximum context length is"`, `"reduce the length of the messages"` | | `azure` | `"content_length_exceeded"` | | `google` | `"RESOURCE_EXHAUSTED"`, `"exceeds the maximum number of tokens"`, `"content is too long"` | | `bedrock` | `"ValidationException.*token"`, `"Input is too long"`, `"exceeds the model's maximum"` | | `mistral` | `"context length exceeded"`, `"maximum number of tokens"` | | `openrouter` | `"context_length_exceeded"` | | `anthropic` | `"prompt is too long"`, `"input is too long"`, `"too many tokens"` | ### Non-Retryable Error Handling When `isContextOverflowError()` detects that an error is a context overflow, the MCP generation retry loop (`performMCPGenerationRetries`) breaks immediately instead of retrying up to 3 times. This prevents wasting API calls on errors that cannot succeed without compaction. Additionally, errors with `statusCode === 400` or `isRetryable === false` are treated as non-retryable and break the retry loop immediately. ### Post-Failure Compaction Passthrough When a generation call fails with a context overflow error and compaction is triggered, the compacted messages are passed through via `options.conversationMessages` to `directProviderGeneration()`, which uses them instead of re-fetching from memory. The compaction target is set to `Math.floor(availableInputTokens * 0.7)` (70% of available context) to leave headroom. --- ## Tool Output Limits **File:** `src/lib/context/toolOutputLimits.ts` Truncates individual tool outputs that exceed size limits. Can optionally save the full output to disk. ### Constants | Constant | Value | Description | | ----------------------- | --------------- | ---------------------------- | | `MAX_TOOL_OUTPUT_BYTES` | `51200` (50 KB) | Maximum tool output in bytes | | `MAX_TOOL_OUTPUT_LINES` | `2000` | Maximum tool output lines | ### `truncateToolOutput(output, options?)` ```typescript function truncateToolOutput( output: string, options?: TruncateOptions, ): TruncateResult; ``` **`TruncateOptions`:** ```typescript type TruncateOptions = { maxBytes?: number; // Default: MAX_TOOL_OUTPUT_BYTES (51200) maxLines?: number; // Default: MAX_TOOL_OUTPUT_LINES (2000) direction?: "head" | "tail"; // Which end to keep (default: "tail") saveToDisk?: boolean; // Save full output to disk (default: false) saveDir?: string; // Directory for saved output (default: os.tmpdir()/neurolink-tool-output) }; ``` **`TruncateResult`:** ```typescript type TruncateResult = { content: string; // Truncated content with notice appended truncated: boolean; // Whether truncation was applied savedPath?: string; // Path to saved full output (if saveToDisk was true) originalSize: number; // Original size in bytes }; ``` When truncated, a notice is appended: `[Output truncated from X bytes to Y bytes]` (with optional saved path). --- ## File Token Budget **File:** `src/lib/context/fileTokenBudget.ts` Calculates how much of the remaining context window can be used for file reads. Implements fast-path for small files and preview mode for very large files. ### Constants | Constant | Value | Description | | -------------------------- | ----------------- | ------------------------------------------------- | | `FILE_READ_BUDGET_PERCENT` | `0.6` | 60% of remaining context allocated for file reads | | `FILE_FAST_PATH_SIZE` | `102400` (100 KB) | Files below this size skip budget validation | | `FILE_PREVIEW_MODE_SIZE` | `5242880` (5 MB) | Files above this size get preview-only mode | | `FILE_PREVIEW_CHARS` | `2000` | Default preview size in characters | ### `calculateFileTokenBudget(contextWindow, currentTokens, maxOutputTokens)` Calculate available token budget for file reads. ```typescript function calculateFileTokenBudget( contextWindow: number, currentTokens: number, maxOutputTokens: number, ): number; ``` Formula: `floor((contextWindow - currentTokens - maxOutputTokens) * FILE_READ_BUDGET_PERCENT)` Returns `0` if remaining tokens is zero or negative. ### `enforceAggregateFileBudget(files, provider, model, maxTokens)` **File:** `src/lib/context/fileTokenBudget.ts` Enforces a total token budget across all file attachments in a single request. When the aggregate content of all files exceeds the available context budget, files are truncated proportionally or dropped to fit. This prevents the scenario where multiple large file attachments (e.g., 5 files totaling 2.8 MB) overflow the context window on the very first message — before any conversation history exists to compact. ```typescript function enforceAggregateFileBudget( files: Array, provider: string, model?: string, maxTokens?: number, ): Array; ``` Called automatically by `buildMultimodalMessagesArray()` before the file processing loop. ### `shouldTruncateFile(fileSize, budget)` Determine how a file should be handled based on its size and the token budget. ```typescript function shouldTruncateFile( fileSize: number, budget: number, ): { shouldTruncate: boolean; maxChars?: number; previewMode?: boolean }; ``` Decision logic: - `fileSize > FILE_PREVIEW_MODE_SIZE (5MB)` → preview mode (2000 chars) - `fileSize - conversation was compacted]"` - Synthetic messages have `metadata.truncated = true` This runs automatically after `compactSession()`. --- ## CLI Session Warnings **File:** `src/cli/loop/session.ts:300-354` In loop mode, the CLI checks context budget after each turn and displays warnings: **At >60% usage** (informational, gray text): ``` Context: 65% used ``` **At >=80% usage** (warning, yellow text — compaction threshold reached): ``` Context usage: 83% of window (166,000 / 200,000 tokens) Auto-compaction will trigger to preserve conversation quality. ``` These warnings only appear when `contextCompaction.enabled` is `true` in the session config. --- ## Provider Support Summary table of default context windows by provider: | Provider | Default Context Window | Notable Models | | ------------ | ---------------------- | -------------------------------------------------- | | Anthropic | 200,000 | All Claude 3/3.5/4 models | | OpenAI | 128,000 | GPT-4o, o1/o3 (200K), GPT-4.1/GPT-5 (1M+) | | Google AI | 1,048,576 | Gemini 2.x/3.x (1M), Gemini 1.5 Pro (2M) | | Vertex | 1,048,576 | Gemini 2.x (1M), Gemini 1.5 Pro (2M) | | Bedrock | 200,000 | Claude models (200K), Nova (300K) | | Azure | 128,000 | GPT-4o, GPT-4-turbo; GPT-4 (8K) | | Mistral | 128,000 | Large/Small (128K), Medium (32K), Codestral (256K) | | Ollama | 128,000 | Configurable per model | | LiteLLM | 128,000 | Passthrough to underlying provider | | Hugging Face | 32,000 | Model-dependent | | SageMaker | 128,000 | Model-dependent | --- ## Redis Conversation History Export # Redis Conversation History Export > **Since**: v7.38.0 | **Status**: Stable | **Availability**: SDK + CLI ## Overview **What it does**: Export complete conversation session history from Redis storage as JSON for analytics, debugging, and compliance auditing. **Why use it**: Access structured conversation data for analysis, user behavior insights, quality assurance, and debugging failed sessions. Essential for production observability. **Common use cases**: - Debugging failed or problematic conversations - Analytics and user behavior analysis - Compliance and audit trail generation - Quality assurance and model evaluation - Training data collection for fine-tuning ## Quick Start :::warning[Redis Required] Conversation history export **only works with Redis storage**. In-memory storage does not support export functionality. Configure Redis before enabling conversation memory. ::: ### SDK Example ```typescript const neurolink = new NeuroLink({ conversationMemory: { enabled: true, store: "redis", // Required for export functionality }, }); // Have a conversation await neurolink.generate({ prompt: "What is machine learning?", context: { sessionId: "session-123" }, }); // Get the conversation history const history = await neurolink.getConversationHistory("session-123"); // Returns: Promise console.log(history); // [ // { role: "user", content: "What is machine learning?" }, // { role: "assistant", content: "..." } // ] // Clear a specific session const cleared = await neurolink.clearConversationSession("session-123"); // Returns: Promise // Clear all conversations await neurolink.clearAllConversations(); // Returns: Promise ``` ### CLI Example ```bash # Enable Redis-backed conversation memory npx @juspay/neurolink loop --enable-conversation-memory --store redis # Have a conversation (session ID auto-generated) > Tell me about AI [AI response...] # List all conversation sessions npx @juspay/neurolink memory list npx @juspay/neurolink memory list --format json npx @juspay/neurolink memory list --user-id user123 # Export conversation history npx @juspay/neurolink memory export --session-id npx @juspay/neurolink memory export --session-id --include-metadata > conversation.json # Export all sessions to a directory npx @juspay/neurolink memory export-all --output ./exports/ npx @juspay/neurolink memory export-all --user-id user123 --output ./user-exports/ # Delete a specific session npx @juspay/neurolink memory delete --session-id npx @juspay/neurolink memory delete --session-id --force # Clear all sessions npx @juspay/neurolink memory clear --confirm # Get memory statistics npx @juspay/neurolink memory stats ``` ## Configuration | Option | Type | Default | Required | Description | | ----------------- | ----------------- | -------- | -------- | ------------------------------ | | `sessionId` | `string` | - | Yes | Unique session identifier | | `format` | `"json" \| "csv"` | `"json"` | No | Export format | | `includeMetadata` | `boolean` | `true` | No | Include session metadata | | `startTime` | `Date` | - | No | Filter: export from this time | | `endTime` | `Date` | - | No | Filter: export until this time | ### Environment Variables ```bash # Redis connection (required for export) export REDIS_URL="redis://localhost:6379" # or export REDIS_HOST="localhost" export REDIS_PORT="6379" export REDIS_PASSWORD="your-password" # if needed # Conversation memory settings export NEUROLINK_MEMORY_ENABLED="true" export NEUROLINK_MEMORY_STORE="redis" export NEUROLINK_MEMORY_MAX_TURNS_PER_SESSION="100" ``` ### Config File ```typescript // .neurolink.config.ts export default { conversationMemory: { enabled: true, store: "redis", // Required for persistent history redis: { host: process.env.REDIS_HOST || "localhost", port: parseInt(process.env.REDIS_PORT || "6379"), password: process.env.REDIS_PASSWORD, }, maxTurnsPerSession: 100, }, }; ``` ## How It Works ### Data Flow 1. **Conversation occurs** → Each turn stored in Redis with session ID 2. **Export requested** → SDK/CLI queries Redis for session 3. **Data aggregated** → Turns assembled with metadata 4. **Format applied** → JSON or CSV serialization 5. **Output delivered** → File or console output ### Redis Storage Structure ``` neurolink:session:{sessionId}:turns → List of conversation turns neurolink:session:{sessionId}:metadata → Session metadata neurolink:sessions → Set of all active session IDs ``` ### Data Schema (JSON Export) ```json { "sessionId": "session-abc123", "userId": "user-456", "createdAt": "2025-09-30T10:00:00Z", "updatedAt": "2025-09-30T10:15:00Z", "turns": [ { "index": 0, "role": "user", "content": "What is NeuroLink?", "timestamp": "2025-09-30T10:00:00Z" }, { "index": 1, "role": "assistant", "content": "NeuroLink is an enterprise AI development platform...", "timestamp": "2025-09-30T10:00:05Z", "model": "gpt-4", "provider": "openai", "tokens": { "prompt": 12, "completion": 45 } } ], "metadata": { "provider": "openai", "model": "gpt-4", "totalTurns": 2, "toolsUsed": ["web-search", "calculator"] } } ``` ## Advanced Usage ### Retrieve Session History ```typescript // Get conversation history for a specific session const history = await neurolink.getConversationHistory("session-123"); // Returns: Promise // Process the history for (const message of history) { console.log(`${message.role}: ${message.content}`); } ``` ### Clear Session Data ```typescript // Clear a specific session const cleared = await neurolink.clearConversationSession("session-123"); if (cleared) { console.log("Session cleared successfully"); } // Clear all conversations await neurolink.clearAllConversations(); console.log("All conversations cleared"); ``` ### Export History to File ```typescript // Get history and save to JSON file const history = await neurolink.getConversationHistory("session-123"); await fs.writeFile( `./exports/session-123.json`, JSON.stringify(history, null, 2), ); ``` ### Integration with Analytics Pipeline :::tip[Analytics Integration] Pipe exported conversation data directly to your analytics dashboards for user behavior insights, quality metrics, and model performance tracking. Combine with [Auto Evaluation](/docs/features/auto-evaluation) for comprehensive quality monitoring. ::: ```typescript // After each conversation session ends async function processSession(sessionId: string) { // Get conversation history const history = await neurolink.getConversationHistory(sessionId); // Send to analytics await analyticsService.track("conversation_completed", { sessionId, turnCount: history.length, messages: history, }); // Archive to data warehouse await dataWarehouse.store("conversations", { sessionId, messages: history }); // Optionally clear the session after archiving await neurolink.clearConversationSession(sessionId); } ``` ## API Reference ### SDK Methods ```typescript // List all conversation sessions const sessions = await neurolink.listSessions(userId); // Returns: Promise // Get conversation history for a session const history = await neurolink.getConversationHistory(sessionId); // Returns: Promise // Export a single session with full history const exportData = await neurolink.exportSession(sessionId, { includeMetadata: true, }); // Returns: Promise // Export all sessions const exports = await neurolink.exportAllSessions(userId, { includeMetadata: true, }); // Returns: Promise // Clear a specific session const cleared = await neurolink.clearConversationSession(sessionId); // Returns: Promise // Clear all conversations await neurolink.clearAllConversations(); // Returns: Promise ``` ### CLI Commands | Command | Description | | -------------------------------------------------------------- | -------------------------------------------- | | `neurolink memory list` | List all conversation sessions with metadata | | `neurolink memory list --user-id ` | List sessions for specific user | | `neurolink memory export --session-id ` | Export single session to JSON | | `neurolink memory export --session-id --include-metadata` | Export with metadata | | `neurolink memory export-all --output ` | Export all sessions to directory | | `neurolink memory delete --session-id ` | Delete a specific session | | `neurolink memory delete --session-id --force` | Delete without confirmation | | `neurolink memory clear --confirm` | Clear all sessions | | `neurolink memory stats` | Show memory statistics | | `neurolink memory history ` | Show conversation history | See [conversation-memory.md](/docs/memory/conversation) for complete memory system documentation. ## Troubleshooting ### Problem: getConversationHistory returns empty array **Cause**: Session ID doesn't exist or Redis not configured **Solution**: ```bash # Verify Redis connection redis-cli ping # Should return PONG # Check environment variables echo $REDIS_URL ``` ```typescript // Verify the session exists before retrieving const history = await neurolink.getConversationHistory(sessionId); if (history.length === 0) { console.log("No messages found for session:", sessionId); } ``` ### Problem: Redis connection failed **Cause**: Redis server not running or incorrect credentials **Solution**: ```bash # Start Redis locally redis-server # Or use Docker docker run -d -p 6379:6379 redis:latest # Test connection redis-cli -h localhost -p 6379 ping ``` ### Problem: Need additional metadata with history **Cause**: `getConversationHistory` returns only message array **Solution**: Use `exportSession` with `includeMetadata` option: ```typescript // Export with full metadata const exportData = await neurolink.exportSession("session-123", { includeMetadata: true, }); // Returns: { sessionId, title, createdAt, updatedAt, messages, exportMetadata } // Or use CLI // neurolink memory export --session-id session-123 --include-metadata ``` ### Problem: Memory commands require Redis for listing **Cause**: In-memory storage doesn't persist session IDs across CLI calls **Solution**: Configure Redis for persistent session management: ```bash # Set up Redis connection export REDIS_URL="redis://localhost:6379" # Enable Redis in loop mode neurolink loop --enable-conversation-memory --store redis ``` ```` ## Best Practices ### Data Retention 1. **Set TTL on sessions** - Auto-delete old conversations ```typescript config: { conversationMemory: { redis: { ttl: 7 * 24 * 60 * 60, // 7 days in seconds }, }, } ```` 2. **Archive regularly** - Export to long-term storage ```typescript // Archive a session before clearing async function archiveSession(sessionId: string) { const history = await neurolink.getConversationHistory(sessionId); await s3.upload(`archives/${sessionId}.json`, JSON.stringify(history)); await neurolink.clearConversationSession(sessionId); // Clean up } ``` ### Privacy & Compliance ```typescript // Redact PII before archiving async function archiveWithRedaction(sessionId: string) { const history = await neurolink.getConversationHistory(sessionId); // Redact sensitive data const redactedHistory = history.map((message) => ({ ...message, content: typeof message.content === "string" ? redactPII(message.content) // Remove emails, phone numbers, etc. : message.content, })); return { sessionId, messages: redactedHistory }; } ``` ### Session Cleanup ```typescript // Clean up old sessions async function cleanupSession(sessionId: string) { // Archive first if needed const history = await neurolink.getConversationHistory(sessionId); if (history.length > 0) { await archiveToStorage(sessionId, history); } // Clear the session const cleared = await neurolink.clearConversationSession(sessionId); console.log(`Session ${sessionId} cleared: ${cleared}`); } // Clear all conversations (use with caution) async function clearAllData() { await neurolink.clearAllConversations(); console.log("All conversations cleared"); } ``` ## Use Cases ### Quality Assurance ```typescript // Review conversations for specific sessions const failedSessions = await db.query( "SELECT session_id FROM sessions WHERE error IS NOT NULL", ); for (const { session_id } of failedSessions) { const history = await neurolink.getConversationHistory(session_id); // Analyze why conversation failed analyzeFailure({ sessionId: session_id, messages: history }); } ``` ### Session Review ```typescript // Review a specific session's conversation async function reviewSession(sessionId: string) { const history = await neurolink.getConversationHistory(sessionId); const report = { sessionId, messageCount: history.length, messages: history.map((msg) => ({ role: msg.role, contentPreview: typeof msg.content === "string" ? msg.content.substring(0, 100) : "[complex content]", })), }; console.table(report.messages); return report; } ``` ## Related Features - [CLI Loop Sessions](/docs/features/cli-loop-sessions) - Persistent conversation mode - [Conversation Memory](/docs/memory/conversation) - Full memory system docs - [Analytics Integration](/docs/reference/analytics) - Track conversation metrics ## Migration Notes If upgrading from in-memory to Redis-backed storage: 1. Enable Redis in configuration 2. Existing in-memory sessions will be lost (not migrated) 3. New sessions automatically stored in Redis 4. Export functionality only works with Redis store 5. Consider gradual rollout with feature flag For complete conversation memory system documentation, see [conversation-memory.md](/docs/memory/conversation). --- ## Credential Validation Added in **v9.59.0**, NeuroLink ships a typed `ModelAccessDeniedError` and a pre-flight `sdk.checkCredentials()` API. Together they let you validate provider credentials _before_ wiring them into a long-running flow — useful for setup wizards, health checks, and surfacing actionable errors to users instead of opaque HTTP 401/403s. -------- | --------------------------------------------------------------------- | | `"ok"` | Credentials valid; the probe succeeded. | | `"missing"` | Required env vars / per-call credentials are not set. | | `"expired"` | OAuth token / temporary credentials have expired. | | `"denied"` | Model access denied — see `ModelAccessDeniedError` below. | | `"network"` | Network failure reaching the provider (DNS, TLS, timeout). | | `"unknown"` | An unclassified provider error; inspect `detail` for the raw message. | `detail` is a short human-readable message suitable for surfacing in a setup UI or log line. ### Probing several providers `checkCredentials()` validates one provider per call. To check multiple providers, run them concurrently: ```typescript const results = await Promise.all( ["openai", "anthropic", "vertex", "deepseek"].map((provider) => neurolink.checkCredentials({ provider }).catch((err) => ({ provider, status: "unknown" as const, detail: err instanceof Error ? err.message : String(err), })), ), ); const broken = results.filter((r) => r.status !== "ok"); for (const r of broken) { console.warn(`${r.provider}: ${r.status} — ${r.detail}`); } ``` --- ## `ModelAccessDeniedError` When a generate/stream call hits a model-access policy (e.g. the team is not allowed to use a particular model, or a tier-restricted model is requested), NeuroLink throws a typed `ModelAccessDeniedError` instead of a generic `Error`. This makes it catchable by the [`providerFallback`](/docs/features/provider-fallback) orchestrator and lets you produce actionable UI. ```typescript try { await neurolink.generate({ input: { text: "Hello" }, provider: "anthropic", model: "claude-opus-4-7", }); } catch (err) { if (err instanceof ModelAccessDeniedError) { console.error("Model access denied for", err.provider); console.error("Requested model:", err.requestedModel); console.error("Allowed models:", err.allowedModels); // Show user a setup link, or fall back to a model in `allowedModels`. } throw err; } ``` ### Error shape ```typescript class ModelAccessDeniedError extends ProviderError { readonly name: "ModelAccessDeniedError"; readonly code: "MODEL_ACCESS_DENIED"; readonly provider?: string; // inherited from ProviderError readonly requestedModel?: string; readonly allowedModels?: string[]; } ``` The exact definition lives in `src/lib/types/errors.ts`. --- ## CLI NeuroLink does not ship a dedicated `check-credentials` CLI command. The closest operator-facing command is: ```bash # Check provider connectivity / status npx @juspay/neurolink status ``` For programmatic credential validation in scripts, call the SDK directly: ```typescript const r = await neurolink.checkCredentials({ provider }); process.exit(r.status === "ok" ? 0 : 1); ``` --- ## Combining with Provider Fallback The most common pattern: validate at boot, surface configuration errors to operators, then let runtime requests use [`providerFallback`](/docs/features/provider-fallback) for the model-access denial cases that survive validation. ```typescript // Boot-time validation for (const provider of ["anthropic", "openai", "vertex"]) { const r = await neurolink.checkCredentials({ provider }); if (r.status !== "ok") { console.warn( `Provider ${provider} not configured: ${r.status} — ${r.detail}`, ); } } // Runtime: per-instance providerFallback handles ModelAccessDeniedError const sdk = new NeuroLink({ providerFallback: async (err) => { if (err instanceof ModelAccessDeniedError && err.allowedModels?.length) { return { model: err.allowedModels[0] }; } return null; }, }); ``` --- ## Setup Wizard Pattern ```typescript async function runSetupWizard() { const apiKey = await prompt("Enter your OpenAI API key:"); process.env.OPENAI_API_KEY = apiKey; const r = await neurolink.checkCredentials({ provider: "openai" }); if (r.status === "ok") { await writeEnv({ OPENAI_API_KEY: apiKey }); console.log("Configured."); } else { console.error(`Invalid key (${r.status}):`, r.detail); } } ``` Per-call credential overrides are also supported on `generate()` / `stream()` — see [Per-Request Credentials](/docs/features/per-request-credentials). --- ## Related - **[Provider Fallback](/docs/features/provider-fallback)** — catch `ModelAccessDeniedError` and switch to an allowed model - **[Per-Request Credentials](/docs/features/per-request-credentials)** — pass credentials per-call or per-instance - **[Provider Setup](/docs/getting-started/provider-setup)** — initial configuration for supported providers - **[Troubleshooting](/docs/reference/troubleshooting)** — error reference and resolution guide --- ## CSV File Support # CSV File Support NeuroLink provides seamless CSV file support as a **multimodal input type** - attach CSV files directly to your AI prompts for data analysis, insights, and processing. ## Overview CSV support in NeuroLink works just like image support - it's a multimodal input that gets automatically processed and injected into your prompts. The system: 1. **Auto-detects** CSV files using FileDetector (magic bytes, MIME types, extensions, content heuristics) 2. **Parses** CSV data using a streaming parser for memory efficiency 3. **Formats** CSV content into LLM-optimized text (markdown/json) 4. **Injects** formatted CSV data into your prompt text 5. **Works** across supported AI providers (not limited to vision models) **Delimiter auto-detection:** the delimiter is detected from the content (comma, **tab / `.tsv`**, semicolon, or pipe) — so tab- and semicolon-separated files parse into the correct columns instead of collapsing into one. Comma remains the default on ambiguity, and parsing is **RFC-4180 quote-aware** (a delimiter inside a `"…"` quoted field, e.g. `"Smith, John"`, does not split the field). The detected delimiter is reported in `metadata.detectedDelimiter`. ## Quick Start ### SDK Usage ```typescript const neurolink = new NeuroLink(); // Basic CSV analysis const result = await neurolink.generate({ input: { text: "What are the key trends in this sales data?", csvFiles: ["sales-2024.csv"], }, }); // Multiple CSV files const comparison = await neurolink.generate({ input: { text: "Compare Q1 vs Q2 performance and identify growth areas", csvFiles: ["q1-sales.csv", "q2-sales.csv"], }, }); // Auto-detect file types (mix CSV and images) const multimodal = await neurolink.generate({ input: { text: "Analyze this data and compare with the chart", files: ["data.csv", "chart.png"], // Auto-detects which is CSV vs image }, }); // Customize CSV processing const custom = await neurolink.generate({ input: { text: "Summarize the top 100 customers by revenue", csvFiles: ["customers.csv"], }, csvOptions: { maxRows: 100, // Limit to first 100 rows formatStyle: "markdown", // Use markdown table format includeHeaders: true, // Include CSV headers }, }); ``` ### CLI Usage ```bash # Attach CSV files to your prompt neurolink generate "Analyze this sales data" --csv sales.csv # Multiple CSV files neurolink generate "Compare these datasets" --csv q1.csv --csv q2.csv # Auto-detect file types neurolink generate "Analyze data and image" --file data.csv --file chart.png # Customize CSV processing neurolink generate "Summarize trends" \ --csv large-dataset.csv \ --csv-max-rows 500 \ --csv-format json # Stream mode also supports CSV neurolink stream "Explain this data in detail" --csv data.csv # Batch processing with CSV echo "Summarize sales data" > prompts.txt echo "Find top performers" >> prompts.txt neurolink batch prompts.txt --csv sales.csv ``` ## API Reference ### GenerateOptions ```typescript type GenerateOptions = { input: { text: string; images?: Array; csvFiles?: Array; // Explicit CSV files files?: Array; // Auto-detect file types }; csvOptions?: { maxRows?: number; // Default: 1000 formatStyle?: "raw" | "markdown" | "json"; // Default: "raw" includeHeaders?: boolean; // Default: true encoding?: string; // Override; else auto-detected (#362) sanitizeColumnNames?: boolean; // Default: false (#378) columnNameCase?: "camelCase" | "snake_case"; // Default: "snake_case" parseTimeoutMs?: number; // Default: 30s strings / 5min files (#379) }; // ... other options }; ``` ### CSV Input Types CSV files can be provided as: - **File paths**: `"./data.csv"` or `"/absolute/path/data.csv"` - **URLs**: `"https://example.com/data.csv"` - **Buffers**: `Buffer.from("name,age\nAlice,30")` - **Data URIs**: `"data:text/csv;base64,..."` ```typescript // File path await neurolink.generate({ input: { text: "Analyze this", csvFiles: ["./data.csv"], }, }); // URL await neurolink.generate({ input: { text: "Analyze this", csvFiles: ["https://example.com/data.csv"], }, }); // Buffer const csvBuffer = Buffer.from("name,age\nAlice,30\nBob,25"); await neurolink.generate({ input: { text: "Analyze this", csvFiles: [csvBuffer], }, }); ``` ### CSV Processing Options #### maxRows Limit the number of rows processed (default: 1000). Useful for large datasets. ```typescript csvOptions: { maxRows: 100; // Only process first 100 rows } ``` #### formatStyle Control how CSV data is formatted for the LLM: - **`raw`** (default, RECOMMENDED): Original CSV format with proper escaping - Best for large files and minimal token usage - Preserves original structure - Handles commas, quotes, newlines correctly - File size stays minimal (63KB stays 63KB, not 199KB) - **`json`**: JSON array format - Best for structured data processing - Easy to parse programmatically - Higher token usage (can expand 3x for large files) - **`markdown`**: Markdown table format - Best for small datasets (\ Not binary (0% confidence) // 2. Check MIME type (if URL) -> text/csv (85% confidence) ✓ STOP // Result: Detected as CSV with 85% confidence ``` ## How It Works ### Internal Processing Flow ````typescript // When you call generate() with CSV files: await neurolink.generate({ input: { text: "Analyze this data", csvFiles: ["data.csv"], }, }); // Internal flow: // 1. messageBuilder.ts detects csvFiles array // 2. Calls FileDetector.detectAndProcess("data.csv") // 3. FileDetector runs detection strategies // 4. Loads file content (from path/URL/buffer) // 5. Routes to CSVProcessor.process(buffer) // 6. CSV parsed using streaming csv-parser library // 7. Formatted to LLM-optimized text (raw/markdown/json) // 8. Appends to prompt text: // "Analyze this data // // ## CSV Data from "data.csv": // ```csv // name,age,city // Alice,30,New York // Bob,25,London // ```" // 9. Sends to AI provider ```` ### Memory Efficiency CSV files are parsed using **streaming** for memory efficiency: ```typescript // CSVProcessor uses Readable streams Readable.from([csvString]) .pipe(csvParser()) .on("data", (row) => { if (count ` (#384) - **Token limits**: Large CSV files may exceed provider token limits - **Streaming**: CSV content is parsed and formatted before sending (not streamed to LLM) ## Error Handling ```typescript try { const result = await neurolink.generate({ input: { text: "Analyze this", csvFiles: ["data.csv"], }, }); } catch (error) { if (error.message.includes("File too large")) { // Handle file size error } else if (error.message.includes("not allowed")) { // Handle file type restriction } else if (error.message.includes("CSV")) { // Handle CSV parsing error. Failures now carry context, e.g.: // [CSVProcessor] Failed to open CSV file (/path/x.csv): ENOENT ... // [CSVProcessor] CSV parsing failed after 3 row(s) : // | headerCount: 3 | lastRow columns: 3 | Expected RFC 4180 CSV ... // (only structural context — counts, never raw header or cell string // values, which for headerless input may literally be first-row data — // is included, so error messages can't leak CSV data (#1199)) // [CSVProcessor] Invalid CSV row 2: expected a string-keyed object ... // A bad/missing path is wrapped (not a raw ENOENT), and both the source // and parser streams are always destroyed on any error path. } } ``` ## Related Features - **[Office Documents](/docs/features/office-documents)**: DOCX, PPTX, XLSX processing - **[PDF Support](/docs/features/pdf-support)**: PDF document processing - **Image Support**: Similar multimodal input for images - **File Detection**: Auto-detect file types with confidence scores - **Memory Efficient**: Streaming parser for large files - **Provider Agnostic**: Works across supported providers - **CLI Integration**: Full CLI support with options ## Summary - CSV support is **multimodal input** (like images) - Use `csvFiles` array or `files` array (auto-detect) - Customize with `csvOptions` (maxRows, formatStyle, includeHeaders) - Works across **supported providers** (not just vision models) - **Memory efficient** streaming parser - CLI support with `--csv`, `--file`, `--csv-max-rows`, `--csv-format` - Only **types** exposed from package (not classes) --- ## The `decide` inference type # The `decide` inference type > **Deep-dive:** [generate, stream, decide: a third inference type for NeuroLink](https://blog.neurolink.ink/posts/generate-stream-decide-a-third-inference-type-for-neurolink/) — > why this shipped as a provider rather than a subsystem, the five call sites, and the four > transport bugs found by adding the Vercel AI Gateway (two of which produced plausible output). NeuroLink recognises three inference types. Two of them produce text: | Type | Call | Produces | | ------------ | ------------------------ | ------------------------------ | | `generate` | `neurolink.generate()` | text | | `stream` | `neurolink.stream()` | text, incrementally | | **`decide`** | **`neurolink.decide()`** | **typed judgements — no text** | A **decision model** takes one `state` plus a map of named, typed questions and returns one typed answer per question, all evaluated in a single parallel pass. There is no text anywhere in the response, so nothing has to be parsed back out of prose. The decide providers are TypeSafe's **Jev**, Convai Innovations' open-weights **Laya**, Juspay's open-weights **XOR**, which also reads an image and audio and extracts typed values, Subquadratic's hosted **SubQ Snap**, Perplexity's hosted **Decisions** API, which also reads images, Cloudflare's **Clef** models on Workers AI, which also read images, OpenAI's **Decisions** API (a public beta), which also reads images, and ScaleDown's hosted **Classify** models, which read text only. > This is not [`neurolink.evaluate()`](/docs/features/auto-evaluation), which scores an > already-generated response with RAGAS scorers. Different feature, different > word. ------ | ------------------------------ | ------------------------------------------------ | | `boolean` | Is this statement true? | `probability` (0–1) — **no confidence** | | `choice` | Which option from this set? | `choice`, `probabilities`, `confidence` | | `score` | Rate against an ordered rubric | `score`, `legend`, `probabilities`, `confidence` | All three mix freely in one call. ### Two more, on XOR: `value`, and `choice` with `unknown` A provider lists the question types it reads in its `decisionLimits` (`questionTypes`); without the list it reads the three above. Asking anything else is refused before any request, as a non-retryable `invalid_request`, and a host question of such a type is dropped on its own (see [`decisionHooks`](#riding-along-decisionhooks)). XOR reads two more: | Type | Question | Answer fields | | ----------------------------- | -------------------------------------- | ----------------------------------------------------------------------- | | `value` | Extract one typed field from the state | `value` (string or number; `null` when absent), `confidence`, `unknown` | | `choice` with `unknown: true` | Which option, or none of them? | as `choice`, plus `unknown: true` when none fits | ```ts const result = await neurolink.decide({ provider: "xor", state: "Invoice INV-2024-0892 for 18,275.50 rupees, due on 15 September.", questions: { amount: { type: "value", dtype: "float", instructions: "Invoice amount?" }, ref: { type: "value", instructions: "Invoice reference?", pattern: "INV-[0-9]{4}-[0-9]{4}", }, intent: { type: "choice", unknown: true, instructions: "What does the customer want?", criteria: { upgrade: "a higher plan", downgrade: "a lower plan" }, }, }, }); readDecisionValue(result.answers, "amount"); // { value: 18275.5, confidence, unknown: false } ``` `dtype` is `string` (the default), `int` or `float`; `pattern` is a regular expression the extracted text must match. A value the state does not hold comes back as `null` with `unknown: true` — an answer, not a missing one. `readDecisionValue` returns undefined only for an absent id or another type. With `unknown: true` on a `choice`, the option count includes `unknown`, and no option may itself be named `unknown`. **Vocabulary note.** TypeSafe calls the yes/no primitive a `noul` and answers it in a field of the same name. The Vercel AI SDK and Pydantic AI both renamed that to `boolean`/`probability` when exposing it, and NeuroLink follows them — the vendor's spelling is translated inside `TypeSafeProvider`, so another decision provider slots in without changing any call site. ### Confidence is not probability `probabilities` says _what_ the model thinks. `confidence` says _whether you should act on it_. On TypeSafe's Jev it is calibrated — derived from the distribution, not self-reported — which is what makes it usable as a gate. Each provider reports its own: Perplexity's is, in Perplexity's words, the model's own certainty estimate and not the top probability, Perplexity does not call it calibrated, and NeuroLink has not measured whether it is, so tune a threshold on your own data (see the [Perplexity guide](/docs/getting-started/providers/perplexity-decider)). **Calibration is a property of _groups_ of answers, not a promise about any one.** Where a confidence is calibrated, answers scored 0.8 are right about 80% of the time across many answers. It does not mean a specific 0.8 answer is right. A `boolean` carries no confidence of its own. Use `decisionBooleanConfidence(p)` — distance from a coin flip, so 0.5 → 0 and 0/1 → 1. Note also that a `boolean` and an equivalent two-option `choice` are **not** guaranteed to agree, and complementary booleans do not reliably sum to 1, so a threshold tuned on one question shape does not transfer to another. --- ## Enabling it ```bash export TYPESAFE_API_KEY=apikey_... # enables TypeSafe export TYPESAFE_MODEL=jev-latest # optional export TYPESAFE_BASE_URL=https://api.typesafe.ai # optional ``` Get a key at [console.typesafe.ai/keys](https://console.typesafe.ai/keys). ### Laya, at a Laya server or a LiteLLM proxy route ```bash export LAYA_BASE_URL=https://your-proxy.example.com/laya # required: any server exposing /predict export LAYA_API_KEY=sk-... # the key that endpoint accepts export LAYA_MODEL=typed-decisions # optional: english | multilingual | typed-decisions | auto ``` Laya has no built-in endpoint. The base URL and key can equally come from the config passed to the SDK, `new NeuroLink({ credentials: { laya: { baseURL, apiKey } } })`, or per call; config set there counts when NeuroLink picks the default decision provider, exactly as the environment does. When a TypeSafe key (`TYPESAFE_API_KEY` or `AI_GATEWAY_API_KEY`) is configured alongside Laya, TypeSafe is the default; Laya runs where a caller names it (`provider: "laya"`) or when neither TypeSafe key is set. Laya counts as configured only with both its key and its base URL. See the [Laya provider guide](/docs/getting-started/providers/laya). ### XOR, at a deployment or a LiteLLM proxy route ```bash export XOR_BASE_URL=https://your-proxy.example.com # required: a deployment, or a proxy route to one export XOR_API_KEY=sk-... # the key that endpoint accepts export XOR_MODEL=xor-latest # optional; xor-omni reads an image and audio ``` XOR, Juspay's open-weights decision model, has no built-in endpoint either. NeuroLink calls `/v1/decisions`, and a trailing `/v1` on the base URL is accepted. The base URL must be `https://`; `http://` is accepted only for `localhost`, `127.0.0.1` and `[::1]`, because every request carries the key and the state. A redirect from the endpoint is refused, not followed. The base URL and key can equally come from the config passed to the SDK, `new NeuroLink({ credentials: { xor: { baseURL, apiKey } } })`, or per call; config set there counts when NeuroLink picks the default decision provider, exactly as the environment does. On a LiteLLM proxy the key's team must allow `xor-latest` (and `xor-omni` for media), otherwise the proxy answers 403 `team_model_access_denied`. Built-in features use the first configured decision provider in the order TypeSafe, Laya, XOR, SubQ, Perplexity, Cloudflare Clef, OpenAI Decisions, ScaleDown. XOR counts as configured only with both its key and its base URL, and runs where a caller names it (`provider: "xor"`) or when neither TypeSafe nor Laya is configured. It reads one image and up to 30 seconds of audio, but no video, and answers `value` questions; see [Images and video](#images-and-video) and the [XOR provider guide](/docs/getting-started/providers/xor). ### SubQ, at its hosted endpoint ```bash export SUBQ_API_KEY=... # required; from console.subq.ai, which shows it once export SUBQ_MODEL=subq-snap-preview # optional; the only model on the Decisions endpoint export SUBQ_BASE_URL=https://api.subq.ai # optional; an origin, without /v1 ``` Subquadratic's `subq-snap-preview` (public preview) speaks the same System One wire as TypeSafe, at a public endpoint, so a key alone configures it and there is no base URL to set. The key and base URL can equally come from the config passed to the SDK, `new NeuroLink({ credentials: { subq: { apiKey, baseURL } } })`, or per call. The provider id is `subq`; `subquadratic` and `subq-snap` name it too. It comes after TypeSafe, Laya and XOR and ahead of Perplexity and Cloudflare Clef: its key belongs to no other provider, so it is set on purpose, whereas theirs are shared with text providers and must not displace it. NeuroLink sends it no images or video: SubQ's image format is not one the decide catalog can describe yet, so an image attached to a call is refused before any request. The state window NeuroLink reports for it is advisory (reported, never enforced, not a guarantee); see the [SubQ provider guide](/docs/getting-started/providers/subq.md#limits). ### Perplexity, at its hosted endpoint ```bash export PERPLEXITY_API_KEY=pplx-... # required; also the Sonar text provider's key export PERPLEXITY_DECIDER_MODEL=pplx-decider-v1-27b # optional export PERPLEXITY_DECIDER_BASE_URL=https://api.perplexity.ai # optional: an origin ``` Perplexity's `pplx-decider-v1-27b` is a hosted API at a public endpoint, so a key alone configures it and there is no base URL to set. NeuroLink calls `/v1/decisions`; a trailing `/v1` on an override is accepted. The key can equally come from the config passed to the SDK, `new NeuroLink({ credentials: { perplexityDecider: { apiKey } } })`, or per call; config set there counts when a `decide()` call picks the default decision provider, exactly as the environment does. The classifier router's `auto` gate counts them too, per-call credentials included, so a `credentials.perplexityDecider` passed on one call can make `auto` pick `jev`. The provider id is `perplexity-decider`: the `perplexity` provider is the Sonar text provider, which serves `generate()` and `stream()` and not `decide()`. **`PERPLEXITY_API_KEY` is shared with that text provider.** A host that set it only to use Sonar has therefore also configured `decide`, and built-in features will use Perplexity whenever none of TypeSafe, Laya, XOR or SubQ is configured. Perplexity comes after XOR and SubQ in descriptor order, so it never displaces one that is. Context compaction's relevance stage and summary gate need no opt-in of their own, so earlier conversation text starts going to Perplexity the first time a conversation outgrows its budget; model routing, tool routing and RAG planning do nothing unless enabled. To keep the shared key from activating decisions, pass the text provider's key as `credentials.perplexity` instead of through the environment, and keep it out of `.env` too, because the SDK and the CLI load that file into the environment, or configure one of TypeSafe, Laya, XOR and SubQ, which then receives those texts instead. The Perplexity provider guide lists [what each consumer sends](/docs/getting-started/providers/perplexity-decider.md#what-is-sent-to-perplexity) and the [exact switches](/docs/getting-started/providers/perplexity-decider.md#one-key-two-providers). It reads images but no video; see [Images and video](#images-and-video). ### Cloudflare Clef, on Workers AI ```bash export CLOUDFLARE_API_KEY=... # required; a Workers AI token, also the Workers AI text provider's key export CLOUDFLARE_ACCOUNT_ID=... # required; also the Workers AI text provider's account id export CLOUDFLARE_CLEF_MODEL=clef-flash # optional: clef (27B, the default) or clef-flash (9B) export CLOUDFLARE_CLEF_BASE_URL=https://api.cloudflare.com/client/v4 # optional ``` Cloudflare's `clef` and `clef-flash` are hosted on Workers AI at a public endpoint, so there is no base URL to set. The account id is part of the route, so Clef counts as configured only with both the token and the account id. They can equally come from the config passed to the SDK, `new NeuroLink({ credentials: { cloudflareClef: { apiKey, accountId } } })` (`baseURL` is optional), or per call; config set there counts when a `decide()` call picks the default decision provider, exactly as the environment does. The classifier router's `auto` gate counts them too, per-call credentials included, so a `credentials.cloudflareClef` passed on one call can make `auto` pick `jev`. The provider id is `cloudflare-clef`: the `cloudflare` provider is the Workers AI text provider, which serves `generate()` and `stream()` and not `decide()`, and `credentials.cloudflare` does not configure `decide`. **The Workers AI endpoint's state window changed during October 2026.** Cloudflare documents a 64K window; until 2026-10-04 text past about 2,048 tokens was ignored without an error, and on 2026-10-07 states of at least 190,153 tokens (`clef-flash`) and 52,154 (`clef`) were read in full (hosted service or model: unknown). NeuroLink refuses a state it estimates at more than 16,000 tokens with `max_tokens_exceeded`, which every built-in consumer treats as "carry on as before"; see [Limits and gotchas](#limits-and-gotchas). Latency grows with the state, about 0.2 s per 1,000 tokens on large ones, so NeuroLink's default timeout adds 250 ms per 1,000 estimated tokens. **`CLOUDFLARE_API_KEY` and `CLOUDFLARE_ACCOUNT_ID` are shared with that text provider.** A host that set them only to use Workers AI text has therefore also configured `decide`, and built-in features will use Clef whenever none of TypeSafe, Laya, XOR, SubQ or Perplexity is configured. Clef comes after TypeSafe, Laya, XOR, SubQ and Perplexity, so it never displaces one that is. No switch turns it off while the two variables are set. The Clef provider guide explains [when NeuroLink uses it](/docs/getting-started/providers/cloudflare-clef.md#when-neurolink-uses-it) and [how the two providers share the token](/docs/getting-started/providers/cloudflare-clef.md#one-token-two-providers). It reads images but no video; see [Images and video](#images-and-video). ### OpenAI Decisions, at its hosted endpoint ```bash export OPENAI_API_KEY=sk-... # required; also the OpenAI chat provider's key export OPENAI_DECISIONS_MODEL=gpt-6-luna # optional export OPENAI_DECISIONS_BASE_URL=https://api.openai.com # optional: an origin ``` OpenAI's Decisions API is a public beta at a public endpoint, so a key alone configures it and there is no base URL to set. NeuroLink calls `/v1/decisions`; a trailing `/v1` on an override is accepted. The key can equally come from the config passed to the SDK, `new NeuroLink({ credentials: { openaiDecisions: { apiKey } } })`, or per call; config set there counts when a `decide()` call picks the default decision provider, exactly as the environment does. The classifier router's `auto` gate counts them too, per-call credentials included, so a `credentials.openaiDecisions` passed on one call can make `auto` pick `jev`. The provider id is `openai-decisions`: the `openai` provider is the chat provider, which serves `generate()` and `stream()` and not `decide()`, and `credentials.openai` does not configure `decide`. Its wire is OpenAI's own (named questions in an array, an array of answers), so NeuroLink translates both ways; the question types you write are unchanged. See the provider guide's [wire mapping](/docs/getting-started/providers/openai-decisions.md#how-a-question-is-sent). **`OPENAI_API_KEY` is shared with that chat provider.** A host that set it only to use OpenAI chat has therefore also configured `decide`, and built-in features will use OpenAI Decisions whenever none of TypeSafe, Laya, XOR, SubQ, Perplexity or Cloudflare Clef is configured. It comes after those six in the order, so it never displaces one that is; only ScaleDown follows it. The built-in consumers (model routing, tool routing, relevance compaction, the summary gate, RAG planning) and the speech-to-text correction check then make paid decision calls, though they still fail open. No switch turns it off while the key is set (short of a gateway `OPENAI_BASE_URL`, below). `neurolink.decide()` and `tryDecide()` build a fresh provider for every call, so a key OpenAI rejects costs one failing request per decision site each time, and the 401 latch never carries across calls. The provider guide explains [when NeuroLink uses it](/docs/getting-started/providers/openai-decisions.md#when-neurolink-uses-it) and [how the two providers share the key](/docs/getting-started/providers/openai-decisions.md#one-key-two-providers). **A gateway's key is never used for the default.** `OPENAI_API_KEY` is also the key of every OpenAI-compatible gateway (LiteLLM, vLLM and the like), so while `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL` names a host other than `https://api.openai.com`, NeuroLink does not take the environment key to be OpenAI's and does not pick OpenAI Decisions as the default; the built-in consumers send nothing to `api.openai.com` for it and behave as they did without a decision model. The comparison is of scheme, host and port, without regard to case; a path, a trailing slash and `/v1` do not matter, a value that is not an http(s) URL counts as another host, and a blank one as unset. Setting `OPENAI_DECISIONS_BASE_URL`, or passing `credentials.openaiDecisions` with a key or a base URL, lifts the check, because you routed this provider on purpose. A call that names `provider: "openai-decisions"` is never checked: it uses the environment key, and sends it to `https://api.openai.com` unless `OPENAI_DECISIONS_BASE_URL` or `credentials.openaiDecisions.baseURL` says otherwise, so a host whose key is a gateway's must route the provider on purpose or not use it, and must not name it. The rule is data on the catalog entry (`decide.ambientKeyGuard`) and applies to this provider alone; the provider guide spells out [the cases](/docs/getting-started/providers/openai-decisions.md#a-gateways-key-is-never-used-for-the-default). It reads images but no video; see [Images and video](#images-and-video). **Much about the endpoint is not established**, including its option limits, image formats and rate limits. Its question cap is the 200 that OpenAI's Python SDK documents, which `tryDecide()` splits at; going over it was not tried against the live endpoint. The guide lists [what is not established](/docs/getting-started/providers/openai-decisions.md#what-is-not-established). ### ScaleDown, at its hosted endpoint ```bash export SCALEDOWN_API_KEY=... # required; a key no other provider reads export SCALEDOWN_MODEL=classify-1 # optional; classify-1 is the default export SCALEDOWN_BASE_URL=https://api.scaledown.xyz # optional: an origin, or an origin with a path prefix ``` ScaleDown's Classify models speak the same System One wire as TypeSafe, at a public endpoint, so a key alone configures it and there is no base URL to set. NeuroLink calls `/v1/scaledown`, drops trailing slashes from an override, and sends the key in an `x-api-key` header and never as a Bearer token. The key can equally come from the config passed to the SDK, `new NeuroLink({ credentials: { scaledown: { apiKey } } })`, or per call. The provider id is `scaledown`; `scaledown-classify` names it too. **ScaleDown is the last decision provider, and its key is its own.** Nothing else reads `SCALEDOWN_API_KEY`, so setting it can only be meant for ScaleDown. It still comes last in the order: a host with only that key gets ScaleDown for the built-in features, and a host that also has any earlier provider configured (including an `OPENAI_API_KEY`, `PERPLEXITY_API_KEY` or Cloudflare pair set only for a text provider) gets that earlier provider and reaches ScaleDown only by naming it. When ScaleDown is the default, the built-in consumers make paid decision calls, and still fail open. **It reads text only, and the state always goes out as a string.** A string state is sent unchanged, any other value as its JSON text, and a string that is empty or only whitespace is refused before any request, as an `invalid_request`. `{}` and `[]` are sent as that text. Images and video are refused before any request. Two optional keys in the entry's `decide` block say this to the shared engine, `authHeader: "x-api-key"` and `stateEncoding: "text"`; an entry that omits them behaves as before. The provider guide has the [request](/docs/getting-started/providers/scaledown.md#how-a-request-is-sent) and the [billing note](/docs/getting-started/providers/scaledown.md#choice-options-and-billing): ScaleDown's documentation says a `choice` question is scored once per option, but the input tokens charged in a live test did not grow with options times state length (the same 20,000-character state cost 2,966, 3,024 and 3,137 tokens at 3, 6 and 12 options); how ScaleDown counts them is not known. **Much about the endpoint is not measured**, including its context size, latency, rate limits and the maximum number of options, questions and levels; the guide lists [what is not measured](/docs/getting-started/providers/scaledown.md#not-measured). All of the facts the guide gives about ScaleDown's endpoint come from its documentation and from probes the marketing session made on 2026-10-15; none were made by NeuroLink's project. **The degradation contract.** `resolveDefaultDecisionProvider()` returns `undefined` when no decision provider is configured (a key, plus a base URL for Laya and XOR, or an account id for Cloudflare Clef; SubQ and ScaleDown need only their key), and `tryDecide()` returns `null` on any failure. There is no configuration in which a missing, invalid, slow or unreachable decision model changes NeuroLink's observable behaviour — it only ever falls back to what it did before. A credential the service does not accept disables that provider instance rather than paying a round trip on every later call to be told so again. An XOR 403 or 402 is not that case: on a LiteLLM proxy it means the key's team lacks the model or the budget, which an admin can fix, so the instance is not disabled. For Perplexity only a 401 is that case: a 413 or a 400 over the model's context length is `max_tokens_exceeded`, a 429 is `rate_limit` (retried once), and any other 4xx is a non-retried `invalid_request`. For ScaleDown only a 401 is that case: a 402 (no credit left, or a key ScaleDown does not recognise; the message says both) and a 422 are non-retried `invalid_request`s (the same instance works again once the cause is fixed), a 429 is `rate_limit` and a 502 or other 5xx is `server` (each retried once), and a 504 that ScaleDown sends is `timeout` and is not retried. For OpenAI Decisions only a 401 is that case (a 403 is a non-retried `invalid_request`), and every 429 is a non-retried `rate_limit`. For Cloudflare Clef only a 401 is that case (a 403 was never seen, and would be a non-retried `invalid_request`, so a permission fixed in the dashboard works at once), a 413 is `max_tokens_exceeded`, a 429 is `rate_limit` (retried, except the Free plan's daily-allocation 429 with code 4006, which a few seconds of backoff do not clear), and a 400 or 422 is a non-retried `invalid_request`. --- ## Two transports The same model is reachable two ways. Which one runs is decided once, in the constructor: | | Direct | Vercel AI Gateway | | ------------------- | ------------------ | --------------------------------------------- | | Key | `TYPESAFE_API_KEY` | `AI_GATEWAY_API_KEY` | | Endpoint | `api.typesafe.ai` | `ai-gateway.vercel.sh/v4/ai/evaluation-model` | | Model named in | request body | `ai-model-id` header | | Question vocabulary | `noul` | `boolean` | | `confidence` | on each answer | on `providerMetadata`, not on the answer | | Billed by | TypeSafe | Vercel | **Holding both keys keeps the direct transport**, so the confidence figures a host already sees do not shift underneath it when a second key appears. Both transports report the vendor's calibrated confidence — the gateway simply puts it somewhere else, under `providerMetadata.typesafe.confidence.`, leaving the answer objects without one. Set `TYPESAFE_TRANSPORT=gateway` (or `credentials.typesafe.transport`) to override. ⚠️ **Read that field, not the distribution peak.** It is tempting to take `max(probabilities)` when an answer carries no `confidence`, and on a near-certain answer the two agree. On an uncertain one they do not, and not by a little: a measured four-way choice returned probabilities `{alpha 0.16, beta 0.28, gamma 0.33, delta 0.23}` — a peak of **0.33** against a reported confidence of **0.10**. That gap straddles the default `minUpgradeConfidence` of 0.3, so the derived number clears a bar the real one fails and a near-random pick gets acted on as a confident one. The peak stays as the fallback when neither source reports a confidence, and it is genuinely a different quantity: an even distribution over N options lands near 1/N, not 0. **Usage is spelled differently too** — `input_tokens` / `output_tokens` on the direct API, `inputTokens` / `outputTokens` on the gateway. Both are read. A decision is priced on input alone, so a parser that knows only one spelling does not error: it reports zero tokens and costs every call at exactly $0. ```bash export AI_GATEWAY_API_KEY=vck_... # gateway only — no TypeSafe key needed export TYPESAFE_TRANSPORT=gateway # optional; forces the gateway when both keys exist ``` Gateway keys are created at **Vercel → your team → AI Gateway → API Keys**. ⚠️ **The gateway refuses to serve any request until the Vercel team has a credit card on file**, including the free credits it advertises. The refusal is a `403` with type `customer_verification_required`, and it arrives _before_ the model id is validated — so an otherwise-perfect request fails with a billing error and no hint that the rest of it was fine. A key that has never billed anything still authenticates: the three states are distinguishable, and worth knowing apart when diagnosing a 4xx. | Sent | Response | | ----------------------------------- | ------------------------------------------------------------------------------------------------------- | | No `Authorization` | `401` "Missing Authorization header" | | Wrong key | `401` "Authentication failed. Check that your Vercel credential is valid and has access to AI Gateway." | | Valid key, no card on file | `403` `customer_verification_required` | | Wrong `ai-gateway-protocol-version` | `400` "Unsupported gateway protocol version" | All four were measured against the live service. The protocol-version header is worth singling out: omitting it or sending anything other than `0.0.1` fails the whole request rather than defaulting to a version. --- ## Using it ```ts NeuroLink, readDecisionChoice, readDecisionBoolean, } from "@juspay/neurolink"; const neurolink = new NeuroLink(); const result = await neurolink.tryDecide({ // null when unconfigured or failing state: ticketText, // string OR structured JSON questions: { team: { type: "choice", instructions: "Which team should handle this?", criteria: { billing: "Payments, invoicing, refunds", technical: "Bugs, outages, integrations", sales: "Pricing, upgrades, new accounts", }, }, urgent: { type: "boolean", instructions: "Does this express urgency?" }, frustration: { type: "score", instructions: "How frustrated is the sender?", criteria: ["Calm", "Mildly annoyed", "Clearly frustrated", "Furious"], }, }, }); const team = result && readDecisionChoice(result.answers, "team"); if (team && team.confidence >= 0.7) { assignTo(team.choice); } else { assignToHumanTriage(); // low confidence is a signal, not an error } ``` `readDecisionBoolean` / `readDecisionChoice` / `readDecisionScore` validate at runtime and return `undefined` for a missing id **or** a mismatched type, so no call site needs a type assertion. `ticketText` is attacker-controlled, so the verdict is a hint: keep `assignTo` reversible or put a deterministic check in front of it (see the Untrusted input bullet under [What it is bad at](#what-it-is-bad-at)). Use `decide()` instead of `tryDecide()` when you want the failure to surface; it throws a `ProviderError` whose `cause` carries a typed `kind` (`authentication`, `rate_limit`, `max_tokens_exceeded`, …). **More questions than a provider takes.** A provider that caps the questions in one request (Laya and Cloudflare Clef take 64, Perplexity and XOR 128, OpenAI Decisions 200) refuses a longer map from `decide()` with `max_tokens_exceeded`, except OpenAI Decisions, whose row is advisory: its cap is reported and used to split, but `decide()` sends a longer map whole and leaves the answer to the server. `tryDecide()`, which every built-in consumer calls, splits the map at the cap instead, keeps the questions in the order given, runs up to four batches at a time and joins the answers into one result: usage is summed, the latency is the slowest batch's, and `requestId` lists the batches' ids. A batch that fails costs only its own questions, which then have no answer (the `read*` helpers return `undefined` for them, and every built-in consumer carries on without that decision); `tryDecide()` returns `null` only when every batch failed. The state and any media are sent with each batch, so a split request costs the state's tokens once for each batch. A provider with no cap (TypeSafe, SubQ, ScaleDown) always gets one request. ### From the CLI The same primitive is available as `neurolink decide [state]`, which calls `decide()` (not `tryDecide()`) and prints one line per answer: ```bash npx @juspay/neurolink decide "Refund request for a damaged item" \ --questions '{"urgent":{"type":"boolean","instructions":"Is this urgent?"}}' ``` To ask about an image, a video or an audio clip, add `--image ` (repeatable), `--video ` or `--audio `. XOR reads one image and audio, Perplexity, Cloudflare Clef and OpenAI Decisions read images only, TypeSafe, Laya, SubQ and ScaleDown read neither, and no shipped provider reads video. With `--audio`, the state may be left out: ```bash npx @juspay/neurolink decide "A product photo from a listing." --provider xor --model xor-omni \ --image ./front.png \ --questions '{"color":{"type":"choice","instructions":"What color is the product?","criteria":{"red":"Mostly red","blue":"Mostly blue"}}}' ``` See the [CLI command reference](/docs/cli/commands.md#decide) for the full flag list, including `--state-file`, `--questions-file`, `--image`, `--video`, `--audio` and `--format json`. ### A choice answer is also a ranking `readDecisionChoice` returns `ranked` — every option sorted by probability, highest first. One `choice` question over N options therefore ranks all N in a single request. This is the basis for picking from a large catalogue. --- ## Images and video A decision provider whose descriptor declares media limits reads images, and possibly one video or one audio clip, alongside `state`. XOR, Perplexity, Cloudflare Clef and OpenAI Decisions read images; XOR also reads audio; TypeSafe, Laya, SubQ and ScaleDown read none. No shipped provider reads video: XOR's gateway drops a video without a word (a solid red clip was answered the same as garbage bytes), so NeuroLink refuses one rather than return a blind answer. Three optional fields on the request carry media, for `decide()` and `tryDecide()` alike: - `images` — up to 8 for Perplexity and OpenAI Decisions (OpenAI's is NeuroLink's own allowance, not a limit OpenAI documents), 4 for Cloudflare Clef, 1 for XOR. - `video` — one video, for a provider that declares video (none today). - `audio` — one clip, for a provider that declares audio (XOR); see [Audio](#audio) below. Each takes the same three input forms: - a `Buffer`; - a local file path; - a `data:image/…`, `data:video/…` or `data:audio/…;base64,` URL. ```ts const result = await neurolink.decide({ provider: "perplexity-decider", state: "A product photo from a listing.", images: ["./front.png", "./back.jpg"], questions: { color: { type: "choice", instructions: "What color is the product?", criteria: { red: "Mostly red", blue: "Mostly blue" }, }, }, }); console.log(result.mediaBytes); // encoded size of the images sent ``` NeuroLink identifies a Buffer or a file from its bytes, not its extension — PNG, JPEG, WebP and GIF images, and MP4, MOV and WebM video — and sends it as a `data:` URL. A `data:` URL you pass yourself must hold base64 image or video content. Clef normalizes `image/jpg` to `image/jpeg`; other data URLs are sent as given. Perplexity and Cloudflare Clef read PNG, JPEG and WebP only, and refuse a GIF before any request. OpenAI Decisions sends every image as an inline data URL and checks no format list, because OpenAI's list is not established. **What is refused.** Everything NeuroLink can check is refused before any request, as a non-retryable `invalid_request`: - an `http(s)` URL — media is not fetched for you, so pass a Buffer, a file path or a `data:` URL; - a string that is not a file path or a `data:` URL, such as bare base64 or a URL with another scheme; - a missing file, a directory, or an empty Buffer or file; - something that is not an image or a video; - more than 8 images, more than 4 for Cloudflare Clef, or more than 1 for XOR; - a request body over the provider's limit: 25 MB for XOR, 32 MiB for Perplexity and for OpenAI Decisions (NeuroLink's own number for the latter), 256,000 bytes for Cloudflare Clef. The limit applies to the encoded body, so the base64 form counts, and a photo usually has to be resized to well under 190 KB before Clef will take it. A file over it is refused from its size, before it is read; - a video, which no shipped provider declares (XOR, Perplexity, Cloudflare Clef, OpenAI Decisions); - an image Perplexity cannot read: one of another type, or over 2,048 tiles of 32 × 32 pixels, which the API would otherwise hold for about a minute before answering 504; - an image Cloudflare Clef cannot read: one that is not PNG, JPEG or WebP; - any media sent to a provider that declares no media capability (TypeSafe, Laya). The message names the providers that accept media. ### Audio XOR hears one clip per request, as WAV, FLAC, Ogg (Vorbis or Opus) or MP3, identified from its bytes and sent as `{ data, format }`. The state may be empty (`state: ""`; the CLI's `--audio` lets you leave it out), and an image may go with it. ```ts const result = await neurolink.decide({ provider: "xor", model: "xor-omni", state: "", audio: "./call.wav", questions: { language: { type: "choice", instructions: "Which language is spoken?", criteria: { english: "English", hindi: "Hindi" }, }, }, }); ``` The model hears the **first 30 seconds** and drops the rest without a word, at about 25 input tokens a second. So a WAV, FLAC or Ogg (Opus or Vorbis) clip that runs longer is refused before any request, its length read from the file; an MP3's length is not read, and only its first 30 seconds count. With no model named and `XOR_MODEL` unset, a request carrying media or a `value` question goes to `xor-omni` and is checked against its window (the catalog's `decide.capableModel`). AAC/M4A is refused by name: it was measured decoding to nothing while the request was still answered. A WAV without a complete `fmt` and `data` chunk is refused too. The result carries `mediaBytes`, the encoded size of the media sent. The `decide` spans carry `decision.images.count`, `decision.audio.count` and `decision.media.bytes`, and never any base64. A deployment started without `OPENJEV_IMAGES=1` answers 200 and silently ignores images, which NeuroLink cannot detect; see the [XOR provider guide](/docs/getting-started/providers/xor.md#troubleshooting). --- ## The one rule: batch, never fan out This inverts the instinct you have from LLMs. **On TypeSafe, question count barely affects latency** (measured against its live API): | questions | round trip | input tokens | | --------- | ---------- | ------------ | | 1 | 393 ms | 310 | | 10 | 390 ms | 481 | | 100 | 423 ms | 2 281 | | 400 | 465 ms | 8 581 | > These are TypeSafe's figures. `perplexity-decider` differs: about 0.3 to 1.1 s > for one question, about 65 ms for each further question (a request takes at > most 128), and an input time that grows faster than linearly with size: 3.9 s > at 65,000 tokens, 10 s at 146,000 and 22.9 s at 251,000. See > [its latency section](/docs/getting-started/providers/perplexity-decider.md#latency-and-the-timeout). > `cloudflare-clef` takes 0.3 to 1.0 s for a small request and 1.1 to 1.3 s for > 64 questions (measured 2026-10-03). A 64-question request with the same > questions and a shorter state took 1.5 s on `clef-flash` and 2.3 s on `clef` on 2026-10-04; see > [its latency section](/docs/getting-started/providers/cloudflare-clef.md#latency-and-the-timeout). > `openai-decisions` has not been timed: its latency is not measured. `scaledown` > has been timed only lightly: 265-token requests took 0.3 to 9.8 s on > 2026-10-20, and a `choice` question is scored once per option, so a request > with many options may need a larger `timeoutMs` than its 30-second default; see > [its timeouts note](/docs/getting-started/providers/scaledown.md#timeouts). On TypeSafe, 400 questions cost ~70 ms more than one. **Concurrent requests, by contrast, queue**: ten parallel calls take ~1.4 s wall with nine landing together at the end, while the server's own upstream time stays flat at 64–169 ms. So on TypeSafe, 400 things in one request take ~465 ms; the same 400 as separate requests take roughly a minute. Add every question you _might_ need to the call you are already making — speculative questions are nearly free on TypeSafe (on Perplexity each costs about 65 ms, up to 128 in a request; Cloudflare Clef takes up to 64), and a second round trip is not. --- ## What NeuroLink uses it for ### Model routing The [classifier router](/docs/features/classifier-router) gains a `jev` strategy, and its default becomes `auto` — resolving to `jev` when a decision provider is configured and `heuristic` when not. One request asks for the difficulty tier, whether the task needs vision/tools/reasoning, whether carrying it out is risky, **and** which pool member to use — all at once, in ~400 ms on TypeSafe's Jev. | | `heuristic` | `llm` | `jev` | | ---------------------- | ------------- | ------------------------------- | --------------------------------------------------- | | Added latency | 0 ms | ~1–8 s | ~400 ms on TypeSafe | | Cost per decision | none | a full LLM call | ~$0.00002 on TypeSafe | | Confidence | keyword score | self-reported (defaults to 0.7) | as the provider reports it (calibrated on TypeSafe) | | Picks a model directly | no | yes | yes | The `jev` column is TypeSafe's figures; the [Perplexity guide](/docs/getting-started/providers/perplexity-decider) gives its latency and the confidence it reports. The [Cloudflare Clef guide](/docs/getting-started/providers/cloudflare-clef) gives its latency; a prompt NeuroLink estimates over 16,000 tokens is refused there and routing falls back to the heuristic, as it does on any failure. Thresholds are **asymmetric**, because the two mistakes do not cost the same: `minUpgradeConfidence` defaults to 0.3 (spending more on a wrong guess costs money) and `minDowngradeConfidence` to 0.6 (spending less on a wrong guess produces a wrong answer). > **The key upgrades routing; it does not switch routing on.** The classifier > router is still opt-in (`classifierRouter.enabled`) and still needs a `pool`, > because NeuroLink cannot invent the set of models you are willing to route > between. What the key changes is _which classifier runs_ inside a router you > already enabled. ### The model catalogue Enabling `classifierRouter.catalog` widens the routable pool beyond what you declared by hand: candidates are built from the 64-model registry (7 providers — see [the model catalogue](/docs/features/classifier-router-catalog) for which), intersected with the credentials this host actually holds, and ranked by a deterministic formula whenever no decision provider is available to choose among them. | | Without `catalog` | With `catalog.enabled` | | -------------- | ------------------------ | ------------------------------------- | | Candidate pool | only the declared `pool` | declared `pool` plus registry matches | | Fallback pick | first pool member | `tierScore()`-ranked, tier-aware | | Cap | none needed | `maxModels`, default 120 | See [the model catalogue](/docs/features/classifier-router-catalog) for how candidates are filtered, rendered, and ranked. ### Per-request context budget A per-request `compactionThreshold` option lowers the point at which history gets compacted, below the 0.8-of-window default. The `jev` strategy can fill it in automatically from a four-level scope rubric (`current-message` through `everything`) — and the mapping is a one-directional invariant: it can only ever lower the 0.8 default, never raise it, because over-filling a window is an unrecoverable provider error. See [per-request context budget](/docs/features/context-budget) for the rubric, the invariant, and how the threshold scales the compaction target. ### Relevance-driven compaction Before the existing positional compaction stages run, an optional Stage 0 asks, per eligible message, whether the current request still needs it — at ~400 ms for the whole batch regardless of message count (on TypeSafe; `perplexity-decider` differs, taking about 0.3 to 1.1 s for one question and about 65 ms for each further one, plus an input time that grows faster than linearly with size; `cloudflare-clef` took 0.3 to 1.0 s for a small request on 2026-10-03, and its endpoint refuses nothing below 16,000 estimated state tokens, but a state that large takes seconds). Only plain user/assistant text is eligible, the most recent messages are never touched, and a message is dropped only on a confident "no." | | Positional stages (1–4) | Stage 0 (relevance) | | ----------------- | ---------------------------------- | ------------------------------------------------------------ | | Basis for keeping | position (recency) | relevance to the current request | | Drop granularity | whole messages / summarized ranges | whole messages | | Runs when | always, once over budget | decision provider configured, request known, and over budget | See [relevance-driven compaction](/docs/features/relevance-compaction) for the eligibility rules, the drop cap, and the separate summary-quality gate on Stage 3. ### Tool / MCP routing The shipped tool router asks a generative model for `{servers: string[]}` on a 15-second budget — a shape that cannot express uncertainty. A decision model instead asks one yes/no question per server, answered with a probability, and a server is excluded only on a confident "no" (`minDropConfidence` default 0.6), because dropping a needed server breaks the turn while keeping an unneeded one only costs a few tokens. A measured wording change moved unrelated servers from a mean probability of 0.31 (dropping 12 of 39 unneeded servers) to a mean of 0.03 (dropping 37 of 39, with zero wrong drops) — seen in [tool / MCP routing by decision model](/docs/features/tool-routing-decision-model), which also covers the exact question shape and its size guards. ### RAG retrieval planning `RAGPipelineConfig.decide` lets each RAG query get its own `topK`/`hybrid`/ `graph`/`rerank` plan instead of one fixed configuration for every query. An explicit per-call `QueryOptions` field always wins over the plan, and a capability the pipeline wasn't configured with can never be switched on by it. See [per-query RAG retrieval planning](/docs/features/rag-retrieval-planning) for the breadth rubric and why its confidence bar is deliberately lower than tool routing's or compaction's. ### One funnel for all five sites Every one of those calls is stamped with a `site` — `routing`, `toolRouting`, `contextRelevance`, `summaryGate` or `ragPlan` (the `DecisionSite` union) — and goes through one private path on `NeuroLink`, which is also where a bound `tryDecide()` lands. For the four sites that run inside a NeuroLink request — `routing`, `toolRouting`, `contextRelevance` and `summaryGate` — that path forwards the outer `generate()` / `stream()` call's per-call `credentials`, `abortSignal` and `requestId` (the top-level option, else `context.requestId`) to the decision, so a request that carries `credentials: { laya: {...} }` routes and compacts against _that_ account rather than the instance's; for `routing` the per-call credentials also count towards the `auto` strategy's activation, so a host that holds no decision key itself still routes a request that carries one. `ragPlan` runs inside a host-wired `RAGPipeline`, outside any NeuroLink request, so it receives only what the host puts on the options it hands `tryDecide` (see "Host-wired consumers" below). The path also adds `decision.site` and `decision.host_question_count` to the `model.decision` span; emits `decision:before` / `decision:after` on the instance emitter; and runs the `decisionHooks` described next. Without hooks or listeners, the decision payload — state and questions — is unchanged; per-call `credentials` are still forwarded, so the full request on the wire (account, base URL) can differ from the instance's. --- ## Riding along: `decisionHooks` Latency on a decision model is flat in question count, so a host with its own questions about the same request pays nothing to ask them in the round trip NeuroLink is already making. `decisionHooks` on the constructor does exactly that — one request per site, never a second: ```ts const neurolink = new NeuroLink({ classifierRouter: { enabled: true, pool }, decisionHooks: { // Called before each site's call with NeuroLink's own questions. Return // extra questions under ids of your choosing, or undefined to add none. extendQuestions: ({ site, state }) => site === "routing" ? { tone: { type: "boolean", instructions: "Is the request polite?" }, team: { type: "choice", instructions: "Which team owns this?", criteria: { payments: "Money movement", platform: "Rest" }, }, } : undefined, // Called with YOUR answers under YOUR ids, plus the full result. onAnswers: ({ site, answers, result }) => { const team = readDecisionChoice(answers, "team"); if (team && team.confidence > 0.7) { tagRequest(team.choice); } }, }, }); ``` What the funnel guarantees: | Concern | Behaviour | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Id collisions | Host questions travel as `host__0`, `host__1`, … on the wire, so they can never collide with `difficulty`, `model`, `server__N`, `msg__N`, …; `onAnswers` maps them back to your ids. | | Malformed questions | Each is checked at runtime (`isDecisionQuestion`); an invalid one is dropped with a warning, its siblings still go. | | The provider's cap | Additions are capped at `maxQuestions − NeuroLink's own count`, dropped from the end with a warning. Without this one question too many would refuse the WHOLE request, and NeuroLink's routing would degrade. This is a count cap, and Laya, XOR (128), Clef, Perplexity and OpenAI Decisions all declare one. TypeSafe caps a request by tokens, not by count: its `decisionLimits()` reading has **no `maxQuestions` key** (absent, never `Infinity`), and every well-formed addition goes on the wire. For TypeSafe (`enforcedLocally: false`) size your questions with `decisionLimits()` and `estimateDecisionStateTokens()` — an over-long host question can still make the request exceed its state-plus-question or combined-request budget, and that refusal is not caught locally. A host question the provider cannot answer — a type outside its `questionTypes`, or a `choice` or `score` past its per-question cap — is dropped on its own, with a warning. | | A throwing or slow hook | Logged at `warn`; the decision proceeds with NeuroLink's own questions. Each hook is bounded by `hookTimeoutMs` (default 2000 ms) because both sit on the request path; the bound must be a finite number from 1 to 2^31 − 1 ms — anything else, `Infinity` included, falls back to the default with one warning, because a timer given such a delay fires immediately. Neither hook can change what NeuroLink does with its own answers — `onAnswers` and the events receive copies. | | An unreadable return | A return value from `extendQuestions` that cannot be read or copied (a proxy, a throwing getter, a function-valued field) is treated as a hook failure: logged at `warn`, and the decision proceeds with NeuroLink's own questions. Every question that is accepted travels as a copy, so editing your object after the hook returned changes nothing on the wire. | | A throwing listener | A `decision:before` / `decision:after` listener that throws is logged at `warn` and the call continues; the events are observe-only, and their `state` / `questions` / `answers` are copies — editing them changes neither the request on the wire nor NeuroLink's own question objects. | | NeuroLink's consumers | See only their own ids, exactly as without hooks. If anything host-facing throws after the call returned, the consumer still gets its own answers from that call; if it throws before, the call is made with NeuroLink's own questions. A host cannot turn a decision into an exception. | | Host-wired consumers | A `RAGPipeline` or `ClassifierRouter` you constructed with `decide: (o) => neurolink.tryDecide(o)` gets the same treatment — the consumer stamps the site, `tryDecide` honours it. Overriding or patching `decide()` on the instance is honoured too: every site call, `tryDecide` included, dispatches through it. | | Question ids | Your ids are ordinary map keys — `__proto__` or `constructor` come back under exactly that name in `onAnswers` and `hostAnswers`. | | No hooks, no provider | Nothing changes. Without a decision provider — none in the environment, the instance `credentials` or the request's per-call `credentials` — no hook runs and no event fires; `tryDecide` returns `null` exactly as it did before hooks existed. | The two events are observe-only and fire once per site call whether or not it produced a result, so a decision path that has stopped working stays visible: ```ts neurolink.getEventEmitter().on("decision:after", (event) => { const { site, answers, hostAnswers, latencyMs, provider, model, result } = event as DecisionAfterEvent; // result is null when the call failed }); ``` `decision:before` carries `{ site, state, questions, hostQuestionCount }` — everything about to be sent, host questions already namespaced — plus the `sessionId` and `requestId` of the surrounding request, so a host can join the events of one turn. Both events fire only when a decision provider is configured; without one there is no call to observe. --- ## Limits and gotchas ### Reading the limits before you send: `decisionLimits()` `neurolink.decisionLimits({ provider?, model?, credentials? })` returns the figures the pre-flight check compares against, resolved for one model — provider as `decide()` resolves it, model as `model ?? the model decide() sends` (the one registered for the provider: `LAYA_MODEL` / `TYPESAFE_MODEL` as read when providers were registered, else the default — a later change to the variable moves neither), the per-model entry flattened over the base: ```ts const limits = neurolink.decisionLimits(); // null with no decision provider // laya, typed-decisions → { provider: "laya", model: "typed-decisions", // maxStateTokens: 768, maxQuestions: 64, nonAsciiTokensPerChar: 1.5, // enforcedLocally: true } // typesafe → { maxStateTokens: 33000, enforcedLocally: false } // (no maxQuestions key: TypeSafe caps by tokens, not by count) // xor, xor-latest → { maxStateTokens: 120000, maxQuestions: 128, // questionTypes: ["boolean", "choice", "score", "value", "choice-unknown"], // maxScoreLevels: 10, maxChoiceOptions: 64, nonAsciiTokensPerChar: 1, // media: { maxImages: 1, video: false, maxRequestBytes: 25000000, // audio: { maxSeconds: 30 } }, // enforcedLocally: true } // (28,000 on xor-omni; `media` is absent for the text-only providers, and // `questionTypes` for every provider that reads only the default three) // openai-decisions → { maxStateTokens: 922000, maxQuestions: 200, // media: { maxImages: 8, video: false, maxRequestBytes: 33554432 }, // enforcedLocally: false } // (922,000 is the model page's input figure, reported and never enforced; // 200 is the question cap in OpenAI's Python SDK: tryDecide() splits at it // and host additions stop at it, but decide() does not refuse above it, and // going over was not tried live; the three media numbers are NeuroLink's own // allowance, not OpenAI's) // scaledown → null: it declares no limits, so a named call reads null and // nothing is refused locally on the size of a state if ( limits && estimateDecisionStateTokens(state, limits) > limits.maxStateTokens ) { state = shorten(state); } ``` `maxQuestions` is present only for a provider that caps by question count (Laya, XOR, Cloudflare Clef, Perplexity, OpenAI Decisions); a reading without the key has no count cap, and a host should test for the key rather than compare against `Infinity`. `media` is present only for a provider that reads images or video (XOR, Perplexity, Cloudflare Clef, OpenAI Decisions); its absence is what the media refusal for TypeSafe, Laya, SubQ and ScaleDown is based on. `enforcedLocally` says who refuses: NeuroLink itself, before any network call (Laya and XOR, whose servers would silently truncate or fail inside the engine), or the provider's server (TypeSafe and OpenAI Decisions, whose descriptor rows are marked `advisory` and are _reported_ but never enforced here — a local refusal would turn a server ceiling into a client one that drifts from it). `estimateDecisionStateTokens` is the very function the pre-flight refusal uses, so a state it sizes as fitting is sent and one it sizes as over is refused; pass the reading so non-ASCII text is charged at the model's measured rate. A named `provider` is read whether or not it is configured — its limits are facts about the model — while the default requires a configured provider, as `tryDecide()` does. **Laya reads far less than Jev.** About 768 tokens of state on `typed-decisions` and `multilingual`, and 320 on `english`, `auto` or an unrecognised model name, against Jev's ~33,000. Laya's server does not refuse a longer state; it answers from the first 1,024 tokens (512 on `english`). So the provider estimates the state's size — counting non-Latin characters at a rate measured per checkpoint — and refuses anything over the limit locally with `max_tokens_exceeded`, before any network call. The estimate errs toward refusing. **XOR's two models have different windows.** Measured through a LiteLLM gateway in October 2026: `xor-latest` reads 131,072 tokens and `xor-omni` 32,768, and each refuses a longer input. NeuroLink allows 120,000 and 28,000 estimated tokens of state (about four characters per token for ASCII, one token per character for other scripts), leaving room for the questions, about 600 tokens for an image and about 25 a second of audio, and refuses more locally with `max_tokens_exceeded`. Dense text — JSON, digits — runs above the estimate, so a state near the limit can still be refused by the server; that arrives as `max_tokens_exceeded`, not retried. A request takes up to 128 questions (more is split by `tryDecide()`), a `choice` 2 to 64 options counting `unknown`, and a `score` 2 to 10 levels; past any of these it is refused before any request. The timeout grows with the state: 5 seconds plus 150 ms for every full 1,000 estimated tokens, because a 120,000-token state took about 18 seconds. **Perplexity's input ceiling covers more than the state.** Measured on a real account in October 2026: the server reads under 262,144 input tokens per request, counted over the state, the questions and the images, and refuses input of 262,144 tokens or more with an explicit 400 instead of cutting the state off. Images are billed as input tokens, about one for each 32 × 32 tile plus 95 to 103 more in the single-image requests measured, which looks like fixed request overhead and not a charge per image. They count toward the ceiling at one token for each tile: eight 2,048-tile images added 16,384 to a request that was then refused. It takes at most 128 questions and 8 images. The documented 32 MiB body limit was not measured. NeuroLink's own window is 100,000 estimated tokens of state, a deliberate local limit and not the server's; a state estimated above it, or more than 128 questions in a `decide()` call, is refused locally with `max_tokens_exceeded` (`tryDecide()` splits the questions at 128). The estimate is about 3.8 characters per token for ASCII text and half a token per non-ASCII character (measured: CJK 0.46 tokens per character, Devanagari 0.44), and it counts the state's text only. Measured on 40,000-character samples, it over-counts English prose (4.34 characters per token) and is close for TypeScript (3.84). It runs about 13% low on minified JSON (3.36), which stays far under the ceiling at the window: 380,000 characters of JSON are about 113,000 real tokens. It runs much lower on log lines (1.35) and arrays of integers (1.16), which are about 281,000 and 328,000 real tokens for the same 380,000 characters, and on emoji (2.6 tokens per code point), so a state that is mostly one of those can pass the window and still be refused by the server. A request that passes it can also be refused when the questions or the images push the input over. That refusal arrives as `max_tokens_exceeded` too, whichever of the server's two wordings it uses (one for text alone, one when images are in the request), and is not retried. A state estimated above the window needs a smaller state or another provider: no setting raises it, so a larger state that would fit the server can be sent only through a decision provider with a larger window. Perplexity documents a request rate of 10 per second for the account's tier, and on the account tested 14 parallel requests got 10 answers and 4 replies of 429. **The Workers AI endpoint's state window changed (hosted service or model: unknown).** On 2026-10-03 and 2026-10-04 it ignored Clef state text past about 2,048 tokens, far less than the documented 64K (a 133-call follow-up on 2026-10-04 found the same cut on both models). On 2026-10-07 `clef-flash` read a fact at the very end of states of 190,153 tokens (a digit array) and 86,819 (prose), and `clef` read 52,154 tokens of prose and answered HTTP 529, code 5012, for the 190,153-token array. The estimator charges digits 1 token each, punctuation 0.75, astral characters 3 and other non-ASCII characters 1.5, with other text about 4 characters a token. It refuses more than 16,000 estimated state tokens with `max_tokens_exceeded`, before any network call: at most about 18,400 real tokens (it counts prose 35% over and a digit array 14% under), 2.8 times fewer than `clef` was seen to read. The rates now approximate real tokens and no longer stand for a cut; other object shapes and Unicode sequences may differ. A request takes at most 64 questions (`tryDecide()` splits larger maps) and four images. Exactly four succeeded and a fifth was refused on both models. NeuroLink retains a 256,000-byte cap for the encoded body, including base64 images. Both models accepted 520,000 text characters and refused 525,000 with 413/code 5021 on 2026-10-04; `clef-flash` had accepted 262,000 and refused 270,000 on 2026-10-03. On 2026-10-05 both models accepted PNG request bodies up to 492,485 bytes and refused 532,505 (`clef-flash`) and 532,499 (`clef`) with the same 413. For plain-text bodies the rule was located on 2026-10-23: the 413 comes when the body in characters / 4 (bytes, for plain ASCII text) exceeds twice the model's context window, and `clef-flash`'s window had fallen from 65,536 to 24,576 tokens, which puts its edge for plain text at 196,608 bytes. A request with an image is not held to that edge: live case 19.14 sends about 253 KB to `clef-flash` and it is answered. See the [Clef guide's limits](/docs/getting-started/providers/cloudflare-clef.md#limits). The 413/code 5021 gate counts the request's text, not its images (measured on 2026-10-23 and 2026-10-24): the characters of the JSON without the `images` array, over four, against twice the context window Cloudflare prints (24,576 tokens for `clef-flash`, 65,536 for `clef`). NeuroLink therefore keeps the 256,000-byte cap on the whole body for images and also holds the text alone to 195,584 characters on `clef-flash` and 523,264 on `clef`, refusing more locally as `max_tokens_exceeded`. See [What the 413 counts](/docs/getting-started/providers/cloudflare-clef.md#what-the-413-counts). **Two separate size ceilings** (TypeSafe), both enforced: - `state` + the **single longest** question ≤ **~33 000 tokens** (measured exactly: 33 002 accepted, 33 003 rejected). Usually the binding one. - `state` + **all** questions combined ≤ **~64 000 tokens**. Questions do _not_ compete with state for the 33 K budget — a near-ceiling state plus 400 extra questions is accepted. **Three different error envelopes.** TypeSafe returns `detail` as an object for application errors and as an **array** for schema validation; the gateway uses neither and returns `{"error":{"message","type"}}`. The provider normalises all three into one `DecisionError`. The validation shape echoes your `input` back, so it is never logged or surfaced. On the gateway, `error.type` decides the kind, not the HTTP status — a `403` carrying `invalid_request_error` is a bad request, not a bad credential, and must not disable the provider instance. Reading the status alone would trip the auth circuit breaker on a working key. **403 vs 401 are inverted** on the direct API, from the usual convention and from TypeSafe's own docs: a _missing_ `Authorization` header returns **403**, an _invalid_ key returns **401**. The gateway does not share this quirk — it returns **401** for both, and reserves **403** for account state. **On TypeSafe, `max_tokens_exceeded` arrives with no `message` field** — the one error a long-context caller is most likely to hit. The provider supplies the sentence. Perplexity's over-length 400 does carry a message, and its provider reads the kind from that text. **Latency**: TypeSafe's p50 is ~400 ms warm, but the first call after idle measured 2.0–2.7 s. The default timeout is 5 s for that reason, and every internal call site is fail-open regardless. Perplexity's time scales with the input and with the question count. Input time grows faster than linearly: 3.9 s at 65,000 tokens, 10 s at 146,000 and 22.9 s at 251,000 (about 17,000, 15,000 and 11,000 tokens per second), against 0.3 to 1.1 s for one question on a short state, plus about 65 ms for each question after the first (128 minimal questions took 8.9 s). Its default timeout is 10 s plus 100 ms for each question, so 10.1 s for one question and 22.8 s for 128, and a `timeoutMs` you pass is used as given. A timeout is retried once, so a request that stalls can take about twice the timeout. Pass a larger `timeoutMs` for any state of more than about 100,000 real tokens, which log lines and arrays of numbers reach well inside the window. The [provider guide](/docs/getting-started/providers/perplexity-decider.md#latency-and-the-timeout) lists the timeout setting for each built-in consumer. On 2026-10-03 Cloudflare Clef answered a small request in 0.3 to 1.0 s, and 64 questions in 1.1 s on `clef-flash` and 1.3 s on `clef` (1.5 s and 2.3 s on 2026-10-04); its default timeout is 5 s, and `timeoutMs` changes it for one call. **Privacy**: when enabled, the `state` you send leaves the machine. For model routing that is the prompt text; for compaction and tool routing it is earlier conversation text. With no decision provider configured, nothing is transmitted. A `PERPLEXITY_API_KEY` set for the Perplexity text provider counts as a decision provider's key, so with it set and none of TypeSafe, Laya, XOR or SubQ configured, the state of a decision goes to Perplexity. The provider guide lists [what each consumer sends](/docs/getting-started/providers/perplexity-decider.md#what-is-sent-to-perplexity). Likewise `CLOUDFLARE_API_KEY` with `CLOUDFLARE_ACCOUNT_ID`, set for the Workers AI text provider, counts as a decision provider's credentials: with them set and none of TypeSafe, Laya, XOR, SubQ or Perplexity configured, the state of a decision goes to Cloudflare. And an `OPENAI_API_KEY` set for the OpenAI chat provider counts as a decision provider's key as well: with it set and none of the six earlier providers configured, the state of a decision goes to OpenAI, unless `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL` names another host than `https://api.openai.com`, in which case that key is a gateway's and is not used by default. `SCALEDOWN_API_KEY`, which nothing else reads, sends the state to ScaleDown when it is the only decision key. **No model-registry lookup**: a decision provider reads its own model setting (`_MODEL`, else its default), so `decide()` does not load the model registry that chat providers use to look up a default model (`MODEL_CONFIG_URL`, else `http://localhost:3001`, then the GitHub copy of `config/models.json`, then `./config/models.json`). The registry lists no decision provider. **Cost**: TypeSafe, $0.042 per million input tokens, output free. Perplexity, $0.04 per million input tokens (image tokens included), output free. Cloudflare Clef, $0.24 per million input tokens for `clef` and $0.09 for `clef-flash`; no output price is listed. OpenAI Decisions, $0.10 per million input tokens, input only, from [OpenAI's Decisions guide](https://developers.openai.com/api/docs/guides/decisions) as read on 2026-10-07; regional and long-context multipliers are not modelled. ScaleDown, USD 0.05 per million input tokens, output not charged: a list price from its launch post and a response's `usage.cost`, reported to this project by the marketing session on 2026-10-15 and not measured here. NeuroLink prices ScaleDown from the reply's input tokens at that rate and does not read `usage.cost`. --- ## What it is bad at "Cannot hallucinate" is a claim about output **shape**, not answer **correctness**: a decision model cannot return malformed JSON or an option you did not offer, but it can still be wrong. TypeSafe reports ~68% accuracy on its own 711-case benchmark, against ~73% for a frontier model. It wins cost and latency on every row and loses accuracy on every row — so it is right for decisions that are **gated and reversible**, and wrong for final answers. - **It reads literally.** It answers the question you wrote, not the one you meant. Split an ambiguous question into two and combine them in code. - **Ask about the act, not the subject.** "This task touches money" scores high on ordinary code that merely _concerns_ money. The risk question in `classifyJev` is worded to exclude writing and testing such code, precisely because the naive phrasing escalated everything. - **It is not a calculator.** Counting, arithmetic and date comparison are unreliable — dates are read as text, not ordered quantities. A `score` is for thresholding and ranking, not for reading an exact magnitude off. - **Irrelevant state costs accuracy.** Filter before sending. - **It never explains itself.** No rationale field exists, which rules it out where a decision must be auditable. - **Option order can matter.** Test with reordered `criteria` if a call is close. - **Don't invert criteria.** A `boolean` whose `true` description means "no" performs measurably worse. - **Untrusted input.** Any text in `state` can steer a verdict: a user prompt, a ticket, an earlier message, a retrieved document, tool output, a transcript, a third-party server's description. A decision model can only return an option you offered, but text written to push it can still pick the option the author wants. The built-in consumers are advisory and fail-open, and none of them feeds human-in-the-loop approval or a guardrail. Their reach is bounded, not zero. For example, a steered verdict can withhold a declared server's tools for the turn, drop earlier messages (up to half of the eligible ones by default), change the model tier or pick any configured model, set a retrieval plan (`topK`, hybrid, graph, rerank), lower the compaction threshold for one request, or decide whether a transcript substitution is applied. Each stays inside what the host configured: a model pick must be a configured candidate, a retrieval plan cannot switch on a capability the pipeline lacks, and the compaction threshold can only stay at or go below its 0.8 default. Tools and messages go only on a confident "no" (0.6 by default). A tier verdict at or above neutral clears a 0.3 bar (default) and one below it a 0.6 bar (default), and a risk reading above 0.7 raises the tier to "hard" or above with no bar. Confidence does not defend against this: it says how decided the model is, not whether the text was written to steer it. Do not make a `decide` verdict the only check before an irreversible or security-sensitive action; keep a deterministic check or a human approval in front of it. Tune thresholds on your own labelled data if the decision matters, and once you have, pin `TYPESAFE_MODEL` to a version id such as `jev-1.13.0` — `jev-latest` is an alias and can move under you, invalidating a tuned threshold silently. --- ## Adding another decision provider The `decide` inference type is provider-neutral by construction. Another decision model needs: 1. An `AIProviderName` member and a `Models` enum (`src/lib/constants/enums.ts`, **outside** the generated regions). 2. A provider class extending `SystemOneDecisionProvider` (`src/lib/providers/systemOneDecision.ts`), which owns the request loop, retries, the auth circuit breaker and answer parsing, and supplies the throwing `getAISDKModel()` / `executeStream()` stubs, the same shape the embedding-only providers (`voyage.ts`, `jina.ts`) use. The class supplies its endpoint, headers, body, error parsing and messages. 3. A descriptor with **`inferenceKinds: ["decide"]`**, no auto-select ranks, and `healthCheck: "env-only"`. That one field is what keeps a text-less model out of every generation fallback chain; nothing else needs to know the provider by name. A provider that reads images or video also declares `decisionLimits.media`; without it, a request that carries media is refused before any network call. 4. A registration block, a credentials slice, a manifest, and the usual Tier-3 onboarding artifacts — `pnpm run verify:provider-onboarding` enumerates them. The Tier-2 catalog JSON path cannot be used: its schema pins `tier: 2`, accepts only an 8-flag text-generation capability vocabulary, and requires `defaultMaxOutputTokens` and `pricingPerMTok.output` — none of which a model that emits no text can honestly supply. --- ## Testing ```bash pnpm run test:decide # live + degradation pnpm run test:providers-mocked # the mocked wire contract ``` The suite drives `dist/index.js` only. Live tests skip without `TYPESAFE_API_KEY`; the degradation and discriminator tests run unconditionally, because "behaves correctly with no key" and "a text-less provider is unreachable from generation" are the contracts that matter most. --- ## Embeddings # Embeddings > **Status**: Stable | **Availability**: SDK + CLI + Server ## Overview Embeddings convert text into dense numerical vectors that capture semantic meaning. Two texts with similar meanings produce vectors that are close together in the embedding space, enabling use cases like: - **Semantic search** -- find documents by meaning rather than exact keyword match - **RAG pipelines** -- retrieve relevant context before generating answers - **Similarity comparison** -- measure how related two pieces of text are - **Clustering and classification** -- group or categorize text automatically NeuroLink exposes embeddings through two provider methods (`embed()` and `embedMany()`), two server endpoints, and indirectly through the CLI's RAG commands. Every implementation calls its provider's embeddings API directly. ## Quick Start ```typescript const provider = await ProviderFactory.createProvider("openai"); const vector = await provider.embed("How do I reset my password?"); // vector: number[] -- e.g., 1536 dimensions for text-embedding-3-small ``` ## Provider Support Nine providers implement embedding support: OpenAI, Google AI Studio, Google Vertex, Amazon Bedrock, Cohere, Voyage, Jina, Ollama, and LiteLLM. Ollama requires a locally available embedding model; LiteLLM requires an embedding deployment on its gateway. Other providers throw a descriptive error when `embed()` or `embedMany()` is called (see [Unsupported Providers](#unsupported-providers) below). | Provider | Default Model | Env Override | Dimensions | | ---------------- | ------------------------------ | --------------------------- | -------------------- | | OpenAI | `text-embedding-3-small` | `OPENAI_EMBEDDING_MODEL` | 1536 | | Google AI Studio | `gemini-embedding-001` | `GOOGLE_AI_EMBEDDING_MODEL` | 3072 | | Google Vertex | `text-embedding-004` | `VERTEX_EMBEDDING_MODEL` | 768 | | Amazon Bedrock | `amazon.titan-embed-text-v2:0` | `BEDROCK_EMBEDDING_MODEL` | 1024 | | Cohere | `embed-english-v3.0` | `modelName` argument | Model dependent | | Voyage | `voyage-3.5` | `VOYAGE_MODEL` | Model dependent | | Jina | `jina-embeddings-v3` | `JINA_MODEL` | Model dependent | | Ollama | `nomic-embed-text` | `OLLAMA_EMBEDDING_MODEL` | Model dependent | | LiteLLM | `gemini-embedding-001` | `LITELLM_EMBEDDING_MODEL` | Deployment dependent | Google AI Studio and Google Vertex also accept `GOOGLE_EMBEDDING_MODEL` as a shared fallback environment variable. Amazon Bedrock also accepts `AWS_EMBEDDING_MODEL` as an alternative environment variable. ## SDK API ### `provider.embed(text, modelName?)` Generate an embedding vector for a single text string. **Parameters:** | Name | Type | Required | Description | | ----------- | -------- | -------- | ------------------------------------------------------ | | `text` | `string` | Yes | The text to embed | | `modelName` | `string` | No | Override the default embedding model for this provider | **Returns:** `Promise` -- the embedding vector. ```typescript // Use the provider's default embedding model const provider = await ProviderFactory.createProvider("googleAiStudio"); const embedding = await provider.embed("NeuroLink supports many AI providers"); console.log(embedding.length); // 3072 // Override the model const embedding2 = await provider.embed( "Custom model example", "gemini-embedding-001", ); ``` ### `provider.embedMany(texts, modelName?)` Generate embedding vectors for multiple texts in a single batch. Each provider implementation handles its own batching, so a model that imposes a batch-size limit is chunked to fit it. Amazon Bedrock processes each text individually via `Promise.all` because the Titan Embed API accepts one input at a time. **Parameters:** | Name | Type | Required | Description | | ----------- | ---------- | -------- | ------------------------------------------------------ | | `texts` | `string[]` | Yes | The texts to embed | | `modelName` | `string` | No | Override the default embedding model for this provider | **Returns:** `Promise` -- one embedding vector per input text. ```typescript const provider = await ProviderFactory.createProvider("openai"); const embeddings = await provider.embedMany([ "First document about authentication", "Second document about billing", "Third document about deployment", ]); console.log(embeddings.length); // 3 console.log(embeddings[0].length); // 1536 ``` ### Response validation Cohere, Voyage, and Jina reject responses containing empty vectors or values that are not finite numbers. This changes malformed responses that previously returned an empty or unusable vector into rejected promises. Valid vectors, including zero and negative values, retain their original values. Each batch must return one vector per input. Voyage and Jina additionally require complete index coverage and restore the input order when the response arrives out of order. Cohere's float envelope and legacy flat vector envelope are both supported. Cohere splits inputs at 96 texts and Voyage at 128; a malformed later batch rejects the entire operation instead of returning partial results. Passing an empty input array to these three providers returns `[]` without a request. Validation errors retain the providers' existing error types: `ProviderError` for Cohere and Voyage, and `Error` for Jina. These checks validate the response boundary; they do not establish a vendor model's availability. ## Server API The NeuroLink server exposes two embedding endpoints under the `/api/agent` route group. Both default to the `openai` provider when `provider` is omitted. ### `POST /api/agent/embed` Generate an embedding for a single text. **Request body:** ```json { "text": "How do I configure billing?", "provider": "openai", "model": "text-embedding-3-small" } ``` | Field | Type | Required | Description | | ---------- | -------- | -------- | ------------------------------------------------ | | `text` | `string` | Yes | Non-empty text to embed | | `provider` | `string` | No | Provider name (default: `"openai"`) | | `model` | `string` | No | Embedding model name (default: provider default) | **Response (200):** ```json { "embedding": [0.0123, -0.0456, 0.0789, "..."], "provider": "openai", "model": "text-embedding-3-small", "dimension": 1536 } ``` ### `POST /api/agent/embed-many` Generate embeddings for multiple texts in one request. **Request body:** ```json { "texts": ["First document", "Second document", "Third document"], "provider": "vertex", "model": "text-embedding-004" } ``` | Field | Type | Required | Description | | ---------- | ---------- | -------- | ------------------------------------------------ | | `texts` | `string[]` | Yes | 1 to 2048 non-empty strings | | `provider` | `string` | No | Provider name (default: `"openai"`) | | `model` | `string` | No | Embedding model name (default: provider default) | **Response (200):** ```json { "embeddings": [ [0.012, -0.045, "..."], [0.034, -0.067, "..."], [0.056, -0.089, "..."] ], "provider": "vertex", "model": "text-embedding-004", "count": 3, "dimension": 768 } ``` **Error response (validation failure):** ```json { "error": { "code": "VALIDATION_ERROR", "message": "Invalid request body", "details": [ { "path": "text", "message": "Text is required", "code": "too_small" } ] }, "metadata": { "timestamp": "2025-05-01T12:00:00.000Z", "requestId": "req-abc123" } } ``` **Error response (provider failure):** ```json { "error": { "code": "EXECUTION_FAILED", "message": "Embedding generation is not supported by the anthropic provider. Supported providers: openai, vertex/google, bedrock." }, "metadata": { "timestamp": "2025-05-01T12:00:00.000Z" } } ``` ## Unsupported Providers Calling `embed()` or `embedMany()` on a provider that does not implement embeddings throws an `Error` with a message listing the supported providers and example models: ``` Embedding generation is not supported by the anthropic provider. Supported providers: openai, vertex/google, bedrock, cohere, voyage, jina. Use an embedding model like text-embedding-3-small (OpenAI), text-embedding-004 (Vertex), embed-english-v3.0 (Cohere), voyage-3 (Voyage), jina-embeddings-v3 (Jina), or amazon.titan-embed-text-v2:0 (Bedrock). ``` Providers that currently do **not** support embeddings include: Anthropic, Mistral, Hugging Face, Azure OpenAI, and SageMaker. To generate embeddings when using one of these providers for text generation, create a second provider instance from a supported embedding provider: ```typescript // Use Anthropic for generation const chatProvider = await ProviderFactory.createProvider("anthropic"); // Use OpenAI for embeddings const embedProvider = await ProviderFactory.createProvider("openai"); const vector = await embedProvider.embed("Text to embed"); ``` ## CLI Usage There is no standalone `neurolink embed` CLI command. Embeddings are used indirectly through the RAG CLI commands, which handle embedding generation automatically during document indexing and querying: ```bash # Index documents (generates embeddings internally) neurolink rag index ./docs/guide.md --indexName my-docs --provider vertex # Query with automatic embedding of the query string neurolink rag query "What are the main features?" --indexName my-docs --provider vertex ``` The RAG commands select an appropriate embedding model based on the configured provider. You can override the model with `--model`: ```bash neurolink rag index ./docs/guide.md \ --indexName my-docs \ --provider openai \ --model text-embedding-3-large ``` The embedding model resolution order for RAG commands is: 1. `--model` flag (if the value matches an embedding model pattern) 2. `NEUROLINK_EMBEDDING_MODEL` environment variable 3. Provider-specific environment variable (e.g., `VERTEX_EMBEDDING_MODEL`) 4. Provider's default embedding model 5. Fallback to OpenAI `text-embedding-3-small` ## Integration with RAG Embeddings are a foundational building block for RAG pipelines. NeuroLink's simplified RAG API (`rag: { files }`) handles embedding generation internally, so you do not need to call `embed()` directly: ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "What are the key features?" }, rag: { files: ["./docs/guide.md"], chunkSize: 512, topK: 5, }, }); ``` For full control over the embedding and retrieval steps, use `createVectorQueryTool` with explicit `embed()` calls: ```typescript NeuroLink, createVectorQueryTool, InMemoryVectorStore, ProviderFactory, } from "@juspay/neurolink"; // Generate embeddings manually const embedProvider = await ProviderFactory.createProvider("openai"); const vectors = await embedProvider.embedMany([ "Document about authentication", "Document about billing", ]); // Store in a vector store const store = new InMemoryVectorStore(); await store.upsert("knowledge", [ { id: "doc1", vector: vectors[0], metadata: { text: "Document about authentication" }, }, { id: "doc2", vector: vectors[1], metadata: { text: "Document about billing" }, }, ]); // Create a query tool and use it with generate() const ragTool = createVectorQueryTool( { id: "knowledge-search", description: "Search the knowledge base", indexName: "knowledge", embeddingModel: { provider: "openai", modelName: "text-embedding-3-small" }, topK: 5, }, store, ); const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "How does authentication work?" }, tools: { [ragTool.name]: ragTool }, }); ``` For more details on RAG pipelines, see the [RAG Document Processing Guide](/docs/tutorials/rag). ## Environment Variables | Variable | Provider(s) | Description | | --------------------------- | ------------------------------- | ----------------------------------------------------------------------- | | `OPENAI_EMBEDDING_MODEL` | OpenAI | Override OpenAI default embedding model | | `GOOGLE_AI_EMBEDDING_MODEL` | Google AI Studio | Override AI Studio default embedding model | | `VERTEX_EMBEDDING_MODEL` | Google Vertex | Override Vertex default embedding model (default: `text-embedding-004`) | | `GOOGLE_EMBEDDING_MODEL` | Google AI Studio, Google Vertex | Shared fallback for Google providers | | `BEDROCK_EMBEDDING_MODEL` | Amazon Bedrock | Override Bedrock default embedding model | | `AWS_EMBEDDING_MODEL` | Amazon Bedrock | Alternative Bedrock env var | | `VOYAGE_MODEL` | Voyage | Override the provider's default embedding model | | `JINA_MODEL` | Jina | Override the provider's default embedding model | | `OLLAMA_EMBEDDING_MODEL` | Ollama | Locally available embedding model | | `LITELLM_EMBEDDING_MODEL` | LiteLLM | Embedding model or deployment served by the gateway | | `NEUROLINK_EMBEDDING_MODEL` | All (CLI RAG only) | Global override for RAG CLI commands | ## Key Files | File | Purpose | | -------------------------------------- | ------------------------------------------------------------------------------ | | `src/lib/core/baseProvider.ts` | Default `embed()` / `embedMany()` stubs | | `src/lib/providers/openAI.ts` | OpenAI embedding implementation | | `src/lib/providers/googleAiStudio.ts` | Google AI Studio embedding implementation | | `src/lib/providers/googleVertex.ts` | Google Vertex embedding implementation | | `src/lib/providers/amazonBedrock.ts` | Amazon Bedrock embedding implementation | | `src/lib/server/routes/agentRoutes.ts` | Server `/embed` and `/embed-many` routes | | `src/lib/server/utils/validation.ts` | `EmbedRequestSchema`, `EmbedManyRequestSchema` | | `src/lib/server/types.ts` | `EmbedRequest`, `EmbedResponse`, `EmbedManyRequest`, `EmbedManyResponse` types | | `src/lib/types/providers.ts` | `AIProvider` type with embedding methods | ## See Also - [RAG Document Processing Guide](/docs/tutorials/rag) -- end-to-end RAG pipelines using embeddings - [SDK API Reference](/docs/sdk/api-reference) -- SDK API reference --- ## Enterprise Human-in-the-Loop System # Enterprise Human-in-the-Loop System > **Since**: v7.39.0 | **Availability**: SDK :::danger[Most of this page is a design sketch, not a reference] **Treat every code sample below as the target API unless it appears in "Currently available" immediately after this box.** A heading marked `(Planned)` has examples that use configuration keys or behaviour that do not exist, and `(Planned)` is not a promise of a date. The sections under "Quick Start (5 Minutes)" are covered by that heading's own label. None of `requireApproval`, `reviewCallback`, `statusCallback`, `mode`, `confidenceThreshold`, `contentPatterns`, `escalationPolicy` or the object form of `auditLog` exists in `src/lib/types/hitl.ts` or is handled by `src/lib/hitl/hitlManager.ts`. `validateConfig` does not reject unknown keys either, so a config copied from this page is **accepted silently** and every one of those keys is dropped — approval gates that never fire, with no error. That includes the compliance sections. The HIPAA / SOC2 / GDPR examples show an `auditLog` storage backend and an `escalationPolicy` that do not exist; do not cite them as evidence of a control. Tracking: [#752](https://github.com/juspay/neurolink/issues/752). ::: ## Executive Summary This section describes the system the rest of this page is a design for. Today NeuroLink ships event-based tool approval and a log of each request and decision (see "Currently available"). It does not ship escalation, asynchronous review or an audit store, and it holds no HIPAA, SOC2 or GDPR certification or control. ### Strategic Value Proposition - **Risk Mitigation**: Prevent costly AI mistakes through mandatory human checkpoints - **Regulatory Compliance (target)**: Produce the review records regulated industries ask for. Today `auditLogging` only writes a log line; compliance is the deployer's responsibility - **Trust & Transparency**: Build stakeholder confidence with auditable AI decisions - **Continuous Improvement**: Capture human expertise to improve AI accuracy over time ### When to Use HITL **Required for:** - Medical diagnosis and treatment recommendations - Financial transactions above risk thresholds - Legal document generation and review - Code execution in production environments - Personal data modification or deletion - Irreversible operations (send email, post to social media) **Not recommended for:** - Read-only operations (information retrieval) - Low-stakes content generation - Development/testing environments - High-volume, low-risk automation --- ## Quick Start (5 Minutes) — target API, not implemented :::warning The configuration in this section is **not implemented**. Use ["Currently available"](#currently-available) above for a setup that works. ::: ### Installation HITL is built into NeuroLink SDK v7.39.0+. No additional packages required: ```bash npm install @juspay/neurolink@latest # or pnpm add @juspay/neurolink@latest ``` ### Basic Configuration (Planned) Minimal setup for tool-based approval workflow: ```typescript const neurolink = new NeuroLink({ hitl: { enabled: true, requireApproval: ["writeFile", "deleteFile", "executeCode"], reviewCallback: async (action, context) => { // Your approval logic - integrate with Slack, email, custom UI console.log(` Approval needed: ${action.tool}`); console.log(` Arguments:`, action.args); // Example: Simple prompt-based approval (replace with your system) const approved = await promptUser( `Allow AI to ${action.tool} with args ${JSON.stringify(action.args)}?`, ); return { approved, reason: approved ? "User authorized" : "User denied", reviewer: "admin@company.com", }; }, }, }); ``` ### First Approval Request Complete end-to-end example with error handling: ```typescript try { const result = await neurolink.generate({ input: { text: "Delete the temporary files in the /tmp directory", }, provider: "anthropic", tools: [ { name: "deleteFile", description: "Delete a file from filesystem", requiresConfirmation: true, // Triggers HITL execute: async (args) => { const fs = await import("fs/promises"); await fs.unlink(args.path); return { success: true, deletedPath: args.path }; }, }, ], }); console.log(result.content); } catch (error) { if (error.code === "USER_CONFIRMATION_REQUIRED") { // Handle approval workflow const approvalResult = await handleApproval(error.details); if (approvalResult.approved) { // Retry with confirmation const retryResult = await retryWithConfirmation(error.details); console.log(retryResult); } } } ``` --- ## Core Concepts ### 1. Approval Workflows The target design supports both synchronous (blocking) and asynchronous (non-blocking) approval patterns. Today only the blocking, event-based flow under "Currently available" exists: #### Synchronous Approval (Blocking) (Planned) AI operation pauses until human approves or rejects: ```typescript const neurolink = new NeuroLink({ hitl: { enabled: true, mode: "synchronous", // Default timeout: 300000, // 5 minutes max wait reviewCallback: async (action, context) => { // Blocks here until approval received return await showApprovalDialog(action); }, }, }); ``` **Use cases:** - Real-time operations requiring immediate decision - Interactive applications with user present - High-risk actions requiring instant validation #### Asynchronous Approval (Non-blocking) (Planned) AI operation returns pending status, continues when approved: ```typescript const neurolink = new NeuroLink({ hitl: { enabled: true, mode: "asynchronous", reviewCallback: async (action, context) => { // Queue for review, return immediately const reviewId = await queueForReview(action); return { pending: true, reviewId, estimatedTime: 900000, // 15 minutes }; }, statusCallback: async (reviewId) => { // Check approval status return await checkReviewStatus(reviewId); }, }, }); ``` **Use cases:** - Batch processing workflows - Operations requiring expert review (takes time) - Multi-level approval chains - Integration with ticketing systems (Jira, ServiceNow) ### 2. Review Triggers Configure when human review is required: #### Confidence Threshold Trigger (Planned) Automatically request review when AI confidence is low: ```typescript const neurolink = new NeuroLink({ hitl: { enabled: true, confidenceThreshold: 0.85, // Review if confidence { if (context.aiConfidence { const containsSensitiveData = context.contentPatterns.some((pattern) => pattern.test(action.content), ); if (containsSensitiveData) { return await requestSecurityReview(action); } return { approved: true }; }, }, }); ``` #### Time-Based Restrictions (Planned) Today, a `customRules` entry whose `condition` checks the time can require confirmation; the `reviewCallback` below does not exist. Require approval outside business hours: ```typescript const neurolink = new NeuroLink({ hitl: { enabled: true, reviewCallback: async (action, context) => { const hour = new Date().getHours(); const isBusinessHours = hour >= 9 && hour { const level = context.escalationLevel || 1; const reviewers = context.escalationPolicy.escalationLevels[level - 1].reviewers; return await requestApprovalFrom(reviewers, action); }, }, }); ``` --- ## SDK Integration ### TypeScript Configuration (Planned) Complete configuration interface: ```typescript type HITLConfiguration = { // Core settings enabled: boolean; mode?: "synchronous" | "asynchronous"; // (Planned feature) timeout?: number; // milliseconds // Approval triggers requireApproval?: string[]; // Tool names confidenceThreshold?: number; // 0-1 (Planned feature) contentPatterns?: RegExp[]; // (Planned feature) // Callbacks reviewCallback: ( action: HITLAction, context: HITLContext, ) => Promise; statusCallback?: (reviewId: string) => Promise; // (Planned feature) // Escalation (Planned feature) escalationPolicy?: { onTimeout: "approve" | "reject" | "escalate"; escalationLevels?: EscalationLevel[]; }; // Audit auditLog?: { enabled: boolean; storage: "file" | "database" | "custom"; customLogger?: (entry: AuditEntry) => Promise; }; }; type HITLAction = { tool: string; args: Record; timestamp: Date; sessionId: string; }; type HITLContext = { aiConfidence?: number; provider: string; model: string; escalationLevel?: number; }; type HITLReviewResult = { approved: boolean; reason?: string; reviewer?: string; modifications?: Record; escalate?: boolean; }; ``` ### Approval Callback Patterns #### Slack Integration (Planned) ```typescript const slack = new WebClient(process.env.SLACK_BOT_TOKEN); const neurolink = new NeuroLink({ hitl: { enabled: true, requireApproval: ["deleteFile", "sendEmail"], reviewCallback: async (action, context) => { // Send approval request to Slack const message = await slack.chat.postMessage({ channel: "#ai-approvals", text: ` AI Approval Request`, blocks: [ { type: "section", text: { type: "mrkdwn", text: `*Action:* \`${action.tool}\`\n*Args:* \`\`\`${JSON.stringify(action.args, null, 2)}\`\`\``, }, }, { type: "actions", elements: [ { type: "button", text: { type: "plain_text", text: "Approve" }, style: "primary", value: action.sessionId, action_id: "approve", }, { type: "button", text: { type: "plain_text", text: "Reject" }, style: "danger", value: action.sessionId, action_id: "reject", }, ], }, ], }); // Wait for response (implement with Slack interactivity) return await waitForSlackResponse(message.ts); }, }, }); ``` #### Email Integration (Planned) ```typescript const transporter = nodemailer.createTransport({ host: process.env.SMTP_HOST, auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS, }, }); const neurolink = new NeuroLink({ hitl: { enabled: true, mode: "asynchronous", reviewCallback: async (action, context) => { const reviewId = generateReviewId(); await transporter.sendMail({ from: "ai-system@company.com", to: "approvers@company.com", subject: `AI Approval Request: ${action.tool}`, html: ` AI Action Requires Approval Tool: ${action.tool} Arguments: ${JSON.stringify(action.args, null, 2)} Approve | Reject `, }); return { pending: true, reviewId, estimatedTime: 1800000, // 30 minutes }; }, statusCallback: async (reviewId) => { return await checkApprovalStatus(reviewId); }, }, }); ``` ### Integration with External Systems #### ServiceNow Integration (Planned) ```typescript const serviceNowClient = axios.create({ baseURL: process.env.SERVICENOW_INSTANCE, auth: { username: process.env.SERVICENOW_USER, password: process.env.SERVICENOW_PASS, }, }); const neurolink = new NeuroLink({ hitl: { enabled: true, mode: "asynchronous", reviewCallback: async (action, context) => { // Create ServiceNow ticket const ticket = await serviceNowClient.post("/api/now/table/incident", { short_description: `AI Approval: ${action.tool}`, description: JSON.stringify(action.args, null, 2), urgency: 2, category: "AI Operations", assignment_group: "AI Review Team", }); return { pending: true, reviewId: ticket.data.result.sys_id, trackingUrl: `${process.env.SERVICENOW_INSTANCE}/nav_to.do?uri=incident.do?sys_id=${ticket.data.result.sys_id}`, }; }, statusCallback: async (reviewId) => { const ticket = await serviceNowClient.get( `/api/now/table/incident/${reviewId}`, ); return { approved: ticket.data.result.state === "6", // Resolved pending: ticket.data.result.state !== "6", reason: ticket.data.result.close_notes, }; }, }, }); ``` --- ## CLI Integration (Planned) The CLI has no HITL support today: `loop --enable-hitl` and the `/hitl` commands below do not exist in `src/cli`. HITL is available through the SDK only. ### HITL in Loop Mode (Planned) Interactive CLI provides built-in HITL commands: ```bash # Start loop with HITL enabled npx @juspay/neurolink loop --enable-hitl # Inside loop session neurolink > /hitl status Pending HITL Approvals (2): 1. Tool: deleteFile Args: { path: "/tmp/data.csv" } Confidence: 0.76 Requested: 2 minutes ago 2. Tool: sendEmail Args: { to: "customer@example.com", subject: "Order Update" } Confidence: 0.92 Requested: 5 seconds ago neurolink > /hitl approve 1 ✅ Approved deleteFile operation Execution completed successfully neurolink > /hitl reject 2 --reason "Email template needs review" ❌ Rejected sendEmail operation Reason logged: Email template needs review ``` ### CLI HITL Commands (Planned) | Command | Description | Example | | -------------------- | --------------------------- | -------------------------------------------- | | `/hitl status` | View pending approvals | `/hitl status` | | `/hitl approve ` | Approve pending action | `/hitl approve 1` | | `/hitl reject ` | Reject with optional reason | `/hitl reject 2 --reason "Security concern"` | | `/hitl history` | View approval history | `/hitl history --last 10` | | `/hitl config` | View HITL configuration | `/hitl config` | --- ## Enterprise Patterns ### Pattern 1: Medical AI Validation (Planned) Physician oversight for AI-generated diagnostic recommendations: ```typescript const medicalAI = new NeuroLink({ hitl: { enabled: true, mode: "synchronous", confidenceThreshold: 0.95, // High bar for medical decisions requireApproval: ["generateDiagnosis", "recommendTreatment"], reviewCallback: async (action, context) => { // Route to qualified physician based on specialty const specialty = determineSpecialty(action.args); const physician = await findAvailablePhysician(specialty); // Present AI analysis to physician const review = await presentToPhysician({ physician, aiAnalysis: { tool: action.tool, recommendation: action.args, confidence: context.aiConfidence, supportingData: context.metadata, }, patientContext: context.patientId, }); // Log for HIPAA compliance await auditLog.recordMedicalReview({ physician: physician.id, decision: review.approved, timestamp: new Date(), patientId: context.patientId, aiConfidence: context.aiConfidence, humanConfidence: review.confidence, }); return { approved: review.approved, reason: review.clinicalReasoning, reviewer: physician.email, modifications: review.modifications, }; }, }, }); // Usage const diagnosis = await medicalAI.generate({ input: { text: "Analyze patient symptoms and recommend diagnosis", }, context: { patientId: "PT-12345", symptoms: ["chest pain", "shortness of breath"], vitals: { bp: "145/95", hr: 98 }, }, tools: [ { name: "generateDiagnosis", description: "Generate diagnostic recommendation", requiresConfirmation: true, execute: async (args) => { return { diagnosis: args.primaryDiagnosis, differentials: args.differentialDiagnoses, recommendedTests: args.tests, }; }, }, ], }); ``` ### Pattern 2: Financial Compliance (Planned) Transaction approval above risk thresholds: ```typescript const financialAI = new NeuroLink({ hitl: { enabled: true, requireApproval: ["executeTransaction", "modifyAccount"], reviewCallback: async (action, context) => { const amount = action.args.amount; const threshold = 10000; // $10,000 if (amount >= threshold) { // Multi-level approval for large transactions const approvals = []; // Level 1: Manager approval const managerApproval = await requestApproval({ approver: "manager@company.com", action, level: 1, }); approvals.push(managerApproval); if (!managerApproval.approved) { return managerApproval; } // Level 2: Finance director for >$50k if (amount >= 50000) { const directorApproval = await requestApproval({ approver: "finance-director@company.com", action, level: 2, }); approvals.push(directorApproval); if (!directorApproval.approved) { return directorApproval; } } // Compliance audit trail await complianceLog.record({ transactionId: action.args.transactionId, amount, approvals, timestamp: new Date(), regulatoryFramework: "SOC2", }); return { approved: true, reason: "Multi-level approval completed", reviewers: approvals.map((a) => a.reviewer), }; } return { approved: true, reason: "Below threshold" }; }, }, }); // Usage const transaction = await financialAI.generate({ input: { text: "Process wire transfer of $75,000 to vendor account", }, tools: [ { name: "executeTransaction", description: "Execute financial transaction", requiresConfirmation: true, execute: async (args) => { return await processWireTransfer(args); }, }, ], }); ``` ### Pattern 3: Legal Document Review (Planned) Attorney validation of AI-generated contracts: ```typescript const legalAI = new NeuroLink({ hitl: { enabled: true, mode: "asynchronous", // Legal review takes time requireApproval: ["generateContract", "modifyClause"], reviewCallback: async (action, context) => { // Determine required legal expertise const practiceArea = determinePracticeArea(action.args); const jurisdiction = action.args.jurisdiction; // Route to qualified attorney const attorney = await findAttorney({ practiceArea, jurisdiction, barAdmissions: [jurisdiction], }); // Create review task const reviewTask = await legalReviewSystem.createTask({ attorney: attorney.id, documentType: action.tool, content: action.args, aiConfidence: context.aiConfidence, priority: action.args.urgency || "standard", deadline: calculateDeadline(action.args.urgency), }); return { pending: true, reviewId: reviewTask.id, estimatedTime: reviewTask.estimatedCompletionTime, trackingUrl: reviewTask.url, }; }, statusCallback: async (reviewId) => { const task = await legalReviewSystem.getTask(reviewId); if (task.status === "completed") { return { approved: task.approved, reason: task.legalOpinion, reviewer: task.attorney.email, modifications: task.suggestedChanges, }; } return { pending: true }; }, }, }); // Usage const contract = await legalAI.generate({ input: { text: "Generate employment contract for California senior engineer position", }, context: { jurisdiction: "California", position: "Senior Software Engineer", complianceRequirements: ["california-labor-law", "federal-employment-law"], }, tools: [ { name: "generateContract", description: "Generate legal contract", requiresConfirmation: true, execute: async (args) => { return { contractText: args.content, clauses: args.clauses, terms: args.terms, }; }, }, ], }); ``` ### Pattern 4: Code Execution Safety (Planned) Sandbox approval before executing AI-generated code: ```typescript const codeAI = new NeuroLink({ hitl: { enabled: true, requireApproval: ["executeCode", "modifyDatabase", "deployToProduction"], reviewCallback: async (action, context) => { if (action.tool === "executeCode") { // Static analysis of code const analysis = await analyzeCode(action.args.code); if (analysis.containsDangerousPatterns) { return { approved: false, reason: `Security concern: ${analysis.issues.join(", ")}`, escalate: true, }; } // Present code to developer for review const review = await presentCodeReview({ code: action.args.code, analysis, context: action.args.context, }); return { approved: review.approved, reason: review.comments, reviewer: review.developer, modifications: review.suggestedChanges, }; } return { approved: true }; }, }, }); // Usage with code execution const result = await codeAI.generate({ input: { text: "Write and execute a Python script to process CSV data", }, tools: [ { name: "executeCode", description: "Execute code in sandboxed environment", requiresConfirmation: true, execute: async (args) => { // Execute in sandbox after approval return await sandbox.execute({ code: args.code, language: args.language, timeout: 30000, }); }, }, ], }); ``` --- ## Configuration Reference ### Full Configuration Object (Planned) Complete TypeScript interface with all available options: ```typescript type HITLConfiguration = { // === Core Settings === enabled: boolean; mode?: "synchronous" | "asynchronous"; // (Planned feature) timeout?: number; // Default: 300000 (5 minutes) // === Approval Triggers === requireApproval?: string[]; // Tool names requiring approval confidenceThreshold?: number; // 0-1, trigger review if AI confidence below (Planned feature) contentPatterns?: RegExp[]; // Patterns that trigger review (Planned feature) // === Callbacks === reviewCallback: ( action: HITLAction, context: HITLContext, ) => Promise; statusCallback?: (reviewId: string) => Promise; // (Planned feature) // === Escalation (Planned feature) === escalationPolicy?: { onTimeout: "approve" | "reject" | "escalate"; escalationLevels?: Array; }; // === Audit & Compliance === auditLog?: { enabled: boolean; storage: "file" | "database" | "custom"; path?: string; // For file storage database?: DatabaseConfig; // For database storage customLogger?: (entry: AuditEntry) => Promise; }; // === Security === security?: { encryptAuditLogs?: boolean; redactSensitiveData?: boolean; requireMFA?: boolean; ipWhitelist?: string[]; }; }; ``` ### Environment Variables (Planned) Configure HITL through environment variables: ```bash # Core HITL Settings NEUROLINK_HITL_ENABLED=true NEUROLINK_HITL_MODE=synchronous NEUROLINK_HITL_TIMEOUT=300000 # Approval Configuration NEUROLINK_HITL_CONFIDENCE_THRESHOLD=0.85 NEUROLINK_HITL_REQUIRE_APPROVAL=writeFile,deleteFile,executeCode # Audit Logging NEUROLINK_HITL_AUDIT_ENABLED=true NEUROLINK_HITL_AUDIT_STORAGE=database NEUROLINK_HITL_AUDIT_DB_URL=postgresql://user:pass@localhost:5432/audit # Integration NEUROLINK_HITL_SLACK_TOKEN=xoxb-your-token NEUROLINK_HITL_SLACK_CHANNEL=#ai-approvals ``` --- ## Security & Audit ### Audit Trail Format (Planned) Today, with `auditLogging: true`, each entry carries `timestamp`, `eventType` (`confirmation-requested`, `confirmation-approved`, `confirmation-rejected`, `confirmation-timeout` or `confirmation-auto-approved`, among a few internal ones such as `configuration-updated`), `toolName`, `userId`, `sessionId`, `arguments`, `reason` and `responseTime`. There is no `aiConfidence`, `reviewer`, `escalationLevel` or `outcome` field. The target format is: ```json { "eventId": "evt_7a9f2c1b", "timestamp": "2025-01-01T14:30:00Z", "sessionId": "sess_abc123", "action": { "tool": "deleteFile", "args": { "path": "/data/sensitive.csv" } }, "context": { "provider": "anthropic", "model": "claude-3-sonnet", "aiConfidence": 0.78, "userId": "user@company.com" }, "review": { "approved": true, "reason": "Authorized by manager", "reviewer": "manager@company.com", "reviewDuration": 45000, "escalationLevel": 1 }, "outcome": { "success": true, "executionTime": 234, "result": { "deleted": true } } } ``` ### Compliance Documentation #### HIPAA Compliance (Planned) HITL audit logs support HIPAA requirements: - **Access Controls**: Reviewer identity logged - **Audit Trail**: Complete decision history - **Data Integrity**: Tamper-evident logging - **Accountability**: Individual authorization tracking ```typescript const hipaaCompliantAI = new NeuroLink({ hitl: { enabled: true, auditLog: { enabled: true, storage: "database", database: { url: process.env.HIPAA_AUDIT_DB, encryption: true, retentionYears: 6, // HIPAA requirement }, }, security: { encryptAuditLogs: true, requireMFA: true, redactSensitiveData: true, }, }, }); ``` #### SOC2 Compliance (Planned) Meet SOC2 Type II requirements: - **Authorization**: Documented approval workflow - **Monitoring**: Real-time audit logging - **Availability**: Timeout and escalation policies - **Confidentiality**: Encrypted audit storage ```typescript const soc2CompliantAI = new NeuroLink({ hitl: { enabled: true, escalationPolicy: { onTimeout: "escalate", escalationLevels: [ { level: 1, reviewers: ["team-lead"], timeout: 300000 }, { level: 2, reviewers: ["manager"], timeout: 600000 }, ], }, auditLog: { enabled: true, storage: "database", database: { url: process.env.AUDIT_DB, encryption: true, }, }, }, }); ``` #### GDPR Compliance (Planned) Support GDPR data protection requirements: - **Lawful Processing**: Human oversight for data operations - **Data Minimization**: Review prevents excessive collection - **Right to Erasure**: Approval required for deletions - **Accountability**: Complete audit trail ```typescript const gdprCompliantAI = new NeuroLink({ hitl: { enabled: true, requireApproval: [ "collectPersonalData", "deletePersonalData", "transferData", ], reviewCallback: async (action, context) => { // Ensure lawful basis documented const lawfulBasis = await determineLawfulBasis(action); if (!lawfulBasis) { return { approved: false, reason: "No lawful basis for processing", }; } // Log for accountability await gdprAuditLog.record({ action: action.tool, lawfulBasis, dataSubject: context.dataSubjectId, processor: context.userId, }); return { approved: true, reason: `Lawful basis: ${lawfulBasis}`, }; }, }, }); ``` ### Security Best Practices #### 1. Secure Approval Callbacks (Planned) ```typescript // ❌ BAD: Exposing sensitive data in logs reviewCallback: async (action, context) => { console.log(action.args); // May contain PII, credentials return { approved: true }; }; // ✅ GOOD: Redact sensitive data reviewCallback: async (action, context) => { const redactedArgs = redactSensitive(action.args); console.log(redactedArgs); return { approved: true }; }; ``` #### 2. Secret Management (Planned) ```typescript // ❌ BAD: Hardcoded credentials const neurolink = new NeuroLink({ hitl: { reviewCallback: async (action) => { const response = await fetch("https://api.example.com/approve", { headers: { Authorization: "Bearer abc123" }, // Hardcoded! }); }, }, }); // ✅ GOOD: Environment variables const neurolink = new NeuroLink({ hitl: { reviewCallback: async (action) => { const response = await fetch("https://api.example.com/approve", { headers: { Authorization: `Bearer ${process.env.APPROVAL_API_TOKEN}`, }, }); }, }, }); ``` #### 3. Input Validation (Planned) ```typescript reviewCallback: async (action, context) => { // Validate tool name const allowedTools = ["readFile", "writeFile"]; if (!allowedTools.includes(action.tool)) { return { approved: false, reason: "Invalid tool name", }; } // Validate arguments if (!isValidPath(action.args.path)) { return { approved: false, reason: "Invalid file path", }; } return { approved: true }; }; ``` --- ## Troubleshooting ### Common Issues #### Issue: Timeout Exceeded (Planned) **Symptom**: Review requests timing out before approval ``` Error: HITL review timeout exceeded (300000ms) ``` **Solution**: ```typescript // Increase timeout for operations requiring human thought const neurolink = new NeuroLink({ hitl: { enabled: true, timeout: 600000, // 10 minutes escalationPolicy: { onTimeout: "escalate", // Escalate instead of failing }, }, }); ``` #### Issue: Approval Callback Not Called (Planned) **Symptom**: HITL enabled but callback never executes **Solution**: Ensure tool has `requiresConfirmation: true`: ```typescript tools: [ { name: "dangerousTool", requiresConfirmation: true, // Must be set execute: async (args) => { // ... }, }, ]; ``` #### Issue: Rejected Approvals Not Handled (Planned) **Symptom**: Application crashes when approval rejected **Solution**: Handle rejection in error handling: ```typescript try { const result = await neurolink.generate({ ... }); } catch (error) { if (error.code === "HITL_APPROVAL_REJECTED") { console.log(`Operation rejected: ${error.reason}`); // Handle gracefully - show user message, log, etc. } } ``` ### Debug Mode (Planned) Enable detailed HITL logging: ```typescript const neurolink = new NeuroLink({ hitl: { enabled: true, debug: true, // Enables verbose logging }, }); // Or via environment variable process.env.NEUROLINK_HITL_DEBUG = "true"; ``` Debug output example: ``` [HITL] Review required for tool: deleteFile [HITL] Confidence: 0.72 (threshold: 0.85) [HITL] Calling reviewCallback with action: {...} [HITL] Review pending: reviewId=rev_123 [HITL] Checking review status every 5s [HITL] Review approved by: manager@company.com [HITL] Executing tool with confirmation ``` --- ## See Also - [Quick HITL Guide](/docs/features/hitl) - Simple HITL setup for common cases - [Guardrails Middleware](/docs/features/guardrails) - Complementary content filtering - [Middleware Architecture](/docs/advanced/middleware-architecture) - How HITL integrates with middleware - [Custom Tools](/docs/sdk/custom-tools) - Building tools with HITL support - [CLI Loop Sessions](/docs/features/cli-loop-sessions) - Using HITL in interactive CLI (planned; the CLI has no HITL commands yet) --- ## File Processors Guide # File Processors Guide NeuroLink includes a comprehensive file processing system that supports 20+ file types with intelligent content extraction, security sanitization, and provider-agnostic formatting. This system enables seamless multimodal AI interactions across NeuroLink's multimodal-capable providers. ## Overview The file processor system is organized into a modular architecture: ``` src/lib/processors/ ├── base/ # BaseFileProcessor abstract class and types ├── registry/ # ProcessorRegistry singleton for processor selection ├── config/ # MIME types, extensions, language maps, size limits ├── errors/ # FileErrorCode enum and error helpers ├── document/ # Excel, Word, RTF, OpenDocument processors ├── media/ # Video and Audio processors (metadata extraction) ├── archive/ # ZIP, TAR, GZ archive processors (file listing + content extraction) ├── markup/ # SVG, HTML, Markdown, Text processors ├── code/ # SourceCode, Config processors ├── data/ # JSON, YAML, XML processors ├── integration/ # FileProcessorIntegration for registry usage └── cli/ # CLI helpers for file processing ``` ## Quick Start ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Summarize this document", files: ["./report.pdf"], }, }); console.log(result.content); ``` ## Supported File Types ### Documents | Type | Extensions | Processor | Features | | ---------------- | ---------------------- | ----------------------- | ---------------------------------------------------- | | **Excel** | `.xlsx`, `.xls` | `ExcelProcessor` | Multi-sheet extraction, cell formatting, data tables | | **Word** | `.docx`, `.doc` | `WordProcessor` | Text extraction, paragraph preservation | | **RTF** | `.rtf` | `RtfProcessor` | Rich text to plain text conversion | | **OpenDocument** | `.odt`, `.ods`, `.odp` | `OpenDocumentProcessor` | LibreOffice/OpenOffice format support | ### Data Files | Type | Extensions | Processor | Features | | -------- | --------------- | --------------- | ------------------------------------------------ | | **JSON** | `.json` | `JsonProcessor` | Validation, pretty-printing, syntax highlighting | | **YAML** | `.yaml`, `.yml` | `YamlProcessor` | Validation, formatting, multi-document support | | **XML** | `.xml` | `XmlProcessor` | Parsing, validation, entity handling | ### Markup Files | Type | Extensions | Processor | Features | | ------------ | ------------------ | ------------------- | --------------------------------------------- | | **HTML** | `.html`, `.htm` | `HtmlProcessor` | OWASP-compliant sanitization, text extraction | | **SVG** | `.svg` | `SvgProcessor` | XSS prevention, text injection (not binary) | | **Markdown** | `.md`, `.markdown` | `MarkdownProcessor` | Formatting preservation, metadata extraction | | **Text** | `.txt` | `TextProcessor` | Plain text handling, encoding detection | ### Source Code | Type | Extensions | Processor | Features | | ------------------- | -------------------------- | --------------------- | ----------------------------------- | | **TypeScript** | `.ts`, `.tsx` | `SourceCodeProcessor` | Language detection, syntax metadata | | **JavaScript** | `.js`, `.jsx`, `.mjs` | `SourceCodeProcessor` | Module detection | | **Python** | `.py` | `SourceCodeProcessor` | Docstring preservation | | **Java** | `.java` | `SourceCodeProcessor` | Package detection | | **Go** | `.go` | `SourceCodeProcessor` | Module awareness | | **Rust** | `.rs` | `SourceCodeProcessor` | Crate detection | | **C/C++** | `.c`, `.cpp`, `.h`, `.hpp` | `SourceCodeProcessor` | Header handling | | **C#** | `.cs` | `SourceCodeProcessor` | Namespace detection | | **Ruby** | `.rb` | `SourceCodeProcessor` | Gem awareness | | **PHP** | `.php` | `SourceCodeProcessor` | Tag handling | | **Swift** | `.swift` | `SourceCodeProcessor` | Framework detection | | **Kotlin** | `.kt`, `.kts` | `SourceCodeProcessor` | Android/JVM awareness | | **Scala** | `.scala` | `SourceCodeProcessor` | SBT integration | | **Shell** | `.sh`, `.bash`, `.zsh` | `SourceCodeProcessor` | Shebang detection | | **SQL** | `.sql` | `SourceCodeProcessor` | Dialect hints | | **And 35+ more...** | Various | `SourceCodeProcessor` | Automatic language detection | ### Configuration Files | Type | Extensions | Processor | Features | | --------------- | ---------------- | ----------------- | ---------------------------------- | | **Environment** | `.env`, `.env.*` | `ConfigProcessor` | Secret masking option | | **INI** | `.ini`, `.cfg` | `ConfigProcessor` | Section parsing | | **TOML** | `.toml` | `ConfigProcessor` | Cargo.toml, pyproject.toml support | | **Properties** | `.properties` | `ConfigProcessor` | Java properties format | ### Media Files | Type | Extensions | Processor | Features | | --------- | ------------------------------------------------------- | ---------------- | -------------------------------------------------------------------------------- | | **Video** | `.mp4`, `.mkv`, `.webm`, `.avi`, `.mov`, `.m4v` | `VideoProcessor` | Duration, resolution, codec, frame rate, bitrate extraction via `music-metadata` | | **Audio** | `.mp3`, `.wav`, `.ogg`, `.flac`, `.aac`, `.m4a`, `.wma` | `AudioProcessor` | Codec, bitrate, sample rate, channels, duration extraction via `music-metadata` | For most providers, audio and video files are not sent as binary. Instead, the processor extracts structured metadata and returns it as formatted text, keeping token usage minimal (~50-200 tokens per file). Video files produce that same metadata text and also bring timestamped keyframes and any embedded subtitles. The Gemini providers additionally receive the audio file itself and the video clip itself (a clip qualifies up to 14 MB of source bytes for the whole request); see the [Video Analysis guide](/docs/features/video-analysis). **Example video output:** ``` Video File: presentation.mp4 Duration: 13s | Resolution: 640x360 | Video Codec: h264 Frame Rate: 29.97 fps | Bitrate: 345 kbps Audio: aac, 48000 Hz, 2 channels ``` **Example audio output:** ``` Audio File: recording.mp3 Codec: MPEG 1 Layer 3 | Bitrate: 128 kbps Sample Rate: 44100 Hz | Channels: 2 (Stereo) | Duration: 1:46 ``` ### Archives | Type | Extensions | Processor | Features | | ------- | ------------------------ | ------------------ | ---------------------------------------------------------------------- | | **ZIP** | `.zip` | `ArchiveProcessor` | File listing with sizes, nested content extraction, ZIP bomb detection | | **TAR** | `.tar` | `ArchiveProcessor` | File listing with sizes | | **GZ** | `.gz`, `.tar.gz`, `.tgz` | `ArchiveProcessor` | Gzip decompression, tar content listing | Archive files return a structured listing of their contents with file sizes and optionally extract text from contained files (routing through existing processors). **Example archive output:** ``` Archive: project.tar.gz Total entries: 6 Files: - code/sample.json (60 B) - code/sample.py (195 B) - document/sample.txt (607 B) ``` **Security:** Archive processing includes ZIP bomb detection (compression ratio limits), path traversal prevention, symlink blocking, entry count limits, and aggregate decompression size limits. ## Usage ### SDK Usage ```typescript const neurolink = new NeuroLink(); // Process multiple file types in a single request const result = await neurolink.generate({ input: { text: "Analyze these files and summarize the key information", files: [ "./data/report.xlsx", // Excel spreadsheet "./config/settings.yaml", // YAML configuration "./src/main.ts", // TypeScript source "./docs/architecture.svg", // SVG diagram (injected as text) "./api/schema.json", // JSON schema ], }, provider: "vertex", }); console.log(result.content); ``` ### CLI Usage ```bash # Single file neurolink generate "Analyze this spreadsheet" --file ./data.xlsx # Multiple files neurolink generate "Compare these configs" \ --file ./config.yaml \ --file ./settings.json \ --file ./app.toml # Mixed with images and PDFs neurolink generate "Explain this codebase" \ --file ./src/main.ts \ --file ./docs/diagram.svg \ --pdf ./docs/spec.pdf \ --image ./screenshot.png ``` ### Stream Mode ```typescript // Streaming with file processing const result = await neurolink.stream({ input: { text: "Walk me through this code step by step", files: ["./src/algorithm.py"], }, }); for await (const chunk of result.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } ``` ## Architecture ### ProcessorRegistry The `ProcessorRegistry` is a singleton that manages all file processors with priority-based selection: ```typescript // Get the singleton instance const registry = ProcessorRegistry.getInstance(); // Register a custom processor (lower priority = higher precedence) registry.register(new MyCustomProcessor(), 50); // Find processor for a file const processor = registry.findProcessor({ filename: "data.xlsx", mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", size: 1024, }); // Process a file const result = await processor.process(fileInfo, fileContent); ``` ### BaseFileProcessor All processors extend the abstract `BaseFileProcessor` class: ```typescript export class MyProcessor extends BaseFileProcessor { readonly name = "my-processor"; readonly supportedMimeTypes = ["application/x-my-format"]; readonly supportedExtensions = [".myf"]; canProcess(file: FileInfo): boolean { return this.supportedExtensions.includes(file.extension); } async process(file: FileInfo, content: Buffer): Promise { const text = this.extractText(content); return { type: "text", content: text, metadata: { processor: this.name, originalFilename: file.filename, }, }; } getInfo(): ProcessorInfo { return { name: this.name, description: "Processes MY format files", supportedMimeTypes: this.supportedMimeTypes, supportedExtensions: this.supportedExtensions, }; } } ``` ### FileDetector The `FileDetector` utility automatically identifies file types: ```typescript const detector = new FileDetector(); // Detect by extension const type1 = detector.detect("report.xlsx"); // Returns: { type: "xlsx", mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" } // Detect by content (magic bytes) const type2 = detector.detectFromContent(buffer); // SVG special handling - returns "svg" type, not "image" const type3 = detector.detect("diagram.svg"); // Returns: { type: "svg", mimeType: "image/svg+xml" } ``` ## Security Features ### OWASP-Compliant Sanitization The markup processors include security sanitization to prevent XSS and injection attacks: #### HTML Sanitization ```typescript // HtmlProcessor automatically sanitizes HTML content // - Removes tags // - Strips event handlers (onclick, onerror, etc.) // - Removes javascript: URLs // - Sanitizes style attributes // - Blocks dangerous protocols const result = await neurolink.generate({ input: { text: "Summarize this HTML content", files: ["./untrusted-content.html"], // Automatically sanitized }, }); ``` #### SVG Sanitization ```typescript // SvgProcessor sanitizes SVG before injection // - Removes embedded scripts // - Strips foreignObject elements // - Sanitizes use/href attributes // - Blocks external entity references // SVG is injected as TEXT, not as binary image // This prevents image-based attacks while preserving vector content ``` ### File Size Limits Default size limits prevent denial-of-service attacks: | Category | Default Limit | Configurable | | ------------ | ------------- | ---------------- | | Documents | 50 MB | Yes | | Data files | 10 MB | Yes | | Code files | 5 MB | Yes | | Config files | 1 MB | Yes | | Images | 10 MB | No — fixed limit | The **image** limit (`SIZE_LIMITS_BYTES.IMAGE_MAX`, 10 MB) is enforced: an oversized image buffer, file, or download throws a descriptive error before any base64 conversion, so a large image can no longer exhaust process memory. This applies to both entry points — images passed via `generate({ files })` (routed through `FileDetector` → `ImageProcessor`) and via `generate({ images })` (routed through the message builder). The internal image helpers that convert buffers/files/URLs accept an optional size override, but it is not exposed through `generate()` or any other public API — the 10 MB limit is fixed for SDK callers. ## Error Handling ### FileErrorCode Enum ```typescript try { const result = await neurolink.generate({ input: { files: ["./corrupted.xlsx"] }, }); } catch (error) { if (error && typeof error === "object" && "code" in error) { switch (error.code) { case FileErrorCode.UNSUPPORTED_TYPE: console.log("File type not supported"); break; case FileErrorCode.FILE_TOO_LARGE: console.log("File too large"); break; case FileErrorCode.CORRUPTED_FILE: console.log("File is corrupted"); break; case FileErrorCode.DOWNLOAD_AUTH_FAILED: console.log("Cannot read file"); break; } } } ``` ## Provider Compatibility All file processors work across NeuroLink's text- and multimodal-capable providers. The processed content is formatted as text that any such provider can understand: | Provider | Documents | Data | Markup | Code | Config | | ----------------- | --------- | ---- | ------ | ---- | ------ | | OpenAI | ✅ | ✅ | ✅ | ✅ | ✅ | | Anthropic | ✅ | ✅ | ✅ | ✅ | ✅ | | Google AI Studio | ✅ | ✅ | ✅ | ✅ | ✅ | | Google Vertex | ✅ | ✅ | ✅ | ✅ | ✅ | | AWS Bedrock | ✅ | ✅ | ✅ | ✅ | ✅ | | Azure OpenAI | ✅ | ✅ | ✅ | ✅ | ✅ | | Mistral | ✅ | ✅ | ✅ | ✅ | ✅ | | LiteLLM | ✅ | ✅ | ✅ | ✅ | ✅ | | Ollama | ✅ | ✅ | ✅ | ✅ | ✅ | | Hugging Face | ✅ | ✅ | ✅ | ✅ | ✅ | | SageMaker | ✅ | ✅ | ✅ | ✅ | ✅ | | OpenAI Compatible | ✅ | ✅ | ✅ | ✅ | ✅ | | OpenRouter | ✅ | ✅ | ✅ | ✅ | ✅ | **Note:** For binary files like images and PDFs, provider-specific adapters handle the formatting. See [PDF Support](/docs/features/pdf-support) and [Multimodal Chat](/docs/features/multimodal-chat). ## Best Practices ### 1. Use Appropriate File Types ```typescript // Good: Use structured data formats for data files: ["./data.json", "./config.yaml"]; // Avoid: Using unstructured text for structured data files: ["./data.txt"]; // Harder for AI to parse ``` ### 2. Combine Related Files ```typescript // Good: Group related files together const result = await neurolink.generate({ input: { text: "Review this module for best practices", files: [ "./src/module.ts", // Implementation "./src/module.test.ts", // Tests "./src/module.types.ts", // Types ], }, }); ``` ### 3. Be Mindful of Token Limits ```typescript // For large files, consider chunking or summarization // Enable automatic truncation for very large files ProcessorConfig.setTruncation({ enabled: true, maxTokens: 50000, strategy: "head-tail", // Keep beginning and end }); ``` ### 4. Use Specific Prompts ```typescript // Good: Be specific about what to analyze const result = await neurolink.generate({ input: { text: "Find security vulnerabilities in this code, focusing on SQL injection and XSS", files: ["./src/api.ts"], }, }); // Less effective: Vague prompt const result = await neurolink.generate({ input: { text: "Look at this", files: ["./src/api.ts"], }, }); ``` ## Extending the System ### Creating a Custom Processor ```typescript BaseFileProcessor, FileInfo, ProcessedFile, ProcessorRegistry, } from "@juspay/neurolink"; class ProtobufProcessor extends BaseFileProcessor { readonly name = "protobuf-processor"; readonly supportedMimeTypes = ["application/x-protobuf"]; readonly supportedExtensions = [".proto"]; canProcess(file: FileInfo): boolean { return file.extension === ".proto"; } async process(file: FileInfo, content: Buffer): Promise { const protoText = content.toString("utf-8"); // Add syntax highlighting hints const formatted = `\`\`\`protobuf\n${protoText}\n\`\`\``; return { type: "text", content: formatted, metadata: { processor: this.name, language: "protobuf", filename: file.filename, }, }; } getInfo() { return { name: this.name, description: "Processes Protocol Buffer definition files", supportedMimeTypes: this.supportedMimeTypes, supportedExtensions: this.supportedExtensions, }; } } // Register with priority 50 (lower = higher precedence) ProcessorRegistry.getInstance().register(new ProtobufProcessor(), 50); ``` ## Related Documentation - [Multimodal Chat](/docs/features/multimodal-chat) - Image and media handling - [PDF Support](/docs/features/pdf-support) - PDF-specific features - [CSV Support](/docs/features/csv-support) - CSV processing details - [CLI Commands](/docs/cli/commands) - CLI file options - [SDK API Reference](/docs/sdk/api-reference) - Full API documentation --- ## Guardrails AI Integration with Middleware # Guardrails AI Integration with Middleware This document outlines the modern, simplified approach to integrating Guardrails AI with the NeuroLink platform using the new `MiddlewareFactory`. This enhances the safety, reliability, and security of your AI applications in a modular and maintainable way. ## Overview Guardrails AI is an open-source library that provides a framework for creating and managing guardrails for large language models (LLMs). By integrating Guardrails AI as middleware, you can enforce specific rules and policies on the inputs and outputs of your models, ensuring they adhere to your safety guidelines and quality standards. ## Key Benefits - **Risk Mitigation**: Protect against common AI risks such as hallucinations, toxic language, and data leakage. - **Quality Assurance**: Ensure that model outputs are accurate, relevant, and meet predefined quality criteria. - **Compliance**: Enforce industry-specific regulations and compliance requirements. - **Customization**: Create custom guardrails tailored to specific use cases and business needs. ## Middleware-based Guardrail Implementation With the new `MiddlewareFactory`, integrating guardrails is easier than ever. The factory automatically handles the registration and application of the `guardrails` middleware when you use a relevant preset. ```mermaid graph TD A[Application] --> B[new MiddlewareFactory({ preset: 'security' })]; subgraph B C{Guardrail Middleware Applied} --> D[Core LLM]; end B --> E[Returns Guarded Model]; ``` ### Using the `security` Preset The easiest way to enable guardrails is to use the `security` preset when creating your `MiddlewareFactory`. This preset enables the `guardrails` middleware with an empty configuration: it filters nothing until you add `badWords`, `modelFilter` or `precallEvaluation` (see [Customizing Guardrails](#customizing-guardrails)). To apply a preset to every call without building a factory, use [`new NeuroLink({ middleware })`, `configureGlobalMiddleware()` or `NEUROLINK_MIDDLEWARE_PRESET`](/docs/features/guardrails.md#defaults-and-precedence). ```typescript // 1. Create a factory with the 'security' preset const factory = new MiddlewareFactory({ preset: "security" }); // 2. Create a context const context = factory.createContext("openai", "gpt-4"); // 3. Apply the middleware to your base model // The guardrails middleware is applied automatically. const guardedModel = factory.applyMiddleware(baseModel, context); // 4. Use the guarded model const result = await guardedModel.generate({ prompt: "This is a test prompt.", }); ``` ### Using the `all` Preset If you want to use guardrails in combination with other built-in middleware like analytics, you can use the `all` preset. ```typescript // This will enable both analytics and guardrails const factory = new MiddlewareFactory({ preset: "all" }); ``` ### Customizing Guardrails While presets provide a great starting point, you can also customize the behavior of the guardrails middleware by providing a custom configuration. ```typescript const factory = new MiddlewareFactory({ // You can start with a preset preset: "security", // And then provide a custom configuration, which will be merged with the preset middlewareConfig: { guardrails: { enabled: true, config: { badWords: { enabled: true, list: ["custom-bad-word-1", "custom-bad-word-2"], }, }, }, }, }); ``` This new, streamlined approach provides a clean and scalable way to add safety and other enhancements to your AI models within the NeuroLink ecosystem. --- ## See Also For configuration examples, best practices, and troubleshooting, see the [Guardrails Middleware Feature Guide](/docs/features/guardrails). --- ## Guardrails Implementation Guide # Guardrails Implementation Guide This document provides comprehensive documentation for the NeuroLink guardrails implementation, including pre-call filtering, content sanitization, and AI-powered evaluation. ## Overview The guardrails implementation provides advanced content filtering and safety mechanisms for AI interactions. It includes: - **Pre-call Evaluation**: AI-powered safety assessment before processing - **Content Filtering**: Bad words and regex pattern filtering - **Parameter Sanitization**: Input cleaning and modification - **Evaluation Actions**: Configurable responses (block, sanitize, warn, log) - **Visual Proof**: Screenshots demonstrating filtering in action ## Architecture ```mermaid graph TD A[User Input] --> B[Guardrails Middleware] B --> C{Pre-call Evaluation} C -->|Safe| D[Content Filtering] C -->|Unsafe| E[Block/Sanitize] D --> F{Bad Words Check} F -->|Clean| G[AI Provider] F -->|Filtered| H[Sanitize Content] H --> G E --> I[Return Blocked Response] G --> J[Response] ``` ## Core Components ### 1. Guardrails Middleware (`src/lib/middleware/builtin/guardrails.ts`) The main middleware component that orchestrates all guardrail functionality: ```typescript // Apply guardrails to any AI provider const guardedModel = new GuardrailsMiddleware(baseModel, config); ``` ### 2. Guardrails Utilities (`src/lib/middleware/utils/guardrailsUtils.ts`) Core utility functions for evaluation and filtering: - `performPrecallEvaluation()` - AI-powered safety assessment - `applyEvaluationActions()` - Execute configured actions based on evaluation - `applySanitization()` - Clean and modify request parameters - `applyContentFiltering()` - Filter content using patterns and word lists ### 3. Type Definitions (`src/lib/types/guardrails.ts`) Complete TypeScript interfaces for configuration and results: ```typescript type GuardrailsMiddlewareConfig = { badWords?: BadWordsConfig; modelFilter?: ModelFilterConfig; precallEvaluation?: PrecallEvaluationConfig; }; ``` ## Configuration ### Basic Configuration ```typescript const guardrailsConfig = { precallEvaluation: { enabled: true, provider: "google-ai", evaluationModel: "gemini-1.5-flash", }, badWords: { enabled: true, list: ["inappropriate", "harmful"], }, }; ``` ### Advanced Configuration ```typescript const advancedConfig = { precallEvaluation: { enabled: true, provider: "google-ai", evaluationModel: "gemini-1.5-flash", evaluationPrompt: `Custom evaluation prompt...`, actions: { onUnsafe: "block", onInappropriate: "sanitize", onSuspicious: "warn", }, thresholds: { safetyScore: 7, appropriatenessScore: 6, confidenceLevel: 8, }, }, badWords: { enabled: true, regexPatterns: [ "\\b(spam|scam)\\b", "\\d{3}-\\d{2}-\\d{4}", // SSN pattern ], }, }; ``` ## Features ### Pre-call Evaluation AI-powered evaluation of user input before processing: ```json { "overall": "safe|unsafe|suspicious|inappropriate", "safetyScore": 8, "appropriatenessScore": 9, "confidenceLevel": 7, "issues": [ { "category": "explicit_content", "severity": "low", "description": "Mild inappropriate language" } ], "suggestedAction": "allow", "reasoning": "Content is generally appropriate with minor concerns" } ``` ### Content Filtering Two-tier filtering system: 1. **Regex Patterns** (Priority 1) ```typescript regexPatterns: [ "\\b(password|secret)\\b", "\\d{16}", // Credit card pattern ]; ``` 2. **Word Lists** (Priority 2) ```typescript list: ["spam", "scam", "phishing"]; ``` Regex patterns run synchronously on the whole response (and `sanitizationPatterns` on the whole user prompt), so a pattern that can backtrack catastrophically would stall the process. Before a pattern is compiled it is checked, and it is refused when it: - is longer than 1000 characters; - repeats a group in which a variable-length part (`+`, `*`, `?`, `{n,m}`) can match the same text as what follows it, such as `(a+)+`, `(\w+\s*)*`, `(.*a){10}`, `(a?a?)+` or `(a{1,30}){1,30}`; - repeats a group whose alternatives may overlap, such as `(a|aa)+`; - chains more than 8 optional parts (`a?a?a?...`) or more than 4 open-ended overlapping ones (`.*a.*b.*c.*d.*e`); - uses a repetition bound above 500, such as `a{1,1000}`. Repeated groups whose variable parts are separated by a character they cannot match, such as `(\d{1,3}\.){3}` or `([a-z0-9-]+\.)+`, are accepted. A refused pattern is skipped and logged with `logger.error` (`Refusing regex pattern ...` for `regexPatterns`, `Refusing sanitization pattern ...` for `sanitizationPatterns`), the same way an invalid regex is. Nothing is thrown at the caller and the remaining patterns still run, but a skipped pattern filters nothing. The check is static and conservative: it refuses some safe patterns, compares classes on a sample of characters, only partly covers exponential shapes built from optional parts, and accepts polynomial ones (`.*.*.*x`), so test patterns on long input. ### Evaluation Actions Configurable responses based on evaluation results: - **block**: Prevent request processing entirely - **sanitize**: Clean content and continue processing - **warn**: Log warning but allow processing - **log**: Record for monitoring but allow processing ## Demo Component ### Using the Demo (`neurolink-demo/middleware/guardrails-precall-demo.ts`) ```typescript const demo = new GuardrailsPrecallDemo(); // Test various input scenarios await demo.testSafeInput(); await demo.testUnsafeInput(); await demo.testBadWords(); await demo.testRegexFiltering(); ``` ### Demo Features - Interactive testing of guardrail functionality - Visual feedback on filtering actions - Performance metrics and timing - Before/after content comparison ## Visual Proof Screenshots demonstrating guardrails in action: ### 1. Pre-call Filtering (`guardrails-pre-call-filtering.png`) - Shows evaluation process and decision making - Displays safety scores and reasoning ### 2. Content Sanitization (`guardrails-pre-call-filtering-2.png`) - Before and after content comparison - Filtering statistics and applied rules ### 3. Block Actions (`guardrails-pre-call-filtering-3.png`) - Demonstrates request blocking for unsafe content - Shows error messages and user feedback ### 4. Performance Metrics (`guardrails-pre-call-filtering-4.png`) - Evaluation timing and processing speeds - Impact on overall request latency ## Integration Examples ### With MiddlewareFactory ```typescript const factory = new MiddlewareFactory({ preset: "security", middlewareConfig: { guardrails: { enabled: true, config: guardrailsConfig, }, }, }); const guardedModel = factory.applyMiddleware(baseModel, context); ``` ### Direct Integration ```typescript const guardrails = new GuardrailsMiddleware(baseModel, { precallEvaluation: { enabled: true, provider: "google-ai", }, }); const result = await guardrails.generate({ prompt: "User input to be evaluated", }); ``` ### Streaming Support ```typescript const stream = await guardrails.generateStream({ prompt: "Streaming content with guardrails", }); for await (const chunk of stream) { console.log(chunk.content); } ``` ## Performance Considerations ### Evaluation Timing - Pre-call evaluation: ~2-5 seconds (depending on model) - Content filtering: \; // Apply content filtering function applyContentFiltering( text: string, badWordsConfig?: BadWordsConfig, context: string = "unknown", ): ContentFilteringResult; // Sanitize request parameters function applySanitization( params: LanguageModelV1CallOptions, sanitizedInput: string, ): LanguageModelV1CallOptions; ``` ## Troubleshooting ### Common Issues 1. **Evaluation Taking Too Long** - Check evaluation model availability - Implement timeout handling - Consider using faster models 2. **Too Many False Positives** - Adjust evaluation thresholds - Review and refine regex patterns - Check word list relevance 3. **Regex Patterns Not Working** - Validate regex syntax - Look for `Refusing regex pattern` in the error log: patterns over 1000 characters or with ambiguous nested repetition are skipped - Test patterns with sample content - Check for proper escaping 4. **Performance Impact** - Monitor evaluation timing - Optimize configuration settings - Consider caching strategies ### Debug Mode Enable debug logging for detailed information: ```typescript const config = { debug: true, // Enable detailed logging precallEvaluation: { enabled: true, logEvaluations: true, }, }; ``` ## Migration Guide ### From Previous Implementations If upgrading from older guardrail implementations: 1. Update configuration format to new interfaces 2. Replace deprecated methods with new utility functions 3. Test evaluation thresholds and adjust as needed 4. Update error handling to use new patterns ### Breaking Changes - Configuration structure has been updated for better organization - Some utility function signatures have changed - Error handling patterns have been improved ## Conclusion The NeuroLink guardrails implementation provides comprehensive content safety and filtering capabilities with: - ✅ AI-powered pre-call evaluation - ✅ Flexible content filtering options - ✅ Configurable response actions - ✅ Visual proof and demonstrations - ✅ High performance and scalability - ✅ Comprehensive error handling - ✅ TypeScript support throughout For additional support or questions, refer to the main NeuroLink documentation or create an issue in the repository. --- ## Guardrails Middleware # Guardrails Middleware > **Since**: v7.29.0 | **Status**: Stable | **Availability**: SDK; the CLI reads `NEUROLINK_MIDDLEWARE_PRESET` ## Overview **What it does**: Guardrails is a built-in language-model middleware (id `guardrails`) that checks what a model returns, and optionally what a user sends. It has three mechanisms. Each is off until you configure it: - **Bad-word filtering** replaces matches of terms or regular expressions you list with a fixed string. Works in `generate()` and `stream()`. - **Model-based filtering** asks a second model whether the reply is safe and replaces the whole reply if the answer is `unsafe`. `generate()` only. - **Pre-call evaluation** asks a model to judge the user's input before the request is sent, and answers a blocked request with a fixed refusal. Works in `generate()` and `stream()`. **What it does not do**: Guardrails ships no word list, no profanity list and no PII patterns. With nothing configured it changes nothing, including under `preset: "security"`. It is a text filter, not a compliance control: a term that is not in your list passes through, and a model-based check can miss unsafe content or be unavailable (see [Model-Based Filtering](#model-based-filtering)). Built-in PII detection is a separate `piiDetection` option on `generate()` and `stream()`, not part of guardrails. **Common use cases**: - Redacting a known set of terms (brand names, internal codenames, banned words) from model output - A second-opinion safety check on replies from `generate()` - Refusing requests that an evaluator model judges unsafe before they reach the main model ## Quick Start ### Redact terms on one call ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Write a product description" }, middleware: { middlewareConfig: { guardrails: { enabled: true, config: { badWords: { enabled: true, list: ["spam", "scam"], }, }, }, }, }, }); // A reply of "This is spam and a scam." arrives as // "This is [REDACTED] and a [REDACTED]." console.log(result.content); ``` Both `middlewareConfig.guardrails.enabled` and `badWords.enabled` must be `true`, and `list` or `regexPatterns` must be non-empty. Missing any one of them filters nothing. ### Set it once for an instance ```typescript const neurolink = new NeuroLink({ middleware: { preset: "security", middlewareConfig: { guardrails: { config: { badWords: { enabled: true, list: ["spam", "scam"] }, }, }, }, }, }); // Every generate(), stream() and generateText() on this instance is filtered await neurolink.generate({ input: { text: "Write a product description" } }); ``` The `preset: "security"` line is what switches guardrails on here; the word list is what makes it filter. ### Set it once for the process ```typescript configureGlobalMiddleware, clearGlobalMiddleware, } from "@juspay/neurolink"; configureGlobalMiddleware({ preset: "security", middlewareConfig: { guardrails: { config: { badWords: { enabled: true, list: ["spam", "scam"] } }, }, }, }); // Every NeuroLink instance in this process now applies it, including // instances created before this call. clearGlobalMiddleware(); // back to the previous behaviour ``` ### Turn a preset on from the environment ```bash export NEUROLINK_MIDDLEWARE_PRESET="security" ``` :::warning[The security preset redacts nothing by itself] `preset: "security"` only enables the guardrails middleware. It adds no `badWords` and no `modelFilter`, so until one of the layers below supplies them, a reply passes through unchanged. That is true of `NEUROLINK_MIDDLEWARE_PRESET=security` too. There is deliberately no default word list: a generic list gives false assurance and false positives. ::: ## Defaults and precedence A call resolves its middleware from four layers. A higher layer overrides a lower one. | Order | Layer | How you set it | Scope | | ----------- | ----------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------- | | 1 (lowest) | Environment | `NEUROLINK_MIDDLEWARE_PRESET` | Read when each `NeuroLink` instance is constructed. A preset name only: `default`, `all` or `security` | | 2 | Global | `configureGlobalMiddleware(options)` | The whole process. Read on every call, so existing instances pick it up. A later call replaces the earlier one | | 3 | Instance | `new NeuroLink({ middleware })` | That instance. Snapshotted at construction: later edits to your object's word lists or strings are not picked up | | 4 (highest) | Per call | `generate({ middleware })` and so on | That call | The defaults apply to `generate()`, `stream()` and `generateText()`. With no default set, a call behaves exactly as it did before: only its own `middleware` counts. :::note[Calls NeuroLink makes for you] The classifier router's model strategy and the probe call in `checkCredentials()` run through `generate()` on your own instance, so all of that instance's defaults apply to them. The SDK also creates separate `NeuroLink` instances for the file summariser, the conversation-memory condenser, the Redis conversation title generator and the image-generation service. Those see the environment layer, which every instance reads, and the global layer, which is read on every call, but not your instance's `middleware` option. A global `badWords` list therefore redacts file summaries and titles, and a global `precallEvaluation` sends whole file contents to the evaluator model. ::: An unrecognised `NEUROLINK_MIDDLEWARE_PRESET` is ignored. A message naming the value is written to stderr, once per distinct value, whether or not debugging is on. A `preset` in a constructor or global default that is not `default`, `all` or `security` throws a `TypeError` at `new NeuroLink()` or `configureGlobalMiddleware()`, so a typo cannot silently replace a valid preset from a lower layer and leave guardrails off. ### How layers combine | Option | Rule | | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `preset` | The highest layer that sets one wins | | `middlewareConfig` | Merged per middleware id. Within an id, `enabled` and `conditions` come from the highest layer that sets them | | `middlewareConfig..config` | Merged key by key. A key set by a higher layer replaces the lower layer's value for that key as a whole: `badWords` is not combined | | `middleware`, `enabledMiddleware`, `disabledMiddleware` (lists) | The highest layer that sets the list replaces it. Lists are never concatenated. An explicit `[]` clears an inherited list | | `global` | Merged key by key | The factory applies `disabledMiddleware` after `enabledMiddleware`, so a lower layer's disabled list could out-vote a call that asked for the opposite. The merge prevents that: an id that a higher layer switches on, by `enabledMiddleware` or by `middlewareConfig..enabled: true`, is removed from a disabled list it would inherit, and the reverse. ```typescript configureGlobalMiddleware({ middlewareConfig: { guardrails: { enabled: true, config: { badWords: { enabled: true, list: ["spam", "scam"] } }, }, }, }); const neurolink = new NeuroLink({ middleware: { middlewareConfig: { // Replaces the global badWords as a whole: "spam" and "scam" are no // longer filtered, "refund" is. `enabled: true` is still inherited. guardrails: { config: { badWords: { enabled: true, list: ["refund"] } } }, }, }, }); await neurolink.generate({ input: { text: "Draft a reply" }, // Switch guardrails off for this call only middleware: { disabledMiddleware: ["guardrails"] }, }); ``` ## Configuration These go under `middlewareConfig.guardrails.config`, except the first row. | Option | Type | Default | Description | | ------------------------------------- | ----------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | `middlewareConfig.guardrails.enabled` | `boolean` | `false`, unless a preset enables it | Master switch. `preset: "security"` and `preset: "all"` set it to `true` | | `badWords.enabled` | `boolean` | `false` | Turn on term filtering | | `badWords.list` | `string[]` | none | Terms to redact. Case-insensitive, matched as substrings (no word boundaries), so `ass` also matches inside `class` | | `badWords.regexPatterns` | `string[]` | none | Case-insensitive regular expressions. When both this and `list` are set, `list` is ignored and a warning is logged | | `badWords.replacementText` | `string` | `[REDACTED]` | What each match is replaced with. The replacement is a fixed string, not length-preserving | | `modelFilter.enabled` | `boolean` | `false` | Turn on the model-based check (`generate()` only) | | `modelFilter.filterModel` | `string` or model | none | `"provider:model"`, a bare model id, or a model handle. See [Model-Based Filtering](#model-based-filtering) | | `precallEvaluation.enabled` | `boolean` | `false` | Evaluate the user's input before the call | | `precallEvaluation.provider` | `string` | `google-ai` | Provider of the evaluator model | | `precallEvaluation.evaluationModel` | `string` | `gemini-2.5-flash` | Evaluator model | For `precallEvaluation` thresholds, actions and sanitization, see [guardrails-ai-integration.md](/docs/features/guardrails-ai). ### Environment variables | Variable | Values | Effect | | ----------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `NEUROLINK_MIDDLEWARE_PRESET` | `default`, `all`, `security` | Lowest-precedence default preset for every `NeuroLink` instance. Blank is ignored; unknown is ignored with a message on stderr | | Preset | Turns on | Notes | | ---------- | --------------------- | ----------------------------------------------------------------------------- | | `default` | analytics | | | `all` | analytics, guardrails | Not everything: auto-evaluation and lifecycle are opt-in per call | | `security` | guardrails | Filters nothing until `badWords`, `modelFilter` or `precallEvaluation` is set | There is no config-file setting for middleware. Use the constructor option, `configureGlobalMiddleware()` or the environment variable. ### CLI The CLI builds a `NeuroLink` instance, so `NEUROLINK_MIDDLEWARE_PRESET` applies to CLI runs too: ```bash export NEUROLINK_MIDDLEWARE_PRESET="security" npx @juspay/neurolink generate "Write a product description" ``` The CLI has no option for a word list or a model filter, so this enables guardrails and filters nothing. Use the SDK to choose what is filtered. ## How It Works ### Filtering Pipeline 1. Your request is sent to the model. With `precallEvaluation` on, an evaluator model sees the input first and an unsafe request is answered with `Request contains inappropriate content and has been blocked.` without reaching the main model. 2. The model replies. 3. The guardrails middleware filters the reply: - **Bad words**: the configured terms or patterns are replaced. - **Model filter** (`generate()` only): a second model classifies the reply. 4. The filtered reply is delivered. ### Bad Word Filtering ```typescript // badWords.list = ["spam"] // Input: "This contains spam and other spam words" // Output: "This contains [REDACTED] and other [REDACTED] words" ``` - Case-insensitive - Replaces each match with a fixed string, `[REDACTED]` by default; override it with `badWords.replacementText` - A term matches anywhere inside a word. Use `regexPatterns` with `\b` when you need word boundaries - Works in both `generate()` and `stream()` ### Regex Patterns `badWords.regexPatterns` takes regular expressions, each applied with the `gi` flags. When it is set it takes priority over `list`: ```typescript badWords: { enabled: true, regexPatterns: [ "\\b(password|secret)\\b", "\\d{3}-\\d{2}-\\d{4}", // SSN "\\d{16}", // card number ], }, ``` Patterns run synchronously against the whole response, so one that backtracks catastrophically would stall every request in the process. The cost comes from input that can be split between the parts of a pattern in many ways: a variable-length part (`+`, `*`, `?`, `{n,m}`) that can match the same text as whatever follows it. A pattern is refused when it: - is longer than 1000 characters; - repeats a group in which such a part can match the same text as what follows it, including the next iteration of the group: `(a+)+`, `(\w+\s*)*`, `(.*a){10}`, `(a?a?)+`, `(a{1,30}){1,30}`; - repeats a group whose alternatives may overlap, such as `(a|aa)+` or `(\w|\d)+`; - chains too many overlapping variable-length parts: more than 8 optional parts in a row (`a?a?a?a?a?a?a?a?a?`), or more than 4 open-ended ones (`.*a.*b.*c.*d.*e.*f`); - uses a repetition bound above 500, such as `a{1,1000}`. A repeated group is fine when each variable-length part is followed by something it cannot match. These all run: `(\d{1,3}\.){3}`, `([a-z0-9-]+\.)+[a-z]{2,}`, `(?:\d{4}[- ]?)+`, `\b(?:\d[ -]*?){13,16}\b`, `(?:\w+\s+)+`. A refused pattern is skipped and logged as an error (`Refusing regex pattern ...`), the same way an invalid regex is. It is never thrown at the caller, and the other patterns in the list still run. Fail-open is the trade: **a skipped pattern filters nothing**, so check the logs after you change a pattern. The same limits apply to `precallEvaluation.sanitizationPatterns` (`Refusing sanitization pattern ...`). The check reads the pattern; it does not run it, so it is conservative and not a proof: - It refuses some safe patterns, such as a small fixed count of an ambiguous part (`(a{1,3}){3}`). Flatten it (`a{1,9}`) or split it. - It compares character classes on a fixed sample of characters (Latin text plus a few other scripts), so a class that only overlaps outside the sample can look disjoint. A back-reference is assumed to overlap with everything. - Exponential shapes built from optional parts are only partly covered: loops and long chains are refused, but the check is a model of the engine, not the engine. Open-ended repeats that cost polynomial time (`.*.*.*x`, up to four in a row) are accepted. Use `list` for plain terms, and test a pattern on long input before deploying it. A hard guarantee would need a time budget around the match itself (a `node:vm` timeout or a worker), which is a possible follow-up. ### Streaming With `badWords.enabled: true`, `stream()` holds each run of text and filters it as one string, so a term split across chunks is still caught. The run is released when a non-text part arrives or the stream ends. Filtering therefore costs incremental delivery: you may receive a long reply in one piece at the end rather than as it is generated. With bad-word filtering off, chunks pass through unbuffered. ```typescript const result = await neurolink.stream({ input: { text: "Write a long story" }, middleware: { middlewareConfig: { guardrails: { enabled: true, config: { badWords: { enabled: true, list: ["spam"] } }, }, }, }, }); for await (const chunk of result.stream) { if ("content" in chunk && typeof chunk.content === "string") { process.stdout.write(chunk.content); // already filtered } } ``` `neurolink.streamText(prompt, options?)` is the older string-only form: it takes the prompt as its first argument and yields plain strings, not objects with a `content` field. ### Model-Based Filtering ```typescript const result = await neurolink.generate({ input: { text: "Summarise this ticket" }, middleware: { middlewareConfig: { guardrails: { enabled: true, config: { modelFilter: { enabled: true, filterModel: "openai:gpt-4o-mini", }, }, }, }, }, }); ``` After the main model replies, the text is sent to the filter model with the prompt `Is the following text safe? Respond with only "safe" or "unsafe".` If the answer, trimmed and lower-cased, is exactly `unsafe`, each text part of the reply is replaced by ``. Any other answer leaves the reply alone. - **`generate()` only.** `stream()` does not run the model filter. - **`filterModel` as a string** is `"provider:model"`. A bare model id such as `gpt-4o-mini` is created on the default provider (`NEUROLINK_PROVIDER`, then `AI_PROVIDER`, then `vertex`), so name the provider unless that is what you want. - **It fails open.** If the filter model cannot be created or the call fails, an error is logged and the reply is returned unfiltered. - **The reply text leaves for another model.** The filter model's provider sees what the main model said. ### Pre-Call Evaluation With `precallEvaluation.enabled: true`, the user's input is sent to an evaluator model (`google-ai` with `gemini-2.5-flash` unless you set `provider` and `evaluationModel`). An input it judges unsafe is blocked by default; if the evaluator errors, the request is allowed. This needs credentials for the evaluator's provider. ## Advanced Usage ### Combining with Other Middleware ```typescript const result = await neurolink.generate({ input: { text: "Draft a refund policy" }, middleware: { preset: "all", // analytics + guardrails middlewareConfig: { guardrails: { config: { badWords: { enabled: true, list: ["profanity1", "profanity2"] }, }, }, }, }, }); ``` ### Dynamic Guardrails A per-call `middleware` can carry a list you load at request time. It replaces the list from any default, because lists are replaced rather than combined. ```typescript const customWords = await loadBlocklistFromDatabase(); const result = await neurolink.generate({ input: { text: "Write a product description" }, middleware: { middlewareConfig: { guardrails: { enabled: true, config: { badWords: { enabled: true, list: [...customWords, "static-term"] }, }, }, }, }, }); ``` ## API Reference - `new NeuroLink({ middleware })`: instance default, a `MiddlewareFactoryOptions` object - `configureGlobalMiddleware(options)`: process-wide default; replaces the previous one and throws a `TypeError` if `options` is not an object - `clearGlobalMiddleware()`: remove the process-wide default - `generate({ middleware })`, `stream({ middleware })`, `generateText({ middleware })`: per-call, highest precedence - `preset: "security"`: guardrails on, nothing configured - `preset: "all"`: analytics and guardrails - `middlewareConfig.guardrails`: the configuration described above See [guardrails-ai-integration.md](/docs/features/guardrails-ai) for pre-call evaluation in depth. ## Troubleshooting ### Problem: Guardrails not filtering content **Cause**: One of the switches is missing, or only a preset is set. `preset: "security"` enables guardrails but gives them nothing to filter. **Solution**: Set all of these, on the call, the instance or the global default: ```typescript const result = await neurolink.generate({ input: { text: "Tell me about security best practices" }, middleware: { preset: "security", // or middlewareConfig.guardrails.enabled: true middlewareConfig: { guardrails: { config: { badWords: { enabled: true, list: ["a-term-you-want-removed"] }, }, }, }, }, }); ``` If a default is set but a call still passes through, check whether the call's own `middleware` switches guardrails off (`disabledMiddleware` or `enabled: false`) or replaces the list. ### Problem: Too many false positives (legitimate content filtered) **Cause**: Terms match anywhere inside a word, so a short or common term catches unrelated words. **Solution**: Use specific terms, or a regular expression with word boundaries: ```typescript config: { badWords: { enabled: true, regexPatterns: ["\\bfree\\b"], // "free" but not "freedom" }, } ``` ### Problem: A regex pattern is not filtering anything **Cause**: The pattern was refused for its length or its shape, or it is not valid regex. Both are skipped, and the log says which **Solution**: Look for `Refusing regex pattern` (or `Invalid regex pattern`) in the error log. A refusal names the reason, for example a repeated group whose variable-length part can match the same text as what follows it. Separate the parts with a character they cannot match (`([\w-]+\.)+` instead of `([\w-]+)+`), split a long pattern into several, or move plain terms to `badWords.list` ### Problem: Model-based filter is slow or does nothing **Cause**: A large filter model adds a second round trip to every `generate()`. If the filter model cannot be created, for example a bare id that does not exist on the default provider, the failure is logged and the reply is returned unfiltered. **Solution**: Use a small model and name its provider: ```typescript config: { modelFilter: { enabled: true, filterModel: "openai:gpt-4o-mini", }, } ``` ### Problem: Guardrails not working in streaming mode **Cause**: `stream()` supports bad-word filtering and pre-call evaluation but not the model filter. **Solution**: Use `badWords` for streams, or use `generate()` when you need the model filter. ### Problem: NEUROLINK_MIDDLEWARE_PRESET has no effect **Cause**: The name is not `default`, `all` or `security` (it is then ignored, with a message on stderr), the variable was set after the `NeuroLink` instance was constructed, or a higher layer sets its own `preset`. **Solution**: Export it before the process starts, and check the layer order in [Defaults and precedence](#defaults-and-precedence). ## Best Practices 1. **Name what you filter.** The presets enable guardrails; your word list or filter model does the filtering. 2. **Set a default for every call you cannot audit.** An instance or global default is applied even where a call site forgot `middleware`. 3. **Prefer specific terms or word-boundary patterns** to short common words. 4. **Test with a real reply.** Run a call that should be filtered and one that should not, and check both. 5. **Treat the model filter as best effort.** It fails open and sees only text parts. ## Related Features - [HITL Workflows](/docs/features/hitl) - User approval for risky actions - [Middleware Architecture](/docs/advanced/middleware-architecture) - How the middleware chain is built - [Built-in Middleware](/docs/advanced/builtin-middleware) - Analytics, guardrails and auto-evaluation - [Guardrails AI Integration](/docs/features/guardrails-ai) - Pre-call evaluation and `MiddlewareFactory` usage ## Migration Notes Instance, global and environment defaults were added after guardrails were first released. They are optional: a call that passes its own `middleware` and sets no default behaves as it always did. --- ## Human-in-the-Loop (HITL) Workflows # Human-in-the-Loop (HITL) Workflows > **Since**: v7.39.0 | **Status**: Stable | **Availability**: SDK ## Overview **What it does**: HITL pauses AI tool execution to request explicit user approval before performing risky operations like deleting files, modifying databases, or making expensive API calls. **Why use it**: Prevent costly mistakes and give users control over potentially dangerous AI actions. Think of it as an "Are you sure?" dialog for AI assistant operations. :::warning[Security Best Practice] Only use HITL for truly risky operations. Overusing confirmation prompts degrades user experience and can lead to "confirmation fatigue" where users approve actions without reading them. ::: **Common use cases**: - File deletion or modification operations - Database write/delete operations - Expensive third-party API calls - Irreversible actions (sending emails, posting to social media) - Operations accessing sensitive data ## Quick Start ### SDK Example ```typescript const neurolink = new NeuroLink({ tools: [ { name: "deleteFile", // (1)! description: "Deletes a file from the filesystem", // (2)! requiresConfirmation: true, // (3)! execute: async (args) => { // (4)! // Your deletion logic }, }, ], }); // When AI tries to use deleteFile: // 1. Tool execution pauses // 2. Returns USER_CONFIRMATION_REQUIRED error // 3. Application shows confirmation dialog // 4. On approval, tool executes with confirmation_received = true ``` 1. Tool identifier used by the AI to invoke this function 2. Describes tool purpose to the LLM for proper selection 3. Triggers HITL checkpoint before execution 4. Actual implementation only runs after user approval ### Handling Confirmation in Your UI HITL uses an event-based workflow where the SDK emits confirmation requests and your app responds with user decisions. ```typescript const neurolink = new NeuroLink({ hitl: { enabled: true, dangerousActions: ["delete", "remove", "drop", "truncate"], timeout: 30000, // 30 seconds }, }); // (1)! Reach the SDK's event emitter. NeuroLink does not extend EventEmitter, // so there is no neurolink.on() / neurolink.emit(). const emitter = neurolink.getEventEmitter(); // (2)! Listen for confirmation requests emitter.on("hitl:confirmation-request", async (event) => { const receivedAt = Date.now(); const { confirmationId, toolName, arguments: args, timeoutMs, } = event.payload; // (3)! Show your app's confirmation UI const approved = await showConfirmationDialog({ action: toolName, details: args, message: `AI wants to ${toolName}. Allow?`, timeoutMs, }); // (4)! Send response back to NeuroLink emitter.emit("hitl:confirmation-response", { type: "hitl:confirmation-response", payload: { confirmationId, // Must match the request approved, // (5)! User decision reason: approved ? undefined : "User denied permission", metadata: { timestamp: new Date().toISOString(), responseTime: Date.now() - receivedAt, // Milliseconds since the request arrived }, }, }); }); // (6)! Handle confirmation timeouts emitter.on("hitl:timeout", (event) => { console.warn(`Confirmation timed out for ${event.payload.toolName}`); }); ``` 1. Get the event emitter - `NeuroLink` is not itself an emitter, so requests and responses both go through `getEventEmitter()` 2. Subscribe to confirmation requests - NeuroLink emits one before running a tool that needs approval 3. Show your confirmation UI with the tool name, arguments and remaining time 4. Reply on the same emitter, echoing the request's `confirmationId` so the response is matched to its request 5. Approval decision determines if tool executes 6. Optional: Handle cases where user doesn't respond in time ## Configuration | Option | Type | Default | Required | Description | | ---------------------- | --------- | ------- | -------- | ------------------------------------ | | `requiresConfirmation` | `boolean` | `false` | No | Mark tool as requiring user approval | ### Tool Registration ```typescript const riskyTool = { name: "sendEmail", description: "Sends an email to a recipient", requiresConfirmation: true, // Enable HITL parameters: { /* ... */ }, execute: async (args) => { /* ... */ }, }; ``` ## How It Works ### Execution Flow 1. **AI requests tool execution** → Tool executor checks if tool requires confirmation 2. **Confirmation required?** → Returns `USER_CONFIRMATION_REQUIRED` error to LLM 3. **LLM asks user** → "I need to [action]. Is that okay?" 4. **User responds**: - **Approve** → UI sets `confirmation_received = true` and retries tool execution - **Deny** → UI sends "User cancelled" message back to LLM 5. **Tool executes** → Permission flag immediately resets to `false` ### Security Features - **One-time permissions**: Each approval works for exactly one action - **No reuse**: AI cannot reuse old permissions for new actions - **Automatic reset**: Permission flag clears immediately after use - **Fail-safe**: Defaults to requiring permission when in doubt ### Built-in tools HITL applies to the built-in tools (`readFile`, `writeFile`, `listDirectory`, `analyzeCSV`, `calculateMath`, `getCurrentTime`, `websearchGrounding` and the opt-in `executeBashCommand`) exactly as it applies to tools you register: `dangerousActions` keywords and `customRules` are matched against the tool name on every model-driven call. Before the 2026-10 security audit fix (finding C3) built-in tools bypassed HITL entirely — only tools executed through the tool registry were gated — so a prompt-injected model could write files or, with the bash tool enabled, run shell commands with no confirmation, while the bash tool's own description claimed otherwise. Two built-ins change the machine and are **confirmed on every call while HITL is enabled, whatever `dangerousActions` lists**: `writeFile` and `executeBashCommand`. To gate them by keywords only, like every other tool, set `confirmBuiltinTools: false`: ```typescript const neurolink = new NeuroLink({ hitl: { enabled: true, dangerousActions: ["delete", "drop"], confirmBuiltinTools: false, // writeFile / executeBashCommand follow the keywords }, }); ``` A denied built-in call is reported to the model as a failed tool call (`Tool execution rejected by user: `); the model sees the denial and can continue without the side effect. A confirmation that returns `modifiedArguments` runs the tool with those arguments. The confirmation request carries `serverId: "direct"` for a built-in tool. Per-call tools passed through `generate({ tools })` are the host's own code and are not gated by HITL; wrap their `execute` yourself if they need it. ## API Reference ### Event Types All HITL events ride the SDK emitter returned by `neurolink.getEventEmitter()`; `emitter` below is that object. **Confirmation Request Event** (`hitl:confirmation-request`): ```typescript emitter.on("hitl:confirmation-request", (event) => { event.payload: { confirmationId: string; // Unique ID for this request toolName: string; // Tool requiring confirmation arguments: unknown; // Tool parameters for review actionType: string; // Human-readable description timeoutMs: number; // Milliseconds until timeout allowModification: boolean; // Hint for your UI; NeuroLink applies modifiedArguments either way metadata: { ... } // Session/user context } }); ``` **Confirmation Response** (emit from your app): ```typescript emitter.emit("hitl:confirmation-response", { type: "hitl:confirmation-response", payload: { confirmationId: string; // Must match request approved: boolean; // User decision reason?: string; // Rejection reason modifiedArguments?: unknown; // User-edited args metadata: { timestamp: string; responseTime: number; } } }); ``` **Timeout Event** (`hitl:timeout`): ```typescript emitter.on("hitl:timeout", (event) => { event.payload: { confirmationId: string; toolName: string; timeout: number; } }); ``` ## Troubleshooting ### Problem: Tool executes without asking for permission **Cause**: Tool not marked with `requiresConfirmation: true` **Solution**: ```typescript // Add confirmation flag to tool definition const tool = { name: "deleteTool", requiresConfirmation: true, // (1)! // ... }; ``` 1. Add this boolean flag to any tool that performs risky operations ### Problem: AI keeps asking for confirmation repeatedly **Cause**: Confirmation responses not being sent or sent with wrong `confirmationId` **Solution**: ```typescript // Always respond to confirmation requests with matching ID const emitter = neurolink.getEventEmitter(); emitter.on("hitl:confirmation-request", async (event) => { const receivedAt = Date.now(); const { confirmationId } = event.payload; // (1)! const approved = await showConfirmationDialog(event.payload); // (2)! Send response with EXACT confirmationId from request emitter.emit("hitl:confirmation-response", { type: "hitl:confirmation-response", payload: { confirmationId, // (3)! Must match request exactly approved, metadata: { timestamp: new Date().toISOString(), responseTime: Date.now() - receivedAt, }, }, }); }); ``` 1. Extract confirmation ID from the request event 2. Always respond to every confirmation request 3. **Critical**: Use the same confirmationId from the request ### Problem: Confirmation dialog doesn't show **Cause**: Not listening to `hitl:confirmation-request` event **Solution**: ```typescript // Set up event listener BEFORE making AI requests const emitter = neurolink.getEventEmitter(); emitter.on("hitl:confirmation-request", async (event) => { // (1)! Show your confirmation UI await handleConfirmationPrompt(event); }); // (2)! Then make AI requests - confirmations will now work const result = await neurolink.generate({ input: { text: "Delete all temporary files" }, }); ``` 1. Register the event handler early in your application startup 2. All subsequent tool executions will trigger confirmations when needed ## Best Practices :::tip[Production Recommendation] Store user confirmation preferences to avoid repeated prompts for the same action type. For example, if a user approves "delete temporary files" once, cache that preference for similar low-risk deletions in the same session. ::: ### For Developers 1. **Mark tools conservatively** - If an operation could cause problems, require confirmation 2. **Clear prompts** - Ensure users understand exactly what will happen 3. **Test confirmation flow** - Verify it works smoothly in your UI 4. **Log approvals** - Keep audit trail of user decisions 5. **Handle denials gracefully** - Allow users to try alternative approaches ### What to Mark as Requiring Confirmation ✅ **Do require confirmation**: - File deletions - Database writes/deletes - Sending emails or messages - Making purchases or payments - Modifying production systems ❌ **Don't require confirmation**: - Read-only operations - Answering questions - Generating content - Searching/fetching data ## Related Features - [Guardrails Middleware](/docs/features/guardrails) - Content filtering and safety checks - [Custom Tools](/docs/sdk/custom-tools) - Building your own tools with HITL - [Middleware Architecture](/docs/workflows/middleware) - Advanced request interception ## Migration Notes If upgrading from versions before v7.39.0: 1. Review all existing tools for risk assessment 2. Add `requiresConfirmation: true` to risky tools 3. Implement confirmation dialog in your UI 4. Test with low-risk tools first 5. Roll out to production gradually --- ## Image Generation Streaming Guide # Image Generation Streaming Guide ## Overview NeuroLink supports image generation through AI models like Google Vertex AI's `gemini-3-pro-image-preview` and `gemini-2.5-flash-image`. This guide explains how image generation works in both `generate()` and `stream()` modes, including CLI usage with automatic file saving, technical architecture, and usage examples. ## Table of Contents 1. [Architecture Overview](#architecture-overview) 2. [Streaming Modes](#streaming-modes) 3. [Image Generation Flow](#image-generation-flow) 4. [Usage Examples](#usage-examples) 5. [Implementation Details](#implementation-details) 6. [Troubleshooting](#troubleshooting) ## Streaming Modes ### Real Streaming vs Fake Streaming NeuroLink uses two different streaming approaches depending on the model capabilities: #### Real Streaming (Text Models) - Uses Vercel AI SDK's native `streamText()` function - Streams tokens as they are generated by the AI model - Provides true real-time streaming experience - Used for: GPT-4, Claude, Gemini (text), etc. #### Fake Streaming (Image Models) - Calls `generate()` internally to get complete result - Yields the result progressively to simulate streaming - Required because image generation models don't support token-by-token streaming - Used for: `gemini-2.5-flash-image`, `gemini-3-pro-image-preview`, etc. ### Why Fake Streaming? Image generation models produce complete images, not incremental tokens. The fake streaming approach: 1. **Maintains API Consistency**: Same `stream()` interface for all models 2. **Preserves User Experience**: Clients can use the same code pattern 3. **Enables Progressive Enhancement**: Can yield text chunks before final image 4. **Supports Analytics**: Tracks generation time and token usage --- ## Image Generation Flow ### Step-by-Step Process ``` 1. Client calls neurolink.stream() ↓ 2. BaseProvider.stream() detects image model ↓ 3. Routes to executeFakeStreaming() ↓ 4. Calls this.generate() internally ↓ 5. Provider.executeImageGeneration() is invoked ↓ 6. AI API generates complete image ↓ 7. Image returned as base64 string ↓ 8. enhanceResult() preserves imageOutput field ↓ 9. executeFakeStreaming() yields text chunks (if any) ↓ 10. executeFakeStreaming() yields image chunk { type: "image", imageOutput: { base64: "..." } } ↓ 11. Client receives and processes image chunk ``` ### Code Flow in BaseProvider ```typescript // src/lib/core/baseProvider.ts async stream(options: StreamOptions): Promise { // Step 1: Detect if this is an image generation model const isImageModel = IMAGE_GENERATION_MODELS.some((m) => this.modelName.includes(m), ); // Step 2: Route to fake streaming for image models if (isImageModel) { return await this.executeFakeStreaming(options, analysisSchema); } // Step 3: Use real streaming for text models return await this.executeRealStreaming(options, analysisSchema); } private async executeFakeStreaming( options: StreamOptions, analysisSchema?: z.ZodSchema, ): Promise { // Step 4: Call generate() to get complete result const result = await this.generate({ prompt: options.prompt, // ... other options }); // Step 5: Create async generator to yield chunks const stream = async function* () { // Yield text chunks if present if (result.text) { const words = result.text.split(" "); for (const word of words) { yield { content: word + " " }; await new Promise((resolve) => setTimeout(resolve, 50)); } } // Step 6: Yield image chunk if present if (result?.imageOutput) { yield { type: "image" as const, imageOutput: result.imageOutput, }; } }; return { stream: stream(), analytics: result.analytics, evaluation: result.evaluation, }; } ``` --- ## Usage Examples ### Example 1: Basic Image Generation with generate() ```typescript const neurolink = new NeuroLink(); // Generate an image using Vertex AI const result = await neurolink.generate({ input: { text: "A serene mountain landscape at sunset" }, provider: "vertex", model: "gemini-3-pro-image-preview", }); // Access the generated image if (result.imageOutput) { const base64Image = result.imageOutput.base64; console.log(`Image generated: ${base64Image.length} characters`); // Save to file const imageBuffer = Buffer.from(base64Image, "base64"); fs.writeFileSync("mountain.png", imageBuffer); console.log("✅ Image saved to mountain.png"); } // Result also contains descriptive text console.log("Content:", result.content); // Output: "Generated image using gemini-3-pro-image-preview (image/png)" // Access analytics (if enabled) if (result.analytics) { console.log(`Generation time: ${result.analytics.responseTime}ms`); console.log(`Tokens used: ${result.analytics.usage.total}`); } ``` ### Example 2: Image Generation with Streaming ```typescript const neurolink = new NeuroLink(); // Stream image generation (uses fake streaming for image models) const result = await neurolink.stream({ input: { text: "A futuristic city with flying cars" }, provider: "vertex", model: "gemini-2.5-flash-image", }); // Process stream chunks for await (const chunk of result.stream) { if ("content" in chunk) { // Text chunk (description or metadata) process.stdout.write(chunk.content); } else if (chunk.type === "image") { // Image chunk - yielded after text chunks complete console.log("\n✅ Image received!"); const base64Image = chunk.imageOutput.base64; // Save the image const imageBuffer = Buffer.from(base64Image, "base64"); fs.writeFileSync("futuristic-city.png", imageBuffer); console.log(`Image size: ${imageBuffer.length} bytes`); console.log(`Saved to: futuristic-city.png`); } } // Access analytics after streaming completes if (result.analytics) { console.log(`\nTotal generation time: ${result.analytics.responseTime}ms`); } ``` **Note:** Image generation uses "fake streaming" - the complete image is generated first, then yielded as a single chunk. This maintains API consistency with text streaming. ### Example 3: CLI Usage ```bash # Basic image generation (saves to default path: generated-images/image-.png) npx neurolink generate "A beautiful sunset over the ocean" \ --provider vertex \ --model gemini-3-pro-image-preview # Output: # Generated image saved to: generated-images/image-2025-12-16T11-50-42-209Z.png # Image size: 1856.34 KB # Generated image using gemini-3-pro-image-preview (image/png) # Generate with custom output path npx neurolink generate "Mountain landscape at sunset" \ --provider vertex \ --model gemini-2.5-flash-image \ --imageOutput ./my-images/mountain.png # Output: # Generated image saved to: ./my-images/mountain.png # Image size: 2048.67 KB # Generated image using gemini-2.5-flash-image (image/png) # Generate with analytics npx neurolink generate "Futuristic city with flying cars" \ --provider vertex \ --model gemini-2.5-flash-image \ --imageOutput ./images/city.png \ --enable-analytics # Use different models npx neurolink generate "Serene forest scene" \ --provider vertex \ --model gemini-3-pro-image-preview # Best quality, requires 'global' location npx neurolink generate "Quick sketch of a cat" \ --provider vertex \ --model gemini-2.5-flash-image # Faster generation ``` **CLI Options:** - `--imageOutput `: Custom path for generated image (default: `generated-images/image-.png`) - `--provider vertex` or `--provider google-ai`: Both Vertex AI and Google AI Studio support image generation - `--model `: Image generation model to use - `--enable-analytics`: Include generation metrics ### Example 4: Detecting Image Chunks in Stream ```typescript const neurolink = new NeuroLink(); const result = await neurolink.stream({ input: { text: "A magical forest with glowing mushrooms" }, provider: "vertex", model: "gemini-2.5-flash-image", }); let textContent = ""; let imageData: string | null = null; for await (const chunk of result.stream) { // Type guard for text chunks if ("content" in chunk) { textContent += chunk.content; } // Type guard for image chunks if ("type" in chunk && chunk.type === "image") { imageData = chunk.imageOutput.base64; console.log("Image chunk received!"); } } console.log("Text description:", textContent); console.log("Image available:", !!imageData); if (imageData) { // Process the image const imageBuffer = Buffer.from(imageData, "base64"); fs.writeFileSync("magical-forest.png", imageBuffer); console.log(`✅ Saved ${(imageBuffer.length / 1024).toFixed(2)} KB image`); } ``` ### Example 5: Error Handling ```typescript const neurolink = new NeuroLink(); try { const result = await neurolink.stream({ input: { text: "A dragon flying over mountains" }, provider: "vertex", model: "gemini-3-pro-image-preview", }); let imageReceived = false; for await (const chunk of result.stream) { if ("type" in chunk && chunk.type === "image") { imageReceived = true; const base64Image = chunk.imageOutput.base64; // Validate image data if (!base64Image || base64Image.length === 0) { throw new Error("Empty image data received"); } // Validate base64 format // Validate base64 format (padding '=' only at end, max 2 chars) if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64Image)) { throw new Error("Invalid base64 format"); } // Save image const imageBuffer = Buffer.from(base64Image, "base64"); // Validate minimum size (1KB) if (imageBuffer.length { const { prompt } = req.body; if (!prompt) { return res.status(400).json({ error: "Prompt is required" }); } const neurolink = new NeuroLink(); try { const result = await neurolink.stream({ input: { text: prompt }, provider: "vertex", model: "gemini-2.5-flash-image", }); // Set headers for streaming response res.setHeader("Content-Type", "text/event-stream"); res.setHeader("Cache-Control", "no-cache"); res.setHeader("Connection", "keep-alive"); for await (const chunk of result.stream) { if ("content" in chunk) { // Send text chunks as SSE res.write( `data: ${JSON.stringify({ type: "text", content: chunk.content })}\n\n`, ); } else if (chunk.type === "image") { // Send image chunk as SSE res.write( `data: ${JSON.stringify({ type: "image", base64: chunk.imageOutput.base64, size: chunk.imageOutput.base64.length, })}\n\n`, ); } } res.write("data: [DONE]\n\n"); res.end(); } catch (error) { res.status(500).json({ error: error.message, details: "Image generation failed", }); } }); // REST endpoint (non-streaming) app.post("/api/generate-image-sync", async (req, res) => { const { prompt } = req.body; const neurolink = new NeuroLink(); try { const result = await neurolink.generate({ input: { text: prompt }, provider: "vertex", model: "gemini-2.5-flash-image", }); if (result.imageOutput) { res.json({ success: true, base64: result.imageOutput.base64, content: result.content, size: Buffer.from(result.imageOutput.base64, "base64").length, }); } else { res.status(500).json({ error: "No image generated" }); } } catch (error) { res.status(500).json({ error: error.message }); } }); app.listen(3000, () => { console.log("Server running on http://localhost:3000"); }); ``` --- ## Implementation Details ### Provider-Specific Implementation Vertex AI provider implements image generation through the REST API: ```typescript // src/lib/providers/googleVertex.ts async executeImageGeneration( options: TextGenerationOptions, ): Promise { const { GoogleAuth } = await import("google-auth-library"); // Authenticate with Google Cloud const auth = new GoogleAuth({ scopes: ["https://www.googleapis.com/auth/cloud-platform"], }); const client = await auth.getClient(); const accessToken = await client.getAccessToken(); // Determine location based on model const location = this.modelName.includes("gemini-3-pro-image") ? "global" // gemini-3-pro-image-preview requires global : this.location; // Other models can use regional endpoints // Build request with response modalities for image generation const requestBody = { contents: [{ role: "user", parts: [{ text: options.prompt }], }], generation_config: { response_modalities: ["TEXT", "IMAGE"], // CRITICAL for image generation temperature: options.temperature || 0.7, candidate_count: 1, }, }; // Call Vertex AI API const url = `https://${location}-aiplatform.googleapis.com/v1/projects/${this.projectId}/locations/${location}/publishers/google/models/${this.modelName}:generateContent`; const response = await fetch(url, { method: "POST", headers: { Authorization: `Bearer ${accessToken.token}`, "Content-Type": "application/json", }, body: JSON.stringify(requestBody), }); const data = await response.json(); // Extract image from response const candidate = data.candidates?.[0]; const imagePart = candidate?.content?.parts?.find( (part) => (part.inlineData || part.inline_data) && ((part.inlineData?.mimeType || part.inline_data?.mime_type)?.startsWith("image/")) ); if (!imagePart) { throw new Error("No image generated in response"); } // Extract base64 data (handle both camelCase and snake_case) const imageData = imagePart.inlineData?.data || imagePart.inline_data?.data; const mimeType = imagePart.inlineData?.mimeType || imagePart.inline_data?.mime_type || "image/png"; // Return result with imageOutput const result: EnhancedGenerateResult = { content: `Generated image using ${this.modelName} (${mimeType})`, imageOutput: { base64: imageData, }, provider: this.providerName, model: this.modelName, usage: { input: this.estimateTokenCount(options.prompt), output: 0, total: this.estimateTokenCount(options.prompt), }, }; // Enhance with analytics/evaluation if enabled return await this.enhanceResult(result, options, startTime); } ``` **Key Implementation Details:** 1. **Authentication**: Uses Google Cloud service account credentials 2. **Location Handling**: Automatically selects `global` for `gemini-3-pro-image-preview` 3. **Response Modalities**: Sets `["TEXT", "IMAGE"]` to enable image generation 4. **Base64 Extraction**: Handles both `inlineData` and `inline_data` formats 5. **Result Enhancement**: Preserves `imageOutput` through analytics pipeline ### Type Definitions ```typescript // src/lib/types/streamTypes.ts export type StreamResult = { stream: AsyncIterable; // Provider information provider?: string; model?: string; // Usage information usage?: TokenUsage; finishReason?: string; // Tool integration toolCalls?: ToolCall[]; toolResults?: ToolResult[]; toolsUsed?: string[]; // Stream metadata metadata?: { streamId?: string; startTime?: number; totalChunks?: number; responseTime?: number; }; // Analytics and evaluation (available after stream completion) analytics?: AnalyticsData | Promise; evaluation?: EvaluationData | Promise; }; // src/lib/types/generateTypes.ts export type GenerateResult = { content: string; outputs?: { text: string }; // Future extensible for multi-modal audio?: TTSResult; imageOutput?: { base64: string } | null; // Provider information provider?: string; model?: string; // Usage and performance usage?: TokenUsage; responseTime?: number; // Tool integration toolCalls?: Array; toolResults?: unknown[]; toolsUsed?: string[]; enhancedWithTools?: boolean; // Analytics and evaluation analytics?: AnalyticsData; evaluation?: EvaluationData; }; // Note: CLI adds savedPath to imageOutput when saving images locally // CLI-specific type (not part of core SDK): // imageOutput?: { base64: string; savedPath?: string } | null; // EnhancedGenerateResult extends GenerateResult with optional analytics/evaluation export type EnhancedGenerateResult = GenerateResult & { analytics?: AnalyticsData; evaluation?: EvaluationData; }; // CLI-specific types export type GenerateCommandArgs = { input: string; provider?: string; model?: string; imageOutput?: string; // Custom path for generated images // ... other options }; ``` ### Analytics Integration The `enhanceResult()` method in BaseProvider preserves the `imageOutput` field while adding analytics: ```typescript // src/lib/core/baseProvider.ts protected async enhanceResult( result: EnhancedGenerateResult, options: TextGenerationOptions, startTime: number, ): Promise { const responseTime = Date.now() - startTime; // CRITICAL: Store imageOutput separately to ensure preservation const imageOutput = result.imageOutput; let enhancedResult = { ...result }; // Add analytics if enabled if (options.enableAnalytics) { try { const analytics = await this.createAnalytics(result, responseTime, options); // Preserve ALL fields including imageOutput when adding analytics enhancedResult = { ...enhancedResult, analytics, imageOutput }; } catch (error) { logger.warn(`Analytics creation failed: ${error.message}`); } } // Add evaluation if enabled if (options.enableEvaluation) { try { const evaluation = await this.createEvaluation(result, options); // Preserve ALL fields including imageOutput when adding evaluation enhancedResult = { ...enhancedResult, evaluation, imageOutput }; } catch (error) { logger.warn(`Evaluation creation failed: ${error.message}`); } } // CRITICAL FIX: Always restore imageOutput if it existed if (imageOutput) { enhancedResult.imageOutput = imageOutput; } return enhancedResult; } ``` **Key Points:** - `imageOutput` is explicitly preserved through analytics/evaluation pipeline - Spread operator ensures all existing fields are maintained - Double-check restoration at the end prevents accidental loss --- ## Troubleshooting ### Common Issues #### 1. No Image Chunk Received **Symptom**: Stream completes but no image chunk is yielded. **Possible Causes**: - Model is not an image generation model - Wrong provider (only Vertex AI supports image generation) - API credentials are invalid or missing - Model not available in selected region **Solution**: ```typescript // Verify you're using Vertex AI provider const result = await neurolink.generate({ input: { text: "Generate an image of a sunset" }, provider: "vertex", // ✅ Required model: "gemini-3-pro-image-preview", // ✅ Valid image model }); // NOT these: // provider: "openai" // ❌ Doesn't support image generation // provider: "anthropic" // ❌ Doesn't support image generation // Note: "google-ai" also supports image generation with gemini-2.5-flash-image // Verify credentials console.log( "GOOGLE_APPLICATION_CREDENTIALS:", process.env.GOOGLE_APPLICATION_CREDENTIALS, ); console.log("GOOGLE_VERTEX_PROJECT:", process.env.GOOGLE_VERTEX_PROJECT); ``` #### 2. Empty Base64 String **Symptom**: Image chunk received but `base64` field is empty. **Possible Causes**: - API returned error but didn't throw - Response format changed - Network issue during transmission **Solution**: ```typescript for await (const chunk of result.stream) { if (chunk.type === "image") { if (!chunk.imageOutput.base64) { console.error("Empty image data received"); console.error("Full chunk:", JSON.stringify(chunk, null, 2)); } else { console.log(`Image data length: ${chunk.imageOutput.base64.length}`); } } } ``` #### 3. Model Not Found Error **Symptom**: Error: `models/gemini-3-pro-image-preview is not found for API version v1` **Cause**: `gemini-3-pro-image-preview` requires `location: "global"` but a regional endpoint is being used. **Solution**: ```typescript // The provider automatically handles location selection: // - gemini-3-pro-image-preview → uses "global" // - Other models → uses configured region (e.g., "us-east5") // Set region in environment variable process.env.GOOGLE_VERTEX_LOCATION = "us-east5"; // For non-preview models // Or pass in options const result = await neurolink.generate({ input: { text: "Generate image" }, provider: "vertex", model: "gemini-2.5-flash-image", // Uses regional endpoint region: "us-east5", }); ``` #### 4. Large Image Timeout **Symptom**: Generation times out for large/complex images. **Solution**: ```typescript const result = await neurolink.stream({ input: { text: "A detailed cityscape with many buildings" }, provider: "vertex", model: "gemini-2.5-flash-image", timeout: 60000, // Increase timeout to 60 seconds }); ``` #### 5. CLI Image Not Saved **Symptom**: CLI shows success but no file created. **Possible Causes**: - `imageOutput` option not passed to `processOptions()` - Directory permissions issue - Disk space full **Solution**: ```bash # Check default location ls -lh generated-images/ # Use custom path with explicit directory npx neurolink generate "test" \ --provider vertex \ --model gemini-2.5-flash-image \ --imageOutput ./my-images/test.png # Check file was created ls -lh ./my-images/test.png # Verify directory permissions ls -ld generated-images/ ``` ### Debug Mode Enable debug logging to troubleshoot issues: ```bash # Set environment variable export DEBUG=neurolink:* # Or use CLI flag npx neurolink generate "test image" \ --provider vertex \ --model gemini-2.5-flash-image \ --debug # Debug output will show: # - Provider selection # - Model configuration # - API request details # - Response parsing # - Image data extraction ``` ### Testing Image Generation Quick test to verify image generation works: ```bash # Test with default path npx neurolink generate "A simple red circle" \ --provider vertex \ --model gemini-2.5-flash-image # Expected output: # Generated image saved to: generated-images/image-2025-12-16T11-50-42-209Z.png # Image size: 234.56 KB # Generated image using gemini-2.5-flash-image (image/png) # Verify file exists ls -lh generated-images/image-*.png | tail -1 # Test with custom path npx neurolink generate "A simple blue square" \ --provider vertex \ --model gemini-2.5-flash-image \ --imageOutput ./test-output/square.png # Expected output: # Generated image saved to: ./test-output/square.png # Image size: 198.34 KB # Generated image using gemini-2.5-flash-image (image/png) # Verify file file ./test-output/square.png # Output: ./test-output/square.png: PNG image data, 1024 x 1024, 8-bit/color RGB ``` --- ## Best Practices ### 1. Always Check for Image Chunks ```typescript let hasImage = false; for await (const chunk of result.stream) { if ("type" in chunk && chunk.type === "image") { hasImage = true; // Process image } } if (!hasImage) { console.warn("No image was generated"); } ``` ### 2. Validate Base64 Data ```typescript if (chunk.type === "image") { const base64 = chunk.imageOutput.base64; // Validate it's valid base64 (padding '=' only at end, max 2 chars) if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64)) { throw new Error("Invalid base64 data"); } // Validate minimum size (e.g., 1KB) if (base64.length 30000) { console.warn("Image generation took longer than 30 seconds"); } } ``` --- ## Conclusion NeuroLink's image generation streaming provides a unified interface for both text and image generation. The fake streaming approach ensures consistency while maintaining the benefits of streaming APIs. By following the patterns and examples in this guide, you can effectively integrate image generation into your applications. For more information: - [API Reference](/docs/sdk/api-reference) - [Provider Comparison](/docs/reference/provider-comparison) - [Provider Status Monitoring](/docs/observability/provider-status) --- ## Interactive CLI - Your AI Development Environment # Interactive CLI: Your AI Development Environment > **Since**: v7.0.0 | **Status**: Production Ready | **Availability**: CLI ## Why Interactive Mode? NeuroLink's Interactive CLI transforms traditional command-line usage into a persistent development environment optimized for AI workflow iteration. Unlike standard CLIs where each command is isolated, Interactive Mode maintains session state, conversation memory, and configuration across all operations - enabling rapid experimentation, debugging, and production runbook execution. ### Traditional CLI vs Interactive Mode | Feature | Traditional CLI | NeuroLink Interactive | Productivity Impact | | ------------------- | ------------------------------ | ------------------------------------- | -------------------------------- | | **Session State** | None - lost after each command | Full persistence across session | 10x faster parameter tuning | | **Memory** | No context between commands | Conversation-aware with history | 5x reduction in repeated context | | **Configuration** | Flags required per command | `/set` persists across entire session | 80% fewer keystrokes | | **Tool Testing** | Manual per-tool invocation | Live discovery & testing with `/mcp` | 3x faster integration testing | | **Streaming** | Optional per command | Real-time default with progress bars | Immediate feedback | | **Error Recovery** | Start over from scratch | Session preserved, fix and retry | 90% time saved on errors | | **Workflow Replay** | Copy-paste commands | Export/import full sessions | Reproducible workflows | **Measured productivity gains:** - 80% faster onboarding for new users - 60% fewer configuration errors - 3-5x faster prompt engineering iteration - Universal accessibility from beginner to expert ## Loop Mode Deep Dive ### Session Variables Configure once, use throughout your session: #### Setting Variables ```bash neurolink > /set provider anthropic ✅ provider set to anthropic neurolink > /set model claude-3-opus ✅ model set to claude-3-opus neurolink > /set temperature 0.3 ✅ temperature set to 0.3 neurolink > /set thinking-level high ✅ thinking-level set to high neurolink > /set max-tokens 4000 ✅ max-tokens set to 4000 ``` #### Getting Current Values ```bash neurolink > /get provider provider: anthropic neurolink > /get all Current Session Configuration: ├── provider: anthropic ├── model: claude-3-opus ├── temperature: 0.3 ├── thinking-level: high ├── max-tokens: 4000 └── conversation-memory: enabled ``` #### Unsetting Variables ```bash neurolink > /unset temperature ✅ temperature unset (reverting to default: 0.7) neurolink > /clear ⚠️ Clear all session variables? (y/n): y ✅ All session variables cleared ``` ### Conversation Memory #### How Memory Works Interactive mode maintains conversation context automatically: ```bash neurolink > My name is Alice and I work on the backend team Nice to meet you, Alice! As a backend developer, you might be interested in... neurolink > What's my name? Your name is Alice, and you mentioned you work on the backend team. neurolink > /history Conversation History (4 messages): 1. USER: My name is Alice and I work on the backend team 2. ASSISTANT: Nice to meet you, Alice! As a backend developer... 3. USER: What's my name? 4. ASSISTANT: Your name is Alice, and you mentioned you work on the backend team. neurolink > /clear ⚠️ This will clear conversation history but preserve session variables. Continue? (y/n): y ✅ Conversation history cleared Session variables (provider, model, etc.) preserved ``` #### Memory Persistence (Redis) With Redis enabled, conversations persist across sessions: ```bash # Session 1 neurolink > I'm debugging the authentication service I can help with that. What specific issue are you seeing? neurolink > exit Session saved to Redis # Later - Session 2 (same session ID) npx @juspay/neurolink loop --session sess_abc123 neurolink > What was I working on? You were debugging the authentication service. Have you made progress? ``` ### Provider Switching Switch providers mid-session to compare responses: ```bash neurolink > /set provider openai ✅ provider set to openai neurolink > Explain quantum computing [OpenAI GPT-4 response] neurolink > /set provider anthropic ✅ provider set to anthropic neurolink > Explain quantum computing [Anthropic Claude response] neurolink > /set provider google-ai ✅ provider set to google-ai neurolink > Explain quantum computing [Google Gemini response] ``` ### Model Experimentation A/B test different models in the same session: ```bash # Test different models on same prompt neurolink > /set provider anthropic neurolink > /set model claude-3-haiku neurolink > Write a haiku about coding [Haiku response - fast, concise] neurolink > /set model claude-3-sonnet neurolink > Write a haiku about coding [Sonnet response - balanced] neurolink > /set model claude-3-opus neurolink > Write a haiku about coding [Opus response - creative, detailed] # Compare thinking levels neurolink > /set thinking-level minimal neurolink > Solve this logic puzzle: ... [Quick response] neurolink > /set thinking-level high neurolink > Solve this logic puzzle: ... [Deep reasoning response with extended thinking] ``` --- ## Command Reference ### Session Management | Command | Description | Example | | ------------------------- | ----------------------------------------------- | --------------------------- | | `/set ` | Set session variable (persists across commands) | `/set provider anthropic` | | `/get ` | Get current value of variable | `/get temperature` | | `/get all` | Show all session variables | `/get all` | | `/unset ` | Remove session variable (revert to default) | `/unset temperature` | | `/show` | Alias for `/get all` | `/show` | | `/clear` | Clear conversation history (keeps variables) | `/clear` | | `/reset` | Reset everything (history + variables) | `/reset` | | `/history` | View conversation history | `/history` | | `/history ` | View last N messages | `/history 10` | | `/export ` | Export session (json, markdown, text) | `/export json session.json` | | `/import ` | Import previous session | `/import session.json` | | `exit` / `quit` / `:q` | Exit loop mode | `exit` | #### Available Session Variables | Variable | Type | Example | Description | | ---------------- | ------- | --------------- | -------------------------- | | `provider` | string | `anthropic` | AI provider to use | | `model` | string | `claude-3-opus` | Specific model | | `temperature` | number | `0.7` | Creativity level (0-1) | | `max-tokens` | number | `4000` | Maximum response length | | `thinking-level` | string | `high` | Extended thinking mode | | `streaming` | boolean | `true` | Enable streaming responses | | `tools` | boolean | `true` | Enable MCP tool usage | ### MCP Tools Commands | Command | Description | Example | | --------------------------- | ---------------------------------------- | ---------------------------------------------------------- | | `/mcp discover` | List all available MCP servers and tools | `/mcp discover` | | `/mcp list` | Alias for discover | `/mcp list` | | `/mcp test ` | Test connectivity to MCP server | `/mcp test github` | | `/mcp add ` | Add MCP server to session | `/mcp add myserver "npx my-mcp-server"` | | `/mcp remove ` | Remove MCP server | `/mcp remove myserver` | | `/mcp status` | Show status of all servers | `/mcp status` | | `/mcp exec ` | Manually execute a tool | `/mcp exec github create_issue --params '{"title":"Bug"}'` | ### HITL Commands | Command | Description | Example | | -------------------- | ----------------------- | -------------------------------------------- | | `/hitl status` | View pending approvals | `/hitl status` | | `/hitl approve ` | Approve pending action | `/hitl approve 1` | | `/hitl reject ` | Reject with reason | `/hitl reject 2 --reason "Security concern"` | | `/hitl history` | View approval history | `/hitl history --last 10` | | `/hitl config` | View HITL configuration | `/hitl config` | ### Help Commands | Command | Description | Example | | ----------------- | --------------------------- | ----------- | | `/help` | Show all available commands | `/help` | | `/help ` | Help for specific command | `/help set` | | `/?` | Alias for help | `/?` | --- ## Real-World Workflows ### Workflow 1: Development Iteration Complete session showing code generation, refinement, and testing: ````bash neurolink > /set provider anthropic neurolink > /set model claude-3-sonnet neurolink > /set temperature 0.3 # Lower temp for code # Initial generation neurolink > Create a TypeScript function to validate email addresses Here's an email validation function: ```typescript function validateEmail(email: string): boolean { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); } ```` neurolink > Add support for validating domains [AI remembers previous context, extends the function] ```typescript function validateEmail(email: string, allowedDomains?: string[]): boolean { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailRegex.test(email)) { return false; } if (allowedDomains) { const domain = email.split("@")[1]; return allowedDomains.includes(domain); } return true; } ``` neurolink > Add unit tests [AI remembers the function, generates tests] ```typescript describe("validateEmail", () => { it("should validate correct emails", () => { expect(validateEmail("user@example.com")).toBe(true); }); it("should reject invalid emails", () => { expect(validateEmail("invalid")).toBe(false); }); it("should validate against allowed domains", () => { expect(validateEmail("user@company.com", ["company.com"])).toBe(true); }); }); ``` neurolink > /export markdown code-session.md ✅ Exported to code-session.md ```` ### Workflow 2: Model Experimentation Comparing responses across providers and models: ```bash # Test prompt engineering across models PROMPT="Explain dependency injection in 50 words" neurolink > /set provider openai neurolink > /set model gpt-4-turbo neurolink > $PROMPT [GPT-4 Turbo response] Word count: 48 neurolink > /set provider anthropic neurolink > /set model claude-3-opus neurolink > $PROMPT [Claude Opus response] Word count: 52 neurolink > /set provider google-ai neurolink > /set model gemini-3-flash neurolink > $PROMPT [Gemini 3 Flash response] Word count: 47 # Compare thinking levels neurolink > /set thinking-level minimal neurolink > Solve: What is 15% of 280? 42 [instant] neurolink > /set thinking-level high neurolink > Solve: If a train leaves at 2pm going 60mph... [extended thinking visible] Thinking... analyzing problem structure Thinking... calculating distances Thinking... verifying solution Answer: [detailed solution with reasoning] neurolink > /export json model-comparison.json ```` ### Workflow 3: MCP Tool Testing Discovering, testing, and using MCP tools: ```bash neurolink > /mcp discover Available MCP Servers (8): ╔═══════════════╦═════════════╦══════════════╗ ║ Server ║ Status ║ Tools ║ ╠═══════════════╬═════════════╬══════════════╣ ║ filesystem ║ ✅ Active ║ 9 tools ║ ║ github ║ ✅ Active ║ 15 tools ║ ║ postgres ║ ❌ Inactive ║ 0 tools ║ ... neurolink > /mcp test postgres Testing MCP server: postgres ❌ Connection failed: ECONNREFUSED Fix: Set POSTGRES_CONNECTION_STRING environment variable export POSTGRES_CONNECTION_STRING="postgresql://user:pass@localhost:5432/db" neurolink > Great, let me fix that [sets env var externally] neurolink > /mcp test postgres ✅ Connection successful! 8 tools available: query, schema, tables, insert, update... neurolink > Use the GitHub tool to list my repositories Using tool: github_list_repos Found 23 repositories: 1. neurolink-examples (public) 2. ai-playground (private) 3. docs-site (public) ... neurolink > Create an issue in neurolink-examples titled "Add HITL example" Using tool: github_create_issue HITL Approval Required Action: github_create_issue Args: repo: neurolink-examples title: Add HITL example body: [AI-generated description] Approve? (y/n): y ✅ Issue created: neurolink-examples#42 https://github.com/user/neurolink-examples/issues/42 neurolink > /export json github-workflow.json ``` ### Workflow 4: Documentation Generation Using AI to generate docs with iterative refinement: ````bash neurolink > /set provider anthropic neurolink > /set temperature 0.5 neurolink > Read the file src/lib/neurolink.ts Using tool: readFile [File contents displayed] neurolink > Generate API documentation for the NeuroLink class # NeuroLink API Documentation ## Class: NeuroLink Main SDK class for interacting with AI providers... [Generated docs] neurolink > Add examples for each method [AI remembers the documentation, adds examples] ## Examples ### generate() ```typescript const result = await neurolink.generate({ input: { text: "Hello" } }); ```` ... neurolink > Save this to docs/api/neurolink.md Using tool: writeFile ✅ Saved to docs/api/neurolink.md neurolink > Now generate docs for the MessageBuilder class Reading src/lib/utils/messageBuilder.ts... [Continues documentation generation] neurolink > /export json doc-generation-session.json ```` --- ## Tips & Tricks ### Power User Features #### Keyboard Shortcuts - **↑ / ↓** - Navigate command history - **Tab** - Auto-complete commands and variables - **Ctrl+C** - Cancel current operation (doesn't exit) - **Ctrl+D** - Exit loop mode - **Ctrl+L** - Clear screen - **Ctrl+R** - Search command history #### Multi-line Input Use backslash continuation for multi-line prompts: ```bash neurolink > Write a function that: \ ... 1. Validates user input \ ... 2. Sanitizes the data \ ... 3. Returns typed result [AI processes full multi-line prompt] ```` Or use triple backticks for code blocks: ```bash neurolink > Review this code: ``` function process(data) { return data.map(x => x \* 2); } ``` [AI reviews the code block] ``` #### Command Aliases Create shortcuts for common operations: ```bash # In your shell profile (.bashrc, .zshrc) alias nlg="npx @juspay/neurolink loop --provider google-ai" alias nla="npx @juspay/neurolink loop --provider anthropic" alias nlo="npx @juspay/neurolink loop --provider openai" # Usage $ nlg # Starts loop with Google AI $ nla # Starts loop with Anthropic ``` ### Session Persistence #### Saving Sessions Explicit save to file: ```bash neurolink > /export json my-session.json ✅ Exported 15 messages to my-session.json # Session includes: # - All conversation history # - Session variables # - Tool usage logs # - Timestamps ``` #### Resuming Sessions ```bash # Resume from file npx @juspay/neurolink loop --session my-session.json # Resume from Redis (if enabled) npx @juspay/neurolink loop --session-id sess_abc123 ``` #### Sharing Sessions Share reproducible workflows with team: ```bash # Developer 1 neurolink > [Creates workflow] neurolink > /export json workflow.json # Developer 2 npx @juspay/neurolink loop --session workflow.json # Can replay exact same workflow ``` ### Integration with Scripts #### Piping Input ```bash # Pipe file contents to AI cat README.md | npx @juspay/neurolink generate "Summarize this:" # Process output from commands git diff | npx @juspay/neurolink generate "Review these changes" # Chain with other tools curl https://api.example.com/data | \ npx @juspay/neurolink generate "Analyze this JSON" ``` #### Non-Interactive Mode ```bash # Run single command and exit npx @juspay/neurolink generate "Hello" --provider anthropic --exit # Batch processing for file in *.md; do npx @juspay/neurolink generate "Summarize: $(cat $file)" \ --provider google-ai \ --output summary-$file done ``` #### CI/CD Usage ```bash # .github/workflows/ai-review.yml - name: AI Code Review run: | npx @juspay/neurolink loop --non-interactive /set provider anthropic Unknown command: /set ``` **Solution**: Ensure you're in loop mode: ```bash # Wrong - regular CLI npx @juspay/neurolink set provider anthropic # Right - loop mode npx @juspay/neurolink loop neurolink > /set provider anthropic ``` #### Issue: Conversation Memory Not Working **Symptom**: AI doesn't remember previous context **Solution**: ```bash # Check if memory is enabled neurolink > /get all ... conversation-memory: disabled # /get all # Memory disabled - enable it npx @juspay/neurolink loop --enable-conversation-memory # Now messages will be tracked for export ``` #### Issue: MCP Tools Not Showing **Symptom**: ```bash neurolink > /mcp discover No MCP servers found ``` **Solution**: ```bash # Install MCP servers first npx @juspay/neurolink mcp install filesystem npx @juspay/neurolink mcp install github # Verify in .mcp-config.json or configure manually ``` ### Debug Mode Enable verbose logging: ```bash # Via environment variable export NEUROLINK_DEBUG=true npx @juspay/neurolink loop # Via flag npx @juspay/neurolink loop --debug # Debug output shows: # - Session initialization # - Variable changes # - Provider selections # - Tool executions # - Memory operations ``` Example debug output: ``` [DEBUG] Initializing loop session [DEBUG] Session ID: sess_abc123 [DEBUG] Redis connection: redis://localhost:6379 (connected) [DEBUG] Conversation memory: enabled [DEBUG] Loading session variables... [DEBUG] Variable set: provider=google-ai [DEBUG] Provider initialized: GoogleAIStudioProvider [DEBUG] Model: gemini-3-flash-preview [DEBUG] MCP servers discovered: 5 [DEBUG] Tools available: 39 ``` --- ## See Also - [CLI Reference](/docs/cli/commands) - Complete CLI command documentation - [Loop Sessions Quick Guide](/docs/features/cli-loop-sessions) - Quick reference for loop mode - [MCP Integration](/docs/mcp/integration) - Deep dive into MCP tools - [Enterprise HITL](/docs/features/enterprise-hitl) - Using HITL in interactive sessions - [Conversation Memory](/docs/features/conversation-history) - Redis persistence configuration - [Provider Setup](/docs/getting-started/provider-setup) - Configure AI providers --- ## LiveKit Voice Agent — Real-Time Voice over WebRTC # LiveKit Voice Agent — Real-Time Voice over WebRTC **A WebRTC voice agent that uses LiveKit for the real-time media loop and NeuroLink as the brain (LLM, tools, memory).** ## Problem Statement & Solution ### The Challenge The original NeuroLink voice agent (see `voice-agent.md`) runs a browser-to-server loop over a **WebSocket**. That design works, but a WebSocket transport carries structural limits for real-time audio: - TCP head-of-line blocking and no jitter buffer cause choppy audio on lossy networks - no built-in acoustic echo cancellation — the assistant can be transcribed by its own mic input - raw PCM is ~8–10× the bandwidth of a compressed codec, and all of it flows through the application server - voice-activity detection runs on the application server's event loop, capping per-process concurrency - SvelteKit and similar frameworks cannot accept the WebSocket upgrade without a custom server entry ### The Solution The LiveKit voice agent moves the transport to **WebRTC via LiveKit**, while keeping **NeuroLink as the brain**. LiveKit (an open-source WebRTC platform with a managed cloud and a self-hostable server) provides the parts that are hard to build correctly: - WebRTC transport with echo cancellation, jitter buffering, packet-loss concealment, and Opus compression - voice-activity detection, turn detection, and interruption handling - a worker/job model that runs **each call in its own process** for isolation and horizontal scaling NeuroLink remains responsible for the conversation itself: - the LLM (any NeuroLink provider — Bedrock/Claude, OpenAI, Gemini, etc.) - tool calling (MCP and registered tools), decided and executed inside `neurolink.stream()` - conversation memory, keyed by a stable `conversationId` ### Key Benefits - **Production-grade real-time audio** without building media plumbing - **NeuroLink stays the brain** — `generate()`/`stream()`, tools, and memory are unchanged - **Worker-per-call scaling** provided by the LiveKit Agents runtime - **Cloud or self-hosted** with identical application code - **Provider-agnostic brain layer** that can later back other transports --- ## Architecture Overview ### System Flow Diagram ```text ┌─────────────────────────────────────────────────────────────┐ │ Browser (livekit-client) │ │ • Captures mic; WebRTC handles AEC, Opus, jitter │ │ • Plays assistant audio │ └────────────────────────┬────────────────────────────────────┘ │ WebRTC ▼ ┌─────────────────────────────────────────────────────────────┐ │ LiveKit Server (Cloud OR self-hosted) │ │ • Auto-creates the room on first join │ │ • Routes media via its SFU │ │ • Dispatches one Job per room to a registered worker │ └────────────────────────┬────────────────────────────────────┘ │ one Job per call (own process) ▼ ┌─────────────────────────────────────────────────────────────┐ │ Voice Agent Worker (@livekit/agents, Node) │ │ Silero VAD ─ turn detection / interruption │ │ STT plugin (Deepgram) ─ speech → text │ │ llmNode ──────────────► NeuroLink brain │ │ TTS plugin (ElevenLabs/Cartesia) ─ text → speech │ └────────────────────────┬────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ NeuroLink (the brain — runs inside llmNode) │ │ • neurolink.stream({ conversationId }) │ │ • history → NeuroLink memory (source of truth) │ │ • tools → MCP / registered tools, executed by NeuroLink │ │ • model → any NeuroLink provider │ └─────────────────────────────────────────────────────────────┘ ``` ### Division of Responsibility | Concern | Owner | | ------------------------------------------- | ----------------------------------- | | WebRTC transport, AEC, jitter, Opus | LiveKit | | VAD, turn detection, interruption | LiveKit Agents | | Worker-per-call process isolation & scaling | LiveKit Agents | | STT / TTS | LiveKit plugins (configurable) | | LLM, tool-calling, memory | NeuroLink | | Conversation history source of truth | NeuroLink memory (`conversationId`) | --- ## Deployment Topologies (Cloud & Self-Hosted) The application code is **identical** across topologies; only `LIVEKIT_URL` and credentials change. ### Topology A — LiveKit Cloud (managed) ```text Browser ──► LiveKit Cloud (rooms + SFU on LiveKit's servers) Voice Agent Worker (your infra) ──outbound──► LiveKit Cloud (registers; Cloud dispatches Jobs) Token endpoint (your app) mints join tokens with the Cloud API key/secret ``` - Rooms are created automatically on LiveKit's servers on first join. - The worker connects **outbound** to Cloud and receives dispatched Jobs over that connection — no inbound exposure or tunneling is required, even in local development. - Billing is per participant-minute (a free Build tier is suitable for development). - **Use when:** fastest setup, minimal media ops, dev/staging, or production without running media infrastructure. ### Topology B — Self-Hosted LiveKit (in-house) ```text Browser ──► your LiveKit server (rooms + SFU on your infrastructure) Voice Agent Worker (your infra) ──► your LiveKit server Token endpoint (your app) mints join tokens with your server's API key/secret ``` - The `livekit-server` (open source) runs on your own infrastructure (for example, Kubernetes behind your ingress/service mesh). - Media stays inside your network; there is **no per-minute media fee** — you pay only for compute and bandwidth. - **Use when:** cost control at scale, data-residency/compliance requirements, or full control over the media path. ### Local Development - **Console mode:** the worker runs standalone using the host machine's microphone and speakers — **no LiveKit server and no browser required**. Best for iterating on the brain loop. - **Local server:** `livekit-server --dev` (placeholder credentials, no external dependencies) with the browser and worker on `localhost`. - **Cloud from local:** point local `LIVEKIT_URL` at a Cloud project. Because the worker connects outbound, Cloud can dispatch Jobs to a locally-running worker without tunneling. --- ## Core Components ### 1. LiveKit Agents Worker A long-lived Node process built on `@livekit/agents`. It registers with the LiveKit server under an `agentName` (for example, `neurolink-voice`). For each room, LiveKit dispatches a **Job**, which the runtime runs in its **own process** — this is the worker-per-call isolation that bounds the blast radius of a crash and enables linear scaling by adding worker replicas. ### 2. Voice Activity Detection & Turn Detection Provided by the LiveKit Agents `AgentSession` using the Silero VAD plugin plus the framework's turn-detection and interruption logic. This replaces the hand-built VAD/turn/barge-in logic of the WebSocket voice agent. ### 3. Speech-to-Text / Text-to-Speech LiveKit handles the audio transport and turn-taking, but does **not** perform STT or TTS itself — those are pluggable provider modules, each its own `@livekit/agents-plugin-` package configured with that provider's API key (via environment). Selected through the `stt` / `tts` fields of the agent config. Available providers (Node SDK, `@livekit/agents-plugin-*` @ 1.4.x): | Capability | Providers | | ---------- | --------------------------------------------------------------------------------------------------------- | | **STT** | Deepgram · OpenAI (Whisper) · Google · AssemblyAI · Cartesia · Sarvam · Baseten | | **TTS** | ElevenLabs · Cartesia · OpenAI · Google · Rime · Neuphonic · Resemble · Inworld · Hume · Sarvam · Baseten | | **VAD** | Silero | `google` provides both STT and TTS, so a Google/Vertex deployment can use it for speech on both sides while NeuroLink (Vertex) serves as the brain — without adding a separate STT/TTS vendor. > The integration wires provider plugins on demand in `voiceAgent.ts` > (`buildStt`/`buildTts`). Adding a provider from the list above is a small, > isolated change in those two functions. ### 4. NeuroLink Brain (`llmNode`) The `llmNode` is the seam between LiveKit and NeuroLink. It extracts the latest user utterance, calls `neurolink.stream()` with a stable `conversationId`, and returns the token stream as `ReadableStream`. Conversation history is **not** taken from LiveKit's `ChatContext`; NeuroLink's memory is the source of truth. ### 5. Token Endpoint A plain HTTP endpoint in the host application that mints a LiveKit join token (`livekit-server-sdk`) for an authenticated user. Because WebRTC needs only this single HTTP call, frameworks that cannot accept a WebSocket upgrade (such as SvelteKit) integrate without a custom server entry. ### 6. Browser Client The host application's frontend uses `livekit-client` to join the room, publish the microphone, and play the agent's audio. The browser handles capture, AEC, and playback natively through WebRTC. --- ## How NeuroLink Owns the Brain This integration is deliberately structured so NeuroLink retains its generic control surface. ### History The `llmNode` ignores LiveKit's accumulated `ChatContext` for generation and instead passes a stable `conversationId` to `neurolink.stream()`. NeuroLink's memory layer loads and persists history under that id, making NeuroLink the single source of truth for conversation state. LiveKit still maintains its own context internally for turn detection; the two do not conflict because LiveKit's turn detection is audio/transcript-driven. ### Tools Tools (MCP and registered tools) live on the NeuroLink instance. With tools enabled, NeuroLink runs the entire tool-calling loop inside `stream()` — the model selects a tool, NeuroLink executes it, feeds the result back, and continues. LiveKit performs **no** tool-calling. To make a merchant/MCP toolset available, have the `createNeuroLink` factory return an instance with those tools registered — it is invoked inside each job process to build the brain for that call. ### Model The model and provider are NeuroLink configuration (`provider`, `model`). Any NeuroLink provider is supported, including Bedrock/Claude. ### Interruption (barge-in) When LiveKit detects barge-in it cancels the in-flight `llmNode`. That cancellation must be propagated into `neurolink.stream()` via an abort signal so the in-flight LLM call **and any running tool call** stop promptly. ### Tool latency While a tool runs inside `stream()`, no audio is produced. To avoid dead air, instruct the model to speak a brief acknowledgment before tool use and/or emit a status event over a LiveKit data channel for the UI. --- ## Runtime Flow ### Normal Turn 1. Browser publishes microphone audio to the room (WebRTC). 2. LiveKit Agents detects the end of the user's turn (VAD + turn detection). 3. STT produces the transcript. 4. `llmNode` calls `neurolink.stream({ conversationId, input })`. 5. NeuroLink generates (running any tool calls internally) and streams tokens. 6. TTS converts tokens to audio; LiveKit plays it back in the room. 7. NeuroLink persists the turn to memory under `conversationId`. ### Barge-In / Abort 1. The assistant is speaking. 2. LiveKit detects user speech and cancels the current `llmNode`. 3. The abort signal cancels the in-flight `neurolink.stream()` (and any active tool). 4. The session yields to the user. --- ## Usage Example > The integration is exposed under `@juspay/neurolink/livekit`. ### Requirements The `@juspay/neurolink/livekit` entry **requires `@livekit/agents`**. Its functions take LiveKit's `JobContext` and run inside a worker where the SDK is installed, so its type declarations import types from `@livekit/agents`. `@livekit/agents`, the `@livekit/agents-plugin-*` packages and `@livekit/rtc-node` are `optionalDependencies` of `@juspay/neurolink`: a default `npm install` installs them, and `npm install --omit=optional` does not. - **Installed without optional dependencies.** Type-checking a file that imports `@juspay/neurolink/livekit` fails with `TS2307: Cannot find module '@livekit/agents'`. Install `@livekit/agents` in the project that uses this entry, or do not import the entry. The other entries of the package do not need it. - **`@types/node` range.** With `strict` on and `skipLibCheck` off, the LiveKit packages' own declarations compile cleanly on `@types/node` 22 and 24.19.2, the versions this was measured on. On `@types/node` 25 (25.9.9) and 26 (26.6.5) two third-party declarations fail: `node_modules/@livekit/agents/dist/worker.d.ts` (TS2344) and `node_modules/@livekit/rtc-node/dist/audio_stream.d.ts` (TS2416). They are not NeuroLink's files and NeuroLink cannot fix them; set `skipLibCheck: true`, or stay on `@types/node` 22 or 24.19.2, in the project that imports this entry. LiveKit runs each call as a Job in its **own child process** and re-imports the agent entry file there. Because a live object cannot cross that process boundary, the NeuroLink instance is built **inside each job process** via a `createNeuroLink` factory — not passed in from a parent. This is split into two files: the agent entry file (the default export) and a small launcher. ### 1. Define and launch the agent #### 1a. Agent entry file (default export) ```ts // voice-agent-entry.ts export default defineVoiceAgent({ // Built once per call, inside the job process (registers its own tools). createNeuroLink: async () => buildConfiguredNeuroLink(), provider: process.env.VOICE_LLM_PROVIDER ?? "bedrock", model: process.env.VOICE_LLM_MODEL ?? "claude-sonnet-4-6", systemPrompt: "You are a concise, helpful voice assistant. Keep replies short and spoken.", stt: { provider: "deepgram" }, tts: { provider: "elevenlabs" }, }); ``` `defineVoiceAgent` overrides the agent's `llmNode` so every turn calls `neurolink.stream()` with a per-room `conversationId` (NeuroLink owns history and tools), and wires abort-on-interrupt: when LiveKit cancels a turn the in-flight stream is aborted. #### 1b. Launcher ```ts // voice-agent-worker.ts — run as its own Node process await startVoiceAgentWorker({ agentFile: new URL("./voice-agent-entry.js", import.meta.url).pathname, agentName: "neurolink-voice", }); ``` `startVoiceAgentWorker` resolves LiveKit connection settings from the environment (`LIVEKIT_URL`/`LIVEKIT_API_KEY`/`LIVEKIT_API_SECRET`) and registers the worker; LiveKit dispatches one Job per room. ### 2. Mint a join token (host application, plain HTTP) ```ts export async function GET({ locals }) { const room = `voice-${locals.merchantId}-${crypto.randomUUID()}`; const token = await mintJoinToken({ identity: locals.userId, room, apiKey: process.env.LIVEKIT_API_KEY!, apiSecret: process.env.LIVEKIT_API_SECRET!, }); return Response.json({ token, url: process.env.LIVEKIT_URL, room }); } ``` ### 3. Join from the browser ```ts const { token, url } = await (await fetch("/api/voice/token")).json(); // Enable the browser's built-in WebRTC audio cleanup as capture defaults. These // are free, run client-side, and need no LiveKit Cloud: echo cancellation stops // the agent's own voice being re-captured, noise suppression removes steady // ambient noise, and auto gain normalizes mic level. const room = new Room({ audioCaptureDefaults: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, }, }); await room.connect(url, token); // room is auto-created on first join await room.localParticipant.setMicrophoneEnabled(true); // remote audio tracks (the agent's voice) play automatically ``` ### Lower-level alternative For full control, build the agent directly with `@livekit/agents` and supply a custom `llmNode` that calls `neurolink.stream()`. `startVoiceAgentWorker` is a convenience wrapper around that pattern. --- ## Source Layout ```text src/lib/voice/livekit/ ├── brain.ts # provider-agnostic: (transcript, conversationId, signal) → NeuroLink stream ├── voiceAgent.ts # @livekit/agents Agent + llmNode adapter + abort-on-interrupt ├── voiceAgentWorker.ts # startVoiceAgentWorker(): WorkerOptions, agentName, plugin wiring ├── tokens.ts # mintJoinToken() (livekit-server-sdk) ├── config.ts # env resolution (LiveKit, STT/TTS, model/provider) └── index.ts # public exports → @juspay/neurolink/livekit ``` - `brain.ts` is transport-agnostic and reusable by future transports (for example, Daily.co). - LiveKit packages are declared as optional/peer dependencies, mirroring how `@picovoice/cobra-node` is handled for the WebSocket voice agent. --- ## Configuration ### LiveKit (Cloud or self-hosted) ```env LIVEKIT_URL=wss://.livekit.cloud # or wss://livekit.internal (self-hosted) or ws://localhost:7880 (dev) LIVEKIT_API_KEY= LIVEKIT_API_SECRET= ``` ### STT / TTS plugins ```env DEEPGRAM_API_KEY= ELEVENLABS_API_KEY= # or CARTESIA_API_KEY ``` ### LLM (NeuroLink brain) ```env VOICE_LLM_PROVIDER=bedrock VOICE_LLM_MODEL=claude-sonnet-4-6 # plus the provider's own credentials (e.g. AWS credentials for Bedrock) ``` ### Turn detection & lifecycle (optional) ```env LIVEKIT_EOU_TURN_DETECTION=true # opt in to the semantic end-of-utterance model (English) LIVEKIT_EOU_UNLIKELY_THRESHOLD=0.15 # optional; lower = more patient, higher = responds sooner VOICE_INACTIVITY_TIMEOUT_MS=600000 # auto-shut down an idle call after this many ms (default 10 min; buildConfiguredNeuroLink(), stt: { provider: "deepgram" }, tts: { provider: "elevenlabs" }, vad: { activationThreshold: 0.6, // 0–1; "is this speech" cutoff. Higher = stricter. minSpeechDuration: 0.2, // seconds of speech before a turn STARTS. minSilenceDuration: 0.6, // seconds of silence before a turn ENDS. }, }); ``` | Field | Default | Raise it when… | | --------------------- | ------- | ---------------------------------------------------- | | `activationThreshold` | `0.6` | A noisy room triggers false turns (try `0.7`–`0.8`). | | `minSpeechDuration` | `0.2`s | Short clicks/taps start spurious turns. | | `minSilenceDuration` | `0.6`s | The agent cuts users off during natural pauses. | ### Semantic turn detection (end-of-utterance) **Why this exists.** VAD only hears _silence_ — it cannot tell the difference between "I'm finished" and a mid-thought pause. With VAD alone, a user who says "I'd like to book a flight to… London" gets cut off at the pause, the agent answers half a sentence, and the rest arrives as a second fragmented turn. Raising `minSilenceDuration` to compensate makes the agent feel sluggish on the turns that _are_ finished. Semantic turn detection breaks that trade-off. **What it does.** A small ML model (`@livekit/agents-plugin-livekit` `turnDetector.EnglishModel`) runs on top of VAD and scores how likely the user has actually finished speaking, using the words transcribed so far. If the user paused mid-thought, the agent keeps listening; if the utterance is grammatically and semantically complete, it responds immediately. The result is one clean turn per thought instead of one turn per pause. **How to enable it.** It is opt-in via environment variable: ```env LIVEKIT_EOU_TURN_DETECTION=true # enable the end-of-utterance model LIVEKIT_EOU_UNLIKELY_THRESHOLD=0.15 # optional; override the "not done yet" cutoff ``` `LIVEKIT_EOU_TURN_DETECTION` accepts any truthy value (`true`, `1`, `yes`, `on`). `LIVEKIT_EOU_UNLIKELY_THRESHOLD` tunes sensitivity: a probability below the cutoff means "the user is probably _not_ done," so the agent waits longer. Lower it to make the agent more patient (wait through more pauses); raise it to make the agent respond sooner. **Tuning the wait.** The `turn` config bounds how endpointing behaves once the model has an opinion: ```ts defineVoiceAgent({ // …stt / tts / createNeuroLink… turn: { mode: "stt", // turn-detection mode minEndpointingDelay: 500, // ms grace period after the model thinks the turn is done maxEndpointingDelay: 6000, // hard ceiling — never wait longer than this }, }); ``` - `minEndpointingDelay` is the grace period applied when the model decides the turn is complete — a small buffer so a quick continuation isn't clipped. - `maxEndpointingDelay` is a safety ceiling. Even if the model keeps believing the user might continue, the agent **never waits forever** — it responds once this ceiling is hit. **Cost & limits.** The English model adds roughly negligible latency, but non-negligible memory, so size your worker hosts accordingly. The model is **English-only**; the multilingual runner is intentionally not registered. For non-English calls, leave EOU disabled and rely on VAD endpointing. ### Interruption (barge-in) Controls what counts as the user interrupting the agent while it is speaking. Requiring real words and a minimum duration stops background noise from cutting the agent off mid-sentence. ```ts defineVoiceAgent({ // …stt / tts / createNeuroLink… interruption: { minWords: 2, // recognized words required to interrupt (default 2) minDuration: 600, // milliseconds of audio required to interrupt (default 600) }, }); ``` Set `minWords: 0` for instant barge-in on any sound — more responsive, but more false interruptions in noisy environments. ### Language & multilingual speech The `language` field on `stt` is a **soft hint**: it biases recognition toward a language without locking to it, so a user can switch languages mid-call and still be transcribed correctly. ```ts defineVoiceAgent({ // … stt: { provider: "soniox", language: "en", // soft hint only — multilingual auto-detect still applies }, }); ``` - Omit `language` for full auto-detection. - The hint only biases the first guess; it never forces the hinted language. (A strict lock causes the realtime stream to stall on other-language audio, so the integration intentionally keeps the hint soft.) ### Speech provider selection STT and TTS plugins are chosen per agent and configured by environment credentials. ```ts defineVoiceAgent({ // … stt: { provider: "soniox", model: "stt-rt-preview", language: "en" }, tts: { provider: "cartesia", voice: "", model: "sonic-3.6" }, }); ``` - **STT:** `soniox`, `deepgram`. **TTS:** `cartesia`, `elevenlabs`. - Only set `voice` / `model` if your account supports them; otherwise omit those fields to use the plugin's own defaults. --- ## Conversation Memory The agent remembers earlier turns automatically when the NeuroLink instance you build inside `createNeuroLink` has conversation memory enabled. History is the agent's source of truth — LiveKit's own transcript context is not used for generation. ```ts export default defineVoiceAgent({ createNeuroLink: async () => new NeuroLink({ conversationMemory: { enabled: true } }), stt: { provider: "deepgram" }, tts: { provider: "elevenlabs" }, }); ``` How it behaves: - **Keyed per call.** Each room/call is an isolated conversation; the id is derived from the room name. Override the prefix with `conversationIdPrefix` (default `"voice"`). - **In-memory by default; Redis for persistence.** Set `REDIS_URL` to use a shared store that survives worker restarts and is shared across worker replicas — important because each call runs in its own job process. - **Works across turns within the session.** The user can say "my name is Alex" and later ask "what's my name?" and the agent recalls it. > Memory persists only when the instance is configured with > `conversationMemory.enabled`. Without it, each turn is independent. ### Remembering a realtime call in the user's own conversation A speech-to-speech call (`defineRealtimeVoiceAgent`) never goes through `stream()` or `generate()`, so by default nothing it says is stored. Opt in with `memory` and the call's turns are written, through `NeuroLink.recordConversationTurn`, to the same conversation memory typed chat uses, appended to the conversation the person already has open. The model is also seeded with that conversation's recent history when the call starts, so it knows what was said before. ```ts export default defineRealtimeVoiceAgent({ memory: { // Same store, key prefix and lifetime as the web app's NeuroLink instance. createNeuroLink: async () => new NeuroLink({ conversationMemory: { enabled: true } }), }, }); ``` **Whose conversation is never taken from the client.** The host that creates the room signs a binding and puts it in the room metadata next to `authToken` and `mcpContext`. The worker stores nothing unless it verifies. ```ts const memory = signVoiceMemoryBinding({ room, // the LiveKit room name you create userId, // the verified session's user id, composed as chat composes it sessionId, // "voice-", or an existing conversation id (see below) secret: process.env.NEUROLINK_VOICE_MEMORY_SECRET!, }); const metadata = Buffer.from( JSON.stringify({ authToken, mcpContext, memory }), ).toString("base64"); ``` - The signature is `HMAC-SHA256` over `["neurolink.voice.memory.v1", room, userId, sessionId, exp]` (a JSON array, so no choice of values can make two bindings collide), `base64url`-encoded. It covers the room name, so a binding copied into another room does not verify. `exp` is Unix seconds; the default lifetime is two hours, the cap 24 hours. - The shared secret is at least 16 characters, read from `NEUROLINK_VOICE_MEMORY_SECRET` unless `memory.secret` is set on the worker. - `sessionId` matches `^[A-Za-z0-9_-]{1,128}$` (no `:`, which is part of the stored key). `userId` is 1 to 256 characters with no whitespace or control characters; `:` is allowed because chat user ids contain it. - **Fail closed.** No secret, no binding, a malformed or expired binding, or a bad signature: the call runs normally, nothing is stored, and a warning names the reason (never the ids). - A client may name the conversation to append to. The host accepts the name only when `neurolink.conversationExists({ sessionId, userId })` is true for the verified user. Otherwise it mints a new `voice-`. **What is stored.** Each finished exchange becomes a user message and an assistant message with the ids `${turnId}:user` and `${turnId}:assistant`, where `turnId` is the realtime session's assistant message id, and `metadata.modality: "voice"`. Recording the same `turnId` again is a no-op. Tool calls are stored as `tool:start` / `tool:end` events on the assistant message, with arguments and results bounded to 4000 characters. A reply cut off by the person speaking over it is stored as far as it got with `metadata.interrupted`. A call that ends mid-turn stores what was said plus a short note, with `metadata.interrupted` and `metadata.callEnded`; a user turn the call ended before answering gets the note alone as the reply. Typed chat turns are stored exactly as before. A message with no `modality` is a typed message. **Out-of-order transcripts.** The user's final transcript can arrive after the assistant has started or finished replying. A complete reply with no user text waits 1.5 seconds (`memory.settleMs`) for one; a reply that never gets one (the opening greeting) is not stored, because a stored turn needs both sides. **Not saved.** Writes are retried and run one at a time, in order. If a turn still cannot be stored, the call carries on, the data-channel event `{ type: "memory", data: { state: "not-saved", turnId } }` is published so a client can show a quiet note on that turn, and the turn is not retried again. The `done` event carries `turnId` while memory is on, so a client can merge its live copy of a turn with history instead of showing it twice. **Shutdown.** The flush is registered before the worker's process reaper and waits for pending writes for at most 800 ms (`memory.flushBudgetMs`); the reaper exits the process about a second after shutdown begins. **Cascaded agents** (`defineVoiceAgent`) already store through `stream()`. Setting `memory: {}` makes them read the same binding: a verified one replaces the static `userId` and the room-derived conversation id for that call, and the opening greeting is run without touching memory so it is not filed as something the person said. Every turn the brain streams is stamped `modality: "voice"`. Not covered here: titles and summaries are produced by background tasks that the worker exit can cut off, so a conversation created by a call may keep the title "New Conversation"; and a typed turn and a voice turn written to the same conversation at the same moment are not serialised against each other. --- ## Realtime Speech-to-Speech Backends (Gemini Live and xAI Grok Voice) `defineRealtimeVoiceAgent` runs one realtime model that does speech-to-text, reasoning, text-to-speech and turn detection over a single connection. Gemini Live on Vertex is the default. xAI's Grok Voice is a second backend, reached through LiveKit's xAI plugin. ### Status Run against the live xAI service on 2026-10-20 with synthetic speech (a text-to-speech voice, not a person), inside a recorded budget: 21 WebSocket sessions, about 95 seconds connected, under US$0.20. Plugin version 1.4.6. What that showed: - **It works through the plugin.** A greeting, a text turn, a spoken turn answered in voice, a function call with its continuation, a seeded history and two voices all completed with no error event. - **`grok-voice-3.0` is accepted and honoured:** `session.created` names it. - **First audio** arrived 985 ms after a text turn (counted from `response.create`) and 1,229 ms after a spoken turn (counted from `input_audio_buffer.speech_stopped`). One sample each, from one network location, so neither is a distribution. - **Price:** xAI's own pages list USD 0.08 per minute. That is a list price; no invoice was checked. - **Function calling works** for one function tool with a flat object schema. Tool names with underscores and the `$schema` and `additionalProperties` fields the sanitizer leaves in were accepted. - **The plugin's `session.update` layout is accepted** and its voice and turn-detection settings take effect. The service's echo of the turn detection leaves out `threshold` and `interrupt_response`; whether it ignores them was not measured. - **Seeded history is accepted:** a user and an assistant message sent before the first turn were used by the model. The same run found the differences from OpenAI that the sections below handle: repeated final transcripts, usage reported in another place, an unknown model or voice accepted without an error, and a wrong key that crashes the plugin's socket. It did **not** cover a full agent in a LiveKit room, interruption, or calls longer than a few seconds; see [Still unmeasured](#still-unmeasured). ### Choosing the backend ```env VOICE_REALTIME_BACKEND=xai # "gemini" (default) or "xai"; case-insensitive; blank means gemini XAI_API_KEY= # xai only; read by the LiveKit xAI plugin, shared with the xAI chat provider VOICE_LIVE_MODEL= # optional; see the defaults below VOICE_S2S_VOICE= # optional; blank leaves the plugin's own voice XAI_REALTIME_BASE_URL= # optional ws:// or wss:// URL; blank keeps the plugin's own endpoint XAI_REALTIME_ALLOW_INSECURE= # optional; "true" allows a ws:// base URL to a host other than loopback ``` | Variable | Backend | Meaning | | --------------------------------------------------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `VOICE_REALTIME_BACKEND` | both | `gemini` or `xai`. Any other value throws at startup, naming the variable and the two choices and repeating nothing from the environment. | | `VOICE_LIVE_MODEL` | both | Realtime model id. Default `gemini-live-2.5-flash` for gemini, `grok-voice-3.0` for xai. xAI does not reject an id it does not know: it runs a default model and says nothing, so a typo changes nothing. The xai backend logs a `realtime.xai.modelMismatch` warning when `session.created` names another model than the one asked for. | | `VOICE_S2S_VOICE` | both | Voice name. Voices differ between the two models: set it for the backend you chose, or leave it blank (the xAI plugin then uses `ara`). xAI does not reject a voice it does not know either, and nothing is logged for one; `GET https://api.x.ai/v1/tts/voices` (with the key as a Bearer token) lists the valid ids. | | `XAI_API_KEY` | xai | Required. Read by the plugin from the environment and shared with the xAI chat provider, which reads the same variable. Never part of the config object and never logged. | | `XAI_REALTIME_BASE_URL` | xai | `ws://` or `wss://` URL of the realtime endpoint, for a gateway or a test server. Unset keeps the plugin's own default, `wss://api.x.ai/v1`. A `ws://` URL is accepted only for `localhost`, an address in `127.0.0.0/8` or `[::1]`; to any other host it throws unless `XAI_REALTIME_ALLOW_INSECURE=true` is set. Anything else that is not a `ws://` or `wss://` URL throws too. Both errors are raised at startup and do not repeat the value. The URL is checked whatever the backend, so a bad value stops a gemini deployment too. A caller's `xaiBaseURL` gets the same checks. | | `XAI_REALTIME_ALLOW_INSECURE` | xai | Set to `true` to allow a `ws://` base URL (from `XAI_REALTIME_BASE_URL` or `xaiBaseURL`) to a host other than loopback. **With it set, `XAI_API_KEY` travels in cleartext to that host**, readable by anything on the path. Leave it unset unless the network between the worker and that host is one you control. Only `true` (any case) counts; any other value, or none, leaves the refusal in place. | | `VERTEX_PROJECT`, `VERTEX_LOCATION`, `VOICE_RESPONSE_MODALITY`, Google ADC fields | gemini | Gemini only. They are ignored for xai, and the xai logs do not print them. | `VOICE_LIVE_MODEL` is shared by both backends. If you switch the backend, change or unset it too, or the new backend is sent the other one's model id. The same choice can be made in code, which beats the environment (a value that is not `gemini` or `xai` throws, repeating nothing): ```ts export default defineRealtimeVoiceAgent({ backend: "xai", voice: "ara" }); ``` `createRealtimeLlm(config)` (exported from `@juspay/neurolink/livekit`) is the factory the agent uses. It returns the LiveKit realtime model for `config.backend` and imports the plugin dynamically, so the core package needs neither plugin unless the realtime agent runs. It takes a complete `RealtimeVoiceConfig` (build one with `resolveRealtimeVoiceConfig()`), throws when the xai backend is chosen and `XAI_API_KEY` is unset, throws when the xai backend is given an `xaiBaseURL` that is not a `ws://` or `wss://` URL or is a `ws://` URL to a host other than loopback without `XAI_REALTIME_ALLOW_INSECURE=true` (a hand-built config gets the same two refusals as config resolution, and the opt-in never admits a value that is not a ws or wss URL), and does **not** run the Vertex helpers (`ensureVertexAdc`, `clearGeminiApiKeyEnv`) for gemini: only the agent entry does, so a caller using the factory directly has to set up Google credentials itself. ### Dependencies The xai backend needs `@livekit/agents-plugin-xai` and `@livekit/agents-plugin-openai`. Both are optional dependencies of this package, so they are installed with its other optional dependencies (an install that omits optional dependencies has to add them by hand), and both resolved to 1.4.6 in its lockfile. The xAI plugin asks for `@livekit/agents` 1.4.6 exactly, which is why that package moved from 1.4.5 to 1.4.6 with it. The options the Gemini backend builds are unchanged by the move, but no live Gemini call was run after it. ### What the xai backend does The LiveKit xAI plugin extends the OpenAI realtime model. It connects to `/realtime?model=` with `Authorization: Bearer ` (the key is never put in the URL) and its first event is a `session.update` that carries the model, the voice, `output_modalities: ["audio"]`, server-side voice-activity detection (threshold 0.5, 300 ms prefix padding, 200 ms silence, response creation and interruption on). The plugin's default endpoint is `wss://api.x.ai/v1`. xAI documents a flatter layout than the plugin sends and accepts the plugin's anyway. Four places where the live service differs from what the plugin assumes, and what this package does about each: - **Input transcription is left out of the layout.** The plugin's default is `{ model: "gpt-4o-mini-transcribe" }`, an OpenAI model name. xAI accepts it, and then answers one spoken utterance with five `completed` transcripts of growing text (20, 36, 58, 58 and 58 characters for one 58-character sentence) plus three `updated` ones. Any `transcription` key does this, including xAI's own `grok-transcribe`. The plugin turns each `completed` event into a final user transcript, so the turn recorder stored 234 characters: the sentence repeated. The factory therefore builds the model with `inputAudioTranscription: undefined`, the one place it erases a plugin default on purpose; the plugin then sends no `transcription` key and xAI sends one `completed` transcript per utterance. Transcription itself stays on. - **Usage is in another place.** xAI sends the token counts at the top level of `response.done` and leaves `response.usage`, where the plugin reads, an empty object, so the plugin's own metrics are zero for every response. The xai model reads the top-level counts (and `response.usage` when the top level has none) and logs `realtime.usage` with the same six fields the Gemini backend logs. A response that reports nothing, such as a cancelled one, logs nothing. `billable_audio_seconds`, which xAI also reports, is not logged; see the price note below. - **An unknown model id or voice is accepted without an error.** A made-up model id connects and runs as `grok-voice-3.0`. So do the plugin's own default, `grok-voice-think-fast-1.0`, and the alias `grok-voice-latest`; `grok-voice-2.0` came back as itself. The xai model compares the model named in `session.created` with the one it asked for and logs a `realtime.xai.modelMismatch` warning when they differ. It does not fail the call, and an alias triggers it too. A made-up voice produced no error and a coarse pitch estimate matching the default voice `ara`; nothing is logged for one, so check ids against `GET https://api.x.ai/v1/tts/voices` (28 voices when measured). - **A wrong key is refused with HTTP 400, not 401,** at the WebSocket upgrade, and the plugin opens its socket with no `error` listener, so the refusal is an uncaught exception. See [Troubleshooting](#troubleshooting). NeuroLink defaults to `grok-voice-3.0`, the flagship id xAI's documentation lists (together with the alias `grok-voice-latest` and a deprecated `grok-voice-2.0`); the measurement above is why it stays the default. **A missing key stops the call before it connects.** If `XAI_API_KEY` is unset the plugin falls back to `OPENAI_API_KEY`, and a stub server showed that fallback sending the OpenAI key as the Bearer token to the configured xAI URL. (An empty value does not fall back: the plugin throws its own `OpenAI API key is required` error. A whitespace-only value is sent as the key.) NeuroLink therefore refuses an unset, empty or whitespace-only key: it throws `XAI_API_KEY is not set ...` when the agent starts and again in `createRealtimeLlm`, and no connection is made. ### How each part of the agent behaves on xai | Part | On xai | | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Vertex ADC and `GEMINI_API_KEY` clearing | Not run. The xai backend never touches the Gemini environment. | | Data-channel event bridge, HITL, room context | Unchanged. They work on the LiveKit room and the agent session, not on a model. | | Session events (user transcript, assistant text, turn done, usage) | Unchanged code, with one difference. The user transcript, assistant text and turn events reach the shapes the agent reads. Usage does not come through the plugin's metrics (they are zero on xai); the xai model logs `realtime.usage` itself and the agent skips the plugin's metrics for xai. | | MCP tool bridge and schema sanitizer | Unchanged. The sanitizer produces plain JSON Schema (the OpenAI-style API takes full JSON Schema), and the plugin forwards it as is. Keeping it is the safer choice: it drops `$ref` and unions that xAI has not been tried with. | | Conversation memory (recording and seeding) | Recording is shared by both backends. Each remembered turn is traced with the model id and the backend's provider: `vertex` for gemini, `xai` for xai. xAI accepted seeded history items in the live run (the model was driven directly, not in a room). | | `realtime.config` and `realtime.room.joined` logs | Name the backend. The Vertex project, location and modality are printed for gemini only; for xai the base URL is reduced to a yes/no. | xAI's list price for Grok Voice is USD 0.08 per minute (source: https://x.ai/news/grok-voice-3, and xAI's voice documentation, read 2026-10-20). That is xAI's figure, not something NeuroLink measured against an invoice. xAI reports `usage.billable_audio_seconds` on each `response.done`. In each of the four recorded sessions with more than one response it rose from one response to the next (for example 1, 3, 9, 11, 12), so it is a running total for the session and not a per-response figure: adding the values up over-counts. How it is computed was not established. ### Still unmeasured A full agent inside a LiveKit room: a `voice.AgentSession` with the event bridge, human confirmations and MCP tools going through the model (the model was driven directly, without a room). Interruption and truncation (`conversation.item.truncate`, `response.cancel`). Reconnection, the plugin's 20-minute session cap, idle timeouts and calls longer than a few seconds. Parallel and server-side tools, and tool schemas with `$ref` or unions (the sanitizer removes those). Latency beyond the two single samples above. Accuracy with human speech and accents. The real charge in xAI's console. The results above are for plugin 1.4.6, which predates later xAI-specific handling in newer plugin releases. ### Troubleshooting - `VOICE_REALTIME_BACKEND must be "gemini" or "xai"`: fix the value, or unset it for gemini. - `XAI_API_KEY is not set`: set it in the worker's environment. The check also rejects a whitespace-only value. - `XAI_REALTIME_BASE_URL must be a ws:// or wss:// URL` (or the same for `xaiBaseURL`): use a WebSocket URL, not an `https://` one. - `XAI_REALTIME_BASE_URL is a ws:// URL to a host other than localhost, ...` (or the same for `xaiBaseURL`): the URL would send `XAI_API_KEY` unencrypted to a host that is not loopback. Use a `wss://` URL. Only if the path to that host is one you trust, set `XAI_REALTIME_ALLOW_INSECURE=true`, knowing the key then travels in cleartext. - A call that will not start on the xai backend: confirm that `VOICE_LIVE_MODEL` and `VOICE_S2S_VOICE` hold xAI values and not leftover Gemini ones, since both variables are shared. - `xAI refused the realtime connection with HTTP 400` (in the log as `realtime.xai.connectRefused`), or `Unexpected server response: 400` in a stack trace: a wrong, revoked or expired `XAI_API_KEY`. xAI answers a wrong key with HTTP 400 at the WebSocket upgrade, not 401. The plugin opens its socket with no `error` listener, so the refusal is an uncaught exception, and a Node process with no handler for it exits with code 1. This package cannot stop that. What it does before the exception takes effect is log the classified error and emit it as an unrecoverable `error` on the model session; the LiveKit agent session forwards that to the handler the agent entry already has, which logs `realtime.session.error` and publishes `status: error` (read from the LiveKit source; not run inside a room). With `installVoiceWorkerProcessGuards()` installed in the process, the exception is logged and a job child exits one second later instead. Only the connection attempt is covered, and every session still connecting in the process is told, because the crash carries no socket and ends the process for all of them: a crash after the connection is made is left to the process, and the real fix is an `error` listener in the plugin's socket code. - A `realtime.xai.modelMismatch` warning: `VOICE_LIVE_MODEL` names an id xAI does not run (a typo, or a retired id), or an alias such as `grok-voice-latest`. The call goes on with the model named in `served`. --- ## Implementation Plan The integration is built and validated in phases. Each phase is independently testable. ### Phase 0 — Console-mode spike (no infrastructure) Build a minimal agent (Silero VAD + Deepgram STT + ElevenLabs TTS + `llmNode` → `neurolink.stream()`) and run it in **console mode** using the host machine's mic/speakers. Validates the NeuroLink brain loop, `conversationId` history, and a tool call — with no LiveKit server and no browser. Requires only STT/TTS and LLM credentials. ### Phase 1 — NeuroLink LiveKit module Implement `brain.ts`, `voiceAgent.ts`, `voiceAgentWorker.ts`, `tokens.ts`, `config.ts`; add the `@juspay/neurolink/livekit` export and optional/peer dependencies. The worker factory **accepts an external NeuroLink instance** so a host application's registered tools are available. Wire abort-on-interrupt. Verify build, type-check, and lint. ### Phase 2 — Host token endpoint + browser client Add the HTTP token endpoint and a browser page using `livekit-client`. Verify token issuance and room connection. ### Phase 3 — End-to-end (local or Cloud) Run the worker against `livekit-server --dev` or a Cloud Build-tier project; complete a full loop in the browser including barge-in, a tool call, and multi-turn memory. ### Phase 4 — Tool-call UX Add abort-on-interrupt verification (barge-in cancels an in-flight tool), tool-latency feedback (acknowledgment phrase and/or data-channel status event), and turn-detection tuning. ### Phase 5 — Production Deploy the worker as its own scalable Node deployment (separate from the web tier). Choose Cloud or self-hosted LiveKit. Validate concurrency and worker-restart isolation. --- ## Operational Behavior ### Scaling LiveKit Agents uses a Worker→Job model: a worker registers with the LiveKit server and is dispatched one **Job per room**, each Job running in its **own process**. Scale by adding worker replicas; a worker failure restarts affected Jobs on another worker without impacting others. ### Inactivity shutdown **Why this matters.** Every call runs in its **own process**, which holds real resources for the whole call: the STT/TTS connections, conversation memory, and — when semantic turn detection is on — the ~200 MB end-of-utterance model. If a caller walks away without hanging up, that process would otherwise linger indefinitely, holding RAM and (on LiveKit Cloud) continuing to bill per participant-minute. An inactivity watchdog reclaims those resources automatically. **What it does.** A timer tracks how long the call has been idle. Any real activity resets it — the user speaking, the agent speaking, or a new conversation item being added. If no activity occurs within the threshold, the watchdog calls the job's **graceful shutdown**, which tears down the process cleanly (the same path used when a call ends normally). **How to configure it.** ```env VOICE_INACTIVITY_TIMEOUT_MS=600000 # default 10 minutes; set <=0 to disable entirely ``` - Default is **10 minutes**. Lower it to reclaim resources faster on short-lived calls; raise it for workflows with long expected silences. - Set to `0` (or any non-positive value) to **disable** the watchdog — calls then end only on explicit hang-up or transport disconnect. ### Cloud vs Self-Hosted Cost - **Cloud:** per participant-minute (a call has two participants — the user and the agent). A free Build tier covers development. - **Self-hosted:** no per-minute media fee; cost is the compute and bandwidth of running `livekit-server` and workers on your infrastructure. ### Why the brain layer is transport-agnostic `brain.ts` exposes a small surface — given a transcript, a `conversationId`, and an abort signal, it returns a NeuroLink stream. This keeps the NeuroLink integration reusable if an alternative transport is added later. --- ## Error Handling & Troubleshooting ### Worker not receiving Jobs - Confirm the worker registered with the correct `LIVEKIT_URL` and `agentName`. - For Cloud, confirm the worker process is running and its outbound connection is established (no inbound exposure is required). ### No assistant audio - Verify STT/TTS plugin credentials. - Check that the TTS plugin is producing frames for the room. ### Assistant talks over the user / does not stop on interruption - Verify abort-on-interrupt is wired: LiveKit's cancellation must abort the in-flight `neurolink.stream()` (and any active tool). ### Long silence during tool calls - Expected while a tool runs inside `stream()`. Add an acknowledgment phrase and/or a data-channel status event. ### Tools not available in voice - Ensure the `createNeuroLink` factory returns an instance with tools registered, and that tools are not disabled. --- ## Extensibility Roadmap 1. **Additional transport providers** — back the same `brain.ts` with another WebRTC provider (for example, Daily.co). Note that some providers' server-side agent paths are not Node-native. 2. **Human-in-the-loop (HITL)** — voice-native confirmation, or route NeuroLink HITL approvals over a LiveKit data channel with matching abort handling. 3. **Tool-call UI events** — emit structured tool start/result events to the client for live status display. 4. **Voice personalization** — selectable voices, language presets, speaking-style controls. 5. **Pluggable STT/TTS through NeuroLink** — use NeuroLink's own STT/TTS providers via custom nodes instead of LiveKit plugins. --- ## MCP Enhancement Architecture Diagrams # MCP Enhancement Architecture Diagrams Visual guides for understanding the MCP enhancement architecture, data flows, and component interactions. > **Main documentation**: For API reference, configuration options, and code examples, see [MCP Enhancements](/docs/features/mcp-enhancements). ## Overall Architecture The MCP enhancement system is organized into five layers, each serving a distinct role in tool management, routing, and execution across multiple MCP servers. ```mermaid graph TD subgraph "Integration Layer" AE[Agent Exposure] TI[Tool Integration] end subgraph "Discovery Layer" ETD[Enhanced Tool Discovery] MRC[MCP Registry Client] end subgraph "Server Layer" MSB[MCP Server Base] MSM[Multi-Server Manager] SC[Server Capabilities] end subgraph "Protocol Layer" EM[Elicitation Manager] TA[Tool Annotations] TC[Tool Converter] EP[Elicitation Protocol] end subgraph "Core Layer" TR[Tool Router] TCA[Tool Cache] RB[Request Batcher] end AE --> ETD TI --> TR TI --> TCA TI --> RB ETD --> MSM ETD --> MRC MRC --> SC MSM --> TR MSM --> MSB MSB --> SC TR --> TA TR --> TC EM --> EP TR --> TCA TR --> RB ``` ## Tool Router Flow The Tool Router selects the best server for each tool call using a multi-step decision process. It checks session affinity first, then narrows candidates by category and annotation, and finally applies the configured strategy. ```mermaid flowchart TD A[Tool Call Arrives] --> B{Affinity Enabled?} B -- Yes --> C{Session/User\nAffinity Match?} B -- No --> E C -- Match Found --> D{Server Healthy?} C -- No Match --> E D -- Healthy --> Z[Return Affinity Server] D -- Unhealthy --> E[Get Candidate Servers] E --> F{Tool Has\nSpecific Server?} F -- Yes --> G{Server Healthy?} F -- No --> H{Tool Has Category?} G -- Healthy --> Z2[Use Specific Server] G -- Unhealthy --> H H -- Yes --> I[Filter by Category Mapping] H -- No --> J[Filter by Annotations] I --> K{Candidates Found?} K -- Yes --> L K -- No --> J J --> L[Apply Routing Strategy] L --> M{Strategy Type} M -- Round-Robin --> N[Select Next in Rotation] M -- Least-Loaded --> O[Select Server with\nLowest Active Load] M -- Capability-Based --> P[Score by Weight\nand Category Match] M -- Priority --> Q[Select Highest\nWeight Server] M -- Random --> R[Random Selection] N --> S[Set Affinity if Enabled] O --> S P --> S Q --> S R --> S S --> T[Emit Route Decision Event] T --> U[Return Routing Decision] ``` ## Tool Cache Strategy The Tool Cache intercepts tool calls before execution. On a cache hit the stored result is returned immediately. On a miss the tool executes, and the result is stored. When the cache reaches capacity, the configured eviction strategy selects which entry to remove. ```mermaid flowchart TD A[Tool Call with Args] --> B[Generate Cache Key\nSHA-256 of tool + args] B --> C{Key in Cache?} C -- Yes --> D{Entry Expired?} C -- No --> H D -- Not Expired --> E[Update Access Metadata] D -- Expired --> F[Delete Expired Entry] F --> H E --> G[Return Cached Result] G --> G2[Emit Cache Hit Event] G2 --> DONE[Done] H[Cache Miss] --> H2[Emit Cache Miss Event] H2 --> I[Execute Tool Call] I --> J{Cache at\nMax Capacity?} J -- Yes --> K[Evict One Entry] J -- No --> L K --> K2{Eviction Strategy} K2 -- LRU --> K3[Remove Least\nRecently Accessed] K2 -- FIFO --> K4[Remove Oldest\nCreated Entry] K2 -- LFU --> K5[Remove Least\nFrequently Accessed] K3 --> L[Store Result in Cache] K4 --> L K5 --> L L --> M[Return Result] M --> DONE N[Auto-Cleanup Timer] -.-> O[Scan All Entries] O -.-> P[Delete Expired Entries] ``` ## Request Batcher Flow The Request Batcher collects individual tool calls into batches, groups them by server, and executes each group in parallel. Results are distributed back to the original callers through their individual promises. ```mermaid sequenceDiagram participant C1 as Caller 1 participant C2 as Caller 2 participant C3 as Caller 3 participant RB as Request Batcher participant Q as Batch Queue participant EX as Batch Executor participant S1 as Server A participant S2 as Server B C1->>RB: add("readFile", args, "serverA") RB->>Q: Queue request (1/10) RB-->>C1: Promise C2->>RB: add("writeFile", args, "serverA") RB->>Q: Queue request (2/10) RB-->>C2: Promise C3->>RB: add("query", args, "serverB") RB->>Q: Queue request (3/10) RB-->>C3: Promise Note over RB,Q: Batch threshold reached (size or timeout) RB->>Q: Select batch by server group Q-->>RB: Server A requests [C1, C2] RB->>EX: Execute batch (Server A) EX->>S1: readFile(args) EX->>S1: writeFile(args) S1-->>EX: [result1, result2] EX-->>RB: Batch results RB-->>C1: Resolve with result1 RB-->>C2: Resolve with result2 RB->>Q: Select next batch Q-->>RB: Server B requests [C3] RB->>EX: Execute batch (Server B) EX->>S2: query(args) S2-->>EX: [result3] EX-->>RB: Batch results RB-->>C3: Resolve with result3 ``` ## Elicitation Protocol The Elicitation Protocol enables MCP tools to request interactive user input mid-execution. This sequence shows how a tool pauses, requests confirmation or data from the user, and resumes once a response arrives. ```mermaid sequenceDiagram participant AI as AI Model participant NL as NeuroLink participant TL as Tool Execution participant EM as Elicitation Manager participant UI as User Interface participant U as User AI->>NL: Call tool "deleteFile" NL->>TL: Execute deleteFile(path) TL->>EM: confirm("Delete /data/report.csv?") EM->>EM: Create request (UUID) EM->>EM: Start timeout timer EM->>UI: Elicitation request (type: confirmation) UI->>U: "Delete /data/report.csv?" alt User Confirms U->>UI: Clicks "Confirm" UI->>EM: Response (value: true) EM->>EM: Clear timeout EM->>TL: ElicitationResponse (responded: true) TL->>TL: Proceed with deletion TL->>NL: Tool result (file deleted) else User Cancels U->>UI: Clicks "Cancel" UI->>EM: Response (value: false) EM->>TL: ElicitationResponse (responded: true, value: false) TL->>NL: Tool result (operation cancelled) else Timeout EM->>EM: Timeout fires EM->>TL: ElicitationResponse (timedOut: true) TL->>NL: Tool result (timed out, used default) end NL->>AI: Return tool result ``` ## Multi-Server Topology The Multi-Server Manager organizes MCP servers into groups, applies per-group load balancing strategies, and maintains health metrics for routing decisions. This diagram shows a typical deployment with server groups, health monitoring, and failover paths. ```mermaid graph TD subgraph "Multi-Server Manager" SM[Server Manager] HM[Health Monitor] LB[Load Balancer] TP[Tool Preferences] end subgraph "Group: Data Servers" direction LR DS1[db-server-1weight: 70] DS2[db-server-2weight: 30] end subgraph "Group: AI Servers" direction LR AS1[ai-primarypriority: 1] AS2[ai-secondarypriority: 2] AS3[ai-tertiarypriority: 3] end subgraph "Standalone Servers" direction LR GH[github-server] FS[filesystem-server] end SM --> |"round-robin"| DS1 SM --> |"round-robin"| DS2 SM --> |"failover-only"| AS1 SM -.-> |"failover"| AS2 SM -.-> |"failover"| AS3 SM --> GH SM --> FS HM --> |"health check"| DS1 HM --> |"health check"| DS2 HM --> |"health check"| AS1 HM --> |"health check"| AS2 HM --> |"health check"| AS3 HM --> |"health check"| GH HM --> |"health check"| FS LB --> |"strategy per group"| SM TP --> |"tool -> server"| SM DS1 --> |"tools: query, insert"| T1[Unified Tool List] DS2 --> |"tools: query, insert"| T1 AS1 --> |"tools: generate, embed"| T1 GH --> |"tools: createPR, listIssues"| T1 FS --> |"tools: readFile, writeFile"| T1 ``` --- ## MCP Enhancements # MCP Enhancements > **Since**: v9.16.0 | **Status**: Stable | **Availability**: SDK ## Overview The MCP Enhancements suite extends NeuroLink's Model Context Protocol integration with production-grade capabilities for managing tool calls at scale. These modules address the operational challenges of running multiple MCP servers in enterprise environments: - **Tool Router** -- Intelligent routing of tool calls across multiple servers with 6 strategies - **Tool Cache** -- High-performance result caching with LRU, FIFO, and LFU eviction - **Request Batcher** -- Automatic batching of tool calls for improved throughput - **Tool Annotations** -- Safety metadata and behavior hints for MCP tools - **Tool Converter** -- Bidirectional conversion between NeuroLink and MCP tool formats - **Tool Integration** -- Middleware chain for confirmation, retry, timeout, and logging - **Enhanced Tool Discovery** -- Advanced search and filtering across multi-server environments - **Elicitation Protocol** -- Interactive user input during tool execution (HITL) - **Multi-Server Manager** -- Load balancing and failover across server groups - **MCP Server Base** -- Abstract base class for building custom MCP servers - **Agent & Workflow Exposure** -- Expose agents and workflows as MCP tools - **Server Capabilities** -- Resource and prompt management per MCP spec - **MCP Registry Client** -- Discover servers from registries and well-known catalogs > **Architecture Diagrams**: For visual diagrams of the overall architecture, routing flows, caching strategies, batching sequences, elicitation protocol, and multi-server topology, see [MCP Enhancement Architecture Diagrams](/docs/features/mcp-enhancements-diagrams). ## Quick Start A complete, runnable example showing routing, caching, and batching working together: ```typescript ToolRouter, ToolCache, RequestBatcher, createAnnotatedTool, } from "@juspay/neurolink"; async function main() { // 1. Set up intelligent routing across servers const router = new ToolRouter({ strategy: "least-loaded", enableAffinity: true, categoryMapping: { database: ["db-server-1", "db-server-2"], ai: ["ai-server-primary"], }, }); router.registerServer("db-server-1", ["database"]); router.registerServer("db-server-2", ["database"]); router.registerServer("ai-server-primary", ["ai"]); // 2. Cache tool results to reduce redundant calls const cache = new ToolCache({ ttl: 60000, maxSize: 500, strategy: "lru", }); // 3. Create a tool with safety annotations const tool = createAnnotatedTool({ name: "queryUsers", description: "Query the users table", inputSchema: { type: "object", properties: { limit: { type: "number" } }, }, execute: async (params) => { return { users: ["Alice", "Bob"] }; }, }); // Annotations inferred: { readOnlyHint: true, idempotentHint: true } // 4. Route the tool call to the best server const decision = router.route( { name: "queryUsers", category: "database" }, { sessionId: "user-123" }, ); console.log(`Routed to: ${decision.serverId} (${decision.strategy})`); // 5. Execute with caching -- only calls the function on cache miss const result = await cache.getOrSet( ToolCache.generateKey("queryUsers", { limit: 10 }), async () => tool.execute!({ limit: 10 }), ); console.log("Result:", result); // 6. Set up batching for high-throughput scenarios const batcher = new RequestBatcher({ maxBatchSize: 10, maxWaitMs: 50, groupByServer: true, }); batcher.setExecutor(async (requests) => { return requests.map((r) => ({ success: true as const, result: { id: r.args.id, name: `User ${r.args.id}` }, })); }); // Batch multiple calls -- they execute together const [user1, user2] = await Promise.all([ batcher.add("getUser", { id: 1 }, "db-server-1"), batcher.add("getUser", { id: 2 }, "db-server-1"), ]); console.log("Batched results:", user1, user2); // Clean up cache.destroy(); batcher.destroy(); } main().catch(console.error); ``` --------------- | ---------------------------------------------- | ---------- | | `round-robin` | Distribute calls evenly across servers | 0.8 | | `least-loaded` | Route to server with fewest active connections | 0.9 | | `capability-based` | Score servers by capability match and weight | Variable | | `affinity` | Maintain session/user consistency | 1.0 | | `priority` | Route by server weight (higher = more traffic) | Variable | | `random` | Random selection for load distribution | 0.5 | ### Configuration ```typescript const config: ToolRouterConfig = { strategy: "least-loaded", enableAffinity: true, categoryMapping: { database: ["db-primary", "db-replica"], "file-system": ["fs-server"], }, serverWeights: [ { serverId: "db-primary", weight: 80, capabilities: ["database", "write"] }, { serverId: "db-replica", weight: 20, capabilities: ["database", "read"] }, ], fallbackStrategy: "round-robin", maxRetries: 3, healthCheckInterval: 30000, affinityTtl: 30 * 60 * 1000, // 30 minutes }; const router = new ToolRouter(config); ``` ### Usage ```typescript // Register servers router.registerServer("db-primary", ["database", "write"]); router.registerServer("db-replica", ["database", "read"]); // Route a tool call const decision = router.route( { name: "queryUsers", category: "database" }, { sessionId: "session-abc" }, ); // => { serverId: "db-primary", strategy: "least-loaded", confidence: 0.9, ... } // Update server load after execution router.updateServerLoad("db-primary", +1); // Request started router.updateServerLoad("db-primary", -1); // Request completed // Update health status router.updateHealthStatus("db-replica", false); // Mark unhealthy // Listen for events router.on("routeDecision", ({ toolName, decision }) => { console.log(`${toolName} -> ${decision.serverId}`); }); // Get routing statistics const stats = router.getStats(); // => { availableServers: 2, healthyServers: 1, activeAffinities: 1, serverLoads: {...} } ``` ### Annotation-Based Routing The router automatically considers tool annotations when selecting servers: - **Read-only tools** -- Routed to any healthy server - **Destructive tools** -- Routed only to primary servers (weight >= 50) - **Idempotent tools** -- Prefer servers in the "caching" category ```typescript const candidates = router.routeByAnnotation({ name: "deleteUser", annotations: { destructiveHint: true }, }); // Returns only high-weight primary servers ``` ### Default Configuration ```typescript // DEFAULT_ROUTER_CONFIG values: // { // strategy: "least-loaded", // enableAffinity: true, // maxRetries: 3, // healthCheckInterval: 30000, // 30 seconds // affinityTtl: 30 * 60 * 1000, // 30 minutes // } ``` ### Events `ToolRouter` extends `EventEmitter` and emits the following typed events (`ToolRouterEvents`): | Event | Payload | Fired When | | ----------------- | ---------------------------------------------------------------- | ---------------------------------------------------- | | `routeDecision` | `{ toolName: string, decision: RoutingDecision }` | A routing decision is made for a tool call | | `routeFailed` | `{ toolName: string, error: Error, attemptedServers: string[] }` | Routing fails after exhausting all candidate servers | | `affinitySet` | `{ key: string, serverId: string }` | A new session/user affinity rule is created | | `affinityExpired` | `{ key: string }` | An affinity rule expires (TTL exceeded) | | `healthUpdate` | `{ serverId: string, healthy: boolean }` | A server's health status changes | ```typescript router.on("routeDecision", ({ toolName, decision }) => { console.log(`${toolName} -> ${decision.serverId} (${decision.strategy})`); }); router.on("healthUpdate", ({ serverId, healthy }) => { console.log(`Server ${serverId} is now ${healthy ? "healthy" : "unhealthy"}`); }); ``` ### Additional Methods | Method | Description | | ----------------------------------------------- | ---------------------------------------------------- | | `registerServer(serverId, capabilities?)` | Register a server as available for routing | | `unregisterServer(serverId)` | Remove a server from routing | | `route(tool, context?)` | Route a tool call to the best server | | `routeByCategory(tool, category)` | Get healthy servers for a category | | `routeByAnnotation(tool)` | Get servers based on tool annotation hints | | `routeByCapability(tool, requiredCapabilities)` | Get servers matching all required capabilities | | `updateServerLoad(serverId, delta)` | Adjust server load counter (+1 on start, -1 on end) | | `updateHealthStatus(serverId, healthy)` | Update server health; emits `healthUpdate` on change | | `setAffinity(key, serverId)` | Manually set session/user affinity | | `clearAffinity(key)` | Remove an affinity rule | | `getStats()` | Get routing statistics (servers, loads, affinities) | | `destroy()` | Stop affinity cleanup timer and clear all rules | ### Key Types ```typescript RoutingStrategy, ToolRouterConfig, RoutingDecision, ServerWeight, CategoryMapping, AffinityRule, ToolRouterEvents, MCPTool, } from "@juspay/neurolink"; ``` --- ## Tool Cache High-performance caching for MCP tool results with multiple eviction strategies, pattern-based invalidation, and cache-aside support. ### Cache Strategies | Strategy | Description | Best For | | -------- | -------------------------------------- | ------------------------------- | | `lru` | Evicts least recently accessed entries | General use, temporal locality | | `fifo` | Evicts oldest entries first | Streaming data, time-sensitive | | `lfu` | Evicts least frequently used entries | Stable workloads, popular items | ### Configuration ```typescript const cache = new ToolCache({ ttl: 5 * 60 * 1000, // 5 minutes maxSize: 1000, strategy: "lru", enableAutoCleanup: true, cleanupInterval: 60000, namespace: "my-app", }); ``` ### Usage ```typescript // Basic set/get cache.set("getUserById:123", { id: 123, name: "Alice" }); const user = cache.get("getUserById:123"); // Cache-aside pattern (recommended) const result = await cache.getOrSet( "getUserById:456", async () => { return await fetchUser(456); // Only called on cache miss }, 30000, // Optional: custom TTL for this entry ); // Pattern-based invalidation (glob-style) cache.invalidate("getUserById:*"); // Invalidate all user cache entries // Generate cache keys from tool name + arguments const key = ToolCache.generateKey("queryDatabase", { table: "users", limit: 10, }); // Monitor cache performance const stats = cache.getStats(); // => { hits: 42, misses: 8, evictions: 3, size: 47, maxSize: 1000, hitRate: 0.84 } // Listen for cache events cache.on("hit", ({ key }) => console.log(`Cache hit: ${key}`)); cache.on("evict", ({ key, reason }) => console.log(`Evicted: ${key} (${reason})`), ); // Clean up cache.destroy(); ``` ### ToolResultCache A specialized wrapper that automatically generates cache keys from tool name and arguments: ```typescript const resultCache = new ToolResultCache({ ttl: 120000, strategy: "lfu", }); // Cache tool results directly resultCache.cacheResult("getUserById", { id: 123 }, { name: "Alice" }); const cached = resultCache.getCachedResult("getUserById", { id: 123 }); // Invalidate all results for a specific tool resultCache.invalidateTool("getUserById"); ``` ### Default Configuration ```typescript // DEFAULT_CACHE_CONFIG values: // { // ttl: 5 * 60 * 1000, // 5 minutes // maxSize: 1000, // strategy: "lru", // enableAutoCleanup: true, // cleanupInterval: 60000, // 1 minute // } ``` ### Events `ToolCache` extends `EventEmitter` and emits the following typed events (`CacheEvents`): | Event | Payload | Fired When | | ------- | -------------------------------------------------------------- | ------------------------------------------------------- | | `hit` | `{ key: string, value: unknown }` | A cache lookup finds a valid (non-expired) entry | | `miss` | `{ key: string }` | A cache lookup finds no entry or an expired entry | | `set` | `{ key: string, value: unknown, ttl: number }` | A new entry is stored in the cache | | `evict` | `{ key: string, reason: "expired" \| "capacity" \| "manual" }` | An entry is removed (expiry, capacity limit, or manual) | | `clear` | `{ entriesRemoved: number }` | All entries are cleared from the cache | ### CacheStats Fields The `getStats()` method returns a `CacheStats` object: | Field | Type | Description | | ----------- | -------- | ----------------------------------------------- | | `hits` | `number` | Total cache hits since creation or last reset | | `misses` | `number` | Total cache misses since creation or last reset | | `evictions` | `number` | Total evictions (expired + capacity + manual) | | `size` | `number` | Current number of entries in the cache | | `maxSize` | `number` | Maximum capacity from configuration | | `hitRate` | `number` | Hit rate (0-1): `hits / (hits + misses)` | ### Additional Methods | Method | Description | | ----------------------------------- | -------------------------------------------------------- | | `get(key)` | Get a value; returns `undefined` on miss or expiry | | `set(key, value, ttl?)` | Store a value with optional per-entry TTL override | | `has(key)` | Check if a key exists and is not expired | | `delete(key)` | Delete a specific key (emits `evict` with `"manual"`) | | `invalidate(pattern)` | Delete entries matching a glob pattern (e.g. `"user:*"`) | | `clear()` | Remove all entries | | `getOrSet(key, factory, ttl?)` | Cache-aside pattern: get or compute and cache | | `getStats()` | Get cache performance statistics | | `resetStats()` | Reset hit/miss/eviction counters | | `keys()` | Get all keys currently in the cache | | `size` | Property: current entry count | | `ToolCache.generateKey(name, args)` | Static: generate a deterministic cache key | | `destroy()` | Stop auto-cleanup timer and clear all entries | ### Key Types ```typescript CacheConfig, CacheStrategy, CacheStats, CacheEvents, } from "@juspay/neurolink"; ``` --- ## Request Batcher Automatic batching of MCP tool calls for improved throughput. Groups requests by server, flushes based on batch size or timeout, and executes batches in parallel. ### Configuration ```typescript const batcher = new RequestBatcher({ maxBatchSize: 10, // Flush when 10 requests are queued maxWaitMs: 100, // Or after 100ms, whichever comes first enableParallel: true, // Execute batch items in parallel maxConcurrentBatches: 5, // Maximum batches in flight groupByServer: true, // Group requests by server ID }); ``` ### Usage ```typescript // Set the batch executor batcher.setExecutor(async (requests) => { return Promise.all( requests.map(async (r) => { try { const result = await executeToolCall(r.tool, r.args, r.serverId); return { success: true, result }; } catch (error) { return { success: false, error }; } }), ); }); // Add requests -- they are batched and flushed automatically const [result1, result2, result3] = await Promise.all([ batcher.add("getUserById", { id: 1 }, "db-server"), batcher.add("getUserById", { id: 2 }, "db-server"), batcher.add("getOrder", { orderId: 99 }, "order-server"), ]); // Manual flush await batcher.flush(); // Wait for all pending requests await batcher.drain(); // Check status console.log(batcher.queueSize); // 0 console.log(batcher.isIdle); // true // Clean up batcher.destroy(); ``` ### ToolCallBatcher A higher-level wrapper designed specifically for MCP tool execution: ```typescript const toolBatcher = new ToolCallBatcher({ maxBatchSize: 5, maxWaitMs: 50 }); toolBatcher.setToolExecutor(async (tool, args, serverId) => { return await mcpClient.callTool(tool, args); }); const result = await toolBatcher.execute("readFile", { path: "/data.json" }); ``` ### Default Configuration ```typescript // DEFAULT_BATCH_CONFIG values: // { // maxBatchSize: 10, // maxWaitMs: 100, // 100 milliseconds // enableParallel: true, // maxConcurrentBatches: 5, // groupByServer: true, // } ``` ### Events `RequestBatcher` extends `EventEmitter` and emits the following typed events (`BatcherEvents`): | Event | Payload | Fired When | | ---------------- | ---------------------------------------------------------------- | --------------------------------------------------- | | `batchStarted` | `{ batchId: string, size: number }` | A batch begins execution | | `batchCompleted` | `{ batchId: string, results: BatchResult[] }` | A batch finishes executing all requests | | `batchFailed` | `{ batchId: string, error: Error }` | A batch-level failure rejects all its requests | | `requestQueued` | `{ requestId: string, queueSize: number }` | A new request is added to the queue | | `flushTriggered` | `{ reason: "size" \| "timeout" \| "manual", queueSize: number }` | A flush is triggered (batch full, timer, or manual) | ```typescript batcher.on("batchCompleted", ({ batchId, results }) => { const successes = results.filter((r) => r.success).length; console.log(`Batch ${batchId}: ${successes}/${results.length} succeeded`); }); ``` ### Additional Methods | Method | Description | | ---------------------------- | --------------------------------------------------------------- | | `setExecutor(fn)` | Set the batch executor function | | `add(tool, args, serverId?)` | Add a request to the queue; returns a Promise | | `flush()` | Manually flush the current batch | | `drain()` | Flush and wait for all active batches to complete (30s timeout) | | `queueSize` | Property: number of pending requests | | `activeBatchCount` | Property: number of batches currently in flight | | `isIdle` | Property: `true` when no pending requests and no active batches | | `destroy()` | Reject all pending requests and stop the batcher | ### Key Types ```typescript BatchConfig, BatchResult, BatchExecutor, BatcherEvents, } from "@juspay/neurolink"; ``` --- ## Tool Annotations Safety metadata and behavior hints for MCP tools, implementing the MCP 2024-11-05 specification. Annotations guide AI models and middleware on how to handle tool execution. ### Annotation Fields | Field | Type | Description | | ---------------------- | ---------- | -------------------------------------------------- | | `readOnlyHint` | `boolean` | Tool only reads data, no side effects | | `destructiveHint` | `boolean` | Tool performs destructive operations | | `idempotentHint` | `boolean` | Tool can be safely retried | | `requiresConfirmation` | `boolean` | Tool needs user confirmation before running | | `title` | `string` | Human-readable title | | `tags` | `string[]` | Custom tags for categorization | | `estimatedDuration` | `number` | Expected execution time in milliseconds | | `rateLimitHint` | `number` | Suggested calls per minute | | `costHint` | `number` | Relative cost (arbitrary units) | | `complexity` | `string` | `"simple"`, `"medium"`, or `"complex"` | | `securityLevel` | `string` | `"public"`, `"internal"`, or `"restricted"` | | `openWorldHint` | `boolean` | Tool may interact with external/open-world systems | | `auditRequired` | `boolean` | Tool execution should be audit-logged | ### Usage ```typescript createAnnotatedTool, inferAnnotations, getToolSafetyLevel, filterToolsByAnnotations, requiresConfirmation, isSafeToRetry, validateAnnotations, getAnnotationSummary, mergeAnnotations, } from "@juspay/neurolink"; // Create a tool with automatic annotation inference const tool = createAnnotatedTool({ name: "deleteUser", description: "Delete a user account permanently", inputSchema: { type: "object", properties: { userId: { type: "string" } }, required: ["userId"], }, execute: async (params) => { /* ... */ }, }); // Annotations inferred: { destructiveHint: true, requiresConfirmation: true, complexity: "simple" } // Check safety level getToolSafetyLevel(tool); // => "dangerous" // Check if confirmation is needed requiresConfirmation(tool); // => true // Check if safe to auto-retry on failure isSafeToRetry(tool); // => false // Get human-readable summary getAnnotationSummary(tool.annotations); // => "[DESTRUCTIVE | requires confirmation | simple complexity]" // Filter tools by annotation predicates const safeTools = filterToolsByAnnotations( allTools, (annotations) => annotations.readOnlyHint === true, ); // Validate annotations for conflicts const errors = validateAnnotations({ readOnlyHint: true, destructiveHint: true, // Conflict! }); // => ["Tool cannot be both readOnly and destructive - these are conflicting hints"] // Merge multiple annotation objects (arrays like tags are merged, not overwritten) const merged = mergeAnnotations( { readOnlyHint: true, tags: ["data"] }, { idempotentHint: true, tags: ["safe"] }, ); // => { readOnlyHint: true, idempotentHint: true, tags: ["data", "safe"] } ``` ### Inference Heuristics `inferAnnotations` analyzes tool names and descriptions to automatically assign hints: - **Read-only**: Names/descriptions containing `get`, `list`, `read`, `fetch`, `query`, `search`, `find` - **Destructive**: Names/descriptions containing `delete`, `remove`, `drop`, `destroy`, `clear`, `purge` - **Idempotent**: Names/descriptions containing `set`, `update`, `put`, `upsert`, `replace` - **Complexity**: Determined by keywords (`analyze`, `process`, `generate` = complex) and description length --- ## Tool Converter Bidirectional conversion between NeuroLink's internal tool format and the MCP protocol tool format, enabling interoperability with external MCP clients and servers. ### Conversion Functions ```typescript neuroLinkToolToMCP, mcpToolToNeuroLink, mcpProtocolToolToServerTool, serverToolToMCPProtocol, batchConvertToMCP, batchConvertToNeuroLink, createToolFromFunction, validateToolName, sanitizeToolName, } from "@juspay/neurolink"; // Convert NeuroLink tool to MCP format const mcpTool = neuroLinkToolToMCP(neuroLinkTool, { inferAnnotations: true, namespacePrefix: "myapp", preserveMetadata: true, }); // Convert MCP tool to NeuroLink format const nlTool = mcpToolToNeuroLink(mcpServerTool, { removeNamespacePrefix: "myapp", }); // Batch convert const mcpTools = batchConvertToMCP(neuroLinkTools); const nlTools = batchConvertToNeuroLink(mcpServerTools); // Create tool from a plain function const tool = createToolFromFunction( "calculateSum", "Calculate the sum of two numbers", async (params: { a: number; b: number }) => params.a + params.b, { parameters: { type: "object", properties: { a: { type: "number" }, b: { type: "number" }, }, required: ["a", "b"], }, }, ); // Validate and sanitize tool names const { valid, errors } = validateToolName("my-tool"); const safeName = sanitizeToolName("My Tool Name!"); // => "My_Tool_Name_" ``` ### Compatibility Matrix ```typescript console.log(TOOL_COMPATIBILITY.MCP_2024_11_05); // { annotations: true, inputSchema: true, outputSchema: false, ... } console.log(TOOL_COMPATIBILITY.NEUROLINK); // { annotations: true, inputSchema: true, outputSchema: true, categories: true, tags: true, ... } ``` ### Key Types ```typescript NeuroLinkTool, MCPProtocolTool, ToolConverterOptions, } from "@juspay/neurolink"; ``` --- ## Tool Integration & Middleware A middleware chain system for tool execution that integrates elicitation (interactive user input), confirmation flows, retry logic, timeouts, and logging. ### Built-in Middleware | Middleware | Description | | ------------------------- | --------------------------------------------------- | | `loggingMiddleware` | Logs tool execution start, duration, and errors | | `confirmationMiddleware` | Prompts user confirmation for destructive tools | | `validationMiddleware` | Validates required parameters, elicits missing ones | | `createTimeoutMiddleware` | Wraps execution with a timeout | | `createRetryMiddleware` | Retries failed calls for idempotent/read-only tools | ### Usage with ToolIntegrationManager ```typescript ToolIntegrationManager, loggingMiddleware, confirmationMiddleware, createTimeoutMiddleware, createRetryMiddleware, } from "@juspay/neurolink"; const manager = new ToolIntegrationManager(); // Set up elicitation handler (for interactive confirmation) manager.setElicitationHandler(async (request) => { if (request.type === "confirmation") { const confirmed = await promptUser(request.message); return { requestId: request.id, responded: true, value: confirmed, timestamp: Date.now(), }; } return { requestId: request.id, responded: false, timestamp: Date.now() }; }); // Add middleware chain manager .use(loggingMiddleware) .use(confirmationMiddleware) .use(createTimeoutMiddleware(30000)) .use(createRetryMiddleware(3, 1000)); // Register and execute tools manager.registerTool(myTool); const result = await manager.executeTool("myTool", { param: "value" }); ``` ### Custom Middleware ```typescript const metricsMiddleware: ToolMiddleware = async ( tool, params, context, next, ) => { const start = Date.now(); try { const result = await next(); recordMetric(tool.name, Date.now() - start, "success"); return result; } catch (error) { recordMetric(tool.name, Date.now() - start, "error"); throw error; } }; ``` ### Composable Middleware Chain ```typescript createToolMiddlewareChain, createElicitationContext, globalToolIntegrationManager, } from "@juspay/neurolink"; // Create a reusable middleware chain from an array of middlewares const chain = createToolMiddlewareChain([ loggingMiddleware, confirmationMiddleware, createTimeoutMiddleware(30000), ]); // Create elicitation context for middleware that needs interactive input const elicitationCtx = createElicitationContext(elicitationManager); // Use the pre-configured global singleton (has default middleware already wired) globalToolIntegrationManager.registerTool(myTool); const result = await globalToolIntegrationManager.executeTool("myTool", params); ``` | Export | Description | | ---------------------------------------- | ----------------------------------------- | | `createToolMiddlewareChain(middlewares)` | Create composable middleware chain | | `createElicitationContext(manager)` | Create elicitation context for middleware | | `globalToolIntegrationManager` | Pre-configured singleton instance | ### Wrapping Individual Tools ```typescript wrapToolWithElicitation, wrapToolsWithElicitation, } from "@juspay/neurolink"; const wrappedTool = wrapToolWithElicitation(tool, { autoConfirmDestructive: false, elicitationTimeout: 60000, enableLogging: true, }); // Batch wrap const wrappedTools = wrapToolsWithElicitation(tools); ``` ### Key Types ```typescript ToolMiddleware, EnhancedExecutionContext, ToolWrapperOptions, } from "@juspay/neurolink"; ``` --- ## Enhanced Tool Discovery Advanced tool search and filtering across multi-server environments with annotation awareness, category inference, compatibility checking, and safety-level grouping. ### Usage ```typescript const discovery = new EnhancedToolDiscovery(); // Discover tools from a server with automatic annotation inference const result = await discovery.discoverToolsWithAnnotations( "github-server", mcpClient, 10000, // timeout ); console.log(`Found ${result.toolCount} tools`); // Search with advanced criteria const searchResult = discovery.searchTools({ name: "file", category: "file-system", annotations: { readOnlyHint: true }, sortBy: "name", sortDirection: "asc", limit: 10, }); // Filter by safety level const safeTools = discovery.getToolsBySafetyLevel("safe"); const dangerousTools = discovery.getToolsBySafetyLevel("dangerous"); // Get tools that require confirmation const confirmationTools = discovery.getToolsRequiringConfirmation(); // Get tools for a specific server const serverTools = discovery.getServerTools("github-server"); // Check tool compatibility const compat = discovery.checkCompatibility("readFile", "fs-server", "2.0.0"); // => { compatible: true, issues: [], warnings: [], recommendations: [] } // Get comprehensive statistics const stats = discovery.getStatistics(); // => { totalTools, toolsByServer, toolsByCategory, toolsBySafetyLevel, ... } ``` ### Search Criteria ```typescript const criteria: ToolSearchCriteria = { name: "query", // Partial name match description: "database", // Keyword match in description serverIds: ["db-server-1"], // Filter by servers category: "database", // Filter by inferred category tags: ["sql"], // Filter by annotation tags annotations: { readOnlyHint: true }, // Filter by annotation flags includeUnavailable: false, // Exclude offline tools sortBy: "successRate", // Sort field sortDirection: "desc", // Sort direction limit: 20, // Max results }; ``` ### Events `EnhancedToolDiscovery` extends `EventEmitter` and emits the following events: | Event | Payload | Fired When | | -------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------- | | `toolDiscovered` | `{ serverId: string, toolName: string, annotations: MCPToolAnnotations, timestamp: Date }` | A tool is discovered from a server | | `annotationsUpdated` | `{ serverId: string, toolName: string, annotations: MCPToolAnnotations, timestamp: Date }` | Tool annotations are manually updated | ### Additional Methods | Method | Description | | ---------------------------------------------------------- | ---------------------------------------------------------------- | | `discoverToolsWithAnnotations(serverId, client, timeout?)` | Discover tools from a server with auto-inferred annotations | | `searchTools(criteria)` | Search tools with advanced filtering criteria | | `getToolsBySafetyLevel(level)` | Get tools by safety level: `"safe"`, `"moderate"`, `"dangerous"` | | `getToolsRequiringConfirmation()` | Get tools that require user confirmation | | `getReadOnlyTools()` | Get all read-only tools | | `checkCompatibility(toolName, serverId, targetVersion?)` | Check tool version and feature compatibility | | `getTool(serverId, toolName)` | Get a specific tool by server and name | | `getAllTools()` | Get all registered tools across all servers | | `getServerTools(serverId)` | Get all tools for a specific server | | `updateToolAnnotations(serverId, toolName, annotations)` | Update tool annotations manually | | `registerServer(server)` | Register a server with the internal multi-server manager | | `getUnifiedTools()` | Get unified tool list from all servers | | `getStatistics()` | Get comprehensive statistics by server, category, safety | ### Key Types ```typescript EnhancedToolInfo, ToolSearchCriteria, ToolSearchResult, CompatibilityCheckResult, } from "@juspay/neurolink"; ``` --- ## Elicitation Protocol The elicitation system enables MCP tools to request interactive user input mid-execution. This is critical for human-in-the-loop (HITL) workflows such as confirming destructive operations, requesting missing parameters, or handling authentication challenges. ### Elicitation Types | Type | Description | Response Type | | -------------- | ------------------------------- | ------------------------- | | `confirmation` | Yes/no confirmation dialog | `boolean` | | `text` | Free text input | `string` | | `select` | Single selection from options | `string` | | `multiselect` | Multiple selection from options | `string[]` | | `form` | Structured form with fields | `Record` | | `file` | File selection/upload | File reference | | `secret` | Sensitive input (passwords) | `string` | ### ElicitationManager ```typescript const manager = new ElicitationManager({ defaultTimeout: 60000, enabled: true, fallbackBehavior: "timeout", // "timeout" | "default" | "error" handler: async (request) => { // Implement your UI prompt based on request type switch (request.type) { case "confirmation": { const confirmed = await showConfirmDialog(request.message); return { requestId: request.id, responded: true, value: confirmed, timestamp: Date.now(), }; } case "text": { const text = await showTextInput(request.message); return { requestId: request.id, responded: true, value: text, timestamp: Date.now(), }; } default: return { requestId: request.id, responded: false, timestamp: Date.now(), }; } }, }); // Convenience methods const confirmed = await manager.confirm("Delete this file?", { toolName: "deleteFile", confirmLabel: "Yes, delete", cancelLabel: "Cancel", }); const name = await manager.getText("Enter project name:", { placeholder: "my-project", defaultValue: "untitled", }); const choice = await manager.select("Select environment:", [ { value: "dev", label: "Development" }, { value: "staging", label: "Staging" }, { value: "prod", label: "Production" }, ]); const formData = await manager.form("Configure deployment:", [ { name: "region", label: "Region", type: "select", required: true, options: [ { value: "us-east-1", label: "US East" }, { value: "eu-west-1", label: "EU West" }, ], }, { name: "replicas", label: "Replicas", type: "number", required: true, defaultValue: 3, }, ]); // Request secret/password input (masked) const apiKey = await manager.getSecret("Enter API key:", { toolName: "configureService", }); // Multi-selection from options const regions = await manager.multiSelect( "Select deployment regions:", [ { value: "us-east-1", label: "US East" }, { value: "eu-west-1", label: "EU West" }, { value: "ap-south-1", label: "AP South" }, ], { minSelections: 1, maxSelections: 2 }, ); // Cancel a pending request manager.cancel("request-id-123", "User navigated away"); // Enable/disable elicitation manager.setEnabled(false); console.log(manager.isEnabled()); // => false // Inspect pending requests console.log(manager.getPendingCount()); // => 0 const pending = manager.getPendingRequests(); manager.clearPending("Session ended"); ``` ### Additional Methods | Method | Description | | ---------------------------------------- | ----------------------------- | | `confirm(message, options?)` | Yes/no confirmation dialog | | `getText(message, options?)` | Free text input | | `select(message, options, config?)` | Single selection from options | | `multiSelect(message, options, config?)` | Multi-selection from options | | `form(message, fields)` | Structured form with fields | | `getSecret(message, options?)` | Request secret/password input | | `cancel(requestId, reason?)` | Cancel pending request | | `setEnabled(enabled)` | Enable/disable elicitation | | `isEnabled()` | Check if enabled | | `getPendingCount()` | Get pending request count | | `getPendingRequests()` | Get all pending requests | | `clearPending(reason?)` | Clear all pending requests | ### ElicitationProtocolAdapter Bridges protocol-level JSON-RPC 2.0 messages with the ElicitationManager for cross-transport communication: ```typescript ElicitationProtocolAdapter, createConfirmationRequest, createTextInputRequest, isElicitationProtocolMessage, } from "@juspay/neurolink"; const adapter = new ElicitationProtocolAdapter({ defaultTimeout: 30000, enableLogging: true, }); // Handle incoming protocol messages const response = await adapter.handleMessage(incomingMessage); // Create protocol-compliant request messages const confirmMsg = createConfirmationRequest("Are you sure?", { toolName: "dropTable", confirmLabel: "Drop it", cancelLabel: "Keep", timeout: 15000, }); // Check if a message is an elicitation protocol message if (isElicitationProtocolMessage(msg)) { await adapter.handleMessage(msg); } ``` ### Events `ElicitationManager` extends `EventEmitter` and emits the following events: | Event | Payload | Fired When | | ---------------------- | ------------------------------------------ | ----------------------------------------------- | | `elicitationRequested` | `Elicitation` (the full request object) | A new elicitation request is created | | `elicitationResponded` | `ElicitationResponse` | The handler successfully responds to a request | | `elicitationError` | `{ request: Elicitation, error: unknown }` | The handler throws an error | | `elicitationTimeout` | `{ request: Elicitation }` | A request times out before receiving a response | | `elicitationCancelled` | `{ requestId: string, reason?: string }` | A pending request is manually cancelled | ```typescript manager.on("elicitationRequested", (request) => { console.log(`Elicitation requested: ${request.type} for ${request.toolName}`); }); manager.on("elicitationTimeout", ({ request }) => { console.log(`Request ${request.id} timed out`); }); ``` ### Key Types ```typescript ElicitationType, Elicitation, ElicitationResponse, ElicitationHandler, ElicitationManagerConfig, ElicitationContext, FormField, SelectOption, ElicitationProtocolMessage, ElicitationProtocolPayload, } from "@juspay/neurolink"; ``` --- ## Multi-Server Manager Coordinates multiple MCP servers with load balancing, failover, unified tool discovery, and server grouping. ### Load Balancing Strategies | Strategy | Description | | --------------- | -------------------------------------------- | | `round-robin` | Rotate through servers sequentially | | `least-loaded` | Prefer server with fewest active requests | | `random` | Random selection | | `weighted` | Weighted random based on server priority | | `failover-only` | Use primary server, failover only on failure | ### Usage ```typescript const manager = new MultiServerManager({ defaultStrategy: "least-loaded", healthAwareRouting: true, healthCheckInterval: 30000, maxFailoverRetries: 3, autoNamespace: true, namespaceSeparator: ".", conflictResolution: "first-wins", }); // Add servers manager.addServer({ id: "db-primary", name: "DB Primary", status: "connected", tools: [...] }); manager.addServer({ id: "db-replica", name: "DB Replica", status: "connected", tools: [...] }); // Create server groups for load balancing manager.createGroup({ id: "database-pool", name: "Database Servers", servers: ["db-primary", "db-replica"], strategy: "least-loaded", healthAware: true, weights: [ { serverId: "db-primary", weight: 70, priority: 0 }, { serverId: "db-replica", weight: 30, priority: 1 }, ], }); // Select a server for a tool call const selection = manager.selectServer("queryUsers", "database-pool"); if (selection) { console.log(`Using server: ${selection.serverId}`); } // Get unified tool list across all servers const tools = manager.getUnifiedTools(); for (const tool of tools) { console.log(`${tool.name} - available on ${tool.servers.length} server(s)`); if (tool.hasConflict) { console.log(" WARNING: Tool name conflict across servers"); } } // Track request metrics manager.requestStarted("db-primary"); // ... execute request ... manager.requestCompleted("db-primary", 150, true); // Get namespaced tools (server.toolName format) const nsTools = manager.getNamespacedTools(); // => [{ fullName: "db-primary.queryUsers", toolName: "queryUsers", ... }] ``` ### Methods | Method | Description | | ----------------------------------------------- | ---------------------------------------- | | `addServer(server)` | Add a server to the manager | | `removeServer(serverId)` | Remove a server from the manager | | `updateServer(serverId, updates)` | Update server configuration | | `getServers()` | Get all servers | | `getServer(serverId)` | Get specific server | | `createGroup(group)` | Create a server group | | `removeGroup(groupId)` | Remove a server group | | `addServerToGroup(serverId, groupId)` | Add server to group | | `removeServerFromGroup(serverId, groupId)` | Remove server from group | | `getGroups()` | Get all groups | | `getGroup(groupId)` | Get specific group | | `selectServer(toolName, groupId?)` | Select a server for a tool call | | `setToolPreference(toolName, serverId)` | Set preferred server for a tool | | `clearToolPreference(toolName)` | Clear tool preference | | `getUnifiedTools()` | Get unified tool list across all servers | | `getNamespacedTools()` | Get tools with server namespace prefixes | | `requestStarted(serverId)` | Track request start for load balancing | | `requestCompleted(serverId, duration, success)` | Track request completion | | `getServerMetrics(serverId)` | Get server metrics | | `getAllMetrics()` | Get all metrics | ### Events `MultiServerManager` extends `EventEmitter` and emits the following events: | Event | Payload | Fired When | | ------------------------ | ---------------------------------------------- | ------------------------------------ | | `serverAdded` | `{ serverId: string, server: MCPServerInfo }` | A server is added to the manager | | `serverRemoved` | `{ serverId: string }` | A server is removed from the manager | | `serverUpdated` | `{ serverId: string, server: MCPServerInfo }` | Server info is updated | | `groupCreated` | `{ group: ServerGroup }` | A new server group is created | | `groupRemoved` | `{ groupId: string }` | A server group is removed | | `serverAddedToGroup` | `{ serverId: string, groupId: string }` | A server is added to a group | | `serverRemovedFromGroup` | `{ serverId: string, groupId: string }` | A server is removed from a group | | `metricsUpdated` | `{ serverId: string, metrics: ServerMetrics }` | Server metrics are updated | | `toolPreferenceSet` | `{ toolName: string, serverId: string }` | A tool routing preference is set | ### Key Types ```typescript LoadBalancingStrategy, MultiServerManagerConfig, ServerGroup, ServerWeight, UnifiedTool, } from "@juspay/neurolink"; ``` --- ## MCP Server Base Abstract base class for building custom MCP servers with consistent patterns for tool registration, execution, and lifecycle management. ### Creating a Custom Server ```typescript class DataProcessingServer extends MCPServerBase { constructor() { super({ id: "data-processing", name: "Data Processing Server", description: "Provides data transformation and analysis tools", version: "1.0.0", category: "data", defaultAnnotations: { securityLevel: "internal", }, }); // Register tools this.registerTool({ name: "transformCSV", description: "Transform CSV data with column mapping", annotations: { readOnlyHint: true, idempotentHint: true, estimatedDuration: 5000, }, inputSchema: { type: "object", properties: { data: { type: "string", description: "CSV content" }, mapping: { type: "object", description: "Column mapping" }, }, required: ["data"], }, execute: async (params) => { const { data, mapping } = params as { data: string; mapping?: object }; const transformed = await this.processCSV(data, mapping); return { success: true, data: transformed }; }, }); } protected async onInit(): Promise { // Async initialization (load configs, warm caches, etc.) } protected async onStart(): Promise { // Start background tasks } protected async onStop(): Promise { // Clean up resources } private async processCSV(data: string, mapping?: object): Promise { // Implementation return data; } } // Usage const server = new DataProcessingServer(); await server.init(); await server.start(); // Execute tools const result = await server.executeTool("transformCSV", { data: "a,b\n1,2" }); // Convert to MCPServerInfo for registration with MultiServerManager const serverInfo = server.toServerInfo(); // Query tools by annotation const readOnlyTools = server.getReadOnlyTools(); const destructiveTools = server.getDestructiveTools(); // Lifecycle events server.on("toolRegistered", ({ toolName }) => console.log(`Registered: ${toolName}`), ); server.on("toolExecuted", ({ toolName, duration }) => console.log(`${toolName}: ${duration}ms`), ); ``` ### Additional Methods | Method | Description | | ----------------------------------------- | -------------------------------------------------------- | | `init()` | Run `onInit()` lifecycle hook | | `start()` | Start the server (calls `onStart()`) | | `stop()` | Stop the server (calls `onStop()`) | | `registerTool(tool)` | Register a tool with the server | | `registerTools(tools)` | Register multiple tools at once | | `executeTool(name, params)` | Execute a registered tool by name | | `getTools()` | Get all registered tools | | `getTool(name)` | Get a specific tool by name | | `hasTool(name)` | Check if tool exists | | `removeTool(name)` | Remove a tool | | `toServerInfo()` | Convert server state to `MCPServerInfo` for registration | | `getToolsByAnnotation(annotation, value)` | Filter tools by a specific annotation key and value | | `getReadOnlyTools()` | Get tools with `readOnlyHint: true` | | `getDestructiveTools()` | Get tools with `destructiveHint: true` | | `getIdempotentTools()` | Get tools with `idempotentHint: true` | | `getToolsRequiringConfirmation()` | Get tools with `requiresConfirmation: true` | ### Events `MCPServerBase` extends `EventEmitter` and emits the following typed events (`MCPServerEvents`): | Event | Payload | Fired When | | ---------------- | ---------------------------------------------------------- | ---------------------------------------------- | | `toolRegistered` | `{ toolName: string, tool: MCPServerTool }` | A tool is registered with the server | | `toolExecuted` | `{ toolName: string, duration: number, success: boolean }` | A tool finishes execution (success or failure) | | `toolError` | `{ toolName: string, error: Error }` | A tool throws an error during execution | | `serverReady` | `{ tools: string[] }` | The server finishes initialization | | `serverStopped` | `{ reason?: string }` | The server is stopped | ### Key Types ```typescript MCPServerBaseConfig, MCPServerEvents, MCPServerTool, MCPToolAnnotations, } from "@juspay/neurolink"; ``` --- ## Agent & Workflow Exposure Expose NeuroLink agents and workflows as MCP tools, allowing external MCP clients to invoke complex AI operations through the standardized MCP protocol. ### Exposing Agents ```typescript exposeAgentAsTool, exposeAgentsAsTools, AgentExposureManager, type ExposableAgent, } from "@juspay/neurolink"; const agent: ExposableAgent = { id: "support-agent", name: "Customer Support Agent", description: "Handles customer support queries with knowledge base lookup", inputSchema: { type: "object", properties: { query: { type: "string", description: "Customer question" }, customerId: { type: "string" }, }, required: ["query"], }, execute: async (input) => { // Agent execution logic return { answer: "...", confidence: 0.95 }; }, metadata: { version: "2.1.0", category: "support", tags: ["customer-service", "knowledge-base"], estimatedDuration: 5000, }, }; // Expose as a single MCP tool const { tool, toolName } = exposeAgentAsTool(agent, { prefix: "agent", executionTimeout: 300000, enableLogging: true, }); // => toolName: "agent_customer_support_agent" ``` ### Exposing Workflows ```typescript exposeWorkflowAsTool, type ExposableWorkflow, } from "@juspay/neurolink"; const workflow: ExposableWorkflow = { id: "onboarding-flow", name: "User Onboarding", description: "Complete user onboarding workflow", steps: [ { id: "validate", name: "Validate Input" }, { id: "create-account", name: "Create Account" }, { id: "send-welcome", name: "Send Welcome Email" }, ], inputSchema: { type: "object", properties: { email: { type: "string" }, name: { type: "string" }, }, required: ["email", "name"], }, execute: async (input) => { return { userId: "user-123", status: "onboarded" }; }, metadata: { version: "1.0.0", idempotent: true, estimatedDuration: 15000, }, }; const { tool } = exposeWorkflowAsTool(workflow, { prefix: "workflow", executionTimeout: 600000, }); ``` ### AgentExposureManager Manages the lifecycle of all exposed agents and workflows: ```typescript const exposureManager = new AgentExposureManager({ prefix: "neurolink", enableLogging: true, }); exposureManager.exposeAgent(supportAgent); exposureManager.exposeWorkflow(onboardingWorkflow); const allTools = exposureManager.getExposedTools(); const agentTools = exposureManager.getToolsBySourceType("agent"); const stats = exposureManager.getStatistics(); // => { totalExposed: 2, exposedAgents: 1, exposedWorkflows: 1, toolNames: [...] } ``` ### ExposureOptions | Field | Type | Default | Description | | ------------------------------ | -------------------------- | -------------------------------------- | ---------------------------------------------- | | `prefix` | `string` | `"agent"`/`"workflow"` | Prefix for generated tool names | | `defaultAnnotations` | `MCPToolAnnotations` | `{}` | Annotations applied to all exposed tools | | `includeMetadataInDescription` | `boolean` | `true` | Append source metadata to tool description | | `nameTransformer` | `(name: string) => string` | lowercase + `_` | Transform source name to MCP tool name | | `wrapWithContext` | `boolean` | `true` | Wrap execution with context (logging, timeout) | | `executionTimeout` | `number` | `300000` (agent) / `600000` (workflow) | Timeout in ms | | `enableLogging` | `boolean` | `true` | Log execution start/end/errors | ### ExposureResult | Field | Type | Description | | ------------ | ----------------------- | ----------------------------------- | | `tool` | `MCPServerTool` | The generated MCP tool | | `sourceType` | `"agent" \| "workflow"` | Whether source is agent or workflow | | `sourceId` | `string` | Original agent/workflow ID | | `toolName` | `string` | Generated MCP tool name | ### Additional Methods (AgentExposureManager) | Method | Description | | ----------------------------- | ----------------------------------------------- | | `exposeAgent(agent)` | Expose an agent and register the tool | | `exposeWorkflow(workflow)` | Expose a workflow and register the tool | | `getExposedTools()` | Get all exposed tools as `MCPServerTool[]` | | `getExposureResult(toolName)` | Get the `ExposureResult` for a tool name | | `getToolsBySourceType(type)` | Get tools filtered by `"agent"` or `"workflow"` | | `unexpose(toolName)` | Remove a single exposed tool; returns boolean | | `clear()` | Remove all exposed tools | | `getStatistics()` | Get counts: totalExposed, agents, workflows | ### Key Types ```typescript ExposableAgent, ExposableWorkflow, ExposureOptions, ExposureResult, } from "@juspay/neurolink"; ``` --- ## Server Capabilities Manages resources and prompts for MCP servers according to the MCP specification. Enables servers to expose data as resources and reusable prompt templates. ### Resources ```typescript ServerCapabilitiesManager, createTextResource, createJsonResource, } from "@juspay/neurolink"; const capabilities = new ServerCapabilitiesManager({ resources: true, prompts: true, resourceSubscriptions: true, }); // Register a static text resource capabilities.registerResource( createTextResource( "config://app/settings", "Application Settings", "key=value\nport=3000", { description: "Current application settings" }, ), ); // Register a dynamic JSON resource capabilities.registerResource( createJsonResource( "data://metrics/current", "Current Metrics", async () => ({ cpu: 45, memory: 72, requests: 1250 }), { description: "Live system metrics", dynamic: true }, ), ); // Register a resource template for pattern-matched URIs capabilities.registerResourceTemplate("data://users/{id}", { name: "User Data", uriPattern: "data://users/{id}", mimeType: "application/json", reader: async (uri) => { const id = uri.split("/").pop(); return { uri, mimeType: "application/json", text: JSON.stringify({ id, name: "User" }), }; }, }); // Read a resource const content = await capabilities.readResource("config://app/settings"); // Subscribe to resource changes const unsubscribe = capabilities.subscribeToResource( "data://metrics/current", (uri, content) => { console.log(`Metrics updated:`, content.text); }, ); // Notify subscribers of a change await capabilities.notifyResourceChanged("data://metrics/current"); // Unsubscribe unsubscribe(); ``` ### Prompts ```typescript // Register a simple template-based prompt capabilities.registerPrompt( createPrompt( "summarize", "Please summarize the following text concisely:\n\n{text}", { description: "Summarize text content", arguments: [ { name: "text", description: "Text to summarize", required: true }, ], }, ), ); // Register a prompt with a custom generator capabilities.registerPrompt({ name: "code-review", description: "Review code for issues and improvements", arguments: [ { name: "code", description: "Source code to review", required: true }, { name: "language", description: "Programming language" }, ], generator: async (args) => ({ messages: [ { role: "user", content: { type: "text", text: `Review this ${args.language || "code"} for bugs, security issues, and improvements:\n\n${args.code}`, }, }, ], }), }); // Generate a prompt const result = await capabilities.getPrompt("summarize", { text: "NeuroLink is an enterprise AI platform...", }); // List all prompts and resources const prompts = capabilities.listPrompts(); const resources = capabilities.listResources(); // Get MCP capabilities object for protocol negotiation const caps = capabilities.getCapabilities(); // => { resources: { subscribe: true, listChanged: true }, prompts: { listChanged: true } } ``` ### Additional Methods (ServerCapabilitiesManager) | Method | Description | | --------------------------------------------- | --------------------------------------------------------- | | `registerResource(resource)` | Register a static or dynamic resource | | `registerResourceTemplate(pattern, template)` | Register a URI-template resource for pattern matching | | `readResource(uri)` | Read a resource by URI (resolves templates) | | `listResources()` | List all registered resources as `MCPResource[]` | | `getResource(uri)` | Get a registered resource by URI | | `subscribeToResource(uri, callback)` | Subscribe to resource changes; returns unsubscribe fn | | `notifyResourceChanged(uri)` | Notify all subscribers that a resource has changed | | `registerPrompt(prompt)` | Register a prompt with static template or async generator | | `getPrompt(name, args?)` | Generate a prompt result with provided arguments | | `listPrompts()` | List all registered prompts as `MCPPrompt[]` | | `getCapabilities()` | Get MCP capabilities object for protocol negotiation | ### Events `ServerCapabilitiesManager` extends `EventEmitter` and emits the following events: | Event | Payload | Fired When | | ---------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | | `resourceRegistered` | `{ uri: string, name: string, timestamp: Date }` | A resource is registered | | `resourceTemplateRegistered` | `{ pattern: string, timestamp: Date }` | A resource template is registered | | `resourceUnregistered` | `{ uri: string, timestamp: Date }` | A resource is unregistered | | `resourceRead` | `{ uri: string, duration: number, success: boolean, timestamp: Date, error?: string }` | A resource is read (success or failure) | | `resourceSubscribed` | `{ uri: string, timestamp: Date }` | A subscription is added to a resource | | `resourceUnsubscribed` | `{ uri: string, timestamp: Date }` | A subscription is removed from a resource | | `resourceChanged` | `{ uri: string, subscriberCount: number, timestamp: Date }` | A resource change is notified to subscribers | | `promptRegistered` | `{ name: string, timestamp: Date }` | A prompt is registered | | `promptUnregistered` | `{ name: string, timestamp: Date }` | A prompt is unregistered | | `promptGenerated` | `{ name: string, duration: number, success: boolean, messageCount?: number, timestamp: Date, error?: string }` | A prompt is generated | | `cleared` | `{ timestamp: Date }` | All resources and prompts are cleared | ### Additional Methods | Method | Description | | --------------------------------------------- | ----------------------------------------------------------- | | `registerResource(resource)` | Register a resource with a reader function | | `registerResourceTemplate(pattern, template)` | Register a URI-pattern-based resource template | | `unregisterResource(uri)` | Remove a resource and its subscriptions | | `listResources()` | List all registered resources | | `readResource(uri, context?)` | Read a resource by URI (checks templates on miss) | | `getResource(uri)` | Get resource definition by URI | | `subscribeToResource(uri, callback)` | Subscribe to resource changes; returns unsubscribe function | | `notifyResourceChanged(uri)` | Read resource and notify all subscribers | | `registerPrompt(prompt)` | Register a prompt with a generator function | | `unregisterPrompt(name)` | Remove a prompt | | `listPrompts()` | List all registered prompts | | `getPrompt(name, args?, context?)` | Generate a prompt with arguments | | `getPromptDefinition(name)` | Get prompt definition without generating | | `getCapabilities()` | Get MCP capabilities object for protocol negotiation | | `getStatistics()` | Get counts of resources, templates, prompts, subscriptions | | `clear()` | Clear all resources, templates, prompts, and subscriptions | ### Key Types ```typescript MCPResource, ResourceContent, ResourceReader, RegisteredResource, MCPPrompt, PromptMessage, PromptResult, PromptGenerator, RegisteredPrompt, ServerCapabilitiesConfig, ResourceSubscriptionCallback, } from "@juspay/neurolink"; ``` --- ## MCP Registry Client Discover MCP servers from a built-in catalog of well-known servers and, when you opt in, from the official MCP Registry or a registry of your own. Search by category, tags, transport type, and verification status. By default the client reads only the built-in catalog and the custom entries you add, and it never makes a network request. [Remote lookup](#remote-lookup-opt-in) is off until you turn it on. ### Usage ```typescript MCPRegistryClient, getWellKnownServer, getAllWellKnownServers, } from "@juspay/neurolink"; const client = new MCPRegistryClient({ enableCache: true, defaultCacheTTL: 3600000, // 1 hour }); // Search for servers const results = await client.search({ query: "database", categories: ["database"], verifiedOnly: true, sortBy: "downloads", limit: 10, }); for (const entry of results.entries) { console.log(`${entry.name} - ${entry.description}`); console.log(` Install: ${client.getInstallCommand(entry)}`); // Check if required env vars are set const { ready, missing } = client.checkRequiredEnvVars(entry); if (!ready) { console.log(` Missing: ${missing.join(", ")}`); } } // Get a specific well-known server const postgres = getWellKnownServer("postgres"); // => { id: "postgres", name: "PostgreSQL", npmPackage: "@modelcontextprotocol/server-postgres", ... } // Convert registry entry to MCPServerInfo for NeuroLink const serverInfo = client.toServerInfo(postgres); // Browse by category const dbServers = await client.getByCategory("database"); const searchServers = await client.getByTag("search"); // Get all available categories and tags const categories = await client.getCategories(); const tags = await client.getTags(); // Add custom registry entries client.addCustomEntry({ id: "my-internal-server", name: "Internal Data Server", description: "Company internal data API", version: "3.0.0", command: "node", args: ["./servers/data-server.js"], categories: ["data", "internal"], verified: false, }); ``` ### Remote lookup (opt-in) Set `remoteLookup: true` to let the client consult the registries in `registries`. The default list is the official MCP Registry at `https://registry.modelcontextprotocol.io`; add your own with `{ type: "custom", url }` or `addRegistry()`. A custom registry must serve the same `/v0.1` API as the official one (`GET /v0.1/servers` and `GET /v0.1/servers/{name}/versions/latest`, see the [registry API reference](https://github.com/modelcontextprotocol/registry/blob/main/docs/reference/api/openapi.yaml)); `url` is its base URL. ```typescript const client = new MCPRegistryClient({ remoteLookup: true, timeout: 5000, // per request, in ms (default 10000) userAgent: "my-app/1.0", // sent on every registry request registries: [ { type: "official" }, { type: "custom", url: "https://registry.example.com", authToken: process.env.REGISTRY_TOKEN, // sent as a Bearer token to this registry only timeout: 2000, // overrides the client-wide timeout cacheTTL: 600000, // overrides defaultCacheTTL }, ], }); // Local catalog and custom entries are checked first, then each registry const entry = await client.getEntry("io.github.example/my-server"); if (entry) { console.log(entry.verified); // always false for a remote entry console.log(client.getInstallCommand(entry)); // npx -y @ } // search() and getAllEntries() list local entries first, then remote ones const results = await client.search({ query: "io.github.example" }); ``` What to expect: - **Opt-in.** With `remoteLookup` unset or `false`, no registry is contacted, whatever `registries` contains. A client you did not construct, such as the one from `neurolink.getMCPRegistryClient()`, can be switched with `client.setRemoteLookup(true)`. - **When a registry is queried.** `getEntry(id)` asks the registries only after the custom entries and the built-in catalog miss. `search()` and `getAllEntries()` merge each registry's servers after the local ones; an id that exists locally is never replaced by a remote entry. `search({ query })` passes the query to the registry, which matches it against the server _name_ (a substring match), so a word that appears only in a remote server's description is not found. - **Remote entries are unverified.** They carry `verified: false`, so `verifiedOnly` never returns them. The registry publishes whatever its authors submit; review a server before running its `command` and `args`. - **Ids differ from the built-in slugs.** The official registry names servers in reverse-DNS form, such as `io.github.example/my-server`. Built-in slugs like `filesystem` are not aliased to them. - **What is mapped.** An `npm` package becomes `npmPackage`, `command: "npx"` and `args: ["-y", "@"]`, with its required environment variables in `requiredEnvVars`. Other package types (for example `pypi` or `oci`) and remote URLs are listed under `entry.metadata.packages` and `entry.metadata.remotes`; no `command` is set for them. - **Package names are validated, not just typed.** A registry is untrusted input, so the client sets `command`, `args`, `npmPackage` and `installCommand` only when the npm `identifier` is a valid package name (optional `@scope/`, lowercase letters, digits and `._~-`, never a leading dash) and the `version` starts with a letter or digit and contains only `0-9A-Za-z.+_~-`. A package that fails either check (for example `--call=...` or a name containing a space or `;`) is listed under `entry.metadata.packages` only, and the entry has no `command`. Review any server before running it, whichever registry it came from. - **Failure never throws.** A timeout, a refused connection, a non-2xx status (other than 404, which is a normal miss), a body that is not JSON or not shaped like a registry response all fall back to the local result. The client emits a `registryError` event (`{ registry, operation, message }`, never the token) and does not cache the failure, so the next call tries again. - **Limits.** Each request is bounded by `timeout`, and a response larger than 8 MiB is rejected as a failure. A list is read up to `maxPages` pages of 100 servers per registry (default 5), so a very large registry is merged partially. Responses are cached per registry for `cacheTTL` (or `defaultCacheTTL`). `enableCache: false` on the client turns caching off for every registry; on a registry it turns it off for that registry only. A 404 is not cached. - **Ids.** `getEntry("")`, `getEntry(".")` and `getEntry("..")` are a miss without a request, because URL normalisation would turn them into a different registry endpoint. - **Registry types.** Only `official` and `custom` registries are queried. `npm` and `github` entries are accepted in `registries` for compatibility but skipped, as are `custom` entries without a URL, and URLs that are not `http(s)` or that embed credentials. - **Bearer tokens need https.** A registry with an `authToken` is queried only over `https:` or on a loopback host (`localhost`, `127.0.0.0/8`, `[::1]`). A plain `http:` URL to any other host is skipped, so the token never crosses the network in clear. - **Network stack.** Requests use Node's global `fetch` directly, not NeuroLink's proxy-aware provider fetch, so `HTTP_PROXY`/`HTTPS_PROXY` apply only if your Node runtime is set up to apply them to `fetch`. ### Methods | Method | Description | | ----------------------------- | ------------------------------------------------------------------------------------------- | | `search(options)` | Search for servers with filters; includes remote servers when remote lookup is on | | `getByCategory(category)` | Browse servers by category | | `getByTag(tag)` | Filter entries by tag | | `getCategories()` | Get all available categories | | `getTags()` | Get all available tags | | `getEntry(id)` | Get a specific registry entry; asks the registries on a local miss when remote lookup is on | | `getAllEntries()` | Get local entries, plus every configured registry's servers when remote lookup is on | | `addCustomEntry(entry)` | Add a custom registry entry | | `removeCustomEntry(id)` | Remove a custom entry | | `addRegistry(config)` | Add a registry source (queried only when remote lookup is on) | | `setRemoteLookup(enabled)` | Turn remote lookup on or off at runtime | | `getPopularServers(limit?)` | Get popular servers | | `getVerifiedServers()` | Get verified servers | | `getStatistics()` | Get registry statistics | | `toServerInfo(entry)` | Convert entry to `MCPServerInfo` | | `getInstallCommand(entry)` | Get install command for an entry | | `checkRequiredEnvVars(entry)` | Check if required env vars are set | ### Well-Known Servers The registry includes these verified servers out of the box: | ID | Name | Categories | Key Tools | | -------------- | ------------ | -------------------- | ------------------------------- | | `filesystem` | Filesystem | file-system | read_file, write_file, list_dir | | `github` | GitHub | version-control, api | create_repo, list_commits | | `postgres` | PostgreSQL | database | query, list_tables | | `sqlite` | SQLite | database | query, list_tables | | `brave-search` | Brave Search | search, api | web_search, local_search | | `puppeteer` | Puppeteer | automation, web | navigate, screenshot, click | | `git` | Git | version-control | git_status, git_log, git_diff | | `memory` | Memory | memory, storage | store, retrieve, search | | `slack` | Slack | communication, api | send_message, list_channels | | `google-drive` | Google Drive | file-system, api | list_files, read_file | ### Key Types ```typescript MCPRegistryClientConfig, RegistryConfig, RegistryEntry, RegistrySearchOptions, RegistrySearchResult, RegistrySourceType, } from "@juspay/neurolink"; ``` --- ## Architecture > For detailed per-module flow diagrams (Tool Router decision flow, Tool Cache eviction, Request Batcher sequencing, Elicitation Protocol handshake, and Multi-Server topology), see [MCP Enhancement Architecture Diagrams](/docs/features/mcp-enhancements-diagrams). The MCP enhancement modules are layered on top of NeuroLink's existing MCP infrastructure: ```mermaid graph TB subgraph "Application Layer" A[NeuroLink SDK] --> B[MCP Tool Registry] end subgraph "MCP Enhancements" B --> C[Tool Router] B --> D[Tool Cache] B --> E[Request Batcher] B --> F[Tool Integration] C --> G[Multi-Server Manager] F --> H[Elicitation Manager] H --> I[Elicitation Protocol] J[Enhanced Tool Discovery] --> G J --> K[Tool Annotations] K --> C L[MCP Server Base] --> M[Agent Exposure] L --> N[Server Capabilities] O[MCP Registry Client] --> G end subgraph "MCP Servers" G --> P[Server 1] G --> Q[Server 2] G --> R[Server N] end ``` ### Data Flow ```mermaid sequenceDiagram participant App as Application participant TI as Tool Integration participant TR as Tool Router participant TC as Tool Cache participant RB as Request Batcher participant S as MCP Server App->>TI: Execute tool call TI->>TI: Run middleware chain TI->>TC: Check cache alt Cache hit TC-->>App: Return cached result else Cache miss TC->>TR: Route to server TR->>TR: Select server (strategy) TR->>RB: Queue request RB->>S: Execute batch S-->>RB: Return results RB-->>TC: Cache result TC-->>App: Return result end ``` --- ## End-to-End Integration Example This example shows how ToolCache, Tool Annotations, ToolIntegration middleware, and MCPServerBase compose together in a realistic scenario: a custom MCP server whose tools are executed through a middleware pipeline with caching, retry, timeout, and confirmation for destructive operations. ```typescript MCPServerBase, ToolCache, ToolIntegrationManager, createAnnotatedTool, loggingMiddleware, confirmationMiddleware, createTimeoutMiddleware, createRetryMiddleware, requiresConfirmation, isSafeToRetry, type MCPServerTool, } from "@juspay/neurolink"; // ------------------------------------------------------- // 1. Build a custom MCP server with annotated tools // ------------------------------------------------------- class InventoryServer extends MCPServerBase { constructor() { super({ id: "inventory", name: "Inventory Server", description: "Product inventory management tools", version: "1.0.0", category: "database", }); // Read-only tool -- annotations are inferred automatically this.registerTool( createAnnotatedTool({ name: "getProduct", description: "Get product details by SKU", inputSchema: { type: "object", properties: { sku: { type: "string" } }, required: ["sku"], }, execute: async (params) => { const { sku } = params as { sku: string }; // Simulate a database lookup return { sku, name: "Widget", stock: 42, price: 9.99 }; }, }), ); // Destructive tool -- inferred as destructive, requires confirmation this.registerTool( createAnnotatedTool({ name: "deleteProduct", description: "Permanently delete a product from inventory", inputSchema: { type: "object", properties: { sku: { type: "string" } }, required: ["sku"], }, execute: async (params) => { const { sku } = params as { sku: string }; return { deleted: true, sku }; }, }), ); } } // ------------------------------------------------------- // 2. Wire up caching, middleware, and the server // ------------------------------------------------------- async function main() { // Start the custom server const server = new InventoryServer(); await server.init(); await server.start(); // Create a cache for read-only tool results const cache = new ToolCache({ ttl: 5 * 60 * 1000, // 5 minutes maxSize: 200, strategy: "lru", }); // Set up middleware pipeline: logging -> confirmation -> timeout -> retry const integration = new ToolIntegrationManager(); integration.setElicitationHandler(async (request) => { if (request.type === "confirmation") { // In production, prompt the user via your UI framework. // Here we auto-approve for demonstration purposes. console.log(\`[Confirmation] \${request.message} -> auto-approved\`); return { requestId: request.id, responded: true, value: true, timestamp: Date.now(), }; } return { requestId: request.id, responded: false, timestamp: Date.now() }; }); integration .use(loggingMiddleware) .use(confirmationMiddleware) .use(createTimeoutMiddleware(30_000)) .use(createRetryMiddleware(3, 1000)); // Register server tools with the middleware manager for (const tool of server.listTools()) { integration.registerTool(tool); } // ------------------------------------------------------- // 3. Execute tools through the integrated pipeline // ------------------------------------------------------- // Read-only call: cached + retryable, no confirmation needed const getProduct = server.listTools().find((t) => t.name === "getProduct")!; console.log("Requires confirmation:", requiresConfirmation(getProduct)); // false console.log("Safe to retry:", isSafeToRetry(getProduct)); // true const productResult = await cache.getOrSet( ToolCache.generateKey("getProduct", { sku: "W-100" }), () => integration.executeTool("getProduct", { sku: "W-100" }), ); console.log("Product:", productResult); // Second call hits cache const cachedResult = cache.get( ToolCache.generateKey("getProduct", { sku: "W-100" }), ); console.log("From cache:", cachedResult !== undefined); console.log("Cache stats:", cache.getStats()); // Destructive call: triggers confirmation middleware, skips cache const deleteResult = await integration.executeTool("deleteProduct", { sku: "W-100", }); console.log("Delete result:", deleteResult); // Invalidate cache for the deleted product cache.invalidate("getProduct:*"); // ------------------------------------------------------- // 4. Clean up // ------------------------------------------------------- cache.destroy(); await server.stop(); } main().catch(console.error); ``` **What this demonstrates:** - **MCPServerBase** provides a structured way to define and register tools with lifecycle hooks (\`init\`, \`start\`, \`stop\`). - **Tool Annotations** are inferred automatically from tool names and descriptions -- \`getProduct\` is read-only, \`deleteProduct\` is destructive. - **ToolIntegrationManager** chains middleware so every tool call passes through logging, confirmation (for destructive tools), timeout, and retry (for idempotent/read-only tools). - **ToolCache** wraps read-only calls with \`getOrSet\` to avoid redundant execution, and \`invalidate\` clears stale entries after mutations. > See the [Architecture Diagrams](/docs/features/mcp-enhancements-diagrams) for visual flows of how these components interact. --- ## Error Handling All MCP enhancement modules use `ErrorFactory` from `@juspay/neurolink` for consistent, typed errors. Errors include a descriptive message and often a `hint` field with a suggested fix. ### Error Types by Module | Module | ErrorFactory Method | When Thrown | | ------------------------- | ----------------------------- | -------------------------------------------------------------- | | **ToolRouter** | (none -- returns empty array) | Returns empty candidates array instead of throwing | | **ToolCache** | (none -- returns undefined) | Returns `undefined` on miss; eviction events carry reason | | **RequestBatcher** | `invalidConfiguration()` | `maxBatchSize ` | Flush any pending batched tool calls immediately | | `getMCPEnhancementsConfig()` | `MCPEnhancementsConfig \| undefined` | Get the current MCP enhancements configuration | | `getElicitationManager()` | `Promise` | Get the global elicitation manager for interactive tool input | | `registerElicitationHandler(handler)` | `Promise` | Register a handler for interactive elicitation requests | | `getMultiServerManager()` | `Promise` | Get the multi-server manager for load balancing and failover | | `getEnhancedToolDiscovery()` | `Promise` | Get the enhanced tool discovery service | | `getMCPRegistryClient()` | `Promise` | Get the MCP registry client for discovering servers | | `exposeAgentAsTool(agent, options?)` | `Promise` | Expose a NeuroLink agent as an MCP tool | | `exposeWorkflowAsTool(workflow, options?)` | `Promise` | Expose a workflow as an MCP tool | | `getToolIntegrationManager()` | `Promise` | Get the tool integration manager for middleware and elicitation | | `convertToolsToMCPFormat(tools, options?)` | `Promise` | Convert NeuroLink tools to MCP format | | `convertToolsFromMCPFormat(tools, options?)` | `Promise` | Convert MCP tools to NeuroLink format | | `getToolAnnotations(toolName)` | `Promise` | Get annotations and safety information for a tool | ### Middleware Chaining `useToolMiddleware` returns `this`, enabling a fluent chaining pattern: ```typescript const loggingMiddleware: ToolMiddleware = async ( tool, params, context, next, ) => { console.log(`Calling tool: ${tool.name}`, params); const result = await next(); console.log(`Tool result: ${tool.name}`, result); return result; }; const confirmationMiddleware: ToolMiddleware = async ( tool, params, context, next, ) => { if (tool.annotations?.destructiveHint) { const confirmed = await askUser(`Allow ${tool.name}?`); if (!confirmed) throw new Error("User declined"); } return next(); }; const neurolink = new NeuroLink(); neurolink .useToolMiddleware(loggingMiddleware) .useToolMiddleware(confirmationMiddleware); ``` ### Elicitation (Interactive Tool Input) Use `getElicitationManager()` or the shorthand `registerElicitationHandler()` to handle interactive input requests from tools during execution: ```typescript // Shorthand: register a handler directly await neurolink.registerElicitationHandler(async (request) => { switch (request.type) { case "confirmation": return { confirmed: await confirmWithUser(request.message) }; case "text": return { value: await promptUser(request.message) }; case "select": return { value: await selectFromOptions(request.options) }; } }); // Full access: get the manager for advanced configuration const elicitationManager = await neurolink.getElicitationManager(); elicitationManager.registerHandler(async (request) => { if (request.type === "confirmation") { const answer = await askUser(request.message); return { confirmed: answer === "yes" }; } }); ``` ### Agent & Workflow Exposure Expose agents and workflows as MCP tools so they can be invoked by other systems via the MCP protocol: ```typescript // Expose an agent const agent = { id: "my-agent", name: "My Agent", description: "An agent that processes data", execute: async (params) => { /* ... */ }, }; const agentTool = await neurolink.exposeAgentAsTool(agent, { prefix: "agent_", }); // Expose a workflow const workflow = { id: "data-pipeline", name: "Data Pipeline", description: "Runs the data processing pipeline", execute: async (params) => { /* ... */ }, steps: [ { id: "step1", name: "Extract" }, { id: "step2", name: "Transform" }, { id: "step3", name: "Load" }, ], }; const workflowTool = await neurolink.exposeWorkflowAsTool(workflow, { prefix: "workflow_", includeMetadataInDescription: true, executionTimeout: 60000, enableLogging: true, }); ``` ### Tool Annotations Retrieve annotations and safety metadata for any registered tool: ```typescript const annotations = await neurolink.getToolAnnotations("deleteFile"); if (annotations) { console.log(annotations.annotations); // { destructiveHint: true, idempotentHint: false, readOnlyHint: false, ... } console.log(annotations.summary); // Human-readable summary of the tool's safety characteristics } ``` Annotations are inferred from the tool name and description. Explicit annotations set on the tool take precedence over inferred values. ### Tool Format Conversion Convert between NeuroLink and MCP tool formats for interoperability: ```typescript // Export local tools to MCP format const mcpTools = await neurolink.convertToolsToMCPFormat( [{ name: "myTool", description: "Does something", execute: async () => {} }], { namespacePrefix: "myapp_" }, ); // Import external MCP tools to NeuroLink format const neurolinkTools = await neurolink.convertToolsFromMCPFormat( externalTools, { removeNamespacePrefix: "external_", }, ); ``` --- ## CLI Commands The `neurolink mcp` command group provides 12 subcommands for managing MCP servers, tools, and annotations from the terminal. ### `neurolink mcp list` List all configured MCP servers. ```bash neurolink mcp list ``` ### `neurolink mcp servers` Show detailed server status including health and connection info. ```bash neurolink mcp servers neurolink mcp servers --status connected neurolink mcp servers --category database neurolink mcp servers --detailed ``` ### `neurolink mcp tools` List tools across all servers with filtering and search. ```bash neurolink mcp tools neurolink mcp tools --server github neurolink mcp tools --category file-system neurolink mcp tools --tag sql neurolink mcp tools --safety dangerous neurolink mcp tools --annotations neurolink mcp tools --search "read file" ``` ### `neurolink mcp discover` Discover tools from servers with automatic annotation inference. ```bash neurolink mcp discover neurolink mcp discover --server github neurolink mcp discover --infer-annotations ``` ### `neurolink mcp create-server ` Scaffold a new custom MCP server project. ```bash neurolink mcp create-server my-data-server neurolink mcp create-server my-server --template basic --output ./servers neurolink mcp create-server my-server --tools readData,writeData,listItems ``` ### `neurolink mcp annotate` Add, update, or infer annotations on MCP tools. ```bash neurolink mcp annotate --tool deleteUser --destructive neurolink mcp annotate --tool getUser --read-only --idempotent neurolink mcp annotate --infer neurolink mcp annotate --list ``` ### `neurolink mcp install ` Install a well-known MCP server from the built-in registry. ```bash neurolink mcp install postgres neurolink mcp install github neurolink mcp install brave-search ``` ### `neurolink mcp add ` Add a custom MCP server by name and command. ```bash neurolink mcp add my-server "npx -y @my-org/my-mcp-server" neurolink mcp add data-api "node ./servers/data.js" ``` ### `neurolink mcp test [server]` Test connectivity to MCP servers. ```bash neurolink mcp test neurolink mcp test github neurolink mcp test postgres --timeout 10000 ``` ### `neurolink mcp exec ` Execute a specific tool on a server with parameters. ```bash neurolink mcp exec github list_repos neurolink mcp exec postgres query --params '{"sql": "SELECT * FROM users LIMIT 5"}' ``` ### `neurolink mcp remove ` Remove a configured MCP server. ```bash neurolink mcp remove my-server ``` ### `neurolink mcp registry ` Browse and search the MCP server registry. ```bash neurolink mcp registry search database neurolink mcp registry list neurolink mcp registry info postgres neurolink mcp registry categories neurolink mcp registry popular ``` --- ## API Reference ### Classes | Class | Description | | ---------------------------- | ------------------------------------------------- | | `ToolRouter` | Intelligent routing across MCP servers | | `ToolCache` | Generic cache with LRU/FIFO/LFU eviction | | `ToolResultCache` | Tool-specific cache with auto key generation | | `RequestBatcher` | Automatic request batching with server grouping | | `ToolCallBatcher` | High-level batcher for MCP tool calls | | `ToolIntegrationManager` | Middleware chain manager with elicitation support | | `EnhancedToolDiscovery` | Advanced tool search and discovery | | `ElicitationManager` | Interactive user input during tool execution | | `ElicitationProtocolAdapter` | JSON-RPC protocol bridge for elicitation | | `MultiServerManager` | Load balancing and failover coordinator | | `MCPServerBase` | Abstract base class for custom MCP servers | | `AgentExposureManager` | Lifecycle manager for exposed agents/workflows | | `ServerCapabilitiesManager` | Resource and prompt manager per MCP spec | | `MCPRegistryClient` | Server discovery from registries | ### Factory Functions | Function | Returns | | -------------------------- | -------------------- | | `createToolRouter()` | `ToolRouter` | | `createToolCache()` | `ToolCache` | | `createToolResultCache()` | `ToolResultCache` | | `createRequestBatcher()` | `RequestBatcher` | | `createToolCallBatcher()` | `ToolCallBatcher` | | `createAnnotatedTool()` | `MCPServerTool` | | `createToolFromFunction()` | `MCPServerTool` | | `createTextResource()` | `RegisteredResource` | | `createJsonResource()` | `RegisteredResource` | | `createPrompt()` | `RegisteredPrompt` | ### Global Instances | Instance | Type | | ------------------------------ | ---------------------------- | | `globalMultiServerManager` | `MultiServerManager` | | `globalElicitationManager` | `ElicitationManager` | | `globalElicitationProtocol` | `ElicitationProtocolAdapter` | | `globalToolIntegrationManager` | `ToolIntegrationManager` | | `globalAgentExposureManager` | `AgentExposureManager` | | `globalMCPRegistryClient` | `MCPRegistryClient` | ### Utility Functions | Function | Description | | -------------------------------- | -------------------------------------------- | | `inferAnnotations()` | Infer annotations from tool name/description | | `mergeAnnotations()` | Merge annotation objects with precedence | | `validateAnnotations()` | Validate annotations for conflicts | | `getToolSafetyLevel()` | Get safety level: safe, moderate, dangerous | | `requiresConfirmation()` | Check if tool needs user confirmation | | `isSafeToRetry()` | Check if tool is safe for automatic retry | | `filterToolsByAnnotations()` | Filter tools by annotation predicate | | `getAnnotationSummary()` | Get human-readable annotation summary | | `neuroLinkToolToMCP()` | Convert NeuroLink tool to MCP format | | `mcpToolToNeuroLink()` | Convert MCP tool to NeuroLink format | | `batchConvertToMCP()` | Batch convert tools to MCP format | | `batchConvertToNeuroLink()` | Batch convert tools to NeuroLink format | | `validateToolName()` | Validate tool name per MCP spec | | `sanitizeToolName()` | Sanitize tool name for MCP compatibility | | `getWellKnownServer()` | Look up a well-known MCP server by ID | | `getAllWellKnownServers()` | Get all well-known MCP servers | | `exposeAgentAsTool()` | Expose an agent as an MCP tool | | `exposeWorkflowAsTool()` | Expose a workflow as an MCP tool | | `exposeAgentsAsTools()` | Batch expose agents | | `exposeWorkflowsAsTools()` | Batch expose workflows | | `isElicitationProtocolMessage()` | Check if message is elicitation protocol | | `createConfirmationRequest()` | Create protocol confirmation request | | `createTextInputRequest()` | Create protocol text input request | | `createSelectRequest()` | Create protocol select request | | `createFormRequest()` | Create protocol form request | --- ## Testing The MCP enhancements include a comprehensive continuous test suite covering all 14 modules. ### Running the Test Suite ```bash pnpm exec tsx test/continuous-test-suite-mcp.ts --provider=vertex ``` ### Environment Variables | Variable | Description | Default | | --------------- | ---------------------------------------- | ---------------------- | | `TEST_PROVIDER` | AI provider to use for integration tests | `vertex` | | `TEST_MODEL` | Model name override | Provider default model | ### Test Coverage The suite contains **44 test functions** with **172+ assertions** organized across 9 parts: | Part | Module | Tests | Focus | | ---- | --------------------------------- | ----- | ----------------------------------------------------- | | 1 | Tool Router | 5 | Strategies, registration, affinity, health, events | | 2 | Tool Cache | 5 | Set/get, TTL, eviction, invalidation, stats | | 3 | Request Batcher | 5 | Batching, flush, drain, server grouping, events | | 4 | Tool Annotations | 5 | Inference, safety levels, validation, merge, filter | | 5 | Tool Converter | 5 | Bidirectional conversion, batch, function, sanitize | | 6 | Tool Integration & Middleware | 5 | Middleware chain, elicitation, timeout, retry, custom | | 7 | Enhanced Discovery & Multi-Server | 5 | Search, safety filter, server groups, namespacing | | 8 | Server Base, Exposure, Registry | 5 | Custom server, agent/workflow exposure, registry | | 9 | Server Capabilities & Elicitation | 4 | Resources, prompts, subscriptions, elicitation types | --- ## MCP Tools Ecosystem - Built-in Tools + Any MCP Server # MCP Tools Ecosystem: Built-in Tools + Any MCP Server > **Since**: v7.0.0 | **Status**: Production Ready | **MCP Version**: 2024-11-05 ## Overview NeuroLink's Model Context Protocol (MCP) integration provides a **universal plugin system** that transforms the SDK from a simple AI interface into a complete AI development platform. With 6 built-in core tools and the ability to connect any community MCP server (58+ cataloged in the [server directory](/docs/guides/mcp/server-catalog)), you can extend AI capabilities to interact with filesystems, databases, APIs, cloud services, and custom enterprise systems. ### What is MCP? The Model Context Protocol is an **open standard** (like USB-C for AI) that enables AI models to securely interact with external tools and data sources through a unified interface. Think of it as: - **For Developers**: A standardized way to connect AI to any external system - **For AI Models**: A tool registry with discoverable, executable functions - **For Enterprises**: A controlled, auditable way to extend AI capabilities ### Why MCP Matters | Traditional Approach | MCP Approach | Benefit | | --------------------------------------- | --------------------------------- | ----------------------- | | Custom tool integrations per provider | One MCP tool works everywhere | 10x faster integration | | Manual tool discovery and configuration | Automatic tool registry | Zero-config tool usage | | Provider-specific tool formats | Universal JSON-RPC protocol | Provider portability | | Limited to SDK-defined tools | any community MCP server + custom | Unlimited extensibility | | Static tool set | Dynamic runtime addition | Adapt to changing needs | ### NeuroLink's Deep MCP Integration **Factory-First Architecture**: MCP tools work internally while users see simple factory methods: ```typescript // Same simple interface const result = await neurolink.generate({ input: { text: "List files and create a summary document" }, }); // But internally powered by: // ✅ Context tracking across tool chains // ✅ Permission-based security // ✅ Tool registry and discovery // ✅ Pipeline execution with error recovery // ✅ Rich analytics and monitoring ``` **Key Features:** - **99% Lighthouse Compatible**: Existing MCP tools work with minimal changes - **Dynamic Server Management**: Add/remove MCP servers programmatically - **Rich Context**: 15+ fields including session, user, permissions, metadata - **Performance Optimized**: 0-11ms tool execution (target: \' to test connectivity ``` ### SDK Discovery ```typescript const neurolink = new NeuroLink(); // Discover all tools const tools = await neurolink.getAllAvailableTools(); console.log(`Total tools: ${tools.length}`); // Group by server const byServer = tools.reduce((acc, tool) => { const server = tool.serverId ?? "unknown"; if (!acc[server]) acc[server] = []; acc[server].push(tool.name); return acc; }, {}); console.log("Tools by server:", byServer); // Filter specific capabilities const fileTools = tools.filter( (t) => t.name.includes("file") || t.name.includes("read") || t.name.includes("write"), ); console.log( "File-related tools:", fileTools.map((t) => t.name), ); ``` --- ## Enterprise MCP Patterns ### Custom MCP Server Development Create your own MCP server for enterprise integration: ```typescript // custom-crm-server.ts const server = new Server( { name: "custom-crm", version: "1.0.0", }, { capabilities: { tools: {}, }, }, ); // Register tools server.setRequestHandler("tools/list", async () => { return { tools: [ { name: "get_customer", description: "Get customer details from CRM", inputSchema: { type: "object", properties: { customerId: { type: "string", description: "Customer ID", }, }, required: ["customerId"], }, }, { name: "create_lead", description: "Create new lead in CRM", inputSchema: { type: "object", properties: { name: { type: "string" }, email: { type: "string" }, company: { type: "string" }, }, required: ["name", "email"], }, }, ], }; }); // Handle tool execution server.setRequestHandler("tools/call", async (request) => { const { name, arguments: args } = request.params; switch (name) { case "get_customer": const customer = await fetchCustomerFromCRM(args.customerId); return { content: [ { type: "text", text: JSON.stringify(customer, null, 2), }, ], }; case "create_lead": const lead = await createLeadInCRM(args); return { content: [ { type: "text", text: `Lead created: ${lead.id}`, }, ], }; default: throw new Error(`Unknown tool: ${name}`); } }); // Start server const transport = new StdioServerTransport(); await server.connect(transport); ``` **Using custom server**: ```typescript await neurolink.addExternalMCPServer("crm", { command: "node", args: ["./custom-crm-server.js"], env: { CRM_API_KEY: process.env.CRM_API_KEY, CRM_ENDPOINT: process.env.CRM_ENDPOINT, }, }); ``` ### Security Considerations #### 1. Tool Sandboxing ```typescript // Restrict filesystem access await neurolink.addExternalMCPServer("filesystem", { command: "npx", args: [ "-y", "@modelcontextprotocol/server-filesystem", "/allowed/directory/only", // Restrict to specific directory ], }); // Use HITL for dangerous operations const neurolink = new NeuroLink({ hitl: { enabled: true, // Case-insensitive substring match against tool names dangerousActions: ["writeFile", "deleteFile", "executeCode", "shell_exec"], }, }); ``` #### 2. Permission System ```typescript // Define permissions per tool const neurolink = new NeuroLink({ tools: { permissions: { readFile: ["admin", "developer", "viewer"], writeFile: ["admin", "developer"], deleteFile: ["admin"], executeCode: ["admin"], }, }, }); // Enforce in context const result = await neurolink.generate({ input: { text: "Delete old log files" }, context: { userId: "user123", role: "viewer", // Will fail - no delete permission }, }); ``` #### 3. Audit Logging ```typescript const neurolink = new NeuroLink({ audit: { enabled: true, logAllTools: true, storage: "database", database: { url: process.env.AUDIT_DB_URL, }, }, }); // Audit log entry format { timestamp: "2025-01-01T14:30:00Z", userId: "user123", tool: "writeFile", args: { path: "/data/report.pdf", size: 1024 }, approved: true, approver: "manager@company.com", result: { success: true } } ``` ### Performance Optimization #### 1. Connection Pooling ```typescript // Reuse database connections await neurolink.addExternalMCPServer("postgres", { command: "npx", args: ["-y", "@modelcontextprotocol/server-postgres"], env: { POSTGRES_CONNECTION_STRING: process.env.DATABASE_URL, POSTGRES_POOL_SIZE: "20", // Connection pool POSTGRES_POOL_TIMEOUT: "30000", }, }); ``` #### 2. Result Caching ```typescript const neurolink = new NeuroLink({ tools: { cache: { enabled: true, ttl: 300, // 5 minutes maxSize: 1000, // Max cached results }, }, }); // Tools with read-only operations cache results const result1 = await neurolink.generate({ input: { text: "Get customer 123 details" }, }); // Cache miss - fetches from CRM const result2 = await neurolink.generate({ input: { text: "Get customer 123 details" }, }); // Cache hit - instant response ``` #### 3. Timeout Handling ```typescript await neurolink.addExternalMCPServer("slow-api", { command: "npx", args: ["-y", "slow-mcp-server"], timeout: 30000, // 30 second timeout retry: { enabled: true, maxAttempts: 3, backoff: "exponential", }, }); ``` --- ## See Also - [MCP Integration Guide](/docs/mcp/integration) - Deep dive into MCP architecture - [MCP Server Catalog](/docs/guides/mcp/server-catalog) - Complete MCP server directory - [Custom Tools](/docs/sdk/custom-tools) - Building custom MCP servers - [Enterprise HITL](/docs/features/enterprise-hitl) - HITL for tool approval workflows - [Interactive CLI](/docs/cli) - Using MCP tools in CLI loop mode - [MCP Foundation](/docs/mcp/overview) - MCP architecture documentation --- ## Memory Guide # Memory Guide > **Since**: v9.12.0 | **Status**: Stable | **Availability**: SDK ## Overview NeuroLink includes a **memory engine** powered by the `@juspay/hippocampus` SDK. Unlike conversation memory (which tracks recent turns in a session), memory maintains a **condensed summary** of durable facts about each user across all conversations. Key characteristics: - **Per-user**: Each user gets an independent memory store keyed by `userId` - **Condensed**: Memory is kept to a configurable word limit (default 50 words) via LLM-powered condensation - **Persistent**: Stored in S3, Redis, SQLite, or a custom backend — survives server restarts - **Non-blocking**: Memory storage happens in the background after each generate/stream call - **Crash-safe**: Every SDK method is wrapped in try-catch — errors are logged, never thrown ## How It Works ``` User prompt arrives │ ▼ ┌─────────────┐ │ memory.get() │ ← Retrieve condensed memory for this userId └──────┬──────┘ │ Prepend memory context to prompt ▼ ┌─────────────┐ │ LLM call │ ← generate() or stream() as normal └──────┬──────┘ │ ▼ ┌──────────────┐ │ memory.add() │ ← In background: condense old memory + new turn via LLM └──────────────┘ ``` On each `generate()` or `stream()` call: 1. **Retrieve**: `memory.get(userId)` fetches the user's condensed memory (if any) 2. **Inject**: The memory is prepended to the user's prompt as context 3. **Generate**: The LLM processes the enhanced prompt normally 4. **Store**: After the response completes, `memory.add(userId, content)` runs in the background. The SDK sends the old memory + new conversation turn to an LLM which produces a new condensed summary ## Quick Start ```typescript const neurolink = new NeuroLink({ conversationMemory: { enabled: true, memory: { enabled: true, storage: { type: "s3", bucket: "my-memory-bucket", prefix: "memory/condensed/", }, neurolink: { provider: "google-ai", model: "gemini-2.5-flash", }, maxWords: 50, }, }, }); // Memory is automatically retrieved and stored on each call const result = await neurolink.generate({ input: { text: "My name is Alice and I run a Shopify store." }, context: { userId: "user-123" }, }); // Next call — the AI already knows about Alice const result2 = await neurolink.generate({ input: { text: "What platform do I use?" }, context: { userId: "user-123" }, }); // → "You use Shopify." ``` ## Configuration The `memory` field on `conversationMemory` accepts a `Memory` object: ```typescript type Memory = HippocampusConfig & { enabled?: boolean }; ``` ### Required Fields | Field | Type | Description | | -------------------- | ------- | ------------------------------------------------------------- | | `enabled` | boolean | Set `true` to activate memory | | `storage.type` | string | Storage backend: `"s3"`, `"redis"`, `"sqlite"`, or `"custom"` | | `neurolink.provider` | string | AI provider for condensation LLM calls | | `neurolink.model` | string | Model for condensation LLM calls | ### Optional Fields | Field | Type | Default | Description | | ----------------------- | -------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `maxWords` | number | 50 | Maximum words in the condensed memory | | `prompt` | string | built-in | Custom condensation prompt (supports `{{OLD_MEMORY}}`, `{{NEW_CONTENT}}`, `{{MAX_WORDS}}` placeholders). Validated at construction — see [Template validation](#template-validation) | | `strictPrompt` | boolean | `false` | When true, a prompt template missing `{{OLD_MEMORY}}` or `{{NEW_CONTENT}}` makes the constructor throw instead of disable-and-log (at `error`) | | `shouldWrite` | function | — | Instance-level write gate — see [Write hooks](#write-hooks-shouldwrite-and-onbeforestore) | | `onBeforeStore` | function | — | Instance-level content transform/veto — see [Write hooks](#write-hooks-shouldwrite-and-onbeforestore) | | `client` | object | — | A host-managed Hippocampus client (`add/get/delete/close`). NeuroLink uses it directly instead of loading `@juspay/hippocampus` | | `neurolink.credentials` | object | inherited | Credentials for the condenser's own NeuroLink instance — see [Condenser credentials](#condenser-credentials) | | `neurolink.instance` | object | built | A host-supplied condenser (`{ generate() }`) — see [Condenser credentials](#condenser-credentials) | | `storage.bucket` | string | — | S3 bucket name (required for S3 storage) | | `storage.prefix` | string | — | S3 key prefix for memory objects | | `storage.url` | string | — | Redis connection URL (required for Redis storage) | | `storage.path` | string | — | SQLite file path (required for SQLite storage) | | `storage.onGet` | function | — | Callback to retrieve memory (required for custom storage) | | `storage.onSet` | function | — | Callback to persist memory (required for custom storage) | | `storage.onDelete` | function | — | Callback to delete memory (required for custom storage) | | `storage.onClose` | function | — | Callback for cleanup on close (optional for custom storage) | ### Storage Backends #### S3 (Recommended for production) ```typescript memory: { enabled: true, storage: { type: "s3", bucket: "my-bucket", prefix: "memory/condensed/", }, neurolink: { provider: "google-ai", model: "gemini-2.5-flash" }, } ``` Each user's memory is stored as a single S3 object at `{prefix}{userId}`. #### Redis ```typescript memory: { enabled: true, storage: { type: "redis", url: "redis://localhost:6379", }, neurolink: { provider: "openai", model: "gpt-4o-mini" }, } ``` #### SQLite (Development) ```typescript memory: { enabled: true, storage: { type: "sqlite", path: "./memory.db", }, neurolink: { provider: "google-ai", model: "gemini-2.5-flash" }, } ``` > **Note**: SQLite requires the `better-sqlite3` optional peer dependency. Install it manually: `pnpm add better-sqlite3` > **Heads up — `@juspay/hippocampus` is now an optional peer.** Starting with this release, NeuroLink no longer pulls `@juspay/hippocampus` as a hard runtime dependency (the package's own peer on `@juspay/neurolink` was dragging the deprecated `@ai-sdk/google` and `@ai-sdk/google-vertex` packages into the production graph). To enable memory in your app, install the SDK explicitly: > > ```bash > pnpm add @juspay/hippocampus > # or: npm install @juspay/hippocampus > ``` > > If memory is configured but the package is missing, NeuroLink logs a one-time `error` and disables memory rather than throwing — generation/streaming continue to work normally. #### Custom (Consumer-Managed) Delegates storage to your application via callbacks. Use this when you want to manage persistence yourself — call your own API, write to your own database, or integrate with any external system. ```typescript memory: { enabled: true, storage: { type: "custom", onGet: async (ownerId) => { // Retrieve memory from your own storage return await myDB.getMemory(ownerId); }, onSet: async (ownerId, memory) => { // Persist the condensed memory await myDB.saveMemory(ownerId, memory); }, onDelete: async (ownerId) => { // Delete memory await myDB.deleteMemory(ownerId); }, }, neurolink: { provider: "google-ai", model: "gemini-2.5-flash" }, } ``` The three callbacks (`onGet`, `onSet`, `onDelete`) are required. An optional `onClose` callback can be provided for cleanup when the SDK shuts down. **Example — file-based storage:** ```typescript const memoryDir = "./data/memory"; memory: { enabled: true, storage: { type: "custom", onGet: async (ownerId) => { try { return await readFile(join(memoryDir, `${ownerId}.txt`), "utf-8"); } catch { return null; } }, onSet: async (ownerId, memory) => { await mkdir(memoryDir, { recursive: true }); await writeFile(join(memoryDir, `${ownerId}.txt`), memory, "utf-8"); }, onDelete: async (ownerId) => { try { await unlink(join(memoryDir, `${ownerId}.txt`)); } catch { /* ignore */ } }, }, neurolink: { provider: "google-ai", model: "gemini-2.5-flash" }, } ``` ## Custom Condensation Prompt The condensation prompt controls how the LLM merges old memory with new conversation turns. You can provide a custom prompt using the `prompt` field: ```typescript memory: { enabled: true, storage: { type: "s3", bucket: "my-bucket" }, neurolink: { provider: "google-ai", model: "gemini-2.5-flash" }, prompt: `You are a memory engine. Merge the old memory with new facts into a summary of at most {{MAX_WORDS}} words. OLD_MEMORY: {{OLD_MEMORY}} NEW_CONTENT: {{NEW_CONTENT}} Condensed memory:`, maxWords: 100, } ``` ### Placeholders | Placeholder | Replaced With | | ----------------- | -------------------------------------------------------- | | `{{OLD_MEMORY}}` | The user's existing condensed memory (may be empty) | | `{{NEW_CONTENT}}` | The new conversation turn: `"User: ...\nAssistant: ..."` | | `{{MAX_WORDS}}` | The configured `maxWords` value | ### Template validation Hippocampus substitutes placeholders with `replaceAll` and requires none of them, so a typo fails silently at the LLM boundary: a template without `{{NEW_CONTENT}}` produces a memory that **never grows**, and one without `{{OLD_MEMORY}}` **overwrites the whole summary on every turn**. NeuroLink validates templates before they can do either: | Template | When it is checked | Missing `{{OLD_MEMORY}}` or `{{NEW_CONTENT}}` | Missing only `{{MAX_WORDS}}` | | ------------------------------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------ | ---------------------------- | | Instance `memory.prompt` | `new NeuroLink()` | Logs at **`error`** and **disables memory** for the instance; with `strictPrompt: true` the constructor **throws** | Warns | | `HC_CONDENSATION_PROMPT` (only when no `prompt`) | `new NeuroLink()` | Same as above | Warns | | Per-call `memory.prompt` | Inside the background write | Warns once per distinct template and **falls back to the instance prompt** for that owner | Warns once | | `additionalUsers[].prompt` | Inside the background write | Same as per-call | Warns once | An **empty or whitespace-only** template counts as unset at every level: it is not validated, never disables memory, and is **stripped before it reaches Hippocampus** — from the constructor config and from every per-call / per-owner `add()` options. Hippocampus resolves `prompt || HC_CONDENSATION_PROMPT || built-in`, so `""` would fall through on its own, but `" "` is truthy and Hippocampus 0.2.x would use it literally, as a template with no placeholders; NeuroLink omits the key so the next one down applies either way. The default is disable-and-log because every other memory failure already degrades that way. The log line is at `error`, not `warn`: warnings are hidden at the default log level (they show only with `NEUROLINK_DEBUG=true`), and a configuration that turns memory off is something the operator has to act on. Per-call fallbacks — a bad per-call template, a hook that throws, a write that fails — stay at `warn`, since the instance keeps working. `strictPrompt` is for hosts that would rather fail deployment than run with memory off: ```typescript memory: { enabled: true, prompt: myTemplate, strictPrompt: true, // throws ErrorFactory.invalidConfiguration on a fatal template } ``` The same check is exported for hosts that assemble templates at runtime: ```typescript const verdict = validateCondensationPrompt(template); // { valid: boolean; missing: ("OLD_MEMORY" | "NEW_CONTENT" | "MAX_WORDS")[]; fatal: (...)[] } ``` ## Condenser credentials Hippocampus condenses old + new memory through a NeuroLink `generate()` call. Left to itself it constructs a **bare** `new NeuroLink()` for that call — no credentials — so a host that passes provider keys via `new NeuroLink({ credentials })` rather than `process.env` gets a memory that silently never grows (the condensation error is swallowed and the old memory returned). NeuroLink now hands Hippocampus a **dedicated child instance** instead: - It inherits the parent's `credentials` (or the explicit `memory.neurolink.credentials` when set), so condensation works wherever generation works with instance-level credentials. **Per-request `credentials`** passed to `generate()` / `stream()` do **not** reach it: the child is built once per instance, and condensation runs after the response, outside the request. A multi-tenant host that holds no instance-level key gets no condensation at all — supply `memory.neurolink.credentials`, or take over condensation with `memory.neurolink.instance`. - It is a child, not the parent: routing condensation through the parent would run its MCP init, skills and middleware, emit `generation:*` on the parent emitter and add the condensation cost to the parent's session budget. - It has memory disabled, so it can never recurse into a memory write of its own. - It is built lazily on the **first condensation**, never at construction or on a read, so a read-only host pays nothing. - It goes with the host: `shutdown()` and `dispose()` release it — but only after **draining the memory writes already scheduled**, bounded by the 30 s write timeout (a write that outlives the bound is left in flight and warned about). A turn's write is deferred to `setImmediate`, so `await nl.generate(…); await nl.shutdown();` — a serverless handler, a per-request instance, a one-shot CLI run — still stores that turn. A write scheduled _after_ the release is skipped (logged at `debug`) rather than rebuilding the child after its host is gone. - Building it leaves the process-wide log sink (`logger.setEventEmitter`) exactly where it was, so another instance's log bridge keeps receiving. ```typescript memory: { enabled: true, neurolink: { provider: "openai", model: "gpt-4o-mini", // Optional: different keys for condensation than for generation. credentials: { openai: { apiKey: process.env.CONDENSER_KEY } }, }, } ``` To take over condensation entirely, pass any object with a `generate()`: ```typescript memory: { enabled: true, neurolink: { instance: { generate: async ({ input }) => ({ content: await myCondenser(input.text) }), }, }, } ``` `instance` receives exactly `{ input: { text }, provider, model, temperature, disableTools: true }` and only its `content` is read back (`HippocampusNeurolinkLike`). When set, NeuroLink builds no child and passes the object through untouched. **Hippocampus version note.** `neurolink.instance` and `neurolink.credentials` are read by `@juspay/hippocampus` ≥ 0.2.0. The peer floor is **0.2.1**, which additionally substitutes the condensation placeholders literally — with 0.2.0 a turn containing `$&` or `$'` corrupts the prompt (juspay/hippocampus#8). On an older Hippocampus the fields are ignored and condensation falls back to a bare `new NeuroLink()` that only sees keys in `process.env`. ### Bring your own client If your application already runs a Hippocampus instance (or anything with the same `add/get/delete/close` surface), hand it over and NeuroLink will not load or construct `@juspay/hippocampus` at all. `add()` and `get()` are what NeuroLink calls, and both must be functions: a client missing either — a write-only double, say — is refused at initialization with an `error` log and memory disabled, rather than failing every read silently later. `delete()` and `close()` are never called by NeuroLink. ```typescript const client = new Hippocampus({ storage: { type: "redis" } }); const neurolink = new NeuroLink({ conversationMemory: { enabled: true, memory: { enabled: true, client }, }, }); ``` `client` may also be a **factory** — `(config) => new Hippocampus(config)` — which receives the `HippocampusConfig` NeuroLink assembled, including the credentialed child under `neurolink.instance`. That is the way to run your own client class (a subclass, a pinned version, a test double) on exactly what `new Hippocampus(config)` would get. A plain instance is used as-is: wiring its condenser is then the host's job. ## Integration with generate() and stream() Memory integrates automatically with both `generate()` and `stream()`: - **Before the LLM call**: Memory is retrieved and prepended to the input text - **After the LLM call**: The conversation turn is stored in the background via `setImmediate()` - **Timeouts**: Retrieval has a 3-second timeout; storage has a 10-second timeout (includes LLM condensation) - **Errors are non-blocking**: If memory retrieval or storage fails, the generate/stream call continues normally ### Requirements For memory to activate on a call, all three conditions must be met: 1. `memory.enabled` is `true` in the config 2. `options.context.userId` is provided in the generate/stream call 3. The response has non-empty content (for write) ### Per-Call Memory Control When memory is globally enabled, it is active for every `generate()` and `stream()` call by default. You can override this behavior on a **per-call basis** using the `memory` option without changing the global config. **Available options** (`MemoryCallOptions`, identical for `generate()` and `stream()`): | Option | Type | Default | Description | | ----------------- | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `enabled` | boolean | `true` | Master toggle — when `false`, both read and write are skipped | | `read` | boolean | `true` | Whether to read past memory and prepend it to the prompt | | `write` | boolean | `true` | Whether to write this conversation turn into memory after the call | | `prompt` | string | instance | Condensation prompt for the **primary owner** on this call. Must contain `{{OLD_MEMORY}}` and `{{NEW_CONTENT}}` (see [Template validation](#template-validation)) | | `maxWords` | number | instance | Word cap for the primary owner's condensed memory on this call | | `shouldWrite` | function | — | Per-call write gate — see [Write hooks](#write-hooks-shouldwrite-and-onbeforestore) | | `onBeforeStore` | function | — | Per-call content transform/veto — see [Write hooks](#write-hooks-shouldwrite-and-onbeforestore) | | `additionalUsers` | array | — | Extra owners to read/write — see [Multi-User Memory](#multi-user-memory) | > **Note:** These options only take effect when the global memory SDK is enabled. If global memory is disabled, per-call options have no effect. **Precedence:** 1. **Global config** — Is memory enabled globally? If not, per-call options are ignored. 2. **`enabled`** — Master per-call toggle. If `false`, both read and write are skipped regardless of individual flags. 3. **`read` / `write`** — Fine-grained control over individual operations. 4. **`prompt` / `maxWords`** — per-call > instance `conversationMemory.memory.prompt` / `maxWords` > Hippocampus built-in default. Before this option existed only `additionalUsers` could override the prompt; the primary owner always condensed with the instance template. #### Per-call prompt for the primary owner ```typescript await neurolink.generate({ input: { text: "I switched the store to Stripe last week." }, context: { userId: "user-123" }, memory: { prompt: `Keep only durable facts about the user's business. OLD_MEMORY: {{OLD_MEMORY}} NEW_CONTENT: {{NEW_CONTENT}} Condensed memory (max {{MAX_WORDS}} words):`, maxWords: 80, }, }); ``` ### Write hooks: `shouldWrite` and `onBeforeStore` Two hooks let a host decide **whether** a turn is remembered and **what** text reaches the condenser. Both are accepted per call (`memory.shouldWrite` / `memory.onBeforeStore`) and on the instance (`conversationMemory.memory.shouldWrite` / `.onBeforeStore`). When both are set for the same hook, **the per-call one wins for that call** — the instance hook is not run. ```typescript type MemoryTurn = { prompt: string; // the caller's original prompt (before memory context was prepended) response: string; // the assistant's final text, trimmed userId: string; // context.userId sessionId?: string; // context.sessionId provider?: string; model?: string; toolsUsed?: string[]; // stream path: this request's own stream result only usage?: TokenUsage; // generate path only finishReason?: string; // generate path only }; shouldWrite?: (turn: MemoryTurn) => boolean | Promise; onBeforeStore?: (content: string, turn: MemoryTurn) => string | null | Promise; ``` - `shouldWrite` runs first. `false` skips **every** `add()` for the turn — the primary owner and all `additionalUsers`. - `onBeforeStore` receives the default `"User: …\nAssistant: …"` rendering. Return a replacement string, or `null` to skip the write. The returned string is what every owner's `add()` receives. - Both run **inside the deferred background write** (after `setImmediate`), so an async hook never sits on the response path. - A hook that **throws** is logged at `warn` and the write is **skipped** — a missed memory is recoverable, a polluted condensed summary is not. A non-string, non-null return from `onBeforeStore` is treated the same way. ```typescript const neurolink = new NeuroLink({ conversationMemory: { enabled: true, memory: { enabled: true, // Instance-wide: never remember turns that were pure tool plumbing. shouldWrite: (turn) => (turn.toolsUsed?.length ?? 0) === 0 || turn.response.length > 200, // Instance-wide: strip anything that looks like a card number. onBeforeStore: (content) => content.replace(/\b\d{13,19}\b/g, "[redacted]"), }, }, }); // Per call: override the gate for a seeding call, keep the instance redaction. await neurolink.generate({ input: { text: "My name is Alice. I run a Shopify store." }, context: { userId: "user-123" }, memory: { shouldWrite: () => true }, }); ``` > **Follow-up (not implemented):** a decide-powered durability gate — one `tryDecide()` question per turn ("does this turn contain a fact worth remembering across conversations?") wired in as the default `shouldWrite` when a decision provider is configured, failing open to "write" without one, exactly like the other `decide` consumers. The hook surface above is the seam it would plug into; today the gate is entirely host-defined. #### Read memory but don't write Use when you want past context but don't want this call stored — e.g., code review where you'll store a curated summary later. ```typescript const result = await neurolink.generate({ input: { text: "Review this pull request for security issues" }, memory: { read: true, write: false }, context: { userId: "user-123" }, }); ``` #### Write memory but don't read Use for onboarding or seeding memory without injecting past context into the prompt. ```typescript const result = await neurolink.generate({ input: { text: "My name is Alice. I work on the payments team and use Python.", }, memory: { read: false, write: true }, context: { userId: "user-123" }, }); ``` #### Skip memory entirely Use for operational or utility calls where memory adds noise. ```typescript const result = await neurolink.generate({ input: { text: "Fetch the latest PR comments from GitHub" }, memory: { enabled: false }, context: { userId: "user-123" }, }); ``` #### Per-call control with stream() The same `memory` option works identically in `stream()`. ```typescript const stream = await neurolink.stream({ input: { text: "Summarize today's standup notes" }, memory: { read: true, write: false }, context: { userId: "user-123" }, }); ``` ## Multi-User Memory Retrieve and store memory for multiple users in a single `generate()` or `stream()` call. This enables **layered memory** — combining a user's personal context with org-level policies, team context, or any other memory scope. The primary user is always determined by `context.userId`. Additional users are specified via `memory.additionalUsers`. Memory for all users (primary + additional) is fetched and stored in parallel. ### Quick Start ```typescript const result = await neurolink.stream({ input: { text: "How should I handle PCI data in our API?" }, context: { userId: "user-alice" }, memory: { additionalUsers: [ { userId: "org-acme", label: "Organization Policy", prompt: `Extract only compliance requirements, security policies, and org-level decisions. OLD_MEMORY: {{OLD_MEMORY}} NEW_CONTENT: {{NEW_CONTENT}} Condensed memory (max {{MAX_WORDS}} words):`, maxWords: 100, }, { userId: "team-payments", label: "Team Context", }, ], }, }); ``` ### Context Format When multiple users' memories are retrieved, they are formatted with labels and injected into the prompt: ``` Context from previous conversations: [User] Alice is a senior engineer on the payments team, prefers Python. [Organization Policy] PCI-DSS Level 1 compliance required. All cardholder data must be encrypted at rest and in transit. [Team Context] Payments team uses microservices architecture with Stripe integration. Current user's request: How should I handle PCI data in our API? ``` The primary user's label is always `"User"`. Additional users use the `label` field, falling back to `userId` if not set. ### Per-User Condensation Each additional user can specify a custom `prompt` and `maxWords` for its condensation strategy. This is useful when different memory scopes need different extraction rules — e.g. personal preferences vs compliance policies. The `prompt` must include `{{OLD_MEMORY}}` and `{{NEW_CONTENT}}` (and should include `{{MAX_WORDS}}`). A per-user template missing either structural placeholder is logged once and that user falls back to the instance prompt — see [Template validation](#template-validation). The primary owner's prompt is set with the per-call `memory.prompt` instead — see [Per-Call Memory Control](#per-call-memory-control). ### Selective Read/Write Control which additional users participate in read and write independently: ```typescript memory: { additionalUsers: [ { userId: "org-acme", label: "Org Policy", write: false }, // read-only { userId: "team-x", label: "Team", read: false }, // write-only ], } ``` ### AdditionalMemoryUser Options | Field | Type | Default | Description | | ---------- | ------- | -------- | -------------------------------------------------------------------------------------------------- | | `userId` | string | required | The owner ID to retrieve/store memory for | | `label` | string | userId | Label used in the formatted memory context | | `read` | boolean | `true` | Whether to read this user's memory | | `write` | boolean | `true` | Whether to write conversation into this user's memory | | `prompt` | string | instance | Custom condensation prompt for this user (validated; falls back to the instance prompt when fatal) | | `maxWords` | number | instance | Max words for this user's condensed memory | ## Environment Variables The `@juspay/hippocampus` SDK reads these environment variables: | Variable | Default | Description | | ------------------------ | -------- | ----------------------------------------------------------- | | `HC_LOG_LEVEL` | `warn` | SDK log level: `debug`, `info`, `warn`, `error` | | `HC_CONDENSATION_PROMPT` | built-in | Default condensation prompt (overridden by config `prompt`) | ## Error Handling The memory SDK is designed to **never crash the host application**: - Every public method (`get()`, `add()`, `delete()`, `close()`) is wrapped in try-catch - Errors are logged via `logger.warn()` and safe defaults are returned - `get()` returns `null` on error - `add()` silently fails on error - Storage initialization errors result in memory being disabled (returns `null` from `ensureMemoryReady()`) ## Type Exports NeuroLink re-exports the memory types for use in host applications: ```typescript HippocampusMemory, HippocampusNeurolinkLike, MemoryCallOptions, MemoryTurn, MemoryShouldWriteHook, MemoryBeforeStoreHook, CondensationPromptValidation, MemoryCustomStorageConfig, } from "@juspay/neurolink"; // HippocampusMemory = HippocampusConfig & MemoryWriteHooks & { enabled?, client?, strictPrompt? } // MemoryCallOptions = the per-call `memory` block on GenerateOptions and StreamOptions // MemoryTurn = what shouldWrite / onBeforeStore receive // HippocampusNeurolinkLike = { generate({ input, provider?, model?, temperature?, disableTools? }) } // MemoryCustomStorageConfig = { type: 'custom', onGet, onSet, onDelete, onClose? } ``` ## See Also - **[Conversation Memory](/docs/memory/conversation)** - Session-based conversation history - **[Memory Integration](/docs/advanced/memory-integration)** - Advanced hippocampus configuration and patterns - **[Context Compaction](/docs/features/context-compaction)** - Automatic context window management - **[Context Summarization](/docs/memory/summarization)** - Conversation compression - **[Per-Request Credentials](/docs/features/per-request-credentials)** - How `credentials` flow to providers. Only instance-level `credentials` (or `memory.neurolink.credentials`) reach the memory condenser; per-request `credentials` do not --- ## Multimodal Chat Experiences # Multimodal Chat Experiences NeuroLink provides full multimodal pipelines so you can mix text, URLs, and local images in a single interaction. The CLI, SDK, and loop sessions all use the same message builder, ensuring parity across workflows. ## Video Generation {#video-generation} NeuroLink supports **video generation** from images using Google's Veo 3.1 model via Vertex AI. Transform static images into 8-second videos with synchronized audio. ```typescript const result = await neurolink.generate({ input: { text: "Smooth camera movement showcasing the product", images: [await readFile("./product.jpg")], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "1080p" } }, }); if (result.video) { await writeFile("output.mp4", result.video.data); } ``` **See:** [Video Generation Guide](/docs/features/video-generation) for complete documentation. ## PPT Generation {#ppt-generation} NeuroLink supports **AI-powered PowerPoint generation** from text prompts. Create professional presentations with 35 slide types, 5 themes, and optional AI-generated images. ```typescript const result = await neurolink.generate({ input: { text: "Quarterly Business Report: Revenue growth, key metrics, and 2026 outlook", }, provider: "vertex", model: "gemini-2.5-pro", output: { mode: "ppt", ppt: { pages: 15, theme: "corporate", audience: "business", generateAIImages: true, }, }, }); if (result.ppt) { console.log(`Presentation saved: ${result.ppt.filePath}`); } ``` **See:** [PPT Generation Guide](/docs/features/ppt-generation) for complete documentation. ## Images {#images} NeuroLink provides comprehensive image support across all vision-capable providers. Images can be provided as local file paths, HTTPS URLs, or Buffer objects, and are automatically converted to the provider's required encoding format. ## What You Get - **Unified CLI flag** – `--image` accepts multiple file paths or HTTPS URLs per request. - **SDK parity** – pass `input.images` (buffers, file paths, or URLs) and stream structured outputs. - **Provider fallbacks** – orchestration automatically retries compatible multimodal models. - **Streaming support** – `neurolink stream` renders partial responses while images upload in the background. :::tip[Format Support] The image input accepts three formats: **Buffer objects** (from `readFileSync`), **local file paths** (relative or absolute), or **HTTPS URLs**. All formats are automatically converted to the provider's required encoding. ::: ## Supported Providers & Models :::warning[Provider Compatibility] Not all providers support multimodal inputs. Verify your chosen model has the `vision` capability using `npx @juspay/neurolink models list --capability vision`. Unsupported providers will return an error or ignore image inputs. ::: | Provider | Recommended Models | Notes | | ---------------------- | ---------------------------------------- | --------------------------------------------------------- | | `google-ai`, `vertex` | `gemini-2.5-pro`, `gemini-2.5-flash` | Local files and URLs supported. | | `openai`, `azure` | `gpt-4o`, `gpt-4o-mini` | Requires `OPENAI_API_KEY` or Azure deployment name + key. | | `anthropic`, `bedrock` | `claude-3.5-sonnet`, `claude-3.7-sonnet` | Bedrock needs region + credentials. | | `litellm` | Any upstream multimodal model | Ensure LiteLLM server exposes `vision` capability. | > Use `npx @juspay/neurolink models list --capability vision` to see the full list from `config/models.json`. ## Prerequisites 1. Provider credentials with vision/multimodal permissions. 2. Latest CLI (`npm`, `pnpm`, or `npx`) or SDK. 3. Optional: Redis if you want images stored alongside loop-session history. ## CLI Quick Start ```bash # Attach a local file (auto-converted to base64) npx @juspay/neurolink generate "Describe this interface" \ --image ./designs/dashboard.png --provider google-ai # Reference a remote URL (downloaded on the fly) npx @juspay/neurolink generate "Summarise these guidelines" \ --image https://example.com/policy.pdf --provider openai --model gpt-4o # Mix multiple images and enable analytics/evaluation npx @juspay/neurolink generate "QA review" \ --image ./screenshots/before.png \ --image ./screenshots/after.png \ --enableAnalytics --enableEvaluation --format json ``` ### Streaming & Loop Sessions ```bash # Stream while uploading a diagram npx @juspay/neurolink stream "Explain this architecture" \ --image ./diagrams/system.png # Persist images inside loop mode (Redis auto-detected when available) npx @juspay/neurolink loop --enable-conversation-memory > set provider google-ai > generate Compare the attached charts --image ./charts/q3.png ``` ## SDK Usage ```typescript const neurolink = new NeuroLink({ enableOrchestration: true }); // (1)! const result = await neurolink.generate({ input: { text: "Provide a marketing summary of these screenshots", // (2)! images: [ // (3)! readFileSync("./assets/homepage.png"), // (4)! "https://example.com/reports/nps-chart.png", // (5)! ], }, provider: "google-ai", // (6)! enableEvaluation: true, // (7)! region: "us-east-1", }); console.log(result.content); console.log(result.evaluation?.overallScore); ``` 1. Enable provider orchestration for automatic multimodal fallbacks 2. Text prompt describing what you want from the images 3. Array of images in multiple formats 4. Local file as Buffer (auto-converted to base64) 5. Remote URL (downloaded and encoded automatically) 6. Choose a vision-capable provider 7. Optionally evaluate the quality of multimodal responses ### Image Alt Text for Accessibility NeuroLink supports alt text for images, which is helpful for accessibility (screen readers) and providing additional context to AI models. Alt text is automatically included as context in the prompt sent to AI providers. ```typescript const neurolink = new NeuroLink(); // Using images with alt text for accessibility const result = await neurolink.generate({ input: { text: "Compare these two charts and summarize the trends", images: [ // (1)! { data: readFileSync("./charts/q1-revenue.png"), altText: "Q1 2024 revenue chart showing 15% growth", // (2)! }, { data: "https://example.com/charts/q2-revenue.png", altText: "Q2 2024 revenue chart showing 22% growth", // (3)! }, ], }, provider: "openai", }); ``` 1. Images can be objects with `data` and `altText` properties 2. Alt text for local file - helps AI understand the image context 3. Alt text for remote URL - provides additional context for accessibility You can also mix simple images with alt-text-enabled images: ```typescript const result = await neurolink.generate({ input: { text: "Analyze these images", images: [ readFileSync("./simple-image.png"), // Simple buffer (no alt text) "https://example.com/image.jpg", // Simple URL (no alt text) { data: readFileSync("./important-chart.png"), altText: "Critical KPI dashboard for Q3", // With alt text }, ], }, provider: "google-ai", }); ``` :::tip[Alt Text Best Practices] - Keep alt text concise but descriptive (under 125 characters is ideal) - Focus on the key information the image conveys - Alt text is automatically included as context in the prompt, helping AI models better understand the images ::: Use `stream()` with the same structure when you need incremental tokens: ```typescript const stream = await neurolink.stream({ input: { text: "Walk through the attached floor plan", images: ["./plans/level1.jpg"], // (1)! }, provider: "openai", // (2)! }); for await (const chunk of stream) { // (3)! process.stdout.write(chunk.text ?? ""); } ``` 1. Accepts file path, Buffer, or HTTPS URL 2. OpenAI's GPT-4o and GPT-4o-mini support vision 3. Stream text responses while image uploads in background ## Configuration & Tuning - **Image sources** – Local paths are resolved relative to `process.cwd()`. URLs must be HTTPS. - **Size limits** – Providers cap images at ~20 MB. Resize or compress large assets before sending. - **Multiple images** – Order matters; the builder interleaves captions in the order provided. - **Region routing** – Set `region` on each request (e.g., `us-east-1`) for providers that enforce locality. - **Loop sessions** – Images uploaded during `loop` are cached per session; call `clear session` to reset. - **Alt text** – Add alt text to images for accessibility; the text is included as context for AI models. ## Best Practices - Provide short captions in the prompt describing each image (e.g., "see `before.png` on the left"). - **Use alt text** for images that convey important information, especially for accessibility compliance. - Combine analytics + evaluation to benchmark multimodal quality before rolling out widely. - Cache remote assets locally if you reuse them frequently to avoid repeated downloads. - Stream when presenting content to end-users; use `generate` when you need structured JSON output. ## CSV File Support ### Quick Start ```bash # Auto-detect CSV files npx @juspay/neurolink generate "Analyze sales trends" \ --file ./sales_2024.csv # Explicit CSV with options npx @juspay/neurolink generate "Summarize data" \ --csv ./data.csv \ --csv-max-rows 500 \ --csv-format raw ``` ### SDK Usage ```typescript // Auto-detect (recommended) await neurolink.generate({ input: { text: "Analyze this data", files: ["./data.csv", "./chart.png"], }, }); // Explicit CSV await neurolink.generate({ input: { text: "Compare quarters", csvFiles: ["./q1.csv", "./q2.csv"], }, csvOptions: { maxRows: 1000, formatStyle: "raw", }, }); ``` ### Format Options - **raw** (default) - Best for large files, minimal token usage - **json** - Structured data, easier parsing, higher token usage - **markdown** - Readable tables, good for small datasets (\<100 rows) ### Best Practices - Use raw format for large files to minimize token usage - Use JSON format for structured data processing - Limit to 1000 rows by default (configurable up to 10K) - Combine CSV with visualization images for comprehensive analysis - Works across supported providers (not just vision-capable models) ## PDF File Support ### Quick Start ```bash # Auto-detect PDF files npx @juspay/neurolink generate "Summarize this report" \ --file ./financial-report.pdf \ --provider vertex # Explicit PDF processing npx @juspay/neurolink generate "Extract key terms" \ --pdf ./contract.pdf \ --provider anthropic # Multiple PDFs npx @juspay/neurolink generate "Compare these documents" \ --pdf ./version1.pdf \ --pdf ./version2.pdf \ --provider vertex ``` ### SDK Usage ```typescript // Auto-detect (recommended) await neurolink.generate({ input: { text: "Analyze this document", files: ["./report.pdf", "./data.csv"], }, provider: "vertex", }); // Explicit PDF await neurolink.generate({ input: { text: "Compare Q1 and Q2 reports", pdfFiles: ["./q1-report.pdf", "./q2-report.pdf"], }, provider: "anthropic", }); // Streaming with PDF const stream = await neurolink.stream({ input: { text: "Summarize this contract", pdfFiles: ["./contract.pdf"], }, provider: "vertex", }); ``` ### Supported Providers | Provider | Max Size | Max Pages | Notes | | --------------------- | -------- | --------- | ------------------------------- | | **Google Vertex AI** | 5 MB | 100 | `gemini-1.5-pro` recommended | | **Anthropic** | 5 MB | 100 | `claude-3-5-sonnet` recommended | | **AWS Bedrock** | 5 MB | 100 | Requires AWS credentials | | **Google AI Studio** | 2000 MB | 100 | Best for large files | | **OpenAI** | 10 MB | 100 | `gpt-4o`, `gpt-4o-mini`, `o1` | | **Azure OpenAI** | 10 MB | 100 | Uses OpenAI Files API | | **LiteLLM** | 10 MB | 100 | Depends on upstream model | | **OpenAI Compatible** | 10 MB | 100 | Depends on upstream model | | **Mistral** | 10 MB | 100 | Native PDF support | | **Hugging Face** | 10 MB | 100 | Native PDF support | **Not supported:** Ollama ### Best Practices - **Choose the right provider**: Use Vertex AI or Anthropic for best results - **Check file size**: Most providers limit to 5MB, AI Studio supports up to 2GB - **Use streaming**: For large documents, streaming gives faster initial results - **Combine with other files**: Mix PDF with CSV data and images for comprehensive analysis - **Be specific in prompts**: "Extract all monetary values" vs "Tell me about this PDF" ### Token Usage PDFs consume significant tokens: - **Text-only mode**: ~1,000 tokens per 3 pages - **Visual mode**: ~7,000 tokens per 3 pages Set appropriate `maxTokens` for PDF analysis (recommended: 2000-8000 tokens). ## Troubleshooting | Symptom | Action | | ---------------------------------- | --------------------------------------------------------------------------------- | | `Image not found` | Check relative paths from the directory where you invoked the CLI. | | `Provider does not support images` | Switch to a model listed in the table above or enable orchestration. | | `Error downloading image` | Ensure the URL responds with status 200 and does not require auth. | | `Large response latency` | Pre-compress images and reduce resolution to under 2 MP when possible. | | `Streaming ends early` | Disable tools (`--disableTools`) to avoid tool calls that may not support vision. | ## Related Features **Content Generation:** - [PPT Generation](/docs/features/ppt-generation) – AI-powered PowerPoint presentations with 35 slide types - [Video Generation](/docs/features/video-generation) – Generate videos from images with Veo 3.1 **Document Processing:** - [Office Documents](/docs/features/office-documents) – DOCX, PPTX, XLSX processing for Bedrock, Vertex, Anthropic - [PDF Support](/docs/features/pdf-support) – PDF document processing for visual analysis - [CSV Support](/docs/features/csv-support) – CSV file processing with auto-detection **Q4 2025 Features:** - [Guardrails Middleware](/docs/features/guardrails) – Content filtering for multimodal outputs - [Auto Evaluation](/docs/features/auto-evaluation) – Quality scoring for vision-based responses **Documentation:** - [CLI Commands](/docs/cli/commands) – CLI flags & options - [SDK API Reference](/docs/sdk/api-reference) – Generate/stream APIs - [Troubleshooting](/docs/reference/troubleshooting) – Extended error catalogue --- ## Multimodal Capabilities Guide # Multimodal Capabilities Guide NeuroLink provides comprehensive multimodal support, allowing you to combine text with various media types in a single AI interaction. This guide covers all supported input types, provider capabilities, and best practices. ## Overview **Supported Input Types:** - **Images** - JPEG, PNG, GIF, WebP, AVIF, HEIC (vision-capable models) - **PDFs** - Document analysis and content extraction - **CSV/Spreadsheets** - Data analysis and tabular content processing - **Audio** - Transcription, analysis, and real-time voice input ([Audio Input Guide](/docs/features/audio-input)) - **Documents** - Excel, Word, RTF, OpenDocument formats ([File Processors Guide](/docs/features/file-processors)) - **Data Files** - JSON, YAML, XML with validation and formatting - **Markup** - HTML, SVG, Markdown with security sanitization - **Source Code** - 50+ programming languages with syntax detection All multimodal inputs work seamlessly across both the CLI and SDK, with automatic format detection and provider-specific optimization. > **New in 2026:** NeuroLink now supports 17+ file types through the ProcessorRegistry system. See the [File Processors Guide](/docs/features/file-processors) for comprehensive documentation. ------------------ | --------- | ------------------------------------------------------ | ---------- | -------- | ------------------------------------ | | **OpenAI** | ✅ | `gpt-4o`, `gpt-4o-mini`, `gpt-5.2` | 10 | ~20 MB | Best for general vision tasks | | **Azure OpenAI** | ✅ | `gpt-4o`, `gpt-4o-mini` | 10 | ~20 MB | Same as OpenAI | | **Google AI Studio** | ✅ | `gemini-2.5-pro`, `gemini-2.5-flash`, `gemini-3-flash` | 16 | ~20 MB | Excellent for visual reasoning | | **Google Vertex AI** | ✅ | `gemini-2.5-pro`, `gemini-2.5-flash`, Claude models | 16/20 | ~20 MB | Gemini: 16 images, Claude: 20 images | | **Anthropic** | ✅ | `claude-3.5-sonnet`, `claude-3.7-sonnet` | 20 | ~20 MB | Strong visual understanding | | **AWS Bedrock** | ✅ | Claude models | 20 | ~20 MB | Same as Anthropic | | **Ollama** | ✅ | `llava`, `bakllava`, `llava-phi3` | 10 | Varies | Local vision models | | **LiteLLM** | ✅ | Depends on upstream | 10 | Varies | Proxy to vision-capable models | | **Mistral** | ✅ | `pixtral-12b-2409`, `pixtral-large-2411` | 10 | ~20 MB | Multimodal Mistral models | | **OpenRouter** | ✅ | Depends on model | 10 | Varies | Routes to various vision models | | **Hugging Face** | ⚠️ | Limited | Varies | Varies | Model-dependent | | **AWS SageMaker** | ❌ | N/A | - | - | Not supported | | **OpenAI Compatible** | ⚠️ | Depends on endpoint | Varies | Varies | Server-dependent | **Legend:** - ✅ Full support with multiple models - ⚠️ Limited or server-dependent support - ❌ Not supported ### PDF Documents | Provider | Supported | Max Size | Max Pages | Processing Mode | Notes | | --------------------- | --------- | -------- | --------- | ---------------- | --------------------------------------- | | **Google Vertex AI** | ✅ | 5 MB | 100 | Native PDF | Best for document analysis | | **Anthropic** | ✅ | 5 MB | 100 | Native PDF | Claude excels at document understanding | | **AWS Bedrock** | ✅ | 5 MB | 100 | Native PDF | Via Claude models | | **Google AI Studio** | ✅ | 2000 MB | 100 | Native PDF | Handles very large files | | **OpenAI** | ✅ | 10 MB | 100 | Files API | `gpt-4o`, `gpt-4o-mini`, `o1` | | **Azure OpenAI** | ✅ | 10 MB | 100 | Files API | Uses OpenAI Files API | | **LiteLLM** | ✅ | 10 MB | 100 | Proxy | Depends on upstream model | | **OpenAI Compatible** | ✅ | 10 MB | 100 | Varies | Server-dependent | | **Mistral** | ✅ | 10 MB | 100 | Native PDF | Native support | | **Hugging Face** | ✅ | 10 MB | 100 | Model-dependent | Varies by model | | **Ollama** | ❌ | - | - | - | Not supported | | **OpenRouter** | ⚠️ | Varies | Varies | Depends on model | Route-dependent | | **AWS SageMaker** | ❌ | - | - | - | Not supported | ### CSV/Spreadsheet Data | Provider | Supported | Max Rows | Format Options | Notes | | ----------------------- | --------- | -------- | ------------------- | --------------------------------- | | **Supported Providers** | ✅ | 10,000 | raw, json, markdown | Broad support - processed as text | CSV support works across **supported providers** because files are converted to text before sending to the AI model. The file is parsed and formatted (raw CSV, JSON, or Markdown table) before inclusion in the prompt. **Format Recommendations:** - **Raw format** - Best for large files (minimal token usage) - **JSON format** - Best for structured data processing - **Markdown format** - Best for small datasets (\ **ffmpeg is optional, and its absence is not symmetric.** Frame extraction > shells out to ffmpeg at runtime. Without it a video attached to a > frame-extraction provider yields the metadata summary and nothing visual — > no error, just an empty `keyframes` array. Native delivery needs no ffmpeg > at all, so on a machine without it Gemini still receives the whole clip. #### Supported containers `.mp4`, `.webm`, `.mov`, `.avi`, `.mkv`, `.mpeg`, `.flv`, `.wmv`, `.3gp` and the other formats in the detector's video registry are all accepted for frame extraction. Inline delivery is narrower — it is limited to the containers Gemini reads directly (mp4, mpeg, mov, avi, flv, webm, wmv, 3gpp) — and a container outside that set falls back to keyframes rather than being re-encoded. Transcoding a long recording mid-request costs minutes of CPU for a payload that would usually breach the inline ceiling anyway. ## Image Input > **Security:** an image or file given as a URL is fetched only over HTTPS from > a public host, with redirects re-checked per hop; one given as a path is read > from anywhere unless `attachments.allowedRoots` is set. Both are controlled > by the `attachments` constructor option — see > [Attachment Security](/docs/features/attachment-security). ### Quick Start **CLI:** ```bash # Single image npx @juspay/neurolink generate "Describe this interface" \ --image ./designs/dashboard.png --provider google-ai # Remote URL npx @juspay/neurolink generate "Analyze this diagram" \ --image https://example.com/architecture.png --provider openai # Multiple images npx @juspay/neurolink generate "Compare these screenshots" \ --image ./before.png \ --image ./after.png \ --provider anthropic ``` **SDK:** ```typescript const neurolink = new NeuroLink({ enableOrchestration: true }); const result = await neurolink.generate({ input: { text: "Analyze these product screenshots", images: [ readFileSync("./homepage.png"), // Local file as Buffer "https://example.com/chart.png", // Remote URL ], }, provider: "google-ai", }); ``` ### Image Formats Supported **Accepted formats:** - JPEG (`.jpg`, `.jpeg`) - PNG (`.png`) - GIF (`.gif`) - WebP (`.webp`) - AVIF (`.avif`) - detected from content (`avif`/`avis`/`avio` brands) as well as extension - BMP (`.bmp`), TIFF (`.tif`, `.tiff`) - detected from content - HEIC (`.heic`, `.heif`) - detected from HEIC/HEIF content brands as well as extension; unsupported provider formats still require PNG/JPEG conversion The MIME type is sniffed from the buffer's magic bytes, not assumed from the filename. A buffer whose bytes match no known image format is labeled `application/octet-stream` (with a warning) rather than silently mislabeled as JPEG. **Input methods:** - **Buffer objects** - `readFileSync()` from Node.js - **Local file paths** - Relative or absolute paths - **HTTPS URLs** - Remote images (auto-downloaded) ### Image Alt Text (Accessibility) NeuroLink supports alt text for images, improving accessibility and providing additional context to AI models. ```typescript const result = await neurolink.generate({ input: { text: "Compare these revenue charts", images: [ { data: readFileSync("./q1-revenue.png"), altText: "Q1 2024 revenue chart showing 15% growth", }, { data: "https://example.com/q2-revenue.png", altText: "Q2 2024 revenue chart showing 22% growth", }, ], }, provider: "openai", }); ``` **Alt text best practices:** - Keep concise (under 125 characters ideal) - Focus on key information the image conveys - Alt text is automatically included as context in prompts ### Image Size Limits **Provider-specific limits:** - Most providers: ~20 MB per image - Recommended: Resize images to : ` warning says which. A Gemini provider does not need it while the clip is delivered natively, since that includes the audio track; a clip that falls back to keyframes (over the inline ceiling) loses its speech unless `--transcribe-audio` is set. Embedded **subtitle tracks** are extracted separately and included whenever they exist, with or without `transcribeAudio`. ### Asking which mechanism applies The capability table is exported, so a caller can ask before sending — useful for choosing a provider, or for budgeting. ```typescript estimateVideoTokens, getVideoProviderConfig, supportsNativeVideo, } from "@juspay/neurolink"; supportsNativeVideo("google-ai"); // true supportsNativeVideo("openai"); // false getVideoProviderConfig("nope"); // null — not described, not "takes frames" // Duration drives the native price; frame count drives the other one. estimateVideoTokens({ provider: "google-ai", durationSec: 60 }); // ~15,600 estimateVideoTokens({ provider: "openai", durationSec: 60, frameCount: 8 }); // ~2,000 ``` ### Best practices - **Ask an audio question of a Gemini provider only.** Nothing on the frame path can hear the clip, so "what was said" has no answer there. - **Keep clips under 14 MB when you want native delivery.** Re-encoding a screen recording at a lower bitrate usually gets a long clip under the ceiling without losing anything a model would read. - **Raise `frames` rather than `quality` for detail over time.** Frames cost roughly 250 tokens each regardless of quality; more of them is what buys coverage of a clip where things change. - **Lower `frames` for local runtimes.** Ollama and llama.cpp hold every frame in the same memory as the model; four is the practical default. ### Troubleshooting | Symptom | Cause | Fix | | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | Model describes the file but not its content | No keyframes extracted — ffmpeg missing — and the provider takes frames | Install ffmpeg, or use a Gemini provider, which needs none | | `Sending keyframes instead of the clip` in the logs | The clip failed the inline gate; the reason is on the same line | Shorten or re-encode it, or accept the frames | | Model cannot hear speech on a Gemini provider | The clip exceeded the inline ceiling and fell back to frames | Get the source under 14 MB, or pass `--transcribe-audio` | | `--transcribe-audio` produced no transcript | The `No transcript for` warning names the reason: no audio track, no speech-to-text backend configured, or audio over 25 MB | Configure an engine (see the transcribe guide), or split the recording | | Only the first seconds of a long clip are described | The frame budget was hit before the end | Raise `frames`; the interval then spreads evenly across the whole clip | --- ## Combining Multiple Input Types NeuroLink excels at combining different media types in a single request. ### Mixed Media Example ```typescript const result = await neurolink.generate({ input: { text: "Analyze this product launch: review the presentation, compare sales data, and assess the promotional materials", pdfFiles: ["./presentation.pdf"], // Slides csvFiles: ["./sales-data.csv"], // Numbers images: [ readFileSync("./promo-banner.png"), // Marketing material "https://example.com/ad-campaign.jpg", ], }, provider: "vertex", // Supports all input types }); ``` ### Streaming with Multimodal ```typescript const stream = await neurolink.stream({ input: { text: "Analyze this floor plan and cost breakdown", images: ["./floor-plan.jpg"], csvFiles: ["./costs.csv"], }, provider: "google-ai", }); for await (const chunk of stream) { process.stdout.write(chunk.text ?? ""); } ``` ### Batch with Multimodal (CLI) The `batch` command supports `--image`, `--csv`, `--pdf`, and `--video`. The file(s) are attached **identically to every prompt** in the batch (a one-line notice is printed to **stderr**, unconditionally — it is not suppressed by `--quiet`, so it never corrupts `--format json` output written to stdout): ```bash neurolink batch questions.txt --csv sales.csv --format json ``` > `--file` (auto-detect) is **not** available in `batch`, because it collides with the `` positional (the prompts-list path). Use the explicit `--image` / `--csv` / `--pdf` / `--video` flags instead. ### File validation & troubleshooting (CLI) Before any provider call, the CLI validates local file inputs across `generate`, `stream`, and `batch`: - A path that points at a **directory**, doesn't exist, or can't be read (e.g. a permissions error) is rejected up front with a clear error and troubleshooting hints — no cryptic `EISDIR`/`EACCES` deep in processing. This also applies to the `batch` `` prompts-list positional itself. - A **large** file (images > 10 MB, CSV/PDF > 50 MB) prints a non-blocking warning to **stderr**. Like the batch attachment notice, this is unconditional — visible without `--debug` and regardless of `--quiet` — and never mixes into stdout, so `--format json` output stays valid JSON even when large-file warnings fire. This runs even under `--dry-run` and without API keys configured. --- ## Configuration & Fine-tuning ### Image-Specific Options ```typescript const result = await neurolink.generate({ input: { text: "Analyze these screenshots", images: [ { data: readFileSync("./screenshot.png"), altText: "Product dashboard showing KPIs", }, ], }, provider: "openai", maxTokens: 2000, // Increase for detailed image analysis }); ``` ### PDF-Specific Options ```typescript const result = await neurolink.generate({ input: { text: "Extract financial data from this report", pdfFiles: ["./annual-report.pdf"], }, provider: "vertex", maxTokens: 8000, // Large token budget for comprehensive extraction }); ``` ### Regional Routing Some providers require regional configuration for optimal performance: ```typescript const result = await neurolink.generate({ input: { text: "Analyze this document", pdfFiles: ["./contract.pdf"], }, provider: "vertex", region: "us-central1", // Vertex AI region }); ``` --- ## Best Practices ### General Guidelines 1. **Provide descriptive prompts** - Reference specific images/files by name 2. **Use alt text for accessibility** - Helps both AI and screen readers 3. **Combine analytics + evaluation** - Benchmark multimodal quality before production 4. **Cache remote assets locally** - Avoid repeated downloads for frequently used files 5. **Stream for user-facing apps** - Use `generate()` for structured JSON output ### Image Best Practices - Provide short captions describing each image in the prompt - Pre-compress large images to reduce processing time - Use appropriate image formats (JPEG for photos, PNG for diagrams) - Consider token limits when sending multiple images ### PDF Best Practices - Choose providers with native PDF support (Vertex, Anthropic, Bedrock) - Be specific about what you need extracted - Use streaming for large documents - Set appropriate `maxTokens` (2000-8000 recommended) ### CSV Best Practices - Use raw format for large datasets - Use JSON format when AI needs structured data manipulation - Limit rows to avoid token exhaustion - Combine with images for visual + numerical analysis --- ## Troubleshooting ### Common Issues | Issue | Solution | | -------------------------------------- | ----------------------------------------------------------------- | | **"Image not found"** | Check file paths are relative to CWD where CLI is invoked | | **"Provider does not support images"** | Switch to vision-capable provider (see matrix above) | | **"Error downloading image"** | Ensure URL returns HTTP 200 and doesn't require authentication | | **"Large response latency"** | Pre-compress images and reduce resolution to < 2 MP | | **"Streaming ends early"** | Disable tools (`--disableTools`) to avoid tool call interruptions | | **"PDF too large"** | Use Google AI Studio (2 GB limit) or split into smaller chunks | | **"CSV token overflow"** | Reduce `maxRows` or use raw format instead of JSON/markdown | ### Provider-Specific Issues **OpenAI/Azure:** - Images must be < 20 MB - PDFs processed via Files API (may take longer) **Google AI Studio/Vertex:** - Best for large PDFs (AI Studio supports up to 2 GB) - Gemini models have excellent visual reasoning **Anthropic/Bedrock:** - Claude excels at document understanding - Strong visual and text analysis capabilities **Ollama:** - Use vision-capable models like `llava`, `bakllava` - Local processing - no cloud API required --- ## Related Features **Document Processing:** - [File Processors Guide](/docs/features/file-processors) - Complete guide to 17+ file types (Excel, Word, JSON, YAML, XML, HTML, SVG, code, etc.) - [Office Documents](/docs/features/office-documents) - DOCX, PPTX, XLSX for Bedrock, Vertex, Anthropic - [PDF Support](/docs/features/pdf-support) - Detailed PDF processing guide - [CSV Support](/docs/features/csv-support) - Advanced CSV processing techniques **Q4 2025 Features:** - [Guardrails Middleware](/docs/features/guardrails) - Content filtering for multimodal outputs - [Auto Evaluation](/docs/features/auto-evaluation) - Quality scoring for vision-based responses **Advanced Features:** - [Audio Input](/docs/features/audio-input) - Transcription, analysis, and real-time voice - [TTS Integration](/docs/features/tts) - Text-to-Speech audio output - [Video Generation](/docs/features/video-generation) - AI-powered video creation - [PPT Generation](/docs/features/ppt-generation) - AI-powered PowerPoint presentations **Documentation:** - [CLI Commands](/docs/cli/commands) - CLI flags and options reference - [SDK API Reference](/docs/sdk/api-reference) - Complete API documentation - [Troubleshooting](/docs/reference/troubleshooting) - Extended error catalog --- ## Examples & Recipes ### Example 1: Product Analysis Analyze a product page with screenshot, description, and pricing data: ```typescript const analysis = await neurolink.generate({ input: { text: "Analyze this product: review the screenshot, pricing data, and provide recommendations", images: [readFileSync("./product-screenshot.png")], csvFiles: ["./pricing-tiers.csv"], }, provider: "google-ai", maxTokens: 3000, }); ``` ### Example 2: Document Comparison Compare two versions of a contract: ```typescript const comparison = await neurolink.generate({ input: { text: "Compare these two contract versions and highlight key differences", pdfFiles: ["./contract-v1.pdf", "./contract-v2.pdf"], }, provider: "anthropic", maxTokens: 5000, }); ``` ### Example 3: Data Visualization Analysis Analyze charts and underlying data together: ```typescript const dataAnalysis = await neurolink.generate({ input: { text: "Analyze these sales charts and verify against the raw data", images: [ "https://example.com/q1-chart.png", "https://example.com/q2-chart.png", ], csvFiles: ["./sales-data.csv"], }, provider: "vertex", enableAnalytics: true, enableEvaluation: true, }); ``` --- ## Summary NeuroLink's multimodal capabilities provide: ✅ **Universal input support** - Images, PDFs, CSV files ✅ **Provider flexibility** - Extensive provider compatibility matrix ✅ **Automatic format detection** - Smart file type recognition ✅ **Accessibility features** - Alt text support for images ✅ **Production-ready** - Battle-tested at enterprise scale ✅ **Developer-friendly** - Works seamlessly across CLI and SDK **Next Steps:** 1. Review the [provider support matrix](#provider-support-matrix) to select the right provider 2. Try the [quick start examples](#quick-start) with your use case 3. Explore [advanced recipes](#examples--recipes) for complex scenarios 4. Check [troubleshooting](#troubleshooting) if you encounter issues --- ## Observability Guide # Observability Guide NeuroLink exports every AI operation to [Langfuse](https://langfuse.com/). Setup is environment variables only. ## Architecture One instrumentation feeds every backend: ``` OpenTelemetry spans (observe / withSpan) -> ExporterSpanProcessor observation spans -> SpanData -> ExporterRegistry sampling, circuit breaker -> LangfuseExporter ``` NeuroLink's own provider uses this pipeline, with `LangfuseExporter` registered when Langfuse is enabled. The Langfuse exporter queues spans without blocking the caller and posts them in batches to Langfuse's OTLP endpoint (`POST /api/public/otel/v1/traces`, OTLP/HTTP JSON, Basic auth with your keys). Every observation is exported: model calls, attempts, steps and tools, and the spans of the RAG, workflow, evaluation, processor and autoresearch features, which arrive as a plain `span` observation. Spans that are not observations (health checks, auth, middleware and NeuroLink's HTTP, MCP, memory and file helper spans), wrapper spans NeuroLink marks internal, and spans another library creates on a shared provider that do not describe a model call are skipped, and their children are re-parented onto the nearest exported ancestor so the tree stays connected. > **Warning: full input and output are captured by default.** Prompts, system prompts, tool arguments, tool results and model output are sent to Langfuse as they are. If your data is sensitive, set `mask` (or `redactIO`) before enabling tracing; it applies to what is sent to Langfuse only. See [Masking sensitive data](#masking-sensitive-data). > **Warning: tracing turns on automatically.** If `LANGFUSE_PUBLIC_KEY` and `LANGFUSE_SECRET_KEY` are present in the environment, NeuroLink starts exporting with no code change. Upgrading with those variables already set starts sending data. Set `observability: { langfuse: false }` to opt out. ## Setup ```bash export LANGFUSE_PUBLIC_KEY=pk-lf-... export LANGFUSE_SECRET_KEY=sk-lf-... export LANGFUSE_BASE_URL=https://cloud.langfuse.com # optional ``` ```typescript const neurolink = new NeuroLink(); await neurolink.generate({ input: { text: "Hello" } }); ``` ### Environment variables | Variable | Purpose | | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `LANGFUSE_PUBLIC_KEY` | Langfuse public key (required to auto-enable) | | `LANGFUSE_SECRET_KEY` | Langfuse secret key (required to auto-enable) | | `LANGFUSE_BASE_URL` | Langfuse host; defaults to Langfuse Cloud | | `LANGFUSE_TRACING_ENVIRONMENT` | Environment label on every Langfuse trace. The OTLP resource's `deployment.environment` is the same value and falls back to `LANGFUSE_ENVIRONMENT`, then `PUBLIC_APP_ENVIRONMENT`; Langfuse traces do not read those two | | `LANGFUSE_RELEASE` | Release label on every Langfuse trace. The OTLP resource's `service.version` is the same value and falls back to `PUBLIC_APP_VERSION`; Langfuse traces do not read it | | `LANGFUSE_ENABLED` | `false`, `0`, `off` or `no` keeps Langfuse off although both keys are set. It governs the keys wherever they come from the environment: `neurolink proxy start`, and an `observability.langfuse` options object that leaves the keys to the environment (only a `mask` or an `environment`), obey it. A setting passed in code wins over it when it turns Langfuse on itself: `langfuse: true`, `enabled: true`, or both keys in the options | | `NEUROLINK_RECORD_INPUTS` | Set to `false` to keep inputs (prompts, messages, tool arguments, proxy request bodies) out of every trace; outputs are still recorded | | `NEUROLINK_MASK_CREDENTIAL_ENTRIES` | Set to `true` to also mask the value of a `{ name, value }` or `{ key, value }` entry whose name is a credential (headers, environment lists, form fields) and a credential inside an object key, in prompts and tool inputs and outputs. Off by default: the masker then reads keys and text only, as in the released build. | | `NEUROLINK_PROXY_TRACE_BODY_LOGGING` | Set to `true` to record Claude and Codex proxy request and response bodies and the content of translated requests on traces; off by default. See [Proxy](#proxy) | | `OTEL_EXPORTER_OTLP_ENDPOINT` | Also export traces and metrics to an OTLP collector, only when NeuroLink owns the tracer provider. Ignored, with one warning, when your application registered its own `TracerProvider` first; see [External OpenTelemetry provider](#external-opentelemetry-provider) | | `OTEL_SERVICE_NAME` | `service.name` of NeuroLink's OTLP export (default `ai-service`; `neurolink proxy start` sets `neurolink-proxy`) | | `NEUROLINK_TELEMETRY_ENABLED` | `true` records NeuroLink's [metrics](#metrics) whatever else is set. A registered `MeterProvider` or `OTEL_EXPORTER_OTLP_ENDPOINT` already turns them on, and without a `MeterProvider` they go nowhere, so on its own it changes nothing; it does not turn tracing on | | `NEUROLINK_TELEMETRY_EXIT_FLUSH` | `false`, `0`, `off` or `no` skips the flush that runs when a script ends on its own (`beforeExit`), so the process ends as soon as it has no work, with no wait for an unreachable collector. See [Serverless and short-lived processes](#serverless-and-short-lived-processes) | | `NEUROLINK_SPAN_ATTRIBUTE_MAX_CHARS` | Largest serialized span input, output or tool payload in characters (default 40000, minimum 10000). Anything over it is trimmed to valid JSON, keeping the user's question, then this turn's newest messages, then history | ### Disable or override ```typescript new NeuroLink({ observability: { langfuse: false } }); new NeuroLink({ observability: { langfuse: { publicKey: "pk-lf-...", secretKey: "sk-lf-...", baseUrl: "https://langfuse.example.com", environment: "production", release: "2026.10.1", exportMode: "batched", flushAt: 50, flushInterval: 5, }, }, }); ``` Every field is optional. `publicKey`, `secretKey`, `baseUrl`, `environment` and `release` fall back to the variables above; the others have the defaults below. The type is `NeurolinkLangfuseConfig`. | Field | Meaning | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `enabled` | `false` turns Langfuse off although keys are set (from untyped config, the strings `"false"`, `"0"`, `"off"` and `"no"` do too); any other value, or leaving it out, leaves it on. `LANGFUSE_ENABLED` is read only when the object leaves the keys to the environment and does not set `enabled: true` | | `publicKey` | Langfuse public key | | `secretKey` | Langfuse secret key | | `baseUrl` | Langfuse host | | `environment` | Environment label | | `release` | Release label | | `mask` | Function applied to input, output and metadata before they are sent to Langfuse; see [Masking sensitive data](#masking-sensitive-data) | | `redactIO` | `true` leaves input and output out of what is sent to Langfuse instead of masking them (default `false`) | | `exportMode` | `"batched"` (default) or `"immediate"` | | `flushAt` | Spans buffered before a batch is sent (default 15) | | `flushInterval` | Seconds between batch flushes (default 5) | | `flushBudgetMs` | Longest a `flush()` or shutdown waits for Langfuse deliveries before dropping what is still in flight (default 3000). `flushOpenTelemetry()`, `shutdownOpenTelemetry()` and the exit flush also wait at most this long for the OTLP collector, and it is the OTLP exporters' request timeout unless `OTEL_EXPORTER_OTLP_TIMEOUT` (or its `_TRACES_` / `_METRICS_` form) is set | ## Per-call context Pass `context` on `generate`, `stream` and `decide`. The values are attached to every span the call creates, including tool calls and fallback attempts, so one call is one trace. ```typescript await neurolink.generate({ input: { text: "Summarize this ticket" }, context: { userId: "user-123", sessionId: "session-456", tags: ["support", "premium"], traceName: "ticket-summary", conversationId: "conv-789", requestId: "req-abc", metadata: { region: "us-east-1" }, }, }); ``` | Field | Recorded as | | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `userId` | Trace user | | `sessionId` | Trace session | | `tags` | Trace tags | | `traceName` | Trace name | | `conversationId` | Metadata key `conversationId` | | `requestId` | Metadata key `requestId` | | `metadata` | Metadata; values up to 200 characters are on every observation, longer values and arrays are recorded in full on the trace only | | `observationName` | Name of the root observation of this call; default `generate` or `stream`; not propagated to child observations or used as the trace name | ### setLangfuseContext Wrap your own code to attach the same attributes to everything inside it, including spans you create yourself. ```typescript const neurolink = new NeuroLink(); const result = await setLangfuseContext( { userId: "user-123", sessionId: "session-456", traceName: "chat" }, () => neurolink.generate({ input: { text: "Hello" } }), ); ``` `setLangfuseContext(params: NeurolinkTraceContext, fn)` returns whatever `fn` returns. It is a thin wrapper over Langfuse's `propagateAttributes`. ## What is recorded ### Naming The observations below (`generate`, `stream`, `decide`, attempts, steps and tools) carry no product name in their span names, attribute keys or metadata keys. Names never carry per-execution values: the model and provider are fields, the step number is metadata. The product name remains in the plain spans listed under [Other spans](#other-spans) and in the proxy root's `neurolink.user_id`, `neurolink.session_id` and `neurolink.conversation_id` attributes. | Observation | Name | Langfuse type | Parent | | -------------------------- | ------------------------------------- | ------------- | ---------------------- | | `generate` / `stream` call | `generate` / `stream` | `agent` | none (trace root) | | Fallback attempt | `generate.attempt` / `stream.attempt` | `span` | root | | Agent loop step | `step` (`step_index` metadata) | `span` | the attempt span | | One model request | `generate` / `stream` | `generation` | its `step` | | Tool execution | the tool's name, e.g. `get_weather` | `tool` | the `step` that ran it | | `decide` | `decide` | `generation` | caller or root | A model request is named after the API the caller used (`NeuroLink.generate` or `provider.generate` gives `generate`, `NeuroLink.stream` or `provider.stream` gives `stream`). Its model is the observation's model field (the model the provider reported, falling back to the requested one) and the provider id is the `provider` metadata key. The trace name is `context.traceName` when given, otherwise the operation name (`generate`, `stream`). An outer `setLangfuseContext` takes precedence over per-call `context` for user, session and trace name. Embeddings, transcribe, TTS and media tracing are not yet recorded. The root also sets trace-level input and output; a `generate` or `stream` nested inside another turn does not. ### Other spans Spans from the RAG, workflow, file, memory, context and evaluation code are exported as plain `span` records with their name, timing, status and their own attributes. They keep their `neurolink.*` names: `neurolink.rag.search`, `neurolink.rag.rerank`, `neurolink.rag.chunk`, `neurolink.workflow.*` (`run`, `run.streaming`, `response.condition`, `judge.score`, `ensemble.execute`, `layers.execute`), `neurolink.file.process`, `neurolink.file.video.process`, `neurolink.context.compact`, `neurolink.memory.summarize` and `neurolink.evaluation.ragas`. ### Steps and chat format Each iteration of the agent loop gets one `step` span with its one-based index in the `step_index` metadata. It parents that iteration's generation and the tool observations the model requested in it, so a multi-tool turn reads as step 1 (call, tools), step 2 (call, tools), and so on. Generation input is a chat message array with the system message first. Generation output is an assistant message array: `content`, plus `reasoning` and `tool_calls` (`{ id, type: "function", function: { name, arguments } }`) when present. Langfuse renders both as a conversation. Generation details: - **Usage** includes input, output, total, cache read, cache creation and reasoning tokens, whatever naming the provider uses. - **Cost** is computed from NeuroLink's pricing table and recorded as `costDetails.total`. - **Model parameters** are temperature, max tokens, top-p and thinking level. - **Time to first token** is recorded as the generation's completion start time for streams. - **Level** is `WARNING` for a `length` or `content-filter` finish, an aborted call, an early `break` out of a stream, or an empty output, and `ERROR` when the call throws. - **Streams** end their spans when the stream finishes, is abandoned or is aborted. ## Masking sensitive data `mask` runs on the input, output and metadata sent to Langfuse. It receives `{ data }` and returns the value to send. ```typescript const neurolink = new NeuroLink({ observability: { langfuse: { mask: ({ data }) => JSON.stringify(data).replace(/\b\d{13,16}\b/g, "[card]"), }, }, }); ``` `mask` and `redactIO` act on what NeuroLink sends to Langfuse, and on nothing else. They cover the trace and observation input and output (`langfuse.observation.input`, `langfuse.observation.output`, `langfuse.trace.input`, `langfuse.trace.output`); `redactIO: true` leaves those out of the request, and `mask` rewrites them instead. `mask` also runs on trace and observation metadata, whether or not the metadata is an object. If it throws, the value is replaced by ``. Everything else goes to Langfuse as it was recorded: the status message, `exception.message`, `error.message`, a tool's `tool.error.message` and a provider retry's `retry.error`, tool-call attributes, the `proxy.body` attribute of proxy body events, event attributes, and the prompt and completion attributes another library's GenAI instrumentation writes on spans that are exported with NeuroLink's. The policy does not reach any other sink either: an exporter you register with `registerExporter`, the spans NeuroLink sends to `OTEL_EXPORTER_OTLP_ENDPOINT`, and `getSpans()` receive the values as they were recorded. If one of them must not see content, take it out where it is recorded (`NEUROLINK_RECORD_INPUTS=false`) or in that sink's own processing. NeuroLink adds no credential masking of its own to error text. A failed call's status message, `error.message`, `tool.error.message`, `retry.error` and exception text are recorded as the provider returned them, in every sink, as the released build did, so an error that echoes a key reaches the sinks with the key. Input, output and tool arguments and results keep the credential masking they always had. To keep a credential out of error text, filter it in a custom exporter or keep it out of the provider's error. ## Langfuse exporter behaviour - **Endpoint.** `POST {baseUrl}/api/public/otel/v1/traces` as OTLP/HTTP JSON. Requests are cut at 500 spans or 3.5 MB. - **Observation types.** Agent, generation, tool, step, attempt and the other observation types reach Langfuse with their native type, model, parameters, usage, cost and first-token time. - **Identity.** User, session, trace name, tags and trace metadata are set on every observation, not only the root. - **Environment and release.** The config field, then `LANGFUSE_TRACING_ENVIRONMENT` / `LANGFUSE_RELEASE`; they fill spans that do not carry them already. The OTLP resource's `deployment.environment` and `service.version` also read `LANGFUSE_ENVIRONMENT`, `PUBLIC_APP_ENVIRONMENT` and `PUBLIC_APP_VERSION`; Langfuse traces do not. - **Batching.** Spans are sent when `flushAt` spans are queued, every `flushInterval` seconds, on `flushOpenTelemetry()` and on shutdown. `exportMode: "immediate"` sends each span as it ends. - **Failures.** A request that fails with 429, 5xx or a network error is retried with exponential backoff, or after the `Retry-After` a 429 or 503 names, up to 60 seconds and never past a flush's budget. Other 4xx responses are not retried. Spans Langfuse reports as rejected (`partialSuccess`) are logged once as a warning and not re-sent; a success whose body is not an object, or whose rejected count is not a whole number between zero and the spans sent, counts as all delivered. At most 4 export requests are in flight at once. Spans that end meanwhile wait, up to 10,000 of them; when Langfuse stops answering, the oldest waiting spans are dropped, counted in `failedSpans` and in the errors of `healthCheck()`, and warned about once a minute. Spans that end during shutdown are sent within the flush budget or counted as dropped. A 401 or 403 is not retried; it is logged as an error ("Langfuse credentials rejected") with the spans dropped at most once a minute, once more when the credentials are accepted again, and for any remainder at shutdown, and a refused batch gets no `Dropped N of M spans` warning. Delivery never throws into your code. A batch that is dropped is reported in the exporter's result (`success: false` with `failedCount`), in a `Dropped N of M spans` warning and in the errors of `healthCheck()`. While Langfuse took none of the latest batch (it refused the request, the request failed, or `partialSuccess` rejected every span), the exporter's status and `healthCheck()` read unhealthy with an error naming the dropped count, until a batch is accepted again. These failures do not open the circuit breaker, so later spans are still delivered. ## Metrics NeuroLink also records OpenTelemetry metrics, on one meter named `neurolink-ai`. They are recorded only when `OTEL_EXPORTER_OTLP_ENDPOINT` is set, when `NEUROLINK_TELEMETRY_ENABLED=true`, or when a global `MeterProvider` is registered (your application's, or NeuroLink's own); a global `TracerProvider` alone, NeuroLink's included, does not turn them on. They are written to the global `MeterProvider`. NeuroLink registers one, exporting to `$OTEL_EXPORTER_OTLP_ENDPOINT/v1/metrics` every 15 seconds, only when it owns the tracer provider and the endpoint is set; beside a host provider they go to the `MeterProvider` your application registered, and nowhere when it registered none. | Metric | Kind | Labels | Recorded for | | ----------------------------------------- | ----------------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ai_requests_total` | counter | `provider`, `model` | each `generate()` that finishes in `BaseProvider.finalizeNativeGenerate` (the native generate path of providers such as Anthropic, SageMaker and the OpenAI Chat Completions family), and each proxied request whose usage the proxy captured | | `ai_request_duration_ms` | histogram, milliseconds | `provider`, `model` | the same requests | | `ai_tokens_used_total` | counter, total tokens | `provider`, `model` | the same requests | | `ai_cost_usd_total` | counter, US dollars | `provider`, `model` | the same requests, when the model's price is known | | `mcp_tool_calls_total` | counter | `tool`, `success`, `duration_bucket` (`fast` under 100 ms, `medium` under 500 ms, `slow` under 1 s, `very_slow`) | each tool call to an external MCP server; `success` is `false` for a thrown error and for a resolved MCP error result | | `custom_tts_failures` | counter | `provider`, `error_code`, and `retriable` when known | each failed TTS synthesis | | `custom_tts_failure_latency_ms_histogram` | histogram, milliseconds | the same | each failed TTS synthesis | `ai_provider_errors_total`, `connections_total` and `response_time_ms` are created on the same meter, but nothing in the package records them, as before this release. The active-connection count that `TelemetryService.recordConnectionClosed` kept is not restored, and the recording functions are not exported. The proxy records its own `proxy_*` metrics; see [Claude Proxy Observability](/docs/features/claude-proxy-observability). ## External OpenTelemetry provider If your application registers its own global `TracerProvider` before tracing starts, NeuroLink creates no provider. `OTEL_EXPORTER_OTLP_ENDPOINT` is then ignored: NeuroLink logs one warning and exports no traces or metrics to it, so add an OTLP exporter, or any other vendor's span processor, to your own providers. `neurolink.getTelemetryStatus().openTelemetry` then reports `usingExternalProvider: true` (its `enabled` stays whether tracing is initialized, as before), and `neurolink telemetry status` and `neurolink observability status` print the endpoint as ignored. NeuroLink's [metrics](#metrics) are recorded on the `MeterProvider` your application registers. For Langfuse choose one of two recipes. The host provider must register a context manager, which `NodeTracerProvider.register()` and `NodeSDK` do. Without one OpenTelemetry cannot carry context between calls, so `setLangfuseContext` user, session and metadata never reach NeuroLink's spans and child spans lose their parents; NeuroLink logs a warning when it finds none. Shutting the host provider down shuts the shared exporters down, as `createExporterSpanProcessor()` always did. If the host rebuilds its provider, pass `createExporterSpanProcessor(undefined, { shutdownExporters: false })`: that processor only flushes the exporters on shutdown, so a rebuilt provider that adds one again keeps exporting. **(a) Exporter pipeline (recommended).** Add `createExporterSpanProcessor()` to your provider and give NeuroLink the Langfuse keys, either through `new NeuroLink({ observability: { langfuse } })` or the `LANGFUSE_PUBLIC_KEY` / `LANGFUSE_SECRET_KEY` environment variables. NeuroLink registers its `LangfuseExporter` on the shared exporter registry, which the processor reads, so `mask`, batching, chunking and retry from the section above all apply. Register the processor before the first NeuroLink call; spans that end before the exporter is registered are not exported. ```typescript const sdk = new NodeSDK({ spanProcessors: [createExporterSpanProcessor()], }); sdk.start(); const neurolink = new NeuroLink({ observability: { langfuse: { publicKey: "pk-lf-...", secretKey: "sk-lf-..." }, }, }); ``` **(b) `LangfuseSpanProcessor`.** Add `new LangfuseSpanProcessor()` from `@langfuse/otel` with its defaults; no custom `shouldExportSpan` filter is needed. Every observation span NeuroLink emits carries a `gen_ai.observation.type` attribute, which the default filter exports, while infrastructure spans are not exported. This path sends OTLP and keeps native Langfuse observation types. The processor takes its keys, `mask`, `flushAt`, `flushInterval`, `exportMode`, environment and release from its own constructor options and `LANGFUSE_*` variables. It does not read `observability.langfuse` from `new NeuroLink(...)`, so those settings must be passed to the processor, and NeuroLink's exporter masking, 500-span / 3.5 MB chunking and retry policy do not apply to it. ```typescript const sdk = new NodeSDK({ spanProcessors: [new LangfuseSpanProcessor()], }); sdk.start(); const neurolink = new NeuroLink(); ``` Register your provider before tracing starts, that is before the first `new NeuroLink({ observability })` and the first NeuroLink call (see [Initialisation](#initialisation)); otherwise NeuroLink creates and registers its own provider and keeps it for the process. NeuroLink never flushes or shuts down a provider it did not create. `@langfuse/otel` is not a dependency of NeuroLink; install it for recipe (b). ## Initialisation Tracing starts synchronously, once per process, at the first of these: - `new NeuroLink({ observability })`. A constructor without an `observability` block starts nothing. - The first `generate`, `stream`, `decide` or `tryDecide` call on any `NeuroLink` instance. - The first span NeuroLink's own code creates, on an entry that loads the start-up module: the main package entry, `@juspay/neurolink/server` and `@juspay/neurolink/livekit`, and the `./rag`, `./workflow`, `./evaluation`, `./processors` and `./autoresearch` subpath entries. That includes direct provider calls with no `NeuroLink` instance, for example `AIProviderFactory.createProvider(...).generate(...)` imported from the main entry. The lightweight `@juspay/neurolink/client` entry does not load the OpenTelemetry Node SDK and does not start tracing: its spans go to a `TracerProvider` your application registered, and are dropped when there is none. A Node application that relied on this entry alone to start tracing (the previous version did) adds `import "@juspay/neurolink"` once at start-up. Tracing configuration is process-wide and the first start wins. An `observability` config passed to `new NeuroLink()` wins over the `LANGFUSE_*` variables only when that construction starts tracing. A later instance's config is ignored: if it differs from the first, NeuroLink logs a warning that names the options that differ, once per set of differing options; an identical config logs one debug line. A start before Langfuse or OTLP is configured sets nothing up, so a later config or environment can still start tracing, unless `langfuse: false` was passed. `langfuse: true`, or an options object, without both keys counts as Langfuse not configured: NeuroLink warns once that the keys are missing and, unless `OTEL_EXPORTER_OTLP_ENDPOINT` is set, starts nothing, so a later config with keys still starts tracing. To run beside your own OpenTelemetry setup, register your `TracerProvider` before tracing starts; see [External OpenTelemetry provider](#external-opentelemetry-provider). Importing the main package entry loads the OpenTelemetry SDK, both OTLP exporters and the metrics SDK at import, even when telemetry stays off, and so does importing one of the subpath entries above. That is the cost of starting tracing without an initialization call, and it adds to start-up time in a cold process. The shared tracers, which the client entry uses, load none of them. ## Serverless and short-lived processes Spans are batched. Flush before the process freezes or exits: ```typescript await flushOpenTelemetry(); await shutdownOpenTelemetry(); ``` Or send each span as it ends: ```typescript new NeuroLink({ observability: { langfuse: { exportMode: "immediate" } }, }); ``` A script that ends on its own flushes pending spans and metrics once the event loop is empty (`beforeExit`). An explicit `process.exit()`, a fatal signal or an uncaught exception skips that flush, so call `await flushOpenTelemetry()` before them. `flushOpenTelemetry()`, `shutdownOpenTelemetry()` and that exit flush wait at most the flush budget (`observability.langfuse.flushBudgetMs`, default 3000 ms) for the OTLP collector, and for Langfuse within the same budget. What did not complete is logged as a warning, and `flushOpenTelemetry()` then rejects with `Flush failed` (its `cause` lists the reasons), as it always did; the exit flush and `shutdown()` catch that themselves, so a collector or Langfuse that cannot be reached does not hold a script past the budget: NeuroLink gives its OTLP exporters the budget as their request timeout. When `OTEL_EXPORTER_OTLP_TIMEOUT` (or its `_TRACES_` / `_METRICS_` form) is set, that timeout applies instead, and a request still in flight can hold the process open until the exporters' timeouts expire. The exit flush is new: before it a script ended at once and delivered nothing it still held, and with a collector that cannot be reached it now ends up to the flush budget (3 s by default) after its last call. Set `NEUROLINK_TELEMETRY_EXIT_FLUSH=false` (also `0`, `off` or `no`) to skip it and end as soon as there is no work. `shutdownOpenTelemetry()` is terminal for the process: telemetry cannot restart afterwards. While other `NeuroLink` instances are still alive it only flushes. ## Health ```typescript getLangfuseHealthStatus, isOpenTelemetryInitialized, } from "@juspay/neurolink"; const { isHealthy, initialized, hasProcessor, usingExternalProvider } = getLangfuseHealthStatus(); ``` `isHealthy` and `hasProcessor` are true only while a Langfuse exporter is registered, whether NeuroLink owns the provider or runs beside a host provider. With a host provider, the exporter still needs `createExporterSpanProcessor()` on that provider to receive spans. ## Proxy The proxy records the pool account label (not an email address), sets `userId` and `sessionId` from `x-neurolink-user-id` and `x-neurolink-session-id` (the session falls back to Claude Code's `x-claude-code-session-id`), names traces `proxy:`, and records usage, cost and time to first token. The `proxy.request` root also carries `neurolink.user_id`, `neurolink.session_id` and `neurolink.conversation_id` as plain attributes for backends that index identity by key. Request and response bodies are recorded on traces only when `NEUROLINK_PROXY_TRACE_BODY_LOGGING=true`, the same opt-in as before the Langfuse migration. With it on, the bodies become the input and output of the proxy observations, so `mask` and `redactIO` apply to them on the Langfuse request, and `NEUROLINK_RECORD_INPUTS=false` still drops the request body. The raw bodies are also attached as span events only when the same flag is on (`proxy.client.request_body`, `proxy.upstream.request_body`, `proxy.upstream.response_body` and `proxy.stream.events`); without it those events carry only sizes and counts. `mask` and `redactIO` do not cover those events, neither the `proxy.body` attribute nor `proxy.stream.events`, so leave the flag off for traffic whose content must not leave the process. Upstream error text is recorded without the flag, as it was before the migration: `error.message` and the status message (`: `) hold the upstream text, capped, as received. `mask` and `redactIO` leave it as it was recorded, as they did before the migration. A translated request, which the proxy serves through a NeuroLink model call, follows the body opt-in: without the flag that call's records keep model, usage, cost, finish reason and timings but no input or output. The `proxy.client.request_headers`, `proxy.upstream.request_headers` and `proxy.upstream.response_headers` events record every header name and, as before, every value as received, except the values of credential headers, which read `[REDACTED]`: `authorization`, `proxy-authorization`, `x-api-key`, `cookie`, `set-cookie`, and names containing `token`, `secret`, `key`, `password` or `credential`, exactly as before. Proxy spans carry both the `gen_ai.request.model`, `gen_ai.response.model` and `gen_ai.usage.*` names used before the migration and the `proxy.request.model`, `proxy.response.model` and `proxy.usage.*` names. The Langfuse export still produces one priced generation per proxied request. See the [Telemetry Guide](/docs/observability/telemetry#-proxy-telemetry-otlp-triple-signal-export) and [Claude Proxy Observability](/docs/features/claude-proxy-observability). ## Voice (LiveKit) Pipeline mode traces through `stream()` and carries the `voice` tag. Realtime mode records one trace per conversation turn, with transcripts as input and output and tool calls as `tool` records. Every realtime turn is traced when tracing is on, with or without voice memory: a call without memory is traced through `setUpRealtimeCallTracing`, with the room name as the session and no user id. Each turn is traced as soon as it closes, never behind the memory store's writes, so a slow or stuck store loses no trace. At shutdown the call closes its open turn and delivers its traces while its pending turn writes finish, both within `memory.flushBudgetMs` (default 800 ms, because the worker is reaped about a second after shutdown starts); `flushOpenTelemetry()` itself is bounded by `observability.langfuse.flushBudgetMs` (default 3000 ms). The `realtime` generation record carries the model id and the provider of the realtime backend (`vertex` for Gemini Live, `xai` for Grok Voice). Full transcripts are sent to Langfuse by default; use `mask` for sensitive data. ## Troubleshooting | Symptom | Check | | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Nothing reaches Langfuse | Both keys set and `langfuse` not `false`; `getLangfuseHealthStatus()`; call `flushOpenTelemetry()` on exit | | Spans missing with own OTEL setup | Add `createExporterSpanProcessor()` to your provider and pass the Langfuse keys to NeuroLink (or set `LANGFUSE_*`), or use `new LangfuseSpanProcessor()` with its own keys; register the processor before the first NeuroLink call | | Wrong host | Variable is `LANGFUSE_BASE_URL`, not `LANGFUSE_BASEURL` | | Traces stop after shutdown | `shutdownOpenTelemetry()` cannot be undone in the same process; use `flushOpenTelemetry()` | ## Migrating from the previous version This release is breaking. ### Configuration fields | Removed or changed | Replacement | | ------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `langfuse.enabled` | Kept, and optional: Langfuse is on when keys are present unless `enabled: false` (or `langfuse: false`); `enabled: true` is no longer needed | | `langfuse.userId`, `langfuse.sessionId` | Per-call `context.userId`, `context.sessionId`, or `setLangfuseContext` | | `useExternalTracerProvider`, `autoDetectExternalProvider` | Automatic: a registered global provider is detected | | `skipLangfuseSpanProcessor` | Register your own provider; NeuroLink then adds nothing | | `openTelemetry` option (`OpenTelemetryConfig`: `enabled`, `endpoint`, `serviceName`, `serviceVersion`) | `OTEL_EXPORTER_OTLP_ENDPOINT` turns the OTLP trace and metric export on while NeuroLink owns the tracer provider, `OTEL_SERVICE_NAME` names the service (default `ai-service`), and `service.version` is the release: config `release`, `LANGFUSE_RELEASE`, `PUBLIC_APP_VERSION`, then `npm_package_version`, then `v1.0.0` (`deployment.environment` is the configured environment and is not sent when none is configured) | | `OTEL_EXPORTER_OTLP_ENDPOINT` beside a host `TracerProvider` | Ignored, with one warning. With a host provider (`useExternalTracerProvider`, `autoDetectExternalProvider`) the previous version still exported OTLP metrics and logs to it; that is not restored. Add an OTLP exporter to your own providers | | `autoDetectOperationName`, `operationName`, `traceNameFormat` | `context.traceName` | | `customAttributes` | `context.metadata` | | `conversationId`, `requestId` on the config | `context.conversationId`, `context.requestId` (stored as metadata) | | `NEUROLINK_TELEMETRY_ENABLED` | Still read: `true` records the [metrics](#metrics); it does not turn tracing on | | `LANGFUSE_ENABLED` | Still read, now only as an off switch: `false`, `0`, `off` or `no` keeps Langfuse off while the keys are in the environment, unless config passed in code turns it on itself (`langfuse: true`, `enabled: true`, or both keys in the options). The keys alone enable tracing, so `LANGFUSE_ENABLED=true` is no longer needed | | `LANGFUSE_ENVIRONMENT`, `PUBLIC_APP_ENVIRONMENT` | Still read, as fallbacks after `LANGFUSE_TRACING_ENVIRONMENT`, for the OTLP resource only | | `PUBLIC_APP_VERSION` | Still read, as a fallback after `LANGFUSE_RELEASE`, for the OTLP resource only | | `OTEL_SERVICE_VERSION` | Not read; `service.version` is the release, as above | | `LANGFUSE_BASEURL` hint | `LANGFUSE_BASE_URL` | ### Exports | Removed or changed | Replacement | | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `initializeOpenTelemetry` | Automatic; see [Initialisation](#initialisation) | | `getLangfuseSpanProcessor` | `createExporterSpanProcessor(registry)` or `new LangfuseSpanProcessor()` | | `getTracerProvider`, `getTracer` | `trace.getTracer()` from `@opentelemetry/api` | | `getSpanProcessors` | Add `createExporterSpanProcessor()` to your provider | | `createContextEnricher` | `setLangfuseContext` or per-call `context` | | `isUsingExternalTracerProvider` | `getLangfuseHealthStatus().usingExternalProvider` | | `isLangfuseInternalSpan`, `langfuseShouldExportSpan` | Removed; only observation spans are exported | | `getLangfuseContext` | Removed | | `runWithCurrentLangfuseContext` | `context.bind(context.active(), fn)` from `@opentelemetry/api` | | `buildObservabilityConfigFromEnv` | Removed; env keys are read automatically | | `createMockLangfuseClient` | No longer exported from the package root; still exported by the evaluation hooks module | | `TelemetryService` | Removed. Its metrics are recorded again under the same names without it (see [Metrics](#metrics)), the TTS failures as `custom_tts_failures` and `custom_tts_failure_latency_ms_histogram`; its recording methods are not public API | | `initializeTelemetry`, `getTelemetryStatus` (root) | Removed; use `getLangfuseHealthStatus` | | `setLangfuseContext(context, callback?)`: async, with an ambient form and `operationName`, `autoDetectOperationName`, `customAttributes` | `setLangfuseContext(params, fn)` is synchronous and `fn` is required, so wrap the code that should carry the context; use `context.traceName` and `context.metadata` for the options | | `getLangfuseHealthStatus()` fields `enabled`, `credentialsValid`, `config` | `isHealthy`, `hasProcessor`, `usingExternalProvider`; the host and environment are in `neurolink.getTelemetryStatus().langfuse` | | `neurolink.getTelemetryStatus().exporters` | Still returned: one `ExporterStatus` per exporter on the shared registry (`ExporterRegistry.getStatuses()`), beside `langfuse` and `openTelemetry` | | `ToolExecutionGuards.withToolSpan` | Removed; tool calls are observed by NeuroLink's own tool execution, with no per-provider wrapper | ### CLI | Removed | Replacement | | ------------------------------------ | -------------------------------------- | | `neurolink telemetry configure` | Set `LANGFUSE_*` environment variables | | `neurolink telemetry list-exporters` | `neurolink telemetry status` | | `neurolink observability exporters` | `neurolink observability status` | ### Types | Removed or changed | Replacement | | -------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `LangfuseContext`, `TraceNameFormat` | `NeurolinkTraceContext` (per-call `context`, `setLangfuseContext`); the trace name is `context.traceName` | | `LangfuseConfig` | `NeurolinkLangfuseConfig` | | `ExporterName`, `ToolSpanCall`, `TelemetryConfigureArgs`, `TelemetryListExportersArgs`, `ObservabilityExportersArgs` | Removed with the CLI commands and tool wrapper that used them | | `AnthropicLoopAdapterConfig`, `GeminiLoopAdapterCoreConfig`, `NativeGenerateLoopArgs`: `provider` | `provider` is now a required string, recorded on each step's generation and used to price it; `GeminiLoopAdapterCoreConfig.buildRequest` returns `GeminiStepRequest` instead of `unknown` | ### Dependencies - `@opentelemetry/sdk-trace-node` moved from a peer dependency to a dependency, so NeuroLink installs it itself. - `@langfuse/otel` moved from an optional dependency to a devDependency of NeuroLink, so install it yourself for `new LangfuseSpanProcessor()`. - `@langfuse/core` and `@langfuse/tracing` are new dependencies. ### Unchanged `ExporterRegistry`, `NoOpExporter`, `AlwaysSampler`, `NeverSampler`, the vendor exporter classes, `ExtendedObservabilityConfig` and the `*ExporterConfig` types are unchanged (`LangfuseExporterConfig` configures `new LangfuseExporter(...)`). NeuroLink wires only `LangfuseExporter`. `LangfuseExporter`, `ExporterSpanProcessor` and `createExporterSpanProcessor` are new root exports. ## See Also - [Telemetry Guide](/docs/observability/telemetry) - [Claude Proxy Observability](/docs/features/claude-proxy-observability) - [Analytics Reference](/docs/reference/analytics) --- ## Office Documents Support # Office Documents Support NeuroLink reads Word, Excel, and PowerPoint files itself and puts their content into the prompt as text. Attach them through the same `input.files` array (or `--file` flag) that carries every other file type; there is no separate Office input field and no provider restriction. ## Overview When a request carries an Office file, NeuroLink: 1. **Detects** the format from the file's bytes, MIME type, and extension. 2. **Extracts** the content in-process: Word through `mammoth` (converted to Markdown), Excel through `exceljs`, and PowerPoint by reading the slide XML inside the `.pptx` package. 3. **Appends** the extracted text to the prompt under a heading that names the file (`## Document: "report.docx"`, `## Spreadsheet: "sales.xlsx"`, `## Presentation: "deck.pptx"`). 4. **Sends** an ordinary text prompt to whichever provider you chose. Because the model receives text, Office files work with every provider and model, including ones with no document API (OpenAI, Ollama, Mistral, and so on). The model sees what the extractors can read: text, tables, and speaker notes. It does not see images, charts, or shapes that carry no text. ## Supported File Types | Format | Extension | MIME Type | What the model receives | | --------------------- | --------- | --------------------------------------------------------------------------- | ------------------------------------------------------- | | **Word Document** | `.docx` | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` | Markdown (headings, lists, tables) and a metrics line | | **PowerPoint** | `.pptx` | `application/vnd.openxmlformats-officedocument.presentationml.presentation` | Text of every slide, table rows, and each slide's notes | | **Excel Spreadsheet** | `.xlsx` | `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` | Every sheet (or one you name) in the format you choose | The same three routes also carry OpenDocument text, spreadsheet and presentation files (`.odt`, `.ods`, `.odp`) and RTF (`.rtf`), which are read as plain text. **Legacy binary formats** (`.doc`, `.xls`, `.ppt`) are recognised but not parsed: the readers only understand the Office Open XML packages above. The request still succeeds, and the model receives a short note saying the file was attached but its content could not be extracted. Re-save such files as `.docx`, `.xlsx`, or `.pptx` first. ## Quick Start ### SDK Usage ```typescript const neurolink = new NeuroLink(); // Word document const summary = await neurolink.generate({ input: { text: "Summarize the key points from this document", files: ["report.docx"], }, provider: "openai", }); // PowerPoint presentation (slide text, tables, and speaker notes) const slides = await neurolink.generate({ input: { text: "List the main topic of each slide and any speaker-note caveats", files: ["quarterly-review.pptx"], }, provider: "anthropic", }); // Excel spreadsheet const sheet = await neurolink.generate({ input: { text: "What are the top 5 products by revenue in this spreadsheet?", files: ["sales-data.xlsx"], }, provider: "vertex", }); // Several documents, mixed with other file types const comparison = await neurolink.generate({ input: { text: "Compare the revenue figures in the report against the spreadsheet", files: ["q1-report.docx", "data.xlsx", "chart.png", "notes.pdf"], }, provider: "openai", }); // Streaming const result = await neurolink.stream({ input: { text: "Provide a detailed analysis of this contract", files: ["contract.docx"], }, provider: "openai", }); for await (const chunk of result.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } ``` ### CLI Usage ```bash # Attach an Office file neurolink generate "Summarize this document" --file report.docx --provider openai # Several files neurolink generate "Compare these reports" --file q1.docx --file q2.docx --provider openai # Spreadsheet neurolink generate "Analyze sales trends" --file sales.xlsx --provider openai # Presentation neurolink generate "Extract key points from the slides" --file presentation.pptx --provider openai # Mixed file types neurolink generate "Analyze all documents" --file report.docx --file data.xlsx --provider openai # Stream mode neurolink stream "Explain this document in detail" --file document.docx --provider openai # Note: `batch` does NOT accept --file. The flag is deliberately unregistered # there because it would collide with the prompts-file positional, so Office # attachments are only available on `generate` and `stream`. ``` The CLI has no flags for `officeOptions`; choosing a sheet or a spreadsheet format is an SDK feature (see below). ## What the Model Receives ### DOCX structure and metrics A `.docx` is converted to Markdown before it reaches the model, so headings, ordered and unordered lists, and tables survive as structure rather than being flattened into prose. Each document is prefixed with a metrics line: ``` Document: 42 words, 9 paragraphs, 268 characters # Quarterly Platform Report ## Adoption - Merchant onboarding automated - Settlement latency reduced | Region | Merchants | Volume | | --- | --- | --- | | APAC | 128 | 44200 | ``` ### PPTX slides, tables, and speaker notes A `.pptx` is read slide by slide, in slide-number order. Each slide's text comes first, then its speaker notes on a `**Speaker notes:**` line: ``` Presentation: 2 slide(s) ### Slide 1 Q3 Revenue & Growth Region | Owner | Volume APAC | Priya & Sam | 44200 EMEA | | Line one Line two **Speaker notes:** Mention the RTO improvement & Q3 . ### Slide 2 Hire two analysts **Speaker notes:** Ask finance about headcount. ``` - Text boxes and titles come out one text run per line, with XML character references decoded (`&` is shown as `&`, `<` as `<`, `©` as the copyright sign). - A table row becomes one line with the cells joined by `|`. An empty cell keeps its separator, so the cells of a row can still be counted (`Q3 | |` has three, `| Open |` has three), and a cell with several paragraphs or line breaks is joined onto the one line with spaces. A row with no text at all is dropped. A literal `|` in cell text is not escaped, so it reads like a separator. - Speaker notes are always included. There is no option to turn them off. - A slide with no text and no notes is left out. A deck of nothing but pictures therefore arrives as the `Presentation: N slide(s)` header alone. - Pictures, charts, SmartArt, and shapes that hold no text contribute nothing. ### Selecting and formatting spreadsheet data ```typescript // Only the "Transactions" sheet, rendered as a markdown table await neurolink.generate({ input: { text: "Which transactions were refunded?", files: ["workbook.xlsx"], }, provider: "openai", officeOptions: { sheetName: "Transactions", formatStyle: "markdown" }, }); // Row objects keyed by the header row, for a model that reasons better over JSON await neurolink.generate({ input: { text: "Total the amounts.", files: ["workbook.xlsx"] }, provider: "openai", officeOptions: { formatStyle: "json" }, }); ``` Naming a sheet that does not exist does not silently fall back to every sheet. The prompt reports the miss and lists the available sheet names. ## Options `officeOptions` is accepted by `generate()` and `stream()`. Two fields are read, both by the spreadsheet reader: | Option | Type | Default | Effect | | ------------- | ---------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `sheetName` | `string` | all | Restrict the workbook to the named sheet. An unknown name is reported in the prompt together with the sheets that do exist. | | `formatStyle` | `"raw" \| "csv" \| "markdown" \| "json"` | `"raw"` | How each sheet is rendered: tab-separated preview (`raw`), comma-separated values with RFC 4180 quoting (`csv`), a markdown table (`markdown`), or an array of row objects keyed by the header row (`json`). | The exported `OfficeProcessorOptions` type also declares `format`, `extractTextOnly`, `maxSizeMB`, `includeMetadata`, `processAllSheets`, and `includeSlideNotes`. Nothing reads them today, so setting them has no effect. The DOCX and PPTX readers take no options. ### File input formats ```typescript // Path (relative or absolute) files: ["./documents/report.docx", "/absolute/path/to/data.xlsx"]; // Buffer (from fs.readFile or any other source) const pptxBuffer = await readFile("deck.pptx"); files: [pptxBuffer]; // A mix of both files: ["report.docx", pptxBuffer, "./sales.xlsx"]; ``` Office files can sit in `input.files` next to PDFs, images, CSV, audio, and code. Office documents have no field of their own: there are no `docxFiles`, `pptxFiles`, `xlsxFiles`, or `officeFiles` inputs, so always use `input.files`. ## Large Files An Office file in `input.files` (or `--file`) that is within the size bounds under [Limitations](#limitations) is always extracted and inlined in full. There is no on-demand mode for it through `generate()`, `stream()` or the CLI, so a very large workbook or deck is bounded only by those limits and by the model's context window. An SDK caller that wants selective reads can use `FileReferenceRegistry` (exported from `@juspay/neurolink/files`) directly, which is a separate path from `input.files`. Its `extractContent` call returns only the slides in `pages` for a presentation (with the same text and speaker notes as above, and `(No text content on this slide)` for a slide that has neither), or the `sheet`, `row_range` and `columns` you name for a spreadsheet. ## Error Handling Extraction problems do not throw. If an Office file is corrupt, password-protected, a legacy binary format, or simply empty, the prompt carries a note in place of its content and the request goes on: ``` [Presentation File: "deck.pptx"] Size: 2.0 KB Format: application/vnd.openxmlformats-officedocument.presentationml.presentation Error: Could not extract content (ADM-ZIP: Invalid or unsupported zip format. No END header found). The file was attached but could not be fully analyzed. ``` A file that cannot be loaded at all does fail the request. A missing path, for example, surfaces as: ``` Failed to process file "deck.pptx": ENOENT: no such file or directory, open 'deck.pptx' ``` ```typescript try { await neurolink.generate({ input: { text: "Analyze this document", files: ["document.docx"] }, provider: "openai", }); } catch (error) { console.error(error instanceof Error ? error.message : error); } ``` There are no Office-specific error classes. ## Best Practices ### 1. Narrow spreadsheets before sending them Every sheet is rendered into the prompt by default. For a large workbook, name the sheet you need and pick the format the model handles best: ```typescript officeOptions: { sheetName: "Transactions", formatStyle: "csv" } ``` ### 2. Use streaming for long documents ```typescript const result = await neurolink.stream({ input: { text: "Provide a comprehensive analysis of this 100-page document", files: ["long-report.docx"], }, provider: "anthropic", maxTokens: 8000, }); for await (const chunk of result.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } ``` ### 3. Be specific in your prompts ```typescript // Too vague "Tell me about this document"; // Specific and actionable "Extract all action items with their due dates from this meeting notes document"; "List the top 5 products by revenue from the sales spreadsheet"; "Summarize the key points from each slide, and flag anything the speaker notes contradict"; "Compare the financial projections between these two quarterly reports"; ``` ## Limitations - **Open XML only.** `.docx`, `.xlsx`, and `.pptx` are parsed. Legacy `.doc`, `.xls`, and `.ppt` are not (see above). - **Text, tables, and notes only.** Embedded images and charts are not sent to the model (a Word image shows up as an `[Image: alt]` marker), and VBA macros are never run. - **No encrypted files.** A password-protected file cannot be read and arrives as a placeholder note. - **Size bounds.** Word and Excel files are bounded at 100 MB each, and a presentation's extracted content at 100 MB in total (the limits live in `src/lib/processors/config/sizeLimits.ts`). Files over the 200 MB general ceiling are refused when loaded. - **Prompt size.** The extracted text counts against the model's context window. A big workbook or a long document can fill it; use `sheetName`, a leaner `formatStyle`, or a model with a larger window. ## Troubleshooting ### The model says it cannot read the document Look for the `Could not extract content` note in the prompt. Typical causes: 1. **Legacy format**: a `.doc`, `.xls`, or `.ppt`. Re-save it as `.docx`, `.xlsx`, or `.pptx`. 2. **Corrupt or truncated file**: confirm it opens in Office. An Office Open XML file is a ZIP and starts with the bytes `PK\x03\x04`. 3. **Password protection**: remove the password before attaching. 4. **No text in the file**: a deck of pictures or a scanned document has nothing to extract, and a picture-only deck arrives as just the `Presentation: N slide(s)` header with no placeholder note. Convert scans to text with OCR first, or attach the images instead. ```typescript const buffer = await readFile("document.docx"); console.log("Magic bytes:", buffer.subarray(0, 4).toString("hex")); // "504b0304" console.log("Size:", (buffer.length / (1024 * 1024)).toFixed(2), "MB"); ``` ### A sheet is missing from the output If you passed `sheetName`, the name must match exactly. When it does not, the prompt says so and lists the sheet names the workbook has. ### A request fails with `Failed to process file` The path or URL could not be loaded. Check that the file exists and that the process can read it. ## Migrating from Manual Extraction If you extracted text yourself before sending it to the model: ```typescript // Before: extract by hand, paste into the prompt const { value: text } = await mammoth.extractRawText({ buffer: readFileSync("report.docx"), }); const result = await neurolink.generate({ input: { text: `Analyze this document:\n\n${text}` }, provider: "openai", }); // After: attach the file; headings, lists, and tables are kept as Markdown const result = await neurolink.generate({ input: { text: "Analyze this document", files: ["report.docx"] }, provider: "openai", }); ``` ## Related Features - [Multimodal Chat](/docs/features/multimodal-chat) - Overview of multimodal capabilities - [PDF Support](/docs/features/pdf-support) - PDF document processing - [CSV Support](/docs/features/csv-support) - CSV file processing ## Technical Details ### Office Document Processing Flow ``` 1. The caller lists the file in input.files (SDK) or passes --file (CLI) ↓ 2. FileDetector identifies the format (magic bytes, MIME type, extension) ↓ 3. The matching reader extracts the content: WordProcessor (docx), ExcelProcessor (xlsx), PptxProcessor (pptx) ↓ 4. messageBuilder appends it to input.text under a "## Document / Spreadsheet / Presentation" heading ↓ 5. The provider receives a plain text prompt ``` An extraction failure at step 3 produces the placeholder note shown under Error Handling instead of content. ### Implementation Files - **`src/lib/processors/document/`** - `WordProcessor`, `ExcelProcessor`, `PptxProcessor`, `RtfProcessor`, `OpenDocumentProcessor` - **`src/lib/utils/fileDetector.ts`** - Format detection and routing of Office files to their readers - **`src/lib/utils/messageBuilder.ts`** - Appends extracted text to the prompt - **`src/lib/types/file.ts`** - `OfficeProcessorOptions` - **`src/lib/files/fileReferenceRegistry.ts`** - Targeted slide, sheet, and row reads for files held in a `FileReferenceRegistry` (SDK only; not reached through `input.files`) - **`src/cli/factories/commandFactory.ts`** - CLI `--file` flag handling --- **Next:** [Multimodal Chat Guide](/docs/features/multimodal-chat) | [PDF Support](/docs/features/pdf-support) | [CSV Support](/docs/features/csv-support) --- ## OpenCode Support for NeuroLink Proxy # OpenCode Support for NeuroLink Proxy ## Status: Implemented & Verified This document was originally written as a design proposal. Every item it called out as missing or to-be-built has since been implemented and verified end-to-end (see §11). The "what was built" wording in §4 and §8 reflects the delivered state; future-tense language has been kept only where it explains historical context. ## 2. How Claude Code Auto-Configuration Works Today When `neurolink proxy start` runs: 1. **Server starts** on configured port (default 4141) 2. **Accounts are loaded** from proxy config + OAuth credentials 3. **Claude Code settings are auto-configured**: - Writes to `~/.claude/settings.json` - Sets `env.ANTHROPIC_BASE_URL = "http://localhost:"` - Sets `env.ENABLE_TOOL_SEARCH = "true"` - Preserves original values in `__proxy_original_env` for restoration 4. **On proxy stop**: restores original Claude Code settings Key code (`src/cli/commands/proxy.ts`): ```typescript const CLAUDE_SETTINGS_PATH = join(homedir(), ".claude", "settings.json"); const PROXY_MANAGED_KEYS = ["ANTHROPIC_BASE_URL", "ENABLE_TOOL_SEARCH"]; async function setClaudeProxySettings(baseUrl: string): Promise { // Reads ~/.claude/settings.json // Snapshots original env values // Sets ANTHROPIC_BASE_URL to proxy URL // Writes back } ``` Claude Code then sends all requests to the proxy's `/v1/messages` endpoint (Anthropic Messages API format). --- ## 3. How OpenCode Configuration Works ### Config File Locations OpenCode uses XDG base directories via the `xdg-basedir` npm package, which resolves `XDG_CONFIG_HOME || ~/.config` on **every** platform — there is no macOS special case. (OpenCode's binary does contain a `/Library/Application Support/opencode` literal, but that is `systemManagedConfigDir()`, an MDM policy directory at the filesystem root with no `$HOME` prefix — not the per-user config path.) | Platform | Global Config Path | | ----------- | ----------------------------------------------- | | **macOS** | `~/.config/opencode/opencode.json` | | **Linux** | `~/.config/opencode/opencode.json` | | **Windows** | `~/.config/opencode/opencode.json` (unverified) | The macOS row was verified empirically against OpenCode 1.3.13 (embedded `xdg-basedir` source in the shipped binary, plus `opencode models` confirming which file is actually loaded). The Windows row follows from the same branch-free resolution code but has **not** been checked on a Windows machine. Project-level config: `.opencode/opencode.json` in any parent directory. ### Provider Config Schema From `packages/opencode/src/config/config.ts` (line 787-846): ```typescript Config.Provider = ModelsDev.Provider.partial().extend({ models: z.record(z.string(), ModelsDev.Model.partial()).optional(), options: z .object({ apiKey: z.string().optional(), baseURL: z.string().optional(), // ... timeout, chunkTimeout, etc. }) .catchall(z.any()) .optional(), }); Config.Info = z.object({ // ... provider: z.record(z.string(), Config.Provider).optional(), model: z.string().optional(), // format: "provider/model" // ... }); ``` ### How OpenCode Loads Providers From `packages/opencode/src/provider/provider.ts`: 1. **Bundled providers** are imported directly (line 127-150): ```typescript const BUNDLED_PROVIDERS = { "@ai-sdk/openai": createOpenAI, "@ai-sdk/anthropic": createAnthropic, "@ai-sdk/openai-compatible": createOpenAICompatible, // ... 20+ providers }; ``` 2. **Custom providers** from config's `provider` field get initialized with their `options` (including `baseURL`, `apiKey`) 3. **Model definitions** come from `models.dev` API (fetched and cached) + config overrides 4. **Auto-discovery**: if env vars for a provider are set (e.g., `ANTHROPIC_API_KEY`), that provider loads automatically ### The Key: `@ai-sdk/openai-compatible` When OpenCode uses a custom provider with `npm: "@ai-sdk/openai-compatible"`, it: - Creates an SDK instance via `createOpenAICompatible({ baseURL, apiKey })` - Sends requests to `{baseURL}/chat/completions` (the AI SDK appends the path) - Uses standard OpenAI Chat Completions wire format - Handles streaming via SSE (`data: {"choices":[...]}` format) --- ## 4. The Gap (Closed): What Was Built ### Endpoints — Added The proxy now exposes both shapes: | Endpoint | Format | For client | Status | | ----------------------------------------- | --------------------------- | ------------ | ------------------------------------- | | `POST /v1/messages` | Anthropic Messages API | Claude Code | Pre-existing | | `POST /v1/messages/count_tokens` | Anthropic | Claude Code | Pre-existing | | `GET /v1/models` (Anthropic format) | Anthropic | Claude Code | Pre-existing | | **`POST /v1/chat/completions`** | **OpenAI Chat Completions** | **OpenCode** | **Added (`openaiProxyRoutes.ts`)** | | **`GET /v1/models` (OpenAI list format)** | **OpenAI** | **OpenCode** | **Added (`buildModelsListResponse`)** | ### Auto-Configuration — Added `src/cli/commands/proxy.ts` gained the symmetric helpers used during `proxy start` / `proxy stop`: - `setOpenCodeProxySettings(baseUrl)` — line 293, writes the `provider.neurolink` block to OpenCode's `opencode.json` (XDG-resolved path) - `clearOpenCodeProxySettings(baseUrl)` — line 341, removes only entries whose `baseURL` matches the proxy's - Wired into the start path (line 1431) and stop/uninstall paths (lines 1292, 2357) - Skipped automatically under `--dev` so isolated dev instances never touch the user's OpenCode config --- ## 5. Architecture ### Data Flow ``` OpenCode NeuroLink Proxy Any Provider ─────── ────────────── ──────────── @ai-sdk/openai-compatible createOpenAICompatible({ baseURL: "http://localhost:4141/v1", apiKey: "proxy-key" }) │ ▼ POST /v1/chat/completions ────▶ openaiProxyRoutes.ts { │ model: "claude-sonnet-4", ├─ parseOpenAIRequest() messages: [...], │ → Extract system prompt tools: [...], │ → Flatten messages stream: true │ → Convert tools (function → AI SDK) } │ → Map tool_choice │ ├─ ModelRouter.resolve(model) │ → claude-* → anthropic │ → gemini-* → vertex │ → custom mappings │ ├─ buildProxyTranslationPlan() │ → Classify request │ → Build fallback chain │ ├─ ctx.neurolink.stream(options) ──────▶ Any Provider │ (Anthropic, Google, │ OpenAI, Bedrock, etc.) ▼ serializeOpenAIResponse() OpenAIStreamSerializer │ SSE Response ◀────────────────────┘ data: {"choices":[{"delta":{"content":"..."}}]} data: {"choices":[{"delta":{"tool_calls":[...]}}]} data: {"choices":[{"delta":{},"finish_reason":"stop"}]} data: [DONE] ``` ### Symmetric Design | Aspect | Claude Code Path | OpenCode Path | | ---------------------- | ----------------------------------- | ------------------------------------ | | **Wire format** | Anthropic Messages API | OpenAI Chat Completions | | **Endpoint** | `POST /v1/messages` | `POST /v1/chat/completions` | | **Format translator** | `claudeFormat.ts` | `openaiFormat.ts` (NEW) | | **Route handler** | `claudeProxyRoutes.ts` | `openaiProxyRoutes.ts` (NEW) | | **Stream serializer** | `ClaudeStreamSerializer` | `OpenAIStreamSerializer` (NEW) | | **Auto-config target** | `~/.claude/settings.json` | XDG `opencode.json` | | **Auto-config key** | `env.ANTHROPIC_BASE_URL` | `provider.neurolink.options.baseURL` | | **Internal pipeline** | Same `ctx.neurolink.stream()` | Same `ctx.neurolink.stream()` | | **Model routing** | Same `ModelRouter` | Same `ModelRouter` | | **Account management** | Same accounts, cooldowns, fallbacks | Same accounts, cooldowns, fallbacks | --- ## 6. Wire Format Translation ### Request: OpenAI → Internal | OpenAI Field | NeuroLink Internal | Notes | | ------------------------------------------------ | ---------------------------------------------- | ------------------------------------ | | `messages[role="system"].content` | `systemPrompt` | Concatenate multiple system messages | | `messages[role="user/assistant/tool"]` | `conversationMessages[]` | Flatten to `{role, content}` | | Last user message `.content` | `prompt` | Extracted as string | | `messages[role="assistant"].tool_calls` | Inline as `[tool_use:id:name] {args}` | Same pattern as `claudeFormat.ts` | | `messages[role="tool"]` | Inline as `[tool_result:tool_call_id] content` | Same pattern as `claudeFormat.ts` | | `content[type="image_url"].image_url.url` | `images[]` | From latest user message only | | `tools[].function.{name,description,parameters}` | `tools{}` via `jsonSchema()` | AI SDK format | | `tool_choice: "auto"/"required"/"none"` | `toolChoice` | Direct mapping | | `tool_choice: {type:"function",function:{name}}` | `toolChoice: "required"` + `toolChoiceName` | Named tool | | `max_tokens` / `max_completion_tokens` | `maxTokens` | Default 4096 if unset | | `temperature`, `top_p` | `temperature`, `topP` | Direct | | `stop` | `stopSequences` | Direct | | `stream` | `stream` | Direct | ### Response: Internal → OpenAI | NeuroLink `InternalResult` | OpenAI Response | | --------------------------------------- | ------------------------------------------------------------------- | | `content` | `choices[0].message.content` | | `toolCalls[].toolName` | `choices[0].message.tool_calls[].function.name` | | `toolCalls[].args` | `choices[0].message.tool_calls[].function.arguments` (stringified!) | | `toolCalls[].toolCallId` | `choices[0].message.tool_calls[].id` | | `finishReason: "end_turn"/"stop"` | `finish_reason: "stop"` | | `finishReason: "tool-calls"/"tool_use"` | `finish_reason: "tool_calls"` | | `finishReason: "length"/"max_tokens"` | `finish_reason: "length"` | | `usage.input` | `usage.prompt_tokens` | | `usage.output` | `usage.completion_tokens` | | `usage.total` | `usage.total_tokens` | | `model` | `model` | | `reasoning` | Not standard — drop or use custom field | ### Streaming: Internal → OpenAI SSE | Event | SSE Frame | | --------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | Stream start | `data: {"choices":[{"delta":{"role":"assistant"}}]}` | | Text chunk | `data: {"choices":[{"delta":{"content":"text"}}]}` | | Tool call start | `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_xx","type":"function","function":{"name":"Read","arguments":""}}]}}]}` | | Tool call args | `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"chunk"}}]}}]}` | | Finish | `data: {"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{...}}` | | Done | `data: [DONE]` | --- ## 7. Auto-Configuration Design ### Current (Claude Code) ``` neurolink proxy start → setClaudeProxySettings("http://localhost:4141") → writes ~/.claude/settings.json → env.ANTHROPIC_BASE_URL = "http://localhost:4141" neurolink proxy stop → clearClaudeProxySettings() → restores original ~/.claude/settings.json values ``` ### New (OpenCode) — Same Pattern ``` neurolink proxy start → setClaudeProxySettings(...) // existing → setOpenCodeProxySettings("http://localhost:4141/v1", "proxy-key") // NEW → detects OpenCode config path (XDG) → reads existing opencode.json (or creates) → adds provider.neurolink = { npm: "@ai-sdk/openai-compatible", name: "NeuroLink Proxy", env: [], models: { /* available models from proxy config */ }, options: { baseURL: "http://localhost:4141/v1", apiKey: "proxy-key" } } → preserves original values for restoration → writes back neurolink proxy stop → clearClaudeProxySettings() // existing → clearOpenCodeProxySettings() // NEW → removes provider.neurolink from opencode.json → restores original values ``` ### OpenCode Config Path Resolution ```typescript // Same logic as OpenCode's global/index.ts const OPENCODE_CONFIG_DIR = join( xdgConfig ?? join(homedir(), ".config"), "opencode", ); const OPENCODE_CONFIG_PATH = join(OPENCODE_CONFIG_DIR, "opencode.json"); ``` On macOS and Linux alike: `~/.config/opencode/opencode.json` (`XDG_CONFIG_HOME` wins when set) ### Detection The proxy should detect whether OpenCode is installed before writing config: ```typescript async function isOpenCodeInstalled(): Promise { // Check if opencode config directory exists (XDG path) // Or check if opencode binary exists in PATH (which opencode) // Or check if ~/.opencode/ exists in any parent directory } ``` If OpenCode is not installed, skip auto-configuration silently (same behavior as Claude Code — if `~/.claude/` doesn't exist, the proxy doesn't fail). ### Alternative: Env-Var Based Auto-Config OpenCode's provider system has an `autoload` mechanism. Each provider's custom loader checks for env vars (via `input.env.some((item) => env[item])`). If the provider's required env vars are present, it autoloads. For providers using `@ai-sdk/openai-compatible`, the env vars are typically: - `OPENAI_COMPATIBLE_BASE_URL` — the endpoint URL - `OPENAI_COMPATIBLE_API_KEY` — the API key **This means an even simpler auto-config path**: instead of writing to `opencode.json`, the proxy could write env vars to a shared `.env` file or inject them into the process environment. However, the config-file approach is more reliable and matches the Claude Code pattern. ### Both Approaches Combined The proxy should use **both** approaches for maximum compatibility: 1. **Config file** (primary): Write `provider.neurolink` to `opencode.json` — this gives users a visible, editable config entry with model definitions 2. **Env vars** (fallback): If the config file approach fails (permissions, etc.), fall back to writing env vars that `@ai-sdk/openai-compatible` auto-detects --- ## 8. Implementation (Delivered) ### New Files (in this branch) | File | Purpose | | -------------------------------------------- | ------------------------------------------------------------------ | | `src/lib/proxy/openaiFormat.ts` | OpenAI ↔ Internal translator (parser, serializer, SSE transform) | | `src/lib/server/routes/openaiProxyRoutes.ts` | `/v1/chat/completions` + `/v1/models` + Anthropic loopback bridge | | `src/lib/proxy/proxyTranslationEngine.ts` | Unified translation engine shared with the Claude route (refactor) | | `test/fixtures/opencode-local-proxy.json` | OpenCode fixture pointing at the dev proxy | | `docs/features/opencode-proxy-support.md` | This document (design + manual testing playbook) | OpenAI wire types and `ProxyFormat` / `StreamSerializerAdapter` live in `src/lib/types/proxy.ts` (the canonical types barrel; the original design-time path `proxyTypes.ts` was renamed during the release-line refactor). ### Modified Files | File | Change (delivered) | | -------------------------------------------- | ------------------------------------------------------------------------------------------- | | `src/lib/server/routes/index.ts` | Adds `openaiProxy` flag + unified `proxy` flag; registers `createOpenAIProxyRoutes` | | `src/cli/commands/proxy.ts` | Adds `setOpenCodeProxySettings()` and `clearOpenCodeProxySettings()`; wired into start/stop | | `src/lib/proxy/modelRouter.ts` | Surfaces `getModelMappings()` / `getPassthroughModels()` for `buildModelsListResponse` | | `src/lib/types/proxy.ts` | OpenAI wire-format types + `ProxyFormat` + `StreamSerializerAdapter` | | `src/lib/types/server.ts` | `CreateRoutesOptions` gains `proxy` and `openaiProxy` flags | | `src/lib/server/routes/claudeProxyRoutes.ts` | Refactored to share the new translation engine; `/v1/models` returns the unified list | ### Reused As-Is (no changes needed) | Component | Why it works | | --------------------------------- | ----------------------------------------------- | | `ModelRouter` | `resolve()` is format-agnostic | | `routingPolicy.ts` | Request classification works on internal format | | `proxyConfig.ts` | Account pools, model mappings — format-agnostic | | `proxyTracer.ts` | OTel tracing — format-agnostic | | `requestLogger.ts` | Structured logging — format-agnostic | | `usageStats.ts` | Per-account stats — format-agnostic | | NeuroLink `generate()`/`stream()` | The entire backend — unchanged | ### Historical Build Sequence (delivered in this order, all complete) 1. ✅ OpenAI wire types added to the proxy types barrel 2. ✅ `openaiFormat.ts` — parser, response serializer, streaming SSE serializer, error builder 3. ✅ `openaiProxyRoutes.ts` — `/v1/chat/completions` + `/v1/models` + Anthropic loopback bridge 4. ✅ `routes/index.ts` updated with `openaiProxy` and unified `proxy` flags 5. ✅ `setOpenCodeProxySettings()` / `clearOpenCodeProxySettings()` added to `proxy.ts` 6. ✅ `neurolink proxy start` auto-configures OpenCode (skipped under `--dev`) 7. ✅ Manual test plan in §11; verified end-to-end against OpenCode 1.3.13 --- ## 9. User Experience ### Before (Manual) User must manually edit OpenCode config to add a custom provider. No auto-detection. ### After (Zero-Config) ```bash neurolink proxy start # Output: # NeuroLink Proxy v9.47.0 listening on http://localhost:4141 # Claude Code: configured (ANTHROPIC_BASE_URL → http://localhost:4141) # OpenCode: configured (provider.neurolink → http://localhost:4141/v1) # 3 accounts loaded (2 anthropic, 1 vertex) ``` Both Claude Code and OpenCode immediately connect to the proxy. No manual configuration needed. ### Model Selection in OpenCode After auto-config, users select models in OpenCode's TUI model picker. Available models come from the proxy's model mappings + available accounts. The proxy serves them via `GET /v1/models`. --- ## 10. Edge Cases | Case | Handling | | --------------------------------------- | ------------------------------------------------------------------------------------------------- | | OpenCode not installed | Skip auto-config silently | | Existing `provider.neurolink` in config | Update `baseURL`/`apiKey`, preserve other fields | | Proxy stops unexpectedly | OpenCode falls back to its other configured providers | | `n > 1` in request | Ignore — return single choice (NeuroLink generates n=1) | | `response_format: json_object` | Map to `structuredOutput` where provider supports it | | Reasoning/thinking content | Not in standard OpenAI format — drop (OpenCode handles this per-provider via `ProviderTransform`) | | Image content in messages | `image_url` blocks → extract to `images[]` | | Legacy `functions` field | Not supported — `tools` only (matches OpenCode's behavior) | | `stream_options: {include_usage: true}` | Include usage in final streaming chunk | | Auth (`Authorization: Bearer`) | Accept any token (validate against proxy config if auth is enabled) | --- ## 11. Manual Testing & Verification This section is a self-contained playbook for verifying the OpenCode proxy support end to end. It assumes you are on the `feat/opencode-support-for-proxy` branch and the global proxy on `:55669` should remain untouched throughout. ### 11.1 Prerequisites - Node 20+ and `pnpm` available - `opencode` CLI installed (`opencode --version` should print 1.3.x or newer) - `jq` and `curl` available - A working `~/.neurolink/proxy-config.yaml` and `~/.neurolink/.env` (used by the global proxy) - The `dist/` directory built from this branch (`pnpm run build:cli` if not built) ### 11.2 Mental Model You are starting a **second** proxy instance, isolated from the global one: | | Global proxy | Dev proxy under test | | ---------------------- | --------------- | ------------------------ | | Port | 55669 | 5555 | | State dir | `~/.neurolink/` | `/.neurolink-dev/` | | Managed by | launchd | foreground process | | Touched by these tests | Never | Yes | Two safety invariants checked throughout: - `curl http://localhost:55669/health` → 200 (global never goes down) - The dev PID from `.neurolink-dev/proxy-state.json` ≠ the global PID from `~/.neurolink/proxy-state.json` ### 11.3 Why a non-Claude alias is required OpenCode 1.3.13 hardcodes the Anthropic SDK whenever the model name contains `claude` — it bypasses `/v1/chat/completions` and posts directly to `/v1/messages`. To exercise this branch's new OpenAI endpoint end-to-end, the OpenCode fixture must use a non-claude alias (we use `gpt-4o`) and the proxy must be told to map that alias to a real Anthropic model. We map to **Haiku** because Sonnet aggressively rate-limits 150-KB requests with OpenCode's full tool set and produces noisy 429s during testing. ### 11.4 One-time setup ```bash cd /path/to/neurolink/feat/opencode-support-for-proxy # (a) Build CLI if needed pnpm run build:cli # (b) Start fresh — wipe any prior dev state. Global state untouched. rm -rf .neurolink-dev mkdir -p .neurolink-dev # (c) Routing config: extend your global mappings with the gpt-4o alias. # Output goes only to .neurolink-dev/proxy-config.yaml — global config is unchanged. jq '.routing["model-mappings"] += [{"from":"gpt-4o","to":"claude-haiku-4-5","provider":"anthropic"}]' \ ~/.neurolink/proxy-config.yaml > .neurolink-dev/proxy-config.yaml # (d) OpenCode fixture in an isolated workspace. # The repo ships two fixtures: # - test/fixtures/opencode-local-proxy.json (claude-sonnet-4-6, hits /v1/messages — exercises Claude passthrough) # - test/fixtures/opencode-local-proxy-openai-route.json (gpt-4o alias, hits /v1/chat/completions — exercises this branch's new code) # For end-to-end verification of this branch you want the second one. mkdir -p /tmp/opencode-proxy-test cp test/fixtures/opencode-local-proxy-openai-route.json /tmp/opencode-proxy-test/opencode.json ``` ### 11.5 Start the dev proxy (separate terminal) ```bash cd /path/to/neurolink/feat/opencode-support-for-proxy node dist/cli/index.js proxy start --dev --port 5555 --config .neurolink-dev/proxy-config.yaml ``` `--dev` scopes all state to `.neurolink-dev/`, skips launchd, and skips client auto-configuration. Wait for `Server is ready`. In a third terminal, tail the proxy lifecycle log: ```bash cd /path/to/neurolink/feat/opencode-support-for-proxy tail -f .neurolink-dev/logs/proxy-$(date -u +%F).jsonl | jq ``` ### 11.6 Smoke checks | # | Check | Command | Pass criteria | | --- | --------------------- | ---------------------------------------------------------------------------------------- | ----------------------------- | | S1 | Dev proxy up | `curl -s http://localhost:5555/health \| jq` | `status: "ok"`, `ready: true` | | S2 | Global untouched | `curl -s -o /dev/null -w "%{http_code}\n" http://localhost:55669/health` | `200` | | S3 | Routing alias visible | `curl -s http://localhost:5555/v1/models \| jq '.data \| map(.id)'` | List contains `gpt-4o` | | S4 | PIDs distinct | `jq -r .pid .neurolink-dev/proxy-state.json && jq -r .pid ~/.neurolink/proxy-state.json` | Two different numbers | ### 11.7 Wire-level tests (curl directly — no OpenCode needed) These prove the proxy code is correct in isolation. Each test should print `HTTP 200` and a sane response. ```bash PROXY=http://localhost:5555 # W1 Non-streaming curl -s $PROXY/v1/chat/completions -H 'content-type: application/json' \ -d '{"model":"claude-sonnet-4-6","messages":[{"role":"user","content":"Reply with one word: hello."}],"max_tokens":20}' \ | jq '.choices[0].message.content' # W2 Streaming curl -N -s $PROXY/v1/chat/completions -H 'content-type: application/json' \ -d '{"model":"claude-sonnet-4-6","messages":[{"role":"user","content":"Count to 3."}],"max_tokens":30,"stream":true}' # W3 Tool call (request) curl -s $PROXY/v1/chat/completions -H 'content-type: application/json' \ -d '{"model":"claude-sonnet-4-6","max_tokens":200, "messages":[{"role":"user","content":"What is the weather in Tokyo? Use the tool."}], "tools":[{"type":"function","function":{"name":"get_weather","description":"Get current weather", "parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}]}' \ | jq '{finish: .choices[0].finish_reason, tool_calls: .choices[0].message.tool_calls}' # W4 Tool result round-trip — multi-turn with assistant.tool_calls + role:tool message curl -s $PROXY/v1/chat/completions -H 'content-type: application/json' \ -d '{"model":"claude-sonnet-4-6","max_tokens":100, "messages":[ {"role":"user","content":"What is the weather in Tokyo?"}, {"role":"assistant","content":null,"tool_calls":[{"id":"toolu_X","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Tokyo\"}"}}]}, {"role":"tool","tool_call_id":"toolu_X","content":"{\"temp_celsius\":18,\"condition\":\"cloudy\"}"} ], "tools":[{"type":"function","function":{"name":"get_weather","description":"Get current weather", "parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}]}' \ | jq '.choices[0].message.content' # W5 Streaming tool call curl -N -s $PROXY/v1/chat/completions -H 'content-type: application/json' \ -d '{"model":"claude-sonnet-4-6","max_tokens":100,"stream":true, "messages":[{"role":"user","content":"Get weather in Paris."}], "tools":[{"type":"function","function":{"name":"get_weather","description":"Get weather", "parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}]}' ``` Expected: - W1: a one-word reply - W2: SSE chunks ending with `data: [DONE]`, each chunk is `chatcmpl-...` shape - W3: `finish: "tool_calls"`, `tool_calls[0].function.name == "get_weather"`, args `{"city":"Tokyo"}` - W4: a sentence describing 18°C cloudy weather in Tokyo - W5: deltas containing `delta.tool_calls[0]` with progressively concatenating `function.arguments`, ending with `finish_reason: "tool_calls"` ### 11.8 OpenCode end-to-end tests Run from the OpenCode workspace so it picks up the fixture: ```bash cd /tmp/opencode-proxy-test ``` | # | Command | Pass criteria | | --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | | E1 | `opencode run "Reply with exactly one word: hello"` | Output contains `hello` | | E2 | `opencode run "What is 17 multiplied by 23? Reply with just the number."` | Output contains `391` | | E3 | `echo "test content $(date)" > marker.txt && opencode run "Read the file marker.txt and tell me what's in it. Just the content."` | Output contains `test content` | | E4 | `opencode run "Run the bash command 'echo PROXY_E2E_OK' and report its output. Just the output."` | Output contains `PROXY_E2E_OK` | | E5 | `rm -f output.txt && opencode run "Create a file output.txt with the text 'success token 7426'. Then read it back."` | `cat output.txt` shows `success token 7426` | | E6 | `mkdir -p src && echo "function alpha() { return 1; }" > src/a.js && echo "function alpha2() { return 3; }" > src/b.js && opencode run "Use grep to find all functions whose name starts with 'alpha' in src/."` | Output mentions both `alpha` and `alpha2` | | E7 | `opencode run --format json "Reply with one word: jsontest"` | Output is JSON-line stream including `step_start`, `text`, `step_finish` events | | E8 | `opencode run "Write a TypeScript function called add that takes two numbers and returns their sum. Reply with just the code."` | Output contains `function add` (or `const add =`) | | E9 | Multi-turn: capture session id from a first JSON run, then continue (snippet below) | Second turn recalls the number from the first | | E10 | `LONG=$(seq 1 200 \| sed 's/^/item_/' \| tr '\n' ' '); opencode run "Items: $LONG. Reply with only the integer count."` | Output contains `200` | Snippet for E9: ```bash SID=$(opencode run --format json "Remember the number 8472. Reply 'noted'." 2>&1 \ | jq -r 'select(.sessionID)|.sessionID' | head -1) opencode run --session "$SID" "What number did I tell you to remember? Just the number." # expected: 8472 ``` ### 11.9 Empirical proof the request flowed through _this branch's_ code Run this immediately after any OpenCode test above: ```bash cd /path/to/neurolink/feat/opencode-support-for-proxy DATE=$(date -u +%F) # (a) Body captures appeared on disk for that request. ls -td .neurolink-dev/logs/bodies/$DATE/*/ | head -2 # (b) The captured body contains the exact prompt you typed and was tagged with the alias. DIR=$(ls -td .neurolink-dev/logs/bodies/$DATE/*/ | head -1) REQ=$(ls "$DIR" | grep client_request | head -1) gunzip -c "$DIR$REQ" | jq '{ user_agent: .headers["user-agent"], content_length: .headers["content-length"], body_model: (.body | (if type=="string" then fromjson else . end) | .model), user_msg: (.body | (if type=="string" then fromjson else . end) | .messages[-1].content) }' ``` Pass criteria for (b): - `user_agent: "node"` — OpenCode runs on Node - `content_length` ≥ 100000 — only OpenCode sends bodies that large (114 tool defs) - `body_model: "claude-haiku-4-5"` — the proxy's router rewrote `gpt-4o` → `claude-haiku-4-5` _before_ this capture, proving the request passed through `openaiProxyRoutes.ts` and `routingPolicy.ts` - `user_msg` is the exact string you sent OpenCode Independent confirmation from OpenCode's own logs: ```bash cd /tmp/opencode-proxy-test opencode run --print-logs --log-level INFO "ping" 2>&1 \ | grep -E "providerID=neurolink|pkg=@ai-sdk/openai-compatible" ``` Pass: two lines including `pkg=@ai-sdk/openai-compatible using bundled provider` — proves the OpenAI-compatible SDK was used, not the bundled Anthropic SDK. ### 11.10 Negative test (proves OpenCode is exclusively talking to the dev proxy) Stop the dev proxy and verify OpenCode hangs/errors. This rules out any "OpenCode silently bypassed the proxy and went straight to Anthropic" hypothesis. ```bash cd /path/to/neurolink/feat/opencode-support-for-proxy DEV_PID=$(jq -r '.pid' .neurolink-dev/proxy-state.json) GLOBAL_PID=$(jq -r '.pid' ~/.neurolink/proxy-state.json) [ "$DEV_PID" = "$GLOBAL_PID" ] && echo "ABORT: PIDs match — refusing to kill global" && exit 1 kill -TERM "$DEV_PID" && sleep 2 curl -s -o /dev/null -w "dev :5555 after stop: %{http_code}\n" http://localhost:5555/health # expect 000 curl -s -o /dev/null -w "global :55669 still: %{http_code}\n" http://localhost:55669/health # expect 200 cd /tmp/opencode-proxy-test timeout 30 opencode run "ping" ; echo "exit=$?" # Pass: exit 124 (timeout) and no LLM reply printed → OpenCode could not reach any model. ``` Then restart the proxy and rerun any E1–E10 to confirm recovery. ### 11.11 Isolation audit ```bash cd /path/to/neurolink/feat/opencode-support-for-proxy # Global proxy unaffected curl -s -o /dev/null -w "global :55669 health: %{http_code}\n" http://localhost:55669/health # 200 # Dev state lives only in repo-local dir, never in HOME ls .neurolink-dev/ # has proxy-state.json, logs/, account-quotas.json [ -f ~/.neurolink/proxy-state-dev.json ] && echo "BAD: dev leaked into HOME" || echo "no leakage" # Dev proxy is bound only to 5555 lsof -nP -iTCP:5555 -sTCP:LISTEN | head -3 ``` ### 11.12 Cleanup ```bash cd /path/to/neurolink/feat/opencode-support-for-proxy DEV_PID=$(jq -r '.pid' .neurolink-dev/proxy-state.json) GLOBAL_PID=$(jq -r '.pid' ~/.neurolink/proxy-state.json) [ "$DEV_PID" != "$GLOBAL_PID" ] && kill -TERM "$DEV_PID" # Optional: remove dev state # rm -rf .neurolink-dev # Optional: remove test workspace # rm -rf /tmp/opencode-proxy-test ``` ### 11.13 Pass/fail summary checklist A clean run looks like this: - [ ] S1–S4 all pass (proxy up, global untouched, alias visible, PIDs distinct) - [ ] W1–W5 all return HTTP 200 with the expected fields - [ ] E1–E10 all produce the expected output strings - [ ] §11.9 (a) shows ≥1 capture per OpenCode run; (b) shows your prompt verbatim and `body_model: claude-haiku-4-5` - [ ] §11.9 OpenCode debug log shows `pkg=@ai-sdk/openai-compatible` - [ ] §11.10 OpenCode times out / errors out when proxy is killed; resumes when restarted - [ ] §11.11 global :55669 health is 200 throughout If any step deviates, the directory `.neurolink-dev/logs/bodies/$(date -u +%F)//` for the failing request contains the exact request body, every retry attempt, and the upstream response — open the matching `*-upstream_response-attempt-N.json.gz` for the upstream error message. ### 11.14 Known caveats - OpenCode 1.3.13 always sends `claude-*` model names with Anthropic format (bypassing `/v1/chat/completions`). Tests must use the alias indirection described above. - Anthropic Sonnet aggressively 429s 150-KB requests when its per-account burst budget is in cooldown. The alias points to **Haiku** to avoid this. If you need to test Sonnet specifically, expect intermittent 429s. - Both the parent `/v1/chat/completions` request and (for Anthropic-routed traffic) the inner loopback `/v1/messages` request now emit lifecycle entries in `proxy-*.jsonl`. The parent line carries `accountType: "openai-bridge"`; the child carries the OAuth account details from the Claude passthrough path. Filter on `requestId` to correlate them, or filter on `path: /v1/chat/completions` to see only the parent entries. --- ## PDF File Support # PDF File Support NeuroLink provides seamless PDF file support as a **multimodal input type** - attach PDF documents directly to your AI prompts for document analysis, information extraction, and content processing. ## Overview PDF support in NeuroLink works as a native multimodal input - the system automatically processes PDF files and passes them directly to the AI provider's vision/document understanding capabilities. The system: 1. **Validates** PDF files using magic byte detection and format verification 2. **Checks** provider compatibility (Vertex AI, Anthropic, Bedrock, AI Studio) 3. **Verifies** file size and page limits per provider 4. **Passes** PDF directly to the provider's native document API 5. **Works** with providers that support native PDF processing **Key Difference from CSV:** Unlike CSV files which are converted to text, PDFs are sent as binary documents to providers with native PDF support. This enables visual analysis of charts, tables, images, and formatted text within PDFs. ## Quick Start ### SDK Usage ```typescript const neurolink = new NeuroLink(); // Basic PDF analysis const result = await neurolink.generate({ input: { text: "What is the total revenue mentioned in this financial report?", pdfFiles: ["financial-report-q3.pdf"], }, provider: "vertex", // or "anthropic", "bedrock", "google-ai-studio" }); // Multiple PDF comparison const comparison = await neurolink.generate({ input: { text: "Compare the revenue figures between Q1 and Q2 reports. What's the growth percentage?", pdfFiles: ["q1-report.pdf", "q2-report.pdf"], }, provider: "vertex", }); // Auto-detect file types (mix PDF, CSV, and images) const multimodal = await neurolink.generate({ input: { text: "Analyze the financial data in the PDF, compare with the CSV spreadsheet, and verify against the chart image", files: ["report.pdf", "data.csv", "chart.png"], // Auto-detects each type }, provider: "vertex", }); // Streaming with PDF const result = await neurolink.stream({ input: { text: "Provide a detailed summary of this contract, highlighting key terms and obligations", pdfFiles: ["contract.pdf"], }, provider: "anthropic", }); for await (const chunk of result.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } ``` ### CLI Usage ```bash # Attach PDF files to your prompt neurolink generate "Summarize this invoice" --pdf invoice.pdf --provider vertex # Multiple PDF files neurolink generate "Compare these contracts" --pdf contract1.pdf --pdf contract2.pdf --provider anthropic # Auto-detect file types neurolink generate "Analyze report and data" --file report.pdf --file data.csv --provider vertex # Stream mode with PDF neurolink stream "Explain this document in detail" --pdf document.pdf --provider bedrock # Batch processing with PDF echo "Summarize the key points" > prompts.txt echo "Extract all monetary values" >> prompts.txt neurolink batch prompts.txt --pdf invoice.pdf --provider vertex ``` ## API Reference ### GenerateOptions ```typescript type GenerateOptions = { input: { text: string; images?: Array; // Image files csvFiles?: Array; // CSV files (converted to text) pdfFiles?: Array; // PDF files (native binary) files?: Array; // Auto-detect file types }; // Provider selection (REQUIRED for PDF) provider: "vertex" | "anthropic" | "bedrock" | "google-ai-studio"; // Standard options model?: string; maxTokens?: number; temperature?: number; // ... other options }; ``` ### StreamOptions ```typescript type StreamOptions = { input: { text: string; pdfFiles?: Array; // Same as GenerateOptions files?: Array; }; provider: "vertex" | "anthropic" | "bedrock" | "google-ai-studio"; // ... other options }; ``` ### File Input Formats ```typescript // String path (relative or absolute) pdfFiles: ["./documents/invoice.pdf"]; pdfFiles: ["/absolute/path/to/report.pdf"]; // Buffer (from fs.readFile or other source) const pdfBuffer = await readFile("document.pdf"); pdfFiles: [pdfBuffer]; // Mixed types pdfFiles: ["invoice.pdf", pdfBuffer, "./report.pdf"]; ``` ### Encrypted (Password-Protected) PDFs Providers without native PDF support fall back to rendering each page to an image. When the source PDF is encrypted, supply the open password so that image-conversion path can decrypt it. The password is only used locally during rendering — it is never sent to the model. ```typescript // SDK — pass the password via pdfOptions const result = await neurolink.generate({ input: { text: "Summarise this statement", pdfFiles: ["./secured.pdf"] }, provider: "azure", // vision provider that renders PDF pages to images pdfOptions: { password: "s3cret" }, }); ``` ```bash # CLI — preferred: set NEUROLINK_PDF_PASSWORD so the password never appears # in shell history, `ps`/process listings, or CI logs. NEUROLINK_PDF_PASSWORD=s3cret neurolink generate "Summarise this statement" \ --pdf ./secured.pdf --provider azure # CLI — --pdf-password is still supported for convenience, but is visible in # shell history and process listings. Using it prints a one-line warning # recommending NEUROLINK_PDF_PASSWORD instead. neurolink generate "Summarise this statement" \ --pdf ./secured.pdf --provider azure --pdf-password s3cret ``` `--pdf-password` takes precedence when both are set. Both work for `generate` and `stream`. Error behaviour (both SDK and CLI): | Situation | Error code | Message | | -------------------------------- | ------------------------ | -------------------------------------------------------------------- | | Encrypted PDF, no password given | `PDF_PASSWORD_REQUIRED` | Prompts you to supply `pdfOptions: { password }` / `--pdf-password`. | | Wrong password supplied | `PDF_INCORRECT_PASSWORD` | Tells you the supplied password is incorrect. | > Providers with **native** PDF support (Vertex, Anthropic, Bedrock, Google > AI Studio) forward the raw PDF bytes to the model and do not use the > image-conversion path, so `password` has no effect there — an encrypted > PDF must be decrypted upstream for those providers. ### Memory Safety: Page Canvas Limits To prevent memory exhaustion on PDFs with very large page dimensions, the image-conversion path caps the rendered canvas at `maxCanvasPixels` (default 16,777,216 px ≈ 4096×4096). Oversized pages are automatically downscaled to fit the cap (a WARN is logged), so a malicious or malformed `/MediaBox` cannot force an unbounded allocation. Override the cap via `pdfOptions.maxCanvasPixels` when you need higher-resolution rendering: ```typescript pdfOptions: { maxCanvasPixels: 33_554_432, // 32 MP ceiling } ``` ### Conversion Resilience & Limits The image-fallback path (providers without native PDF support) is hardened: - **Accurate page counts (#287).** Page-limit enforcement and the reported `metadata.estimatedPages` use a real pdfjs parse (time-bounded), not a header regex that miscounts compressed/object-stream PDFs. It degrades to the regex estimate on timeout/failure. - **Per-page isolation (#294).** A single page that fails to render no longer discards the whole conversion — the successful pages are returned and each failure is reported in `result.errors` as `{ page, error }`. - **Default render scale 1.5 (#297).** Lowered from 2 to roughly halve per-page canvas memory; the render scale is validated to the `0.1`–`10` range, and an estimated-memory line is logged before conversion. - **Aggregate multi-PDF limits (#309).** When several PDFs are attached, their combined page count and size are checked against the provider's ceiling — N files each under the single-file limit can no longer exceed it together. - **URL pre-flight (#317).** A remote PDF's `Content-Length` is checked with a `HEAD` request before any body is downloaded, so an oversized URL is rejected up front (falling back to the streaming byte guard when the header is absent). ### Streaming Conversion For large documents, `PDFProcessor.convertToImagesStream()` yields each page's image as soon as it renders (with an optional `onProgress` callback) instead of buffering the whole document (#302): ```typescript for await (const page of PDFProcessor.convertToImagesStream(pdfBuffer, { onProgress: ({ pagesConverted, totalPages, elapsedMs }) => console.log(`${pagesConverted}/${totalPages} in ${elapsedMs}ms`), })) { if (page.error) { console.warn(`page ${page.pageIndex} failed: ${page.error}`); } else { handlePng(page.image); // base64 PNG } } ``` `convertToImages()` is **not** implemented as a wrapper over this stream — it's a separate, parallel implementation with its own page-render loop that happens to return the same per-page `errors` contract (an array of `{ page, error }` collected across the whole document instead of yielded per-page). Pick whichever fits the call site: `convertToImagesStream()` to start handling pages before the whole document finishes rendering, `convertToImages()` for a single buffered result. ## Provider Support ### Supported Providers | Provider | Max Size | Max Pages | API Type | Notes | | --------------------- | -------- | --------- | --------- | --------------------------- | | **Google Vertex AI** | 5 MB | 100 | Document | Recommended for general use | | **Anthropic Claude** | 5 MB | 100 | Document | Best for detailed analysis | | **AWS Bedrock** | 5 MB | 100 | Document | Enterprise deployments | | **Google AI Studio** | 2000 MB | 100 | Files API | Largest file support | | **OpenAI** | 10 MB | 100 | Files API | GPT-4o, GPT-4o-mini, o1 | | **LiteLLM** | 10 MB | 100 | Proxy | Depends on upstream model | | **OpenAI Compatible** | 10 MB | 100 | Proxy | Depends on upstream model | ### Unsupported Providers The following providers **do not currently support** native PDF processing: - Azure OpenAI - Ollama (local models) **Error Message for Unsupported Providers:** ``` PDF files are not currently supported with azure-openai provider. Supported providers: Google Vertex AI, Anthropic, AWS Bedrock, Google AI Studio, OpenAI Current provider: azure-openai Options: 1. Switch to a supported provider (--provider vertex or --provider openai) 2. Convert your PDF to text manually 3. Wait for future update (Azure OpenAI conversion is planned) ``` > **PDF-to-image page-size guard:** for providers reached via the image-conversion fallback, each page is rendered to a bounded canvas. A page whose dimensions × render scale would exceed the per-page pixel ceiling (`PDF_LIMITS.DEFAULT_MAX_CANVAS_PIXELS`, ~16.7M px ≈ 64 MB) is **uniformly downscaled** rather than allocating gigabytes of memory — so a large-format PDF (architectural drawing, map) is converted safely instead of exhausting memory. A warning is included in the conversion result when downscaling occurs. ### Provider-Specific Features #### Google Vertex AI ```typescript await neurolink.generate({ input: { text: "Analyze this report", pdfFiles: ["report.pdf"], }, provider: "vertex", model: "gemini-1.5-pro", // Best for document understanding }); ``` #### Anthropic Claude ```typescript await neurolink.generate({ input: { text: "Extract all invoice details", pdfFiles: ["invoice.pdf"], }, provider: "anthropic", model: "claude-sonnet-4-6", // Latest model }); ``` #### AWS Bedrock (with Converse API) ```typescript await neurolink.generate({ input: { text: "Summarize this contract", pdfFiles: ["contract.pdf"], }, provider: "bedrock", // Visual PDF analysis with citations // Text-only: ~1,000 tokens/3 pages // Visual: ~7,000 tokens/3 pages }); ``` #### Google AI Studio ```typescript await neurolink.generate({ input: { text: "Analyze this large document", pdfFiles: ["large-report.pdf"], // Up to 2GB! }, provider: "google-ai-studio", }); ``` ## Features ### 1. Auto-Detection Use the `files` array for automatic file type detection: ```typescript // Automatically detects PDF, CSV, and image types await neurolink.generate({ input: { text: "Analyze all these documents", files: [ "report.pdf", // Auto-detected as PDF "data.csv", // Auto-detected as CSV "chart.png", // Auto-detected as image ], }, provider: "vertex", }); ``` ### 2. Multiple PDF Files Process multiple PDFs in a single request: ```typescript // Compare documents await neurolink.generate({ input: { text: "Compare version 1 and version 2 of the contract. What changed?", pdfFiles: ["contract-v1.pdf", "contract-v2.pdf"], }, provider: "anthropic", }); // Analyze related documents await neurolink.generate({ input: { text: "Summarize insights from all quarterly reports", pdfFiles: [ "q1-report.pdf", "q2-report.pdf", "q3-report.pdf", "q4-report.pdf", ], }, provider: "vertex", }); ``` ### 3. Size and Page Limits Each provider has specific limits: ```typescript // Example: Checking file size before upload const fileStats = await stat("large-document.pdf"); const sizeMB = fileStats.size / (1024 * 1024); if (sizeMB > 5) { // Use Google AI Studio for large files provider = "google-ai-studio"; // Supports up to 2GB } else { // Use Vertex AI for normal files provider = "vertex"; // Up to 5MB } ``` ### 4. Mixed Multimodal Inputs Combine PDFs with other file types: ```typescript // PDF + CSV analysis await neurolink.generate({ input: { text: "Compare the PDF report with the CSV data. Are there any discrepancies?", pdfFiles: ["report.pdf"], csvFiles: ["raw-data.csv"], }, provider: "vertex", }); // PDF + Image verification await neurolink.generate({ input: { text: "Does the chart in the image match the data in the PDF report?", pdfFiles: ["report.pdf"], images: ["chart.png"], }, provider: "vertex", }); // All three types await neurolink.generate({ input: { text: "Analyze the PDF document, compare with CSV data, and verify against the screenshot", files: ["document.pdf", "data.csv", "screenshot.png"], }, provider: "vertex", }); ``` ## Best Practices ### 1. Choose the Right Provider ```typescript // For detailed document analysis provider: "anthropic"; // Claude excels at understanding complex documents // For large files (>5MB) provider: "google-ai-studio"; // Supports up to 2GB // For general use with good balance provider: "vertex"; // Gemini 1.5 Pro recommended // For enterprise/on-premises provider: "bedrock"; // AWS infrastructure ``` ### 2. Optimize File Size ```typescript // Check file size before processing async function validatePDF(filePath: string, provider: string) { const stats = await stat(filePath); const sizeMB = stats.size / (1024 * 1024); const limits = { vertex: 5, anthropic: 5, bedrock: 5, "google-ai-studio": 2000, }; if (sizeMB > limits[provider]) { throw new Error( `File ${filePath} (${sizeMB.toFixed(2)}MB) exceeds ${limits[provider]}MB limit for ${provider}`, ); } console.log(`✓ File validated: ${sizeMB.toFixed(2)}MB`); } await validatePDF("report.pdf", "vertex"); ``` ### 3. Handle Errors Gracefully ```typescript try { const result = await neurolink.generate({ input: { text: "Analyze this PDF", pdfFiles: ["document.pdf"], }, provider: "vertex", }); } catch (error) { if (error.message.includes("not currently supported")) { console.error("PDF not supported by this provider. Try: --provider vertex"); } else if (error.message.includes("exceeds")) { console.error("File too large. Try: --provider google-ai-studio"); } else if (error.message.includes("Invalid PDF")) { console.error("File is not a valid PDF format"); } else { console.error("Error:", error.message); } } ``` ### 4. Use Streaming for Large Documents ```typescript // For long documents, use streaming to get results faster const result = await neurolink.stream({ input: { text: "Provide a detailed analysis of this 50-page report", pdfFiles: ["long-report.pdf"], }, provider: "vertex", maxTokens: 8000, }); for await (const chunk of result.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } ``` ### 5. Be Specific in Your Prompts ```typescript // ❌ Too vague "Tell me about this PDF"; // ✅ Specific and actionable "Extract all monetary values from this invoice and sum them up"; "List all action items mentioned in this meeting notes PDF"; "Compare the Q1 and Q2 revenue figures from these financial reports"; "Find any mentions of security vulnerabilities in this audit report"; ``` ## Limitations ### File Format Requirements - **Must** be valid PDF files (starting with `%PDF-` magic bytes) - **Must** be within provider size limits (5MB for most, 2GB for AI Studio) - **Must** have valid PDF structure (not corrupted) ### Provider Limitations ```typescript // ❌ Will fail with unsupported providers await neurolink.generate({ input: { text: "Analyze this PDF", pdfFiles: ["doc.pdf"], }, provider: "azure-openai", // Not supported }); // ✅ Use supported providers await neurolink.generate({ input: { text: "Analyze this PDF", pdfFiles: ["doc.pdf"], }, provider: "openai", // Supported (GPT-4o, GPT-4o-mini, o1) }); ``` ### Page Limits All providers limit PDF to **100 pages maximum**: ```typescript // Warning logged for large documents // [PDF] PDF appears to have 150+ pages. vertex supports up to 100 pages. ``` ### Token Usage PDFs consume significant tokens: - **Text-only mode**: ~1,000 tokens per 3 pages - **Visual mode**: ~7,000 tokens per 3 pages **Tip:** Set appropriate `maxTokens` for PDF analysis: ```typescript await neurolink.generate({ input: { text: "Summarize this 10-page document", pdfFiles: ["document.pdf"], }, provider: "vertex", maxTokens: 4000, // ~3,000 tokens for PDF + 1,000 for response }); ``` ## Troubleshooting ### Error: "PDF files are not currently supported" **Problem:** Using unsupported provider (Azure OpenAI, Ollama, etc.) **Solution:** ```bash # Change provider to supported one neurolink generate "Analyze PDF" --pdf doc.pdf --provider vertex # Or use auto-detection with correct provider neurolink generate "Analyze PDF" --file doc.pdf --provider anthropic ``` ### Error: "PDF size exceeds limit" **Problem:** File too large for provider (>5MB for most providers) **Solution:** ```bash # Switch to Google AI Studio (2GB limit) neurolink generate "Analyze PDF" --pdf large-doc.pdf --provider google-ai-studio # Or compress PDF externally before upload ``` ### Error: "Invalid PDF file format" **Problem:** File is not a valid PDF or corrupted **Solution:** ```bash # Verify file is valid PDF file document.pdf # Should show "PDF document" # Check magic bytes head -c 5 document.pdf # Should show "%PDF-" # Try re-saving or repairing PDF ``` ### Error: "Provider not specified" **Problem:** No provider selected (PDF requires explicit provider) **Solution:** ```typescript // ❌ Missing provider await neurolink.generate({ input: { text: "Analyze", pdfFiles: ["doc.pdf"], }, }); // ✅ Specify provider await neurolink.generate({ input: { text: "Analyze", pdfFiles: ["doc.pdf"], }, provider: "vertex", }); ``` ### PDF Content Not Being Analyzed **Problem:** AI says "I cannot read the PDF" even though file is attached **Common Causes:** 1. **Wrong provider**: Make sure using supported provider 2. **File path wrong**: Verify file exists at specified path 3. **Buffer issue**: If using Buffer, ensure it's valid PDF data **Debug:** ```typescript // Verify file exists await stat("document.pdf"); // Throws if not found // Verify it's a valid PDF const buffer = await readFile("document.pdf"); const header = buffer.toString("utf-8", 0, 5); console.log("PDF header:", header); // Should be "%PDF-" // Check size const sizeMB = buffer.length / (1024 * 1024); console.log("Size:", sizeMB.toFixed(2), "MB"); ``` ## Advanced Usage ### Custom Provider Configurations ```typescript // AWS Bedrock with Converse API await neurolink.generate({ input: { text: "Analyze with citations", pdfFiles: ["document.pdf"], }, provider: "bedrock", model: "anthropic.claude-3-sonnet-20240229-v1:0", // Bedrock automatically enables citations for visual PDF analysis }); ``` ### Combining Multiple File Types ```typescript // Real-world example: Financial analysis await neurolink.generate({ input: { text: ` 1. Review the PDF financial report for Q3 results 2. Compare with the raw transaction data in the CSV 3. Verify the summary chart matches the data 4. Highlight any discrepancies `, pdfFiles: ["q3-financial-report.pdf"], csvFiles: ["q3-transactions.csv"], images: ["q3-summary-chart.png"], }, provider: "vertex", maxTokens: 8000, }); ``` ### Batch Processing Multiple PDFs ```typescript // Process multiple invoices const invoices = [ "invoice-001.pdf", "invoice-002.pdf", "invoice-003.pdf", // ... more files ]; for (const invoice of invoices) { const result = await neurolink.generate({ input: { text: "Extract: invoice number, date, total amount, vendor name", pdfFiles: [invoice], }, provider: "anthropic", }); console.log(`${invoice}:`, result.content); } ``` ### Using with AI Tools ```typescript // PDF analysis with tool use await neurolink.generate({ input: { text: "Analyze this invoice and save the data", pdfFiles: ["invoice.pdf"], }, provider: "vertex", tools: { saveInvoiceData: { description: "Save extracted invoice data", parameters: { type: "object", properties: { invoiceNumber: { type: "string" }, date: { type: "string" }, amount: { type: "number" }, vendor: { type: "string" }, }, }, execute: async (params) => { // Save to database await db.invoices.insert(params); return "Saved successfully"; }, }, }, }); ``` ## Examples See `examples/pdf-analysis.ts` for complete working examples: - Basic PDF analysis - Multiple PDF comparison - Mixed file type analysis (PDF + CSV) - Provider-specific features - Error handling patterns ## Related Features - [Multimodal Chat](/docs/features/multimodal-chat) - Overview of multimodal capabilities - [Office Documents](/docs/features/office-documents) - DOCX, PPTX, XLSX processing - [CSV Support](/docs/features/csv-support) - CSV file processing - [Image Support](/docs/features/multimodal-chat#images) - Image analysis ## Technical Details ### PDF Processing Flow ``` 1. User provides PDF file(s) ↓ 2. FileDetector validates format (magic bytes) ↓ 3. PDFProcessor checks provider support ↓ 4. Validate size/page limits ↓ 5. Pass Buffer to messageBuilder ↓ 6. Format as the provider's native file/document part ↓ 7. Send to provider's native PDF API ↓ 8. Provider processes PDF visually ↓ 9. Return AI response ``` ### Implementation Files - **`src/lib/utils/pdfProcessor.ts`** - PDF validation and processing - **`src/lib/utils/fileDetector.ts`** - File type detection - **`src/lib/utils/messageBuilder.ts`** - Multimodal message construction - **`src/lib/types/fileTypes.ts`** - PDF type definitions - **`src/cli/factories/commandFactory.ts`** - CLI `--pdf` flag handling ### Type Definitions ```typescript // PDF Processor Options type PDFProcessorOptions = { provider?: string; bedrockApiMode?: "converse" | "invoke"; }; // PDF Provider Configuration type PDFProviderConfig = { maxSizeMB: number; maxPages: number; supportsNative: boolean; requiresCitations: boolean | "auto"; apiType: "document" | "files-api" | "unsupported"; }; // File Processing Result type FileProcessingResult = { type: "pdf"; content: Buffer; mimeType: "application/pdf"; metadata: { confidence: number; size: number; version: string; estimatedPages: number | null; provider: string; apiType: string; }; }; ``` ## Performance Considerations ### Token Usage - **10-page PDF**: ~3,000-23,000 tokens (depending on visual mode) - **Set maxTokens appropriately**: PDF tokens + expected response tokens - **Monitor costs**: PDFs use more tokens than text inputs ### Processing Speed - **Small PDFs (\5MB)**: ~5-15 seconds - **Use streaming**: Get results faster for long responses ### Memory Usage - PDFs loaded as Buffers in memory - Large files (>100MB) may impact performance - Consider processing large files in chunks if possible ## Future Enhancements Planned features for PDF support: - **OCR Integration**: Extract text from scanned PDFs - **Page Selection**: Analyze specific pages only - **PDF Generation**: Create PDFs from AI responses - **Form Filling**: Extract and populate PDF forms ## Feedback and Support Found a bug or have a feature request? Please: 1. Check existing issues on GitHub 2. Create a new issue with: - Provider used - PDF file details (size, pages) - Error message or unexpected behavior - Sample code (if possible) ## Changelog ### Version 9.2.0 (Current) - ✅ Initial PDF support for Vertex AI, Anthropic, Bedrock, AI Studio - ✅ Auto-detection via `--file` flag - ✅ Multiple PDF processing - ✅ Size and page limit validation - ✅ Comprehensive error messages - ✅ CLI and SDK integration - ✅ Streaming support - ✅ Mixed multimodal inputs (PDF + CSV + images) --- **Next:** [Multimodal Chat Guide](/docs/features/multimodal-chat) | [CSV Support](/docs/features/csv-support) --- ## Per-Request Credentials # Per-Request Credentials > **Status**: Stable | **Availability**: SDK only ## Overview NeuroLink allows provider credentials to be supplied at two levels below the environment-variable default: on the `NeuroLink` constructor (instance level) and on individual `generate()` / `stream()` calls (per-call level). Credentials are resolved in the following order of precedence: ``` per-call credentials > instance credentials > environment variables ``` This enables multi-tenant architectures where different users or tenants supply their own provider API keys (bring-your-own-key, BYOK), without requiring separate NeuroLink instances per user or touching the process environment. Typical use cases: - **Multi-tenant SaaS** — each API request carries the calling user's provider key; no shared key leakage between tenants - **BYOK products** — end users paste their OpenAI / Anthropic keys in settings; you forward them to NeuroLink per call - **Testing and CI** — inject credentials programmatically without setting environment variables - **Provider switching** — override only the active provider's credentials while leaving others to fall through to env vars ## Quick Start ```typescript // Instance-level default: all calls from this instance use these credentials const neurolink = new NeuroLink({ credentials: { openai: { apiKey: "sk-instance-key" }, }, }); // Per-call override: this single call uses a different key const result = await neurolink.generate({ input: { text: "Summarize this document" }, provider: "openai", credentials: { openai: { apiKey: "sk-tenant-key" }, }, }); ``` ## Instance-Level vs Per-Call ### Instance-Level Credentials Set `credentials` in the `NeuroLink` constructor. These apply as the default for every `generate()` and `stream()` call made on that instance. Useful when serving a single tenant or when you have a known key for the duration of the instance lifecycle. ```typescript const neurolink = new NeuroLink({ credentials: { anthropic: { apiKey: "sk-ant-..." }, openai: { apiKey: "sk-..." }, }, }); ``` ### Per-Call Credentials Set `credentials` directly on `generate()` or `stream()`. These override the instance-level credentials for that single call only. Only the providers you explicitly set are overridden — others continue falling through to instance credentials and then environment variables. ```typescript const result = await neurolink.generate({ input: { text: "Hello" }, provider: "anthropic", credentials: { anthropic: { apiKey: "sk-ant-user-specific-key" }, // openai left unset — falls through to instance or env var }, }); ``` ### Precedence Rules | Level | Scope | Set on | | ----------- | --------------------- | ----------------------------------------------------------------------------------- | | Per-call | Single request only | `generate({ credentials })`, `stream({ credentials })` or `decide({ credentials })` | | Instance | All calls on instance | `new NeuroLink({ credentials })` | | Environment | Process-wide fallback | `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, … | Unset providers at any level fall through to the next. You never need to repeat a credential at the per-call level if the instance default is correct. ## Provider Credential Reference All fields are optional — omit any field you want to fall through to a lower-precedence level. | Provider | Key | Fields | | -------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------- | | OpenAI | `openai` | `apiKey`, `baseURL` | | Anthropic | `anthropic` | `apiKey`, `oauthToken`, `baseURL` | | Google AI Studio | `googleAiStudio` | `apiKey`, `baseURL` | | Google Vertex AI | `vertex` | `projectId`, `location`, `apiKey` (Express Mode), `serviceAccountKey`, `clientEmail`, `privateKey`, `baseURL` | | Amazon Bedrock | `bedrock` | `accessKeyId`, `secretAccessKey`, `sessionToken`, `region` | | Amazon SageMaker | `sagemaker` | `accessKeyId`, `secretAccessKey`, `sessionToken`, `region`, `endpoint` | | Azure OpenAI | `azure` | `apiKey`, `resourceName`, `deploymentName`, `apiVersion` | | Mistral | `mistral` | `apiKey` | | Hugging Face | `huggingFace` | `apiKey`, `baseURL` | | OpenRouter | `openrouter` | `apiKey`, `baseURL` | | LiteLLM | `litellm` | `apiKey`, `baseURL` | | OpenAI-Compatible | `openaiCompatible` | `apiKey`, `baseURL` | | Cerebras | `cerebras` | `apiKey`, `baseURL` | | SambaNova | `sambanova` | `apiKey`, `baseURL` | | Ollama | `ollama` | `baseURL` | | TypeSafe (Jev) | `typesafe` | `apiKey`, `baseURL`, `transport`, `gatewayApiKey`, `gatewayURL` | | Laya | `laya` | `apiKey`, `baseURL` (required: Laya has no built-in endpoint) | | XOR | `xor` | `apiKey`, `baseURL` (required: XOR has no built-in endpoint; calls `/v1/decisions`) | | Perplexity Decisions | `perplexityDecider` | `apiKey`, `baseURL` (optional: defaults to `https://api.perplexity.ai`; calls `/v1/decisions`) | | Cloudflare Clef | `cloudflareClef` | `apiKey`, `accountId`, `baseURL` (optional: defaults to `https://api.cloudflare.com/client/v4`) | | SubQ | `subq` | `apiKey`, `baseURL` (optional: defaults to `https://api.subq.ai`; calls `/v1/systemone`) | | OpenAI Decisions | `openaiDecisions` | `apiKey`, `baseURL` (optional: defaults to `https://api.openai.com`; calls `/v1/decisions`) | | ScaleDown | `scaledown` | `apiKey`, `baseURL` (optional: defaults to `https://api.scaledown.xyz`; calls `/v1/scaledown`) | Cloudflare Clef needs both `apiKey` and `accountId`; the account id is part of the route (`/accounts//ai/run/@cf/cloudflare/`), so a token alone does not configure it. `credentials.cloudflare` is the Workers AI text provider's slice and does **not** configure `decide`: the two providers read the same `CLOUDFLARE_API_KEY` and `CLOUDFLARE_ACCOUNT_ID` variables but take their own credentials; see [One token, two providers](/docs/getting-started/providers/cloudflare-clef.md#one-token-two-providers). `credentials.openai` is the chat provider's slice and does **not** configure `decide`; OpenAI Decisions reads its own, `credentials.openaiDecisions`. The two providers read the same `OPENAI_API_KEY` variable from the environment, so an ambient key set for chat does configure `decide` as the default provider when none ahead of it is configured, unless `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL` names a host other than `https://api.openai.com` (then it is taken to be a gateway's; a `credentials.openaiDecisions` key or base URL, or `OPENAI_DECISIONS_BASE_URL`, lifts that), and `credentials.openai` does not; see [One key, two providers](/docs/getting-started/providers/openai-decisions.md#one-key-two-providers). ScaleDown reads its own slice, `credentials.scaledown`, and its key is shared with no text provider: `SCALEDOWN_API_KEY` is read by nothing else. The key travels in an `x-api-key` header, never as a Bearer token. It is the last decision provider in the order, so a key set here does not become the default while any earlier provider is configured; see [When NeuroLink uses it](/docs/getting-started/providers/scaledown.md#when-neurolink-uses-it). The full type definition is `NeurolinkCredentials` in `src/lib/types/providers.ts`. ## SDK Examples ### OpenAI ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain quantum entanglement" }, provider: "openai", model: "gpt-4o", credentials: { openai: { apiKey: "sk-tenant-abc123" }, }, }); ``` Custom base URL for OpenAI-compatible proxies: ```typescript credentials: { openai: { apiKey: "sk-...", baseURL: "https://my-proxy.example.com/v1" }, } ``` ### Anthropic ```typescript const result = await neurolink.generate({ input: { text: "Write a haiku" }, provider: "anthropic", credentials: { anthropic: { apiKey: "sk-ant-api03-..." }, }, }); ``` OAuth token (Anthropic Claude subscription): ```typescript credentials: { anthropic: { oauthToken: "eyJ..." }, } ``` A gateway or proxy in front of Anthropic (`baseURL` wins over `ANTHROPIC_BASE_URL`, with or without a trailing `/v1`; a gateway that does its own auth accepts any `apiKey`): ```typescript credentials: { anthropic: { apiKey: "any-key-the-gateway-accepts", baseURL: "https://claude-gw.example.com" }, } ``` ### Vertex AI — Express Mode Express Mode uses a simple API key instead of service-account credentials, making it suitable for per-request BYOK flows: ```typescript const result = await neurolink.generate({ input: { text: "Summarize this" }, provider: "vertex", model: "gemini-2.5-pro", credentials: { vertex: { apiKey: "AIza...", // Express Mode key projectId: "my-project", location: "us-central1", }, }, }); ``` Full service-account credentials (server-side only — keep private keys out of client code): ```typescript credentials: { vertex: { projectId: "my-project", location: "us-central1", serviceAccountKey: JSON.stringify(serviceAccountJson), // OR inline fields: // clientEmail: "sa@project.iam.gserviceaccount.com", // privateKey: "-----BEGIN RSA PRIVATE KEY-----\n...", }, } ``` ### Amazon Bedrock ```typescript const result = await neurolink.generate({ input: { text: "Draft a press release" }, provider: "bedrock", model: "anthropic.claude-3-5-sonnet-20241022-v2:0", credentials: { bedrock: { accessKeyId: "AKIA...", secretAccessKey: "wJalrXUt...", region: "us-east-1", // sessionToken: "AQoDYXdz..." // for temporary STS credentials }, }, }); ``` ### Azure OpenAI ```typescript const result = await neurolink.generate({ input: { text: "Translate to French" }, provider: "azure", credentials: { azure: { apiKey: "az-key-...", resourceName: "my-azure-resource", deploymentName: "gpt-4o", apiVersion: "2024-02-01", }, }, }); ``` ### Streaming with Credentials `credentials` works identically on `stream()`. Note that `neurolink.stream()` returns a `StreamResult` wrapper — iterate over its `.stream` property: ```typescript const result = await neurolink.stream({ input: { text: "Tell me a story" }, provider: "openai", credentials: { openai: { apiKey: "sk-tenant-xyz" }, }, }); for await (const chunk of result.stream) { if ("content" in chunk && chunk.content) { process.stdout.write(chunk.content); } } ``` ### Multi-Tenant Request Handler A typical pattern for a multi-tenant API endpoint. Note the provider-name → credential-key mapping: the registered provider names (`google-ai`, `openai-compatible`, `huggingface`) differ from their `NeurolinkCredentials` slot keys (`googleAiStudio`, `openaiCompatible`, `huggingFace`), so map explicitly to avoid runtime surprises. ```typescript // Maps registered provider names to their NeurolinkCredentials slot keys. // Most providers are 1:1; only the three camelCase ones need translation. const PROVIDER_TO_CRED_KEY = { openai: "openai", anthropic: "anthropic", "google-ai": "googleAiStudio", vertex: "vertex", bedrock: "bedrock", sagemaker: "sagemaker", azure: "azure", mistral: "mistral", huggingface: "huggingFace", openrouter: "openrouter", litellm: "litellm", "openai-compatible": "openaiCompatible", ollama: "ollama", } as const satisfies Record; // Single shared instance — no keys baked in const neurolink = new NeuroLink(); async function handleAIRequest(req: Request) { const { prompt, provider, tenantApiKey } = await req.json(); const credKey = PROVIDER_TO_CRED_KEY[provider as keyof typeof PROVIDER_TO_CRED_KEY]; if (!credKey) { return Response.json( { error: `Unknown provider: ${provider}` }, { status: 400 }, ); } const result = await neurolink.generate({ input: { text: prompt }, provider, credentials: { // This example uses { apiKey: tenantApiKey } which works for API-key providers. [credKey]: { apiKey: tenantApiKey }, } as NeurolinkCredentials, }); return Response.json({ text: result.content }); } ``` > **Note:** This example assumes API-key authentication. Providers like Bedrock > (which use `accessKeyId`/`secretAccessKey`) and Ollama (which use `baseURL`) > require different credential shapes — see the [Provider Credential Reference](#provider-credential-reference) above. ## Limitations 1. **CLI does not support `--credentials`** — passing API keys as CLI flags would expose them in shell history, process lists, and log aggregators. Use environment variables for CLI usage instead. 2. **No credential rotation within a streaming call** — credentials are resolved once when `generate()` or `stream()` is called; you cannot swap keys mid-stream. 3. **No built-in secret storage** — NeuroLink passes credentials directly to the underlying provider SDK. Key storage, rotation, and encryption are the caller's responsibility. Consider integrating with a secrets manager (AWS Secrets Manager, HashiCorp Vault, Passetto) before injecting credentials into calls. 4. **Ollama accepts only `baseURL`** — Ollama does not use API keys; only the endpoint URL can be overridden. 5. **Unrecognised fields are silently ignored** — each provider only reads the fields documented in the reference table above. Passing extra fields has no effect. 6. **Internal fallback switches providers** — When a provider call fails and NeuroLink's internal fallback activates (selecting a different provider), the per-request credentials scoped to the original provider do not apply to the fallback provider. The fallback provider resolves credentials from its own instance-level or environment-variable sources. If you need strict per-call credential control and want to prevent fallback provider switches, set `disableInternalFallback: true` on the stream/generate call. ## Key Files | File | Purpose | | --------------------------------------- | -------------------------------------------------------------------------- | | `src/lib/types/providers.ts` | `NeurolinkCredentials` type definition | | `src/lib/types/configTypes.ts` | `NeurolinkConstructorConfig.credentials` field | | `src/lib/types/generateTypes.ts` | `GenerateOptions.credentials` + `TextGenerationOptions.credentials` fields | | `src/lib/types/streamTypes.ts` | `StreamOptions.credentials` field | | `src/lib/factories/providerFactory.ts` | Per-provider credential slice extraction | | `src/lib/factories/providerRegistry.ts` | Provider factory registrations | | `src/lib/neurolink.ts` | `resolveCredentials()` merge helper + `generate()`/`stream()` threading | ## See Also - [Authentication Providers](/docs/features/authentication-providers) -- token validation, RBAC, and session management for your own API endpoints - [Observability Guide](/docs/features/observability) -- tracing generate/stream calls. Credentials are passed only to the underlying provider SDK, not captured in NeuroLink span attributes; if you attach custom span enrichment, avoid logging the `credentials` field. - [SDK API Reference](/docs/sdk/api-reference) -- complete SDK reference --- ## PPT Generation - AI-Powered Presentations # PPT Generation - AI-Powered Presentations NeuroLink enables AI-powered PowerPoint presentation generation from text prompts. Transform ideas into professional, visually-appealing presentations with intelligent content planning, multiple slide types, and optional AI-generated images. ## Overview PPT generation in NeuroLink uses a multi-stage pipeline powered by any supported AI provider: 1. **Accepts** a text prompt describing the presentation topic via `input.text` 2. **Plans** structured content using AI-powered content planning 3. **Generates** individual slides with appropriate types, layouts, and content 4. **Creates** optional AI-generated images for visual slides 5. **Assembles** a complete `.pptx` file using pptxgenjs 6. **Returns** a `PPTGenerationResult` containing file path and metadata ```mermaid graph LR A[Text Prompt] --> B[Content Planning AI] B --> C[Slide Schemas] C --> D[Slide Generator] D --> E[Image Generation] E --> F[PPTX Assembly] F --> G[PPTGenerationResult] G --> H[Save to File] ``` ## What You Get - **Professional presentations** – Generate complete PowerPoint files with 5-50 slides - **35 slide types** – From title and content slides to charts, timelines, dashboards, and composite layouts - **5 built-in themes** – Modern, Corporate, Creative, Minimal, and Dark - **AI image generation** – Optional background and decorative images using Gemini - **User-provided images** – Use your own images instead of AI generation - **SDK integration** – Use `neurolink.generate()` with `output.mode: "ppt"` - **CLI support** – Generate presentations directly from command line - **Multi-provider support** – Works with Vertex AI, OpenAI, Anthropic, Google AI, Azure, and Bedrock ## Supported Providers & Models ### Provider Compatibility | Provider | Recommended Models | Slide Types | Image Gen | Quality | Notes | | ----------- | -------------------------------- | ----------- | ----------- | ------- | ------------------------ | | `vertex` | gemini-2.5-pro, gemini-3 | All 35 | ✅ Native | Highest | Full feature support | | `google-ai` | gemini-2.5-pro, gemini-3 | All 35 | ✅ Native | Highest | Full feature support | | `openai` | gpt-4o, gpt-4-turbo | All 35 | ⚠️ External | High | Uses OpenAI for planning | | `anthropic` | claude-4.5-sonnet, claude-3-opus | All 35 | ⚠️ External | Highest | Advanced reasoning | | `azure` | gpt-4o, gpt-4-turbo | All 35 | ⚠️ External | High | Enterprise deployment | | `bedrock` | claude-3-sonnet, titan | All 35 | ⚠️ External | High | AWS integration | ### Model Tiers | Tier | Models | Slide Types | Notes | | ---------- | ------------------------------------------------------------------------ | ----------- | ----------------------------- | | `advanced` | claude-4.5-opus, claude-4.5-sonnet, gpt-4o, gemini-2.5-pro, gemini-3-pro | All 35 | Full prompt with all features | | `basic` | gemini-flash, claude-instant, gpt-3.5 | 10 core | Simplified prompt for speed | ## Prerequisites 1. **AI provider credentials** configured for your chosen provider 2. **For AI images**: Vertex AI or Google AI credentials with Gemini access 3. **Sufficient storage**: Output files range from 100KB to 10MB+ depending on images ## Quick Start ### SDK Usage ```typescript const neurolink = new NeuroLink(); // Basic PPT generation const result = await neurolink.generate({ input: { text: "Create a presentation about AI in Healthcare", }, provider: "vertex", model: "gemini-2.5-pro", output: { mode: "ppt", ppt: { pages: 10, theme: "modern", audience: "business", tone: "professional", }, }, }); // Access result if (result.ppt) { console.log(`Presentation saved: ${result.ppt.filePath}`); console.log(`Total slides: ${result.ppt.totalSlides}`); } ``` #### With Full Options ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Quarterly Sales Report Q4 2025 - Key achievements, challenges, and outlook", }, provider: "vertex", model: "gemini-2.5-pro", output: { mode: "ppt", ppt: { pages: 15, theme: "corporate", audience: "business", tone: "professional", generateAIImages: true, aspectRatio: "16:9", outputPath: "./presentations/q4-report.pptx", logoPath: readFileSync("./assets/company-logo.png"), }, }, }); console.log("Presentation metadata:", { filePath: result.ppt?.filePath, slides: result.ppt?.totalSlides, theme: result.ppt?.metadata?.theme, fileSize: result.ppt?.metadata?.fileSize, }); ``` #### With User-Provided Images ```typescript const neurolink = new NeuroLink(); // Use your own images instead of AI generation const result = await neurolink.generate({ input: { text: "Product Launch Presentation for our new smartphone", images: [ readFileSync("./product-hero.jpg"), readFileSync("./product-features.png"), "./marketing/lifestyle-shot.jpg", // File path also works ], }, provider: "anthropic", model: "claude-3.5-sonnet", output: { mode: "ppt", ppt: { pages: 12, theme: "creative", generateAIImages: false, // Use provided images only }, }, }); ``` ### CLI Usage ```bash # Basic PPT generation npx @juspay/neurolink generate "Introduction to Machine Learning" \ --outputMode ppt \ --pptPages 10 \ --pptOutput ./ml-presentation.pptx # Full options npx @juspay/neurolink generate "Company Strategy 2026" \ --provider vertex \ --model gemini-2.5-pro \ --outputMode ppt \ --pptPages 15 \ --pptTheme corporate \ --pptAudience business \ --pptTone professional \ --pptAspectRatio 16:9 \ --pptOutput ./strategy-2026.pptx # Disable AI image generation npx @juspay/neurolink generate "Machine Learning 101" \ --outputMode ppt \ --pptTheme minimal \ --pptTone educational \ --pptNoImages ``` ### CLI Arguments - `--outputMode` (string, default: `text`) — Output mode: `text`, `video`, or `ppt` - `--pptPages`, `--pages` (number, default: `10`) — Number of slides (5-50) - `--pptTheme` (string, default: AI-selected) — Theme: `modern`, `corporate`, `creative`, `minimal`, `dark` - `--pptAudience` (string, default: AI-selected) — Target audience: `business`, `students`, `technical`, `general` - `--pptTone` (string, default: AI-selected) — Presentation tone: `professional`, `casual`, `educational`, `persuasive` - `--pptNoImages` (boolean, default: `false`) — Disable AI images for visual slides (images are enabled by default) - `--pptAspectRatio` (string, default: `16:9`) — Aspect ratio: `16:9` or `4:3` - `--pptOutput`, `--po` (string, default: auto-generated) — Output file path ## Slide Types NeuroLink supports **35 distinct slide types** organized by category: ### Opening/Closing Slides | Type | Description | Layout Options | | ---------------- | -------------------------------- | ---------------------------------- | | `title` | Opening slide with main title | `title-centered`, `title-bottom` | | `section-header` | Section divider with large title | `title-centered` | | `thank-you` | Final slide with contact info | `contact-info`, `title-centered` | | `closing` | Summary and next steps | `summary-bullets`, `title-content` | ### Content Slides | Type | Description | Layout Options | | --------------- | ------------------------------ | ------------------------------ | | `content` | Standard title + bullet points | `title-content`, image layouts | | `agenda` | Table of contents | `title-content`, `two-column` | | `bullets` | Enhanced bullet points | `title-content` | | `numbered-list` | Step-by-step content | `title-content` | ### Visual Slides | Type | Description | Image Required | | ------------------ | ------------------------- | -------------- | | `image-focus` | Large centered image | Yes | | `image-left` | Image left, content right | Yes | | `image-right` | Content left, image right | Yes | | `full-bleed-image` | Full background image | Yes | | `gallery` | Multiple images grid | Yes | ### Data Slides | Type | Description | Data Structure | | ------------ | ------------------------- | -------------- | | `table` | Data table with headers | `TableRow[]` | | `chart-bar` | Bar chart | `ChartSeries` | | `chart-line` | Line chart for trends | `ChartSeries` | | `chart-pie` | Pie chart for proportions | `ChartSeries` | | `chart-area` | Area chart | `ChartSeries` | | `statistics` | Big numbers display | `Statistic[]` | ### Layout Slides | Type | Description | Columns | | --------------- | ----------------------- | ------- | | `two-column` | Two equal columns | 2 | | `three-column` | Three column layout | 3 | | `split-content` | Asymmetric 60/40 split | 2 | | `comparison` | Side-by-side comparison | 2 | ### Special Slides | Type | Description | Key Content | | -------------- | ----------------------- | ----------------- | | `quote` | Impactful quote | `quote`, `author` | | `timeline` | Chronological events | `TimelineItem[]` | | `process-flow` | Step-by-step process | `ProcessStep[]` | | `features` | Feature list with icons | `FeatureItem[]` | | `team` | Team member profiles | `TeamMember[]` | | `icons` | Icon grid with labels | `icons[]` | | `conclusion` | Summary with takeaways | `bullets` | ### Composite/Dashboard Slides | Type | Description | Components | | --------------- | -------------------------- | ------------------------ | | `dashboard` | Multi-zone flexible grid | charts + stats + bullets | | `mixed-content` | Left bullets + right chart | bullets + data | | `stats-grid` | Multiple stat boxes | `Statistic[]` | | `icon-grid` | Icon boxes in grid | icons | ## Themes ### Built-in Themes | Theme | Colors | Best For | | ----------- | ----------------------- | ------------------- | | `modern` | Blue, Purple, Cyan | Tech, Innovation | | `corporate` | Dark Blue, Green, Slate | Business, Finance | | `creative` | Orange, Pink, Yellow | Marketing, Design | | `minimal` | Black, White, Gray | Clean, Professional | | `dark` | Cyan, Purple on Dark | Tech, Startups | ### Theme Structure ```typescript interface PresentationTheme { name: string; displayName: string; description: string; colors: { primary: string; // Main accent color secondary: string; // Secondary accent accent: string; // Highlight color background: string; // Slide background text: string; // Body text color textOnPrimary: string; // Text on primary color muted: string; // Muted/caption text }; fonts: { heading: string; body: string; sizes: { title: number; subtitle: number; heading: number; body: number; caption: number; }; }; } ``` ## Type Definitions ### PPTOutputOptions Options for PPT generation configuration: ```typescript type PPTOutputOptions = { /** Number of slides (5-50) */ pages: number; /** Output format (currently only 'pptx') */ format?: "pptx"; /** Presentation theme */ theme?: "modern" | "corporate" | "creative" | "minimal" | "dark"; /** Target audience */ audience?: "business" | "students" | "technical" | "general"; /** Presentation tone */ tone?: "professional" | "casual" | "educational" | "persuasive"; /** Generate AI images for visual slides */ generateAIImages?: boolean; /** Output file path */ outputPath?: string; /** Aspect ratio */ aspectRatio?: "16:9" | "4:3"; /** Logo image (Buffer, file path, or ImageWithAltText) */ logoPath?: Buffer | string | ImageWithAltText; }; ``` ### PPTGenerationResult Result type for generated presentation: ```typescript type PPTGenerationResult = { /** Path to generated file */ filePath: string; /** Total number of slides */ totalSlides: number; /** Output format */ format: "pptx"; /** Provider used for content planning */ provider: string; /** Model used for content planning */ model: string; /** Additional metadata */ metadata?: { theme?: string; audience?: string; tone?: string; imageModel?: string; fileSize?: number; }; }; ``` ### Content Structure Types ```typescript // Bullet point with optional formatting type BulletPoint = { text: string; subBullets?: string[]; icon?: string; emphasis?: boolean; fontSize?: number; bulletStyle?: "disc" | "number" | "checkmark" | "arrow" | "dash" | "none"; color?: string; bold?: boolean; }; // Statistics for data slides type Statistic = { value: string; label: string; trend?: "up" | "down" | "neutral"; change?: string; icon?: string; }; // Timeline items type TimelineItem = { date: string; title: string; description?: string; icon?: string; }; // Process steps type ProcessStep = { step: number; title: string; description?: string; icon?: string; }; // Chart data type ChartSeries = { name: string; labels: string[]; values: number[]; color?: string; }; ``` ### Extended GenerateResult The `generate()` function returns an extended result when PPT mode is enabled: ```typescript type GenerateResult = { content: string; provider?: string; model?: string; usage?: TokenUsage; responseTime?: number; // PPT-specific field (present when output.mode === "ppt") ppt?: PPTGenerationResult; // Other optional fields toolsUsed?: string[]; analytics?: AnalyticsData; evaluation?: EvaluationData; }; ``` ## Configuration & Best Practices ### Configuration Options | Option | Type | Default | Required | Description | | ----------------------------- | ------------------ | ---------------- | -------- | --------------------------------- | | `input.text` | `string` | - | Yes | Topic/description (10-1000 chars) | | `input.images` | `Array` | - | No | User-provided images | | `provider` | `string` | `vertex` | No | AI provider for content planning | | `model` | `string` | provider default | No | Model for content planning | | `output.mode` | `string` | `text` | Yes | Must be `"ppt"` for PPT output | | `output.ppt.pages` | `number` | `10` | Yes | Number of slides (5-50) | | `output.ppt.theme` | `string` | `modern` | No | Presentation theme | | `output.ppt.audience` | `string` | `general` | No | Target audience | | `output.ppt.tone` | `string` | `professional` | No | Presentation tone | | `output.ppt.generateAIImages` | `boolean` | `false` | No | Enable AI image generation | | `output.ppt.aspectRatio` | `string` | `16:9` | No | Slide aspect ratio | | `output.ppt.outputPath` | `string` | auto-generated | No | Output file path | | `output.ppt.logoPath` | `Buffer \| string` | - | No | Logo for slides | ### Best Practices #### 1. Prompt Engineering ```typescript // ❌ Vague prompt const vaguePrompt = "Make a presentation"; // ✅ Specific and detailed const specificPrompt = "Create a presentation about Machine Learning in Healthcare: covering benefits, use cases (diagnosis, drug discovery, patient care), implementation challenges, and future outlook"; // ✅ Include structure hints const structuredPrompt = `Product Launch Presentation for SmartWatch Pro: - Start with value proposition - Cover 5 key features - Include competitor comparison - Show pricing tiers - End with launch timeline and CTA`; ``` #### 2. Audience & Tone Matching ```typescript // Technical audience const technicalPpt = await neurolink.generate({ input: { text: "Kubernetes Architecture Deep Dive", }, output: { mode: "ppt", ppt: { pages: 15, audience: "technical", tone: "educational", theme: "dark", }, }, }); // Executive audience const executivePpt = await neurolink.generate({ input: { text: "Digital Transformation ROI Report", }, output: { mode: "ppt", ppt: { pages: 10, audience: "business", tone: "professional", theme: "corporate", }, }, }); ``` #### 3. Image Strategy ```typescript // AI-generated images for creative presentations const creativePpt = await neurolink.generate({ input: { text: "Future of Space Tourism" }, output: { mode: "ppt", ppt: { pages: 12, theme: "creative", generateAIImages: true, // AI generates thematic images }, }, }); // User-provided images for brand consistency const brandPpt = await neurolink.generate({ input: { text: "Annual Report 2025", images: [ readFileSync("./brand/hero.jpg"), readFileSync("./brand/team.jpg"), readFileSync("./brand/office.jpg"), ], }, output: { mode: "ppt", ppt: { pages: 20, generateAIImages: false, logoPath: "./brand/logo.png", }, }, }); ``` ## Comprehensive Examples ### Example 1: Basic Presentation ```typescript const neurolink = new NeuroLink(); async function generateBasicPresentation() { const result = await neurolink.generate({ input: { text: "Introduction to Cloud Computing: Benefits, Types, and Best Practices", }, provider: "vertex", model: "gemini-2.5-pro", output: { mode: "ppt", ppt: { pages: 10, theme: "modern", audience: "general", tone: "educational", }, }, }); if (result.ppt) { console.log({ filePath: result.ppt.filePath, totalSlides: result.ppt.totalSlides, provider: result.ppt.provider, }); } } ``` ### Example 2: Business Presentation with Analytics ```typescript const neurolink = new NeuroLink(); async function generateBusinessPresentation() { const result = await neurolink.generate({ input: { text: `Q4 2025 Sales Performance Report: - Revenue: $12.5M (up 23% YoY) - New customers: 450 - Customer retention: 94% - Top products: Enterprise Suite, Cloud Platform - Challenges: Supply chain, competition - 2026 targets: $18M revenue, 600 new customers`, }, provider: "anthropic", model: "claude-3.5-sonnet", enableAnalytics: true, output: { mode: "ppt", ppt: { pages: 15, theme: "corporate", audience: "business", tone: "professional", outputPath: "./reports/q4-sales.pptx", }, }, }); console.log("Analytics:", result.analytics); console.log("Presentation:", result.ppt); } ``` ### Example 3: Technical Documentation with Code ```typescript const neurolink = new NeuroLink(); async function generateTechnicalDocs() { const result = await neurolink.generate({ input: { text: `API Integration Guide for Payment Gateway: - Authentication (OAuth 2.0, API Keys) - Endpoints overview - Request/Response formats - Error handling - Code examples in TypeScript - Testing and sandbox environment - Security best practices`, }, provider: "openai", model: "gpt-4o", output: { mode: "ppt", ppt: { pages: 12, theme: "dark", audience: "technical", tone: "educational", }, }, }); return result.ppt; } ``` ### Example 4: Batch Presentation Generation ```typescript const neurolink = new NeuroLink(); const limit = pLimit(2); // Max 2 concurrent generations const topics = [ { topic: "AI in Healthcare", audience: "business" }, { topic: "Machine Learning Basics", audience: "students" }, { topic: "Cloud Architecture Patterns", audience: "technical" }, ]; async function batchGenerate() { const results = await Promise.all( topics.map((item) => limit(async () => { const result = await neurolink.generate({ input: { text: item.topic }, output: { mode: "ppt", ppt: { pages: 10, audience: item.audience as any, outputPath: `./presentations/${item.topic.replace(/\s+/g, "-").toLowerCase()}.pptx`, }, }, }); return { topic: item.topic, filePath: result.ppt?.filePath, slides: result.ppt?.totalSlides, }; }), ), ); console.table(results); } ``` ### Example 5: Error Handling ```typescript const neurolink = new NeuroLink(); async function generateWithErrorHandling(topic: string) { try { const result = await neurolink.generate({ input: { text: topic }, output: { mode: "ppt", ppt: { pages: 10, theme: "modern", }, }, timeout: 300000, // 5 minutes for PPT generation }); return result.ppt; } catch (error) { if (error instanceof PPTError) { console.error(`PPT Error [${error.code}]:`, error.message); switch (error.code) { case "PPT_PLANNING_FAILED": console.error("Content planning failed - try a different prompt"); break; case "PPT_INVALID_AI_RESPONSE": console.error( "AI returned invalid response - retry with different model", ); break; case "PPT_IMAGE_GENERATION_FAILED": console.error("Image generation failed - try without AI images"); break; case "PPT_ASSEMBLY_FAILED": console.error("PPTX assembly failed - check file permissions"); break; case "PPT_FILE_WRITE_FAILED": console.error("File write failed - check disk space and permissions"); break; case "PPT_TIMEOUT": console.error("Generation timed out - try fewer slides"); break; } } else if (error instanceof NeuroLinkError) { console.error(`NeuroLink Error:`, error.message); } throw error; } } ``` ## Error Handling & Validation ### Validation Rules | Parameter | Validation | Error Type | Example Message | | ------------------------ | ------------------- | ---------- | ------------------------------------------ | | `input.text` | 10-1000 characters | PPTError | `Prompt must be 10-1000 characters` | | `output.ppt.pages` | 5-50 slides | PPTError | `Pages must be between 5 and 50` | | `output.ppt.theme` | Valid theme name | PPTError | `Invalid theme. Use: modern, corporate...` | | `output.ppt.audience` | Valid audience type | PPTError | `Invalid audience type` | | `output.ppt.tone` | Valid tone type | PPTError | `Invalid tone type` | | `output.ppt.aspectRatio` | `16:9` or `4:3` | PPTError | `Invalid aspect ratio` | ### Error Codes ```typescript const PPT_ERROR_CODES = { PLANNING_FAILED: "PPT_PLANNING_FAILED", INVALID_AI_RESPONSE: "PPT_INVALID_AI_RESPONSE", IMAGE_GENERATION_FAILED: "PPT_IMAGE_GENERATION_FAILED", ASSEMBLY_FAILED: "PPT_ASSEMBLY_FAILED", FILE_WRITE_FAILED: "PPT_FILE_WRITE_FAILED", INVALID_INPUT: "PPT_INVALID_INPUT", TIMEOUT: "PPT_TIMEOUT", }; ``` ## Troubleshooting | Symptom | Cause | Solution | | ----------------------- | -------------------------------- | -------------------------------------------- | | Content planning fails | Invalid/vague prompt | Use more specific, detailed prompts | | Slides have wrong types | Model not following instructions | Try advanced-tier model (claude-3.5, gpt-4o) | | Images not generating | `generateAIImages` not enabled | Set `generateAIImages: true` | | Images fail to generate | Missing Vertex AI credentials | Configure `GOOGLE_APPLICATION_CREDENTIALS` | | File write fails | Permission denied | Check output directory permissions | | Generation times out | Too many slides with images | Reduce pages or disable AI images | | Bullet formatting wrong | AI not following format | Use simplified slide types | | Charts have no data | AI didn't generate chart data | Provide explicit data in prompt | | Logo not appearing | Invalid logo path/buffer | Verify logo file exists and is valid image | | Incorrect aspect ratio | Using wrong dimension | Ensure aspectRatio matches content design | ### Debug Mode ```typescript // Enable verbose logging const neurolink = new NeuroLink({ debug: true, logLevel: "verbose", }); // Or via environment variable // export NEUROLINK_DEBUG=true ``` ## Testing ### Unit Test Example ```typescript describe("PPT Generation", () => { it("should generate presentation with valid options", async () => { const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Test presentation about AI" }, output: { mode: "ppt", ppt: { pages: 5, theme: "modern", audience: "general", tone: "professional", }, }, }); expect(result.ppt).toBeDefined(); expect(result.ppt?.filePath).toMatch(/\.pptx$/); expect(result.ppt?.totalSlides).toBeGreaterThanOrEqual(5); expect(result.ppt?.format).toBe("pptx"); }); it("should throw error for invalid page count", async () => { const neurolink = new NeuroLink(); await expect( neurolink.generate({ input: { text: "Test" }, output: { mode: "ppt", ppt: { pages: 100 }, // Invalid: max is 50 }, }), ).rejects.toThrow(); }); }); ``` ### Mock Strategy for CI/CD ```typescript vi.mock("@juspay/neurolink", () => ({ NeuroLink: vi.fn().mockImplementation(() => ({ generate: vi.fn().mockResolvedValue({ content: "", provider: "vertex", model: "gemini-2.5-pro", ppt: { filePath: "./test-output.pptx", totalSlides: 10, format: "pptx", provider: "vertex", model: "gemini-2.5-pro", metadata: { theme: "modern", audience: "general", tone: "professional", }, }, }), })), })); ``` ## Limitations | Limitation | Description | Workaround | | ---------------- | ------------------------------- | ------------------------------------- | | Max slides | 50 slides per presentation | Split into multiple presentations | | Min slides | 5 slides minimum | Use at least 5 pages | | Output format | Only PPTX supported | Convert with external tools if needed | | Image generation | Only with Vertex AI / Google AI | Use user-provided images | | Custom templates | Not supported yet | Use theme customization | | Animations | Basic transitions only | Edit in PowerPoint after generation | | Video embedding | Not supported | Add videos manually after generation | ## Performance Optimization ### Generation Time Estimates | Configuration | Estimated Time | Notes | | ------------------------- | -------------- | -------------------------- | | 10 slides, no images | 15-30s | Fast, text-only | | 10 slides, with AI images | 60-120s | Image generation adds time | | 20 slides, no images | 30-60s | Linear scaling | | 20 slides, with AI images | 120-240s | Parallel image generation | | 50 slides, no images | 60-120s | Large presentation | | 50 slides, with AI images | 300-600s | Consider splitting | ### Optimization Tips 1. **Disable AI images** for faster generation: `generateAIImages: false` 2. **Use basic-tier models** for simple presentations: `gemini-2.5-flash` 3. **Provide user images** instead of AI generation for brand consistency 4. **Limit slide count** to what's actually needed 5. **Use structured prompts** for better AI content planning ## Related Features - [Video Generation](/docs/features/video-generation) – Generate videos from images - [Multimodal Chat](/docs/features/multimodal-chat) – Image and text processing - [Office Documents](/docs/features/office-documents) – Process existing PPTX files ## Implementation Files | File | Purpose | | -------------------------------------------------- | ------------------------------------------------ | | `src/lib/features/ppt/presentationOrchestrator.ts` | Main orchestration pipeline | | `src/lib/features/ppt/contentPlanner.ts` | AI-powered content planning | | `src/lib/features/ppt/slideGenerator.ts` | Individual slide generation | | `src/lib/features/ppt/slideRenderers.ts` | Slide type rendering functions | | `src/lib/features/ppt/constants.ts` | Themes, prompts, and configuration | | `src/lib/features/ppt/types.ts` | Type definitions | | `src/lib/types/pptTypes.ts` | Public API types | | `src/lib/utils/parameterValidation.ts` | Input validation: `validatePPTGenerationInput()` | **Next:** [Video Generation](/docs/features/video-generation) | [Multimodal Chat](/docs/features/multimodal-chat) --- ## Provider Fallback & Model Chains Added in **v9.58.0**, NeuroLink supports two complementary mechanisms for handling **model-access denial** errors at request time: the `providerFallback` callback (dynamic, code-driven) and the `modelChain` config (declarative). They give you a single place to express "if my preferred model rejects me, try this one instead" without scattering try/catch logic across every call site. > **Scope clarification.** Both mechanisms only fire on `ModelAccessDeniedError` (or messages matching `team … not allowed to access model` / `team can only access`). Rate limits, 5xx errors, network failures, and generic provider errors are **not** routed through this orchestrator — those bubble up to the caller as-is. If you need broader resilience, wrap your own retry/circuit-breaker around `generate()` / `stream()`. ------------------------ | -------------------------------------------------------------------------------------------------------- | | `providerFallback` callback | You need conditional logic — different fallbacks for different error shapes, A/B routing, custom logging | | `modelChain` config | You want a simple ordered list of model names to try in sequence on access denial | `providerFallback` and `modelChain` are **not composable** — if `providerFallback` is set (instance- or per-call), `modelChain` is ignored. Internally, when `providerFallback` is _not_ provided, NeuroLink synthesises a callback from `modelChain` that walks the list. They are two ways to wire the same callback slot. --- ## `providerFallback` callback ```typescript const neurolink = new NeuroLink({ providerFallback: async (error) => { // Return null to give up (the original error is rethrown to the caller). // Return { provider?, model? } to retry. Either field can be omitted — // an omitted provider keeps the current one; an omitted model keeps the current one. if ( error instanceof ModelAccessDeniedError && error.allowedModels?.length ) { return { model: error.allowedModels[0] }; } return null; }, }); const result = await neurolink.generate({ input: { text: "Summarize this PDF" }, provider: "anthropic", model: "claude-opus-4-7", }); ``` The callback signature is: ```typescript type ProviderFallbackCallback = (error: unknown) => Promise; ``` - `null` → stop, surface the original error to the caller. - `{ provider, model }` → retry with this combination. Either field may be omitted; the missing field is inherited from the failing call. The callback is `async`, takes a single `error` argument (no separate `attemptedProvider` / `attempts` parameters), and is invoked at most once per call by the orchestrator. To loop through several alternates, return the next candidate each time and rely on the orchestrator to re-invoke the callback on the next denial. ### Per-call override You can also pass `providerFallback` directly on `generate()` / `stream()`. The per-call value wins over the instance-level configuration: ```typescript await neurolink.generate({ input: { text: "..." }, provider: "anthropic", model: "claude-opus-4-7", providerFallback: async (err) => { if (err instanceof ModelAccessDeniedError) { return { provider: "openai", model: "gpt-4o" }; } return null; }, }); ``` For streaming, the orchestrator additionally guards: fallback only kicks in if the stream **has not yet yielded any tokens**. Once tokens have started flowing, a mid-stream denial cannot be transparently retried. --- ## `modelChain` config A simple ordered list of model **names**. NeuroLink walks the chain on each access-denial. ```typescript const neurolink = new NeuroLink({ modelChain: [ "claude-opus-4-7", // try first "claude-sonnet-4-6", // then this "gpt-4o", // then this "gemini-3-flash-preview", // last resort ], }); await neurolink.generate({ input: { text: "..." } }); // First call: claude-opus-4-7. If that returns ModelAccessDeniedError, // the synthesized callback returns { model: "claude-sonnet-4-6" } and // the orchestrator retries. ``` `modelChain` is `string[]` only — bare model names. There is no support for object entries with `provider` / `baseURL` per row. The current provider is preserved across the chain; only the model name changes. If you need to switch providers on denial, use `providerFallback` and return `{ provider, model }`. ```typescript type ModelChain = string[]; ``` --- ## Internal no-output fallback (`disableInternalFallback`, `fallbackOnMaxSteps`) Separate from the orchestration above, `stream()` carries an internal safety net: when the drained stream produced no non-sentinel text, audio, or image chunks and recorded no tool calls or tool results, NeuroLink retries the request once on a fallback route. An audio-only or image-only stream counts as real output and does not trigger the retry. The route's provider and model are resolved independently: the per-call `fallbackProvider` / `fallbackModel` options each override their matching `FALLBACK_PROVIDER` / `FALLBACK_MODEL` environment variable, which overrides the corresponding model-router value. Two per-call knobs control the retry: - `disableInternalFallback: true` — turn the safety net off entirely. The Claude proxy does this so the proxy itself can own fallback order. - `fallbackOnMaxSteps: false` — keep the safety net, but exempt turns that ended at your own `maxSteps` bound. A tool-looping turn that runs out of step budget produces no final text, which otherwise looks exactly like a failed stream to the no-output check — and the retry spends a second provider's tokens to exceed a budget you set deliberately. With this set, the capped turn is surfaced as-is and reports `metadata.stopReason === "step-cap"` after the stream is drained. Default (unset) preserves the retry. `generate()` has no no-output retry, but the same flag governs its two internal fallbacks: the static provider-priority walk that runs when no provider was requested, and the catalog model-fallback walk a provider performs when the vendor rejects its model as invalid. With `disableInternalFallback: true`, `generate()` tries exactly one provider from that static list and surfaces an invalid model as the classified `InvalidModelError` after a single request. A configured `ModelPool`, `providerFallback` and `modelChain` are your own fallback and are unaffected on either path: a pool still walks its own candidates. --- ## Observability When the orchestrator advances past an access-denial, it emits a `model.fallback` event on the SDK's internal emitter: ```typescript // Payload shape (verbatim from src/lib/neurolink.ts) type ModelFallbackEvent = { requestedProvider: string | undefined; requestedModel: string | undefined; fallbackProvider: string | undefined; fallbackModel: string | undefined; reason: string; kind: "generate" | "stream"; timestamp: number; }; ``` The same event also flows through the OTEL/Langfuse pipeline, so you can monitor fallback frequency in production without subscribing to the in-process emitter. --- ## Patterns ### Walk allowed models from the error itself ```typescript const neurolink = new NeuroLink({ providerFallback: async (err) => { if (err instanceof ModelAccessDeniedError && err.allowedModels?.length) { // Use the first allowed model; the orchestrator will re-invoke us if that one is denied too. return { model: err.allowedModels[0] }; } return null; }, }); ``` ### Tier-up on denial ```typescript const neurolink = new NeuroLink({ providerFallback: async (err) => { if (err instanceof ModelAccessDeniedError) { // If a cheap model is denied, jump to a higher-tier one return { model: "claude-opus-4-7" }; } return null; }, }); ``` ### Cross-provider failover ```typescript const neurolink = new NeuroLink({ providerFallback: async (err) => { if (err instanceof ModelAccessDeniedError) { return { provider: "openrouter", model: "anthropic/claude-opus-4-7" }; } return null; }, }); ``` --- ## Related - **[Credential Validation](/docs/features/credential-validation)** — `sdk.checkCredentials()` and the typed `ModelAccessDeniedError` - **[Real-time Voice Services](/docs/features/real-time-services)** — fallback also applies to realtime sessions on access denial - **[Provider Setup](/docs/getting-started/provider-setup)** — configuring supported providers - **[Observability](/docs/observability/health-monitoring)** — wiring `model.fallback` events into your monitoring stack --- ## Provider Orchestration Brain # Provider Orchestration Brain The orchestration engine introduced in 7.42.0 pairs a task classifier with a provider/model router. When enabled, NeuroLink inspects each prompt, chooses the most suitable provider/model based on capabilities and availability, and carries that preference through the fallback chain. ## Highlights - **Binary task classifier** – categorises prompts (analysis vs. creative, etc.) before routing. - **Model router** – selects provider/model pairs, honouring local providers like Ollama when available. - **Provider validation** – confirms credentials/availability before committing to the route. - **Non-invasive** – orchestration augments requests via context so standard fallback logic still applies. ## Enabling Orchestration (SDK) ```typescript const neurolink = new NeuroLink({ enableOrchestration: true }); // (1)! const result = await neurolink.generate({ input: { text: "Generate product launch plan" }, // (2)! enableAnalytics: true, // (3)! enableEvaluation: true, // (4)! }); console.log(result.provider, result.model); // (5)! ``` 1. Enable orchestration for automatic provider/model selection 2. Task classifier analyzes prompt to determine best provider 3. Log routing decisions to analytics 4. Validate routed provider meets quality expectations 5. See which provider/model was selected by the router The router adds `__orchestratedPreferredProvider` to the request context so analytics and downstream logging capture routing decisions. ## Tuning the Router - **Environment awareness** – orchestration only routes to providers that pass `hasProviderEnvVars`, so missing API keys fall back gracefully. - **Ollama detection** – checks `http://localhost:11434/api/tags` to verify local models before selection. - **Confidence scores** – `ModelRouter.route` returns `confidence` and `reasoning`. Enable debug logs (`export NEUROLINK_DEBUG=true`) to inspect decisions. - **Manual overrides** – specifying `provider` or `model` bypasses orchestration for that call. ## Working with the CLI CLI sessions instantiate NeuroLink without orchestration by default. To experiment with the router from the CLI: ```bash node -e " # (1)! const { NeuroLink } = require('@juspay/neurolink'); (async () => { const neurolink = new NeuroLink({ enableOrchestration: true }); # (2)! const res = await neurolink.generate({ input: { text: 'Compare Claude and GPT-4o' } }); # (3)! console.log(res.provider, res.model); # (4)! })(); " ``` 1. Run Node.js one-liner from CLI 2. Enable orchestration in SDK mode 3. Let router select best provider for comparison task 4. Output selected provider and model Future CLI releases will surface a `--enable-orchestration` flag; until then keep orchestration for SDK/server workloads. ## Best Practices :::tip[Routing Strategy] Enable orchestration in development to understand routing patterns, then pin `provider` or `model` in production for predictable behavior. Orchestration is ideal for exploratory workflows; explicit selection ensures consistency in critical paths. ::: :::tip[Self-Hosted First] The default fallback order prioritizes self-hosted providers — LiteLLM and Ollama — before cloud providers. This avoids external API costs and rate limits during development. Ensure your local providers are running to take advantage of this local-first routing. ::: - Pair orchestration with evaluation to verify the routed provider meets quality expectations. - Maintain provider credentials for all potential routes; orchestration skips providers missing keys. - Monitor debug logs in staging to understand how tasks map to providers before rolling out widely. - Combine with regional controls (`region` option) when routing to cloud-specific providers such as Vertex or Bedrock. ## Troubleshooting | Symptom | Action | | ----------------------------------- | -------------------------------------------------------------------------------------------------- | | Router always returns empty context | Ensure `enableOrchestration: true` and prompts contain text. | | Routed provider never used | Check credentials via `neurolink status`; orchestration only hints the preferred provider. | | Ollama route ignored | Confirm Ollama server running at `http://localhost:11434` and model tag matches router suggestion. | | Fallback cycles between providers | Pin provider/model explicitly or reduce orchestrated confidence thresholds (see `ModelRouter`). | ## `ModelPool` — failover with per-member cooldown Orchestration above _hints_ a provider. `ModelPool` is the separate, explicit mechanism that **owns** selection: you hand it an ordered list of provider/model/region members and it tries them in turn, taking a failed member out of rotation for a while rather than retrying it on every call. **File:** `src/lib/routing/modelPool.ts` · **Types:** `src/lib/types/modelPool.ts` ```typescript const pool = new ModelPool({ members: [ { provider: "vertex", model: "gemini-2.5-flash" }, { provider: "openai", model: "gpt-4o-mini" }, ], strategy: "priority", // or "round-robin" | "weighted" cooldownMs: 60_000, // retryable failures only }); ``` `strategy` picks among the members that are currently _available_: `priority` always takes the first, `round-robin` rotates, `weighted` prefers higher `weight`. ### Cooldown is classified, not uniform A failure is classified into a `ProviderErrorClass` — `rate_limit`, `auth`, `context_window`, `server`, `network`, `unknown` — and the class decides how long the member sits out: | Class | Cooldown | | -------------------------------------------- | ----------------------------------------- | | `rate_limit`, `server`, `network`, `unknown` | `cooldownMs` (default **60s**) | | `auth`, `context_window` | **permanent** for the life of the process | "Permanent" is literal: `PERMANENT_COOLDOWN_MS` is ten years. The reasoning is that neither class can fix itself mid-process — a rejected key stays rejected, and a request that overflowed a model's window will overflow it again — so retrying only burns latency on every subsequent call. ⚠️ **This is why a context budget may only ever shrink.** One optimistic guess that overflows a model's window does not cost a retry; it retires that model for the life of the process. Everything in [context budget](/docs/features/context-budget) and the [model catalogue](/docs/features/classifier-router-catalog) that looks over-cautious about raising a threshold is cautious for this reason, and the catalogue vetoes a model whose window cannot hold the request _regardless of how confident the pick was_ — an oversized request is a hard provider error, not a slightly worse answer. ### A configured pool disables the classifier router The [classifier router](/docs/features/classifier-router) is skipped entirely when a `modelPool` is configured, because the two would otherwise both claim the right to choose a model. The pool wins: it is the explicit, host-declared statement, and it is the one carrying failover state. A host that wants per-request routing should use the classifier router's own `pool` rather than a `ModelPool`. ## Dive Deeper - Code reference: `src/lib/utils/modelRouter.ts` - Code reference: `src/lib/utils/taskClassifier.ts` - Code reference: `src/lib/routing/modelPool.ts` - [Classifier Router](/docs/features/classifier-router) — per-request model selection - [Provider Fallback](/docs/features/provider-fallback) - [`docs/advanced/analytics.md`](/docs/reference/analytics) for logging orchestration metadata. --- ## `GET /accounts` — one row per account # `GET /accounts` — one row per account ## What it is for Answering "which of my accounts can still take work?" used to need two calls whose schemas do not line up: - **`/status`** returns six rows here — three real logins plus `proxy/internal` and two `translation` pseudo-accounts — with request and error counters, and no quota. - **`/limits`** returns three rows, only the real logins, with quota and no counters. Every consumer therefore reimplemented the same merge, discarded the plumbing rows by hand, and drifted whenever the proxy's internals moved. `/accounts` does the join once, server-side, and adds the thing neither endpoint had: per-account token totals and cost. ## Response ```jsonc { "generatedAt": 1787258002241, "usageDate": "2026-08-20", // UTC day the usage totals cover "quotaFromSnapshot": true, "quotaError": null, // set if the quota snapshot could not be loaded "usageError": null, // set if the request log was unreadable "costBasis": "api-equivalent", "accounts": [ { "label": "someone@example.com", "key": "anthropic:someone@example.com", "kind": "account", // "account" | "internal" | "translation" "type": "oauth", "status": "active", // "active" | "cooling" | "exhausted" | "unrouted" // "unrouted": a real account the quota snapshot does not mention "cooling": false, "allowed": null, // see the note below "expired": null, "isPrimary": false, "requests": 88514, "errors": 964, "rateLimits": 232, "quotaRateLimits": 4, "quota": { "sessionUsed": 0.31, "weeklyUsed": 0.24, "weeklyResetAt": 1787360399, // unix SECONDS, as upstream sends it "weeklyResetAtMs": 1787360399000, // normalised, added by this endpoint "lastUpdated": 1787253037063, // already ms, passed through untouched "sessionHealth": "ok", // ok | degraded | unknown "weeklyHealth": "ok", "windows": [ /* each with severity, isActive and resetsAtMs */ ], }, "usage": { "requests": 5053, "inputTokens": 367688, "outputTokens": 4290265, "cacheReadTokens": 1253653209, "cacheCreationTokens": 0, "costUsd": 897.78, "unpricedRequests": 0, "unpricedModels": [], }, }, ], } ``` ### `costBasis: "api-equivalent"` is not a bill Pooled OAuth accounts bill by **subscription**. `costUsd` is what the recorded tokens _would_ have cost at published per-token rates — useful for judging whether a subscription is earning its keep, and for spotting a runaway account. It is not an invoice, and a consumer that renders it as one is wrong. On this machine it reads roughly $900/day, which is alarming without that framing. `unpricedModels` names any model with no pricing row, so a $0 contribution is visible rather than silent. ## Query parameters | Param | Default | Meaning | | --------- | ------- | ------------------------------------------------------------ | | `refresh` | `false` | `true` forces a live quota fetch from Anthropic's usage API. | **The default is deliberate.** A live refresh spends the user's own OAuth credentials upstream. This endpoint is built to be polled, so it reads the stored snapshot unless asked otherwise; a dashboard on a short interval must not hammer Anthropic. ## Notes on individual fields - **`allowed` and `expired` are always `null`.** Deriving them needs the token store, which `/status` reaches behind its own timeouts. `cooling` is the field an operator acts on and one small file read answers it, so that one is real. Use `/status` when you need the other two. - **`status` is derived**, not passed through. `/limits` returns `status: "snapshot"`, which describes how the quota was obtained rather than the account's health, and must not leak into a field consumers read as health. - **Timestamps.** Upstream mixes units in one object: `sessionResetAt`, `weeklyResetAt` and `windows[].resetsAt` are unix **seconds**; `lastUpdated`, `windows[].updatedAt` and `coolingUntil` are **milliseconds**. Only the seconds fields get a `*Ms` companion; the rest pass through untouched. Blanket-multiplying the object would throw the millisecond fields tens of thousands of years forward. - **`isPrimary`** marks the account the pool prefers, from the proxy's hot-reloaded routing config where one is set and the value it was constructed with otherwise. Keys compare normalised, so a bare label (`me@example.com`) and a full pool key (`anthropic:me@example.com`) match. It is `false` on `internal` and `translation` rows, which are not credentials and cannot be primary. - **`severity` and `isActive`** are absent on header-sourced `overage` windows — a structural property of how those rows are parsed, not a transient gap. This endpoint fills them (`severity: "critical"` when the window is rejected, `isActive: false`) so no consumer needs the branch. ## How usage totals are computed `src/lib/proxy/accountLedger.ts` reads `~/.neurolink/logs/proxy-.jsonl` incrementally: one cursor per file, advanced only to the last complete newline. The directory runs to hundreds of megabytes, so a re-read per request is not an option. Measured on a 930 MB directory: **40 ms cold, 1 ms warm.** Four correctness rules the module exists to enforce: 1. **Only `proxy-.jsonl`.** `proxy-attempts-*` carries one row per retry; folding it in multiplies a retried request's tokens by its retry count. 2. **Fold by `requestId`, conditionally.** A request is logged twice when a streamed body finishes and its token counts arrive late — the Codex engine does exactly this. Totals derive from a requestId-keyed map, never a sum of lines. The fold is NOT unconditional deduplication: two lines merge only when the earlier one carries no usage. `requestId` can come from a client-supplied `X-Request-ID` and nothing enforces uniqueness, so two genuinely distinct usage-bearing requests that share an id are counted separately. A consumer that dedupes on id alone will undercount — see the fuller explanation below. 3. **Filter by engine.** The log is shared with the Codex pool, and an operator can use the same email for both. Without the filter, ChatGPT tokens land on the Anthropic row and get priced at the wrong vendor's rates. 4. **Never build the row set from the log.** An account that served no traffic today would vanish — precisely when you most want to see it, because it is probably cooling or exhausted. A deleted file (retention) freezes its totals rather than dropping them; a file that shrank was deleted and recreated, so the cursor resets. ## Row kinds and what they mean `kind` says what a row actually is, and consumers are expected to filter on it: | `kind` | Meaning | | ------------- | ---------------------------------------------------- | | `account` | A real credential. Render it. | | `internal` | Proxy plumbing (`proxy/internal`). Not a credential. | | `translation` | A translation pseudo-account. Not a credential. | An account that is **currently unroutable** — disabled in the token store after a permanent refresh failure, or excluded by the active allowlist — is still `kind: "account"`, with `status: "unrouted"` and no `quota` block. It is absent from the quota snapshot, so its row is built from usage stats alone. This matters because it is the row an operator is looking for when they ask why an account stopped serving traffic. Tagging it `internal` — as the endpoint originally did for anything the quota snapshot did not return — hid it behind exactly the filter this table tells consumers to apply. ## What `usage` counts as one request Usage comes from the proxy's request log, where a single request can appear on more than one line: the Codex engine writes once when the response headers are known, carrying no tokens, and again when the SSE stream ends, carrying all of them. Those two lines are folded together, so a streamed request counts once and keeps its tokens. Two lines are only folded when the earlier one carries no usage. `requestId` can come straight from a client-supplied `X-Request-ID` header and nothing enforces uniqueness, so a fixed correlation header or an idempotency wrapper produces genuinely distinct requests that agree on id, account and model. Those each carry their own usage, and are counted separately rather than collapsed into one. ## Per-CLI attribution Each row's `usage` carries a `byClient` map splitting the same totals by the CLI that spent them: ```json "usage": { "requests": 412, "costUsd": 18.44, "byClient": { "claude-code": { "requests": 380, "costUsd": 17.90, "inputTokens": 1200000, "outputTokens": 90000, "cacheReadTokens": 400000, "cacheCreationTokens": 12000 }, "opencode": { "requests": 32, "costUsd": 0.54, "inputTokens": 40000, "outputTokens": 3000, "cacheReadTokens": 0, "cacheCreationTokens": 0 } } } ``` One pooled account is routinely shared by several CLIs, so an account-level total cannot answer _what_ is costing money — only _which credential_ paid. The split reconciles with the account total: summing `byClient` requests and cost gives back `requests` and `costUsd`, and a test asserts it, so a dashboard showing both cannot contradict itself. ### Client names The name is derived from `User-Agent`, and the raw header is stored alongside it. Only prefixes observed in real traffic are classified — a guessed mapping that never matches looks identical to one that works, and files a client under the wrong name when the guess collides. | Key | Meaning | | -------------- | -------------------------------------------------------------------- | | `claude-code` | `claude-cli/*` | | `sdk` | `ai/*`, the AI SDK's own agent | | `unknown` | A `User-Agent` was sent but is not classified yet | | `unattributed` | No `User-Agent` recorded — traffic logged before attribution existed | `unknown` and `unattributed` are deliberately distinct: the first is a client we saw and could not name, the second is history we cannot reconstruct. Folding them together would make old traffic look like an unidentified tool. For an `unknown` client the raw `User-Agent` is preserved on the log record, so it stays attributable by its own header rather than collapsing into one bucket with every other unrecognised caller. Adding a name is then a one-line entry in `src/lib/proxy/clientAttribution.ts` once the header has actually been observed. --- ## Onboarding a New AI Coding CLI onto the NeuroLink Proxy # Onboarding a New AI Coding CLI onto the NeuroLink Proxy ## Status: Understanding document — no code changes proposed yet This document maps what it actually costs to add a fourth, fifth or sixth AI coding CLI to the NeuroLink proxy. It is the result of verifying an earlier audit (performed against **v11.2.2**, commit `0e935499`) line by line against **v11.2.3**, commit `8728bbb3`. Everything below was re-read in this worktree. Where the earlier audit was wrong or imprecise, §2 says so plainly. Line numbers are from `8728bbb3` and were checked with `grep -n` / `sed -n`; they will drift. > **Branch state, as of the audit (2026-08-21):** `feat/cli-support` carried > **zero** commits of its own — `git log origin/release..HEAD` was empty and > `origin/release` was one commit _ahead_ (`67386e95`, `.releaserc.json` only). > Recorded as the starting point this audit worked from; it is a historical > snapshot, not a claim about the branch today. ## 1. The shape of the problem The proxy is a Hono app bound to `127.0.0.1:55669` by default (`proxy.ts:3864`, `:4532`, `:5590`; port default `55669` at `:4536`). It terminates a CLI's own OAuth token, swaps in one from a pooled account, forwards upstream, and relays SSE back. It exposes **three wire surfaces**: | Door | Factory | Upstream | | ----------------------------------- | ------------------------------------------------------- | --------------------------------------- | | `POST /v1/messages` | `createClaudeProxyRoutes` (`claudeProxyRoutes.ts:8316`) | `api.anthropic.com` | | `POST /v1/chat/completions` | `createOpenAIProxyRoutes` (`openaiProxyRoutes.ts:351`) | translation engine / Anthropic loopback | | `POST /backend-api/codex/responses` | `createCodexProxyRoutes` (`codexProxyRoutes.ts:568`) | `chatgpt.com/backend-api` | Dispatch is **by URL path**. A CLI is "onboarded" by writing _that CLI's own config file_ so it points at the right door. Three such writers exist, hand-authored, sharing no abstraction: | CLI | Writer | Restore | Target | | ----------- | --------------------------------------------- | --------------------------------------- | ---------------------------------- | | Claude Code | `setClaudeProxySettings` `proxy.ts:625-652` | `clearClaudeProxySettings` `:654` | `~/.claude/settings.json` (`:248`) | | OpenCode | `setOpenCodeProxySettings` `proxy.ts:734-784` | `clearOpenCodeProxySettings` `:786-843` | `opencode.json` (`:722`) | | Codex | `setCodexProxySettings` `proxy.ts:922-994` | `clearCodexProxySettings` `:996` | `~/.codex/config.toml` (`:857`) | **`/v1/chat/completions` is the important door and nothing is pointed at it.** `/v1/chat/completions` speaks plain OpenAI Chat Completions and requires **no inbound authentication at all** — `grep` for `authorization` in `openaiProxyRoutes.ts` returns nothing. The OpenCode writer supplies a placeholder `apiKey: proxyKey || "neurolink-proxy"` (`proxy.ts:778`) purely because the AI SDK demands a non-empty string. Any CLI that can be told a base URL and an arbitrary API key lands here with zero protocol work. ### Coverage, verified on this machine | CLI | Installed | Verdict | Mechanism | | ------------ | ----------------------------- | ------------------------- | -------------------------------------------------------------- | | Claude Code | yes | **live** | `ANTHROPIC_BASE_URL` | | Codex | yes | **live** | `config.toml` `base_url` + `wire_api="responses"` | | OpenCode | 1.3.13 | **live** | `provider.neurolink` in `opencode.json` (fixed: #1366/#1367) | | Qwen Code | `@qwen-code/qwen-code@0.17.0` | **live** | `security.auth.baseUrl` → `/v1/chat/completions` | | Copilot CLI | `@github/copilot@1.0.56` | **live** | `COPILOT_PROVIDER_*` via a sourceable env script | | Hermes Agent | no | easy (unverified on disk) | `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` | | Gemini CLI | `@google/gemini-cli@0.53.0` | moderate | `GOOGLE_GEMINI_BASE_URL`, API-key mode only | | Amp | `0.0.1780291930-gf6d536` | **hard** | `AMP_URL` honoured, but fronts a proprietary backend — see §7c | | Cursor | `cursor-agent` 2026.05.28 | **refuted** | env vars are dead code — proven by live test | | Antigravity | 1.107.0 | hard | proprietary Cascade protobuf | | Grok CLI | no | unconfirmed | not installed | | Kiro CLI | no | hard | fixed AWS hosts, OAuth device flow | Near-term: **2 live → 6** — five of those are now live (Claude Code, Codex, OpenCode, Qwen Code, Copilot CLI), with config-writer work only and zero new route modules. The remaining one is Hermes Agent, which the table above marks easy but unverified on disk. > The eleven-CLI roster above is PokeTokenBar's list plus Qwen Code, which this > audit added after verifying it directly. It is still not the whole field: SARA > tracks **Amp**, which neither of the others does, while PokeTokenBar tracks > Hermes, Kiro, Antigravity and Grok, which SARA does not. **The union is 12.** > Scope coverage against the union, not any single list. Amp is now exhaustively > assessed — see §7c — and is **not onboardable** as a config-writer client. --- ## 2. Corrections to the v11.2.2 audit The earlier audit's structural claims hold. Five of its specific claims do not. ### 2.1 The cost defect is attributed to the wrong route — and the failure mode is different **Claimed:** `proxyTracer.ts:497` and `:826` hard-code `calculateCost("anthropic", …)`, so Codex traffic to `chatgpt.com` is costed against Anthropic's price table. **Actually:** - There are **four** hard-coded `"anthropic"` sites, not two: `proxyTracer.ts:497`, `:826`, `:874` (all `calculateCost`) and `:883` (the `recordAIRequest` metric call, which feeds `ai_requests_total`; the proxy also counts requests with its own `proxy_requests_total` counter). - **`codexProxyRoutes.ts` never imports `ProxyTracer` and never calls `calculateCost`.** Its `logRequest()` object literal (`:322-339`) has no token keys at all, and it never parses `usage` out of the SSE stream. Codex traffic is not mis-priced — it is **entirely unaccounted**. Fixing it starts with parsing `usage`, not with the pricing call. - The hard-coded provider actually mis-prices **`/v1/chat/completions`**, which routes through `ModelRouter` to any provider. - The failure mode is usually **$0, not a wrong number**. `findRates` returns `undefined` when nothing matches, and `calculateCost` then returns `0` (`pricing.ts:755-758`). The `anthropic` table (`pricing.ts:26-161`) has **no `_default`** sentinel — the first one is at `:406`. So `findRates("anthropic", "gpt-4o")` → `undefined` → **$0**. Real mis-pricing only happens when a _Claude-named_ model is routed elsewhere (e.g. a `claude-*` alias mapped to Vertex Gemini), which prices Gemini traffic at Sonnet rates. - Compounding it: `ProxyTracer.model` is `private readonly` (`proxyTracer.ts:248`), fixed at construction to the model the **client asked for**. `setModelSubstitution()` only writes span attributes. So even with a correct provider string, cost is computed against the requested model, not the served one. **Good news:** `pricing.ts` already ships 18 provider tables including `openai` with a `"gpt-5.1-codex"` entry (`:162+`). For the `/v1/chat/completions` path this is a parameter change, not new pricing data. ### 2.2 "Nothing identifies the calling CLI at request time" is false — and this is an onboarding hazard **Claimed:** `detectClientApp()` (`proxyTracer.ts:226-235`) is the only User-Agent sniff and it only labels trace spans. **Actually:** there is a second sniff that drives **real request behaviour**. `isLikelyClaudeClient()` (`claudeProxyRoutes.ts:2341-2350`) tests `headers["user-agent"]?.startsWith("claude-cli/")` (among other signals), and its result gates: 1. which OAuth beta header set is sent — `CLAUDE_CODE_OAUTH_BETAS` vs `NON_CLAUDE_OAUTH_BETAS` (`:7221-7236`); 2. whether `polyfillOAuthBody()` preserves the client's own system-prompt / agent identity blocks verbatim or strips and relocates them; 3. `maybeRefreshClaudeSnapshot()` (`:2398`). **This matters directly for CLI #4 and #5.** Any non-Claude CLI pointed at `/v1/messages` via `ANTHROPIC_BASE_URL` — Hermes is exactly this case — takes the `NON_CLAUDE_OAUTH_BETAS` branch and a different system-prompt path. That is probably correct behaviour, but it is behaviour, and it must be tested rather than assumed. ### 2.3 "314,116 requests and no ledger" is overstated `usageStats.ts` (1,478 lines, zero occurrences of `inputTokens` / `outputTokens` / `totalTokens` / `cost`) is confirmed. But `neurolink proxy analyze` is a real, wired command (`src/cli/parser.ts:260`) and `proxyAnalysis.ts:437-527` reads the same `proxy-YYYY-MM-DD.jsonl` files `requestLogger.ts` writes and sums `inputTokens`, `cacheReadTokens` and `cacheCreationTokens` per window. The gap is narrower and more specific than "no ledger": **`outputTokens` and `cost` are absent from `proxyAnalysis.ts` entirely**, and nothing aggregates the Codex engine at all (§2.1). ### 2.4 OpenCode is two bugs, not a one-line fix The path bug is confirmed and is genuinely one line — but a path-only fix leaves a second, independent bug in place. - `getOpenCodeConfigDir()` (`proxy.ts:711-720`) returns `~/Library/Application Support/opencode` on darwin. The installed OpenCode 1.3.13 binary embeds the **unmodified `xdg-basedir` npm package** (`XDG_CONFIG_HOME || join(homedir, ".config")`) with **no platform branch at all**. Empirically: `~/.config/opencode/opencode.json` exists (2,640 bytes, holds a working custom provider that `opencode models` confirms is loaded); `~/Library/Application Support/opencode` does not exist. Deleting the `darwin` branch is the whole fix. - **The second bug survives that.** `setOpenCodeProxySettings` returns `Promise` (`:734`) and the call sites print `✓ Auto-configured OpenCode settings` **unconditionally** (`:3491-3493`, `:5403-5405`). `setCodexProxySettings` returns `Promise` and its `✓` is gated on it (`:3502`, `:5413`). So even after the path fix, a user without OpenCode installed still gets a success message for work that did not happen. **Origin of the mistake:** the OpenCode binary _does_ contain the literal `/Library/Application Support/opencode` — as `systemManagedConfigDir()`, an MDM / enterprise policy tier at the **filesystem root** (no `$HOME`), paired with `/etc/opencode` and `%ProgramData%\opencode`. Someone found that string and read it as the per-user path. **It is also baked into our own docs.** `docs/features/opencode-proxy-support.md:67` asserts the macOS path is `~/Library/Application Support/opencode/opencode.json`, while `:313-323` of the same file shows resolution code with no darwin branch that would compute `~/.config/opencode`. The doc contradicts itself, and it is titled _"Implemented & Verified"_. **How it escaped verification:** §11's E2E playbook runs the dev proxy with `--dev`, which by its own option description performs "no client auto-configuration" (`proxy.ts:3910-3917`), and hand-copies a fixture to `/tmp/opencode-proxy-test/opencode.json`. The writer is never executed. There is also zero automated coverage — `grep` for `setOpenCodeProxySettings` across `test/` returns nothing; only two unused fixture JSON files mention OpenCode. ### 2.5 Smaller drifts | Claim | Correction | | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `RouteGroup` at `types/server.ts:395-448` | `RouteGroup` is `:443-458`. `:395-431` is `RouteDefinition`. | | Copilot works via `OPENAI_API_KEY`+`OPENAI_BASE_URL` | True **only** with `COPILOT_ENABLE_ALT_PROVIDERS=true` (`app.js:6119`). The `COPILOT_PROVIDER_*` path has no such gate. | | Gemini OAuth is pinned to `cloudcode-pa.googleapis.com` | Pinned _by default_, but `CODE_ASSIST_ENDPOINT` overrides it unconditionally (`getBaseUrl()`, chunk `:309590-309592`), documented by Google as dev/test-only. | | Claude writer range `622-651` | Function is `625-652`; `:623` is `PROXY_MANAGED_KEYS`, correct. | | Cursor refutation | **Upheld, and strengthened.** A live run with `CURSOR_LOCAL_AGENT_BASE_URL` set returned `Authentication required` — the env vars had zero effect. Do not build for it. | --- ## 3. Touch points: a config-writer-only CLI **This section described eleven edits. It is now two.** The writers moved behind a `CliProxyClientConfigurator` contract (`src/lib/types/proxyClient.ts`), one module per client under `src/cli/proxy-clients/`, assembled by `registry.ts`. The four duplicated call-site blocks in `proxy.ts` collapsed into `applyAllClients()` and `restoreAllClients()`. To add a CLI that only needs to be told a base URL: | # | File | What to do | | --- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 1 | `src/cli/proxy-clients/.ts` | Implement `CliProxyClientConfigurator`: `id`, `displayName`, `detect()`, `apply(proxyBaseUrl)`, `restore(proxyBaseUrl)`. Snapshot the user's prior config before overwriting, and return `false` from `apply` when nothing was written. | | 2 | `src/cli/proxy-clients/registry.ts` | Add it to `PROXY_CLIENT_CONFIGURATORS`. | Plus a test and a doc entry, as for any change. Nothing in `proxy.ts` is touched at all. ### The one client that needs a shell, not a file Copilot CLI reads its provider settings from `process.env` only — `app.js` resolves `COPILOT_PROVIDER_BASE_URL` and siblings directly, and `~/.copilot/config.json` (which announces itself as "managed automatically") carries no provider block. **There is no file the proxy can write that Copilot will read.** Rather than edit a shell profile — which lives outside the proxy's blast radius and runs on every shell — the configurator writes `~/.neurolink/copilot-env.sh` and expects one line in your profile: ```sh [ -f ~/.neurolink/copilot-env.sh ] && . ~/.neurolink/copilot-env.sh ``` The proxy deletes the script on stop, and the `-f` guard makes a missing file a no-op, so no NEW shell picks up a stale export. A shell that already sourced it keeps the variables for its own lifetime — deleting a file cannot unset variables in a running process. Run `unset COPILOT_PROVIDER_URL COPILOT_PROVIDER_API_KEY` (or start a new shell) if you stopped the proxy in a session that had it loaded. Note also that Copilot's `OPENAI_API_KEY` + `OPENAI_BASE_URL` path works only with `COPILOT_ENABLE_ALT_PROVIDERS=true`; the `COPILOT_PROVIDER_*` path has no such gate, which is why it is the one used. ### What the contract enforces Three defects came from the writers disagreeing with each other. The contract makes each one unrepresentable: - **`detect()` is required**, so a writer cannot create config for a CLI that was never installed — the bug Claude Code shipped with. - **`apply()` returns `boolean`**, so a caller cannot print `✓` for work that did not happen — the bug OpenCode shipped with. - **The base-URL suffix belongs to the client** (`/v1` for OpenAI-compatible clients, bare origin for Codex), so no call site has to remember it. ### Behaviour the loops preserve `applyAllClients` wraps each client independently: one failing can neither stop the others nor abort shutdown. The daemon-start path reports failures at debug level and the setup wizard prints a visible warning — deliberately different, and both preserved. The `proxy guard` path still keys its `cleared` flag off Claude Code specifically. ## 4. Touch points: a new-wire-format CLI For Gemini CLI, which needs Google's `generateContent` shape and `usageMetadata` translation. Everything in §3 **plus**: | # | File | Lines | What to do | | --- | ---------------------------------------------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | A | `src/lib/server/routes/ProxyRoutes.ts` | new | `createProxyRoutes(basePath = ""): RouteGroup`. Model it on `codexProxyRoutes.ts` (self-contained) rather than `claudeProxyRoutes.ts` (8,300+ lines). | | B | `src/cli/commands/proxy.ts` | `:1978-1983` | Add the dynamic import alongside the other three. | | C | `src/cli/commands/proxy.ts` | `:2121-2145` | Add to the hand-assembled `allProxyRoutes` array. Mounting at `:2148-2150` is generic and needs no change. | | D | **`src/lib/server/routes/index.ts`** | `:11-29`, `:36-66` | **The second seam.** Import, re-export, and add to `createAllRoutes` — otherwise the door is CLI-only, as Codex is today. | | E | `src/lib/types/server.ts` | `:1401-1409` | Add a `CreateRoutesOptions` flag if the door should be independently toggleable. | | F | `docs/guides/server-adapters/api-reference.md` | `:657-660`, `:680-686` | **Now documented** — the `proxy`/`claudeProxy`/`openaiProxy` flags and all three proxy factories are listed. Keep it current when a door is added, or the next provider repeats the drift that made this row necessary. | | G | `src/lib/proxy/modelRouter.ts` | `resolve()`, `:50-65` | Only if model-name prefixes need extending (`gemini-` → vertex, `claude-` → anthropic). Codex bypasses `ModelRouter` entirely. | | H | `OAuth.ts` + `AccountUsage.ts` | new | Only if the CLI brings its own subscription pool. See §6. | **Two things you do _not_ need to touch**, contrary to reasonable expectation: - `src/lib/proxy/proxyDispatcher.ts` — installs one global undici keep-alive `Agent` process-wide. No provider or path names appear in the file. - `ProviderTransportCoordinator` — provider-agnostic, but instantiated **only** inside `claudeProxyRoutes.ts:249`. There is no global instance to register into; a new door may optionally construct its own. **A naming trap:** there are two unrelated `ModelRouter` classes. `src/lib/proxy/modelRouter.ts` is the HTTP one; `src/lib/utils/modelRouter.ts` is an unrelated task-classification router. Grepping without checking the import path finds the wrong one. --- ## 5. What the existing machinery gives you — and where it stops ### What `RouteGroup` genuinely provides `RouteGroup` (`types/server.ts:443-458`) is `{ prefix, routes: RouteDefinition[], middleware?, auth?, roles? }`, and `RouteDefinition` (`:395-431`) carries `method`, `path`, `handler`, plus optional schemas, auth, rate limits and streaming config. The real payoff is at the mount: `proxy.ts:2148-2150` iterates `allProxyRoutes` and calls `app[method](route.path, …)` generically, wrapping every route in the same draining check, request-metadata tracking and error envelope. **A new door inherits all of that for free** simply by being in the array. That is a genuine, load-bearing abstraction. ### Where it stops — "registry" overstates it - **There is no plugin loader, manifest, or dynamic registry for route groups.** The array at `proxy.ts:2121-2145` is hand-edited, and `createAllRoutes` in `routes/index.ts` is a second hand-edited list. The two are not derived from each other, which is exactly why Codex exists in one and not the other. - **The config writers had no abstraction — since fixed; kept here as the finding that motivated the fix.** They now sit behind a `CliProxyClientConfigurator` contract with one module per client under `src/cli/proxy-clients/`, assembled by `registry.ts` (see the section above). What follows is what the audit found at the time, which is why the strategies still differ per client: Claude and OpenCode do JSON round-trips with an inline snapshot key (`__proxy_original_env`, `__proxy_original_neurolink`); Codex does regex-driven TOML text manipulation with a marker-delimited block **and** a separate sidecar snapshot at `~/.neurolink/codex-proxy-snapshot.json`. At the time this was a notable departure from the codebase's own stated Factory+Registry convention for providers, processors, chunkers and rerankers. - **The SDK seam is untested by this repo's own CLI.** `neurolink proxy` never calls `createAllRoutes`; `neurolink server` calls it but never passes any proxy flag (`grep -i proxy src/cli/commands/server.ts` → nothing). The `proxy` / `claudeProxy` / `openaiProxy` options exist solely for external SDK consumers, and no code in this repo exercises them. **The single highest-leverage refactor was extracting a `ClientConfigurator` registry** — `{ id, detect(), apply(baseUrl), restore(baseUrl) }` — so the four duplicated call-site blocks collapse into one loop. **This has since been done**: the writers live under `src/cli/proxy-clients/` behind `CliProxyClientConfigurator`, and the call sites are `applyAllClients()` / `restoreAllClients()`. It turned "eleven edits across one huge file" into "one new file plus one registry line," and it is what would have prevented both halves of the OpenCode bug. Do not re-extract it; onboarding a new CLI now means adding a module and a registry line. --- ## 6. Position: the account namespace is not a prerequisite The earlier audit's headline recommendation was to generalise the account-key namespace _before_ CLI #5 and #6. **I disagree, and the code says so.** ### The facts are right `accountSelection.ts` is 52 lines and entirely Anthropic-shaped — `LEGACY_ANTHROPIC_ACCOUNT_KEY`, `ENV_ANTHROPIC_ACCOUNT_KEY`, `normalizeAnthropicAccountKey()`, `anthropicAccountKeysEqual()`, all normalising to an `anthropic:` prefix. Codex runs a parallel namespace via `CODEX_ACCOUNT_PREFIX = "codex:"` (`codexAccountUsage.ts:29`). `codexProxyRoutes.ts` imports **nothing** from `accountSelection.ts` — verified, zero hits. Pooling really is written twice. ### But it does not block a config-writer CLI — at all Trace an inbound `/v1/chat/completions` request: - If `ModelRouter` resolves the model to `anthropic`, the handler forwards it by loopback to the proxy's **own `/v1/messages`** (`openaiProxyRoutes.ts:396`, bridge at `:141-148`). Its comment is explicit: this "reuses the full Claude passthrough path (OAuth account rotation, retry, SSE interception, etc.)". The request rides the **existing Anthropic pool, unchanged**. - Otherwise it falls through to the translation engine and `ctx.neurolink.stream()` — normal SDK credential resolution, **no account pool involved at all**. Either way, `accountSelection.ts`, `accountCooldown.ts`, `accountQuota.ts` and the token store are untouched. Reinforcing this: account selection **has no concept of caller identity**. `clientApp` exists but is telemetry-only. Pooling is scoped by provider key prefix, never by which CLI called. A new caller is invisible to that subsystem _by construction_, not by luck. **So: Copilot CLI, Hermes and a fixed OpenCode need zero namespace work.** Sequencing a refactor ahead of them would be pure delay. ### And for a CLI that _does_ bring its own pool Copy the Codex pattern. The repo's own `CLAUDE.md` already prescribes it — "a new `OAuth.ts`, a `AccountUsage.ts` quota parser, and a `ProxyRoutes.ts` engine — do not modify the Anthropic hot path" — and the code supports it cheaply: `accountCooldown.ts` (162 lines) and the storage half of `accountQuota.ts` (`:500-541`) are already provider-agnostic `Record` keyed by an opaque `accountKey`, with no prefix branching. `tokenStore.listByPrefix()` is generic. Cost: roughly three new files, ~800–1,000 lines, zero risk to the Anthropic hot path. Generalising the namespace _first_ would also mean confronting the migration `CLAUDE.md` explicitly defers: Anthropic quota is keyed by **bare label** and persisted that way in every user's `~/.neurolink/account-quotas.json`, so re-keying means either discarding every stored snapshot or shipping a tolerate-both migration for a release. **Recommended sequence:** 1. Fix OpenCode (path + boolean return + the doc). Smallest possible change, restores a feature users already believe they have. 2. Add Copilot CLI. Env-var only, existing door, no new route module. 3. Add Qwen Code and Hermes. Qwen is the same shape as Copilot (`OPENAI_BASE_URL`, existing door). Hermes needs the `isLikelyClaudeClient` branch (§2.2) tested deliberately, since it lands on `/v1/messages` without a `claude-cli/` User-Agent. 4. **Then** extract the `ClientConfigurator` registry, with four real implementations to generalise from rather than three. 5. Only when a CLI with its own subscription pool arrives, copy the Codex pattern — and revisit the namespace only if a _fourth_ pool appears after that. --- ## 7. The observability / routing split These are independent capabilities with different ceilings, and treating them as one thing has hidden how cheap the second is. **Routing tops out at 5–6 of 10.** It depends on vendors shipping base-URL overrides nobody here controls. Kiro and Antigravity are structurally closed. Cursor looked like the cleanest win in the matrix and turned out to be dead code. **Reading each CLI's own local logs reaches 10 of 10.** No auth, no vendor cooperation, no proxy in the request path. It works for CLIs that can never be routed, and it recovers months of history the proxy can never see. It is also an independent source of truth — it would have caught §2.1 immediately. ### Prior art — start with SARA, not PokeTokenBar **The file-walking layer already exists in TypeScript, one repo over.** SARA (the `sara` project, a sibling checkout) ships an eight-CLI session reader registry at `packages/agents/src/sessions/`: - `registry.ts:171-213` — dedicated lazy-factory readers for Claude, Codex, OpenCode and Gemini, registered via `registerReader(id, async () => …)` with dynamic imports — the same shape as `providerRegistry.ts`. - `registry.ts:228` — a generic `ProviderSpec` loop covering Cursor, Amp, Qwen and Copilot, with the specs in `jsonlReaders.ts:94-200`. - Per-CLI on-disk paths already resolved: `~/.cursor/projects/…`, `~/.local/share/amp/threads`, `~/.qwen/projects/…`, `~/.copilot/session-state`. - `registry.ts:252` keeps `const VERIFIED = ["claude", "codex"]` and exposes it as `verified` on each descriptor (`:272`) — an honesty marker separating readers confirmed against real data from ones written to spec. **Worth copying that idea regardless of what else we take.** **What SARA does not do is extract usage.** Only `claudeReader.ts` touches tokens at all (18 hits for `token`/`usage`/`cost`; `codexReader.ts`, `geminiReader.ts`, `opencodeReader.ts` and `jsonlReaders.ts` each have **zero**) — and it does so only to compute current context-window occupancy, deliberately non-cumulative so it self-corrects after compaction (`claudeReader.ts:52-69`). The other readers parse transcript parts and stop. **So the split is:** take file-walking, path resolution, provider detection and the registry shape from SARA — same language, already written. Take the _token extraction and aggregation_ semantics from PokeTokenBar, which is the part SARA lacks and the part that is actually hard. The `poketokenbar` project is ~3,600 lines of Swift covering these ten formats: `LocalUsageReader.swift` (1,264), `LocalUsageCache.swift` (373), `LocalAdditionalUsageProvider.swift` (1,077), `LocalAntigravityUsageReader.swift` (542), `LocalUsageProvider.swift` (171). A TypeScript port is **smaller than a transliteration**, because Node needs neither Swift's actor/`NSLock` concurrency scaffolding nor `BinaryLocator.swift` (230 lines that exist only so a Finder-launched `.app` can see shell exports). Per-format estimates: Claude ~120 lines, Gemini ~80, Hermes ~70, OpenCode ~150, Grok ~180, Cursor ~180 + ~150 shared incremental-SQLite scaffolding. **Risk concentrates in two:** Codex (~600 lines — a session-DAG/prefix-match reconciliation algorithm, not a file parse) and Antigravity (a mini protobuf codec with no schema). Budget and review those separately from the other eight. Three things a port must decide up front: 1. **A tri-state cost field.** Claude/Gemini/Grok/OpenCode/Hermes report real or well-modelled cost; Cursor/Copilot/Antigravity are flat-rate and report none; Kiro's numbers are a _byte heuristic_ and must never be shown with the same confidence. This maps onto the existing `jsonRepaired` / `jsonTruncated` "exact or salvaged" convention in `CLAUDE.md` rule 3 — reuse it rather than invent one. 2. **Dedup is per-format, not generic.** Claude/Grok/OpenCode use content-hash keep-max; Gemini needs last-write-wins because `message_update` records intentionally supersede; Cursor/Copilot need SQLite rowid high-water marks _plus_ a `didReset` full-rescan fallback for post-`VACUUM`. Codex needs the DAG resolution. 3. **SQLite is a real dependency decision.** Six of ten formats need it. `package.json` lists `sqlite3` in `onlyBuiltDependencies` but the lockfile shows it is not actually installed — the only SQLite reference is `better-sqlite3` as an _unmet optional_ peer of `@juspay/hippocampus`. Given this repo's recent CI commits specifically about avoiding unnecessary native binaries (`6f839235`, `a3490501`), `node:sqlite` (Node 22.5+) deserves serious consideration over a native module. Only **4 of 10** formats are testable against real data on this machine today: Claude (16,830 `.jsonl` files), Codex (122 rollouts), Gemini (9 files), OpenCode (a 305 MB `opencode.db`). PokeTokenBar's own per-format test fixtures are worth reusing for the other six. Note also that `~/.copilot/session-store.db` on this machine has **no `assistant_usage_events` table** — PokeTokenBar's Copilot reader targets a schema that has since changed, so "the file exists" is not evidence a format is portable. ### Where it belongs **Not on this branch.** `feat/cli-support` is about routing — config writers and route modules. Local-log reading shares no code with any of it: it never touches `proxy.ts`, `routes/`, or the account pools, and it is explicitly _not_ a modification of `accountUsage.ts` (which polls providers' **remote** usage APIs for accounts in NeuroLink's own pool, covering only Anthropic and Codex). It should be its own branch and its own subsystem — a new `src/lib/localUsage/` with one reader per CLI behind a lazy dynamic-import registry mirroring `providerRegistry.ts`, and types in `src/lib/types/localUsage.ts` per rule 2. One wrinkle worth designing for early: PokeTokenBar is a long-running menu-bar app, so it keeps Kiro's and Codex's cross-scan merge state in memory. A CLI invocation has no equivalent, so that state must be persisted to disk. --- ## 7b. Feasibility, verified live (2026-08-22) Four rows the audit left unresolved were tested against a real proxy on this machine rather than reasoned about. The method is the one that refuted Cursor: start `neurolink proxy start --port 9911`, point the CLI's documented override at it, run one trivial command, and see whether anything arrives. | CLI | Override | Result | | ---------------------- | ------------------------ | ------------------------------------------------------------------------------- | | **Gemini CLI** 0.53.0 | `GOOGLE_GEMINI_BASE_URL` | **Honoured — traffic arrives.** Verdict upgraded from assumed to verified. | | **Amp** 0.0.1780291930 | `AMP_URL` | **Honoured — but fronts a proprietary backend. Not onboardable; see §7c.** | | **Hermes Agent** | — | Cannot be verified: not installed, no binary and no config dir on this machine. | | **Grok CLI** | — | Cannot be verified: not installed; two rival npm packages claim the name. | ### Gemini CLI — the override is real; the door is what is missing With `GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:9911` the CLI reached the proxy and failed with `ModelNotFoundError: 404 Not Found` from `classifyGoogleError`. That is the correct answer from a proxy with no `generateContent` route: the redirect worked, and there was nothing to answer it. So the remaining work is exactly §4's new-wire-format list and nothing more — no vendor cooperation is needed, and the override does not have to be discovered or negotiated. Two operational notes for whoever builds it: the CLI refuses to run outside a trusted directory (`--skip-trust` or `GEMINI_CLI_TRUST_WORKSPACE=true` for headless testing), and it issues a `generateJson` call during startup, so the door has to answer more than just the user's turn. ### Amp — override honoured, but it brings its own front door `AMP_URL` is genuinely live, unlike Cursor's inert variables: pointed at the proxy, Amp built its login URL against it — `http://127.0.0.1:9911/auth/cli-login?authToken=…` — and waited for a code. That is also the finding. Amp does not authenticate with a bearer token the way the five live CLIs do; it expects an OAuth-style CLI login flow at its own endpoint before any API traffic. Onboarding it therefore means implementing Amp's auth surface, not writing a config file, which puts it in the new-wire-format class with Gemini rather than the config-writer class. Its bundle vendors Google's GenAI SDK, so `generateContent` strings inside it describe a dependency and not Amp's own wire — worth knowing before someone greps for them and concludes otherwise. This was the assessment with no `AMP_API_KEY` set, so the login prompt was as far as the CLI got. **§7c re-runs this with a key supplied, past the login prompt, and reaches a materially worse conclusion: Amp is not "new-wire-format like Gemini," it is a proprietary control-plane CLI, and pointing it at this proxy makes it fail every invocation rather than merely fail to find a route.** ### Hermes and Grok — unverifiable here, and that is the finding Neither is installed: no binary on `PATH`, no `~/.hermes` or `~/.config/hermes`, nothing under any package root. The audit's "easy (unverified on disk)" verdict for Hermes remains exactly that — it was never validated, and the `ANTHROPIC_BASE_URL` claim comes from documentation rather than from a bundle. Recording this rather than leaving the rows ambiguous: the blocker is availability, not difficulty, and the first step for either is installing it — not writing a configurator against a guessed config surface. --- ## 7c. Amp CLI, exhaustively assessed (2026-08-29) §7b's Amp finding stopped at the login prompt because no `AMP_API_KEY` was set. Supplying a placeholder key (`AMP_API_KEY=test-capture-key`) bypasses the OAuth flow and lets the CLI proceed — which is what actually settles whether Amp is onboardable as a `CliProxyClientConfigurator`, not merely whether `AMP_URL` is honoured. **Config surface, confirmed from the installed binary (`0.0.1780291930-gf6d536`, `@sourcegraph/amp` wrapping `@ampcode/cli`) and matching a live `amp --help`:** - `AMP_URL` (env, highest precedence; default `https://ampcode.com/`) — the same variable §7b tested. - A persisted `"url"` key in the global settings file, default `~/.config/amp/settings.json` (resolved via `XDG_CONFIG_HOME || ~/.config` — no macOS-specific `Application Support` branch; confirmed both from the bundle's path-resolution constants and from `amp --help` reporting exactly that path on this machine). - `AMP_SETTINGS_FILE` — overrides the settings-file path outright; used throughout this investigation to keep every probe out of the user's real `~/.config/amp/settings.json`. - `AMP_HOME`, `AMP_LOG_LEVEL`, `AMP_LOG_FILE` — logging/home overrides, not routing-relevant. - `AMP_API_KEY` (env) or a settings-file `apiKey` — bearer credential. None of this contradicts §7b. What's new is what happens once the CLI is actually let past login. **Two probes against a local capture server (not the live proxy), both with `AMP_URL` and `AMP_SETTINGS_FILE` redirected into a scratch directory and `AMP_API_KEY` set to a placeholder:** 1. A naive stub returning `200 {"error":"capture-server-stub"}` for every request. Amp's client reads `$.error.code`, gets `undefined` back from a string error, and fails with a garbled `getUserInfo error: undefined` — an artifact of the stub's shape, not a finding on its own, but it already shows the first call Amp makes once past login is `POST /api/internal?getUserInfo`. 2. A properly-shaped server returning `{"ok":true,"result":{...}}` envelopes for `getUserInfo` and `loadPlugins`. With those two calls satisfied, Amp proceeded to `POST /api/thread-actors` with body `{"executorType":"local-client","agentMode":"smart"}` — a third, distinct proprietary RPC that provisions the agent's execution thread. No model call was ever attempted; the run was stopped once this third call landed, since answering it too would mean building out Amp's orchestration layer, not a completions endpoint. So the actual call sequence, before Amp ever needs a model response, is: `/api/internal?getUserInfo` → `/api/internal?loadPlugins` → `/api/thread-actors`. All three are bespoke JSON-RPC-shaped endpoints private to Amp's backend, and none of them map onto any of the proxy's four wire doors (`/v1/messages`, `/v1/chat/completions`, `/backend-api/codex/responses`, `/v1beta/models/{model}:generateContent`). The bundle also contains `/api/provider/{anthropic,openai/v1,google}` sub-paths. These are **not** something the CLI calls directly once `AMP_URL` is repointed — they are the internal sub-paths Amp's own backend (or a self-hosted Amp Enterprise gateway) uses to reach upstream model providers. The CLI cannot reach them without first clearing the `/api/internal` and `/api/thread-actors` calls above, so implementing just the provider sub-paths would not unblock anything. (This also corrects §7b's aside about vendored Google GenAI SDK strings: that observation stands on its own, but it is a separate red herring from these internal provider sub-paths, not the same one.) **Confirmation against the real live proxy** (`neurolink proxy start`, `http://127.0.0.1:55669`, the same instance used elsewhere in this document): pointing an installed Amp at it with `AMP_API_KEY` set reproduces the same `/api/internal?getUserInfo` call, which the proxy answers with its default `404` (no such route exists on any of its four doors), and Amp exits immediately: ``` Error: API request for getUserInfo failed: 404 ``` No model call is attempted — the CLI fails structurally before reaching that stage, so this is not a case of "wrong door, add a route" the way Gemini's `ModelNotFoundError: 404` was in §7b. A `404` on `/api/internal` cannot possibly reach the proxy's upstream-attempt accounting, so the routing proof here is the `404` response and Amp's fatal exit themselves, not a `stats.totalAttempts` counter delta — that counter is only a clean signal for a _positive_ routing proof, and this is a negative one by construction. **Verdict: Amp is not onboardable as a `CliProxyClientConfigurator`, and no `amp.ts` was written.** This is a different failure mode from Copilot's sourceable-script problem (§3's "one client that needs a shell, not a file"): an un-sourced Copilot script is _inert_ — Copilot keeps working exactly as it did before the proxy touched it. Pointing Amp's `AMP_URL` at this proxy is **actively harmful** — every invocation hard-fails with a fatal error until an operator reverts the setting, because the proxy does not implement (and cannot cheaply implement) Amp's proprietary auth/user-info RPC, its thread orchestration RPC, or the OAuth login flow found in §7b. Shipping a configurator that "successfully" applies this URL would leave users with a broken `amp` CLI and a proxy that reports success — worse than not onboarding it at all, and precisely the outcome this document's §3 and the Copilot precedent warn against reproducing. `registry.ts`'s six configurators (Claude Code, OpenCode, Codex, Qwen Code, Copilot, Gemini CLI) are unchanged; no config file outside this worktree's scratch directory was ever written, and no real `~/.config/amp` or `~/.amp` was touched. Amp's coverage-table verdict (§1) is revised from an unassessed slot in the twelve-CLI union to **hard** — alongside Antigravity and Kiro, not alongside Gemini's config-writer-adjacent "moderate." Worth flagging for whoever revisits this against a newer Amp release: the `/api/internal` query-string RPC style (`?getUserInfo`, `?loadPlugins`) reads as intentionally proprietary rather than an accidental subset of some open protocol — there is no partial-compatibility shortcut here to chase. --- ## 8. Defects Eleven filed on `juspay/neurolink`. Eight are fixed and released (v11.13.0 and v11.14.0, via #1399-#1402); three remain open. | # | Defect | Location | Issue | Status | | --- | ------------------------------------------------------------------------------------------- | -------------------------------------------- | -------------------------------------------------------- | ------------------------------------- | | 1a | OpenCode writer targets a path OpenCode never reads on macOS | `proxy.ts:711-720` | [#1366](https://github.com/juspay/neurolink/issues/1366) | **fixed** | | 1b | `✓ Auto-configured OpenCode` prints unconditionally — survives 1a's fix | `proxy.ts:734`, `:3491`, `:5403` | [#1367](https://github.com/juspay/neurolink/issues/1367) | **fixed** | | 1c | The same wrong path is asserted in our own docs, which contradict themselves | `opencode-proxy-support.md:67` vs `:313-323` | [#1366](https://github.com/juspay/neurolink/issues/1366) | **fixed** | | 1d | Zero test coverage for the writers; §11's playbook uses `--dev`, which skips them | `test/` | [#1368](https://github.com/juspay/neurolink/issues/1368) | **fixed** — all three writers covered | | 2a | Codex engine has no token/cost accounting at all — never parses `usage` | `codexProxyRoutes.ts:322-339` | [#1369](https://github.com/juspay/neurolink/issues/1369) | **fixed** | | 2b | Provider hard-coded `"anthropic"` at four sites | `proxyTracer.ts:497`, `:826`, `:874`, `:883` | [#1370](https://github.com/juspay/neurolink/issues/1370) | **fixed** | | 2c | Cost computed against the _requested_ model, not the served one | `proxyTracer.ts:248` | [#1370](https://github.com/juspay/neurolink/issues/1370) | **fixed** | | 3 | `proxyAnalysis.ts` aggregates no `outputTokens` and no cost | `proxyAnalysis.ts:437-527` | [#1371](https://github.com/juspay/neurolink/issues/1371) | **fixed** | | 4 | SDK server-adapter docs omit all three proxy factories and the `proxy` flags | `api-reference.md:657-686` | [#1372](https://github.com/juspay/neurolink/issues/1372) | **docs written**, issue still open | | 5 | Codex CLI model discovery 404s — proxy has `/responses` but not `/backend-api/codex/models` | `codexProxyRoutes.ts:615` | [#1383](https://github.com/juspay/neurolink/issues/1383) | open | | 6 | Client config writers: no locking or atomic writes between apply and restore | `src/cli/proxy-clients/` | [#1384](https://github.com/juspay/neurolink/issues/1384) | open | **Security note, not a defect:** the proxy takes no inbound authentication on any door. That is defensible at the `127.0.0.1` default, but `--host` accepts `0.0.0.0`, which would expose pooled OAuth subscription tokens to the network. Any new writer must not assume an auth layer exists. --- ## 9. Repo conventions this work must follow - **`CLAUDE.md` rules 2, 7–15 are ESLint-enforced.** Most relevant here: types go in `src/lib/types/` only (rule 2); `type`, never `interface` (rule 7); barrel-only internal type imports (rule 13); no double assertions (rule 14). - **Rule 15 — tests are end-to-end only.** Import from `dist/index.js`, or drive `node dist/cli/index.js`. Never mix `dist` and `src` in one suite. Both `test/continuous-test-suite-proxy.ts` and `-codex.ts` are on the `e2e-tests-only` `allow` list in `eslint.config.js:262-291` with written justifications, and the codex suite deliberately keeps its last two cases driving the built CLI. A new proxy suite should follow that shape, and adding to the allow list is a review decision. - **Keep payloads out of assertion messages.** `defineSuite` downgrades a failure to SKIP when the message matches `isExpectedProviderError()`, so quoting a payload containing `502` or `ECONNREFUSED` turns a real failure green. Sanity-check any new suite by breaking one assertion on purpose. - **CI has six jobs, not two.** `CLAUDE.md`'s note is incomplete: alongside `test` and `provider-safety-net` there are `build-check`, **`proxy-performance`** ("Proxy Performance Gates", runs `pnpm run proxy:performance` against `proxyLifecycle.ts` / `proxyActivity.ts`), `quality-gate` (validate, commit-message validation, `tsc --noEmit --strict`) and `semantic-release-validation`. `provider-safety-net` also runs several suites the pre-push hook does not — `test:providers-mocked`, `test:error-classifier-contract` and the bedrock / sagemaker / anthropic / aistudio characterization suites. **A new proxy engine can trip `proxy-performance`.** - **Docs PRs are gated.** `docs-pr-validation.yml` triggers on `docs/**` and runs a Docusaurus typecheck and build **without** `continue-on-error`. Frontmatter and link checks are soft. - **Decide the orphaning question deliberately.** `codex-proxy-support.md` and `opencode-proxy-support.md` have no frontmatter, are absent from `docs-site/scripts/sync-docs.ts`, and are unlinked from `docs/features/index.md`. Following that precedent exactly means a new doc is not published and not discoverable. This document follows the precedent; that should be revisited. - **Branch naming: no ticket numbers here.** The global `/BZ--` convention is Juspay-internal Bitbucket. This OSS repo uses plain `/` — `feat/cli-support`, `fix/adjust-body-after-400`. Conventional commits; never commit directly to `release`. - **⚠️ `docs/development/contributing.md` is stale** — it teaches `interface` types (`:161`) and vitest `describe/it` (`:169-172`), both of which contradict enforced rules 7 and 15. Do not cite it as authoritative. --- ## Appendix: verification method Eight independent auditors, one per claim cluster, each required to cite `file:line` actually read and to report corrections rather than agree. Findings that could be checked against this machine were checked against installed binaries and live config, not documentation — including a live `cursor-agent` run that confirmed its env vars are inert, and a `opencode models` run that confirmed which config file is really loaded. Claims that did not survive are listed in §2 rather than quietly dropped. --- ## Proxy Peer Sharing # Proxy Peer Sharing Your proxy pool has 5-hour and 7-day windows that often go unused. Someone else's pool runs out. Peer sharing lets the first lend to the second — on the lender's terms, revocable at any moment. Each person runs their own `neurolink proxy`. There is no central server: a **lender** exposes their proxy and issues a **grant**; a **borrower** adds it as a **peer** and reaches for it only once their own accounts are spent. > **Before you share.** Lending subscription capacity to other people is very > likely outside your provider's consumer terms, and the account carrying the > traffic is the one exposed. This is a deliberate choice, not a default. ## Quick start **Lender:** ```bash # 1. Start the proxy as usual. Your own client keeps using this port. neurolink proxy start --port 3000 # 2. Issue a grant. This brings up the gate-only share listener on 3001, # which refuses every request that carries no token. neurolink proxy share create --peer bob --preset spare # 3. Publish that listener — not the main port — and re-mint the link # against the URL it prints. neurolink proxy expose neurolink proxy share url https://your-tunnel.trycloudflare.com neurolink proxy share rotate --peer bob ``` **Borrower:** ```bash neurolink proxy peer add --name alice --link "neurolink://share/...#nls_..." neurolink proxy peer test --name alice ``` That is the whole loop. The borrower's own accounts keep serving as before; the peer is consulted only when none of them can. ## Gates Sharing is not a menu of modes. A grant carries one set of **gates**, all of which must pass. The effective allowance is the tightest of them, so a grant can lend spare headroom _and_ cap the total _and_ restrict the model, all at once. | Gate | Flag | Means | | ----------------- | ------------------------------- | ----------------------------------------------------------------- | | Reserve floor | `--reserve 30` | Admit only while your own utilization leaves 30% headroom | | Window slice | `--max-slice 5h=20,7d=15` | At most a fifth of the **pool**, however it is spread | | Per-account slice | `--max-slice-per-account 20` | The same ceiling applied to each account independently | | Spillover | `--spillover 12h\` | | `POST /peer/net` | Settle one round of reciprocal netting | | `POST /peer/note` | Check a coin note, or redeem it into your balance | `/peer/limits` is scoped to the caller's own grant. It carries no account labels and no per-account figures, so it cannot be used to describe — or count — the lender's pool. ## Privacy Borrowed traffic is somebody else's conversation, so on the lender's node: - **Request and response bodies are never captured** for a borrowed request. - **`x-neurolink-account` and the pool counters are stripped** from borrowed responses on both the Claude and the Codex door — that header carries the lender's account label, which for an OAuth account is their email address. - **Error messages name no account.** A borrower whose request ends in a 401 or 403 is told how many pooled accounts need attention, never which ones. - **`GET /limits` and `GET /accounts` are refused for borrowed traffic.** Both operator views name every account with its quota and spend, and a live refresh drives usage-API calls under the lender's tokens; a borrower gets `/peer/limits` instead. - **`/status` releases account identity only to the update-control token** once the gate is on, since a gated proxy is by definition one that may be exposed. With an inbound token configured, `/status` is refused outright without it. - **The borrower's own headers stay on the lender's node.** Only protocol headers travel upstream; the share token, `x-neurolink-*`, trace context and CDN/forwarding identity (`cf-connecting-ip`, `x-forwarded-for`, …) are dropped, so a borrower's real address is never presented to the provider under the lender's identity. - **Borrowed Codex requests cannot touch account-side state.** `previous_response_id`, `prompt_cache_key`, `metadata` and `user` are dropped and `store` is forced to `false`; `instructions` is the borrower's own prompt and is kept. - **Borrowed requests never write the header snapshot.** The per-account identity snapshot is captured only from the lender's own Claude Code client. The borrower still receives the quota and grant headers their routing needs. ## Ordering A borrower's request falls through in this order: 1. Its own accounts, in the usual quota-aware order. 2. Peers, by priority — same models, same wire format, one extra hop. 3. The configured provider fallback chain (Gemini, OpenAI, …), which answers as a different model. A node with no accounts at all still borrows: peers are tried before the "no credentials" error is returned. A borrowed request is never forwarded on to another peer. Chaining a lend onto a lend would spend a third party's capacity under a grant that says nothing about them. ## Two levels of sharing Everything above describes **live** sharing: the borrower forwards each request through your proxy, so your gate is in the request path and your credentials never leave your device. It is the default and the right choice for most people. **Complete** sharing trades that for availability. The borrower holds its own credential on your account and calls the provider directly, so it keeps working when your laptop is shut. | | Live | Complete | | ---------------------------------- | ---------------------------- | -------------------------------------- | | Your credentials leave your device | No | Yes — a separate, independent grant | | Works while you are offline | No | Yes, until the lease's grace runs out | | Revocation | Instant, next request | Next heartbeat; grace period at worst | | Enforcement | Cryptographic | Cooperative, plus after-the-fact audit | | Extra latency | One hop | None | | You can see their prompts | Yes (never captured to disk) | No | ### Provisioning a complete share Provisioning is **split**: the borrower generates the PKCE verifier and you only authorize. You never hold a token for the credential you just minted, so there is nothing for you to leak, re-send, or forget to delete. **1. The borrower asks** (they must already have your share token added as a peer): ```bash neurolink proxy peer request --name alice ``` This generates a verifier locally, sends only its SHA-256 challenge over the authenticated grant, and keeps the verifier on their machine. **2. You authorize:** ```bash neurolink proxy share provision --peer bob \ --from-account you@example.com \ --offline-grace 24h --heartbeat 15m --lease-ttl 7d ``` It prints an authorization URL carrying _their_ challenge. Sign in, authorize, and paste the code back: ```bash neurolink proxy share provision --peer bob --code ``` **3. The borrower collects:** ```bash neurolink proxy peer request --name alice --claim neurolink proxy peer sync # force a check-in ``` They exchange the code with their own verifier, on their own machine, and the tokens land only there. The code is single-use and expires with the request (15 minutes). Intercepting it buys nothing: the token endpoint will not exchange a code without the verifier, and the verifier never crossed the wire. This does **not** copy your own tokens. Anthropic's OAuth refresh tokens rotate, so two devices on one refresh chain invalidate each other — and the loser gets disabled. That loser could be you. ### How control survives your device being off What the borrower collects carries a **lease**: a signed, time-boxed statement of consent that the borrower enforces on itself. - **`--heartbeat`** (default 15m) — how often the borrower checks in. A `pause` or `revoke` reaches them at the next one. - **`--offline-grace`** (default 24h) — how long they may keep working while you are unreachable. This is the headline trade-off: shorter means tighter control, longer means they survive your weekend. - **`--lease-ttl`** (default 7d) — a hard stop baked into the signature, binding even on a borrower that never calls home again. Set `--offline-grace 0` and complete mode has live mode's availability with none of its enforcement, which is rarely what anyone wants. ### Verifying what a borrower reports Reported spend is the borrower's word. The lender checks it against something the borrower cannot influence: the account's own utilization, which the provider reports. At each heartbeat the lender records the account's 5h/7d utilization alongside what the borrower claimed. When a window moved materially, **this node served none of that traffic**, and the borrower reported nothing, the interval is counted as drift. Three consecutive drifting check-ins pause the grant automatically. The check abstains whenever the movement is explainable — the lender used the account too, or the borrower did declare spend — because a false accusation costs someone their access. `share status` shows the verdict on every complete share: ``` audit consistent with the account's own usage audit drifting (2 consecutive) audit auto-paused on usage drift 2026-08-21T11:04:00.000Z ``` Auditing needs to know which of your accounts the share draws on, so pass `--from-account` at provision time. Without it the share still works, but reported spend is the only record of it. Resuming an auto-paused grant rearms the audit, so a grant that drifts again is paused again. ### What complete mode cannot promise A credential on someone else's machine can be extracted by them, and the token store is obfuscated rather than encrypted. A borrower who stops running the shipped software is not stopped by any of the above. What you keep is the honest path plus the audit above. It catches a borrower that stops reporting; it cannot catch one that reports honestly and simply spends what it was lent, and it says nothing about intervals you also used. Use complete sharing for people you would trust with the account itself. Use live sharing for everyone else. ### What the borrower enforces locally A complete-mode borrower applies the lease's own terms before using the credential, so a share scoped to Sonnet stays scoped to Sonnet even though the lender is not in the request path: - the lease's **hard expiry** and **offline grace**; - the **model allowlist** and **schedule** snapshotted into the lease; and - the **reserve floor** and **slice ceiling**, evaluated against the account's own quota figures. The last two run through the same evaluator the lender uses, rather than a borrower-side reimplementation that would drift the first time a gate was added. A resident credential is minted from exactly one account, so the pool-wide slice collapses to the per-account case and both sides read the same number. A refusal says which of those applied — an out-of-scope model tells the borrower to ask for a wider share, while a lapsed lease tells them to `peer sync`. Neither is reported as a credential problem, because sending someone to re-authenticate into a lender's account is advice that cannot work. ## Receipts Until a charge is settled, the lender's word is the only record of it. A receipt makes that checkable: the lender signs every settlement, and the statement carries the **usage it was computed from**, so a borrower recomputes the charge rather than accepting it. ```bash neurolink proxy peer receipts --name alice # borrower: collect and check neurolink proxy share receipts --peer bob # lender: what you charged ``` The borrower's check answers three separate questions, because they have three different causes: | Finding | Means | | ---------- | -------------------------------------------------------------------- | | Unverified | The receipt did not come from this lender's secret | | Miscounted | The coin figure disagrees with the receipt's own usage block | | Gap | A charge was never shown to you — sequences are contiguous per grant | The signing key is a per-grant **receipt secret**, minted with the grant and carried in the share link after the token (`#.`). It deliberately survives `share rotate`, so receipts issued under an old token stay checkable. A peer added by hand takes it with `--receipt-secret`; without one, charges are listed but nothing is verified, and the CLI says so. A receipt proves authorship only to the holder of the key — it settles a dispute between the two parties to it and is worth nothing to a third. That is the cost of an HMAC, and it is the same trade leases make. ## Reciprocal netting Two nodes that lend to each other otherwise run two one-way debts that never meet. Netting forgives the overlap: ```bash neurolink proxy peer net --name alice ``` If Bob has consumed 300 coins of Alice's and Alice has consumed 500 of Bob's, 300 cancels on both sides. Positions are stated as **cumulative totals**, never as a delta, so running it twice forgives nothing the second time rather than paying out again. When the two sides' records of what has already been forgiven disagree, the larger wins — forgiving less is the direction that cannot hand out coins twice. Netting needs a grant in each direction. `peer net` looks for a grant you issued labelled with the peer's own name; point it elsewhere with `--reciprocal `. ## Transferable coin notes A grant's coins are bound to the pair that agreed them. A note is not: it is a bearer credit against the issuing node, redeemable once by whoever holds it. ```bash neurolink proxy share note --coins 200 --ttl 30d # A mints neurolink proxy share notes # A lists what it minted neurolink proxy peer redeem --name alice --coin-note --check # C asks neurolink proxy peer redeem --name alice --coin-note # C spends ``` That is `A`-issued, `B`-held, `C`-redeemed: the note travels out of band, and whoever ends up with it redeems against A, into a grant A issued them. Marking spent and crediting happen under one lock, so two holders racing the same note produce exactly one credit and one `spent`. A holder cannot verify a note offline — it is signed with a secret only the issuer has — so `--check` asks the issuer instead. That step has to exist regardless of the signature scheme, because a valid signature says nothing about whether the note has already been spent. ## The share listener A proxy that lends anything runs **two** listeners: | Port | Who it is for | Untokened request | | ---------------------- | ----------------------- | ----------------- | | Main (`--port`) | Your own client | Served, as always | | Share (`--share-port`) | Peers, through a tunnel | Refused | It appears on its own the moment you issue the first grant and goes away when the last one is revoked — no restart on either edge — and `share create` tells you the port. Expose that one. The split exists because the gate refuses untokened requests and your own client sends none. An address check could not stand in for it: cloudflared and every reverse proxy connect from `127.0.0.1`, so tunnelled traffic is indistinguishable from local traffic by origin. The listener a connection was accepted on is not something a client can influence, which is why the decision is made there. ```bash neurolink proxy start --port 3000 # share listener lands on 3001 neurolink proxy start --share-port 8443 # or put it where you like NEUROLINK_PROXY_SHARE_LISTENER=0 neurolink proxy start # or not at all ``` `NEUROLINK_PROXY_REQUIRE_GRANT=1` still exists and now means something narrower: gate the **main** port as well. It is one of the three things that permit a non-loopback bind (the others are an inbound token and an explicit `--allow-unauthenticated`; see the Claude proxy guide's "Inbound authentication"). It refuses your own client too, which is what made it awkward in the first place — an inbound token is usually the better fit. ## Exposure Any address a borrower can reach works — a domain you already own behind nginx or Caddy, a permanent named tunnel, a VPN hostname, a plain DNS record. Nothing in the sharing path knows or cares how you got one. Record it once and every link is minted against it: ```bash neurolink proxy share url https://proxy.mycompany.com neurolink proxy share url # show the current one neurolink proxy share url get # bare value, exits non-zero if unset neurolink proxy share url --clear # forget it ``` Point that address at the **share port**, not the main one. `share url` also probes that address and warns if it answers a request carrying no share token — the check matters more when you front the proxy yourself, since nothing else in your stack knows the gate is supposed to be on. `neurolink proxy expose` is a convenience for people who have no address yet: it wraps `cloudflared`, picks the share listener automatically, and refuses to open a tunnel to a port that serves untokened requests. If you already have a domain, skip it entirely. ## Exposure with cloudflared `neurolink proxy expose` wraps `cloudflared`, and refuses to open a tunnel to a proxy that serves untokened requests — it checks by asking the proxy, not by reading configuration. `--force` overrides that, and should only be used when something in front of the tunnel already authenticates every request. Quick tunnels get a new URL on every restart, which rots every peer's configuration. Use a named tunnel (`--named `) for a peer you expect to keep. ## What an exposed proxy still reveals On the share listener — or on the main port with `NEUROLINK_PROXY_REQUIRE_GRANT=1` — `/v1/messages` and the Codex and OpenAI-compatible routes all require a share token. Two endpoints stay open on purpose, because a tunnel and a peer both need a liveness probe: - **`/health`** — status, readiness, version, uptime. No account data. - **`/status`** — counters, health and routing state, with **account identity redacted**: labels become `account-1`, `account-2`, and the primary-account block is blanked. A caller holding the update-control token sees the real values. A borrower's request reaches the same routes as yours, so image references are vetted for it too: on the OpenAI-compatible and Gemini routes (and on `/v1/messages` when a model is routed to another provider) a borrower can send `data:` URIs and public `https://` URLs, but a local path, an `http://` URL or any other scheme is refused with a `400` before anything is read or fetched. A borrower cannot make your proxy read a file on your disk or call a service on your network. A loopback allowlist would not have worked here: `cloudflared` runs on the same machine and connects to `127.0.0.1`, so tunnelled traffic arrives from loopback exactly like the operator's own CLI does. Separating the two by **listener** is what makes the distinction real. ## Files | Path | Owner | Contents | | -------------------------------------------- | -------- | ------------------------------------------------------------ | | `~/.neurolink/proxy-grants.json` | lender | Grants, hashed tokens, policy, state, this node's public URL | | `~/.neurolink/proxy-share-ledger.json` | lender | Coin spend and per-window buckets | | `~/.neurolink/proxy-share-audit.json` | lender | Drift observations, streak, auto-pause marker | | `~/.neurolink/proxy-share-provisioning.json` | lender | Outstanding split-PKCE challenges and single-use codes | | `~/.neurolink/proxy-peers.json` | borrower | Peers, tokens, priorities, cooldowns, pending verifier | | `~/.neurolink/proxy-resident-grants.json` | borrower | Leases governing credentials a lender provisioned here | | `~/.neurolink/proxy-share-receipts.json` | lender | Signed receipts per grant, and the cumulative netted total | | `~/.neurolink/proxy-share-notes.json` | issuer | Every coin note minted, and which have been redeemed | All eight are `0o600` and written by atomic rename. Field-level detail is in the [config reference](/docs/features/claude-proxy-config-reference). Tokens are stored **hashed** on the lender's side. The raw token exists once, in the output of `share create` — which is why `share link` cannot reprint one and tells you to rotate instead. ## Scope The gate covers every inbound proxy route, including the Codex and OpenAI-compatible surfaces. Account-level gates (reserve floor, window slice) and coin settlement are implemented for the Anthropic engine; a borrowed request on another engine is admitted or refused by the grant's request-level gates only. --- ## Per-query RAG retrieval planning # Per-query RAG retrieval planning `RAGPipeline.query()` has always resolved four knobs — `topK`, `hybrid`, `graph`, `rerank` — from config, with an optional per-call override on each. Nothing inspected the query itself: "what is the refund window?" (one precise passage, worth matching by an exact phrase) and "how does billing relate to entitlements?" (many passages, relationships across documents) got the same plan. `RAGPipelineConfig.decide` lets a [decision model](/docs/features/decide-inference-type) answer all four for the query in hand, in one request (~400ms on TypeSafe; on Perplexity each further question adds about 65 ms, up to 128, see [its guide](/docs/getting-started/providers/perplexity-decider.md#limits); on Cloudflare Clef a small request took 0.3 to 1.0 s on 2026-10-03, see [its guide](/docs/getting-started/providers/cloudflare-clef.md#latency-and-the-timeout)). **The degradation contract.** `config.decide` is optional and defaults to unset. Without it, `query()` behaves exactly as before — the configured defaults and any explicit `QueryOptions` are all that determine `topK`, `hybrid`, `graph` and `rerank`. Setting `plan: false` on a call skips planning for that one call even when `decide` is configured, without touching anything else. > ⚠️ **This is opt-in wiring, not automatic.** Per-query planning lives on > `RAGPipeline`. The `rag: { files }` shortcut on `generate()` / `stream()` does > not construct one, so that path keeps its fixed `topK`/`hybrid`/`graph`/ > `rerank` settings. To get planning you build the pipeline yourself and pass a > `decide` function, as below. ```typescript const nl = new NeuroLink(); const pipeline = new RAGPipeline({ enableHybridSearch: true, enableReranking: true, rerankingModel: "simple", decide: (options) => nl.decide(options), }); const response = await pipeline.query( "How does billing relate to entitlements across services?", ); // response.metadata.plan describes what the decision model suggested, // when it ran. ``` ## What gets asked One request always asks `breadth` — a `score` question rather than a raw number, because a decision model places a query on an ordered scale reliably and reads a digit string as text, not as a quantity to reason with: | Level | Criterion | topK multiplier | | ----- | ----------------------------------------------------------------------------------- | --------------- | | 0 | One specific fact, definition or value. A single passage answers it completely. | 0.5× | | 1 | A handful of related points — a procedure, a short comparison, one topic explained. | 1× | | 2 | Several distinct areas that each need their own supporting passage. | 1.5× | | 3 | A broad survey that needs evidence from across the whole corpus. | 2.5× | The multiplier is applied to the pipeline's own configured `defaultTopK` and clamped to between **1** and **50**. Below **0.5** confidence the breadth reading is dropped entirely and the configured `topK` stands untouched. `hybrid`, `graph` and `rerank` are each a plain boolean — and each is asked **only when the pipeline was actually configured with that capability**. Asking about a knob nobody can act on would cost input tokens for nothing and invite the mistake of acting on it anyway: - **hybrid**: "This question contains exact terms that must be matched literally — an identifier, error code, file name, version number, API name, or a quoted phrase — rather than only a topic to match by meaning." - **graph**: "Answering this requires connecting information that lives in separate documents, such as how two things relate, what depends on what, or tracing a chain across sources." - **rerank**: "This question is specific enough that the ORDER of the retrieved passages matters — a nearly-right passage would produce a wrong answer, so precision is worth an extra ranking pass." ## A deliberately lower bar than tool routing or compaction `hybrid`, `graph` and `rerank` are each read with the plain library default — 0.5 probability, 0.4 confidence — not the stricter 0.6 confidence override that [tool routing](/docs/features/tool-routing-decision-model) and [relevance compaction](/docs/features/relevance-compaction) both apply. This is a deliberate asymmetry, not an oversight: a wrong guess here is cheap (an extra ranking pass that didn't help, or a missed lexical match on an otherwise-fine semantic result), where a wrong guess on a dropped tool server or a dropped conversation message breaks the turn outright. The bar matches the cost of being wrong. ## Precedence: explicit always wins, capability is a hard ceiling ```ts if (plan) { if (options?.topK === undefined && plan.topK !== undefined) { topK = plan.topK; } if (options?.hybrid === undefined && plan.hybrid !== undefined) { useHybrid = plan.hybrid; } // ...graph, rerank follow the same pattern } ``` An explicit `QueryOptions` field always wins over the plan, per field — setting `hybrid: true` on one call while letting `topK` be planned works exactly as written. And the plan can never turn on a capability the pipeline itself was not configured with: `canHybrid`/`canGraph`/`canRerank` gate whether the question is even asked, so `graph: true` cannot appear in a plan for a pipeline with no graph index. This is the same "suggestion, not an override of capability" contract every other consumer of `decide` in this codebase follows. ## What this is bad at - **Breadth is a rubric, not a real answer-length estimate.** A level-3 reading multiplies `topK` by 2.5× regardless of how large the corpus actually is — for a small collection that can mean requesting more passages than exist. - **The three capability booleans don't interact.** `hybrid` and `rerank` are decided independently even though a rerank pass changes how much a lexical-match boost from hybrid search actually matters; there's no joint reasoning about the combination, only three separate yes/no answers. - **It only sees the query text.** It has no visibility into what's actually indexed, so "a broad survey that needs evidence from across the whole corpus" is judged from the question's phrasing alone, not from how much relevant material exists to survey. - **It shares the base model's general limits** — literal reading, no arithmetic, degraded accuracy under a noisy state — all described in [what `decide` is bad at](/docs/features/decide-inference-type#what-it-is-bad-at). - **No memory across queries.** Each call to `query()` is planned from scratch; a session that alternates between narrow and broad questions gets no benefit from what the previous plan decided. ## See also - [The `decide` inference type](/docs/features/decide-inference-type) - [Tool / MCP routing by decision model](/docs/features/tool-routing-decision-model) - [Relevance-driven compaction](/docs/features/relevance-compaction) --- ## RAG Document Processing Guide # RAG Document Processing Guide > **Since**: v8.44.0 | **Status**: Stable | **Availability**: SDK + CLI > **Provider Defaults:** When `--provider` (CLI) or `provider` (SDK) is not specified, NeuroLink defaults to **Vertex AI** with **gemini-2.5-flash** (see `src/lib/rag/ragIntegration.ts`). Set the `NEUROLINK_PROVIDER` or `AI_PROVIDER` environment variable to change the default provider, or pass an explicit `embeddingModel` / `generationModel` config. ## Overview NeuroLink provides enterprise-grade RAG (Retrieval-Augmented Generation) capabilities for building production AI applications: - **10 Chunking Strategies**: Character, recursive, sentence, token, markdown, HTML, JSON, LaTeX, semantic, and semantic-markdown chunking for any content type - **Hybrid Search**: Combine BM25 keyword search with vector embeddings using RRF or linear fusion - **Multi-Factor Reranking**: LLM, cross-encoder, Cohere API, and simple position-based reranking options - **Factory + Registry Patterns**: Extensible architecture with lazy loading, aliases, and full TypeScript support - **Resilience Built-In**: Circuit breakers, retry handlers, and comprehensive error handling ## Quick Start ### Basic Document Processing ```typescript // Load and chunk a document const doc = await loadDocument("/path/to/document.md"); const chunker = await createChunker("markdown", { maxSize: 1000, overlap: 100, }); const chunks = await chunker.chunk(doc.content); // Each chunk includes metadata console.log(chunks[0]); // { // id: "chunk-abc123", // text: "## Introduction\n\nThis document covers...", // metadata: { // documentId: "doc-xyz", // chunkIndex: 0, // startOffset: 0, // endOffset: 847 // } // } ``` ### Full RAG Pipeline ```typescript const pipeline = new RAGPipeline({ embeddingModel: { provider: "vertex", modelName: "gemini-3-flash-preview" }, generationModel: { provider: "vertex", modelName: "gemini-3-flash-preview" }, }); // Ingest documents await pipeline.ingest(["./docs/*.md", "./knowledge/**/*.txt"]); // Query with automatic retrieval and generation const response = await pipeline.query("What are the key features?"); console.log(response.answer); console.log(response.sources); // Retrieved chunks with citations ``` ## Integration with generate() and stream() The RAG system integrates seamlessly with NeuroLink's `generate()` and `stream()` APIs through the `createVectorQueryTool`. This allows AI models to automatically query your knowledge base during generation. ### Using RAG with generate() ```typescript NeuroLink, createVectorQueryTool, InMemoryVectorStore, } from "@juspay/neurolink"; // 1. Set up vector store with your data const vectorStore = new InMemoryVectorStore(); await vectorStore.upsert("knowledge-base", [ { id: "doc1", vector: embedding1, metadata: { text: "Your document content..." }, }, // ... more documents ]); // 2. Create the RAG tool const ragTool = createVectorQueryTool( { id: "knowledge-search", description: "Search the knowledge base for relevant information", indexName: "knowledge-base", embeddingModel: { provider: "vertex", modelName: "gemini-3-flash-preview" }, topK: 5, reranker: { model: { provider: "vertex", modelName: "gemini-3-flash-preview" }, topK: 3, }, }, vectorStore, ); // 3. Use with generate() const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "What are the key features of our product?" }, tools: { [ragTool.name]: ragTool }, provider: "vertex", model: "gemini-3-flash-preview", }); console.log(result.content); console.log(result.toolExecutions); // See RAG tool results ``` ### Using RAG with stream() ```typescript // Same setup as above, then: const result = await neurolink.stream({ input: { text: "Explain our pricing model in detail" }, tools: { [ragTool.name]: ragTool }, provider: "vertex", model: "gemini-3-flash-preview", }); for await (const chunk of result.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } ``` ### Complete RAG Pipeline Example This example demonstrates a full RAG pipeline from document loading to AI-powered retrieval: ```typescript NeuroLink, createVectorQueryTool, InMemoryVectorStore, } from "@juspay/neurolink"; loadDocument, createChunker, createMetadataExtractor, } from "@juspay/neurolink"; // Step 1: Load and chunk documents const doc = await loadDocument("./docs/product-guide.md"); const chunker = await createChunker("markdown", { maxSize: 1000, overlap: 100, preserveHeaders: true, }); const chunks = await chunker.chunk(doc.content); // Step 2: Extract metadata for better retrieval (optional) const extractor = await createMetadataExtractor("llm", { provider: "vertex", modelName: "gemini-3-flash-preview", }); const enrichedChunks = await extractor.extract(chunks, { summary: true, keywords: true, }); // Step 3: Generate embeddings using the NeuroLink provider const neurolink = new NeuroLink(); // Helper function to generate embeddings async function generateEmbeddings(texts: string[]): Promise { const embeddings: number[][] = []; for (const text of texts) { const result = await neurolink.generate({ input: { text }, provider: "vertex", model: "gemini-3-flash-preview", }); // Extract embedding from result (provider-specific) embeddings.push(result.embedding || []); } return embeddings; } const embeddings = await generateEmbeddings(enrichedChunks.map((c) => c.text)); // Step 4: Store in vector store const vectorStore = new InMemoryVectorStore(); await vectorStore.upsert( "product-docs", enrichedChunks.map((chunk, i) => ({ id: chunk.id, vector: embeddings[i], metadata: { text: chunk.text, summary: chunk.metadata.summary, keywords: chunk.metadata.keywords, source: "product-guide.md", }, })), ); // Step 5: Create RAG tool const ragTool = createVectorQueryTool( { id: "product-search", description: "Search product documentation for answers to user questions", indexName: "product-docs", embeddingModel: { provider: "vertex", modelName: "gemini-3-flash-preview" }, topK: 5, includeSources: true, reranker: { model: { provider: "vertex", modelName: "gemini-3-flash-preview" }, topK: 3, weights: { semantic: 0.6, vector: 0.3, position: 0.1 }, }, }, vectorStore, ); // Step 6: Use with generate() const response = await neurolink.generate({ input: { text: "How do I configure the billing settings?" }, tools: { [ragTool.name]: ragTool }, provider: "vertex", model: "gemini-3-flash-preview", systemPrompt: `You are a helpful product assistant. Use the product-search tool to find relevant information before answering questions. Always cite your sources.`, }); console.log("Answer:", response.content); console.log( "Sources used:", response.toolExecutions?.map((t) => t.result?.sources), ); ``` ### Configuration Options for createVectorQueryTool | Option | Type | Default | Description | | ----------------- | ----------------------------------------- | --------------------- | ------------------------------------------------------ | | `id` | `string` | `vector-query-{uuid}` | Unique identifier for the tool | | `description` | `string` | Default description | Description shown to AI for tool selection | | `indexName` | `string` | **Required** | Name of the index in the vector store | | `embeddingModel` | `{ provider: string, modelName: string }` | **Required** | Embedding model configuration | | `enableFilter` | `boolean` | `false` | Enable metadata filtering in queries | | `includeVectors` | `boolean` | `false` | Include raw vectors in results | | `includeSources` | `boolean` | `true` | Include source documents in response | | `topK` | `number` | `10` | Number of results to retrieve | | `reranker` | `RerankerConfig` | `undefined` | Optional reranker configuration | | `providerOptions` | `VectorProviderOptions` | `undefined` | Provider-specific options (Pinecone, pgVector, Chroma) | #### Reranker Configuration | Option | Type | Default | Description | | --------- | ----------------------------------------------------------- | ----------------------------------------------- | --------------------------------- | | `model` | `{ provider: string, modelName: string }` | **Required** | Model for semantic reranking | | `weights` | `{ semantic?: number, vector?: number, position?: number }` | `{ semantic: 0.5, vector: 0.3, position: 0.2 }` | Score weights (must sum to 1.0) | | `topK` | `number` | Same as tool `topK` | Results to return after reranking | ### Event Handling Listen for tool events during RAG operations to monitor and debug: ```typescript const neurolink = new NeuroLink(); // NeuroLink does not extend EventEmitter; events come from getEventEmitter() const emitter = neurolink.getEventEmitter(); // Listen for tool execution events emitter.on("tool:start", (event) => { console.log(`Tool started: ${event.toolName}`); console.log(`Parameters:`, event.parameters); }); emitter.on("tool:end", (event) => { console.log(`Tool completed: ${event.toolName}`); console.log(`Success: ${event.success}`); console.log(`Response time: ${event.responseTime}ms`); if (event.result) { console.log(`Results found: ${event.result.totalResults}`); } if (event.error) { console.error(`Error:`, event.error.message); } }); // Listen for generation events emitter.on("generation:start", (event) => { console.log(`Generation started with provider: ${event.provider}`); }); emitter.on("generation:end", (event) => { console.log(`Generation completed in ${event.responseTime}ms`); console.log(`Tools used: ${event.toolsUsed?.join(", ") || "none"}`); }); // Execute RAG query with event monitoring const result = await neurolink.generate({ input: { text: "What are the system requirements?" }, tools: { [ragTool.name]: ragTool }, provider: "vertex", model: "gemini-3-flash-preview", }); ``` ### Dynamic Vector Store Resolution For multi-tenant applications, you can provide a resolver function instead of a static vector store: ```typescript const ragTool = createVectorQueryTool( { id: "tenant-search", description: "Search tenant-specific knowledge base", indexName: "documents", embeddingModel: { provider: "vertex", modelName: "gemini-3-flash-preview" }, topK: 5, }, (context) => { // Return different vector stores based on request context const tenantId = context.tenantId || "default"; return getVectorStoreForTenant(tenantId); }, ); // The context is passed from generate options const result = await neurolink.generate({ input: { text: "Search query" }, tools: { [ragTool.name]: ragTool }, context: { tenantId: "tenant-123", userId: "user-456" }, }); ``` ### Metadata Filtering Enable metadata filtering for more precise retrieval: ```typescript const ragTool = createVectorQueryTool( { id: "filtered-search", description: "Search with metadata filters", indexName: "knowledge-base", embeddingModel: { provider: "vertex", modelName: "gemini-3-flash-preview" }, enableFilter: true, // Enable filter parameter topK: 10, }, vectorStore, ); // The AI can now use filters in its queries // Example filter syntax supported: // { category: 'billing' } - Exact match // { date: { $gte: '2024-01-01' } } - Comparison operators // { tags: { $in: ['feature', 'guide'] } } - Array membership // { $and: [{ type: 'doc' }, { status: 'published' }] } - Logical operators ``` ## Chunking Strategies NeuroLink provides 10 chunking strategies optimized for different content types. ### Available Strategies | Strategy | Best For | Key Config | | ------------------- | --------------------------- | -------------------------------------- | | `character` | Simple text, logs | `maxSize`, `separator` | | `recursive` | General documents (default) | `maxSize`, `overlap`, `separators` | | `sentence` | Natural language, Q&A | `maxSize`, `minSentences` | | `token` | LLM context optimization | `maxSize` (tokens), `tokenizer` | | `markdown` | Documentation, READMEs | `preserveHeaders`, `codeBlockHandling` | | `html` | Web content | `preserveTags`, `removeTags` | | `json` | API responses, config | `preserveStructure`, `flattenDepth` | | `latex` | Academic papers | `sectionCommands`, `preserveMath` | | `semantic` | Context-aware splitting | `similarityThreshold`, `embedder` | | `semantic-markdown` | Knowledge bases | `semanticThreshold`, `embedder` | ### Strategy Configuration ```typescript // List all available strategies const strategies = getAvailableStrategies(); // ['character', 'recursive', 'sentence', 'token', 'markdown', 'html', 'json', 'latex', 'semantic', 'semantic-markdown'] // Recursive chunker (recommended for general use) const recursiveChunker = await createChunker("recursive", { maxSize: 1000, overlap: 200, separators: ["\n\n", "\n", ". ", " ", ""], keepSeparator: true, }); // Markdown chunker (for documentation) const markdownChunker = await createChunker("markdown", { maxSize: 1000, overlap: 100, preserveHeaders: true, codeBlockHandling: "preserve", // 'preserve' | 'split' | 'remove' }); // Token chunker (for LLM optimization) const tokenChunker = await createChunker("token", { maxSize: 512, // Max tokens per chunk overlap: 50, // Token overlap tokenizer: "cl100k_base", // OpenAI tokenizer }); ``` ### Content-Type Recommendations ```typescript // Get strategy based on content type getRecommendedStrategy("text/markdown"); // 'markdown' getRecommendedStrategy("text/html"); // 'html' getRecommendedStrategy("application/json"); // 'json' getRecommendedStrategy("text/x-latex"); // 'latex' getRecommendedStrategy("text/plain"); // 'recursive' ``` ## Hybrid Search Hybrid search combines BM25 keyword matching with vector similarity for improved retrieval quality. ### How It Works 1. **BM25 Search**: Traditional keyword matching using term frequency and document length normalization 2. **Vector Search**: Semantic similarity using embeddings 3. **Score Fusion**: Combine rankings using RRF or linear combination ### Fusion Methods #### Reciprocal Rank Fusion (RRF) RRF is robust to score scale differences and works well in most cases: ```typescript // Combine rankings from multiple sources const fusedScores = reciprocalRankFusion( [vectorRankings, bm25Rankings], 60, // k parameter (default: 60) ); // RRF formula: score(d) = sum(1 / (k + rank(d))) ``` #### Linear Combination Linear combination allows fine-tuning the balance between vector and keyword scores: ```typescript const combinedScores = linearCombination( vectorScores, // Map bm25Scores, // Map 0.5, // alpha: weight for vector scores (0-1) ); // Linear formula: score(d) = alpha * vectorScore(d) + (1 - alpha) * bm25Score(d) ``` ### Hybrid Search Pipeline ```typescript createHybridSearch, InMemoryBM25Index, InMemoryVectorStore, } from "@juspay/neurolink"; // Create indices const bm25Index = new InMemoryBM25Index({ k1: 1.2, b: 0.75 }); const vectorStore = new InMemoryVectorStore(); // Add documents to both indices const documents = [ { id: "doc1", text: "Machine learning fundamentals...", metadata: { topic: "ml" }, }, { id: "doc2", text: "Deep learning architectures...", metadata: { topic: "dl" }, }, ]; await bm25Index.addDocuments(documents); await vectorStore.addDocuments(documents); // Create hybrid search const hybridSearch = createHybridSearch({ bm25Index, vectorStore, fusionMethod: "rrf", // 'rrf' | 'linear' alpha: 0.5, // Vector weight (for linear fusion) k: 60, // RRF parameter }); // Execute search const results = await hybridSearch.search("neural network training", { topK: 10, filter: { topic: "ml" }, }); ``` ### BM25 Configuration ```typescript type BM25Config = { k1: number; // Term frequency saturation (default: 1.2) b: number; // Document length normalization (default: 0.75) lowercase: boolean; // Normalize to lowercase (default: true) stemming: boolean; // Apply stemming (default: false) stopwords: string[]; // Words to ignore (default: English stopwords) }; ``` ## Reranking Reranking re-scores initial search results for improved relevance. ### Available Reranker Types | Type | Description | Requires Model | Best For | | --------------- | ----------------------------------- | -------------- | ------------------------ | | `simple` | Position + vector score combination | No | Fast, cost-free baseline | | `llm` | LLM semantic relevance scoring | Yes | High-quality semantic | | `cross-encoder` | Cross-encoder model scoring | Yes | Accuracy-focused tasks | | `cohere` | Cohere Rerank API | API Key | Production-grade results | | `batch` | Batch LLM processing | Yes | Large result sets | ### Reranker Configuration ```typescript // List available types const types = getAvailableRerankerTypes(); // ['simple', 'llm', 'cross-encoder', 'cohere', 'batch'] // Simple reranker (no model required) const simpleReranker = await createReranker("simple", { topK: 10, positionWeight: 0.3, scoreWeight: 0.7, }); // LLM reranker (requires model) const llmReranker = await createReranker("llm", { topK: 5, model: "gemini-3-flash-preview", temperature: 0.0, batchSize: 5, }); // Cohere reranker (requires API key) const cohereReranker = await createReranker("cohere", { topK: 10, model: "rerank-v3.5", maxChunksPerDoc: 10, }); // Rerank results const reranked = await simpleReranker.rerank(searchResults, query, { topK: 5 }); ``` ### Batch Reranking for Large Sets ```typescript // Process large result sets efficiently const reranked = await batchRerank(searchResults, query, { batchSize: 10, parallelBatches: 3, model: "gemini-3-flash-preview", topK: 20, }); ``` ## Metadata Extraction Extract structured metadata from chunks using LLMs. ### Extraction Types | Type | Description | Output | | ----------- | ------------------------- | ------------------------- | | `title` | Document/section title | `string` | | `summary` | Brief content summary | `string` | | `keywords` | Relevant keywords | `string[]` | | `questions` | Q&A pairs for the content | `{question, answer}[]` | | `custom` | Custom schema extraction | `Record` | ### Usage ```typescript createMetadataExtractor, extractMetadata, LLMMetadataExtractor, } from "@juspay/neurolink"; // Using factory const extractor = await createMetadataExtractor("llm", { provider: "vertex", modelName: "gemini-3-flash-preview", }); // Extract metadata from chunks const results = await extractor.extract(chunks, { title: true, summary: true, keywords: true, questions: { maxQuestions: 3 }, }); // Results include extracted metadata per chunk console.log(results[0]); // { // title: "Introduction to Machine Learning", // summary: "This section covers the fundamentals...", // keywords: ["machine learning", "supervised learning", "classification"], // questions: [ // { question: "What is supervised learning?", answer: "..." } // ] // } ``` ## Configuration Reference ### Chunker Configuration | Option | Type | Default | Description | | ------------ | ------------------------- | --------- | ---------------------------------- | | `maxSize` | `number` | `1000` | Maximum chunk size (chars/tokens) | | `overlap` | `number` | `200` | Overlap between chunks | | `minSize` | `number` | `50` | Minimum chunk size | | `documentId` | `string` | auto-UUID | Document identifier for metadata | | `metadata` | `Record` | `{}` | Additional metadata for all chunks | ### Reranker Configuration | Option | Type | Default | Description | | ----------------------- | --------- | ------- | ------------------------------- | | `topK` | `number` | `10` | Number of top results to return | | `minScore` | `number` | `0.0` | Minimum score threshold | | `includeOriginalScores` | `boolean` | `false` | Include original scores | ### Hybrid Search Configuration | Option | Type | Default | Description | | -------------- | ------------------- | ------- | --------------------------- | | `fusionMethod` | `'rrf' \| 'linear'` | `'rrf'` | Score fusion method | | `alpha` | `number` | `0.5` | Vector weight (linear only) | | `k` | `number` | `60` | RRF k parameter | | `topK` | `number` | `10` | Results to return | ### Environment Variables | Variable | Description | Required | | -------------------------------- | ----------------------------------------- | -------- | | `GOOGLE_APPLICATION_CREDENTIALS` | For Vertex AI (service account JSON path) | Yes | | `OPENAI_API_KEY` | For OpenAI provider | Optional | | `COHERE_API_KEY` | For Cohere reranker | Optional | | `ANTHROPIC_API_KEY` | For Claude-based reranking | Optional | ## Advanced Usage ### Integration with Observability Track RAG operations with Langfuse for debugging and optimization: ```typescript const pipeline = new RAGPipeline(config); await setLangfuseContext( { userId: "user-123", sessionId: "session-456", operationName: "rag-query", metadata: { pipeline: "customer-support", chunkingStrategy: "markdown", }, }, async () => { const response = await pipeline.query("How do I reset my password?"); return response; }, ); ``` ### Integration with Guardrails Validate RAG inputs and outputs with guardrails: ```typescript createGuardrail, validateInput, validateOutput, } from "@juspay/neurolink"; // Create guardrails for RAG const inputGuardrail = createGuardrail({ type: "input", rules: [ { type: "maxLength", value: 1000 }, { type: "noPersonalInfo", enabled: true }, ], }); const outputGuardrail = createGuardrail({ type: "output", rules: [ { type: "factualOnly", enabled: true }, { type: "noPII", enabled: true }, ], }); // Apply guardrails to RAG pipeline const validatedQuery = await validateInput(inputGuardrail, query); const response = await pipeline.query(validatedQuery); const validatedResponse = await validateOutput( outputGuardrail, response.answer, ); ``` ### Custom Chunker Registration Extend the chunker registry with custom implementations: ```typescript // Define custom chunker class CustomChunker implements Chunker { constructor(private config?: ChunkerConfig) {} async chunk(text: string, options?: ChunkerConfig) { // Custom chunking logic const maxSize = options?.maxSize ?? this.config?.maxSize ?? 500; // ... implementation } } // Register with the registry ChunkerRegistry.register("custom", CustomChunker, { name: "Custom Chunker", description: "My custom chunking strategy", aliases: ["my-chunker"], defaultConfig: { maxSize: 500 }, }); // Now use it const chunker = await createChunker("custom", { maxSize: 800 }); ``` ### Graph RAG Use knowledge graphs for relationship-aware retrieval: ```typescript // Create graph with similarity threshold for edge creation const graphRag = new GraphRAG({ dimension: 1536, // Embedding dimension threshold: 0.7, // Similarity threshold for creating edges }); // Build graph from chunks and their embeddings const chunks = [ { text: "Machine learning basics", metadata: { topic: "ml" } }, { text: "Neural networks", metadata: { topic: "dl" } }, ]; const embeddings = [ { vector: [0.1, 0.2 /* ... */] }, { vector: [0.15, 0.25 /* ... */] }, ]; graphRag.createGraph(chunks, embeddings); // Or add nodes incrementally const nodeId = graphRag.addNode( { text: "Deep learning", metadata: { topic: "dl" } }, { vector: [0.12, 0.22 /* ... */] }, ); // Query with embedding vector using random walk with restart const results = graphRag.query({ query: queryEmbedding, // Query embedding vector topK: 10, randomWalkSteps: 100, restartProb: 0.15, }); // Get graph statistics const stats = graphRag.getStats(); // { nodeCount: 3, edgeCount: 4, avgDegree: 1.33, threshold: 0.7 } ``` ### Resilience Patterns Use circuit breakers and retry handlers for production reliability: ```typescript // Circuit breaker for external API calls const breaker = new RAGCircuitBreaker("reranker-api", { failureThreshold: 5, resetTimeout: 60000, halfOpenMaxCalls: 3, operationTimeout: 30000, }); // Wrap reranker calls const result = await breaker.execute(async () => { return await cohereReranker.rerank(results, query); }, "rerank"); // Listen to circuit breaker events breaker.on("stateChange", ({ oldState, newState, reason }) => { console.log(`Circuit breaker: ${oldState} -> ${newState} (${reason})`); }); // Retry handler with exponential backoff const retryHandler = new RAGRetryHandler({ maxRetries: 3, initialDelay: 1000, maxDelay: 30000, backoffMultiplier: 2, jitter: true, }); const chunks = await retryHandler.executeWithRetry(async () => { return await chunker.chunk(largeDocument); }); ``` ## CLI Usage NeuroLink CLI provides commands for RAG operations. ### Document Processing ```bash # Chunk a document neurolink rag chunk ./document.md --strategy markdown --max-size 1000 --overlap 100 # Chunk with output to file neurolink rag chunk ./document.md -s recursive --format json --output chunks.json # Process multiple documents (use shell loop) for file in ./docs/*.md; do neurolink rag chunk "$file" --strategy markdown --format json; done ``` ### Index Management ```bash # Build an index from a document neurolink rag index ./docs/guide.md --indexName my-docs --provider vertex --model gemini-3-flash-preview # Query an existing index neurolink rag query "What are the main features?" --indexName my-docs --topK 5 --provider vertex --model gemini-3-flash-preview # Index with Graph RAG enabled neurolink rag index ./docs/guide.md --indexName my-docs --graph --provider vertex --model gemini-3-flash-preview ``` ## Simplified RAG API (`rag: { files }`) > **Security:** `rag.files` paths are read under the instance's > `attachments.allowedRoots` (a path outside them is skipped with a warning), > each file is capped at 50 MiB, and `WebLoader` fetches only HTTPS public > hosts unless its `attachmentPolicy` says otherwise. See > [Attachment Security](/docs/features/attachment-security). > **Since**: v9.2.0 | **Recommended** for most use cases Instead of manually creating chunkers, vector stores, and tools, pass `rag: { files }` directly to `generate()` or `stream()`. NeuroLink handles the entire pipeline automatically. ### SDK Usage ```typescript const neurolink = new NeuroLink(); // Generate with RAG - just pass files const result = await neurolink.generate({ input: { text: "What are the key features described in the docs?" }, rag: { files: ["./docs/guide.md", "./docs/api.md"], strategy: "markdown", // Optional: auto-detected from file extension chunkSize: 512, // Optional: default 1000 chunkOverlap: 50, // Optional: default 200 topK: 5, // Optional: default 5 }, }); // Stream with RAG - identical API const streamResult = await neurolink.stream({ input: { text: "Summarize the architecture" }, rag: { files: ["./docs/architecture.md"] }, }); for await (const chunk of streamResult.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } ``` ### CLI Usage ```bash # Basic RAG with generate neurolink generate "What is this about?" --rag-files ./docs/guide.md # RAG with custom chunking strategy neurolink generate "Explain the API" --rag-files ./docs/guide.md --rag-strategy markdown --rag-chunk-size 512 # RAG with streaming and multiple files neurolink stream "Summarize everything" --rag-files ./docs/a.md ./docs/b.md --rag-top-k 10 ``` ### CLI Flags Reference | Flag | Type | Default | Description | | --------------------- | ---------- | ------------- | ------------------------------------------------------------------------------------------------------------------- | | `--rag-files` | `string[]` | - | File paths to load for RAG context | | `--rag-strategy` | `string` | auto-detected | Chunking strategy (character, recursive, sentence, token, markdown, html, json, latex, semantic, semantic-markdown) | | `--rag-chunk-size` | `number` | 1000 | Maximum chunk size in characters | | `--rag-chunk-overlap` | `number` | 200 | Overlap between adjacent chunks | | `--rag-top-k` | `number` | 5 | Number of top results to retrieve | ### RAGConfig Type ```typescript type RAGConfig = { files: string[]; // Required: file paths to load strategy?: ChunkingStrategy; // Default: auto-detected from file extension chunkSize?: number; // Default: 1000 chunkOverlap?: number; // Default: 200 topK?: number; // Default: 5 toolName?: string; // Default: "search_knowledge_base" toolDescription?: string; // Custom tool description embeddingProvider?: string; // Defaults to generation provider embeddingModel?: string; // Defaults to provider's default }; ``` ### How It Works 1. Files are loaded from disk and auto-detected for chunking strategy (`.md` -> markdown, `.html` -> html, `.json` -> json, etc.) 2. Content is chunked using the selected strategy with configurable size and overlap 3. Chunks are embedded using a simple character-frequency hash (128 dimensions) and stored in an in-memory vector store 4. A `search_knowledge_base` tool is created and injected into the AI model's available tools 5. A system prompt instructs the AI to use the search tool before answering 6. The AI autonomously decides when to search the knowledge base during generation/streaming ### Auto-Detected Strategies by Extension | Extension | Strategy | | ---------------------------------------------------------------------------------------- | --------- | | `.md`, `.mdx` | markdown | | `.html`, `.htm` | html | | `.json` | json | | `.tex`, `.latex` | latex | | `.txt`, `.csv`, `.xml`, `.yaml`, `.yml` | recursive | | `.ts`, `.js`, `.py`, `.java`, `.go`, `.rs`, `.c`, `.cpp`, `.rb`, `.php`, `.swift`, `.kt` | recursive | ## Best Practices ### Chunking 1. **Match chunk size to model context** - Use token chunker when optimizing for specific LLM context windows 2. **Choose strategy by content type** - Markdown for docs, HTML for web content, JSON for structured data 3. **Use 10-20% overlap** - Prevents context loss at chunk boundaries 4. **Preserve structure when possible** - Format-aware chunkers maintain semantic coherence 5. **Test with your data** - Optimal settings vary by domain and use case ### Reranking 1. **Start with simple reranker** - Fast, free, and often sufficient for basic use cases 2. **Use LLM reranking for quality** - When accuracy matters more than latency 3. **Batch large result sets** - Use batch reranker for 50+ results 4. **Consider cost** - API-based rerankers (Cohere) have per-call costs 5. **Cache reranking results** - Results for the same query/docs can be reused ### Hybrid Search 1. **Start with RRF** - Robust to score scale differences, less tuning needed 2. **Tune alpha for linear fusion** - Start at 0.5, adjust based on evaluation 3. **Keep indices in sync** - Update both BM25 and vector indices together 4. **Filter early** - Apply metadata filters before fusion when possible 5. **Monitor retrieval quality** - Track precision/recall metrics in production ## Troubleshooting | Problem | Solution | | ----------------------------- | ------------------------------------------------------------------------ | | Empty chunks returned | Check if `maxSize` is too small for your content; try increasing to 500+ | | Duplicate content in chunks | Reduce `overlap` parameter or use a structure-aware chunker | | Missing context at boundaries | Increase `overlap` to 15-20% of `maxSize` | | Slow reranking performance | Switch to `simple` reranker or reduce `topK` before reranking | | Poor search quality | Tune BM25 parameters (`k1`, `b`) or adjust fusion `alpha` weight | | Out of memory with large docs | Process documents in batches; use streaming where available | | Reranker API timeouts | Use `CircuitBreaker` wrapper; reduce batch size | | Inconsistent chunk metadata | Ensure `documentId` is set consistently across processing runs | ### Debug Logging ```bash # Enable verbose logging for RAG operations DEBUG=neurolink:rag:* pnpm exec tsx your-script.ts # Log specific components DEBUG=neurolink:rag:chunker pnpm exec tsx your-script.ts DEBUG=neurolink:rag:reranker pnpm exec tsx your-script.ts DEBUG=neurolink:rag:hybrid pnpm exec tsx your-script.ts ``` ## API Reference ### Core Exports **Document Processing:** - `loadDocument(path)` - Load a single document - `loadDocuments(paths)` - Load multiple documents - `MDocument` - Fluent document processing class - `processDocument(text, options)` - Process text through chunking and metadata extraction **Chunking:** - `createChunker(strategy, config)` - Create a chunker instance - `ChunkerFactory` - Factory for chunker creation - `ChunkerRegistry` - Registry with all chunker implementations - `getAvailableStrategies()` - List available chunking strategies - `getRecommendedStrategy(contentType)` - Get recommended strategy for content type **Reranking:** - `createReranker(type, config)` - Create a reranker instance - `RerankerFactory` - Factory for reranker creation - `RerankerRegistry` - Registry with all reranker implementations - `getAvailableRerankerTypes()` - List available reranker types - `rerank(results, query, model)` - Direct reranking function - `batchRerank(results, query, options)` - Batch reranking **Retrieval:** - `createHybridSearch(config)` - Create hybrid search instance - `InMemoryBM25Index` - In-memory BM25 index - `InMemoryVectorStore` - In-memory vector store - `reciprocalRankFusion(rankings, k)` - RRF score fusion - `linearCombination(vectorScores, bm25Scores, alpha)` - Linear score fusion - `createVectorQueryTool(vectorStore, options)` - Create vector query tool **Metadata:** - `createMetadataExtractor(type, config)` - Create metadata extractor - `LLMMetadataExtractor` - LLM-powered extractor class - `extractMetadata(chunks, params)` - Extract metadata from chunks **Pipeline:** - `RAGPipeline` - Full RAG pipeline class - `createRAGPipeline(config)` - Create pipeline instance - `assembleContext(chunks, options)` - Assemble context from chunks - `formatContextWithCitations(chunks, format)` - Format with citations **Resilience:** - `RAGCircuitBreaker` - Circuit breaker pattern for RAG operations - `RAGRetryHandler` - Retry with exponential backoff and jitter **Types:** - `Chunk`, `ChunkMetadata`, `ChunkerConfig` - `Reranker`, `RerankerConfig`, `RerankerType` - `HybridSearchOptions`, `BM25Config` - `RAGPipelineConfig`, `RAGResponse` - `MetadataExtractor`, `MetadataExtractorConfig` ## See Also - [RAG Configuration Guide](/docs/rag/configuration) - Detailed configuration reference - [RAG Testing Guide](/docs/rag/testing) - Testing RAG pipelines - [Observability Guide](/docs/observability/health-monitoring) - Tracing and monitoring - [Guardrails Guide](/docs/features/guardrails) - Input/output validation - [Vector Store Integrations](/docs/guides/vector-stores) - Production vector stores --- ## Real-time Voice Services NeuroLink integrates the two major realtime voice APIs behind a single, provider-agnostic interface: **OpenAI Realtime** (`openai-realtime`) and **Google Gemini Live** (`gemini-live`). These let you build full-duplex voice agents where audio streams in and out simultaneously, with the model responding mid-utterance and calling tools in-flight. Realtime voice is exposed through the `RealtimeProcessor` static class (not a method on the `NeuroLink` instance). For non-realtime synthesis and transcription, see the **[TTS Guide](/docs/features/tts)** and **[STT Guide](/docs/features/audio-input)**. ----------- | ------------------------------- | ------------------------------- | | Provider value | `"openai-realtime"` | `"gemini-live"` | | Transport | WebSocket | WebSocket / WebRTC | | Modalities | audio in/out, text in/out | audio in/out, text, video | | Tool calls | Yes (via `onFunctionCall`) | Yes (via `onFunctionCall`) | | Interruption | Server-side VAD + manual cancel | Native barge-in + manual cancel | Both APIs support concurrent audio input and output streams, so the user can interrupt the model mid-response and the model can stream audio while still listening for new input. --- ## Quick Start (SDK) The `RealtimeProcessor` is a static class — there is no `new RealtimeProcessor()` and no `neurolink.openRealtimeSession(...)` method. Connect with `RealtimeProcessor.connect(provider, config, handlers)`: ```typescript // OpenAI Realtime const session = await RealtimeProcessor.connect( "openai-realtime", { provider: "openai-realtime", model: "gpt-4o-realtime-preview", voice: "alloy", instructions: "You are a helpful voice assistant.", }, { onAudio: (chunk) => speaker.write(chunk.audio), onTranscript: (text, isFinal) => { if (isFinal) console.log("User said:", text); }, onError: (err) => console.error(err), }, ); // Send audio chunks (PCM16 mono 24kHz, raw Buffer or RealtimeAudioChunk) await RealtimeProcessor.sendAudio("openai-realtime", audioChunk); // Send text input alongside audio await RealtimeProcessor.sendText("openai-realtime", "What's the weather?"); // Manually request a model response (for manual turn detection) await RealtimeProcessor.triggerResponse("openai-realtime"); // Cancel an in-progress response (barge-in) await RealtimeProcessor.cancelResponse("openai-realtime"); // Close the session await RealtimeProcessor.disconnect("openai-realtime"); ``` ```typescript // Gemini Live — same handler shape, just a different provider value const session = await RealtimeProcessor.connect( "gemini-live", { provider: "gemini-live", model: "gemini-2.0-flash-live", instructions: "Speak naturally and ask follow-up questions.", }, { onAudio, onTranscript, onError }, ); ``` The handler shape is provider-agnostic: the same `RealtimeEventHandlers` object works across both providers, so you can switch with a single string change. ### Event handler reference ```typescript type RealtimeEventHandlers = { onAudio?: (chunk: RealtimeAudioChunk) => void; onTranscript?: (text: string, isFinal: boolean) => void; onText?: (text: string, isFinal: boolean) => void; onFunctionCall?: ( name: string, args: Record, ) => Promise; onStateChange?: (state: RealtimeSessionState) => void; onError?: (error: Error) => void; onTurnStart?: () => void; onTurnEnd?: () => void; }; ``` --- ## Quick Start (CLI) NeuroLink does not ship a `neurolink voice realtime` interactive CLI. Instead, the realtime voice **server** is exposed via: ```bash # Canonical: start the realtime voice WebSocket server npx @juspay/neurolink serve voice --port 8081 # Deprecated alias (still works, prints a deprecation notice) npx @juspay/neurolink voice-server --port 8081 ``` Connect a browser/mobile client to `ws://localhost:8081/voice` to drive the session. The server bridges the client to the chosen provider (configured via env vars and per-session messages) and forwards events bidirectionally. The TTS and STT _flags_ on `generate` / `stream` (e.g. `--tts`, `--stt`, `--input-audio`) are for non-realtime synthesis and transcription — see [TTS](/docs/features/tts) and [STT](/docs/features/audio-input). --- ## Self-hosted Realtime Voice Server For multi-tenant deployments — voice bots, IVR-style applications, in-app voice features — NeuroLink ships a real-time voice agent server. It bridges browser/mobile clients to provider realtime APIs with session management, observability, and tool routing. ```bash npx @juspay/neurolink serve voice --port 8081 ``` > **Note:** the server is launched from the CLI, as in Quick Start (CLI) above. `startVoiceServer`, the function behind that command, is internal: it is a function rather than a `NeuroLinkVoiceServer` class, and the package does not export it, so there is no supported import path for starting it from code. The server emits OTEL spans + Langfuse traces per session, supports HITL approvals on tool calls, and can be deployed standalone or behind your own gateway. --- ## Provider Selection | Use case | Recommended provider | | --------------------------------------------------------- | ----------------------------------------------------- | | English-first, broad voice catalog, GPT-4o reasoning | `openai-realtime` | | Multilingual, video input, lowest latency in many regions | `gemini-live` | | Customer support voice bots with structured tool calls | `openai-realtime` (more deterministic function calls) | | In-app voice search / multimodal queries | `gemini-live` | Either can be wrapped behind `providerFallback` so a model-access denial automatically falls through to the alternate model. See [Provider Fallback](/docs/features/provider-fallback) — note that the orchestrator only triggers on access-denied errors, not on rate limits or generic failures. --- ## Tool Calls Inside Realtime Sessions Both providers can call functions registered with the realtime session. Use the `onFunctionCall` handler (not `onToolCall` — that name is reserved for the streaming-text API): ```typescript const session = await RealtimeProcessor.connect( "openai-realtime", { provider: "openai-realtime", model: "gpt-4o-realtime-preview", tools: [ { name: "lookupOrderStatus", description: "Look up the status of an order", parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"], }, }, ], }, { onFunctionCall: async (name, args) => { if (name === "lookupOrderStatus") { const order = await db.findOrder(args.id as string); return { status: order.status, eta: order.eta }; } }, }, ); ``` When [HITL](/docs/features/hitl) middleware is wired in front of the function-call handler, sensitive operations (e.g. `cancelOrder`, `chargeCard`) pause for human approval before responding back into the realtime stream. --- ## Observability Realtime sessions emit: - `session:start`, `session:end` events with duration + token usage - Per-utterance `transcript:user`, `transcript:assistant` events - `tool:call`, `tool:result` events - `audio:in:bytes`, `audio:out:bytes` for bandwidth tracking These flow into the same OTEL/Langfuse pipeline as text generation. See the [Observability Guide](/docs/observability/health-monitoring). --- ## Status & Inspection ```typescript RealtimeProcessor.isConnected("openai-realtime"); // boolean RealtimeProcessor.getProviders(); // string[] of registered providers RealtimeProcessor.supports("openai-realtime"); // boolean RealtimeProcessor.getSession("openai-realtime"); // RealtimeSession | null RealtimeProcessor.getSupportedFormats("openai-realtime"); // TTSAudioFormat[] ``` --- ## Related - **[TTS Guide](/docs/features/tts)** — non-realtime text-to-speech (6 providers) - **[STT Guide](/docs/features/audio-input)** — transcription (4 providers) - **[Voice Agent Guide](/docs/features/voice-agent)** — building voice agents end-to-end - **[Provider Fallback](/docs/features/provider-fallback)** — failover between models on access denial - **[Observability](/docs/observability/health-monitoring)** — wiring fallback events into your monitoring stack --- ## Regional Streaming Controls # Regional Streaming Controls Latency, compliance, and model availability often depend on which region you call. NeuroLink threads the `region` parameter through the generate/stream stack so you can target specific data centres when working with providers that expose regional endpoints. ## Quick Start ```typescript const neurolink = new NeuroLink(); const result = await neurolink.stream({ input: { text: "Summarise EMEA incident reports" }, provider: "bedrock", model: "anthropic.claude-sonnet-4-6", region: "eu-central-1", }); for await (const chunk of result.stream) { process.stdout.write(chunk); } ``` ## Supported Providers | Provider | How to Set Region | Defaults | | ------------------------ | -------------------------------------------------------------------------- | ----------- | | **Amazon Bedrock** | `AWS_REGION` env, `config init`, or request `region` option | `us-east-1` | | **Amazon SageMaker** | `SAGEMAKER_DEFAULT_ENDPOINT` + `AWS_REGION` or request `region` | `us-east-1` | | **Google Vertex AI** | `GOOGLE_VERTEX_LOCATION` / `config init` / request `region` | `us-east5` | | **Azure OpenAI** | Deployment-specific endpoint; use `AZURE_OPENAI_ENDPOINT` (region encoded) | — | | **LiteLLM pass-through** | Use LiteLLM server configuration | — | Providers without native region controls ignore the option safely. ## CLI Usage The CLI reads region information from configuration profiles or provider environment variables. ```bash # Bedrock: ensure AWS credentials + region set export AWS_REGION=ap-south-1 npx @juspay/neurolink generate "Translate catalog" --provider bedrock # Vertex AI: switch to Tokyo region for lower latency export GOOGLE_VERTEX_LOCATION=asia-northeast1 npx @juspay/neurolink stream "Localise onboarding" --provider vertex --model gemini-2.5-pro # One-off override via shell env AWS_REGION=eu-west-1 npx @juspay/neurolink stream "Summarise EMEA incidents" --provider bedrock ``` Run `neurolink config init` to persist region defaults per provider. ## SDK Usage ```typescript const neurolink = new NeuroLink({ enableOrchestration: true }); const result = await neurolink.generate({ input: { text: "Compile regional latency metrics" }, provider: "vertex", model: "gemini-2.5-pro", region: "europe-west4", enableEvaluation: true, }); console.log(result.content, result.provider); ``` Streaming obeys the same option: ```typescript const stream = await neurolink.stream({ input: { text: "Narrate service availability" }, provider: "bedrock", model: "anthropic.claude-sonnet-4-6", region: "eu-central-1", }); ``` ## Operational Tips :::tip[Compliance & Data Residency] Use regional routing to comply with data sovereignty requirements (GDPR, HIPAA, etc.). Pin the `region` parameter to ensure AI processing stays within approved geographical boundaries for sensitive workloads. ::: :::tip[Latency Optimization] Co-locate your NeuroLink deployment with your application servers. For example, if your API runs in `eu-west-1`, set `region: "eu-west-1"` for Bedrock/Vertex calls to minimize cross-region latency penalties. ::: - **Compliance** – ensure the requested region is enabled for the model (e.g., Anthropic via Vertex only supports `us` regions). - **Latency** – co-locate with your application servers to avoid cross-region penalties. - **Fallbacks** – when orchestration re-routes to a provider that ignores `region`, the call completes but logs a warning. - **Credentials** – AWS requests still require valid IAM credentials; Vertex needs service account rights in the target location. ## Troubleshooting | Symptom | Fix | | -------------------------------------- | -------------------------------------------------------------------------- | | `Invalid region format` | Use standard IDs (`us-east-1`, `asia-northeast1`). | | `Model not available in region` | Switch to a supported region or change model (see provider console). | | `Credential error after region change` | Re-run `neurolink config init` so stored credentials match the new region. | | `High latency on fallback provider` | Disable orchestration or pin a provider/model explicitly. | ## Related Material - [SageMaker Integration Guide](/docs/getting-started/providers/sagemaker) - [Enterprise Proxy Setup](/docs/deployment/enterprise-proxy) - [Dynamic Models Guide](/docs/guides/dynamic-models) --- ## Relevance-driven compaction # Relevance-driven compaction Every stage of context compaction has always been positional: pruning protects the most recent tokens, truncation drops the oldest half, summarization keeps a trailing ratio. None of that has any notion of what the current request is actually about, so a fifty-turn conversation that ends with "now rename that variable" keeps forty turns about database migrations and drops nothing that matters less. Stage 0 asks a [decision model](/docs/features/decide-inference-type) directly: "is this message needed to answer the current request?" — once per eligible message, in a single batched round trip. **The degradation contract.** Stage 0 runs only when a `decide` function is wired in **and** the caller supplied `currentRequest` **and** the conversation is already over its token budget. Any one of those missing, and compaction proceeds exactly as it did before Stage 0 existed — Stages 1 through 4 (pruning, dedup, summarization, truncation) are unchanged. ```typescript const nl = new NeuroLink(); await nl.generate({ input: { text: "Now rename that variable to `userId` everywhere." }, context: { currentRequest: "Now rename that variable to `userId` everywhere.", }, }); ``` `currentRequest` is wired automatically from the active prompt on every internal call site that constructs `ContextCompactorDeps` — this example shows the field that has to be present, not something most callers pass by hand. ## What is eligible to drop A message is eligible only if losing it cannot corrupt the request, which rules out far more than it keeps: - role must be `user` or `assistant` — tool calls, tool results and system messages are never eligible, because dropping half of a tool-call pair produces a malformed request rather than a smaller one - content must be non-empty text - a message already marked `metadata.isSummary` is skipped — it already represents messages that were dropped, so dropping it discards all of them at once - a pinned skill message (`metadata.isSkill`) is skipped — it's replayed verbatim by design and already protected from truncation elsewhere - a message carrying `tool`, `toolCallId`, or `events` is skipped, for the same tool-call-pairing reason as above - a truncation marker or condensed-parent placeholder is skipped On top of that, the most recent messages are **never** eligible regardless of what the model says — `protectRecent` defaults to the last **6** messages. ## Dropped only on a confident no For each eligible message, the question is a plain boolean: > This earlier message contains information the assistant still needs in > order to answer the current request correctly. Treat it as needed if it > states a requirement, a decision, a constraint, a correction, a name, a > number, or a preference that the current request builds on. Treat it as > not needed if the current request is about something else entirely, or if > the message is small talk, an acknowledgement, or superseded by a later > message. A message is dropped only when the answer is a confident `false` — `minDropConfidence` defaults to **0.6**, the same bar [tool routing](/docs/features/tool-routing-decision-model) uses and for the same reason: keeping a useless message costs a few tokens, losing a needed one costs the answer. An unanswered question, a malformed answer, or a near-coin-flip verdict all keep the message. ## The drop cap, and which messages it protects At most `maxDropRatio` (default **0.5**) of the _eligible_ messages may be removed in one pass. When more than that are confidently flagged, the implementation keeps the ones nearest the current turn and drops the older confident flags first — the newest confident "not needed" verdicts are the ones spared when the cap binds, consistent with every other stage's assumption that recency correlates with relevance. Past this ratio, the model is more likely to have misread the request than to be right about most of the conversation, and positional truncation (Stage 4) is the safer tool for a wholesale reduction. Two more bounds keep the request itself small: at most **300** messages are ever asked about in one batch (`MAX_QUESTIONS`), and each message's text is truncated to **1200** characters before being sent as state. ## The summary-quality gate A second, independent gate sits on Stage 3 (LLM summarization). Before a generated summary replaces the messages it covers, it is checked against two questions over the original messages: does the summary preserve every decision, requirement, constraint, correction and open question, and is the summary actually a summary — not a refusal, an apology, an error message, or a request for clarification. **This gate fails open**, and deliberately in the opposite direction from Stage 0's drop gate: an unanswered question, a failed call, or no decision provider all **accept** the summary, because rejecting it means falling through to plain truncation — which loses strictly more than a slightly imperfect summary would. The summary is rejected only on a confident (0.6+) `is_refusal: true`, or a confident `preserves: false`. ## What this is bad at - **It only ever removes whole messages.** There's no notion of "keep the decision in this message but drop the small talk around it" — the eligibility and drop questions operate at message granularity, so a long message that is 90% irrelevant and 10% load-bearing is kept whole or dropped whole. - **A confident model can still be confidently wrong.** Calibration bounds the fraction of high-confidence answers that are wrong across many requests — it says nothing about any one verdict. The 0.6 bar and the 6-message recency floor exist because of this, not instead of it. - **It cannot see relevance created later in the same conversation.** The question is asked against the current request only; a message dropped now because it looked irrelevant to this turn cannot be un-dropped if a later turn needed it after all. - **It shares the base model's general limits** — literal reading, no arithmetic, and degraded accuracy under a very long or noisy state — all described in [what `decide` is bad at](/docs/features/decide-inference-type#what-it-is-bad-at). - **It only runs when already over budget.** Stage 0 is not a standing filter on every request; a conversation under its token budget is left completely untouched, however irrelevant its history might be. ## See also - [The `decide` inference type](/docs/features/decide-inference-type) - [Per-request context budget](/docs/features/context-budget) - [Tool / MCP routing by decision model](/docs/features/tool-routing-decision-model) --- ## Skills Guide # Skills Guide > **Since**: v9.82.0 | **Status**: Stable | **Availability**: SDK, CLI, Server ## Overview NeuroLink includes native **skills** support: versioned, discoverable instruction packs (SOPs, playbooks, workflows) the model consults before answering from general knowledge. Skills follow the [Agent Skills](https://agentskills.io) progressive-disclosure architecture — three levels, each loaded only when needed: 1. **Discovery** — a compact listing (name + description, never instructions) is embedded in the `use_skill` tool description on every `generate()`/`stream()` call. The model decides from context when a skill applies; there is no mandatory pre-flight search call. 2. **Activation** — when a skill matches the task, the model calls `use_skill(name)` and receives the **full instructions, never truncated**. The activation is **pinned to the session**: the instructions persist in conversation history, replayed byte-identically on every later turn (provider prompt caches bill them at cached rates), and re-invocations return a tiny `already_loaded` note instead of the body. 3. **Resources** — skills can bundle auxiliary files (`references/*.md`, templates, schemas). They cost zero tokens until the model reads one with `read_skill_resource`. A 20-skill catalog costs roughly 500–700 tokens of always-on listing; an activated 4K-token SOP is fetched once per session and cached thereafter. ## Quick Start ```typescript const neurolink = new NeuroLink({ skills: { enabled: true, storage: { type: "filesystem", path: "./skills" }, }, }); // The model sees the skills listing inside the use_skill tool description // and loads instructions only when a skill matches the task. const result = await neurolink.generate({ input: { text: "A refund is disputed — how do I escalate?" }, context: { sessionId: "thread-42", userId: "u1" }, }); ``` With a `sessionId` and conversation memory configured, an activated skill stays loaded for the whole session — later turns replay it from history instead of re-fetching it. Without conversation memory, activation is per-turn (nothing is pinned, and `use_skill` simply re-fetches when asked again). ## Skill Format ### Directory layout (recommended) ``` skills/ refund_dispute_escalation/ SKILL.md # frontmatter + instructions references/ edge-cases.md # loaded on demand via read_skill_resource escalation-matrix.md ``` `SKILL.md` starts with YAML frontmatter; the markdown body is the instructions: ```markdown 1. Verify the dispute in the payments dashboard… 2. … ``` Every sibling file of `SKILL.md` becomes an on-demand resource, addressable by its relative path (e.g. `references/edge-cases.md`). ### Other accepted layouts - `/.md` — single frontmatter markdown file (no resources) - `/.json` — JSON-serialized `SkillDefinition` (what mutations write) Optional fields: `scope: "scoped"` + `scopeIds: [...]` restrict a skill to specific scopes (channels/teams/tenants); `status: "deprecated"` hides it from matching. > **Scoping is fail-closed (multi-tenant safe).** A `scoped` skill is returned only to callers that supply a **matching** `scopeId` — via the per-call `skills.scopeId`, the instance `defaultScopeId`, or the server route's `?scopeId=`. When **no** scopeId is resolvable, scoped skills are **excluded** from `use_skill`/`list_skills` discovery, from `search`, and from the prompt-index listing, so on a shared multi-tenant instance a forgotten scopeId never leaks one tenant's scoped skills to another. Global skills (the default, no `scope`) are always visible. To surface a tenant's scoped skills, pass that tenant's `scopeId`. ### Authoring guidance - **Description is the matching signal.** Say _what_ the skill does and _when_ to use it, in one or two sentences. The model selects skills purely from descriptions. - **Keep instructions lean** (guideline: under ~5K tokens). Move rarely-needed detail into `references/` — if information is needed 20% of the time, it belongs in a resource file. - **Instructions are never truncated or capped** — budgets apply only to the discovery listing, which shortens descriptions uniformly (never drops names) when the catalog outgrows `listingBudgetChars`. ## How Activation Works ``` Turn 1: user asks → model sees listing → use_skill("deploy_sop") → full instructions returned (tool result) → pinned into session history: ask → [Skill loaded: deploy_sop v3] → answer Turn 2+: history replays the pinned instructions byte-identically (cached prefix for Anthropic cache_control / Gemini implicit caching); use_skill("deploy_sop") again → { status: "already_loaded" } ``` Guarantees, in order of the pipeline: - **Version pinning** — a session keeps the version it activated; a mid-session skill update never mutates instructions the model already follows. New sessions get the new version. - **Summarization-safe** — when conversation memory summarizes old turns, pinned skill messages are re-included verbatim after the summary. - **Truncation-safe** — the context compactor's sliding-window stage re-seats pinned skill messages instead of dropping them, and never content-truncates them. - **Restart-safe** — activation state is derived from the stored history itself (messages carry `metadata.isSkill`), so dedup works across process restarts and multiple instances sharing Redis memory. Without a `sessionId` (or with `sessionPersistence: false`), activation is per-turn: the instructions still arrive as a tool result for the current turn; nothing is pinned. ## Discovery Modes | Mode | Where the listing lives | When to use | | ------------------ | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- | | `"tool"` (default) | `` block inside the `use_skill` tool description | Best default — keeps the host's system prompt untouched and the listing byte-stable for provider prompt caching | | `"system-prompt"` | `## Available Skills` index appended to the system prompt | When you want the listing visible in prompt dumps/debugging | | `"none"` | Nowhere | Hosts that inject their own discovery or rely on `preload` | The listing is rendered from a name-sorted index and is a pure function of it, so calls with the same scope/tag filters render byte-identical listings — a prerequisite for Anthropic `cache_control` prefix caching and Gemini implicit caching. When the catalog exceeds `listingBudgetChars` (default 15000), every description is shortened uniformly (first sentence, then a hard cap); names are never dropped. ## Per-Call Options ```typescript await neurolink.generate({ input: { text: "…" }, context: { sessionId: "thread-42" }, skills: { enabled: true, // master toggle for this call discovery: "tool", // override the instance discovery mode scopeId: "channel-123", // include skills scoped to this id tags: ["payments"], // restrict the listing to these tags preload: ["deploy_sop"], // activate up front, no model round-trip }, }); ``` `preload` activates skills before the model runs: instructions are injected into the call's system prompt and pinned to the session like a normal activation. Use it when the host already knows which skill applies (e.g. a channel bound to a runbook). ## Built-in Tools | Tool | Injected | Purpose | | ------------------------------------------------ | -------------------------------- | ------------------------------------------------------------------------------------ | | `use_skill` | per call | Load a skill's full instructions by exact name; returns `already_loaded` when active | | `read_skill_resource` | per call | Read a bundled resource file of a loaded skill | | `list_skills` | registered | Lightweight catalog for "what can you do?" questions | | `skill_create` / `skill_update` / `skill_delete` | registered when `allowMutations` | Model-proposed mutations, gated by `onMutationRequest` | ## Storage Backends ```typescript // In-process (tests, embedded) storage: { type: "memory", skills: [...], resources: { "skill-id": { "references/x.md": "…" } } } // Filesystem (CLI, local development) storage: { type: "filesystem", path: "./skills" } // S3 (production, curator-compatible layout) storage: { type: "s3", bucket: "my-bucket", prefix: "team-skills/" } // Redis (shared store on the pooled core client, no TTL) storage: { type: "redis", url: process.env.REDIS_URL } // Anything else storage: { type: "custom", store: mySkillStore } ``` Resource layouts per backend: - **Filesystem** — sibling files of `SKILL.md` (see above) - **S3** — `skills/.json` for the skill, `skills//` for resources; `index.json` is self-healing and refreshed with ETag-conditional reads (an unchanged index costs a 304, not a download) - **Redis** — `` for skills, `__resources__::` for resources (the `__resources__:` segment is reserved and excluded from the index scan) - **Custom** — implement the optional `getResource(id, path)` on your `SkillStore` S3 requires the optional peer `@aws-sdk/client-s3`. A custom store implements `get(id)`, `put(skill)`, `delete(id)`, `index()` (index entries must be cheap — they back every listing), plus optionally `getResource` and `invalidate`. ## Mutations & Approval Gate ```typescript const neurolink = new NeuroLink({ skills: { enabled: true, storage: { type: "s3", bucket: "team-skills" }, allowMutations: true, onMutationRequest: async (action) => { const ticket = await sendToSlackApproval(action); return { outcome: "pending", reference: ticket }; }, }, }); ``` - Reads **fail open** (errors → empty results + warn log); writes **fail closed**. - Deletes are soft — deprecated skills stop matching but stay in storage for audit. - Updates bump `version`; active sessions keep the version they loaded. ## Observability Every activation stamps the active span with `skill.name`, `skill.version`, `skill.instructions_chars`, and `skill.pinned`, so traces show exactly which skills a turn loaded and what they cost. ## CLI ```bash neurolink skills list --skills-dir ./skills neurolink skills show refund_dispute_escalation neurolink skills search "refund" --tag payments neurolink skills create --name deploy_sop --description "How to deploy" --instructions-file ./sop.md neurolink skills delete deploy_sop # Make skills available to a run neurolink generate "how do I deploy?" --skills-dir ./skills ``` `NEUROLINK_SKILLS_DIR` works as an alternative to `--skills-dir`. ## Server `/api/agent/skills` exposes CRUD routes when the server's NeuroLink instance has skills configured (503 `SKILLS_UNAVAILABLE` otherwise); mutation routes additionally require `allowMutations: true`. ## Config Reference | Key | Default | Purpose | | --------------------- | -------------------- | ---------------------------------------------------------------------- | | `enabled` | — | Master switch (required) | | `storage` | `{ type: "memory" }` | Persistence backend | | `discovery` | `"tool"` | Where the listing surfaces (`"tool"` \| `"system-prompt"` \| `"none"`) | | `listingBudgetChars` | `15000` | Character budget for the `"tool"` listing | | `sessionPersistence` | `true` | Pin activated instructions into session history | | `maxMatches` | `5` | Max skills hydrated per programmatic `search()` | | `promptIndexMaxItems` | `50` | Max entries in the `"system-prompt"` index | | `indexCacheTtlMs` | `30000` | Index cache TTL (0 disables) | | `defaultScopeId` | — | Scope filter applied when a call provides none | | `allowMutations` | `false` | Register the `skill_*` mutation tools | | `onMutationRequest` | — | Host approval gate for mutations | ## Programmatic Access ```typescript const manager = neurolink.getSkillsManager(); const all = await manager?.list(); const matches = await manager?.search({ query: "refund", limit: 3 }); const skill = await manager?.get("refund_dispute_escalation"); const resource = await manager?.getResource( skill!.id, "references/edge-cases.md", ); ``` --- ## Speech-to-Speech Agents: Architecture and Gemini Live Integration Plan # Speech-to-Speech Agents: Architecture and Gemini Live Integration Plan Status: Proposal (Docs only) Owner: NeuroLink Platform Last updated: 2025-09-01 ## Goals - Use `NeuroLink.stream` as the single, unified API for both text and voice streaming (no separate engine entrypoint). - Start with Google Gemini Live API (Studio) as the first realtime provider. - Server-level only: users attach their own WebSocket(s) and forward events; we do not host WS in the SDK. - Keep the design provider-agnostic to allow adding OpenAI Realtime, ElevenLabs, Azure Speech, etc. ## Scope (Phase 1) - Extend `neurolink.stream` to accept audio input frames and emit audio output events (audio-only out). - Provider: Google Gemini Live (Studio) bridged internally from the stream code path. - No built-in HTTP/WS server: consumers maintain their own transport and forward events. - Basic audio guidance (PCM16LE framing, resampling hints); no full DSP stack. - Config via env; minimal telemetry via existing logger. Non-goals (Phase 1): - Building a client/browser UI or bundling web audio capture. - Managing customer WebSocket endpoints and broadcasting logic. - Advanced AEC/AGC/VAD DSP processing. We’ll document expectations and provide simple utilities only. - Persisted conversation memory integration (initially). We’ll design for it; implementation can follow. ## High-Level Architecture (Stream-Centric) ``` ┌──────────────────────────┐ │ Application Server │ │ (your Express/Fastify) │ ├──────────────────────────┤ │ Your WS endpoints │ ◀── you own creation & forwarding to clients │ - /ws/input │ │ - /ws/output │ ├──────────────────────────┤ │ NeuroLink.stream │ │ - StreamOptions (extended) │ voice/text input │ - AsyncIterable │ voice/text output │ - Audio helpers (lightweight) │ PCM framing/resampling guidance │ - Telemetry hooks (minimal in P1) │ ├──────────────────────────┤ │ Providers │ │ - GeminiLiveProvider │ (Phase 1) │ - OpenAIRealtime │ (Phase 2+) │ - ... others │ └──────────────────────────┘ ▲ │ │ events (audio/text/tools/status) │ ws/grpc over provider SDK │ sendAudio/sendText/flush/control ▼ Provider SDK (e.g. @google/genai or Vertex Live API) ``` ## Proposed Changes (Stream Extensions Only) - Extend `StreamOptions` to support audio input alongside text: - `input: { text?: string; audio?: { frames: AsyncIterable; sampleRateHz: number; encoding: 'PCM16LE'; channels?: 1 } }` - Extend `StreamResult.stream` to yield discriminated events: - `AsyncIterable` - Add `AudioChunk` type: `{ data: Buffer; sampleRateHz: number; channels: number; encoding: 'PCM16LE' }` - No new top-level entrypoints; keep `neurolink.stream()` as the single API. Phase 2 (NeuroLink Client — new SDK package) planned modules: - Package name: `@juspay/neurolink-client` (new package from scratch) - Repository layout: monorepo subpackage `packages/neurolink-client/` (or separate repo if preferred) - `packages/neurolink-client/src/index.ts` — central exports for browser/client usage - `packages/neurolink-client/src/types.ts` — client-side event and message types - `packages/neurolink-client/src/wsBridge.ts` — WebSocket bridge (send/receive) with pluggable codecs - `packages/neurolink-client/src/codecs/{json,binary}.ts` — default JSON and optional binary audio codecs - `packages/neurolink-client/src/utils/{base64,pcm}.ts` — helpers for encoding/PCM16LE framing No additional public entrypoints planned beyond `neurolink.stream`. ## Stream API Extensions (Provider-Agnostic) ### Extended Types ```ts // Additions to existing StreamOptions (src/lib/types/streamTypes.ts) type PCMEncoding = "PCM16LE"; type AudioInputSpec = { frames: AsyncIterable; // PCM16LE mono frames (20-60ms recommended) sampleRateHz: number; // usually 16000 for input encoding: PCMEncoding; // 'PCM16LE' channels?: 1; // Phase 1: mono }; type AudioChunk = { data: Buffer; sampleRateHz: number; // Gemini typically 24000 on output channels: number; // 1 encoding: PCMEncoding; // 'PCM16LE' }; // StreamOptions extension // input: { text: string } remains valid for text-only flows type ExtendedStreamInput = { text?: string; audio?: AudioInputSpec; }; // StreamResult extension: discriminated union events type StreamEvent = | { type: "text"; content: string } | { type: "audio"; audio: AudioChunk }; ``` ### Session Lifecycle ```ts type SpeechSession = { id: string; start(): Promise; close(code?: number, reason?: string): Promise; // Sending upstream (server -> provider) sendAudioFrame( pcm16le: Buffer, sampleRateHz: number, opts?: { endOfSegment?: boolean }, ): void; sendText(text: string): void; // optional text prompts/messages flush(): void; // request model to produce output // Events (subscribe and forward over your WS) on(event: "audio", listener: (chunk: AudioChunk) => void): this; on(event: "text", listener: (delta: TextDelta) => void): this; on(event: "tool-call", listener: (call: ToolCallEvent) => void): this; // future on(event: "tool-result", listener: (res: ToolResultEvent) => void): this; // future on(event: "status", listener: (s: ProviderStatusEvent) => void): this; on(event: "error", listener: (err: Error) => void): this; on( event: "close", listener: (info: { code?: number; reason?: string }) => void, ): this; }; type AudioChunk = { data: Buffer; sampleRateHz: number; channels: number; encoding: "PCM16LE"; }; type TextDelta = { text: string; isFinal?: boolean; }; ``` ### Provider Bridging Each provider’s existing `stream()` implementation will detect `input.audio` and bridge to the provider’s live API, mapping provider callbacks to the unified stream events defined above. ## Gemini Live Mapping (Phase 1 via stream) Two access modes are planned: 1. Studio API via `@google/genai` (API key) - Env: `GOOGLE_AI_API_KEY` (alias: `GEMINI_API_KEY`) - Connect: `client.live.connect({ model, callbacks, config })` - Pros: simple setup; good for quick start. 2. Vertex AI Live API (service account) - Env: `GOOGLE_APPLICATION_CREDENTIALS` (or inline credentials), `GOOGLE_VERTEX_PROJECT`, `GOOGLE_VERTEX_LOCATION` - SDK: `@google-cloud/vertexai` once parity for Live is stable; alternatively direct WS following docs. - Pros: enterprise auth, quota, monitoring; aligns with existing Vertex usage in repo. Phase 1 decision (locked): use Studio channel via `@google/genai` as the primary path; output is audio-only. Vertex channel and other capabilities move to Phase 2. Reference docs (sourced for details): - Live API overview: https://cloud.google.com/vertex-ai/generative-ai/docs/live-api - Streamed conversations: https://cloud.google.com/vertex-ai/generative-ai/docs/live-api/streamed-conversations - Tools with Live API: https://cloud.google.com/vertex-ai/generative-ai/docs/live-api/tools ### Provider Config (Phase 1) ```ts // Internally, provider config sets: // responseModalities: ['AUDIO'] // speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName = 'Orus' (default) // Optional languageCode ``` ### Event Mapping (Phase 1) - Provider parses `LiveServerMessage.serverContent.modelTurn.parts[]`. - If `inlineData` audio present, yield event `{ type: 'audio', audio: { data, sampleRateHz: 24000, encoding: 'PCM16LE', channels: 1 } }`. - Text deltas: deferred to Phase 2. - `serverContent.interrupted === true`: emit `status` `{ type: 'interrupted' }` and stop/flush local playback queues. - onopen/onclose/onerror: map to `status`/`close`/`error`. - Tools (Phase 2): `serverContent.toolCall` → `tool-call` event for integration with MCP pipeline. Additional Live API behaviors from docs: - Turn-based and streaming: you can stream user audio continuously (client → model) and receive overlapping model audio replies (server → client). Many realtime APIs also support an explicit end-of-input signal to prompt the model to respond; consult the Streamed Conversations doc for Gemini-specific control messages. - Interruptions: the server may signal interruptions mid-playback when new input arrives; handle by stopping queued audio (as shown in sample) and resetting `nextStartTime`. ### Audio Expectations (Phase 1) - Upstream format: PCM16LE mono, recommended 16 kHz. If clients provide 44.1/48 kHz float32, resample then convert to PCM16LE. - Downstream format: Gemini typically outputs 24 kHz PCM; we’ll emit chunks with `sampleRateHz=24000`. - Utilities will include minimal conversion helpers; full DSP left to consumers or future phases. Notes aligned to docs: - The Live API accepts mixed modalities (audio and text) in the same session. Sending text messages mid-conversation is supported. - For low-latency, send small audio frames frequently (e.g., 20–60ms worth per frame) instead of large buffers. ## Server-Level Usage with `neurolink.stream` (Phase 1) ```ts const neurolink = new NeuroLink(); // Build an AsyncIterable of PCM16LE mono frames at 16kHz from your WS/client async function* framesFromClient(wsConn) { for await (const msg of wsConn) { // msg is already a Buffer of PCM16LE mono (16kHz) yield msg as Buffer; } } const streamResult = await neurolink.stream({ provider: "google-ai", // internally routed to Gemini Live (Studio) for audio model: "gemini-2.5-flash-preview-native-audio-dialog", input: { audio: { frames: framesFromClient(clientWs), sampleRateHz: 16000, encoding: "PCM16LE", }, }, }); for await (const ev of streamResult.stream) { if ((ev as any).type === "audio") { // Forward Buffer to clients over your WS serverWs.send((ev as any).audio.data); } } ``` ## Configuration (Phase 1) - Studio: - `GOOGLE_AI_API_KEY` (preferred) or `GEMINI_API_KEY` - Vertex channel is deferred to Phase 2. Studio channel uses `@google/genai` Live SDK semantics (client.live.connect). The subsystem follows the project’s dotenv loading pattern. No hard dependency added to runtime unless the feature is used. ## Telemetry & Logging - Phase 1: reuse `src/lib/utils/logger.ts` for structured logs; expose minimal counters (session count, bytes in/out, errors). OTEL deferred. - Phase 2+: optional OpenTelemetry spans (connect, sendAudio, receiveAudio, flush, close) with attributes: provider, model, channel (studio|vertex), sessionId, sampleRates, bytesIn/bytesOut, firstAudioLatencyMs. ## Error Handling & Resilience - Categorize errors: auth (401/403), network (WS close abnormal), rate limit, server (5xx), protocol (invalid frame). - Configurable backoff on reconnect for transient failures; max retries per session. - Surface provider close codes/reasons to consumers. - Guardrails on input audio (size/rate), with backpressure callbacks. - Vertex-specific items (regional endpoints/quotas, close code mapping) are Phase 2. ## Extensibility (Other Providers) - Implement provider-specific live bridging in the existing `stream()` path: - Detect `input.audio` and route to the provider’s live API (e.g., OpenAI Realtime, ElevenLabs, Azure). - Map provider callbacks to stream events: `{ type: 'audio' }` and, in Phase 2, `{ type: 'text' }`. - Optional capability flags: `supports.tools` (P2), `supports.duplex`, `supports.textDelta` (P2), `input.sampleRates`. - For providers like OpenAI Realtime, add `supports.webrtc` if WebRTC control is planned (P3). ## Tools Integration (Phase 2) - Gemini Live tools map well to our MCP infrastructure. - Plan: bridge provider tool-calls to NeuroLink MCP registry (`src/lib/mcp/**`). - The streaming pipeline surfaces `tool-call` intents; execute via NeuroLink MCP; return `tool-result` back to the provider stream. - Based on docs, Live API supports tool/function execution mid-session; we’ll translate those to our MCP tool contract and return results back through the provider’s tool result pathway. ## Voice Catalog & Advanced Controls (Phase 3) - Voice catalog discovery for Gemini Live; expose `listVoices()` and cache results. - Dynamic voice switching mid-session (where supported). - Advanced prosody/style parameters; SSML-like controls if surfaced by provider. - Diarization/transcription toggles; dual-stream (audio+text) combined experiences. - Optional WS/WebRTC adapters and client helpers. ## Security Considerations - Never expose service account creds to clients. Server-only control. - Validate audio frame size/rate from clients; apply quotas. - Consider PII handling and retention policies for recorded buffers. - Support regionality via Vertex location settings. ## Implementation Phases & Steps ### Phase 1 (Now): Studio + Audio-Only 1. Scaffolding (core contracts) - Add `src/lib/realtime/{types,events,provider,session,engine}.ts`. - Minimal audio utils: `audio/pcm.ts` (PCM16LE framing) and `audio/resample.ts` (optional). - Add planned exports to `src/lib/index.ts` (guarded if needed). 2. Gemini Live Provider (Studio) - Implement via `@google/genai` (`client.live.connect`). - Map callbacks to `audio`/`status`/`error`/`close`; no text deltas. - Normalize output audio to `{ data: Buffer, sampleRateHz: 24000, encoding: 'PCM16LE' }`. 3. Session API & Controls - Implement `sendAudioFrame`, `flush`, `start`, `close`. - Backpressure safety (drop/queue strategy when overwhelmed). 4. Minimal Telemetry & Logging - Counters: session count, bytes in/out, errors; debug logs. 5. Smoke Tests & Example - Synthetic audio roundtrip test. - Example usage snippet in docs (no WS server bundled). ### Phase 2: Vertex, Text & Tools 1. Vertex Live API Channel - WS connection to Vertex regional endpoint; env-driven project/location. 2. Text Deltas - Enable `text` events; downstream subtitle-like handling. 3. Tools Integration - Bridge Live API tool calls to NeuroLink MCP; emit `tool-call`/`tool-result`. 4. Telemetry (OTEL) - Add optional spans and metrics; health endpoints. 5. NeuroLink Client SDK (WS bridge — new package) - Build a brand-new client SDK as a separate npm package `@juspay/neurolink-client`. - Connects to your server’s WS endpoint; no audio capture/playback included. - Responsibilities: send upstream audio frames and control messages to server; receive downstream audio/status/text events from server. - Default wire protocol (JSON envelope; optional binary audio): - Upstream JSON: `{ type: 'audio', data: , sampleRateHz: 16000, encoding: 'PCM16LE' }` - Upstream control: `{ type: 'flush' }`, `{ type: 'text', text: string }` - Downstream JSON: `{ type: 'audio', data: , sampleRateHz: 24000, encoding: 'PCM16LE' }`, `{ type: 'status', status: string }`, `{ type: 'text', text: string }` (if enabled) - Optional binary mode: raw PCM16LE frames with configurable header disabled by default. - Planned API: ```ts import { createRealtimeClient } from "@juspay/neurolink-client"; const client = createRealtimeClient({ url: "wss://your-server/ws", authToken, sendBinaryAudio: false, }); client.on("audio", (chunk) => { /* play or forward */ }); client.on("status", (s) => { /* UI indicators */ }); // push audio captured elsewhere (already PCM16LE mono @16kHz) client.sendAudioFrame(pcmBuffer, 16000); client.flush(); client.close(); ``` - The SDK won’t capture audio or render playback; it only bridges events over WS. - Packaging: ESM-first, tree-shakeable, no Node-only deps; minimal peer deps. 6. CLI Helpers (optional) - `neurolink live status`, basic debugging commands. ### Phase 3: Voice Catalog & Advanced Features 1. Voice Catalog - `listVoices()` with cache; per-model voice metadata. 2. Advanced Audio Controls - Prosody/style, SSML-like parameters, dynamic voice switching. 3. Transcription & Diarization - Expose toggles and events; combined audio+text pipelines. 4. WS/WebRTC Adapters (optional) - Lightweight helpers for common server/client patterns. ## Task Checklist ### Phase 1 — Studio + Audio-Only (via stream) - [ ] Extend `StreamOptions` to accept `input.audio` (PCM16LE frames @16kHz). - [ ] Extend `StreamResult.stream` to yield `{ type: 'audio', audio: AudioChunk }` events. - [ ] Implement Gemini Live (Studio) bridging in provider stream path when `input.audio` is present. - [ ] Default voice and output sample rate: Orus @24kHz; normalize `AudioChunk` accordingly. - [ ] Minimal telemetry/logging: session count, bytes in/out, error count; debug logs. - [ ] Smoke test: synthetic audio input → audio output events. - [ ] Documentation: server usage snippet and guidance for WS forwarding. ### Phase 2 — Vertex, Text, Tools, Client SDK - [ ] Implement Vertex Live API channel (WS) with `GOOGLE_VERTEX_PROJECT`/`GOOGLE_VERTEX_LOCATION` env support. - [ ] Enable text delta events and downstream handling. - [ ] Bridge Live API tool-calls to MCP; emit `tool-call`/`tool-result` events and roundtrip to provider. - [ ] Add optional OpenTelemetry spans/metrics (connect/send/receive/flush/close). - [ ] Create new package `@juspay/neurolink-client` (ESM, browser-first). - [ ] Implement client WS bridge (`wsBridge.ts`) and message codecs (`codecs/{json,binary}.ts`). - [ ] Define client SDK types and API (`createRealtimeClient`, `sendAudioFrame`, `flush`, events). - [ ] Client SDK documentation and example integration. - [ ] Optional: CLI helpers (e.g., `neurolink live status`). ### Phase 3 — Voice Catalog & Advanced Controls - [ ] Implement `listVoices()` discovery and caching for Gemini Live. - [ ] Support dynamic voice switching mid-session (where supported). - [ ] Add advanced prosody/style/SSML-like parameters (provider-permitting). - [ ] Add transcription/diarization toggles and corresponding events. - [ ] Optional server/client helpers for WS/WebRTC patterns. ## Open Questions for Review - Minimum audio contract for upstream: we recommend PCM16LE 16 kHz mono; OK to lock this as a requirement for Phase 1? - Client WS protocol: keep default JSON + base64 audio with opt-in binary? Any constraints from your infra? - Do we want a tiny built-in WS helper (opt-in) in Phase 3 for servers, or keep strictly library-only on server side? --- If this plan looks good, next step is to extend the `stream` types and implement the Gemini Live (Studio) provider bridging for audio, keeping all server transport concerns outside the library as requested. --- ## Streaming Guide # Streaming Guide > **Since**: v8.0.0 | **Status**: Stable | **Availability**: SDK + CLI > > **Provider Defaults:** When `--provider` (CLI) or `provider` (SDK) is not specified, NeuroLink defaults to **Vertex AI** with **gemini-2.5-flash**. Set the `NEUROLINK_PROVIDER` or `AI_PROVIDER` environment variable to change the default provider. ## Overview Streaming lets you receive AI-generated text incrementally -- token by token -- instead of waiting for the entire response. This is the same mechanism behind the "typing" effect you see in ChatGPT and other chat interfaces. **Why use streaming?** - **Faster time-to-first-token** -- Users see output within milliseconds rather than waiting seconds for a complete response. - **Better UX** -- Progressive rendering feels more interactive and responsive. - **Lower memory footprint** -- Process tokens as they arrive instead of buffering the full response. - **Early cancellation** -- Stop generation as soon as you have what you need. ## Quick Start ```typescript const neurolink = new NeuroLink(); const result = await neurolink.stream({ input: { text: "Explain how TCP works in two paragraphs" }, }); for await (const chunk of result.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } ``` That is the simplest possible streaming call. The sections below cover every option in detail. ## SDK API ### `neurolink.stream(options): Promise` The `stream()` method accepts a `StreamOptions` object and returns a `StreamResult`. ### StreamOptions (Key Parameters) | Parameter | Type | Required | Description | | -------------- | ------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `input` | `{ text: string, ... }` | Yes | The prompt and optional multimodal inputs (images, PDFs, files, audio) | | `provider` | `string` | No | AI provider name (`"openai"`, `"anthropic"`, `"google-ai"`, `"vertex"`, etc.) | | `model` | `string` | No | Specific model (`"gpt-4o"`, `"claude-3-5-sonnet"`, `"gemini-2.5-flash"`) | | `temperature` | `number` | No | Randomness (0.0 = deterministic, 2.0 = creative). Default varies by provider | | `maxTokens` | `number` | No | Maximum tokens in the response | | `systemPrompt` | `string` | No | System message to control AI behavior | | `agentMode` | `boolean \| { version: "1" \| "2" }` | No | Prepend Neurolink's versioned terminal agent instructions to `systemPrompt`; `true` applies the current version (`"2"`), and the result reports `agentModeVersion`. Same option on `generate()` | | `tools` | `Record` | No | Custom tools the model can invoke during generation | | `rag` | `RAGConfig` | No | RAG configuration -- pass `{ files: [...] }` for automatic retrieval | | `timeout` | `number \| string` | No | Request timeout in milliseconds | | `abortSignal` | `AbortSignal` | No | External cancellation signal | | `maxSteps` | `number` | No | Maximum tool execution steps (default: 5) | | `disableTools` | `boolean` | No | Set `true` to disable all tool usage | | `tts` | `TTSOptions` | No | Enable text-to-speech audio alongside text | ### `input` Object The `input` field is the only required parameter. At minimum it needs a `text` property: ```typescript // Text only input: { text: "Your prompt here" } // Text + images input: { text: "What is in this image?", images: [Buffer.from(pngData), "https://example.com/photo.jpg"] } // Text + PDF files input: { text: "Summarize this document", pdfFiles: ["./report.pdf"] } // Text + auto-detected files input: { text: "Review this code", files: ["./src/app.ts"] } ``` ## StreamResult Calling `stream()` returns a `StreamResult` object. The response itself arrives through the `.stream` async iterable, while metadata fields resolve once the stream completes. | Field | Type | Description | | ---------------- | ----------------------------------------- | ---------------------------------------------------------------- | | `stream` | `AsyncIterable` | The async iterable you consume with `for await` | | `provider` | `string` | Name of the provider that served the request | | `model` | `string` | Model that was used | | `usage` | `TokenUsage` | Token usage (prompt, completion, total) | | `finishReason` | `string` | Why generation stopped (`"stop"`, `"length"`, `"tool-calls"`) | | `toolCalls` | `ToolCall[]` | Tool calls made during generation | | `toolResults` | `ToolResult[]` | Results from tool execution | | `toolExecutions` | `ToolExecutionSummary[]` | Detailed summary of all tool executions | | `metadata` | `object` | Stream metadata (streamId, startTime, totalChunks, responseTime) | | `analytics` | `AnalyticsData \| Promise` | Usage analytics (when `enableAnalytics: true`) | ## Stream Chunks Each chunk yielded by `result.stream` is a discriminated union: ### Text Chunks The most common chunk type. Contains a `content` string with the next piece of generated text. ```typescript for await (const chunk of result.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } ``` You can also check the `type` discriminator: ```typescript for await (const chunk of result.stream) { if (chunk.type === "text") { process.stdout.write(chunk.content); } } ``` ### Audio Chunks (TTS) When TTS is enabled, the stream interleaves text and audio chunks: ```typescript const result = await neurolink.stream({ input: { text: "Tell me a story" }, provider: "google-ai", tts: { enabled: true, voice: "en-US-Neural2-C" }, }); const audioBuffers: Buffer[] = []; for await (const chunk of result.stream) { switch (chunk.type) { case "text": process.stdout.write(chunk.content); break; case "audio": audioBuffers.push(chunk.audio.data); break; } } ``` See the [TTS Guide](/docs/features/tts) for full audio streaming details. ## Collecting the Full Response If you need the complete text after streaming finishes, accumulate chunks into a string: ```typescript const result = await neurolink.stream({ input: { text: "Write a haiku about programming" }, }); let fullText = ""; for await (const chunk of result.stream) { if ("content" in chunk) { fullText += chunk.content; } } console.log("Complete response:", fullText); console.log("Tokens used:", result.usage); console.log("Finish reason:", result.finishReason); ``` ## Streaming with Tools Tools work transparently during streaming. The model calls tools mid-stream, receives results, and continues generating. You consume the stream exactly the same way -- tool execution happens behind the scenes. ```typescript const neurolink = new NeuroLink(); const weatherTool = tool({ description: "Get current weather for a city", parameters: z.object({ city: z.string() }), execute: async ({ city }) => { return { temperature: 22, condition: "sunny", city }; }, }); const result = await neurolink.stream({ input: { text: "What is the weather like in Tokyo right now?" }, tools: { getWeather: weatherTool }, maxSteps: 3, }); for await (const chunk of result.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } // After stream completes, inspect tool activity console.log("Tool calls:", result.toolCalls); console.log("Tool results:", result.toolResults); ``` ## Streaming with RAG Pass `rag: { files: [...] }` to automatically index documents and give the model a search tool. The model decides when to search during generation. ```typescript const result = await neurolink.stream({ input: { text: "What deployment strategies does the guide recommend?" }, rag: { files: ["./docs/deployment-guide.md"], strategy: "markdown", chunkSize: 512, topK: 5, }, }); for await (const chunk of result.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } ``` See the [RAG Guide](/docs/tutorials/rag) for configuration details and advanced usage. ## Streaming with Multimodal Input Stream responses that analyze images, PDFs, or other files: ```typescript // Stream with image input const result = await neurolink.stream({ input: { text: "Describe what you see in detail", images: [readFileSync("./photo.png")], }, provider: "openai", model: "gpt-4o", }); for await (const chunk of result.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } ``` ## Cancellation with AbortSignal Use an `AbortSignal` to cancel a stream from outside: ```typescript const controller = new AbortController(); // Cancel after 5 seconds setTimeout(() => controller.abort(), 5000); const result = await neurolink.stream({ input: { text: "Write a very long story" }, abortSignal: controller.signal, }); try { for await (const chunk of result.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } } catch (error) { if (error.name === "AbortError") { console.log("\nStream cancelled."); } } ``` ## CLI Streaming The NeuroLink CLI streams by default with the `stream` command: ```bash # Basic streaming neurolink stream "Explain quantum computing" # With provider and model neurolink stream "Write a poem" --provider openai --model gpt-4o # With temperature neurolink stream "Creative story about robots" --temperature 0.9 # With RAG neurolink stream "Summarize the docs" --rag-files ./docs/guide.md # With system prompt neurolink stream "Translate to French" --system "You are a professional translator" ``` ## Error Handling Errors can occur either when initiating the stream or while consuming chunks. Handle both cases: ```typescript try { const result = await neurolink.stream({ input: { text: "Hello" }, provider: "openai", timeout: 10000, }); try { for await (const chunk of result.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } } catch (streamError) { // Error during streaming (network drop, provider error mid-stream) console.error("Stream interrupted:", streamError.message); } } catch (initError) { // Error before streaming starts (auth failure, invalid model, budget exceeded) console.error("Failed to start stream:", initError.message); } ``` ### Common Errors | Error | Cause | Solution | | ------------------------- | ------------------------------------------ | --------------------------------------------------- | | `SESSION_BUDGET_EXCEEDED` | Session cost exceeded `maxBudgetUsd` limit | Increase budget or start a new session | | `PROVIDER_AUTH_ERROR` | Missing or invalid API key | Set the provider's API key environment variable | | `TIMEOUT` | Request exceeded timeout | Increase `timeout` or use `abortSignal` for control | | `MODEL_NOT_FOUND` | Invalid model name | Check provider docs for supported model names | ## Provider Support All NeuroLink providers support streaming: | Provider | Streaming | Notes | | ----------------- | --------- | ----------------------------------------------------------- | | OpenAI | Yes | Full streaming with tool support | | Anthropic | Yes | Full streaming with tool support | | Google AI Studio | Yes | Full streaming with tool support | | Google Vertex AI | Yes | Full streaming with tool support | | Amazon Bedrock | Yes | Full streaming with tool support | | Azure OpenAI | Yes | Full streaming with tool support | | Mistral | Yes | Full streaming with tool support | | LiteLLM | Yes | Full streaming; tool support depends on underlying model | | Ollama | Yes | Full streaming; tool support depends on model | | Hugging Face | Yes | Streaming support; tool support varies by model | | Amazon SageMaker | Limited | Falls back to fake streaming (generate then emit as chunks) | | OpenAI-Compatible | Yes | Depends on the endpoint's streaming support | When real streaming is not available for a provider or model, NeuroLink transparently falls back to "fake streaming" -- it generates the full response and then emits it as chunks. Your consuming code does not need to change. ## See Also - [Advanced Streaming Guide](/docs/advanced/streaming) -- Enterprise streaming patterns, backpressure, and event types - [TTS Guide](/docs/features/tts) -- Text-to-speech audio streaming - [RAG Guide](/docs/tutorials/rag) -- Retrieval-augmented generation with streaming - [Thinking Configuration](/docs/features/thinking-configuration) -- Extended thinking with streaming - [Multimodal Guide](/docs/features/multimodal) -- Images, PDFs, and files with streaming --- ## Structured Output with Zod Schemas # Structured Output with Zod Schemas Generate type-safe, validated JSON responses using Zod schemas. Both `generate()` and `stream()` accept `schema`; `generate()` returns `structuredData` directly, while a fully drained stream exposes it as `result.metadata.structuredData`. ## Quick Start ```typescript const neurolink = new NeuroLink(); const UserSchema = z.object({ name: z.string(), age: z.number(), email: z.string(), }); const result = await neurolink.generate({ input: { text: "Create a profile for John Doe, 30, software engineer" }, schema: UserSchema, output: { format: "json" }, }); const user = JSON.parse(result.content); console.log(user); // { name: "John Doe", age: 30, email: "john.doe@example.com" } ``` ## Requirements 1. **`schema`**: A Zod schema defining the output structure — always required. 2. **`output.format`**: Must be `"json"` or `"structured"` to get a JSON string in `result.content` (defaults to `"text"` if not specified). This is independent of `structuredData`: passing `schema` alone, with no `output.format`, is enough for `result.structuredData` to be populated — this is the path the [tools section below](#works-with-tools) uses. ## Complex Schemas ```typescript const CompanySchema = z.object({ name: z.string(), headquarters: z.object({ city: z.string(), country: z.string(), }), employees: z.array( z.object({ name: z.string(), role: z.string(), salary: z.number(), }), ), financials: z.object({ revenue: z.number(), profit: z.number(), }), }); const result = await neurolink.generate({ input: { text: "Analyze TechCorp company" }, schema: CompanySchema, output: { format: "json" }, }); ``` ## Works with Tools Structured output works seamlessly with MCP tools: ```typescript const result = await neurolink.generate({ input: { text: "Get weather for San Francisco" }, schema: WeatherSchema, output: { format: "json" }, tools: { getWeather: myWeatherTool }, }); // Tools execute first, then response is formatted as JSON ``` ### How this works on OpenAI-compatible providers OpenAI-compatible vendors vary in whether they accept `response_format` and `tools` in the same request. NeuroLink is conservative by default and does not send them together. For catalog providers whose combined request has been verified live, `capabilities.structuredOutputWithTools: true` opts both `generate()` and `stream()` into sending them together, so the vendor can use native constrained decoding without an extra formatting request. Separate successful tool and structured-output probes are not enough to enable the flag. When a provider is not opted in, the tool turn runs untouched. If its answer does not satisfy your schema, the SDK re-asks **once** with the tools removed, which is what makes native `response_format` legal again. That second pass only reformats an answer the model has already produced, so tool results still drive the content; `toolsUsed`, `toolExecutions` and `usage` cover the whole turn, not just the reformat. If an opted-in provider later rejects the combined request, the same conflict recovery retries without structured output, so a stale capability flag costs one request rather than the turn. Two consequences worth knowing: - A `generate({ schema })` call that needed the reformat costs **up to three** requests: the original tool turn, the `response_format` re-ask, and — only if the vendor rejects the schema itself (a non-object root) rather than the request — a third tools-free pass with the schema spelled into the prompt instead, described below. Calls whose first answer already satisfies the schema cost one, as before. - The reformat is accepted only if it actually produced a schema-valid value. If it fails, if the SDK's own turn deadline is reached, or if it comes back as prose anyway, the original answer is returned rather than an error — so this can improve an outcome but never degrade one. A caller that cancels the request still gets its cancellation. In those cases `structuredData` may still be unset, which is the honest signal that the model never produced the value. The schema is deliberately **not** injected into the tool turn's system prompt. Some models read a JSON Schema sitting next to a tool list as another tool and answer by calling one that does not exist — Groq's `llama-3.3-70b-versatile` tries to call a tool named `json`, which the server rejects outright. The re-ask is not a single attempt. It tries native `response_format` first, because removing the tools is precisely what makes that legal again. Some vendors then reject the **schema itself** rather than the request: Groq answers a non-object root with `invalid JSON schema for response_format: schema must have type 'object'`, so an array- or scalar-rooted schema fails at this stage. When that happens the SDK degrades a second time and re-runs the same tools-free pass with the schema spelled into the prompt instead. That is why a `z.array(z.string())` schema returns `["red","blue","yellow"]` with matching `structuredData` rather than prose. Both stages run without tools; only the way the schema is communicated changes. ### Important: Google Gemini Providers Limitation **Google API Constraint:** Google Gemini (both Vertex AI and Google AI Studio) **cannot combine function calling with structured output (JSON schema validation)**. This is a documented Google API limitation, not a NeuroLink issue. > **Gemini 3 / Gemini 2.5 Note:** This limitation applies to **all Gemini models**, including the latest Gemini 3 and Gemini 2.5 series (e.g., `gemini-2.5-pro`, `gemini-2.5-flash`). While these models have excellent JSON schema support for structured output, they still cannot use tools and JSON schema validation together in the same request. **Error Message:** ``` Function calling with a response mime type: 'application/json' is unsupported ``` **Solution:** Use `disableTools: true` when using schemas with Google providers: ```typescript const result = await neurolink.generate({ input: { text: "Analyze TechCorp company" }, schema: CompanySchema, output: { format: "json" }, provider: "vertex", // or "google-ai" disableTools: true, // ✅ REQUIRED for Google providers with schemas }); ``` **This is Industry Standard:** All major AI frameworks (LangChain, Vercel AI SDK, Agno, Instructor) use the same approach - disabling tools when using response schemas with Google models. ### Workarounds for Gemini Tools + Structured Output If you need both tool execution and structured output with Gemini, consider these approaches: 1. **Two-Step Approach:** First call with tools enabled (no schema), then a second call with schema to format the result: ```typescript // Step 1: Execute tools const toolResult = await neurolink.generate({ input: { text: "Get current weather for Tokyo" }, provider: "vertex", tools: { getWeather: myWeatherTool }, }); // Step 2: Format with schema const structured = await neurolink.generate({ input: { text: `Format this data: ${toolResult.content}` }, schema: WeatherSchema, output: { format: "json" }, provider: "vertex", disableTools: true, }); ``` 2. **Use a Different Provider:** OpenAI and Anthropic support tools and structured output together: ```typescript const result = await neurolink.generate({ input: { text: "Get weather and format as JSON" }, schema: WeatherSchema, output: { format: "json" }, provider: "openai", // ✅ Supports tools + schema together tools: { getWeather: myWeatherTool }, }); ``` 3. **Choose One or the Other:** Design your workflow to use either tools OR structured output per request, not both. **Related Limitation:** Complex schemas may trigger "Too many states for serving" errors. Solutions: 1. Simplify schema structure 2. Reduce nested objects 3. Use `disableTools: true` to reduce state complexity ## Important Notes - **Available in `generate()` and `stream()`** - `generate()` exposes `result.structuredData`; after the stream is fully drained, `stream()` exposes `result.metadata.structuredData` - **`output.format` controls `result.content`** - If it is not "json" or "structured", `result.content` is plain text even with a schema; `result.structuredData` can still be populated from `schema` alone (see [Requirements](#requirements)) - **Auto-validated, with a no-throw fallback when tools are involved** - Without tools, an invalid response throws `NoObjectGeneratedError` with validation details. With tools attached, a failed schema match triggers the tool-free re-ask described in [Works with Tools](#works-with-tools); if that also fails, the original answer is returned rather than an error, and `structuredData` is left unset - **Provider support** - Works with OpenAI, Anthropic, Google AI Studio, Vertex AI - **Gemini JSON Schema Support** - Gemini 3 / Gemini 2.5 models have excellent native JSON schema support - **Gemini Tools Limitation** - All Gemini models (including Gemini 3) cannot combine tools with schemas - use `disableTools: true` ## See Also - [API Reference](/docs/sdk/api-reference) - [Custom Tools](/docs/sdk/custom-tools) - [MCP Integration](/docs/mcp/integration) --- ## TaskManager - Scheduled & Self-Running Tasks # TaskManager - Scheduled & Self-Running Tasks ## Overview TaskManager adds scheduled and self-running task capabilities to NeuroLink. It enables AI agents to execute prompts on a schedule (cron, interval, or one-shot), with two execution modes: **Isolated** (fresh context per run) and **Continuation** (preserves conversation history across runs). The system is available as both an **SDK API** and **CLI commands**, and ships with **built-in tools** so AI agents can self-schedule tasks during conversations. ------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------ | | **Isolated** | Each run gets a fresh NeuroLink context. No memory of previous runs. | One-off checks, stateless monitoring, report generation | | **Continuation** | Conversation history is preserved across runs. The AI "remembers" previous executions. | Trend analysis, progressive monitoring, iterative refinement | ### Task Backends The scheduling/looping mechanism is abstracted behind a `TaskBackend` interface. Two implementations ship by default: | Backend | Default | Requires | Survives Restart | Best For | | --------------- | -------- | -------- | ---------------- | ----------------------------------------------------- | | **BullMQ** | Yes | Redis | Yes | Production, multi-process, reliable scheduling | | **NodeTimeout** | Fallback | Nothing | No | Development, zero-dependency setups, simple use cases | ### Storage Strategy Storage is **automatically tied to the backend** — users never configure it separately: | Backend | Task Store | Run Logs | Why | | --------------- | ---------- | ----------- | ------------------------------------------------------------------------------------------- | | **BullMQ** | Redis | Redis | Same Redis instance; multi-process safe, survives container restarts, works across replicas | | **NodeTimeout** | JSON file | JSONL files | No Redis available; local dev, single process, human-readable for debugging | This means: - **Production servers** (BullMQ) → everything in Redis → horizontally scalable, no file I/O, container-friendly - **Local dev / CLI** (NodeTimeout) → JSON files → zero dependencies, inspectable with any text editor --- ## Architecture Follows NeuroLink's established **Factory + Registry** pattern. ### Directory Structure ``` src/lib/tasks/ index.ts # Public exports taskManager.ts # TaskManager class (orchestrator) taskExecutor.ts # Task execution engine types.ts # Task type definitions store/ taskStore.ts # TaskStore interface redisTaskStore.ts # Redis implementation (used with BullMQ backend) fileTaskStore.ts # JSON file implementation (used with NodeTimeout backend) backends/ taskBackend.ts # TaskBackend interface taskBackendRegistry.ts # Registry for backend implementations bullmqBackend.ts # BullMQ implementation nodeTimeoutBackend.ts # Node.js setTimeout/setInterval implementation tools/ taskTools.ts # Built-in agent tools (createTask, listTasks, etc.) src/cli/commands/ task.ts # CLI command: `neurolink task` ``` ### Component Diagram ``` NeuroLink | v TaskManager / \ v v TaskExecutor TaskStore (interface) | / \ v v v TaskBackend RedisTaskStore FileTaskStore (interface) (BullMQ mode) (NodeTimeout mode) / \ | | v v v v BullMQ NodeTimeout Redis .neurolink/tasks/ (Redis) (setTimeout) ``` **Storage auto-selection:** When `backend: "bullmq"`, TaskManager creates a `RedisTaskStore` (task definitions + run logs in Redis). When `backend: "node-timeout"`, it creates a `FileTaskStore` (JSON + JSONL on disk). The `TaskStore` interface abstracts this so all other components are storage-agnostic. ### How It Fits Into NeuroLink ```typescript // neurolink.ts - new property class NeuroLink { private _taskManager?: TaskManager; get tasks(): TaskManager { if (!this._taskManager) { this._taskManager = new TaskManager(this); } return this._taskManager; } } ``` --- ## Type Definitions ```typescript // ── Schedule Types ────────────────────────────────────── type TaskScheduleType = "cron" | "interval" | "once"; type CronSchedule = { type: "cron"; expression: string; // Standard 5-field cron: "0 9 * * *" timezone?: string; // IANA timezone: "America/New_York" }; type IntervalSchedule = { type: "interval"; every: number; // Milliseconds }; type OnceSchedule = { type: "once"; at: Date | string; // ISO 8601 timestamp or Date object }; type TaskSchedule = CronSchedule | IntervalSchedule | OnceSchedule; // ── Execution Mode ────────────────────────────────────── type TaskExecutionMode = "isolated" | "continuation"; // ── Task Status ───────────────────────────────────────── type TaskStatus = | "pending" // Created but not yet scheduled | "active" // Scheduled and running on schedule | "paused" // Temporarily stopped | "completed" // One-shot task finished, or maxRuns reached | "failed" // Permanently failed (exhausted retries) | "cancelled"; // Manually deleted // ── Task Definition (what users provide) ──────────────── type TaskDefinition = { name: string; prompt: string; schedule: TaskSchedule; mode?: TaskExecutionMode; // Default: "isolated" // Optional overrides provider?: string; model?: string; thinkingLevel?: ThinkingLevel; systemPrompt?: string; tools?: boolean; // Enable/disable tools for this task. Default: true maxTokens?: number; temperature?: number; // Execution limits maxRuns?: number; // Max executions. Omit for unlimited. timeout?: number; // Per-run timeout in ms. Default: 120000 // Retry retry?: { maxAttempts?: number; // Default: 3 backoffMs?: number[]; // Default: [30000, 60000, 300000] }; // Callbacks (SDK only) onSuccess?: (result: TaskRunResult) => void | Promise; onError?: (error: TaskRunError) => void | Promise; onComplete?: (task: Task) => void | Promise; // When task reaches terminal state // Metadata metadata?: Record; }; // ── Task (internal, stored) ───────────────────────────── type Task = { id: string; // nanoid name: string; prompt: string; schedule: TaskSchedule; mode: TaskExecutionMode; status: TaskStatus; // Overrides provider?: string; model?: string; thinkingLevel?: ThinkingLevel; systemPrompt?: string; tools: boolean; maxTokens?: number; temperature?: number; // Limits & retry maxRuns?: number; timeout: number; retry: { maxAttempts: number; backoffMs: number[] }; // Tracking runCount: number; lastRunAt?: string; // ISO 8601 nextRunAt?: string; // ISO 8601 createdAt: string; // ISO 8601 updatedAt: string; // ISO 8601 // Continuation mode state sessionId?: string; // Conversation session ID for continuation mode // Metadata metadata?: Record; }; // ── Run Results ───────────────────────────────────────── type TaskRunResult = { taskId: string; runId: string; status: "success" | "error"; output?: string; // AI response text toolCalls?: Array; tokensUsed?: { input: number; output: number }; durationMs: number; timestamp: string; // ISO 8601 error?: string; }; type TaskRunError = { taskId: string; runId: string; error: string; attempt: number; maxAttempts: number; willRetry: boolean; timestamp: string; }; // ── Task Store Interface ──────────────────────────────── // Auto-selected based on backend: BullMQ → RedisTaskStore, NodeTimeout → FileTaskStore interface TaskStore { readonly type: "redis" | "file"; initialize(): Promise; shutdown(): Promise; // Task CRUD save(task: Task): Promise; get(taskId: string): Promise; list(filter?: { status?: TaskStatus }): Promise; update(taskId: string, updates: Partial): Promise; delete(taskId: string): Promise; // Run log CRUD appendRun(taskId: string, run: TaskRunResult): Promise; getRuns( taskId: string, options?: { limit?: number; status?: string }, ): Promise; } // RedisTaskStore: stores tasks as Redis hashes, run logs as Redis lists // Key patterns: "neurolink:task:{id}" (hash), "neurolink:task:{id}:runs" (list) // Auto-prunes run logs via LTRIM to keep latest `maxRunLogs` entries // // FileTaskStore: stores tasks in .neurolink/tasks/tasks.json, run logs in .neurolink/tasks/runs/{id}.jsonl // Auto-prunes JSONL when file exceeds `runLogMaxSize`, keeping `runLogKeepLines` entries // ── Backend Interface ─────────────────────────────────── interface TaskBackend { readonly name: string; initialize(): Promise; shutdown(): Promise; schedule(task: Task): Promise; cancel(taskId: string): Promise; pause(taskId: string): Promise; resume(taskId: string): Promise; isHealthy(): Promise; } // ── TaskManager Config ────────────────────────────────── type TaskManagerConfig = { enabled?: boolean; // Default: true backend?: "bullmq" | "node-timeout"; // Default: "bullmq" // BullMQ-specific (also used by RedisTaskStore) redis?: { host?: string; // Default: "localhost" port?: number; // Default: 6379 password?: string; db?: number; url?: string; // Alternative: full Redis URL }; // FileTaskStore-specific (only used when backend is "node-timeout") storePath?: string; // Default: ".neurolink/tasks/tasks.json" logsPath?: string; // Default: ".neurolink/tasks/runs/" // Limits maxConcurrentRuns?: number; // Default: 5 maxRunLogs?: number; // Default: 2000 (max run entries per task) // Retention (prevents Redis/disk from growing forever) taskRetention?: { completedTTL?: number; // Auto-delete completed tasks after N ms. Default: 30 days failedTTL?: number; // Auto-delete failed tasks after N ms. Default: 7 days cancelledTTL?: number; // Auto-delete cancelled tasks after N ms. Default: 7 days runLogTTL?: number; // Auto-expire individual run log entries after N ms. Default: 30 days }; // Note: Active and paused tasks never expire. Only terminal-state tasks are subject to TTL. // In Redis, TTLs are set via EXPIRE. In FileTaskStore, a periodic sweep removes expired entries. }; ``` --- ## SDK API ### Initialization ```typescript // TaskManager auto-initializes with defaults (BullMQ + Redis) const neurolink = new NeuroLink(); // Or configure explicitly const neurolink = new NeuroLink({ tasks: { enabled: true, backend: "bullmq", redis: { url: "redis://localhost:6379" }, maxConcurrentRuns: 5, }, }); // Zero-dependency mode (no Redis needed) const neurolink = new NeuroLink({ tasks: { backend: "node-timeout" }, }); ``` ### Creating Tasks ```typescript // Cron-based isolated task const dailyReport = await neurolink.tasks.create({ name: "daily-report", prompt: "Generate a daily status report of system health metrics.", schedule: { type: "cron", expression: "0 9 * * *", timezone: "America/New_York", }, mode: "isolated", provider: "openai", model: "gpt-4o", }); // Interval-based continuation task (AI remembers previous runs) const monitor = await neurolink.tasks.create({ name: "api-monitor", prompt: "Check the API health endpoint and compare with previous observations. Alert if degradation detected.", schedule: { type: "interval", every: 5 * 60 * 1000 }, // Every 5 minutes mode: "continuation", provider: "anthropic", model: "claude-sonnet-4-6", maxRuns: 100, onSuccess: (result) => { if (result.output?.includes("ALERT")) { sendSlackNotification(result.output); } }, }); // One-shot task (runs once at a specific time) const reminder = await neurolink.tasks.create({ name: "deploy-reminder", prompt: "Remind the team about the scheduled deployment.", schedule: { type: "once", at: "2026-04-01T14:00:00Z" }, mode: "isolated", }); ``` ### Managing Tasks ```typescript // List all tasks const tasks = await neurolink.tasks.list(); const activeTasks = await neurolink.tasks.list({ status: "active" }); // Get a specific task const task = await neurolink.tasks.get("task_abc123"); // Run immediately (outside of schedule) const result = await neurolink.tasks.run("task_abc123"); // Pause/Resume await neurolink.tasks.pause("task_abc123"); await neurolink.tasks.resume("task_abc123"); // Update a task (partial update) await neurolink.tasks.update("task_abc123", { prompt: "Updated prompt text", schedule: { type: "interval", every: 10 * 60 * 1000 }, }); // Delete a task await neurolink.tasks.delete("task_abc123"); // View run history const runs = await neurolink.tasks.runs("task_abc123", { limit: 20 }); // Shutdown (cleanup all backends gracefully) await neurolink.tasks.shutdown(); ``` --- ## CLI Commands ```bash # ── Create tasks ───────────────────────────────────────── # Cron schedule neurolink task create \ --name "daily-report" \ --prompt "Generate a daily status report" \ --cron "0 9 * * *" \ --timezone "America/New_York" \ --mode isolated \ --provider openai \ --model gpt-4o # Interval schedule neurolink task create \ --name "api-monitor" \ --prompt "Check API health and compare with previous runs" \ --every 5m \ --mode continuation \ --provider anthropic # One-shot schedule neurolink task create \ --name "reminder" \ --prompt "Remind about deployment" \ --at "2026-04-01T14:00:00Z" \ --mode isolated # ── Manage tasks ───────────────────────────────────────── neurolink task list # List all tasks neurolink task list --status active # Filter by status neurolink task get # Show task details neurolink task run # Run immediately neurolink task pause # Pause scheduling neurolink task resume # Resume scheduling neurolink task update --prompt "New prompt" neurolink task delete # Delete task # ── View logs ──────────────────────────────────────────── neurolink task logs # View recent runs neurolink task logs --limit 50 # View more runs neurolink task logs --status error # Filter by status ``` ### CLI Shorthand for Intervals The `--every` flag accepts human-readable durations: | Input | Meaning | | ----- | ---------------- | | `30s` | 30 seconds | | `5m` | 5 minutes | | `2h` | 2 hours | | `1d` | 1 day | | `500` | 500 milliseconds | --- ## Built-in Agent Tools These tools are registered as direct agent tools, available to the AI during any conversation. They allow the AI to self-schedule work. ### `createTask` The AI can schedule follow-up tasks during a conversation. ``` Tool: createTask Description: Schedule a recurring or one-shot task that runs a prompt on a schedule. Input: name: string - Human-readable task name prompt: string - The prompt to execute on each run schedule: object - { type: "cron"|"interval"|"once", expression?, every?, at? } mode?: string - "isolated" (default) or "continuation" Output: { taskId, name, status, nextRunAt } ``` **Example AI usage:** > User: "Monitor my API endpoint every 10 minutes and alert me if it goes down." > AI calls `createTask` with `{ name: "api-monitor", prompt: "Check https://api.example.com/health ...", schedule: { type: "interval", every: 600000 }, mode: "continuation" }` ### `listTasks` ``` Tool: listTasks Description: List all scheduled tasks and their current status. Input: status?: string - Filter by status: "active", "paused", "completed", "failed" Output: Array ``` ### `getTaskRuns` ``` Tool: getTaskRuns Description: Get the run history of a scheduled task. Input: taskId: string - The task ID limit?: number - Max results (default: 10) Output: Array ``` ### `deleteTask` ``` Tool: deleteTask Description: Cancel and remove a scheduled task. Input: taskId: string - The task ID to delete Output: { success: boolean, deletedTask: string } ``` ### `runTaskNow` ``` Tool: runTaskNow Description: Immediately execute a scheduled task outside of its normal schedule. Input: taskId: string - The task ID to run Output: { runId, status, output, durationMs } ``` --- ## Backend Interface & Extensibility ### TaskBackend Interface All backends implement this interface. To add a new backend (e.g., Agenda, Bree, pg-boss), implement `TaskBackend` and register it. ```typescript interface TaskBackend { readonly name: string; /** Initialize the backend (connect to Redis, etc.) */ initialize(): Promise; /** Gracefully shut down */ shutdown(): Promise; /** Schedule a task for execution */ schedule(task: Task, executor: TaskExecutorFn): Promise; /** Cancel a scheduled task */ cancel(taskId: string): Promise; /** Pause a task's schedule */ pause(taskId: string): Promise; /** Resume a paused task */ resume(taskId: string): Promise; /** Check if backend is operational */ isHealthy(): Promise; } type TaskExecutorFn = (task: Task) => Promise; ``` ### Registering a Custom Backend ```typescript // Register at startup TaskBackendRegistry.register("pg-boss", async (config) => { const { PgBossBackend } = await import("./pgBossBackend.js"); return new PgBossBackend(config); }); // Use it const neurolink = new NeuroLink({ tasks: { backend: "pg-boss" }, }); ``` ### BullMQ Backend Details - Uses `bullmq` `Queue` + `Worker` + `upsertJobScheduler()` - Cron tasks → BullMQ repeatable jobs - Interval tasks → BullMQ repeatable jobs with `every` option - One-shot tasks → BullMQ delayed jobs - Pause/Resume via task cancellation and re-scheduling through TaskManager - Survives process restarts (Redis-persisted) - Configurable concurrency via `maxConcurrentRuns` ### NodeTimeout Backend Details - Uses `setTimeout` for one-shot, `setInterval` for recurring - Cron expressions parsed with `croner` library (lightweight, no deps) - Timers are in-process — lost on restart - Task definitions persisted to disk via `FileTaskStore` — re-scheduled on startup from file - Good for: development, testing, single-process deployments --- ## Continuation Mode - How It Works Continuation mode preserves conversation context across task runs, enabling the AI to build understanding over time. ### Implementation 1. On first run, a new `sessionId` is generated and stored on the Task 2. Each run appends the task's prompt as a user message and the AI's response as an assistant message 3. The conversation messages are stored via NeuroLink's existing memory system (Redis or in-memory) 4. On subsequent runs, the full history is loaded and passed as `conversationMessages` (typed as `ChatMessage[]`) to `generate()` 5. Context compaction kicks in automatically when history exceeds budget ### Example: Progressive Monitoring ```typescript const monitor = await neurolink.tasks.create({ name: "trend-watcher", prompt: "Check current Bitcoin price. Compare with your previous observations. Report any significant trends.", schedule: { type: "interval", every: 60 * 60 * 1000 }, // Hourly mode: "continuation", tools: true, // AI can use websearch, etc. }); ``` **Run 1 output:** "Bitcoin is at $67,234. This is my first observation." **Run 2 output:** "Bitcoin is at $67,891, up 0.98% from last hour ($67,234)." **Run 3 output:** "Bitcoin at $68,102. Steady upward trend over 3 hours: $67,234 → $67,891 → $68,102 (+1.29% total)." The AI maintains awareness of all previous observations without any external state management. --- ## Persistence & Storage Storage is **automatically tied to the backend** — no separate configuration needed. ### RedisTaskStore (BullMQ backend) Used automatically when `backend: "bullmq"`. All data lives in Redis alongside BullMQ's job state. **Redis key patterns:** | Key | Type | Content | | ----------------------------- | ---- | --------------------------------------------------- | | `neurolink:tasks` | Hash | All task definitions (field = taskId, value = JSON) | | `neurolink:task:{id}:runs` | List | Run log entries (newest first) | | `neurolink:task:{id}:history` | List | Continuation mode conversation history | Run logs auto-pruned via `LTRIM` to keep the latest `maxRunLogs` entries (default 2000). Terminal-state tasks (completed, failed, cancelled) auto-expire via Redis `EXPIRE` based on `taskRetention` config (default: 30 days for completed, 7 days for failed/cancelled). Active and paused tasks **never expire**. **Production advantages:** - Multi-process safe (multiple server instances share the same tasks) - Survives container/process restarts - No file I/O — works in ephemeral containers (Docker, K8s, serverless) - Atomic operations for concurrent access ### FileTaskStore (NodeTimeout backend) Used automatically when `backend: "node-timeout"`. Data stored as human-readable files on disk. **Task definitions** (`.neurolink/tasks/tasks.json`): ```json { "version": 1, "tasks": { "task_abc123": { "id": "task_abc123", "name": "daily-report", "prompt": "Generate a daily status report", "schedule": { "type": "cron", "expression": "0 9 * * *" }, "mode": "isolated", "status": "active", "runCount": 14, "lastRunAt": "2026-03-29T09:00:02.341Z", "nextRunAt": "2026-03-30T09:00:00.000Z", "createdAt": "2026-03-15T10:00:00.000Z", "updatedAt": "2026-03-29T09:00:02.341Z" } } } ``` **Run logs** (`.neurolink/tasks/runs/.jsonl`), one line per run, append-only: ```jsonl {"runId":"run_001","status":"success","output":"Report generated...","durationMs":4523,"timestamp":"2026-03-29T09:00:02Z"} {"runId":"run_002","status":"error","error":"Provider timeout","durationMs":120000,"timestamp":"2026-03-30T09:00:00Z"} ``` Auto-pruned when entries exceed `maxRunLogs` (default 2000), keeping the most recent entries. ### Summary | Data | BullMQ (Redis) | NodeTimeout (File) | | -------------------- | ---------------------------------- | ----------------------------------- | | Task definitions | `neurolink:tasks` hash | `.neurolink/tasks/tasks.json` | | Run history | `neurolink:task:{id}:runs` list | `.neurolink/tasks/runs/{id}.jsonl` | | Continuation history | `neurolink:task:{id}:history` list | In-memory (lost on restart) | | Job scheduling state | Managed by BullMQ in Redis | In-process timers (lost on restart) | --- ## Configuration via NeuroLink Constructor ```typescript // Production: BullMQ + Redis (default) const neurolink = new NeuroLink({ tasks: { enabled: true, // Default: true (core component) backend: "bullmq", // Default: "bullmq" redis: { url: "redis://localhost:6379", // or individual fields: // host: "localhost", // port: 6379, // password: "secret", // db: 0, }, maxConcurrentRuns: 5, // Default: 5 maxRunLogs: 2000, // Default: 2000 per task }, }); // Development: NodeTimeout + files (zero-dependency) const neurolink = new NeuroLink({ tasks: { backend: "node-timeout", storePath: ".neurolink/tasks/tasks.json", // Only used with node-timeout logsPath: ".neurolink/tasks/runs/", // Only used with node-timeout }, }); ``` ### Environment Variable Overrides > **Note:** The following environment variables are **planned but not yet implemented**. They are not currently read by any code. Configuration should be done programmatically via the `NeuroLink` constructor options until these are wired up. | Variable | Purpose | Default | | -------------------------------- | ---------------------------------- | ----------------------------- | | `NEUROLINK_TASKS_ENABLED` | Enable/disable TaskManager | `true` | | `NEUROLINK_TASKS_BACKEND` | Backend selection | `bullmq` | | `NEUROLINK_TASKS_REDIS_URL` | Redis connection URL (BullMQ) | `redis://localhost:6379` | | `NEUROLINK_TASKS_STORE_PATH` | File store path (NodeTimeout only) | `.neurolink/tasks/tasks.json` | | `NEUROLINK_TASKS_MAX_CONCURRENT` | Max concurrent task runs | `5` | --- ## Retry & Error Handling ### Retry Policy - **Transient errors** (rate limits, network timeouts, 5xx): Auto-retry with exponential backoff - **Permanent errors** (auth failures, invalid config): Task marked as `failed` immediately - Default: 3 attempts with backoff at 30s, 60s, 5min ### Error Classification ```typescript // Transient (will retry) - Provider rate limit exceeded - Network timeout - 5xx server errors - Redis connection temporarily lost // Permanent (task fails) - Invalid API key - Model not found - Invalid prompt (empty, too long) - Task configuration error ``` ### One-shot vs Recurring Error Behavior | Task Type | On Transient Error | On Permanent Error | | ----------------------------- | -------------------------------------- | ------------------ | | One-shot (`once`) | Retry up to maxAttempts | Mark as `failed` | | Recurring (`cron`/`interval`) | Retry, then skip to next scheduled run | Mark as `failed` | --- ## Events TaskManager emits events via NeuroLink's existing `TypedEventEmitter`, which you reach with `getEventEmitter()` (`NeuroLink` itself has no `on()`): ```typescript const emitter = neurolink.getEventEmitter(); emitter.on("task:created", (task: Task) => { ... }); emitter.on("task:started", (task: Task) => { ... }); emitter.on("task:completed", (result: TaskRunResult) => { ... }); emitter.on("task:failed", (result: TaskRunResult) => { ... }); emitter.on("task:paused", (task: Task) => { ... }); emitter.on("task:resumed", (task: Task) => { ... }); emitter.on("task:deleted", (taskId: string) => { ... }); ``` --- ## Implementation Phases ### Phase 1: Core Infrastructure 1. Type definitions (`src/lib/tasks/types.ts`) 2. TaskBackend interface (`src/lib/tasks/backends/taskBackend.ts`) 3. TaskBackendFactory + Registry (`src/lib/tasks/backends/taskBackendFactory.ts`, `taskBackendRegistry.ts`) 4. TaskStore interface (`src/lib/tasks/store/taskStore.ts`) 5. RedisTaskStore (`src/lib/tasks/store/redisTaskStore.ts`) 6. FileTaskStore (`src/lib/tasks/store/fileTaskStore.ts`) ### Phase 2: Backends 7. NodeTimeout backend (`src/lib/tasks/backends/nodeTimeoutBackend.ts`) 8. BullMQ backend (`src/lib/tasks/backends/bullmqBackend.ts`) ### Phase 3: Orchestration 9. TaskExecutor - run engine (`src/lib/tasks/taskExecutor.ts`) 10. TaskManager - main orchestrator (`src/lib/tasks/taskManager.ts`) 11. Integration into NeuroLink class (`src/lib/neurolink.ts`) ### Phase 4: Tools & CLI 12. Built-in agent tools (`src/lib/tasks/tools/taskTools.ts`) 13. Register tools in directAgentTools 14. CLI commands (`src/cli/commands/task.ts`) ### Phase 5: Types & Exports 15. Export types from `src/lib/types/index.ts` 16. Export TaskManager from main SDK entry point --- ## Dependencies | Package | Purpose | Required By | | -------- | ----------------------- | ------------------------- | | `bullmq` | Production job queue | BullMQ backend | | `croner` | Cron expression parsing | NodeTimeout backend | | `nanoid` | Task/Run ID generation | Core (already in project) | `bullmq` is the only new required dependency. `croner` is lightweight (~5KB) for cron parsing in the NodeTimeout backend. `ioredis` is a peer dependency of `bullmq`. --- ## Security Considerations - **BullMQ mode:** Task prompts are stored in Redis. Use Redis AUTH and TLS in production. - **NodeTimeout mode:** Task prompts are stored in plaintext JSON files on disk. Manage file permissions appropriately. - Built-in tools respect NeuroLink's existing HITL (Human-In-The-Loop) manager if configured. - Task creation via AI tools can be disabled: `tools: false` in task config, or globally via `shouldDisableBuiltinTools()`. - Callbacks (`onSuccess`, `onError`) execute in the same process — do not pass untrusted code. --- ## Comparison with OpenClaw | Feature | NeuroLink TaskManager | OpenClaw Cron | | ------------------- | ---------------------------------------------------- | --------------------------------------- | | Scheduling | Cron, interval, one-shot | Cron, interval, one-shot | | Execution modes | Isolated, Continuation | Main, Isolated, Current, Custom session | | Backend | BullMQ (default), NodeTimeout | In-process scheduler | | Persistence | Redis (BullMQ) or files (NodeTimeout), auto-selected | JSON file | | Delivery | Callbacks, events | Announce (Slack/Telegram), Webhook | | AI self-scheduling | Built-in tools | System events | | SDK API | First-class | Gateway API only | | CLI | Yes | Yes | | Restart survival | Yes (BullMQ) | Yes (file-based) | | Extensible backends | Yes (Factory + Registry) | No | --- ## Example: Multi-Step Workflow via Continuation Tasks A continuation-mode task can drive an autonomous multi-step workflow. The AI remembers where it left off and progresses through steps on each run. ### Feature Implementation Workflow This example automates: write doc → review → revise → implement → create PR → resolve comments → push. ```typescript const featureWorkflow = await neurolink.tasks.create({ name: "implement-user-auth", prompt: `You are implementing a feature: "Add user authentication". Your workflow steps are: 1. Write a technical design doc (save to docs/auth-design.md) 2. Review the doc for completeness, edge cases, security concerns 3. Make revisions based on your review 4. Implement the code changes based on the final doc 5. Create a PR via GitHub MCP tools 6. Check PR for review comments 7. Address each comment, push fixes, repeat step 6-7 until resolved Rules: - Complete ONE step per run. State which step you just finished and which is next. - Use tools (readFile, writeFile, github) as needed. - If blocked, explain why and what you need. Begin from where you left off. Check your previous messages to determine current step.`, schedule: { type: "interval", every: 5 * 60 * 1000 }, // Every 5 minutes mode: "continuation", // AI remembers all previous runs provider: "anthropic", model: "claude-sonnet-4-6", tools: true, // Enable file ops, GitHub MCP, etc. maxRuns: 20, // Safety limit onSuccess: (result) => { console.log(`[Step completed] ${result.output?.slice(0, 200)}`); // Stop early if the AI signals completion if (result.output?.includes("ALL STEPS COMPLETE")) { neurolink.tasks.pause(result.taskId); } }, }); ``` **How it plays out:** | Run | AI Behavior | | --- | -------------------------------------------------------------------------------------- | | 1 | Writes `docs/auth-design.md` using `writeFile` tool. "Step 1 complete. Next: review." | | 2 | Reads the doc, identifies gaps. "Step 2 complete: found 3 issues. Next: revise." | | 3 | Rewrites sections. "Step 3 complete. Doc is ready. Next: implement." | | 4 | Reads doc, writes code across multiple files. "Step 4 complete. Next: create PR." | | 5 | Uses GitHub MCP to create PR. "Step 5 complete. PR #42 created. Next: check comments." | | 6 | Reads PR comments via GitHub MCP. "2 comments found. Next: address them." | | 7 | Pushes fixes, re-checks. "All comments resolved. ALL STEPS COMPLETE." | | — | `onSuccess` callback detects completion, pauses the task. | Because this is `continuation` mode, the AI has full context of every previous run — it knows what it wrote, what was reviewed, and what comments were left. No external state management needed. ### CLI Equivalent ```bash neurolink task create \ --name "implement-user-auth" \ --prompt "You are implementing a feature: 'Add user authentication'. ..." \ --every 5m \ --mode continuation \ --provider anthropic \ --model claude-sonnet-4-6 \ --max-runs 20 ``` --- ## Existing Code Impact TaskManager is implemented as a **new module** (`src/lib/tasks/`). Minimal changes to existing code: | Existing File | Change | Lines | | ------------------------------ | ----------------------------------- | ----- | | `src/lib/neurolink.ts` | Add `tasks` getter property | ~10 | | `src/lib/types/index.ts` | Re-export task types | ~2 | | `src/lib/agent/directTools.ts` | Import and spread task tools | ~3 | | `src/cli/index.ts` | Register `task` CLI command | ~1 | | `package.json` | Add `bullmq`, `croner` dependencies | ~2 | Everything else is **new files** in `src/lib/tasks/`. No refactoring, no restructuring of existing code. --- ## FAQ **Q: Do I need Redis to use TaskManager?** A: No. Set `backend: "node-timeout"` for a zero-dependency setup. Redis is only required for the BullMQ backend (the default). When using BullMQ, Redis stores both job scheduling state and task definitions/run logs — no file I/O at all. **Q: Will tasks stay in Redis forever?** A: No. Active/paused tasks persist as long as they're running. Once a task reaches a terminal state (completed, failed, cancelled), it auto-expires based on `taskRetention` config — defaults: 30 days for completed, 7 days for failed/cancelled. Run logs are capped at `maxRunLogs` (default 2000) per task via `LTRIM`, and individual entries can have a TTL. You can also manually delete tasks via `tasks.delete()` or `neurolink task delete`. **Q: Can the AI schedule tasks without user intervention?** A: Yes. The built-in `createTask` tool allows the AI to self-schedule tasks during any conversation. If HITL is enabled, the user will be prompted for approval. **Q: How does continuation mode handle growing context?** A: It uses NeuroLink's existing context compaction system. When conversation history exceeds the model's context budget, BudgetChecker triggers automatic summarization. **Q: Can I use TaskManager in a serverless environment?** A: The BullMQ backend works in serverless with a persistent Redis instance — no local filesystem needed. The NodeTimeout backend requires a long-running process with filesystem access. **Q: What happens when I switch backends?** A: Tasks stored in Redis (BullMQ) and tasks stored on disk (NodeTimeout) are independent. Switching backends does not migrate data. If you need to migrate, use `tasks.list()` on the old backend and `tasks.create()` on the new one. **Q: How do I monitor task health?** A: Use `neurolink.tasks.list()` / `neurolink task list` for status overview, `neurolink.tasks.runs(taskId)` / `neurolink task logs ` for run history, and subscribe to `task:*` events for real-time monitoring. --- ## Extended Thinking Configuration # Extended Thinking Configuration Enable extended thinking/reasoning modes for AI models that support deeper reasoning capabilities. This feature allows models to "think through" complex problems before providing a response. ## Overview NeuroLink supports extended thinking/reasoning configuration for models that provide this capability. Extended thinking enables models to perform more thorough reasoning, particularly useful for complex tasks like mathematical proofs, coding problems, and multi-step analysis. ## Supported Models ### Gemini 3 Models (Google Vertex AI / AI Studio) - `gemini-3.1-pro` - Full thinking support with high token budgets (up to 100,000) - `gemini-3-flash-preview` - Fast thinking with support for "minimal" level (up to 50,000) ### Gemini 2.5 Models (Google Vertex AI / AI Studio) - `gemini-2.5-pro` - Supports thinking configuration (up to 32,000 tokens) - `gemini-2.5-flash` - Supports thinking configuration (up to 32,000 tokens) ### Claude Models (Anthropic) All Claude 4.0+ models support extended thinking via budget tokens: - `claude-sonnet-4-20250514` (Claude Sonnet 4) - `claude-opus-4-20250514` (Claude Opus 4) - `claude-opus-4-1-20250805` (Claude Opus 4.1) - `claude-sonnet-4-5-20250929` (Claude Sonnet 4.5) - `claude-opus-4-5-20251101` (Claude Opus 4.5) - `claude-haiku-4-5-20251001` (Claude Haiku 4.5) - `claude-sonnet-4-6` (Claude Sonnet 4.6) - `claude-opus-4-6` (Claude Opus 4.6) ## Quick Start ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Prove that the square root of 2 is irrational" }, provider: "google-ai", model: "gemini-2.5-flash", thinkingConfig: { thinkingLevel: "high" }, }); console.log(result.content); ``` ## Gemini 3 Thinking Configuration For Gemini 3 models, use `thinkingLevel` to control reasoning depth: ```typescript const response = await neurolink.generate({ input: { text: "Prove that the square root of 2 is irrational" }, provider: "vertex", model: "gemini-3-flash-preview", thinkingConfig: { thinkingLevel: "high", // 'minimal' | 'low' | 'medium' | 'high' }, }); ``` ### Thinking Levels | Level | Description | Best For | | --------- | -------------------------------------- | ------------------------------- | | `minimal` | Near-zero thinking (Flash models only) | Simple queries requiring speed | | `low` | Fast reasoning for simple tasks | Quick analysis, summaries | | `medium` | Balanced reasoning/latency trade-off | General-purpose tasks | | `high` | Maximum reasoning depth | Complex reasoning, math, coding | ### Maximum Token Budgets by Model | Model | Max Thinking Budget | | --------------------- | ------------------- | | `gemini-3-pro-*` | 100,000 tokens | | `gemini-3-flash-*` | 50,000 tokens | | `gemini-2.5-*` | 32,000 tokens | | `claude-opus-4-6` | 100,000 tokens | | `claude-sonnet-4-6` | 100,000 tokens | | `claude-opus-4-5-*` | 100,000 tokens | | `claude-sonnet-4-5-*` | 100,000 tokens | | `claude-haiku-4-5-*` | 100,000 tokens | | `claude-opus-4-1-*` | 100,000 tokens | | `claude-opus-4-*` | 100,000 tokens | | `claude-sonnet-4-*` | 100,000 tokens | ## Anthropic Claude Thinking Configuration For Claude models, use `budgetTokens` to set the thinking token budget: ```typescript const response = await neurolink.generate({ input: { text: "Solve this complex math problem step by step..." }, provider: "anthropic", model: "claude-sonnet-4-6", thinkingConfig: { enabled: true, budgetTokens: 10000, // Range: 5000-100000 }, }); ``` ### Budget Token Guidelines - **Minimum**: 5,000 tokens - **Maximum**: 100,000 tokens - **Recommended for simple tasks**: 5,000-10,000 tokens - **Recommended for complex reasoning**: 20,000-50,000 tokens - **Maximum depth**: 50,000-100,000 tokens ### Turning thinking off Some Claude models, `claude-sonnet-5` among them, think before answering even when no `thinkingConfig` is given, and that thinking counts against the request's `max_tokens`. To turn it off for a call, pass `type: "disabled"`: ```typescript const response = await neurolink.generate({ input: { text: "Reply with one word." }, provider: "anthropic", model: "claude-sonnet-5", thinkingConfig: { type: "disabled" }, }); ``` NeuroLink sends `thinking: { type: "disabled" }` on both `generate()` and `stream()`. Turning thinking off does not change which sampling parameters a model accepts. On a model that takes a `temperature`, NeuroLink still sends it with thinking disabled; it is dropped only while thinking is on. Some models, `claude-sonnet-5` among them, do not accept a `temperature` at all, and NeuroLink leaves it off for them whatever the thinking setting. `enabled: false`, or no `thinkingConfig` at all, sends nothing, so the model's own default applies. If `enabled: true` and `budgetTokens` are also set, thinking is enabled, as before. ## Configuration Options The `thinkingConfig` object supports the following options: ```typescript thinkingConfig: { enabled?: boolean; // Enable/disable thinking type?: "enabled" | "disabled"; // "disabled" turns thinking off (Anthropic) budgetTokens?: number; // Token budget (Anthropic models) thinkingLevel?: "minimal" | "low" | "medium" | "high"; // Thinking level (Gemini models) } ``` ## CLI Usage Extended thinking is also available via the CLI: ```bash # Enable thinking with default settings neurolink generate "Solve this problem" --thinking # Set thinking budget for Anthropic neurolink generate "Complex problem" --provider anthropic --thinking --thinkingBudget 20000 # Set thinking level for Gemini 3 neurolink generate "Complex problem" --provider vertex --model gemini-3-pro-preview --thinkingLevel high ``` ### CLI Options | Option | Description | Default | | ------------------ | ----------------------------------------------------- | ------- | | `--thinking` | Enable extended thinking | false | | `--thinkingBudget` | Token budget (Anthropic: 5000-100000) | 10000 | | `--thinkingLevel` | Thinking level (Gemini 3: minimal, low, medium, high) | medium | ## Best Practices ### When to Use High Thinking - Complex mathematical proofs and calculations - Multi-step coding problems and debugging - Detailed analysis requiring multiple considerations - Tasks where accuracy is more important than speed ### When to Use Low/Minimal Thinking - Simple queries where speed matters - Straightforward information retrieval - Quick summaries and formatting tasks - High-volume, latency-sensitive applications ### General Guidelines 1. **Start with medium**: Use `medium` as your default and adjust based on results 2. **Match model to task**: Use Pro models for complex tasks, Flash for speed 3. **Monitor token usage**: Higher thinking levels consume more tokens 4. **Test performance**: Compare response quality vs. latency for your use case ## Example: Complex Reasoning Task ```typescript const neurolink = new NeuroLink(); // Complex coding problem with high reasoning const result = await neurolink.generate({ input: { text: ` Design an optimal algorithm to find the longest palindromic subsequence in a string. Explain your approach, prove its correctness, and analyze the time and space complexity. `, }, provider: "vertex", model: "gemini-3-pro-preview", thinkingConfig: { thinkingLevel: "high", }, maxTokens: 4000, }); console.log(result.content); ``` ## Model Detection Utilities NeuroLink provides utilities to check thinking support: ```typescript supportsThinkingConfig, getMaxThinkingBudgetTokens, } from "@juspay/neurolink"; // Check if a model supports thinking const supports = supportsThinkingConfig("gemini-3-pro-preview"); // true // Get maximum budget for a model const maxBudget = getMaxThinkingBudgetTokens("gemini-3-flash-preview"); // 50000 ``` ## Important Notes - **Provider compatibility**: Thinking configuration is provider-specific. Gemini uses `thinkingLevel`, Claude uses `budgetTokens` - **Token consumption**: Extended thinking uses additional tokens beyond the response - **Latency impact**: Higher thinking levels increase response time - **Not all models support thinking**: Check `supportsThinkingConfig()` before enabling - **Streaming support**: Thinking configuration works with both `generate()` and `stream()` ## See Also - [API Reference](/docs/sdk/api-reference) - [Provider Configuration](/docs/getting-started/provider-setup) - [Streaming](/docs/features/regional-streaming) --- ## Tool / MCP routing by decision model # Tool / MCP routing by decision model The shipped tool router asks a generative model for `{servers: string[]}` on a 15-second budget. That shape cannot express uncertainty — a server is in the list or it is not, and the only recourse for a model that is unsure is to include it. A [decision model](/docs/features/decide-inference-type) instead asks one calibrated yes/no question per server, in a single round trip of about 400ms and $0.00002 on TypeSafe (on Perplexity each further question adds about 65 ms, up to 128 in a request; see [its guide](/docs/getting-started/providers/perplexity-decider.md#limits); on Cloudflare Clef a request takes up to 64 questions, and `tryDecide()` splits a larger set into batches of 64; see [its guide](/docs/getting-started/providers/cloudflare-clef.md#limits); OpenAI Decisions takes up to 200 questions (the figure in OpenAI's Python SDK, not tried against the live endpoint), and `tryDecide()` splits a larger set into batches of 200; see [its guide](/docs/getting-started/providers/openai-decisions.md#what-is-sent-to-openai); ScaleDown declares no question cap, and its maximum is not measured, see [its guide](/docs/getting-started/providers/scaledown.md#not-measured)), and each answer comes back with a real probability rather than a name that either did or didn't make a list. **The degradation contract.** `selectServersByDecision()` is used only when a decision provider is configured; hosts never wire `decideFn` by hand — it is bound automatically wherever tool routing resolves, using the same `tryDecide()` that returns `null` on any failure or absent configuration. No decision provider, a failed call, fewer than two candidate servers, or an answer set that would drop nothing — any of these fall straight through to the existing generative router, unchanged. ```typescript const nl = new NeuroLink({ toolRouting: { enabled: true, minDropConfidence: 0.6, // default }, }); ``` ## One question per server Each routable server gets its own boolean question, built from its description (or, absent one, its tool names): ``` instructions: The request needs the "github" server, which can read and write GitHub issues. criteria.true: Carrying out the request involves reading and writing GitHub issues. criteria.false: The request is about something else; nothing it asks for involves reading and writing GitHub issues. ``` A server is excluded only on a confident `false` — `minDropConfidence` defaults to **0.6**. `undefined` (unanswered, malformed, or too close to a coin flip) and a confident `true` both keep the server. This is the same asymmetry as the classifier's upgrade/downgrade bars: keeping an unneeded server costs a few hundred tokens of tool definitions; dropping a needed one breaks the turn outright, because the model can never call a tool it was never shown and has no way to ask for it back. Two size guards bound the request: at most **200** servers are asked about in one batch (`MAX_SERVERS`), and the query text sent as state is capped at **10,000** characters. Servers past the cap are never asked about and are therefore always kept — a server that was not offered to the model must never be silently dropped by its own absence from the question set. NeuroLink refuses a state it estimates at more than 16,000 tokens with `max_tokens_exceeded`. A query long enough to be estimated above that is refused, and routing falls through to the generative router, as it does on any failure. ## The wording that made this work: a measured A/B result The first phrasing tried was the obvious one: "answering this request will require calling at least one tool from this server," with `false` meaning "this server is unrelated, OR the request needs no tool at all." Measured against a 10-request × 5-server labelled set, it separated correctly but weakly — unrelated servers averaged **p = 0.31** and reached as high as **0.80**, so at the 0.6 drop bar only **12 of 39** unneeded servers were actually dropped. Three changes fixed it: naming the server explicitly, asking in the present tense about what carrying out the request _involves_ rather than what "will require," and splitting the bundled `false` criterion (which was really two separate claims joined by "or") into one single claim. That moved unrelated servers to a mean of **p = 0.03** with a maximum of **0.35** — **37 of 39** dropped at the same 0.6 bar, still with **zero wrong drops**. The lesson generalises past this one question: a decision model reads literally, and an "or" in a criterion is two questions wearing one coat. Each half of a compound criterion pulls the answer toward the middle whenever only one half is true, which is exactly the muddy, hard-to-gate signal the first version produced. ## What this is bad at - **It reasons about servers, not individual tools.** The unit of decision is a whole MCP server; a server with twenty tools where the request needs one is kept or dropped as a unit, not tool-by-tool. - **The description quality bounds the question quality.** A server with no declared description falls back to a comma-joined list of its own tool names, which carries much less signal than a well-written one-line description — the wording fix above only helps once the server's own text is legible to a literal reader. - **A close call still resolves to "keep."** There is no partial exclusion; anything from a coin flip up to just under 0.6 confidence is treated identically to a confident `true`. - **It shares the base model's general limits** — literal reading, no arithmetic, accuracy sensitive to a noisy or oversized state — all described in [what `decide` is bad at](/docs/features/decide-inference-type#what-it-is-bad-at). - **The query is untrusted input sent as state**, and this module does not sanitize it. The reach is deliberately bounded, not zero. Server ids are never read back off the wire (answers are matched by position, not by name), so a crafted query cannot name a tool that was not already registered, and the result is only a denylist appended to `excludeTools`. It can still steer a verdict: a confident `false` (0.6 by default) withholds that server's tools for the turn. Do not rely on this router as a security control; see the Untrusted input bullet under [what `decide` is bad at](/docs/features/decide-inference-type#what-it-is-bad-at). ## See also - [The `decide` inference type](/docs/features/decide-inference-type) - [Model routing with a decision model](/docs/features/classifier-router-jev-strategy) - [Relevance-driven compaction](/docs/features/relevance-compaction) --- ## The transcribe inference type # The `transcribe` inference type NeuroLink has four inference types. `transcribe` is the one that starts from audio: | Type | Call | Produces | | ---------------- | --------------------------------------------------- | -------------------------------- | | `generate` | `neurolink.generate()` | text | | `stream` | `neurolink.stream()` | text, incrementally | | `decide` | `neurolink.decide()` | typed judgements | | **`transcribe`** | **`neurolink.transcribe()` / `transcribeStream()`** | **text from audio, with timing** | It runs through any registered speech-to-text (STT) engine and adds the layers that make an engine usable on real speech: a **dictionary** of names and jargon, a **correction** pass guarded by the decision model and finished by an LLM rewrite, a **second-opinion** engine, a **fallback** engine for audio the first one cannot read, and **client-side streaming** for engines that only take whole files. **Zero configuration.** With no STT provider configured, `transcribe()` uses **Whistle**, the built-in local engine: it runs on this machine, needs no key and no network; its model files (about 18 MB) ship inside the package. Whistle reads English, German, French, Spanish, Italian, Dutch and Polish; for other languages, accents, noisy rooms or heavy jargon, configure a cloud or self-hosted engine, or add a dictionary and correction. ## SDK > **Security:** `audio` given as a URL must be HTTPS to a public host (set > `attachments.allowInsecureUrls` / `allowPrivateNetwork` on the instance to > relax that) and is capped while it downloads; `audio` given as a path is > bounded by `attachments.allowedRoots` when configured. See > [Attachment Security](/docs/features/attachment-security). ```typescript const neurolink = new NeuroLink(); const result = await neurolink.transcribe({ audio: "./meeting.wav", // Buffer, Uint8Array, path, file:// or http(s):// URL }); console.log(result.text); console.log(result.engine, result.language, result.timings, result.steps); ``` `audio` accepts bytes (`Buffer`, `ArrayBuffer`, `Uint8Array`), a path, a `file://` URL or an `http(s)://` URL. The container is inferred from the path or the bytes; pass `format` (`"wav"`, `"mp3"`, `"m4a"`, `"ogg"`, `"opus"`, `"webm"`, `"flac"`, `"mp4"`, `"pcm16"` …) for a buffer it cannot be read from. ### Options | Option | Meaning | | ---------------- | --------------------------------------------------------------------------------------------------------------------------------- | | `provider` | STT provider name or alias. Default: `NEUROLINK_STT_PROVIDER`, then the first configured provider, then Whistle. | | `model` | Model of that provider. Default: `NEUROLINK_STT_MODEL`, only when the provider also came from the environment. | | `language` | Language code or locale, or `"auto"`. Default: `NEUROLINK_STT_LANGUAGE`, else the engine detects it. | | `prompt` | Context prompt for engines that bias on one; dictionary terms are appended to it. | | `diarization` | Label speakers, on engines that diarize. | | `wordTimestamps` | Ask for word-level timings. | | `dictionary` | Names and jargon, see [Dictionary](#dictionary). | | `correction` | The correction layer, see [Correction](#correction). | | `fallback` | `{ provider, model?, when? }`, see [Fallback](#fallback-and-second-opinion). | | `streaming` | Tuning for `transcribeStream()`, see [Streaming](#streaming). | | `timeoutMs` | Whole-call timeout. | | `credentials` | Per-call credentials; the `stt` slice (`credentials.stt.whisper.apiKey`, `credentials.stt.deepgram.apiKey` …) beats the env vars. | ### Result `TranscribeResult` is the engine's `STTResult` (`text`, `confidence`, `language`, `duration`, `words`, `segments`, `speakers`, `metadata`) plus what the layers did: | Field | Meaning | | ------------------ | -------------------------------------------------------------------------------------------------------- | | `raw` | The engine's text before any correction. | | `text` | The final text — the corrected text when correction changed it, else `raw`. | | `corrected` | Present only when correction changed the text. | | `languageDetected` | `false` when the engine reported a low language-detection score. | | `languageScores` | Candidate languages with the engine's own scores, where it reports them. | | `decisions` | One record per dictionary candidate: what was heard, the term, `term` or `literal`, and the probability. | | `engine` | `{ provider, model, fallbackUsed?, secondOpinion? }`. | | `timings` | `transcribeMs`, `secondOpinionMs`, `decideMs`, `rewriteMs`, `correctionMs`, `totalMs`. | | `steps` | A readable trail: `"dictionary 2/2"`, `"rewrite timed out · kept text"` … | ## Providers and environment | Provider (aliases) | Configured by | Notes | | --------------------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------- | | `whisper` (`openai-stt`, `openai-compatible`) | `OPENAI_STT_API_KEY` or `OPENAI_API_KEY`; `OPENAI_STT_BASE_URL` for another server | Any OpenAI-compatible `/audio/transcriptions` endpoint. | | `deepgram` | `DEEPGRAM_API_KEY` | Native streaming. | | `elevenlabs-stt` (`scribe`, `elevenlabs`) | `ELEVENLABS_API_KEY` | | | `google-stt` | `GOOGLE_API_KEY`, `GOOGLE_AI_API_KEY`, `GEMINI_API_KEY` or `GOOGLE_APPLICATION_CREDENTIALS` | | | `azure-stt` | `AZURE_SPEECH_KEY` | | | `whistle` (`local`) | nothing | Built-in, local, always available. | The order of that table is precedence: without `provider` or `NEUROLINK_STT_PROVIDER`, the first configured provider is used, and Whistle only when none is. | Variable | Effect | | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `NEUROLINK_STT_PROVIDER` | Default provider for `transcribe()`, `transcribeStream()`, the CLI and the server routes. | | `NEUROLINK_STT_MODEL` | Default model, applied with the provider from `NEUROLINK_STT_PROVIDER` / auto-selection. | | `NEUROLINK_STT_LANGUAGE` | Default language when a call does not name one. | | `NEUROLINK_WHISTLE_DIR` | Where Whistle keeps its model files. Default: the copy shipped in the package (`models/whistle/`), else `~/.neurolink/models/whistle`. | | `NEUROLINK_WHISTLE_AUTO_DOWNLOAD` | `0` forbids fetching the files into `~/.neurolink/models/whistle`; with the bundled copy present nothing is ever fetched. | | `FFMPEG_PATH` | ffmpeg binary for compressed input to Whistle and for `--stream` on non-WAV files. | ## Dictionary A dictionary teaches the pipeline the words an engine cannot know — product names, people's names, internal jargon — and how engines tend to mis-hear them: ```json [ { "term": "Acme Pay", "heardAs": ["acne pay", "ack me pay"], "meaning": "the company's payments product" }, { "term": "Kubernetes", "heardAs": ["cooper netties"] } ] ``` | Field | Required | Use | | --------- | -------- | ------------------------------------------------------------------------------------------------- | | `term` | yes | The correct spelling, written exactly like this in the output. | | `heardAs` | no | Mis-hearings, in any script. Each one found in a transcript becomes a candidate for replacement. | | `meaning` | no | What the term means, given to the decision model and the rewrite so they can tell term from word. | The dictionary is used three ways: its terms are sent to engines that take a prompt or vocabulary, each `heardAs` found in the transcript becomes a candidate repair, and the whole list is given to the rewrite model. ## Correction ```typescript const result = await neurolink.transcribe({ audio: "./standup.m4a", dictionary, correction: { rewrite: { provider: "", model: "" }, transliterate: "latin", context: "A daily engineering stand-up about the payments service.", }, }); ``` Correction runs on a finished transcript (or on each final utterance when streaming), in two stages: 1. **Dictionary, guarded.** Each candidate is put to the decision model as one question — did the speaker mean the term, or the ordinary word? — so a product name never rewrites the everyday word it sounds like. All candidates go in one `tryDecide()` call. With no decision provider, on a timeout (`decideTimeoutMs`, default 4000) or on any error, the dictionary is applied as is. `guard: "none"` always applies it. The guard asks for the default decision provider, and it sends the first 4,000 characters of the transcript to it. A lone `OPENAI_API_KEY` counts as one (it is also Whisper's key), so a host that set it only for Whisper and passes a dictionary sends the transcript text to OpenAI's Decisions endpoint, unless `OPENAI_BASE_URL`, `OPENAI_API_BASE` or `credentials.openai.baseURL` names a host other than `https://api.openai.com` (a gateway's key is not used for the default); see [One key, two providers](/docs/getting-started/providers/openai-decisions.md#one-key-two-providers). `SCALEDOWN_API_KEY`, which no other provider reads, counts too: with it as the only decision key, the transcript text goes to ScaleDown, the last provider in the order. 2. **Rewrite.** A text model fixes spelling, punctuation and capitalisation, writes dictionary terms correctly, reconciles a second opinion and writes Indic-script words in Latin letters the way people type them (Hinglish, Tanglish …) — never translating them. `transliterate: "native"` keeps the original script. `rewrite: false` stops after the dictionary. | Option | Default | Meaning | | ------------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `enabled` | on with a dictionary or any `correction` object, unless it is only `rewrite: false` | Run the layer at all. | | `guard` | `"decide"` | `"decide"` asks the decision model per candidate; `"none"` always applies. | | `decideTimeoutMs` | 4000 | Guard timeout. | | `rewrite` | `"auto"` | `"auto"` runs the rewrite only when there is something for it to do (see below); `{ provider?, model?, timeoutMs?, mode? }` names the text model (`mode: "always"` runs it every time); `false` stops after the dictionary. | | `perSentence` | `true` | Correct a final sentence by sentence (see below). `false` keeps one whole-text pass. | | `transliterate` | `"latin"` for Indian languages, `"native"` for any other known language | `"latin"` or `"native"`. Unset, Arabic, CJK, Cyrillic … text keeps its script; Urdu still romanises like the other Indian languages. | | `punctuate` | `true` | Punctuation and capitalisation in the rewrite. | | `secondOpinion` | none | `{ provider, model? }`, or `"auto"` to use the `fallback` engine — see below. | | `contextUtterances` | 0 (off) | Corrected utterances before this one that the rewrite sees as read-only context (streaming and `chunking: "utterances"`). Opt-in: a rewrite that copies context is refused by the added-words guard. | | `context` | none | One sentence about who is talking and about what. | | `maxDropRatio` | 0.25 | A rewrite that drops more than this share of the words is discarded. | ### When the rewrite runs, and on what With `rewrite: "auto"` (the default) each text is checked before the model is called, and the rewrite runs only when it has a job: a second opinion to reconcile, a dictionary term that was applied, non-Latin script when Latin output is requested, or a sentence of four or more words with no terminal punctuation and `punctuate` on. An English sentence that arrived clean from the engine therefore costs nothing after the dictionary, and `steps` says `rewrite skipped · nothing to change`. `mode: "always"` restores the old behaviour. With `perSentence` (the default) a final is split on terminal punctuation and the danda, and each sentence goes through the dictionary and its own rewrite decision, three sentences at a time. A Hindi sentence followed by an English one is romanised and left alone respectively, the English sentence never waits for the Hindi one, and `steps` reports `per sentence (n)` with how many sentences were rewritten, skipped or kept. A second opinion is whole-utterance by nature and keeps the single pass. ### The rewrite knows the language The detected language of each utterance picks the rewrite's rules. Indian languages, English and speech whose language is unknown keep the Hinglish / Tanglish prompt above. Any other known language (Spanish, Japanese, Arabic …) gets a general post-editing prompt in that language: fix mis-hearings, keep the language and its own script, never translate. When streaming, the last `contextUtterances` corrected utterances travel with each rewrite as read-only context, so a name spelled one way stays spelled that way and the script does not drift between sentences. ### Guards on what the engine said Two things a speech engine produces that were never said are caught before the dictionary or the rewrite see the text, on every pass, live or file: - **A decoding loop** ("Same one. Same one. …" for hundreds of words, which a long-form engine can fall into on a long or noisy chunk) is collapsed to two occurrences; natural repeats of up to three stay. `steps` reports `repetition collapsed (n words)`. On a file, an utterance that was mostly loop is re-run as two halves, since the loop belongs to the chunk, not the speech. - **A prompt echo**, an engine answering a pause with the vocabulary prompt it was given ("Names and terms used: …", or a list of two or more terms), is discarded as no text (`prompt echo discarded`) and the empty path takes over. A speaker who says a single term ("Juspay.") is kept. The term list is sent to every OpenAI-compatible server; set `vocabularyPrompt: false` on an endpoint that echoes it (`OPENAI_STT_VOCABULARY_PROMPT=0` for the `whisper` slice). - **A near-silent utterance** (under a quarter speech) whose whole output is a word or two in a script the session has not spoken is reported as silence, not text. With the speech detector on, so is a short utterance whose text would mean more than twelve words per second of detected speech. ### Clean verbatim `correction: { cleanup: "clean" }` lets the rewrite remove fillers ("um", a meaningless "like"), stutters ("they they they") and restarted false starts, and never content; in that mode the rewrite may drop up to half the words (`maxDropRatio` still overrides). The default, `"verbatim"`, keeps every word as said. ### Nothing is ever dropped Every layer fails open, and none may lose words: - A rewrite that drops more than `maxDropRatio` of the words is discarded and the dictionary-applied text is kept. - A rewrite that times out, fails or returns nothing keeps the text it was given. - A guard that times out or fails applies the dictionary as is. - When streaming, a final pass that returns less than the live text keeps the live text, and an utterance no engine could read is reported as a `silence` event with its length rather than disappearing. - `raw` always holds the engine's own text, so a caller can show or diff it. Each of those outcomes is written to `steps`, so a degraded path is visible rather than silent. ## Fallback and second opinion ```typescript await neurolink.transcribe({ audio, provider: "", fallback: { provider: "whisper", when: ["unsure", "empty", "error"] }, correction: { secondOpinion: { provider: "whisper" } }, }); ``` - **Fallback** takes the request (or, when streaming, the utterance) when the primary engine cannot read it: `when` defaults to `["unsure", "empty"]` — a low language-detection score, or no text — and `"error"` adds engine failures. `engine.fallbackUsed` says when it ran. - **Second opinion** runs a second engine on the same audio in parallel; the rewrite reconciles the two transcripts, taking each language's words from the engine that reads it better. When the primary reports an unsure language, or no text, the second opinion's text leads. With `rewrite: false` that is all it does — there is no reconciliation without the rewrite. `secondOpinion: "auto"` uses the `fallback` engine: with an Indic primary and an English-oriented fallback, every utterance the primary leads is also read by the fallback, and the rewrite takes Indian-language words from one and English words from the other. One extra engine call per utterance, run in parallel with the final pass. ### Files through the live pipeline ```typescript await neurolink.transcribe({ audio: "./meeting.wav", provider: "indic", fallback: { provider: "spark" }, chunking: "utterances", }); ``` By default a recording goes to the engine whole (`chunking: "engine"`). With `chunking: "utterances"` it goes through the same pipeline as live captions: the endpointer cuts it into utterances, each utterance gets the language probe and its own engine, the dictionary with the decision guard and the per-sentence correction, three utterances at a time (`streaming.concurrency`), with a failed final tried once more (`streaming.finalRetries`) and a 180 s engine timeout instead of the live 30 s. The result has one `segment` per utterance with its `language`, and `steps` reports how many utterances the fallback took and any the engines could not read (reported, never dropped). A mixed-language recording gets the right engine per utterance; an English-only one costs the same as before. Needs WAV, or ffmpeg on the server for other containers. The OpenAI-compatible route takes it as the `chunking=utterances` form field. The same pipeline is available over the WebSocket with `mode: "file"` in the first frame: send the whole recording's PCM as fast as the socket takes it, then `{"type":"end"}`, and receive `final` and `corrected` per utterance as they finish. No request time limit applies, and up to 512 MB of audio (about 4.5 hours) may be queued. File-mode utterances are cut at 20 s (12 s at a pause) rather than the live 28 s. ### Routing: the probe and the prior With a fallback set, the engines are not tried one after the other: ```typescript await neurolink.transcribe({ audio, provider: "indic", fallback: { provider: "spark" }, routing: { probe: true, lockAfterPasses: 2, prior: "carry" }, // the defaults }); ``` - **Streaming probe.** The first pass of every utterance (from about 1.2 s of audio) runs the primary and the fallback **in parallel**. When the primary reports an unsure language, or nothing, and the fallback produced mostly Latin-script words, the fallback leads the utterance from that moment; a primary that is confident on two probes locks (or on one, when the fallback had no words to offer). By default the second pass probes again (`lockAfterPasses: 2`), so a Hindi utterance misjudged at 1.2 s is handed back to the Indic engine once it is sure, and words always beat an empty answer whatever the script. Verdicts that disagree buy one more probe: a language score on two or three seconds of audio jitters (an English clip scored −0.46, −0.16 and −0.44 on consecutive passes against a −0.18 threshold), so one confident verdict after an unsure one never settles an utterance by itself. English spoken into an Indic engine shows Latin captions about 1.5 s after the first word instead of 5 s. The older rule (two unsure passes after 3 s; two confident passes rule it out for good, one only delays it) stays as a safety net for utterances the probe locked on the primary. `lockAfterPasses` keeps both engines running for more passes before locking; `probe: false` disables the probe. - **Batch probe.** When the primary engine has a language-only model (`lidModel` on its endpoint; the IndicConformer wrapper serves `-lid`), it is asked for a verdict on the first eight seconds, in about 200 ms, before anything is transcribed. Unsure sends the recording to the fallback without a full primary pass; confident runs the primary alone. A pinned `language` skips the probe. - **Prior.** The last language an engine was confident about is carried into the next utterance (`prior: "carry"`), for engines that take one: an endpoint with `priorLanguageForm: "auto-{lang}"` receives `language=auto-hi` after a Hindi utterance, so a borderline next sentence is read as Hindi rather than flipping to a neighbour. The prior is never sent to the fallback, never sent when `language` is pinned, and never sent to a server that did not declare the form. - **Language → engine table.** `routing.engines` names the engine for each language, `"*"` for the rest: ```typescript routing: { engines: { hi: "indic", ta: "indic", en: "spark", "*": "spark" } } ``` A pass whose detected language belongs to another engine is read again by that engine (with the language as its prior), and the rest of the utterance goes straight to it. Its text is used when it heard words and reads the language; otherwise the original text stays. Batch transcription does the same for the whole recording. A pinned `language` turns routing off. The final names the engine that wrote it, and `steps` records `routed hi → indic`. - **Level.** Quiet utterances are raised to a normal speech level before any engine hears them (gain only goes up, at most 8×, limited by the peak, so nothing clips and digital silence stays silent). `streaming.normalize: false` sends the audio as captured. ## Output languages Every utterance can also be written in other languages and scripts: ```typescript const result = await neurolink.transcribe({ audio, output: { languages: ["es", "hi-Latn", "source"] }, }); result.text; // the transcript, exactly as without `output` result.outputs?.es; // { language: "es", text, status: "ok", ms, segments? } result.outputs?.["hi-Latn"]; // Hindi in Latin letters, whatever was spoken ``` Each entry is a BCP-47 tag: a language (`es`, `ta`), optionally a script (`hi-Latn` is Hindi written in Latin letters, the way people type it) and a region (`fr-CA`). `"source"` is the transcript itself. Up to eight per request. - **One call per utterance.** A single structured call renders every requested language (four per call; more run in parallel). It gets both the native-script engine text and its corrected form, so a translation is never made from romanised text alone, the earlier utterances and their renderings as context (`contextUtterances`, default 3), and the dictionary terms as a glossary kept verbatim (`glossary: false` turns that off). - **No call when there is nothing to do.** `"source"`, and a target in the transcript's own language and script, are the corrected text (`status: "same-language"`). - **Guards.** An answer that is empty, in the wrong script for its tag, or the source handed back untranslated is refused; a refused target gets one retry on its own, then `status: "rejected"` with a `reason`. - **Never costs the transcript.** Rendering runs after the text is settled and fails open: `text`, `final` and `corrected` are what they would be without it. Statuses: `ok`, `same-language`, `timeout`, `error`, `rejected`, and `partial` for a long recording where some batches rendered. - **Long recordings** are rendered per segment (20 segments per call), so `outputs..segments` line up with `result.segments` and their timings. - **Model.** `output.provider` / `output.model`, else `NEUROLINK_STT_OUTPUT_PROVIDER` / `NEUROLINK_STT_OUTPUT_MODEL`, else the rewrite's model. Translation quality follows the model; a stronger one than the rewrite's is usually worth it. `timeoutMs` defaults to 15000. When streaming, each utterance's renderings arrive as `output` events, one per language, after its `corrected` event (`basedOn: "corrected"`) or after the `final` when correction is off. `output.languages` may also be a live source — `{ current(): string[] }` — read once per utterance, which is how a socket's control frames and a session's listeners change the languages mid-stream. ### Sessions: one call, many listeners ```typescript const session = new TranscriptionSession(neurolink, { id: "standup" }); const es = session.subscribe({ languages: ["es"] }, (event) => show(event)); session.subscribe({ languages: ["hi-Latn"], speakers: ["alice"] }, render); await Promise.all([ session.addSpeaker("alice", { audio: aliceFrames, provider: "indic", fallback: { provider: "spark" }, }), session.addSpeaker("bob", { audio: bobFrames }), ]); ``` Each speaker is one `transcribeStream()` (call platforms give one track per participant). The session renders each utterance once into the **union** of the languages its listeners read right now: ten listeners in Spanish cost one rendering, a language nobody reads costs nothing. A listener receives every event of the speakers it follows, tagged with `speaker`, and only the `output` events of its own languages; `interim: false` drops live captions. `subscription.update({ languages })` changes them from the next utterance. A listener who joins late gets the backlog — the last `backlog` (default 50) utterances with every rendering already made for them; a language added later applies from the next utterance on. ## Streaming ```typescript for await (const event of neurolink.transcribeStream({ audio: micFrames, // AsyncIterable of PCM16LE mono streaming: { sampleRate: 16000 }, dictionary, })) { if (event.type === "interim") render(event.committed, event.tail); if (event.type === "final") commit(event.text); if (event.type === "corrected") replace(event.utterance, event.text); } ``` Engines with a native stream use it; every other engine is streamed on the client by a chunked adapter (a speech detector finds utterances, the current utterance is re-transcribed every `intervalMs`, and the prefix two passes agree on is committed). `streaming.mode: "chunked"` forces the adapter. | Event | Carries | | ------------ | ---------------------------------------------------------------------------------------------- | | `interim` | The utterance's current `text`, split into `committed` (stable) and `tail` (may still change). | | `language` | The detected language and whether the engine was sure. | | `final` | The utterance's final text, segment and words, the engine, and whether the fallback took it. | | `correcting` | Partial text of the streamed rewrite. | | `corrected` | The corrected text, its `raw`, decisions, steps and timings. | | `silence` | An utterance no engine could read, with its length. | | `error` | A message, and `recoverable: true` when the stream carries on with the next utterance. | Tuning (`streaming`): `sampleRate` (16000), `endSilenceMs` (750), `intervalMs` (900), `softCutSeconds` (16), `maxUtteranceSeconds` (28), `onsetRms` (0.006), `prerollMs` (350), `minSpeechMs` (250). **The speech detector** (`streaming.vad`). By default the adapter runs [Silero VAD](https://github.com/snakers4/silero-vad) over the stream: a 2.3 MB ONNX model (MIT, 6000+ languages) that scores every 32 ms frame with the probability that it is a human voice, which an energy gate cannot tell from a chair, a keyboard or a far-away TV. The model ships with the package under `models/silero-vad/` and runs through the optional dependency `onnxruntime-node` (prebuilt for Linux, macOS and Windows on x64 and arm64, about 0.1 ms per frame). When either is missing the energy gate takes over, with one warning in the log. `vad.engine` is `"auto"` (that), `"silero"` (an error when it cannot load) or `"energy"`; `NEUROLINK_STT_VAD` sets the default. An utterance opens after `vad.startMs` (120) of consecutive frames at or above `vad.onset` (0.6) — the pre-roll keeps that audio — and a frame counts as speech at or above `vad.sustain` (0.35). Every `final` and `silence` event says which detector found the utterance (`vad`) and how much of it was speech (`speechSeconds`). With the detector on, the engine is also spared the closing pause: audio more than 300 ms after the last speech frame is not sent (and every chunk any engine gets ends in 400 ms of digital silence, because a chunk cut off right after speech sent Qwen3-ASR into a decoding loop until its timeout), and a short utterance whose text would mean more than twelve words per second of detected speech is reported as `silence`, since that is an engine filling a pause with a stock phrase, not a sentence. `minSpeechMs`, the near-silence rule and the language thresholds all count the detector's speech, not energy. ## Getting good results The layers above are generic; which engine to point them at, and what to expect from each, is not. The numbers below were measured on 2026-10-07 on a laptop (Apple Silicon) through `neurolink serve`: Whistle in-process, an IndicConformer wrapper on the same machine, and Qwen3-ASR ("spark") on a GPU box behind LiteLLM; the guard is a System One decision model, the rewrite an `open-fast` chat model, both over the network. Your numbers will differ, the ratios will not. ### Pick the engine by what is said | Engine | Good at | Weak at | Batch speed | | --------------------------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ----------------- | | `whistle` (built in, no network) | English and six European languages, clean speech, long files (5 min in 15 s) | Anything else: it will produce fluent English that is not what was said | ~18–20× real time | | IndicConformer (`indic` endpoint) | 22 Indian languages in native script, code-mixed Hindi/English, language auto-detect | English-only or non-Indian speech: it reports `languageDetected: false` and returns little | ~28× real time | | Qwen3-ASR (`spark` endpoint) | Mixed-language speech, Hinglish in Latin letters, long files, jargon | Slowest of the three; Tamil/Kannada phonetics are approximate | ~5–9× real time | | `elevenlabs-stt` | Hosted, 90+ languages, speaker diarization | Needs a key and the network | network bound | Two patterns cover most rooms: - **Indian languages with English in the mix:** `provider: "indic"` with `fallback: { provider: "spark" }`. Indic answers when it is sure; when it reports `languageDetected: false` or comes back empty (an English-only meeting, for instance) the fallback takes over and the result says so in `steps` (`fallback spark (unsure)`). Measured on a 45 s English meeting: Indic alone returned nothing, Indic + fallback returned all 156 words. - **English, offline, no keys:** `whistle`, which is also what you get with nothing configured. Pin `language` when you know it; `auto` costs a detection pass on Indic and lets a short utterance be mis-detected. Send 16 kHz mono where you can: every engine resamples to it, and the stream requires it. ### A file is transcribed whole; a stream is cut into utterances `transcribe()` and both POST routes hand the **entire recording** to the engine in one request. Whistle and the Indic wrapper split long audio on silence internally; Qwen3-ASR takes it whole; none of them need you to chunk, and the measured 5-minute file came back complete from all three (851, 849 and 849 words). The one limit is the upload: `bodyParser.rawMaxSize` (64 MB; `neurolink serve --max-upload`) on the multipart route and the JSON body limit (10 MB) on the envelope route, so send long recordings as multipart, or raise the limit. Correction then runs **per segment line** (the engine's segments, or sentences), so a dictionary term found in minute four is judged on its own sentence, not on five minutes of context; set `NEUROLINK_STT_CORRECT_WHOLE=1` to correct the whole text in one pass instead. `transcribeStream()` and the WebSocket are what the demo's **Live** page uses, and they work differently: audio arrives as 20 ms blocks, a speech detector (Silero VAD, or an energy gate with a noise-floor estimate when it is not available) finds **utterances** (speech onset, 750 ms of silence to close, soft cut at 16 s, hard cut at 28 s with the remainder carried over), the open utterance is re-transcribed every 900 ms (`interim` events, with the prefix two passes agreed on as `committed`), and when it closes you get one `final`. The dictionary, the guard and the rewrite then run on **that utterance** and come back as one `corrected` event, which is why the demo shows a sentence appear, then change a word or two about a second later. A stream never waits for the whole recording, and nothing is held back: an utterance no engine could read is reported as `silence` with its length. ### Dictionary and correction: what they cost and when to use which | Configuration | Adds to a 10 s clip | What you get | | -------------------------------------------------------- | -------------------- | --------------------------------------------------------------------------------------------- | | `dictionary` only (`correction: { rewrite: false }`) | ~0.1 s per candidate | Each `heardAs` hit is judged by the decision model (term or literal) and replaced when a term | | `dictionary` + rewrite (`correction: { enabled: true }`) | +0.4–1.7 s | The judged text is then rewritten for punctuation, casing and script by a chat model | | `correction.guard: "none"` | ~0 s | Dictionary applied without asking; use when every alias is unambiguous | | `transliterate: "latin"` | inside the rewrite | Hinglish in Latin letters from a Devanagari engine (Indic → `khaali meeting hai at three pm`) | Write `heardAs` in the script the engine actually emits: Devanagari aliases for Indic (`"न्यूरोलिंक"`), Latin for Whistle and Qwen3-ASR (`"nurellink"`, `"neural link"`). A `meaning` helps the guard decide between a product name and a common word. The decision model is asked per candidate and fails open: with no decision provider configured the dictionary is applied as is and every decision carries a `note` saying so. The rewrite is the one layer that can change words, so it is bounded: a rewrite that drops more than a quarter of the words, times out or errors is discarded and `steps` says `kept text`. With a weak engine on the wrong language the rewrite will "fix" nonsense into fluent nonsense (Whistle on Tamil becomes "Now like a meeting, Iraqi Mondo Muniki…"); the fix is the engine, not the corrector. ### Latency to expect Batch, `POST /api/agent/transcribe`, median of three runs, server-side `timings` in ms, 9–11 s clips: | Engine | Clip | Engine | Guard | Rewrite | Total | × real time | | ------- | -------- | -----: | ----: | ------: | ----: | ----------: | | whistle | English | 535 | 145 | 564 | 1636 | 6.5× | | whistle | Hinglish | 457 | – | 507 | 962 | 9.4× | | indic | Hinglish | 323 | 107 | 1162 | 1607 | 5.6× | | indic | Tamil | 356 | – | 897 | 1282 | 8.3× | | spark | English | 1187 | – | 445 | 1809 | 5.9× | | spark | Hinglish | 1667 | – | 918 | 2447 | 3.7× | | spark | Tamil | 2067 | – | 444 | 2781 | 3.8× | Raw (no correction) is the Engine column alone: Whistle ≈ 0.5 s, Indic ≈ 0.35 s, Spark 1.2–2.1 s for ten seconds of audio. The guard column is blank when no dictionary alias was heard; it is ~100–150 ms when one was. Streaming, WebSocket, 100 ms frames paced in real time: | Engine | First interim | Final after end of speech | Corrected after final | | ------- | ------------: | ------------------------: | --------------------: | | whistle | ~1.0 s | ~0.5 s | ~0.5 s | | indic | ~0.8 s | \ --transliterate latin neurolink transcribe talk.wav --word-timestamps --format srt > talk.srt cat clip.wav | neurolink transcribe - --stream ``` The text output is the transcript, then a dim line with the engine, the language (`detected` or `unsure`), the audio length, each layer's time and the steps. `--format json` prints the whole `TranscribeResult` (one event per line with `--stream`); `--format srt|vtt` builds subtitle cues from the segments, or from the word timings. `--stream` decodes the file to 16 kHz mono PCM16 (WAV in process, anything else through ffmpeg) and runs it through `transcribeStream()`. Credentials are env-only, as for every CLI command. The full flag table is in the [CLI reference](/docs/cli/commands.md#transcribe). ## Server routes `createAllRoutes()` / `registerAllRoutes()` mount two routes on every adapter (Hono, Express, Fastify, Koa); `createTranscribeRoutes(basePath, options)` mounts them on their own. Neither accepts credentials: engines use the server's own configuration, and a `credentials` field in a body is ignored. ### `POST /api/agent/transcribe` JSON body with exactly one audio source: ```json { "audio": "", "format": "wav", "provider": "", "language": "auto", "dictionary": [{ "term": "Acme Pay", "heardAs": ["acne pay"] }], "correction": { "rewrite": { "model": "" } }, "fallback": { "provider": "" }, "diarization": false, "wordTimestamps": true } ``` | Source | Rules | | ----------- | ------------------------------------------------------------------------------------------------------------------------------- | | `audio` | Base64, or a `data:audio/...;base64,` URL. Bounded by the adapter's JSON body limit (`bodyParser.jsonLimit`, 10 MB by default). | | `audioUrl` | An `http(s)` URL the server downloads through the SSRF guard (private addresses and redirects refused), capped in size. | | `audioPath` | A path on the server. **Refused by default**; allowed only inside the directories in `transcribe.allowedAudioRoots`. | The response is the `TranscribeResult`, in the adapters' usual `{ data, metadata }` envelope. Errors use the usual error shape: 400 for an invalid body or an unsupported provider, language or format, 403 for a refused `audioPath`, 413 for audio over the limit, 500 for an engine failure. ### `POST /v1/audio/transcriptions` (OpenAI-compatible) `multipart/form-data`, the way OpenAI's API takes it, so an OpenAI client pointed at `http://:/v1` works unchanged: | Field | Meaning | | --------------------------- | ----------------------------------------------------------------------------------------------------------- | | `file` | The audio (required). Its name or type sets the container. | | `model` | `` or `/`. OpenAI's own model names and `auto` mean the server's default engine. | | `language`, `prompt` | As in the SDK. | | `response_format` | `json` (`{ "text" }`, the default), `text` (plain text) or `verbose_json`. | | `timestamp_granularities[]` | `word` requests word timings. | | `temperature` | Accepted and ignored. | | `provider` | Extension: the STT provider, overriding `model`. | | `diarize` | Extension: `true` labels speakers. | | `dictionary` | Extension: the dictionary as a JSON string. | | `correct` | Extension: `true` runs the correction layer. | | `fallback` | Extension: fallback STT provider. | | `second_opinion` | Extension: second-opinion STT provider (turns correction on). | `verbose_json` returns OpenAI's shape — `task`, `text`, `language`, `duration`, `segments[]` (`id`, `start`, `end`, `text`), `words[]` (`word`, `start`, `end`) — plus NeuroLink's extras: `raw`, `corrected`, `decisions`, `engine`, `language_detected`, `steps` and `timings`. Errors use OpenAI's error shape. The upload is bounded by the adapter's `bodyParser.rawMaxSize` (by default `bodyParser.maxSize` when that is set, else 64 MB). Route options (`registerAllRoutes(server, "/api", { transcribe: { ... } })`): | Option | Default | Meaning | | ------------------- | ------- | ------------------------------------------------------------------------------- | | `allowedAudioRoots` | none | Directories `audioPath` may read from; without it every `audioPath` is refused. | | `maxAudioBytes` | 50 MB | Largest audio accepted from any source. | | `openaiBasePath` | `""` | Prefix of the OpenAI-compatible route. | ### WebSocket `/v1/audio/transcriptions/stream` The route adapters do not handle WebSocket upgrades, so the streaming endpoint attaches to the Node HTTP server you own: ```typescript const server = http.createServer(handler); const socket = await attachTranscribeWebSocket(server, neurolink, { // Authorization: Bearer , or the subprotocol "neurolink-api-key." // offered next to "neurolink" (browsers cannot set headers). The token in the // URL (?token=) is refused unless `allowQueryToken: true`: URLs are logged. authToken: process.env.TRANSCRIBE_WS_TOKEN, // Defaults: 100 sockets in all, 16 per remote address (a further upgrade is // answered 503 before the handshake), a socket paused above 8 MiB of queued // audio, 512 MiB queued across the process. `mode: "file"` on a non-loopback // listener needs the token unless `allowUnauthenticatedFileMode: true`. maxConnections: 100, maxConnectionsPerAddress: 16, }); server.listen(3000); ``` 1. The first frame is **text**: a JSON config with the JSON route's fields minus the audio, plus `streaming` (for example `{ "language": "auto", "streaming": { "sampleRate": 16000 } }`). 2. Then **binary** frames of PCM16LE mono audio at that sample rate. 3. A text frame `{ "type": "end" }`, or closing the socket, ends the audio. `{ "type": "output", "languages": ["es", "fr"] }` changes the output languages from the next utterance on; any other text frame ends the audio. The server sends one JSON text frame per `TranscribeStreamEvent` and closes with 1000 when the stream is done; an invalid config gets an `error` event and close code 1008. **Sessions over the socket.** A speaker connects to `/v1/audio/transcriptions/stream?session=&speaker=` and uses the protocol above. A listener connects to `/v1/audio/transcriptions/stream/subscribe?session=` (the `subscribePath` option; `false` turns sessions off) and sends `{ "type": "subscribe", "languages": ["es"], "speakers": ["alice"] }`, again at any time to change them. Listeners get the speaker's events tagged with `speaker`, and only the `output` events of their languages. A session lives while a speaker or a listener is connected; the same auth token guards both paths. ### OpenAI Realtime transcription: `/v1/realtime?intent=transcription` The same live pipeline, behind OpenAI's Realtime transcription protocol, so a client that already speaks it needs no NeuroLink adapter. With LiveKit Agents (`livekit-plugins-openai`, tested on 1.3.11): ```python from livekit.plugins import openai stt = openai.STT( base_url="https:///v1", api_key="", model="neurolink-call", # a profile name; see below use_realtime=True, detect_language=True, # without it the plugin pins "en" ) ``` What the client sends: | Event | Handling | | -------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `session.update` (`session.type: "transcription"`, `session.audio.input`) or the beta `transcription_session.update` | Sets the rate (`format.rate`, default 24000; PCM16 only), the `model` (a profile), `language` and `prompt`. Answered with `session.updated` / `transcription_session.updated`. A running stream keeps the settings it started with. | | `input_audio_buffer.append` | Base64 PCM16 mono at the session's rate. | | `input_audio_buffer.commit` | Closes the open utterance. Not needed: an audio gap of 0.7 s (a muted mic) closes it too. | | `input_audio_buffer.clear` | Acknowledged with `input_audio_buffer.cleared`; audio already sent is kept. | What the server sends, per utterance (one conversation item, `item_id`): 1. `input_audio_buffer.speech_started` (`audio_start_ms`). 2. `conversation.item.input_audio_transcription.delta`: the words two passes agreed on, as they settle. Clients append deltas, so words still changing are never sent and nothing has to be retracted. 3. `input_audio_buffer.speech_stopped` (`audio_end_ms`), then `input_audio_buffer.committed` (`previous_item_id`). 4. `conversation.item.input_audio_transcription.completed` (`transcript`): the corrected text, or the raw final after `correctionWaitMs`. It also carries `neurolink: { engine, language, language_detected, corrected }`. Items complete strictly in order, because a client keeps one running text: a later utterance's events are held until the earlier one has completed. An utterance no engine could read completes with an empty transcript, which clears the client's interim. Errors are OpenAI-shaped `error` events. NeuroLink extras that a stock client ignores: `neurolink.final`, `neurolink.corrected` and `neurolink.output` (output-language renderings). **Profiles.** A realtime client can send only a model name, a language, a prompt and turn-detection numbers, so everything else comes from a profile the operator defines and the client names as its `model`: ```bash NEUROLINK_STT_REALTIME_PROFILES='{ "neurolink-call": { "provider": "bodhan", "model": "indic-transcribe-flex-mixed", "fallback": { "provider": "spark", "when": ["empty", "error"] }, "dictionary": [{ "term": "NeuroLink", "heardAs": ["neuralink"] }], "correction": { "transliterate": "latin" }, "clientLanguage": false } }' ``` `model` is sent to the engine as is. A suffix such as `@en,hi` is read only by the voice-bench `stt-aux` sidecar; any other server, LiteLLM included, treats the whole string as a model name and refuses it. When the primary refuses every pass, the fallback carries the call, and the server logs one error per stream that names the failed engine. A profile takes every field of the stream config (provider, model, fallback, routing, dictionary, correction, output, streaming …) plus: | Field | Default | Meaning | | --------------------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | `completed` | `"corrected"` | `"final"` sends `completed` at once with the raw final (about 0.3 s sooner) | | `correctionWaitMs` | 3000 | Longest wait for the correction before `completed` goes out with the raw final | | `clientLanguage` | `true` | Whether the client's `language` pins the transcription. Set `false` when clients may send a default such as LiveKit's `"en"` | | `clientTurnDetection` | `false` | Whether `turn_detection.silence_duration_ms` sets the closing pause (minimum 300 ms); NeuroLink's endpointer keeps its 750 ms otherwise | A `model` that names no profile but a configured STT provider (`bodhan`) uses that provider; any other name, OpenAI's `gpt-4o-mini-transcribe` included, uses the profile named `default`, or the server's defaults. The client's `prompt` becomes correction context where the profile corrects; it is never sent to the engine, which could echo it. `attachTranscribeWebSocket()` takes `realtimeProfiles` (merged over the env) and `realtimePath` (`false` turns the route off). Auth is the server's API key, as `Authorization: Bearer`, the `neurolink-api-key.` subprotocol, or the `openai-insecure-api-key.` subprotocol OpenAI's browser SDK sends; `?token=` only with `allowQueryToken: true`. ### STT evaluation: `POST /v1/evals/stt` A call can run two STTs on the same audio: the one people see (`primary`) and one run only to be compared (`shadow`). The sender posts both transcripts here in batches, and reads back how far apart they were per speaker. The server's API key guards it like every other route. **The collector is off by default**: it stores every transcript it is sent and reads them back to whoever asks. Mount it with `transcribe: { evals: {} }` in the route options (any `ServerSTTEvalOptions` object) or `NEUROLINK_STT_EVAL_ENABLED=1`; `evals: false` keeps it off whatever the environment says. Memory is bounded by `evals.maxBytes` (64 MiB of segments by default; the least recently updated calls are evicted, and stay on disk when a directory is set). When the server identifies callers (per-person authentication with `carryMiddlewareState`), a call belongs to the caller that created it: others cannot list, read or append to it. Calls made under no authentication or a shared key stay visible to every holder. ```jsonc POST /v1/evals/stt { "call_id": "c-123", "room": "standup", "batch": 3, // 1, 2, … per call; numbers may skip after a failed send "final": false, // true on the batch sent once the last participant left "models": { "primary": "google", "shadow": "neurolink" }, "segments": [{ "id": "uuid", // stable: a resend with the same id replaces it "source": "primary", // or "shadow" "model": "google", "participant_identity": "alice", "participant_name": "Alice", "text": "we ship on friday", "language": "en-US", "start_time": 1792000000.0, "end_time": 1792000002.0, // epoch s, or null "received_at": 1792000002.5 // epoch s }] } → 200 { "call_id": "c-123", "batch": 3, "final": false, "inserted": 1, "updated": 0, "ignored": 0, "segments": { "primary": 41, "shadow": 39 } } ``` A batch may hold up to 5,000 segments, and an empty final batch is valid. Resends are idempotent: an id already held is replaced and counted as `updated`. `GET /v1/evals/stt` lists calls, most recent first. `GET /v1/evals/stt/:callId` returns the per-speaker comparison (`?segments=true` adds the segments in time order): | Field | Meaning | | ------------------------------------------- | ----------------------------------------------------------------------------------------- | | `speakers_compared[].disagreement` | Word edit distance between the two STTs / the primary's words, on normalized text | | `speakers_compared[].phonetic_disagreement` | The same on phonetic word keys, so Devanagari against Latin for the same words agrees | | `speakers_compared[].primary` / `.shadow` | `model`, `segments`, `words`, `languages` reported, `mean_latency_s` (final after speech) | | `speakers_compared[].method` | `full`, or `windowed` (5-minute windows) for a speaker over 4,000 words | | `overall` | Both measures summed over every speaker | Neither side is ground truth: a disagreement says the STTs differ, not which one is right. Calls live in memory unless `NEUROLINK_STT_EVAL_DIR` (or the `evals.dir` route option) names a directory, where each batch is appended to one JSON-lines file per call and replayed on start. `evals: false` in the transcribe route options keeps the routes off; so does leaving `evals` unset without `NEUROLINK_STT_EVAL_ENABLED=1`. **Langfuse.** With `NEUROLINK_STT_EVAL_LANGFUSE_PUBLIC_KEY` and `NEUROLINK_STT_EVAL_LANGFUSE_SECRET_KEY` set (and `NEUROLINK_STT_EVAL_LANGFUSE_BASE_URL`, default `https://cloud.langfuse.com`), every accepted batch is also exported to that Langfuse project. These keys are separate from NeuroLink's own `LANGFUSE_*`, so evaluations get a project of their own. Only the server's environment sets this: no request field and no route option can turn it off or send the data elsewhere. | In Langfuse | What it holds | | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | Trace `stt-eval` (session = `call_id`) | `room`, both models, `final`, batch and segment counts | | Event `primary:` / `shadow:` | One per segment: its text as output; source, model, language and timings as metadata | | Scores `stt_disagreement`, `stt_phonetic_disagreement` | The call overall | | Scores `stt_speaker_disagreement`, `stt_speaker_phonetic_disagreement` | One per speaker (named in the comment) | Ids derive from the call and segment ids, so a resent segment updates its event and the scores are updated as batches arrive. The export runs in the background: it never delays or fails the sender's batch, and a failure is only logged. --- ## Text-to-Speech (TTS) Integration Guide # Text-to-Speech (TTS) Integration Guide NeuroLink provides integrated Text-to-Speech (TTS) capabilities, allowing you to generate high-quality audio from text prompts or AI-generated responses. This feature is perfect for voice assistants, accessibility features, narration, podcasts, and more. ## Overview **Key Features:** - **Multiple providers** - Google Cloud TTS, OpenAI TTS, ElevenLabs, Azure TTS, Fish Audio, Cartesia, and 60db - **High-quality voices** - Neural, Wavenet, Standard, and multilingual voice types - **Multiple languages** - 50+ voices across 10+ languages - **Flexible audio formats** - MP3, WAV, OGG/Opus - **Voice customization** - Adjust speed, pitch, and volume - **Two synthesis modes** - Direct text-to-speech OR AI response synthesis - **Production-ready** - Works with Google Cloud, OpenAI, ElevenLabs, Azure, Fish Audio, Cartesia, and 60db ## Supported Providers TTS is available through the following providers: | Provider | Authentication | Voices / Models | Notes | | -------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **google-ai** | Service Account (`GOOGLE_APPLICATION_CREDENTIALS`) | 50+ voices (Neural2, Wavenet, Standard) | Same auth as `vertex` (TTS uses Google Cloud Text-to-Speech client) | | **vertex** | Service Account (`GOOGLE_APPLICATION_CREDENTIALS`) | 50+ voices (Neural2, Wavenet, Standard) | Recommended for production | | **openai-tts** | API Key (`OPENAI_API_KEY`) | 6 voices: alloy, echo, fable, onyx, nova, shimmer; models: tts-1, tts-1-hd | Good default quality | | **elevenlabs** | API Key (`ELEVENLABS_API_KEY`) | Multilingual voices; model: eleven_multilingual_v2 | High-quality multilingual synthesis | | **azure-tts** | API Key (`AZURE_SPEECH_KEY` + region `AZURE_SPEECH_REGION`) | Neural voices with SSML support | Enterprise-grade Azure Speech | | **fish-audio** | API Key (`FISH_AUDIO_API_KEY`) | 14 languages, voice cloning (15 s reference); models: `s1` (default), `speech-1.6`, `speech-1.5` | Low-cost, ~80% cheaper than ElevenLabs — see [provider guide](/docs/getting-started/providers/fish-audio) | | **cartesia** | API Key (`CARTESIA_API_KEY`) | Cartesia voice library, English-first; models: `sonic-3.6` (default) | Low-latency Sonic models — see [provider guide](/docs/getting-started/providers/cartesia). Synchronous `/tts/bytes`; the WebSocket streaming flow is exposed separately via `CartesiaStream` in the voice server. | | **sixtydb** | Workspace API key (`SIXTYDB_API_KEY`) | Quality and fast workspace voice catalogs | WAV or PCM16 at 24 kHz — see [provider guide](/docs/getting-started/providers/sixtydb) | **Planned for future releases:** - AWS Polly --- ## Voice Selection ### Available Voice Types Google Cloud TTS offers three voice quality tiers: | Voice Type | Quality | Cost | Use Case | Example Voice | | ------------ | ------- | ------ | --------------------------------------- | ------------------ | | **Neural2** | Highest | High | Natural conversations, voice assistants | `en-US-Neural2-C` | | **Wavenet** | High | Medium | Professional narration, podcasts | `en-US-Wavenet-D` | | **Standard** | Good | Low | Cost optimization, bulk generation | `en-US-Standard-B` | ### Voice Discovery `--tts-voice` takes a provider-specific identifier, and `neurolink voices` prints the ones a provider will accept: ```bash neurolink voices --provider openai-tts # the six OpenAI voices neurolink voices --provider google-ai --language en-US # filter by language neurolink voices --provider elevenlabs --json # machine-readable ``` `--provider` is required. The list is sorted by name and the count is printed at the end. Providers are registered only when their credentials are present, so an unconfigured provider is reported the same way a misspelled one is — with the set that _is_ registered named in the message, and a non-zero exit. The same list is available from the SDK: ```typescript const voices = await TTSProcessor.getVoices("google-ai", { languageCode: "en-US", }); ``` `languageCode` is passed through to the provider, which decides what filtering it means: Google and Azure query their APIs with it, and OpenAI's fixed list ignores it. An unregistered provider, or one whose handler does not implement voice listing, raises a `TTS_PROVIDER_NOT_SUPPORTED` error. Google voice identifiers follow Google Cloud TTS naming conventions: `---` (e.g., `en-US-Neural2-C`, `en-GB-Wavenet-D`). Refer to the [Google Cloud TTS voice list](https://cloud.google.com/text-to-speech/docs/voices) for all available voices. ### Supported Languages **English Variants:** - `en-US` - United States English - `en-GB` - British English - `en-AU` - Australian English - `en-IN` - Indian English **Other Languages:** - `es-ES`, `es-US` - Spanish (Spain, Latin America) - `fr-FR`, `fr-CA` - French (France, Canada) - `de-DE` - German - `ja-JP` - Japanese - `hi-IN` - Hindi - `zh-CN`, `zh-TW` - Chinese (Simplified, Traditional) - `pt-BR`, `pt-PT` - Portuguese (Brazil, Portugal) - `it-IT` - Italian - `ko-KR` - Korean - `ru-RU` - Russian ### Voice Selection Guidelines **For Natural Conversations:** ```typescript tts: { voice: "en-US-Neural2-C", // Female, natural // OR voice: "en-US-Neural2-A", // Male, natural } ``` **For Professional Narration:** ```typescript tts: { voice: "en-US-Wavenet-D", // Male, professional // OR voice: "en-GB-Wavenet-A", // British, professional } ``` **For Cost Optimization:** ```typescript tts: { voice: "en-US-Standard-B", // Lower cost } ``` --- ## TTS Synthesis Modes NeuroLink supports two TTS synthesis modes, selected with `tts.mode`: | `tts.mode` | What is spoken | Model call | `usage` | | -------------------- | --------------------------------- | ---------- | --------- | | `"direct"` (default) | the input text / prompt, verbatim | none | all zeros | | `"response"` | the model's generated reply | yes | real | `result.ttsMetadata.mode` reports which one ran. The older `useAiResponse: true` flag still means `mode: "response"` and is still honoured, but an explicit `mode` wins when both are present. `stream()` always synthesizes the streamed reply and ignores `mode`. ### Mode 1: Direct Text-to-Speech (Default) Converts input text directly to speech **without** AI generation. ```typescript const result = await neurolink.generate({ input: { text: "Welcome to our service!" }, provider: "google-ai", tts: { enabled: true, mode: "direct", // Default: synthesize input text voice: "en-US-Neural2-C", }, }); // Audio contains: "Welcome to our service!" // No AI generation occurs; result.ttsMetadata.mode === "direct" ``` > **Direct mode ignores LLM options.** Because no model is called, `tools`, > `systemPrompt`, `conversationMessages`, `schema` and > `conversationMemoryConfig` have no effect. If a request carries any of them > without an explicit `tts.mode`, NeuroLink logs one warning naming the > ignored options — the usual fix is `mode: "response"`. The request is never > rejected, so existing "speak this text" callers are unaffected. **Use cases:** - Pre-written scripts - System notifications - Fixed announcements - Voice confirmations ### Mode 2: AI Response Synthesis Generates AI response first, then converts the response to speech. ```typescript const result = await neurolink.generate({ input: { text: "Tell me a joke" }, provider: "google-ai", tts: { enabled: true, mode: "response", // Synthesize AI's response (legacy: useAiResponse: true) voice: "en-US-Neural2-C", }, }); // AI generates joke text // TTS synthesizes the joke audio // Both text and audio available in result; result.ttsMetadata.mode === "response" ``` > **Note:** when `mode: "response"`, NeuroLink synthesizes the chat > provider's text response. If your chat provider has no TTS counterpart > (e.g. `anthropic`, `bedrock`), set `tts.provider` explicitly — otherwise > streaming continues as text-only and logs a provider-resolution warning. > Chat providers that double as TTS handlers (e.g. `google-ai`, `vertex`) > auto-resolve when `tts.provider` is omitted. **Use cases:** - Voice assistants - Interactive AI conversations - Dynamic content narration - AI-powered podcasts ### Cleaning text for speech (`tts.sanitize`) Model output is written for a screen. Read aloud, `**bold**` becomes "asterisk asterisk", a URL is spelled out letter by letter, and an emoji is announced by name. `tts.sanitize` runs the text through `prepareTextForSpeech()` first: ```typescript const result = await neurolink.generate({ input: { text: "Summarise the release notes" }, tts: { enabled: true, mode: "response", sanitize: true }, }); ``` With `sanitize: true` the defaults apply; pass an object to tune them: | Option | Default | Effect | | ----------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------ | | `markdown` | `true` | Strip headings, emphasis, inline code, bullets, blockquotes, HTML tags; tables become comma-separated rows; links → text | | `codeBlocks` | `"phrase"` | Fenced code: `"phrase"` speaks `codeBlockPhrase`, `"drop"` removes it, `"keep"` reads the contents | | `codeBlockPhrase` | `"Code block omitted."` | Spoken stand-in for a fenced block | | `urls` | `"hostname"` | `https://docs.example.com/a/b` → `docs.example.com` (an IDN host in Unicode, not punycode); `"remove"` drops the URL | | `emoji` | `true` | Remove emoji and pictographs with their skin-tone modifiers, variation selectors and the joiners between them | It is **off by default**: existing callers get byte-identical synthesis input. The pass is careful about what it does not touch: - Emphasis is a **pair** around a word run — `**bold**`, `*it*`, `_this_` — so an asterisk between digits is arithmetic and stays: `2*3*4 = 24` is spoken as written, as is `*123*1#`. Backslash escapes are resolved first and the escaped character is kept: `\*not bold\*` becomes `*not bold*`. - Only real HTML tag names are stripped (``, ``, ``, …). Angle-bracketed placeholders such as `` or ``, generics and comparisons are left alone. - The zero-width joiner is removed only between or beside pictographs; in Indic and Arabic text, where it shapes letters, it is kept. In `stream()` the pass runs **per segment** with code blocks kept (fence lines stripped), because a segment may hold an unterminated fence. Segments are cut at sentence ends with no awareness of markdown spans, so a construct that crosses a segment boundary — a link whose `](` lands in the next segment, an emphasis run closed two sentences later — is not recognised and its markers are spoken. Use `generate()` with `mode: "response"` when the whole reply must be cleaned as one text. The function is exported for use on your own text: ```typescript prepareTextForSpeech( "## Title\n\nSee **this** at https://docs.example.com/x ", ); // → "Title\n\nSee this at docs.example.com" ``` Every regular expression in the pass is linear-time, and every bounded span excludes its own opener so a run of openers cannot walk the bound. Measured on one machine (Node 24): 1 MB of ordinary markdown takes about 36 ms, and the worst adversarial shapes — 1 MB of `[`, `![`, `**`, ` \ --tts-voice \ --tts-format \ --tts-speed \ --tts-pitch \ --tts-output \ --tts-use-ai-response # --tts : enable TTS (boolean flag, required) # --tts-provider : google-ai|vertex|openai-tts|elevenlabs|azure-tts|fish-audio|cartesia|sixtydb # --tts-voice : voice id (optional — provider default applies) # --tts-format : mp3|wav|ogg (default: mp3) # --tts-speed : 0.25-4.0 (default: 1.0) # --tts-pitch : -20.0 to 20.0 (default: 0.0) # --tts-output : save to file # --tts-use-ai-response : synthesize AI response instead of input text ``` **Discovering voice ids for `--tts-voice`:** ```bash neurolink voices --provider [--language ] [--json] ``` See [Voice Discovery](#voice-discovery). **Selecting a specific TTS provider:** ```bash # Use OpenAI TTS neurolink generate "Hello" --tts --tts-provider openai-tts # Use ElevenLabs neurolink generate "Hello" --tts --tts-provider elevenlabs # Use Azure TTS neurolink generate "Hello" --tts --tts-provider azure-tts # Use Fish Audio neurolink generate "Hello" --tts --tts-provider fish-audio # Use Cartesia neurolink generate "Hello" --tts --tts-provider cartesia ``` --- ## Use Cases & Examples ### 1. Voice Assistant Create a voice assistant that speaks responses: ```typescript const assistant = new NeuroLink(); const response = await assistant.generate({ input: { text: "What's the weather like today?" }, provider: "google-ai", tts: { enabled: true, useAiResponse: true, // Speak AI's weather response voice: "en-US-Neural2-C", play: true, }, }); // AI generates weather info and speaks it ``` ### 2. Accessibility Features Screen reader-style narration for visually impaired users: ```typescript const narration = await neurolink.generate({ input: { text: "Button clicked. Navigation menu opened." }, provider: "google-ai", tts: { enabled: true, voice: "en-US-Neural2-C", speed: 1.2, // Slightly faster for efficiency play: true, }, }); ``` ### 3. Podcast Generation Generate professional podcast intros: ```bash neurolink generate "Welcome to Tech Insights Podcast, episode 42. Today we're discussing the future of AI development." \ --provider google-ai \ --tts-voice en-US-Wavenet-D \ --tts-speed 0.95 \ --tts-format mp3 \ --tts-output podcast-intro.mp3 ``` ### 4. Language Learning Slow pronunciation for language learners: ```bash # Slow French pronunciation neurolink generate "Je m'appelle Claude. Comment allez-vous?" \ --provider google-ai \ --tts-voice fr-FR-Neural2-A \ --tts-speed 0.7 \ --tts-output french-slow.mp3 # Normal speed for comparison neurolink generate "Je m'appelle Claude. Comment allez-vous?" \ --provider google-ai \ --tts-voice fr-FR-Neural2-A \ --tts-speed 1.0 \ --tts-output french-normal.mp3 ``` ### 5. Multilingual Support Generate audio in multiple languages: ```typescript const translations = { english: { text: "Hello, welcome to our application.", voice: "en-US-Neural2-C", }, french: { text: "Bonjour, bienvenue dans notre application.", voice: "fr-FR-Wavenet-A", }, spanish: { text: "Hola, bienvenido a nuestra aplicación.", voice: "es-ES-Neural2-A", }, hindi: { text: "नमस्ते, हमारे एप्लिकेशन में आपका स्वागत है।", voice: "hi-IN-Wavenet-A", }, }; for (const [lang, config] of Object.entries(translations)) { const result = await neurolink.generate({ input: { text: config.text }, provider: "google-ai", tts: { enabled: true, voice: config.voice, format: "mp3", output: `welcome-${lang}.mp3`, }, }); console.log(`Generated ${lang} audio (${result.audio?.size} bytes)`); } ``` ### 6. Batch Audio Generation Generate multiple audio files efficiently: ```typescript async function generateBatchAudio( texts: string[], voice: string = "en-US-Neural2-C", ) { const results = []; for (const text of texts) { const result = await neurolink.generate({ input: { text }, provider: "google-ai", tts: { enabled: true, voice, format: "mp3", }, }); results.push({ text, audioBuffer: result.audio?.buffer, audioSize: result.audio?.size, }); } return results; } // Usage const audioFiles = await generateBatchAudio([ "Welcome to our application.", "Please enter your username and password.", "Login successful. Redirecting to dashboard.", ]); // Save all files audioFiles.forEach((item, index) => { if (item.audioBuffer) { writeFileSync(`audio-${index}.mp3`, item.audioBuffer); } }); ``` ### 7. Streaming Text + Audio Mode 2 can synthesize sentence-buffered audio while the text response is still streaming. `stream()` synthesizes whenever `tts.enabled` is set; `useAiResponse` selects input-versus-response synthesis for `generate()` and does not apply to `stream()`. `streamingBufferSize` sets the minimum number of buffered characters before a completed sentence is flushed (default: 120). A provider's `maxTextLength` remains a hard boundary; handlers without an override use the 3,000-character default. Handlers can optionally expose provider-native audio reads for each buffered text segment. NeuroLink prefers that capability when it supports the requested options and otherwise keeps the existing one-buffer-per-segment synthesis path. Custom and built-in handlers without the optional capability remain compatible. Two handlers currently offer it, each only for the options whose incremental delivery has been verified against the live API: | Handler | Streams natively for | Everything else | | ------------ | --------------------------------------------------------------------------------------- | ------------------ | | `openai-tts` | `mp3`, `pcm16` | buffered synthesis | | `google-ai` | `pcm16` and `ogg`/`opus`, **and** only for a `Chirp3-HD`, `Chirp-HD` or `Journey` voice | buffered synthesis | Google's restriction is the streaming endpoint's own, not NeuroLink's: it rejects every other voice family (`Neural2`, `Studio`, `Wavenet`, `Standard`) with `only Chirp 3: HD voices are supported for streaming synthesis`, and rejects `MP3` and `LINEAR16` as unsupported encodings even though `synthesizeSpeech` accepts both. SSML is also excluded — the streaming request has no SSML field at all, so `` input stays on the buffered path rather than being sent as literal text. Because the default format is `mp3` and the default voice is a `Neural2` one, native streaming is strictly opt-in: pass both a streaming-capable voice and `format: "pcm16"` (or `"ogg"`) to get it. ```typescript // Sentence-buffered audio arrives in many reads instead of one per sentence. const streamResult = await neurolink.stream({ input: { text: "Summarize the quarterly report." }, tts: { enabled: true, provider: "google-ai", voice: "en-US-Chirp3-HD-Aoede", format: "pcm16", }, }); ``` Note that `pcm16` is headerless: the chunks report `sampleRate: 24000` so a consumer can wrap them, and Google's buffered path does not support `pcm16` at all, so that format only works for the streaming-capable voices above. Provider-local chunk indexes and finality are not exposed directly. NeuroLink recomputes a single global zero-based index, cumulative byte size, and exactly one final chunk across all successful segments. Empty transport reads on the native path are dropped and never reach the consumer; the buffered path is unchanged and forwards whatever a handler's `synthesize()` returns, so a handler that answers with a zero-byte buffer still produces an empty chunk and a repeated cumulative size, exactly as it did before native streaming existed. Each read is forwarded as soon as the next one arrives — the single one-chunk hold is what guarantees the final flag — rather than waiting for the segment to complete. A handler that declines the capability for a segment, or that fails while NeuroLink is still working out whether the capability is there, falls back to buffered synthesis for that segment rather than leaving a gap — as does a native stream that completes without producing any audio. That covers every step of the question, reads as well as calls, since reading a property can run a getter or a proxy trap that throws: reading `synthesizeStream`, a member that is not callable, reading or calling `isConfigured`, the call itself throwing, and a returned value that is not async-iterable (its `Symbol.asyncIterator` being unreadable included). A throwing `isConfigured` falls back the same way but then fails on the buffered path as well — shaped, exactly as it would for a handler with no native member. A handler that simply reports itself unconfigured is not in that list: that segment fails with `TTS_PROVIDER_NOT_CONFIGURED`, exactly as it did before native streaming existed. Once the segment's own work begins — at the `[Symbol.asyncIterator]()` call — an error fails that segment like any other synthesis failure, and its audio is not re-fetched through the buffered path. If a stream consumer exits early, cancellation reaches an active native request rather than waiting for the pending response-body read to finish, and the segment that was in flight still records its `tts.synthesize` span. If one segment fails, NeuroLink keeps the text stream and already-yielded audio, attempts the remaining segments, and resolves `streamResult.audio` from the surviving chunks. After the stream is drained, `streamResult.ttsMetadata` reports `success: false` and a structured, sanitized `error` identifying the failed segment count and positions. The first segment failure supplies the error detail. ```typescript async function streamAndSpeak(prompt: string, voice: string) { const streamResult = await neurolink.stream({ input: { text: prompt }, provider: "google-ai", model: "gemini-2.0-flash-exp", tts: { enabled: true, provider: "google-ai", voice, streamingBufferSize: 80, }, }); let fullText = ""; for await (const chunk of streamResult.stream) { if ("content" in chunk) { fullText += chunk.content; process.stdout.write(chunk.content); } else if ("type" in chunk && chunk.type === "tts_audio") { // Chunks are ordered by index. cumulativeSize grows monotonically, // and exactly the last successful audio chunk has isFinal=true. playAudioChunk(chunk.audio.data); } } // After stream iteration, audio resolves to the concatenated TTS result. // Native OpenAI mp3/pcm16 chunks are transport fragments: consume them in // order or use this aggregate; an individual fragment need not be playable. // Buffered providers still contribute one complete buffer per text segment. // Concatenating those segment buffers produces one playable stream for // mp3/mpeg/mpga/pcm16, but NOT a valid file for header-bearing containers // (wav, flac, m4a, mp4, webm), and a chained stream for ogg/opus that some // decoders read only through its first segment. return { text: fullText, audio: await streamResult.audio, }; } // Usage const result = await streamAndSpeak( "Explain quantum computing in simple terms", "en-US-Neural2-C", ); ``` The buffering heuristic recognizes `.`, `!`, or `?` followed by whitespace or the end of a text chunk. Short sentences remain buffered until the configured boundary or stream completion. Text without sentence punctuation is hard-split at the provider limit, so repeated synthesis calls never exceed that cap. The same chunk ordering and finality rules apply when a provider falls back to synthetic streaming. --- ## Error Handling ### Common Error Patterns ```typescript async function generateTTSWithRetry( text: string, voice: string, maxRetries: number = 3, ) { let lastError: Error | undefined; for (let attempt = 1; attempt setTimeout(resolve, 1000 * attempt)); } } } return { success: false, error: lastError?.message || "Unknown error occurred", attempts: maxRetries, }; } // Usage const result = await generateTTSWithRetry( "Generate this with retry logic", "en-US-Neural2-C", ); if (result.success && result.audio) { console.log("Success!"); writeFileSync("output.mp3", result.audio.buffer); } else { console.error("Failed:", result.error); } ``` --- ## Troubleshooting ### Common Issues | Issue | Cause | Solution | | -------------------------------- | ------------------------ | -------------------------------------------------------------------------------------------- | | **"TTS client not initialized"** | Missing credentials | Set `GOOGLE_APPLICATION_CREDENTIALS` or `GOOGLE_AI_API_KEY` | | **"Invalid voice name"** | Voice ID not found | Check the [Google Cloud TTS voice list](https://cloud.google.com/text-to-speech/docs/voices) | | **"Text too long"** | Input exceeds 5000 bytes | Split text into smaller chunks | | **"Synthesis failed"** | Network/API error | Check network connection and credentials | | **Audio doesn't play** | Missing audio player | Install `afplay` (macOS), `ffplay` (Linux), or use WAV on Windows | | **Empty audio buffer** | API returned no content | Check API quota and retry | ### Authentication Issues **Service Account:** ```bash # Verify credentials file exists ls -la $GOOGLE_APPLICATION_CREDENTIALS # Test authentication gcloud auth application-default login ``` **API Key:** ```bash # Verify API key is set echo $GOOGLE_AI_API_KEY ``` ### Audio Playback Issues **macOS:** - `afplay` is pre-installed, supports all formats - If playback fails, check system volume settings **Linux:** - Install `ffmpeg` for full format support: `sudo apt install ffmpeg` - Alternative: Use `aplay` for WAV files only **Windows:** - Built-in playback only supports WAV - Install VLC or Windows Media Player for other formats - SDK auto-converts to WAV when `play: true` on Windows --- ## Best Practices ### Performance Optimization 1. **Cache voices** - Voice list is cached for 5 minutes 2. **Batch processing** - Group multiple TTS requests when possible 3. **Use appropriate quality** - Standard voices are faster and cheaper 4. **Optimize text length** - Keep under 5000 bytes per request ### Production Deployment 1. **Use service accounts** - More secure than API keys 2. **Implement retry logic** - Handle transient network failures 3. **Monitor quota usage** - Track Google Cloud TTS API usage 4. **Set appropriate timeouts** - Default is 30 seconds 5. **Handle errors gracefully** - Provide fallback behavior ### Voice Selection 1. **Test before deploying** - Different voices suit different use cases 2. **Match gender to persona** - Choose appropriate gender for your application 3. **Consider language variants** - `en-US` vs `en-GB` vs `en-IN` 4. **Use Neural2 for quality** - Best natural-sounding voices ### Cost Management 1. **Use Standard voices** - For high-volume, non-critical use cases 2. **Cache generated audio** - Avoid regenerating the same content 3. **Monitor API usage** - Set budget alerts in Google Cloud Console --- ## Pricing Google Cloud TTS pricing (as of 2026): | Voice Type | Price per 1M characters | | ------------ | ----------------------- | | **Neural2** | $16.00 | | **Wavenet** | $16.00 | | **Standard** | $4.00 | **Monthly free tier:** 1 million characters (Standard voices) or 1 million characters (Wavenet/Neural2 voices) For detailed pricing, see [Google Cloud TTS Pricing](https://cloud.google.com/text-to-speech/pricing). --- ## Related Features **Multimodal Capabilities:** - [Multimodal Guide](/docs/features/multimodal) - Images, PDFs, CSV inputs - [PDF Support](/docs/features/pdf-support) - Document processing - [Video Generation](/docs/features/video-generation) - AI-powered video creation - [PPT Generation](/docs/features/ppt-generation) - AI-powered PowerPoint presentations **Advanced Features:** - [Streaming](/docs/advanced/streaming) - Stream AI responses in real-time - [Provider Orchestration](/docs/features/provider-orchestration) - Multi-provider failover **Documentation:** - [CLI Commands](/docs/cli/commands) - Complete CLI reference - [SDK API Reference](/docs/sdk/api-reference) - Full API documentation - [Troubleshooting](/docs/reference/troubleshooting) - Extended error catalog --- ## Summary NeuroLink's TTS integration provides: - **Multiple TTS providers** - Google Cloud TTS, OpenAI TTS, ElevenLabs, Azure TTS, Fish Audio, Cartesia - **High-quality voices** - Neural2, Wavenet, Standard, and multilingual options - **Multiple languages** - 50+ voices across 10+ languages - **Flexible synthesis modes** - Direct text or AI response - **Voice customization** - Speed, pitch, volume control - **Easy integration** - Works seamlessly with CLI and SDK via `--tts-provider` flag **Next Steps:** 1. Set up [Google Cloud credentials](#environment-setup) 2. Discover available [voices](#voice-discovery) 3. Try the [quick start examples](#quick-start) 4. Explore [use cases](#use-cases--examples) for your application 5. Check [troubleshooting](#troubleshooting) if needed --- ## Turn Time Budget # Turn Time Budget Turn-lifecycle limits for agentic (multi-step tool-calling) turns, enforced inside NeuroLink's native Gemini and Claude loops — Vertex (Gemini and Claude-on-Vertex) and Google AI Studio, both `generate()` and `stream()` in each case. NeuroLink sees every model call, every tool start/finish, and every stream chunk — so it is the layer that can tell a productive long turn from a wedged one, and end each with an honest message and a machine-readable reason. ## Options All four options ride `generate()` / `stream()` alongside `maxSteps` and the per-model-call `timeout`: | Option | Meaning | Default | | ------------------ | ----------------------------------------------------------------------------------------------------------- | ------------------------------------- | | `turnTimeoutMs` | Hard wall-clock cap for the WHOLE agentic turn (all model calls + tool executions) | see "Defensive defaults" below | | `stallTimeoutMs` | Max time with **no progress** (no stream chunk, no tool start/finish, no step start) before the turn ends | disabled | | `wrapupTimeLeadMs` | With less than this much turn time remaining, a wrap-up nudge rides the next tool-result turn | `120_000` when `turnTimeoutMs` is set | | `toolTimeoutMs` | Per-tool-execution timeout; a timed-out tool fails **that step** (error tool_result) and the turn continues | `300_000` | ```typescript const result = await neurolink.generate({ input: { text: "Investigate the amount mismatch across services" }, provider: "vertex", maxSteps: 50, turnTimeoutMs: 1_800_000, // 30 min whole-turn budget stallTimeoutMs: 300_000, // no progress for 5 min => end the turn toolTimeoutMs: 300_000, // a wedged tool costs one step, not the turn }); ``` ### `turnTimeoutMs` vs `timeout` on the native loop path On the native loop path (direct Anthropic, LiteLLM, OpenAI-compatible), an explicit `turnTimeoutMs` owns the whole-turn hard abort, and `timeout` keeps its per-model-call meaning. Historically `timeout` alone bounded the ENTIRE multi-step loop there, so `{ timeout: 300_000, turnTimeoutMs: 2_400_000 }` killed a 40-minute turn at 5 minutes flat — surfacing as the provider SDK's generic cancel (`Request was aborted.`) mid-loop. When the hard cap does fire, the error now carries the timer's own identity (`… timed out after …`) instead of that generic cancel shape. ### Defensive defaults When `turnTimeoutMs` is **unset**, each loop keeps its pre-existing behavior: - **Vertex Gemini (generate + stream)** and **Vertex Claude stream**: the defensive whole-turn bound of `timeout ?? 300_000` ms still applies (a turn must never hang forever) — but its firing is now labeled honestly as a time-limit exit instead of masquerading as a step-cap exit. - **Vertex Claude generate**: historically had no whole-turn bound (only the per-call `timeout`), and still has none — long multi-step turns keep running. Set `turnTimeoutMs` explicitly to bound them. - **Google AI Studio (generate + stream)**: the pre-existing per-request timeout controller (`timeout`, defaulting to the provider's own budget) remains the whole-turn bound, and no second deadline is armed alongside it. Its firing is now reported as `stopReason: "time-limit"` rather than as a bare abort. An explicit `turnTimeoutMs` adds a tighter deadline on top. ## `stopReason` — the turn-exit discriminator `finishReason` is provider-shaped and historically overloaded ("tool-calls" covered both step-cap exits and Gemini `MALFORMED_FUNCTION_CALL` failures). Branch on `result.stopReason` instead: | `stopReason` | Meaning | | ---------------- | ------------------------------------------------------------------ | | `completed` | The model finished on its own (text answer or `final_result`) | | `step-cap` | The `maxSteps` budget ran out while the model still wanted tools | | `time-limit` | The `turnTimeoutMs` (or defensive) wall-clock deadline passed | | `stalled` | No progress for `stallTimeoutMs` | | `aborted` | The caller's `abortSignal` ended the turn | | `context-cap` | The in-loop context guard stopped the turn (Vertex loops only) | | `provider-error` | Provider/model failure (e.g. persistent `MALFORMED_FUNCTION_CALL`) | A loop only reports what it can observe. The AI Studio loops never report `context-cap`, because their context guard reclaims room or does nothing — it has no stop-the-turn branch to report. Also on the result: `rawFinishReason` (the verbatim provider value, e.g. `MALFORMED_FUNCTION_CALL`, `max_tokens`) and `stepsUsed`. On `stream()` results, read `metadata.stopReason` / `metadata.rawFinishReason` / `metadata.stepsUsed` **after draining the stream** — background loops resolve them at close, and metadata is the mutable reference that survives wrapper spreads. Providers without a native loop leave `stopReason` undefined — keep any legacy `finishReason` heuristics as a fallback. ## Honest terminal messages Each exit cause has its own user-facing message; the step-cap text ("...reached the N-step limit...") is emitted **only** when `step >= maxSteps` genuinely terminated the loop: - time-limit: _"I had to stop after Xm Ys — this turn hit its processing time limit. I completed N tool calls before stopping; ask me to continue and I'll pick up from there."_ - stalled: _"I had to stop because this turn made no progress for Xs — a tool or model call appears to be stuck. ..."_ - aborted: _"This turn was stopped before I could finish. ..."_ ## MALFORMED_FUNCTION_CALL handling Gemini's `MALFORMED_FUNCTION_CALL` / `UNEXPECTED_TOOL_CALL` finish reasons map to unified `finishReason: "error"` (never `"tool-calls"`). A `MALFORMED_FUNCTION_CALL` step is retried **once** with a corrective note; if it persists, the turn ends with `stopReason: "provider-error"` — usually worth a caller-side retry. ## Other Gemini finish reasons The native Gemini loops (AI Studio and Vertex) map the SDK's finish reason onto the unified values below and keep the verbatim value in `rawFinishReason`. Vertex puts the unified value on `finishReason`; on AI Studio it is the `unified` field of the finish part that model middleware receives. | Gemini finish reason | `finishReason` | | ----------------------------------------------------------------------------------------- | ---------------- | | `MAX_TOKENS`, `CONTINUATION` (token limit reached before the model was done) | `length` | | `TOO_MANY_TOOL_CALLS` (the model called tools until the system cut the turn off) | `tool-calls` | | `MALFORMED_FUNCTION_CALL`, `UNEXPECTED_TOOL_CALL` | `error` | | `SAFETY`, `RECITATION`, `BLOCKLIST`, `PROHIBITED_CONTENT`, `SPII`, `LANGUAGE`, `IMAGE_*`¹ | `content-filter` | | `STOP`, `OTHER`, `FINISH_REASON_UNSPECIFIED`, `IMAGE_OTHER`, `NO_IMAGE` | `stop` | ¹ `IMAGE_SAFETY`, `IMAGE_PROHIBITED_CONTENT` and `IMAGE_RECITATION`. `tool-calls` also marks a turn that ran out of `maxSteps`, so branch on `stopReason` to tell the two apart: `TOO_MANY_TOOL_CALLS` leaves `stopReason: "completed"`, a spent step budget reports `step-cap`. A value the SDK adds later reads `stop` until it is mapped. ## Telemetry - `result.analytics` (when `enableAnalytics` is on) carries `stepsUsed`, `toolCallCount`, `stopReason`, `elapsedMs`, `rawFinishReason`. - The SDK emitter fires `turn:lifecycle` events (alongside `tool:start`/`tool:end`) for non-completed exits, tool timeouts, and malformed-call retries: ```typescript neurolink.getEventEmitter().on("turn:lifecycle", (event) => { // { provider, timestamp, phase: "time-limit" | "stalled" | "aborted" | // "step-cap" | "provider-error" | "tool-timeout" | "malformed-retry", // step?, maxSteps?, toolName?, toolCallCount?, elapsedMs? } }); ``` --- ## Video Analysis # Video Analysis Attach a video file to `generate()` or `stream()` and ask about it. What the model receives depends on the provider: - **Gemini (Google AI Studio and Vertex AI)** receives the clip itself, inline, with its audio track. It sees continuous motion and hears the speech. - **Every other provider** receives a metadata summary, timestamped keyframes as ordinary images, and any embedded subtitle track. It sees a handful of stills and hears nothing, unless you ask for a transcript with `--transcribe-audio`. Video analysis suits screen recordings in particular: checking whether a workflow worked, finding the moment a UI went wrong, or comparing two recordings. The prompts in this guide ask for a logical audit of that kind. The audit style comes from your prompt; the SDK imposes no report format. For the cross-modality overview (images, PDFs, audio, video) see the [Multimodal guide](/docs/features/multimodal). ## How It Works 1. **Detection.** The file type is recognized from the file's leading bytes as well as its extension (MP4 and MOV by their `ftyp` box, AVI by its RIFF header, and so on). Through `generate()`, `stream()` and the CLI a file can be at most 100 MB. On the Gemini providers a larger file is refused with an error-level log line (`File too large: ... (max: 100.00 MB)`, printed even without `--debug`) and the request goes on without it, and without any file listed after it in the same call: the model receives no `## Video File` section at all. 2. **Processing.** `VideoProcessor` reads the duration, resolution, codecs, frame rate and bitrate, extracts timestamped keyframes with ffmpeg, extracts the first embedded subtitle track if there is one, and, only if you ask, transcribes the speech. The summary becomes a `## Video File` section in the prompt text and the keyframes are attached as images, each labelled with the moment it was sampled. 3. **Delivery.** If the provider can take video, the clip itself is added to the request as inline data, in addition to the summary and the keyframes. If it cannot, or the clip does not qualify, the model works from the summary and the keyframes alone. A video that cannot be processed at all (a corrupt file, say) does not fail the request: the model receives a short placeholder describing the attachment. --- ## Native Delivery to Gemini Gemini accepts video inline, and takes the audio track with it. Sending the file itself needs no ffmpeg, so on a machine without it Gemini still receives the whole clip. Keyframes and the metadata summary are still attached when they could be produced. ### Which providers The capability table is `VIDEO_PROVIDER_CONFIGS`, keyed by provider name or alias: | Provider names | Delivery | Inline ceiling | Longest clip | Hears audio | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- | -------------- | ------------ | ----------- | | `vertex`, `google-vertex`, `googlevertex`, `google-ai-studio`, `googleaistudio`, `google-ai`, `googleai`, `gemini` | Native, inline | 14 MB | 3600 s | yes | | `openai`, `azure`, `anthropic`, `bedrock`, `amazon-bedrock`, `mistral`, `litellm`, `openrouter`, `openai-compatible`, `huggingface`, `sagemaker`, `deepseek`, `nvidia-nim`, `lmstudio`, `cerebras`, `sambanova` | Keyframes | none | none | no | | `ollama`, `llamacpp`, `llama-cpp` | Keyframes | none | none | no | Two details matter: - A Vertex request for a model whose id contains `claude` is routed to the Anthropic SDK, which never sees a video part, so it gets the keyframe row, not the Gemini one. - A provider that is not in the table keeps the keyframe behavior. The table says nothing about whether such a provider understands the frames; `getVideoProviderConfig()` returns `null` for it, and `supportsNativeVideo()` reads that as `false`. ### What qualifies a clip All of these must hold, checked per clip: 1. **Source.** The clip must be a local file path or a `Buffer` (or an object with a `buffer`). A URL is fetched for keyframes and the metadata summary only; its bytes are not kept for delivery, so it never goes to Gemini as a clip. This case is not reported as a fallback: no warning is logged and no reason is given, so a URL entry that you expected to be heard simply arrives as keyframes. Download the file first to send it whole. 2. **Container.** Gemini reads these inline: `video/mp4`, `video/mpeg`, `video/mpg`, `video/mov`, `video/quicktime`, `video/avi`, `video/x-msvideo`, `video/x-flv`, `video/webm`, `video/wmv`, `video/x-ms-wmv` and `video/3gpp`. Anything else, MKV for example, falls back to keyframes. There is no transcode step: re-encoding a long recording inside a generation request costs minutes of CPU, for a payload that would usually breach the ceiling anyway. 3. **Size.** The 14 MB ceiling is one budget for the whole request, counted in source bytes, not a per-clip limit. Before a clip ships, its bytes are added to the source bytes of every inline part already in the request, which means images (the keyframes among them), PDFs, audio and any clip accepted earlier. With nothing else attached that is the clip's own size. 4. **Duration.** At most 3600 s. A clip whose duration could not be measured is not refused for it. Why 14 MB when Gemini documents 20 MB: inline data travels as base64 in a JSON body, which costs 4 bytes per 3, and the 20 MB limit covers the whole request, prompt and system instructions included. 14 MB of source encodes to about 18.7 MB, leaving headroom. 15 MB would encode to exactly 20.0 MB and leave none. ### Falling back to keyframes A clip that does not qualify is not an error. It is left out of the request, the model works from the summary and keyframes, and a warning names the reason. The one exception is a URL source (see above), which is silent. Warnings are only printed in debug mode (`--debug`, or `NEUROLINK_DEBUG=true` for the SDK), so run with one of those to see it: ```text Sending keyframes instead of the clip for big.mp4: the clip is 15.0MB, which would bring this request's inline attachments to 15.0MB, over the 14MB inline ceiling shared by the whole request for google-ai-studio. ``` The keyframes already in the request count against the budget, which is why that line speaks of the request's inline attachments. The reasons you can see are: - ` does not accept video attachments` - ` is not a container reads inline` - `the clip is X MB, over the 14MB inline ceiling for `, or, when other inline parts already used part of the budget, `the clip is X MB, which would bring this request's inline attachments to Y MB, over the 14MB inline ceiling shared by the whole request for ` - `the clip runs N s, over the 3600s ceiling for ` A fallback loses the clip's audio, because keyframes carry none. If the speech matters, add `--transcribe-audio` (see [Audio transcription](#audio-transcription)) or shorten or compress the clip below the ceiling. Clips above 14 MB are not uploaded through the Gemini Files API. That is a separate piece of work that has not been done, so the ceiling is a hard edge today. ### Asking before you send The capability table is exported, so a caller can check a provider and a clip without making a request: ```typescript canDeliverVideoNatively, estimateVideoTokens, getVideoProviderConfig, isNativeVideoMimeType, supportsNativeVideo, VIDEO_PROVIDER_CONFIGS, } from "@juspay/neurolink"; supportsNativeVideo("google-ai"); // true supportsNativeVideo("openai"); // false getVideoProviderConfig("not-a-provider"); // null: not described, not "takes frames" isNativeVideoMimeType("video/x-matroska"); // false // Reasons come back as strings you can log verbatim. canDeliverVideoNatively("google-ai", { buffer: Buffer.alloc(20 * 1024 * 1024), filename: "big.mp4", mimeType: "video/mp4", }); // { deliver: false, reason: "the clip is 20.0MB, over the 14MB inline ceiling for google-ai" } // Duration drives the native price; frame count drives the keyframe price. estimateVideoTokens({ provider: "google-ai", durationSec: 60 }); // 15,600 estimateVideoTokens({ provider: "openai", durationSec: 60, frameCount: 8 }); // 2,000 ``` `estimateVideoTokens` prices a native clip at 260 tokens per second, a keyframe at 250 tokens, and a minute of transcribed speech at 400. It is a budgeting estimate, not a quote. --- ## Keyframes Every other provider, and Gemini when a clip falls back, works from keyframes. - **Cadence.** Without an explicit `frames`, the interval between frames follows the clip's duration: | Clip length | One frame every | | ------------ | --------------- | | up to 10 s | 1 s | | up to 30 s | 2 s | | up to 2 min | 3 s | | up to 10 min | 6 s | | up to 30 min | 20 s | | longer | 60 s | The total is capped at 100 frames; if a tier would produce more, the interval widens so the frames still cover the whole clip. The count does not depend on the provider. The `recommendedFrameCount` in the capability table (16, 8 or 4) is only what `estimateVideoTokens` assumes when you give it no `frameCount`; it does not set how many frames are extracted. - **Size.** Frames are scaled to fit within 768 by 768 pixels, keeping the aspect ratio and never enlarging, then encoded as JPEG at quality 80 unless you set `quality` or `format`. - **Timestamps.** Each frame carries the time ffmpeg actually sampled it at, in its image label and in a `## Keyframes` list in the prompt, so "what happens at 0:30?" has an answer. - **Subtitles.** The first embedded subtitle track is extracted as plain text and added under `## Subtitles / Captions`, up to 10,000 characters. It is included whether or not you transcribe. - **No ffmpeg, no frames.** Frame extraction shells out to ffmpeg, which comes from the optional `ffmpeg-static` dependency or your `PATH`. Without it a keyframe provider receives the metadata summary and nothing visual, and no error is raised. Native Gemini delivery is unaffected. --- ## CLI Flags and `videoOptions` The flags are available on `generate`, `stream` and `batch`. `--video` attaches the clip (`input.videoFiles`). The other four flags each map to one field of the `videoOptions` object that `generate()` and `stream()` accept (type `VideoProcessorOptions`). | CLI flag | SDK field | Default | Meaning | | ------------------------- | ------------------------------ | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--video ` | `input.videoFiles` | none | Attach a video; repeatable. `--file ` works too, but is not available on `batch`, where it would collide with the prompts-file positional. | | `--video-frames ` | `videoOptions.frames` | chosen from the duration, at most 100 | Keyframe budget. An explicit `n` is spread evenly across the whole clip and clamped to 100; zero, negative or non-numeric values are ignored. It is a ceiling: a clip with sparse frames can return fewer. | | `--video-quality \` | `videoOptions.quality` | 80 | Encoder quality for keyframes. Rounded and clamped to 1 to 100. | | `--video-format ` | `videoOptions.format` | `jpeg` | Keyframe encoding: `jpeg` or `png`. On Google AI Studio (`google-ai`) use `jpeg`: its PNG keyframes are currently sent labelled `image/jpeg`. Vertex AI labels PNG correctly. | | `--transcribe-audio` | `videoOptions.transcribeAudio` | `false` | Transcribe the clip's speech and include it as text. | `--video-frames` and `--video-quality` deliberately have no CLI default, so an unset flag leaves the choice to the processor. The three keyframe options and the transcript shape what the model reads in the prompt and the attached images. They do not change the clip that goes to Gemini, which is sent as is. ```typescript const result = await neurolink.generate({ input: { text: "Describe each scene", files: ["./demo.mp4"] }, provider: "openai", videoOptions: { frames: 16, // keyframe budget, clamped to 100 quality: 90, // 1-100, default 80 format: "jpeg", // "jpeg" | "png", default "jpeg" (use jpeg on Google AI Studio) transcribeAudio: true, // default false }, }); ``` ```bash neurolink generate "Describe each scene" --video ./demo.mp4 \ --provider openai --video-frames 16 --video-quality 90 --video-format jpeg ``` --- ## Audio Transcription Gemini hears the audio track of a clip it receives natively, so it does not need a transcript. Transcription is for the others: a recorded standup or a narrated demo reaches a keyframe provider with its entire spoken content missing, and "summarize this meeting" would be answered from a few screenshots. It also helps when a Gemini clip falls back to keyframes. Set `--transcribe-audio`, or `videoOptions.transcribeAudio: true`. It is off by default because it costs an ffmpeg pass plus a speech-to-text call, and most attached video is silent screen capture. The flag does not look at the provider: on Gemini, with the clip delivered natively, it still spends the ffmpeg pass and the speech-to-text call and adds the transcript to the prompt next to the audio Gemini already hears. Leave it off there. **What happens.** ffmpeg drops the video stream and writes the audio as mono 16 kHz MP3 (16-bit PCM WAV for an engine that does not read MP3). That goes to the speech-to-text engine, and the result is added to the prompt under `## Spoken Audio (transcribed)`, truncated at 20,000 characters. It is labelled as a machine transcription and kept apart from `## Subtitles / Captions`, so the model can tell the two apart when both exist. **Which engine.** The one named by `NEUROLINK_STT_PROVIDER`; otherwise the first configured hosted engine in this order: OpenAI-compatible Whisper (`OPENAI_STT_API_KEY` or `OPENAI_API_KEY`), Deepgram, ElevenLabs, Google Speech-to-Text, Azure Speech; otherwise the built-in local engine. Video uses the same engine selection as audio files and `neurolink.transcribe()`. See the [transcribe guide](/docs/features/transcribe) for configuration. **Limits.** The extracted audio must be 25 MB or less. Audio extraction times out after 180 s and one transcription request after 120 s. **Failure is not fatal.** Transcription is best effort. When it cannot run, the request still succeeds with the keyframes and metadata, and a warning (printed in debug mode, like the delivery warnings above) says why: ```text [VideoProcessor] No transcript for demo.mp4: the video has no audio track. The model will receive the keyframes and metadata only. ``` The reasons are: no audio track; the transcription backend could not be loaded or is not configured; the audio track could not be extracted, or was empty; the extracted audio is over 25 MB; the engine returned an empty transcript (silence, music); or the request failed. The reason is also available as `transcriptionSkippedReason` on the processed video. Audio files attached on their own (`.mp3`, `.wav`, `.m4a` and so on) are transcribed automatically, with no flag, whenever an engine is available. See the [Audio Input guide](/docs/features/audio-input). --- ## Usage ### CLI Usage Analyze any video file with a natural language prompt. ```bash # Basic video analysis neurolink generate "Analyze the login workflow in this video" \ --video ./recordings/screen-capture.mp4 \ --provider vertex \ --model gemini-2.5-flash ``` ### SDK Usage Integrate video analysis into your TypeScript/JavaScript projects. ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Dissect the logical progression of this activity", files: ["./examples/tutorial.mp4"], }, provider: "vertex", model: "gemini-2.5-flash", }); console.log(result.content); ``` #### Advanced SDK Examples **Custom Model Configuration** Fine-tune the analysis by adjusting token limits and temperature. ```typescript const result = await neurolink.generate({ input: { text: "Perform a detailed audit of the checkout workflow", files: ["payment-flow.mov"], }, model: "gemini-2.5-flash", maxTokens: 3000, temperature: 0.2, // Lower temperature for more consistent logic auditing provider: "vertex", }); ``` **Disabling Tool Interference** By default, the model might try to use available tools. For pure video analysis, you can disable them. ```typescript const result = await neurolink.generate({ input: { text: "Analyze the video timeline", files: ["video.mp4"], }, disableTools: true, }); ``` **A provider without video support, with speech** Send keyframes and a transcript to a provider that cannot take a clip. ```typescript const result = await neurolink.generate({ input: { text: "Summarize what was said and what was shown", videoFiles: ["./standup.mp4"], }, provider: "openai", videoOptions: { frames: 12, transcribeAudio: true }, }); ``` --- ## Examples ### 1. UI/UX Bug Analysis Identify why a user is unable to complete a form or where the interface is misleading. **Prompt**: "Find why the user is getting stuck at the payment step. Look for validation errors or hidden UI elements." ### 2. Silent Failure Detection Detect cases where an action is taken but the system provides no feedback (no loaders, no success messages). **Prompt**: "Audit the 'Submit' button click. Is there a visual 'bond' between the click and the next state? Report any lag or missing loading indicators." ### 3. Workflow Validation Verify if a complex multi-step process follows the intended business logic. **Prompt**: "Trace the logical progression from 'Item Selection' to 'Checkout'. Does every state change correspond to a user action?" ### 4. Comparison Analysis Compare two recordings to find discrepancies in behavior. **Prompt**: "Compare these two clips. The first one is the expected behavior and the second one has a bug. Identify the exact frame or timestamp where the logic deviates." --- ## Command Gallery Quick CLI recipes for common tasks. ### Debug delivery and fallback decisions Full technical detail, including whether the clip or keyframes were sent and why: ```bash neurolink generate "Audit this video" --video bug.mp4 --debug ``` ### Use a specific model ```bash neurolink generate "Analyze logic" --video demo.mov --model gemini-2.5-flash ``` ### Force a specific provider ```bash neurolink generate "Extract patterns" --video test.mp4 --provider vertex ``` ### Keyframe provider with more frames and the speech ```bash neurolink generate "What is said and shown?" --video talk.mp4 \ --provider openai --video-frames 24 --transcribe-audio ``` --- ## Best Practices - **Prefer Gemini for anything with sound or fast motion.** Only the native path sees what happens between frames and hears the audio. - **Keep clips under the ceiling.** A recording that is a few megabytes at most travels whole; a longer one falls back to keyframes. Trimming to the relevant stretch, or re-encoding at a lower bitrate, keeps it on the native path. Remember the budget is shared with every other inline attachment in the same request. - **Frame depth.** On the keyframe path, short videos (under 10 s) get one frame per second and long ones are sampled more sparsely. Set `--video-frames` to spend your frame budget evenly across a clip you care about. - **Add a transcript only where it helps.** `--transcribe-audio` is for providers that cannot hear the clip. It is not provider-aware, so on Gemini it only adds a redundant transcript and a speech-to-text call. - **Prompt precision.** Guide the model with specific questions about the activity, and ask for the structure you want (a timeline, an action-reaction table, a verdict) in the prompt. - **Format.** The analysis is returned as text in `result.content`, making it easy to store, display, or pipe to other tools. --- ## Video Director Mode – Multi-Clip Generation & Merging # Video Director Mode Director Mode extends NeuroLink's [video generation](/docs/features/video-generation) capability to produce **multi-segment videos with seamless AI-generated transitions**. Instead of a single clip, you define an array of **segments** — each with its own prompt and image — and NeuroLink orchestrates the full pipeline: generating each clip, extracting boundary frames, producing transition videos (with individually configurable durations) using Veo 3.1's first-and-last-frame interpolation, and merging everything into one continuous video. ## Overview Director Mode is triggered automatically when you supply an **`input.segments`** array to the video generation API. Each segment is a self-documenting `{ prompt, image }` object, mapping cleanly to the pipeline concept of ordered video segments. ```mermaid graph TD A["Segment 1: Image A + Prompt 1"] --> G1["Generate Clip 1 (4-8s)"] B["Segment 2: Image B + Prompt 2"] --> G2["Generate Clip 2 (4-8s)"] C["Segment 3: Image C + Prompt 3"] --> G3["Generate Clip 3 (4-8s)"] G1 --> F1["Extract Last Frame of Clip 1"] G2 --> F2a["Extract First Frame of Clip 2"] G2 --> F2b["Extract Last Frame of Clip 2"] G3 --> F3["Extract First Frame of Clip 3"] F1 --> T1["Generate Transition 1→2"] F2a --> T1 F2b --> T2["Generate Transition 2→3"] F3 --> T2 G1 --> M["Merge: Clip1 + Trans1 + Clip2 + Trans2 + Clip3"] T1 --> M G2 --> M T2 --> M G3 --> M M --> O["Final Merged Video (MP4)"] ``` ### How It Works 1. **Parallel clip generation** – All main clips are generated concurrently (fixed concurrency of 2) via Veo 3.1's image-to-video endpoint, with a circuit breaker that trips after 2 consecutive failures to avoid wasted API calls 2. **Frame extraction** – The last frame of clip N and first frame of clip N+1 are extracted from generated video buffers (with MP4 ftyp header validation) 3. **Parallel transition generation** – Veo 3.1 Fast's **first-and-last-frame interpolation** API generates transitions between each pair of adjacent clips in parallel (same concurrency limit), with individually configurable duration (4, 6, or 8 seconds each) 4. **Sequential merge** – Clips and transitions are concatenated: `Clip₁ → Trans₁₋₂ → Clip₂ → Trans₂₋₃ → Clip₃ → …` 5. **Single output** – The merged result is returned as one `VideoGenerationResult` buffer ### Key Technology: Veo First-and-Last-Frame Interpolation The transition clips use Veo 3.1's native `lastFrame` parameter in the `predictLongRunning` API. Instead of generating from a single image, you provide **two** images — the first frame and the last frame — and Veo generates a video that smoothly interpolates between them: ```json { "instances": [ { "prompt": "Smooth cinematic transition", "image": { "bytesBase64Encoded": "", "mimeType": "image/jpeg" }, "lastFrame": { "bytesBase64Encoded": "", "mimeType": "image/jpeg" } } ], "parameters": { "sampleCount": 1, "durationSeconds": 6, "aspectRatio": "16:9", "resolution": "720p" } } ``` This produces a physically coherent, AI-generated morph — far superior to simple crossfade or dissolve effects. The `durationSeconds` value is set independently for each transition (from the `transitionDurations` array), allowing shorter or longer interpolations per segment boundary. ## What You Get - **Multi-segment video** – Chain any number of video segments into a single continuous output - **AI transitions** – Per-transition configurable duration (4, 6, or 8 seconds each) generated by Veo 3.1 frame interpolation (not simple crossfades) - **Parallel generation** – Both main clips and transitions are generated concurrently (fixed concurrency of 2) with a circuit breaker for clip failures - **Mixed image inputs** – Each segment's `image` field accepts a Buffer, file path, URL, or `ImageWithAltText` - **Consistent settings** – Resolution, aspect ratio, and audio settings apply uniformly across all segments and transitions - **Per-segment customization** – Each segment is a self-contained `{ prompt, image }` object - **Buffer validation** – All video buffers are validated for MP4 ftyp headers before frame extraction and merging - **SDK only** – Use programmatically via `generate()` (CLI not supported for Director Mode) ## Supported Provider & Model | Provider | Model | Interpolation Support | Transition Duration | Max Segments | Concurrency | | -------- | ------------------------------------------------ | --------------------- | ------------------- | ------------ | ----------- | | `vertex` | `veo-3.1` (clips) / `veo-3.1-fast` (transitions) | First + Last Frame | 4-8s per transition | 10 | 2 (fixed) | > **Note:** The `lastFrame` parameter is supported by `veo-2.0-generate-001`, `veo-3.1-generate-001`, and `veo-3.1-fast-generate-001`. NeuroLink uses `veo-3.1-generate-001` for main clips and `veo-3.1-fast-generate-001` for transition clips (faster generation with minimal quality difference for short interpolations). ## Prerequisites Same as [Video Generation prerequisites](/docs/features/video-generation#prerequisites), plus: 1. **Sufficient quota** – Director Mode generates `N + (N-1)` video operations (N clips + N-1 transitions). Ensure your Vertex AI project has adequate quota. 2. **Adequate timeout** – Multi-segment generation takes proportionally longer. Set `timeout` accordingly (recommended: 5-10 minutes for 3+ segments). ## Quick Start ### SDK Usage ```typescript const neurolink = new NeuroLink(); // Director Mode: define segments → merged video const result = await neurolink.generate({ input: { segments: [ { prompt: "Camera slowly pans across the product on a white table", image: await readFile("./scene1.jpg"), }, { prompt: "Dynamic zoom into product details with dramatic lighting", image: await readFile("./scene2-detail.jpg"), }, { prompt: "Wide shot pulling back to reveal the full scene", image: await readFile("./scene3-wide.jpg"), }, ], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "720p", length: 6, // Per-segment clip duration (reused from VideoOutputOptions) aspectRatio: "16:9", audio: true, }, }, timeout: 600000, // 10 minutes for multi-segment }); if (result.video) { await writeFile("director-output.mp4", result.video.data); console.log(`Total duration: ${result.video.metadata?.duration}s`); console.log(`Segments: ${result.video.metadata?.segmentCount}`); } ``` ### Using Image URLs > **Security:** segment image URLs are fetched only over HTTPS from public > hosts, and segment image paths honour `attachments.allowedRoots` — see > [Attachment Security](/docs/features/attachment-security). ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { segments: [ { prompt: "Serene sunrise over calm waters", image: "https://example.com/sunrise.jpg", }, { prompt: "Waves crashing on a rocky coastline", image: "https://example.com/coastline.jpg", }, ], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "1080p", length: 8 }, }, timeout: 600000, }); if (result.video) { await writeFile("ocean-director.mp4", result.video.data); } ``` ### Mixed Input Types Each segment's `image` field accepts a Buffer, file path, URL, or `ImageWithAltText`: ```typescript const result = await neurolink.generate({ input: { segments: [ { prompt: "Product reveal from shadow to light", image: await readFile("./product-dark.jpg"), // Buffer }, { prompt: "360-degree rotation showcasing all angles", image: "https://cdn.example.com/product-turntable.png", // URL }, { prompt: "Final hero shot with brand overlay", image: { data: await readFile("./hero.jpg"), altText: "Hero" }, // ImageWithAltText }, ], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "1080p", length: 6, aspectRatio: "16:9" }, }, }); ``` > **Note:** Director Mode is SDK-only. CLI support is not available for this generation type. Use the standard `--outputMode video` CLI flags for single-clip video generation. ## Comprehensive Examples ### Example 1: Product Commercial (3 Segments) ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { segments: [ { prompt: "Dramatic reveal: camera sweeps up from a dark surface to unveil the product under a spotlight", image: await readFile("./product-dark.jpg"), }, { prompt: "Close-up detail shot: camera slowly orbits the product, focusing on texture and craftsmanship", image: await readFile("./product-detail.jpg"), }, { prompt: "Lifestyle context: camera pulls back to show the product in an elegant room setting", image: await readFile("./product-lifestyle.jpg"), }, ], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "1080p", length: 8, aspectRatio: "16:9", audio: true, }, // Director-specific options director: { transitionPrompts: [ "Elegant dissolve with subtle camera drift", "Smooth pull-back revealing the wider scene", ], transitionDurations: [4, 6], // Per-transition: first transition 4s, second 6s }, }, timeout: 600000, }); if (result.video) { await writeFile("product-commercial.mp4", result.video.data); console.log("Director Mode output:", { totalDuration: result.video.metadata?.duration, // ~34s (3×8s + 4s + 6s) segmentCount: result.video.metadata?.segmentCount, // 3 transitionCount: result.video.metadata?.transitionCount, // 2 resolution: result.video.metadata?.dimensions, fileSize: `${(result.video.data.length / 1024 / 1024).toFixed(1)} MB`, }); } ``` ### Example 2: Social Media Story (Portrait, 4 Segments) ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { segments: [ { prompt: "Morning coffee being poured in slow motion", image: await readFile("./coffee.jpg"), }, { prompt: "Hands wrapping a gift box with a ribbon", image: await readFile("./wrapping.jpg"), }, { prompt: "Gift box placed on a doorstep, camera tilts up", image: await readFile("./doorstep.jpg"), }, { prompt: "Recipient opens door, reaction shot", image: await readFile("./reaction.jpg"), }, ], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "1080p", length: 4, aspectRatio: "9:16", // Portrait for stories/reels audio: true, }, director: { transitionPrompts: [ "Quick, energetic swipe transition", "Fast zoom through a blur into the next scene", "Snap cut with motion blur connecting the moments", ], transitionDurations: [4, 6, 8], // Each transition can have its own duration }, }, timeout: 900000, }); if (result.video) { await writeFile("story.mp4", result.video.data); // Total: 4×4s clips + transitions (4s + 6s + 8s) = 34 seconds } ``` ### Example 3: AI-Driven Storyboard ```typescript const neurolink = new NeuroLink(); // Step 1: Use AI to generate a storyboard from a concept const storyboard = await neurolink.generate({ input: { text: `Create a 3-scene storyboard for a 30-second product commercial for a luxury watch. Return a JSON array of objects with "scene" (number), "prompt" (video generation prompt), and "imageDescription" (what the input image should show).`, }, provider: "vertex", model: "gemini-3-flash-preview", output: { format: "json" }, }); const scenes = JSON.parse(storyboard.content); // Step 2: Generate video using the AI storyboard const watchImages = [ await readFile("./watch-closeup.jpg"), await readFile("./watch-wrist.jpg"), await readFile("./watch-lifestyle.jpg"), ]; const result = await neurolink.generate({ input: { segments: scenes.map((s: { prompt: string }, i: number) => ({ prompt: s.prompt, image: watchImages[i], })), }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "1080p", length: 8, aspectRatio: "16:9" }, director: { transitionPrompts: [ "Cinematic slow dissolve with depth of field shift", "Smooth pan transitioning to the next scene", ], }, }, timeout: 600000, }); if (result.video) { await writeFile("ai-storyboard.mp4", result.video.data); } ``` ### Example 4: Batch Director Mode ```typescript type StoryConfig = { name: string; segments: Array; }; async function batchDirectorGenerate(stories: StoryConfig[]) { const neurolink = new NeuroLink(); const results = []; for (const story of stories) { console.log(`Generating: ${story.name}`); try { const segments = await Promise.all( story.segments.map(async (seg) => ({ prompt: seg.prompt, image: await readFile(seg.imagePath), })), ); const result = await neurolink.generate({ input: { segments, }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "720p", length: 6 }, }, timeout: 600000, }); if (result.video) { const outputPath = `./output/${story.name}.mp4`; await writeFile(outputPath, result.video.data); results.push({ name: story.name, output: outputPath, success: true }); } } catch (error) { results.push({ name: story.name, success: false, error: error instanceof Error ? error.message : String(error), }); } } return results; } // Usage const results = await batchDirectorGenerate([ { name: "product-A", segments: [ { prompt: "Hero reveal", imagePath: "./a-hero.jpg" }, { prompt: "Feature showcase", imagePath: "./a-feature.jpg" }, { prompt: "Call to action", imagePath: "./a-cta.jpg" }, ], }, { name: "product-B", segments: [ { prompt: "Unboxing experience", imagePath: "./b-unbox.jpg" }, { prompt: "In-use demonstration", imagePath: "./b-demo.jpg" }, ], }, ]); console.table(results); ``` ### Example 5: Error Handling in Director Mode > **⚠️ Full-job retry warning:** The `generateWithRetry` function below retries the _entire_ `neurolink.generate()` call on any retriable `VideoError`. This means **all segments and transitions are re-generated from scratch**, incurring full cost each attempt ($10-60+ depending on settings). This is appropriate only for transient failures (e.g., rate limits) where partial results are not recoverable. > > Note that Director Mode already handles transition failures gracefully — failed transitions fall back to hard cuts rather than failing the pipeline (see [Partial Failure Handling](#partial-failure-handling)). Only fatal errors like `DIRECTOR_CLIP_FAILED` or `DIRECTOR_MERGE_FAILED` propagate as `VideoError`. Keep this in mind when deciding whether a full-job retry is warranted. > > **Preferred approach:** Once per-segment resume semantics are available, prefer retrying at the clip/transition level rather than re-running the entire pipeline. Until then, if you use full-job retry, keep `maxRetries` low (1-2) and restrict retries to rate-limit or timeout errors to control costs. ```typescript const neurolink = new NeuroLink(); // WARNING: Each retry re-runs ALL segments via neurolink.generate(), // incurring full API cost. See note above. async function generateWithRetry(maxRetries = 2) { for (let attempt = 1; attempt setTimeout(r, backoff)); continue; } } throw error; } } } ``` ## Type Definitions ### Director Mode Input (Extended `GenerateOptions`) Director Mode introduces a `DirectorSegment` type and adds a `segments` field to `GenerateOptions.input`: ```typescript /** * A single segment in Director Mode, representing one video clip. */ type DirectorSegment = { /** Prompt describing the video content for this segment */ prompt: string; /** Input image for this segment (Buffer, URL string, file path, or ImageWithAltText) */ image: Buffer | string | ImageWithAltText; }; type GenerateOptions = { input: { /** Prompt for standard (single-clip) mode */ text: string; /** Standard mode images */ images?: Array; /** * Director Mode segments. When provided, Director Mode is activated automatically. * Each segment contains its own prompt and image — no need for separate text/images arrays. * Must contain 2-10 segments. */ segments?: DirectorSegment[]; // ... other existing fields }; output?: { mode?: "text" | "video" | "ppt"; /** * Video output options. In Director Mode, `video.length` controls the * per-segment clip duration (4, 6, or 8 seconds). There is no separate * `segmentDurationSeconds` field — this single field applies uniformly * to all segments to avoid duplication and ambiguity. */ video?: VideoOutputOptions; /** Director Mode configuration (only used when input.segments is provided) */ director?: DirectorModeOptions; }; // ... other existing fields }; ``` ### DirectorModeOptions ```typescript type DirectorModeOptions = { /** * Prompts for generating transition clips (array of N-1 entries for N segments). * transitionPrompts[i] is used for the transition between segment i and segment i+1. * If provided, must contain exactly N-1 prompts where N is the number of segments. * * **When omitted:** The pipeline auto-generates a default prompt for each transition: * `"Smooth cinematic transition between scenes"`. This produces a generic but * visually coherent interpolation. For narrative-driven videos, explicit prompts * that describe the desired camera movement or visual flow are recommended. */ transitionPrompts?: string[]; /** * Duration of each transition clip in seconds (array of N-1 entries for N segments). * transitionDurations[i] sets the duration for the transition between segment i and segment i+1. * Each value must be 4, 6, or 8 (4 recommended for seamless feel). * If omitted, all transitions default to 4 seconds. * @default [4, 4, ...] (all 4s) */ transitionDurations?: Array; }; ``` > **Note:** Concurrency is fixed internally at 2 parallel Vertex API calls. This is not user-configurable — it balances throughput against API rate limits and is shared across both clip generation and transition generation phases. ### Extended VideoGenerationResult (Director Mode) ```typescript type VideoGenerationResult = { data: Buffer; mediaType: "video/mp4" | "video/webm"; metadata?: { // Standard fields duration?: number; dimensions?: { width: number; height: number }; model?: string; provider?: string; aspectRatio?: string; audioEnabled?: boolean; processingTime?: number; // Director Mode fields (present when Director Mode is used) /** Number of main segments in the video */ segmentCount?: number; /** Number of transition clips generated */ transitionCount?: number; /** Duration of each main clip in seconds */ clipDuration?: number; /** Durations of each transition in seconds (one per transition) */ transitionDurations?: number[]; /** Per-segment metadata */ segments?: Array; /** Per-transition metadata */ transitions?: Array; }; }; ``` ## Architecture & Implementation ### Pipeline Flow ``` User Input (N segments, each with prompt + image) │ ▼ ┌─────────────────────────────────┐ │ 1. Validation │ │ - Validate each segment has │ │ prompt and image │ │ - Enforce segment limit (≤10) │ └─────────────────┬───────────────┘ │ ▼ ┌─────────────────────────────────┐ │ 2. Parallel Clip Generation │ │ - Generate N clips via │ │ generateVideoWithVertex() │ │ - Respect concurrency limit │ └─────────────────┬───────────────┘ │ ▼ ┌─────────────────────────────────┐ │ 3. Frame Extraction │ │ - Extract last frame from │ │ clip[i] (decode MP4 → JPEG) │ │ - Extract first frame from │ │ clip[i+1] │ └─────────────────┬───────────────┘ │ ▼ ┌─────────────────────────────────┐ │ 4. Parallel Transition Gen. │ │ - For each pair (i, i+1): │ │ Call Veo with image (last │ │ frame) + lastFrame (first │ │ frame of next clip) │ │ - Per-transition duration │ │ - Parallel (concurrency = 2) │ │ - Failures → hard cut fallback │ └─────────────────┬───────────────┘ │ ▼ ┌─────────────────────────────────┐ │ 5. Video Merge │ │ - Concatenate: │ │ clip1 + trans1 + clip2 + │ │ trans2 + ... + clipN │ │ - Re-mux to single MP4 │ └─────────────────┬───────────────┘ │ ▼ VideoGenerationResult (merged buffer + metadata) ``` ### Dependency DAG The pipeline has a **per-pair dependency structure** — each transition depends only on its two adjacent clips, not on all clips globally. Understanding this DAG is essential for maximizing parallelism without race conditions: ``` Phase 1 – Clip Generation (parallel, subject to concurrency limit): Clip₁ Clip₂ Clip₃ ... ClipN │ │ │ │ ▼ ▼ ▼ ▼ Phase 2 – Frame Extraction (per-clip, runs as soon as a clip completes): lastFrame₁ firstFrame₂ lastFrame₂ firstFrame₃ ... firstFrameN │ │ │ │ │ └──────┬──────┘ └──────┬──────┘ │ ▼ ▼ │ Phase 3 – Parallel Transition Generation (per-pair, each depends on its two boundary frames): (once Clip₁ & Clip₂ done) (once Clip₂ & Clip₃ done) Trans₁₋₂ Trans₂₋₃ ... Trans₍N₋₁₎₋N │ │ │ └───────────┬───────────────┘───────────────────────┘ ▼ Phase 4 – Sequential Merge (must wait for ALL clips and transitions): Clip₁ → Trans₁₋₂ → Clip₂ → Trans₂₋₃ → Clip₃ → ... → ClipN │ ▼ Final Merged Video ``` **Key constraint:** Each transition Trans₍ᵢ₎₋₍ᵢ₊₁₎ depends only on Clip₍ᵢ₎ and Clip₍ᵢ₊₁₎ — specifically, the last frame of Clip₍ᵢ₎ and the first frame of Clip₍ᵢ₊₁₎. Frame extraction runs per-clip as soon as each Clip₍ᵢ₎ finishes (not after all clips complete). Transition generation then runs in parallel (concurrency = 2, shared with the clip phase) as soon as the required adjacent clip pair is ready. Each transition that fails degrades to a hard cut rather than failing the pipeline. Phase 4 (merge) remains strictly sequential and must wait for all clips and transitions to complete before concatenation. **Circuit breaker:** During clip generation, if 2 consecutive clips fail, the circuit breaker trips and remaining clips are skipped immediately. This avoids wasting API quota on a provider that is likely experiencing an outage. ### Technology Dependencies #### FFmpeg Adapter (`ffmpegAdapter.ts`) All video operations (frame extraction and merging) use a **shared FFmpeg adapter** (`ffmpegAdapter.ts`) that centralizes: - **Binary resolution:** FFmpeg path is resolved once and cached. Resolution order: 1. `FFMPEG_PATH` environment variable (explicit path) 2. `ffmpeg-static` npm package (optional peer dependency) 3. System `ffmpeg` on PATH - **Temp directory management:** Creates tracked temp directories with process-level cleanup handlers (`process.on("exit")`) to prevent orphaned files on abnormal exit. - **Buffer validation:** `isValidMp4Buffer()` checks minimum size (12 bytes) and MP4 ftyp box magic bytes at offset 4-7 before any FFmpeg processing. - **Named constants:** All timeouts, buffer sizes, and quality parameters are exported constants (`FFMPEG_FRAME_TIMEOUT_MS=30s`, `FFMPEG_MERGE_TIMEOUT_MS=120s`, `JPEG_QUALITY="2"`, etc.). #### Frame Extraction (`frameExtractor.ts`) Frame extraction uses the native FFmpeg binary via the shared adapter: - **Operation:** Writes video buffer to a temp file → runs FFmpeg to seek and extract → reads JPEG output → cleans up temp files. - **Validation:** Each input buffer is validated with `isValidMp4Buffer()` before processing. Invalid buffers throw `VideoError` with `DIRECTOR_FRAME_EXTRACTION_FAILED` code. - **Performance:** First/last frame extraction from a 4-8s clip completes in \ **Dependency:** A native `ffmpeg` binary is required. Install via your OS package manager, Docker layer, Lambda layer, or the optional `ffmpeg-static` npm package. Set `FFMPEG_PATH` to explicitly specify the binary location. ```` ### Transition Generation: Veo API Request Each transition clip uses the **first-and-last-frame** Veo endpoint. The request body includes both `image` (first frame = last frame of previous clip) and `lastFrame` (last frame = first frame of next clip): ```typescript const transitionRequestBody = { instances: [ { prompt: transitionPrompts[i], // i-th transition prompt (0-indexed) image: { bytesBase64Encoded: lastFrameOfClipN, // Last frame of preceding clip mimeType: "image/jpeg", }, lastFrame: { bytesBase64Encoded: firstFrameOfClipN1, // First frame of following clip mimeType: "image/jpeg", }, }, ], parameters: { sampleCount: 1, durationSeconds: transitionDurations[i], // Per-transition duration (4, 6, or 8) aspectRatio: "16:9", // Matches main clips resolution: "720p", // Matches main clips generateAudio: true, // Matches main clips }, }; ```` This uses the same `predictLongRunning` → `fetchPredictOperation` polling flow as standard video generation, with the addition of the `lastFrame` field. ### Implementation Files | File | Purpose | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | `src/lib/adapters/video/vertexVideoHandler.ts` | Extended with `generateTransitionWithVertex()`, `lastFrame` support, `VideoError`, `VIDEO_ERROR_CODES` | | `src/lib/adapters/video/directorPipeline.ts` | Director Mode orchestrator: parallel clip generation (circuit breaker), parallel transitions, merge | | `src/lib/adapters/video/ffmpegAdapter.ts` | Shared FFmpeg adapter: binary resolution, temp file management, process execution, buffer validation | | `src/lib/adapters/video/frameExtractor.ts` | Extract first/last frames from MP4 buffers via native FFmpeg binary | | `src/lib/adapters/video/videoMerger.ts` | Concatenate video buffers into single MP4 via FFmpeg concat demuxer (lossless when codecs match) | | `src/lib/types/multimodal.ts` | `DirectorSegment`, `DirectorModeOptions` type definitions | | `src/lib/types/generateTypes.ts` | Extended `GenerateOptions` input with `segments` field | | `src/lib/core/baseProvider.ts` | Director Mode detection and routing in `handleVideoGeneration()` | | `src/lib/utils/parameterValidation.ts` | `validateDirectorModeInput()` validation | ### Key Functions - **`generateTransitionWithVertex(firstFrame, lastFrame, prompt, options, duration, region)`** – Generates a transition clip using Veo 3.1 Fast's first-and-last-frame API - **`extractFirstFrame(videoBuffer)`** – Extracts the first frame from a video buffer as JPEG (validates MP4 ftyp header) - **`extractLastFrame(videoBuffer)`** – Extracts the last frame from a video buffer as JPEG (validates MP4 ftyp header) - **`mergeVideoBuffers(buffers)`** – Concatenates multiple MP4 buffers into one (validates each buffer) - **`executeDirectorPipeline(segments, videoOptions, directorOptions, region)`** – Full Director Mode orchestrator - **`validateDirectorModeInput(options)`** – Validates segment structure, count, transition prompts/durations - **`isValidMp4Buffer(buffer)`** – Validates MP4 buffer has ftyp header (from `ffmpegAdapter.ts`) - **`getFfmpegPath()`** – Resolves FFmpeg binary path with caching (from `ffmpegAdapter.ts`) ## Configuration & Best Practices ### Duration Calculation > **Note:** In Director Mode, `output.video.length` controls the duration of each main segment clip. There is no separate `segmentDurationSeconds` field — the existing `VideoOutputOptions.length` is reused to avoid duplication. All segments share the same clip duration; per-segment duration variance is not currently supported (use different Director Mode calls if needed). Each transition can have its own duration, so the total is the sum of all clip durations plus the sum of all individual transition durations: | Segments | Clip Duration | Transition Durations | Total Duration | | -------- | ------------- | -------------------- | ------------------------- | | 2 | 6s | [4s] | 16s (2×6 + 4) | | 3 | 8s | [4s, 6s] | 34s (3×8 + 4 + 6) | | 4 | 4s | [4s, 6s, 8s] | 34s (4×4 + 4 + 6 + 8) | | 5 | 6s | [4s, 6s, 4s, 8s] | 52s (5×6 + 4 + 6 + 4 + 8) | | N | Ds | [T₁, T₂, …, T₍ₙ₋₁₎] | N×D + Σ Tᵢ | ### API Call Count | Segments | Main Clips | Transition Clips | Total API Calls | | -------- | ---------- | ---------------- | --------------- | | 2 | 2 | 1 | 3 | | 3 | 3 | 2 | 5 | | 5 | 5 | 4 | 9 | | 10 | 10 | 9 | 19 | ### Worst-Case Analysis (10 Segments at Maximum Settings) The 10-segment limit balances capability with practical constraints: | Metric | Value | Calculation | | ------------------------ | ------------ | ---------------------------------------------------------- | | **Total API calls** | 19 | 10 clips + 9 transitions | | **Wall-clock time** | ~25 minutes | ceil(10/2) × 3min (clips) + ceil(9/2) × 2min (transitions) | | **Total video duration** | ~152 seconds | 10 × 8s (clips) + 9 × 8s (transitions, worst case) | | **Burst quota required** | 2 concurrent | Fixed concurrency of 2 | > **Why 10?** Beyond 10 segments, single-pipeline wall-clock time exceeds 30 minutes and costs grow proportionally. For longer productions, chain multiple Director Mode calls and concatenate the outputs externally, or use the upcoming Batch Director API. ### Best Practices #### 1. Prompt Engineering for Transitions ```typescript // ❌ Generic / unhelpful const badTransition = "Make a transition"; // ✅ Describe the camera movement or visual flow const goodTransition = "Camera smoothly drifts right, transitioning between scenes"; // ✅ Match the scene context const contextualTransition = "Focus shifts from foreground to background as light changes"; // ✅ Use per-transition prompts for narrative coherence const perTransition = [ "Camera follows a path from the garden into the house", "Time-lapse of light changing from day to dusk", ]; ``` #### 2. Image Preparation for Smooth Transitions ```typescript // Best results when adjacent segments share visual characteristics: // - Similar color palette // - Compatible lighting conditions // - Related subject matter // The Veo interpolation works best when: // 1. Both frames have similar aspect ratios to the target // 2. The visual distance between frames is moderate (not extreme jumps) // 3. Images are well-exposed and sharp ``` #### 3. Timeout Configuration ```typescript // Rule of thumb: ~2-3 minutes per video generation call // With fixed concurrency=2: timeout ≥ ceil(N/2) × 180000 + ceil((N-1)/2) × 180000 // 3 segments: ~10 minutes const threeSegments = { timeout: 600000 }; // 5 segments: ~15 minutes const fiveSegments = { timeout: 900000 }; // 10 segments: ~30 minutes const tenSegments = { timeout: 1800000 }; ``` #### 4. Cost Optimization | Strategy | Impact | Trade-off | | ------------------------------------- | ----------------- | ---------------------- | | Use 720p for drafts | ~20% lower cost | Lower visual quality | | Use 4s clips for previews | ~50% lower cost | Shorter segments | | Limit to 3-5 segments | Fewer API calls | Shorter total video | | Use `veo-3.1-fast` for main clips too | Faster generation | Slightly lower quality | > **Pricing reference:** Look up current per-second rates for Veo 3.1 (main clips) and Veo 3.1 Fast (transitions) on the [Vertex AI Generative AI pricing page](https://cloud.google.com/vertex-ai/generative-ai/pricing). Rates vary by resolution (720p vs 1080p) and model variant. ## Error Handling & Validation ### Director Mode Validation Rules | Parameter | Validation | Error Message | | -------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | `input.segments` | Must be array with 2-10 entries | `Director Mode requires 2-10 segments` | | `input.segments[i].prompt` | Must be a non-empty string | `Segment X requires a non-empty prompt` | | `input.segments[i].image` | Must be Buffer, string (URL/path), or ImageWithAltText | `Segment X requires a valid image (Buffer, URL, path, or ImageWithAltText)` | | `transitionPrompts` | Optional; if provided, length must be N-1 | `Expected X transition prompts, got Y` | | `transitionDurations` | Optional; if provided, array of N-1 values, each 4, 6, or 8 | `Expected N-1 transition durations, got X` / `Invalid transition duration at index X. Use 4, 6, or 8` | | Segment limit | Max 10 segments | `Director Mode supports up to 10 segments` | ### Partial Failure Handling Director Mode uses a **differentiated failure strategy** depending on which pipeline stage fails: | Failure Type | Behavior | Rationale | | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | **Main clip generation fails** | Pipeline fails immediately with `DIRECTOR_CLIP_FAILED` error. Returns metadata about which segments succeeded (for debugging). | A missing segment cannot be meaningfully recovered — the final video would have a gap. | | **Frame extraction fails** | Retry extraction once. If retry fails, skip the affected transition and fall back to a hard cut. | Frame extraction is a local CPU operation; transient failures are rare but possible with corrupted buffers. | | **Transition generation fails** | Skip the failed transition and concatenate adjacent clips directly (hard cut). Log a warning. | A missing transition degrades quality but produces a valid video. The user can re-run with a simpler transition prompt. | | **Video merge fails** | Pipeline fails with `DIRECTOR_MERGE_FAILED` error. Returns individual clip buffers in `error.context.clipBuffers` for manual recovery. | Merge failure is non-recoverable within the pipeline, but individual clips are still valuable. | **Design rationale:** Main clip failures are fatal because there's no sensible way to fill a segment gap. Transition failures are non-fatal because a hard cut (direct concatenation) is a valid — if less polished — editing technique. This mirrors how professional video editors treat transitions as optional polish, not structural requirements. **Partial result metadata:** When transitions fall back to hard cuts, the result metadata indicates which transitions were skipped: ```typescript // If a transition clip fails, the pipeline can: // 1. Skip the transition (hard cut between clips) // 2. Retry the transition with a simpler prompt // 3. Fail the entire operation (default for main clip failures) const result = await neurolink.generate({ input: { segments: [ { prompt: "Scene 1", image: img1 }, { prompt: "Scene 2", image: img2 }, { prompt: "Scene 3", image: img3 }, ], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "720p", length: 6 }, director: { transitionPrompts: [ "Smooth cinematic transition between scenes", "Gentle camera drift connecting the moments", ], }, }, }); // If transition 1→2 fails but clips succeed, the result may contain // a hard cut at that point. Check metadata for details: if (result.video?.metadata?.transitions) { for (const tx of result.video.metadata.transitions) { if (!tx.duration) { console.warn( `Transition ${tx.fromSegment}→${tx.toSegment} used hard cut`, ); } } } ``` ### Error Types Director Mode error codes are part of the unified `VIDEO_ERROR_CODES` constant exported from `vertexVideoHandler.ts`. All Director Mode errors are thrown as `VideoError` (extends `NeuroLinkError`): ```typescript // Director-specific codes within VIDEO_ERROR_CODES const VIDEO_ERROR_CODES = { // Standard video error codes GENERATION_FAILED: "VIDEO_GENERATION_FAILED", PROVIDER_NOT_CONFIGURED: "VIDEO_PROVIDER_NOT_CONFIGURED", POLL_TIMEOUT: "VIDEO_POLL_TIMEOUT", INVALID_INPUT: "VIDEO_INVALID_INPUT", // Director Mode error codes /** Invalid segment structure (missing prompt or image) */ DIRECTOR_SEGMENT_MISMATCH: "DIRECTOR_SEGMENT_MISMATCH", /** Too many segments requested */ DIRECTOR_SEGMENT_LIMIT_EXCEEDED: "DIRECTOR_SEGMENT_LIMIT_EXCEEDED", /** A main clip generation call failed (fatal) */ DIRECTOR_CLIP_FAILED: "DIRECTOR_CLIP_FAILED", /** Frame extraction from clip failed */ DIRECTOR_FRAME_EXTRACTION_FAILED: "DIRECTOR_FRAME_EXTRACTION_FAILED", /** Transition clip generation failed (non-fatal, falls back to hard cut) */ DIRECTOR_TRANSITION_FAILED: "DIRECTOR_TRANSITION_FAILED", /** Video merge/concatenation failed */ DIRECTOR_MERGE_FAILED: "DIRECTOR_MERGE_FAILED", /** Pipeline timeout (overall) */ DIRECTOR_PIPELINE_TIMEOUT: "DIRECTOR_PIPELINE_TIMEOUT", } as const; ``` ## Comparison: Standard vs Director Mode | Feature | Standard Video Generation | Director Mode | | --------------- | ----------------------------- | ------------------------------------------------------------ | | Input format | `input.text` + `input.images` | `input.segments` array (2-10 `DirectorSegment` objects) | | Output | Single clip (4-8s) | Merged multi-segment video | | Transitions | N/A | AI-generated clips with per-transition duration (4-8s) | | API calls | 1 | N + (N-1) calls | | Veo API feature | `image` only | `image` + `lastFrame` | | Processing time | 1-3 minutes | 5-30 minutes (depends on segment count) | | Max duration | 8 seconds | ~152s (10×8s clips + 9×8s transitions max) | | Concurrency | N/A | Fixed at 2 parallel operations (clips + transitions) | | Error recovery | All-or-nothing | Circuit breaker for clips, hard cut fallback for transitions | ## Troubleshooting | Symptom | Cause | Solution | | ---------------------------------- | ------------------------------------------- | ---------------------------------------------------------- | | "Segment mismatch" error | Missing prompt or image in a segment | Ensure each segment has both `prompt` and `image` | | Transition looks jarring | Large visual gap between adjacent clips | Use visually similar images; improve transition prompt | | Pipeline timeout | Too many segments or high resolution | Reduce segment count, use 720p, or increase timeout | | Rate limit errors | Too many concurrent API calls | Concurrency is fixed at 2; reduce segment count instead | | Frame extraction fails | Corrupted video buffer | Retry the failed clip generation | | Audio discontinuity at transitions | Each clip has independently generated audio | Expected behavior — transition clips bridge the audio gap | | "Segment limit exceeded" | More than 10 segments provided | Split into multiple Director Mode calls | | High cost | Many high-resolution segments | Use 720p and 4s clips for drafts, upgrade for final output | ### Debug Mode ```typescript // Enable debug logging to trace the Director pipeline const neurolink = new NeuroLink({ debug: true, logLevel: "verbose", }); // Or via environment variable // export NEUROLINK_DEBUG=true // Debug output shows: // - Segment validation results // - Per-clip generation start/completion // - Frame extraction timing // - Transition generation details // - Merge operation status ``` ## Limitations | Limitation | Description | Workaround | | ---------------------- | ---------------------------------------------------------- | ------------------------------------------------------------- | | Max 10 segments | API and processing constraints | Chain multiple Director Mode calls | | Fixed transition model | Transitions always use `veo-3.1-fast`; not configurable | N/A | | No custom audio | Audio is AI-generated for each clip independently | Post-process with external audio editing tools | | Fixed concurrency | Concurrency is hardcoded to 2; not user-configurable | Adjust segment count to control API load | | Requires native FFmpeg | FFmpeg binary must be available for frame extraction/merge | Install via package manager, Docker layer, or `ffmpeg-static` | | MP4 output only | Merged output is always MP4 | Convert with ffmpeg post-generation if needed | | Vertex AI only | Veo models are Vertex-exclusive | No alternative providers currently | | Processing time | Multi-segment is inherently slower | Use lower resolution and shorter clips for drafts | ## Related Features - [Video Generation](/docs/features/video-generation) – Single-clip video generation (Director Mode builds on this) - [Multimodal Chat](/docs/features/multimodal-chat) – Image and file input capabilities - [Video Analysis](./video-analysis) – Analyze existing video content **Next:** [Video Generation](/docs/features/video-generation) | [Multimodal Chat](/docs/features/multimodal-chat) --- ## Video Generation with Veo 3.1 # Video Generation with Veo 3.1 NeuroLink integrates multiple video-generation providers — Google's Veo 3.1 (default), Kling, Runway, and Replicate-hosted models — behind a single `nl.generate({ output: { mode: "video" } })` call. Transform static images into dynamic, professional-quality video content with synchronized audio (where the provider supports it). ## Overview Video generation in NeuroLink dispatches through the central `VideoProcessor` registry. The system uses the existing `generate()` function with video-specific options: 1. **Accepts** an input image via `input.images` and text prompt via `input.text` 2. **Validates** image format, size, and aspect ratio requirements 3. **Selects** the handler matching `output.video.provider` (default `"vertex"`) — see [Routing Across Providers](#routing-across-providers) below 4. **Generates** a clip (length / audio / resolution support varies per provider) 5. **Returns** a `VideoGenerationResult` containing video buffer and metadata ```mermaid graph LR A[Input Image] --> B[NeuroLink SDK] C[Text Prompt] --> B B --> D{VideoProcessor} D -->|"provider:vertex (default)"| E[Vertex Veo 3.1] D -->|"provider:kling"| F[PiAPI Kling] D -->|"provider:runway"| G[Runway gen3] D -->|"provider:replicate"| H[Replicate model] E --> I[VideoGenerationResult] F --> I G --> I H --> I I --> J[Save / Stream / Process] ``` ## What You Get - **Video with audio** – Generate 8-second video clips with synchronized audio from a single image and text prompt - **SDK integration** – Use existing `neurolink.generate()` with `output.mode: "video"` to create videos - **CLI support** – Generate videos directly from the command line with `--outputMode video` - **Buffer-based output** – Receive video as Buffer objects via `VideoGenerationResult` for flexible post-processing - **Multiple resolutions** – Support for 720p and 1080p output - **Aspect ratio control** – Choose between 9:16 (portrait) and 16:9 (landscape) formats - **Director Mode** – Chain multiple segments into one continuous video with AI-generated transitions (see [Video Director Mode](./video-director-mode)) ## Supported Providers & Models `nl.generate({ output: { mode: "video", video: { provider } } })` dispatches through the central `VideoProcessor` registry, which knows four shipped handlers. The default when `provider` is omitted is `vertex`. ### Provider Compatibility | Provider | Default Model | Length | Audio | Input | Auth | Notes | | ----------- | ----------------------------------------- | -------------- | -------------- | ------------------------------------ | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `vertex` | `veo-3.1` | 4 / 6 / 8 s | Yes | image + text prompt | `GOOGLE_APPLICATION_CREDENTIALS` | Default — best fit for GCP / Vertex tenants | | `kling` | PiAPI Kling v1.6 | 5 / 10 s | No | publicly accessible image URL + text | `KLING_API_KEY` (PiAPI token) | Requires `imageUrl` (handler rejects inline base64). See [provider guide](/docs/getting-started/providers/kling). | | `runway` | Runway gen3 | 5 / 10 s | No | image + text | `RUNWAY_API_KEY` | Length must be 5 or 10 (rejected at upstream if 4). See [provider guide](/docs/getting-started/providers/runway). | | `replicate` | `meta/wan-2-2/i2v` (override via `model`) | Model-specific | Model-specific | image + text | `REPLICATE_API_TOKEN` | Any image-to-video model on Replicate via `video.model`. See [provider guide](/docs/getting-started/providers/replicate). | ### Model Versions & Capabilities | Model Version | Release Date | Key Features | Notes | | ------------- | ------------ | ----------------------------- | ------------------------------- | | `veo-3.1` | 2024 | Audio generation, 8s duration | **Default for `vertex`** | | `kling-v1.6` | 2024 | Sharp motion, 720p / 1080p | Routed via PiAPI | | `gen3-turbo` | 2024 | 5 s / 10 s clips, 720p+ | Runway's faster generation tier | > **Note:** Use the per-provider setup pages > ([Vertex Veo](/docs/getting-started/providers/google-vertex), > [Kling](/docs/getting-started/providers/kling), > [Runway](/docs/getting-started/providers/runway), > [Replicate](/docs/getting-started/providers/replicate)) > for credential and quota details. ### Known Limitations - `vertex`: max video duration 8 seconds per clip (4 / 6 / 8 s); image required; audio auto-generated; concurrent request limit 5 per project; processing 30–120 s - `kling`: image must be a publicly accessible URL — pass `video.imageUrl`. Inline `Buffer` images are rejected at the handler - `runway`: length validated upstream as 5 or 10 seconds — using `4` will surface a Runway 400. The local 4 / 6 / 8 schema gate matches Vertex's contract; future versions may widen the type - `replicate`: per-model quirks (some models have token caps, some return WebP/GIF). Override `video.model` to pick a specific model checkpoint - For multi-segment videos with transitions, see [Video Director Mode](./video-director-mode) (currently Vertex-only) ### Routing Across Providers Pick a provider per-call by setting `output.video.provider`: ```typescript // Vertex (default — same as omitting `provider`) await nl.generate({ input: { text: "...", images: [imageBuffer] }, output: { mode: "video", video: { provider: "vertex", length: 6, resolution: "720p" }, }, }); // Kling (PiAPI) — requires a publicly accessible image URL, not a Buffer await nl.generate({ input: { text: "...", images: [imageBuffer] }, output: { mode: "video", video: { provider: "kling", imageUrl: "https://your-cdn.example.com/source.jpg", length: 5, resolution: "720p", }, }, }); // Runway gen3 — length must be 5 or 10 upstream await nl.generate({ input: { text: "...", images: [imageBuffer] }, output: { mode: "video", video: { provider: "runway", length: 5, resolution: "720p" }, }, }); // Replicate (any image-to-video model) await nl.generate({ input: { text: "...", images: [imageBuffer] }, output: { mode: "video", video: { provider: "replicate", model: "meta/wan-2-2/i2v", length: 4 }, }, }); ``` `result.provider` echoes the chosen handler — useful for logging and multi-provider A/B harnesses. #### Unknown Provider Behavior Passing an unregistered provider name throws a typed `VideoError(VIDEO_ERROR_CODES.PROVIDER_NOT_SUPPORTED)` with the list of known names. NeuroLink does **not** silently fall back to Vertex when the requested provider is unknown — a misspelled provider is always surfaced as an error. ```typescript try { await nl.generate({ input: { text: "...", images: [imageBuffer] }, output: { mode: "video", video: { provider: "klng" /* typo */ } }, }); } catch (err) { // err.code === "VIDEO_PROVIDER_NOT_SUPPORTED" // err.context.available === ["vertex", "kling", "runway", "replicate"] } ``` ## Prerequisites 1. **Vertex AI credentials** with Veo access enabled 2. **Google Cloud project** with billing enabled 3. **Service account** with `aiplatform.user` role 4. **Sufficient storage** for video buffers (each 8-second video is approximately 2-5 MB) ## Quick Start ### SDK Usage ```typescript const neurolink = new NeuroLink(); // Basic video generation using generate() with video output mode const result = await neurolink.generate({ input: { text: "Camera slowly zooms in on the product with soft lighting", images: [readFileSync("./product-image.jpg")], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "720p", length: 8, aspectRatio: "16:9", audio: true, }, }, }); // Access video data from VideoGenerationResult if (result.video) { writeFileSync("output.mp4", result.video.data); console.log(`Video generated: ${result.video.metadata?.duration}s`); } ``` #### With Full Options ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Dynamic camera movement showcasing the product from multiple angles", images: [await readFile("./input.jpg")], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "1080p", length: 8, aspectRatio: "16:9", audio: true, }, }, }); if (result.video) { await writeFile("output.mp4", result.video.data); console.log("Video metadata:", { duration: result.video.metadata?.duration, dimensions: result.video.metadata?.dimensions, format: result.video.mediaType, }); } ``` #### Image URL Input ```typescript const neurolink = new NeuroLink(); // Use image URL instead of Buffer const result = await neurolink.generate({ input: { text: "Elegant rotation revealing product details", images: ["https://example.com/product.png"], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "720p", length: 8, }, }, }); if (result.video) { await writeFile("output.mp4", result.video.data); } ``` ### CLI Usage ```bash # Basic video generation npx @juspay/neurolink generate "Create a product showcase video" \ --image ./input.jpg \ --videoOutput ./output.mp4 # Full options npx @juspay/neurolink generate "Dynamic camera movement" \ --image ./input.jpg \ --provider vertex \ --model veo-3.1 \ --videoResolution 1080p \ --videoLength 8 \ --videoAspectRatio 16:9 \ --videoAudio true \ --videoOutput ./output.mp4 # JSON output mode (for scripting) npx @juspay/neurolink generate "prompt" \ --image input.jpg \ --videoOutput output.mp4 \ --format json # With analytics npx @juspay/neurolink generate "Camera pans across futuristic city" \ --image ./input-city.jpg \ --videoResolution 1080p \ --videoOutput ./city-video.mp4 \ --enable-analytics ``` ### CLI Arguments | Argument | Type | Default | Description | | -------------------- | ------- | -------------- | -------------------------------------- | | `--image` | string | Required | Path to the input image file | | `--videoOutput` | string | `./output.mp4` | Path to save the generated video | | `--provider` | string | `vertex` | AI provider to use | | `--model` | string | `veo-3.1` | Model version | | `--videoResolution` | string | `720p` | Output resolution (`720p` or `1080p`) | | `--videoLength` | number | `4` | Video duration in seconds (4, 6, or 8) | | `--videoAspectRatio` | string | `16:9` | Aspect ratio (`9:16` or `16:9`) | | `--videoAudio` | boolean | `true` | Enable audio generation | ## Comprehensive Examples ### Example 1: Basic Video Generation ```typescript const neurolink = new NeuroLink(); async function generateSingleVideo() { const result = await neurolink.generate({ input: { text: "Smooth camera pan revealing the product with ambient lighting", images: [await readFile("./product-hero.jpg")], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "720p", length: 8 }, }, }); if (result.video) { await writeFile("product-video.mp4", result.video.data); console.log({ duration: result.video.metadata?.duration, dimensions: result.video.metadata?.dimensions, mediaType: result.video.mediaType, size: result.video.data.length, }); } } ``` ### Example 2: Batch Video Generation ```typescript const neurolink = new NeuroLink(); async function batchGenerateVideos( inputDir: string, outputDir: string, prompt: string, ) { const files = await readdir(inputDir); const imageFiles = files.filter((f) => [".jpg", ".jpeg", ".png", ".webp"].includes(path.extname(f).toLowerCase()), ); const results = []; for (const imageFile of imageFiles) { console.log(`Processing: ${imageFile}`); try { const imageBuffer = await readFile(path.join(inputDir, imageFile)); const result = await neurolink.generate({ input: { text: prompt, images: [imageBuffer], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "720p", length: 8 }, }, }); if (result.video) { const outputPath = path.join( outputDir, `${path.basename(imageFile, path.extname(imageFile))}.mp4`, ); await writeFile(outputPath, result.video.data); results.push({ input: imageFile, output: outputPath, duration: result.video.metadata?.duration, success: true, }); } } catch (error) { results.push({ input: imageFile, error: error instanceof Error ? error.message : "Unknown error", success: false, }); } } return results; } // Usage const results = await batchGenerateVideos( "./product-images", "./product-videos", "Dynamic product showcase with smooth camera movement", ); console.table(results); ``` ### Example 3: Different Aspect Ratios ```typescript const neurolink = new NeuroLink(); // Portrait video for social media stories/reels const portrait = await neurolink.generate({ input: { text: "Vertical video with upward camera movement", images: [await readFile("./portrait-image.jpg")], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "1080p", aspectRatio: "9:16", length: 8, }, }, }); // Landscape video for YouTube/websites const landscape = await neurolink.generate({ input: { text: "Cinematic horizontal pan across the scene", images: [await readFile("./landscape-image.jpg")], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "1080p", aspectRatio: "16:9", length: 8, }, }, }); ``` ### Example 4: Integration with Image Analysis ```typescript const neurolink = new NeuroLink(); // Step 1: Analyze product image and generate video concept const analysis = await neurolink.generate({ input: { text: `Analyze this product image and suggest a compelling video concept. Focus on key visual features and motion opportunities.`, images: [await readFile("product-image.jpg")], }, provider: "vertex", model: "gemini-3-flash-preview", }); console.log("AI Video Concept:", analysis.content); // Step 2: Generate video using AI-suggested prompt const result = await neurolink.generate({ input: { text: analysis.content, // Use AI-generated prompt images: [await readFile("product-image.jpg")], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "1080p", aspectRatio: "16:9", length: 8, }, }, }); if (result.video) { await writeFile("ai-directed-video.mp4", result.video.data); console.log("AI-driven video generation complete!"); } ``` ### Example 5: Error Handling ```typescript const neurolink = new NeuroLink(); async function generateVideoWithErrorHandling( imagePath: string, prompt: string, ) { const maxRetries = 3; let lastError: Error | null = null; for (let attempt = 1; attempt setTimeout(resolve, waitTime)); continue; } if (error.category === "network" && error.retriable) { console.log(`Network error on attempt ${attempt}. Retrying...`); await new Promise((resolve) => setTimeout(resolve, 2000)); continue; } if (error.category === "execution") { console.error(`Execution error: ${error.message}`); throw error; } } throw error; } } throw lastError || new Error("Max retries exceeded"); } ``` ### Example 6: Video Generation Pipeline ```typescript type PipelineConfig = { inputDir: string; outputDir: string; prompts: Record; // filename pattern -> prompt defaultPrompt: string; resolution: "720p" | "1080p"; aspectRatio: "9:16" | "16:9"; concurrency: number; }; async function videoPipeline(config: PipelineConfig) { const neurolink = new NeuroLink(); const limit = pLimit(config.concurrency); // Ensure output directory exists await mkdir(config.outputDir, { recursive: true }); // Get all image files const files = await readdir(config.inputDir); const imageFiles = files.filter((f) => /\.(jpg|jpeg|png|webp)$/i.test(f)); // Process with concurrency limit const results = await Promise.all( imageFiles.map((imageFile) => limit(async () => { // Find matching prompt pattern or use default const prompt = Object.entries(config.prompts).find(([pattern]) => imageFile.startsWith(pattern), )?.[1] || config.defaultPrompt; try { const imageBuffer = await readFile( path.join(config.inputDir, imageFile), ); const result = await neurolink.generate({ input: { text: prompt, images: [imageBuffer], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: config.resolution, aspectRatio: config.aspectRatio, length: 8, }, }, }); if (result.video) { const outputPath = path.join( config.outputDir, `${path.basename(imageFile, path.extname(imageFile))}.mp4`, ); await writeFile(outputPath, result.video.data); return { input: imageFile, output: outputPath, duration: result.video.metadata?.duration, success: true, }; } return { input: imageFile, success: false, error: "No video generated", }; } catch (error) { return { input: imageFile, success: false, error: error instanceof Error ? error.message : "Unknown error", }; } }), ), ); return results; } // Usage const pipelineResults = await videoPipeline({ inputDir: "./raw-images", outputDir: "./generated-videos", prompts: { "product-": "Elegant product rotation with soft lighting", "hero-": "Dramatic zoom with cinematic lighting", "lifestyle-": "Natural movement with ambient atmosphere", }, defaultPrompt: "Smooth camera movement showcasing the subject", resolution: "1080p", aspectRatio: "16:9", concurrency: 3, }); console.table(pipelineResults); ``` ## Type Definitions ### VideoGenerationInput Extended input type for video generation requests: ```typescript // Part of GenerateOptions input - uses existing multimodal types type VideoGenerationInput = { text: string; // Prompt describing desired video motion/style images: Array; // Input image (required) }; ``` ### VideoOutputOptions Options for video output configuration: ```typescript type VideoOutputOptions = { /** Output resolution - "720p" (1280x720) or "1080p" (1920x1080) */ resolution?: "720p" | "1080p"; /** Video duration in seconds (4, 6, or 8 seconds supported) */ length?: 4 | 6 | 8; /** Aspect ratio - "9:16" for portrait or "16:9" for landscape */ aspectRatio?: "9:16" | "16:9"; /** Enable audio generation (default: true) */ audio?: boolean; }; ``` ### VideoGenerationResult Result type for generated video: ```typescript type VideoGenerationResult = { /** Raw video data as Buffer */ data: Buffer; /** Video media type */ mediaType: "video/mp4" | "video/webm"; /** Video metadata */ metadata?: { /** Original filename if applicable */ filename?: string; /** Video duration in seconds */ duration?: number; /** Video dimensions */ dimensions?: { width: number; height: number; }; /** Frame rate in fps */ frameRate?: number; /** Video codec used */ codec?: string; /** Model used for generation */ model?: string; /** Provider used for generation */ provider?: string; /** Aspect ratio of the video */ aspectRatio?: string; /** Whether audio was enabled during generation */ audioEnabled?: boolean; /** Processing time in milliseconds */ processingTime?: number; }; }; ``` ### Extended GenerateResult The `generate()` function returns an extended result when video mode is enabled: ```typescript type GenerateResult = { content: string; // Text content (prompt echoed back) provider?: string; model?: string; usage?: TokenUsage; responseTime?: number; // Video-specific field (present when output.mode === "video") video?: VideoGenerationResult; // Other optional fields toolsUsed?: string[]; analytics?: AnalyticsData; evaluation?: EvaluationData; }; ``` ## Configuration & Best Practices ### Configuration Options | Option | Type | Default | Required | Description | | -------------------------- | ------------------- | ---------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `input.images[0]` | `Buffer \| string` | - | Yes | Image buffer, file path, or URL | | `input.text` | `string` | - | Yes | Text description of desired video | | `output.video.provider` | `VideoProviderName` | `"vertex"` | No | Video handler: `vertex` (default), `kling`, `runway`, `replicate`. See [Routing Across Providers](#routing-across-providers). | | `output.video.model` | `string` | provider-default | No | Model version / checkpoint id (e.g. `veo-3.1-generate-001`, `meta/wan-2-2/i2v`) | | `output.mode` | `string` | `"text"` | Yes | Must be `"video"` for video output | | `output.video.resolution` | `string` | `"720p"` | No | Output resolution (`720p` or `1080p`) | | `output.video.length` | `number` | `6` | No | Duration in seconds — **provider-dependent**: `vertex` accepts 4/6/8, `kling` and `runway` accept 5/10, `replicate` is model-specific. See [Routing Across Providers](#routing-across-providers) for per-provider details. | | `output.video.aspectRatio` | `string` | `"16:9"` | No | Aspect ratio (`9:16` or `16:9`) | | `output.video.audio` | `boolean` | `true` | No | Enable audio generation | ### Video Quality Settings ```typescript // High quality for professional content const professional = await neurolink.generate({ input: { text: "Cinematic product showcase with dramatic lighting", images: [await readFile("./product.jpg")], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "1080p", length: 8, aspectRatio: "16:9", audio: true, }, }, }); // Optimized for social media const social = await neurolink.generate({ input: { text: "Quick product reveal", images: [await readFile("./input.jpg")], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "720p", length: 4, aspectRatio: "9:16", audio: true, }, }, }); ``` ### Best Practices #### 1. Prompt Engineering ```typescript // ❌ Vague and unclear const vaguePrompt = "Make a video of this product"; // ✅ Specific and actionable const specificPrompt = "Smooth 360-degree rotation of the product with soft studio lighting, camera slowly zooms out"; // ✅ Include camera direction const cameraDirectionPrompt = "Camera slowly pans from left to right, revealing product details with cinematic depth of field"; // ✅ Describe motion and atmosphere const atmospherePrompt = "Dynamic product showcase with subtle particle effects, ambient lighting transitions from warm to cool"; ``` **Prompt Template Examples:** | Use Case | Template | | ---------------- | ---------------------------------------------------------------------------------- | | Product Rotation | `"Elegant 360-degree rotation of [product] with [lighting style] lighting"` | | Hero Shot | `"Cinematic zoom from [distance] to [detail] with [motion style] camera movement"` | | Lifestyle | `"Natural scene with [subject] in [environment], subtle ambient movement"` | | Social Media | `"Quick dynamic reveal of [product] with energetic transitions"` | #### 2. Image Preparation ```typescript // Image requirements const imageRequirements = { minResolution: "720p", // 1280x720 minimum recommendedResolution: "1080p", // 1920x1080 for best results formats: ["JPEG", "PNG", "WebP"], maxSize: "10MB", aspectRatio: "Match desired video output", }; // Preprocessing recommendations async function prepareImage(inputPath: string, outputRatio: "9:16" | "16:9") { const targetWidth = outputRatio === "16:9" ? 1920 : 1080; const targetHeight = outputRatio === "16:9" ? 1080 : 1920; return sharp(inputPath) .resize(targetWidth, targetHeight, { fit: "cover", position: "center", }) .jpeg({ quality: 90 }) .toBuffer(); } ``` #### 3. Performance Optimization ```typescript // Parallel processing with rate limiting const limit = pLimit(3); // Max 3 concurrent requests (within provider limits) const images = ["img1.jpg", "img2.jpg", "img3.jpg", "img4.jpg", "img5.jpg"]; const videos = await Promise.all( images.map((img) => limit(async () => { const result = await neurolink.generate({ input: { text: "Product showcase", images: [await readFile(img)], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "720p", length: 8 } }, }); return result.video; }), ), ); ``` #### 4. Quality vs. Cost Tradeoffs | Setting | Quality | Cost | Use Case | | --------- | ------- | ------- | ------------------------ | | 720p, 4s | Good | Low | Quick previews, drafts | | 720p, 8s | Good | Medium | Social media content | | 1080p, 6s | High | High | Marketing materials | | 1080p, 8s | Highest | Highest | Professional productions | ## Error Handling & Validation ### Validation Rules | Parameter | Validation | Error Type | Example Message | | -------------------------- | ------------------------------- | -------------- | -------------------------------------------------- | | `input.images[0]` | Must be valid image file/buffer | NeuroLinkError | `Invalid image format. Supported: JPEG, PNG, WebP` | | `input.images[0]` | Max 10MB | NeuroLinkError | `Image size exceeds 10MB limit` | | `input.text` | 1-500 characters | NeuroLinkError | `Prompt must be between 1 and 500 characters` | | `output.video.resolution` | `720p` or `1080p` | NeuroLinkError | `Invalid resolution. Use '720p' or '1080p'` | | `output.video.length` | 4, 6, or 8 | NeuroLinkError | `Invalid length. Use 4, 6, or 8 seconds` | | `output.video.aspectRatio` | `9:16` or `16:9` | NeuroLinkError | `Invalid aspect ratio. Use '9:16' or '16:9'` | ### Error Types NeuroLink uses a unified error handling system with error categories: ```typescript // Error categories (from ErrorCategory enum) type ErrorCategory = | "validation" | "timeout" | "network" | "resource" | "permission" | "configuration" | "execution" | "system"; // Video-specific error codes (standard single-clip generation) const VIDEO_ERROR_CODES = { GENERATION_FAILED: "VIDEO_GENERATION_FAILED", PROVIDER_NOT_CONFIGURED: "VIDEO_PROVIDER_NOT_CONFIGURED", POLL_TIMEOUT: "VIDEO_POLL_TIMEOUT", INVALID_INPUT: "VIDEO_INVALID_INPUT", // Director Mode adds additional codes (DIRECTOR_CLIP_FAILED, etc.) // See Video Director Mode docs for the full list }; ``` > **Note:** Video errors are thrown as `VideoError` (extends `NeuroLinkError`) with the codes above. Director Mode introduces additional error codes — see [Video Director Mode – Error Types](./video-director-mode#error-types) for the complete list. ### Error Handling Example ```typescript try { const result = await neurolink.generate({ input: { text: prompt, images: [imageBuffer], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "720p" } }, }); } catch (error) { if (error instanceof NeuroLinkError) { console.error(`Error [${error.code}]:`, error.message); console.error("Category:", error.category); console.error("Severity:", error.severity); console.error("Retriable:", error.retriable); // Handle specific error categories switch (error.category) { case "validation": console.error("Validation issues:"); // - Unsupported image format (use JPEG, PNG, or WebP) // - Image too large (max 10MB) // - Invalid prompt length (1-500 characters) // - Invalid resolution, length, or aspect ratio break; case "timeout": console.error("Request timed out - retry with backoff"); break; case "configuration": case "permission": console.error( "Config/auth failed - check GOOGLE_APPLICATION_CREDENTIALS", ); break; case "network": console.error("Network error - retry with backoff"); break; case "execution": console.error("Execution error - check status and quotas"); // Detect rate limiting via error code if (error.code.includes("RATE_LIMIT")) { console.error("Rate limited - implement exponential backoff"); } break; } } } ``` ## Token & Cost Information ### Pricing Structure | Resolution | Duration | Estimated Cost | Notes | | ---------- | --------- | -------------- | -------------------- | | 720p | 4 seconds | ~$1.60 | Best for previews | | 720p | 8 seconds | ~$3.20 | Standard quality | | 1080p | 4 seconds | ~$2.00 | High quality short | | 1080p | 8 seconds | ~$4.00 | Professional quality | > **Note:** Pricing is approximate and subject to change (as of October 2025). Check Google Cloud pricing for current rates. ### Storage Costs | Resolution | Duration | Approx. File Size | | ---------- | --------- | ----------------- | | 720p | 4 seconds | ~1-2 MB | | 720p | 8 seconds | ~2-4 MB | | 1080p | 4 seconds | ~2-3 MB | | 1080p | 8 seconds | ~4-6 MB | ## Working with Video Results ```typescript const neurolink = new NeuroLink(); // Generate video const result = await neurolink.generate({ input: { text: "Product showcase video", images: [await readFile("./product.jpg")], }, provider: "vertex", model: "veo-3.1", output: { mode: "video" }, }); // Check for video result if (result.video) { // Save to file await writeFile("output.mp4", result.video.data); // Access metadata console.log({ duration: result.video.metadata?.duration, resolution: result.video.metadata?.dimensions, model: result.video.metadata?.model, size: result.video.data.length, }); } ``` ## Troubleshooting | Symptom | Cause | Solution | | ------------------------- | --------------------------------- | -------------------------------------------------------- | | Authentication error | Invalid or missing credentials | Verify `GOOGLE_APPLICATION_CREDENTIALS` is set correctly | | Authorization error | Service account lacks permissions | Add `aiplatform.user` role to service account | | Validation error (format) | Unsupported image type | Convert image to JPEG, PNG, or WebP | | Validation error (size) | Image exceeds 10MB limit | Compress or resize image before upload | | Rate limit error | Too many requests | Implement exponential backoff | | Network timeout | Processing took too long | Try lower resolution or shorter duration | | Provider quota exceeded | Monthly quota reached | Request quota increase or wait for reset | | Connection error | Network issues | Check network connectivity; retry with backoff | | Video quality is poor | Low resolution input image | Use minimum 720p source images | | Audio not matching video | Complex scene | Simplify prompt; focus on visual elements | | Unexpected aspect ratio | Input image ratio mismatch | Preprocess image to match target aspect ratio | ### Debug Mode ```typescript // Enable verbose logging for debugging const neurolink = new NeuroLink({ debug: true, logLevel: "verbose", }); // Or via environment variable // export NEUROLINK_DEBUG=true ``` ## Limitations ### Current Limitations | Limitation | Description | Workaround | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | | Max duration | Provider-specific: Vertex 4/6/8 s, Runway 5/10 s, Kling 5/10 s, Replicate per-model. | Chain multiple clips via [Video Director Mode](./video-director-mode) (Vertex) | | Audio input | No custom audio supported on any provider | Audio is auto-generated (Vertex Veo) or absent (Kling / Runway / Replicate) | | Text-only prompts | All four providers require an image (and Kling needs a public URL — see [Routing Across Providers](#routing-across-providers)) | Generate an image first, then pass it as `input.images[0]` | | Director Mode | Currently Vertex-only | Generate per-segment clips with non-Vertex providers and stitch externally | | Concurrent requests | Provider-specific (Vertex: 5/project; Replicate: 6/min on free tier) | Implement request queuing | ## Testing ### Unit Test Examples ```typescript describe("Video Generation", () => { it("should generate video with valid inputs", async () => { const neurolink = new NeuroLink(); const imageBuffer = Buffer.from("fake-image-data"); const result = await neurolink.generate({ input: { text: "Test video generation", images: [imageBuffer], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "720p", length: 8 } }, }); expect(result.video).toBeDefined(); expect(result.video?.data).toBeInstanceOf(Buffer); expect(result.video?.metadata?.duration).toBe(8); }); it("should throw error for invalid image format", async () => { const neurolink = new NeuroLink(); await expect( neurolink.generate({ input: { text: "Test", images: ["invalid-file.txt"], }, provider: "vertex", model: "veo-3.1", output: { mode: "video" }, }), ).rejects.toThrow(); // Should throw ValidationError }); it("should respect resolution settings", async () => { const neurolink = new NeuroLink(); const imageBuffer = Buffer.from("fake-image-data"); const result = await neurolink.generate({ input: { text: "Test", images: [imageBuffer], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "1080p" } }, }); expect(result.video?.metadata?.dimensions?.width).toBe(1920); expect(result.video?.metadata?.dimensions?.height).toBe(1080); }); }); ``` ### Mock Strategy for CI/CD ```typescript // Mock the NeuroLink class to return video generation results vi.mock("@juspay/neurolink", () => ({ NeuroLink: vi.fn().mockImplementation(() => ({ generate: vi.fn().mockResolvedValue({ content: "", provider: "vertex", model: "veo-3.1", video: { data: Buffer.from("mock-video-data"), mediaType: "video/mp4", metadata: { duration: 8, dimensions: { width: 1920, height: 1080 }, model: "veo-3.1", }, }, }), })), })); ``` ### Integration Test Pattern ```typescript describe("Video Generation Integration", () => { it("should complete full generation workflow", async () => { // Skip in CI without credentials if (!process.env.GOOGLE_APPLICATION_CREDENTIALS) { console.log("Skipping: No Google credentials"); return; } const neurolink = new NeuroLink(); const imageBuffer = await readFile("./test-fixtures/sample-image.jpg"); const result = await neurolink.generate({ input: { text: "Smooth camera pan for product showcase", images: [imageBuffer], }, provider: "vertex", model: "veo-3.1", output: { mode: "video", video: { resolution: "720p", length: 4 }, }, }); expect(result.video).toBeDefined(); expect(result.video?.data).toBeInstanceOf(Buffer); expect(result.video?.data.length).toBeGreaterThan(0); expect(result.video?.metadata?.duration).toBe(4); }, 180000); // 3 minute timeout for video generation }); ``` ## Related Features - [Video Director Mode](./video-director-mode) – Multi-segment video generation with AI transitions - [Multimodal Chat](/docs/features/multimodal-chat) – Overview of multimodal capabilities and image support - [PDF Support](/docs/features/pdf-support) – Document processing for visual analysis - [CSV Support](/docs/features/csv-support) – Data file processing ## Implementation Files The video generation feature is implemented across these files: | File | Purpose | | ---------------------------------------------- | ----------------------------------------------------------------------------- | | `src/lib/types/multimodal.ts` | Core types: `VideoOutputOptions`, `VideoGenerationResult` | | `src/lib/types/generateTypes.ts` | Extended `GenerateOptions` with video output mode | | `src/lib/adapters/video/vertexVideoHandler.ts` | Vertex AI Veo 3.1 video generation handler, `VideoError`, `VIDEO_ERROR_CODES` | | `src/lib/adapters/video/ffmpegAdapter.ts` | Shared FFmpeg adapter (binary resolution, temp files, buffer validation) | | `src/lib/adapters/video/frameExtractor.ts` | Frame extraction from MP4 buffers (used by Director Mode) | | `src/lib/adapters/video/videoMerger.ts` | MP4 concatenation via FFmpeg concat demuxer (used by Director Mode) | | `src/lib/adapters/video/directorPipeline.ts` | Director Mode pipeline orchestrator (multi-segment generation) | | `src/lib/core/baseProvider.ts` | Video generation routing in `generate()` method | | `src/lib/neurolink.ts` | Main SDK interface with video result handling | | `src/lib/utils/parameterValidation.ts` | Input validation: `validateVideoGenerationInput()`, `validateImageForVideo()` | | `src/lib/utils/errorHandling.ts` | Error factory methods for video generation errors | ### Key Functions - **`generateVideoWithVertex()`** - Main video generation function in `vertexVideoHandler.ts` - **`generateTransitionWithVertex()`** - Transition generation with first-and-last-frame API (Director Mode) - **`validateVideoGenerationInput()`** - Comprehensive input validation in `parameterValidation.ts` - **`validateImageForVideo()`** - Image format and size validation in `parameterValidation.ts` - **`handleVideoGeneration()`** - Private method in `BaseProvider` that orchestrates the video generation flow - **`executeDirectorPipeline()`** - Director Mode orchestrator (parallel clips, transitions, merge) **Next:** [Multimodal Chat Guide](/docs/features/multimodal-chat) | [Video Director Mode](./video-director-mode) --- ## Real-Time Voice Agent - Streaming Voice Loop Design # Real-Time Voice Agent - Streaming Voice Loop Design **Automatic low-latency voice conversations with STT, LLM, TTS, and barge-in support** ## Problem Statement & Solution ### The Challenge Real-time voice assistants are harder than ordinary request/response chat because they must coordinate: - continuous microphone audio input - speech detection - real-time transcription - streaming LLM generation - streaming TTS playback - interruption while the assistant is still speaking Without careful coordination, common failures appear quickly: - user speech gets cut off too early - assistant speech is echoed back into the mic - interruptions trigger too often or too late - TTS providers fail under token-by-token flooding - local MCP/tool initialization adds large latency spikes ### Our Solution NeuroLink exposes a dedicated `voice-server` mode that runs a full browser-to-server voice loop: 1. Browser captures microphone audio 2. Cobra detects speaking/silence boundaries 3. Soniox performs streaming STT 4. NeuroLink streams the LLM response 5. Cartesia converts the response into streaming PCM audio 6. Browser plays audio immediately and supports mid-response interruption ### Key Benefits - **Low-latency speech loop** for natural conversations - **Automatic barge-in** while assistant audio is playing - **Buffered TTS chunking** to avoid provider overload on long replies - **Warmup path** to reduce first-turn cold start cost - **Environment-driven configuration** for Cartesia endpoint/version overrides - **Voice-mode tool isolation** by disabling MCP tools during real-time turns --- ## Architecture Overview ### System Flow Diagram ```text ┌─────────────────────────────────────────────────────────────┐ │ Browser │ │ • Captures 16kHz PCM mic audio │ │ • Sends audio over WebSocket │ │ • Plays assistant PCM audio │ └────────────────────────┬────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Voice WebSocket Handler │ │ • Maintains per-session state │ │ • Routes audio frames to VAD + STT │ │ • Sends assistant audio back to browser │ └────────────────────────┬────────────────────────────────────┘ │ ┌─────────────┼─────────────┐ ▼ ▼ ▼ Cobra VAD Soniox STT TurnManager • speech start • partials • IDLE • speech stop • finals • USER_SPEAKING • PROCESSING • ASSISTANT_SPEAKING └─────────────┬─────────────┘ ▼ ┌─────────────────────────────────────────────────────────────┐ │ NeuroLink LLM Streaming │ │ • Default: Azure gpt-4o-automatic (configurable via env) │ │ • tools disabled for lower latency │ │ • short spoken response style │ └────────────────────────┬────────────────────────────────────┘ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Cartesia TTS │ │ • transcript chunks in │ │ • PCM S16LE 24kHz out │ └────────────────────────┬────────────────────────────────────┘ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Browser Playback │ │ • buffered playback │ │ • sends playback_done when queue drains │ └─────────────────────────────────────────────────────────────┘ ``` --- ## Core Components ### 1. Voice Activity Detection **Provider:** Picovoice Cobra Purpose: - identify when the user starts speaking - identify when the user stops speaking - move session state between `IDLE`, `USER_SPEAKING`, and `PROCESSING` Implementation details: - 512-sample frames - threshold-based speech probability - explicit start and stop hysteresis using consecutive frames ### 2. Streaming Speech-to-Text **Provider:** Soniox Purpose: - transcribe incoming speech continuously - use non-final tokens for reliable barge-in detection - use final tokens plus `` to trigger LLM processing ### 3. Turn State Management **Component:** `TurnManager` State machine: ```text IDLE -> USER_SPEAKING -> PROCESSING -> ASSISTANT_SPEAKING ``` Purpose: - prevent overlapping turns - distinguish user speech from assistant playback state - ensure barge-in only fires when the assistant is actually speaking ### 4. Streaming TTS Adapter **Provider:** Cartesia Purpose: - accept streaming transcript chunks - return PCM S16LE 24kHz audio for immediate playback Important implementation detail: - transcript is buffered into phrase/sentence chunks before being sent - this avoids sending one tiny WS message per token - reduces `Service unavailable` failures for long responses ### 5. Browser Client Files in `src/lib/server/voice/public`: - `src/lib/server/voice/public/index.html` - `src/lib/server/voice/public/app.js` - `src/lib/server/voice/public/pcm-worklet.js` - `src/lib/server/voice/public/styles.css` Responsibilities: - microphone capture - audio frame encoding and streaming - assistant playback queueing - playback completion signaling - simple voice UI state updates --- ## Runtime Flow ### Normal Turn 1. Browser sends microphone PCM frames to server 2. Cobra detects speech start and publishes `vad_start` 3. Soniox streams transcription in parallel 4. On final transcript + ``, server calls NeuroLink streaming 5. LLM response is buffered into TTS-friendly chunks 6. Cartesia returns audio chunks 7. Browser plays audio immediately 8. Browser sends `playback_done` after the queue drains 9. Session returns to `IDLE` ### Barge-In Flow 1. Assistant is already speaking 2. Soniox emits new non-final user speech tokens 3. Server verifies current state is `ASSISTANT_SPEAKING` 4. Server interrupts active TTS 5. Browser receives `{ type: "interrupt" }` 6. Current turn is canceled and user takes over ### Warmup Flow On server startup: 1. NeuroLink performs a tiny LLM stream request using the configured voice provider 2. Cartesia WebSocket connection is opened and closed once 3. Subsequent first-user-turn latency is reduced --- ## CLI Integration ### Command ```bash neurolink voice-server --port 3000 ``` ### Implementation Entry Point - `src/cli/commands/voiceServer.ts` ### What the command does - starts an Express server - serves the browser UI - exposes a `/health` endpoint - attaches a WebSocket voice session handler - performs LLM + TTS warmup in the background --- ## Source Layout ### CLI - `src/cli/commands/voiceServer.ts` ### Voice Server Module ```text src/lib/server/voice/ ├── voiceServerApp.ts ├── voiceWebSocketHandler.ts ├── frameBus.ts ├── turnManager.ts ├── types.ts └── public/ ├── index.html ├── app.js ├── pcm-worklet.js └── styles.css ``` ### TTS Adapter - `src/lib/adapters/tts/cartesiaHandler.ts` --- ## Configuration ### Required Environment Variables ```env # Cartesia CARTESIA_API_KEY= # Soniox SONIOX_API_KEY= # Picovoice Cobra PICOVOICE_ACCESS_KEY= # Azure OpenAI (for LLM — default provider) AZURE_OPENAI_API_KEY= AZURE_OPENAI_ENDPOINT= ``` ### Optional Voice LLM Overrides ```env # Override the LLM provider/model used for voice turns (defaults: azure / gpt-4o-automatic) VOICE_LLM_PROVIDER=azure VOICE_LLM_MODEL=gpt-4o-automatic ``` ### Optional Cartesia Overrides ```env CARTESIA_WS_BASE_URL=wss://api.cartesia.ai/tts/websocket CARTESIA_API_VERSION=2025-04-16 ``` ### Optional Soniox Overrides ```env SONIOX_WS_URL=wss://stt-rt.soniox.com/transcribe-websocket ``` These exist because the endpoint base URL is usually shared, but API key and version may vary by environment or future provider rollout. --- ## Operational Behavior ### Tuned Constants | Constant | Value | Purpose | | -------------------------------- | ------------: | ------------------------------------- | | `VOICE_THRESHOLD` | `0.7` | Cobra speech probability cutoff | | `VOICE_FRAMES_TO_START` | `5` (~160ms) | Filter short noise bursts | | `SILENCE_FRAMES_TO_STOP` | `30` (~960ms) | Avoid cutting natural pauses | | Pre-lock before assistant speech | `1000ms` | Protect initial TTS connection window | | Lock refresh on first audio | `+400ms` | Cover browser AEC lock-on window | ### Why MCP Tools Are Disabled Voice mode sets: ```ts process.env.NEUROLINK_DISABLE_MCP_TOOLS = "true"; ``` Reason: - tool/MCP initialization adds several seconds of latency - real-time voice turns need predictable low overhead - voice mode is optimized for direct conversation, not tool orchestration ### Why TTS Buffering Matters Sending every token directly to Cartesia can overload the provider on long responses. Current strategy: - accumulate text in a local buffer - flush at sentence/phrase boundaries or after a minimum chunk length - keep speech natural while reducing provider stress --- ## Error Handling & Troubleshooting ### Common Runtime Failure Modes #### 1. Invalid MCP HTTP Auth Symptom: ```text Authorization header is badly formatted ``` Impact: - degraded latency - failed or partial turns - noisy logs during voice testing Fix: 1. correct the local token/env value, or 2. disable that MCP server locally while testing voice mode Important: - this is a **local environment issue** - do not commit personal `.mcp-config.json` changes unless they are intended for everyone #### 2. Cartesia Temporary Unavailability Symptom: ```text Service unavailable: TTS generation services are temporarily unavailable ``` Impact: - no assistant audio for that turn - turn resets so the user can retry Mitigation already implemented: - mid-stream TTS errors abort the turn cleanly - failed turns are not committed to conversation history - long-response flooding was reduced via chunked TTS buffering #### 3. Missing Environment Variables Examples: - `CARTESIA_API_KEY is not set in environment` - `PICOVOICE_ACCESS_KEY is not set in environment` Fix: - populate values from `.env.example` ### Health Check ```text GET http://localhost:3000/health ``` Returns: ```json { "status": "ok" } ``` --- ## Performance Characteristics ### Expected Latency | Condition | STT -> First Audio | | --------------- | -----------------: | | Warm turn | ~700–1400ms | | Cold first turn | ~7000ms | ### Why cold start is slower - initial LLM provider request setup (Azure by default) - initial Cartesia TLS/WebSocket setup - one-time runtime warmup overhead Warmup in `src/lib/server/voice/voiceServerApp.ts` helps reduce this for the first real user turn. --- ## Extensibility Roadmap Possible next steps: 1. **Provider abstraction for STT/TTS** - support alternative STT providers - support alternative TTS providers 2. **Richer browser client** - waveform UI - transcripts in real time - reconnect UX 3. **Session persistence** - resumable voice sessions - persisted conversation history 4. **Voice personalization** - user-selectable voices - language presets - speaking style controls 5. **Operational hardening** - retries/backoff for TTS transport - structured metrics for per-turn latency - better provider fallback strategies --- ## Workflow Engine Guide # Workflow Engine Guide > **Since**: v9.20.0 | **Status**: Stable (Testing Phase) | **Availability**: SDK + CLI > > **Provider Defaults:** When `--provider` (CLI) or `provider` (SDK) is not specified, NeuroLink defaults to **Vertex AI** with **gemini-2.5-flash**. Set the `NEUROLINK_PROVIDER` or `AI_PROVIDER` environment variable to change the default provider. ## Overview The NeuroLink Workflow Engine enables multi-model orchestration patterns where multiple AI models collaborate to produce higher-quality outputs. Instead of relying on a single model, the engine: - **Executes multiple models** in parallel or sequential layers - **Evaluates responses** using independent judge models that score on a 0-100 scale - **Selects the best response** based on judge scores, or synthesizes an improved response from all outputs - **Provides detailed metrics** including per-model response times, token usage, confidence, and consensus levels The engine ships with 9 pre-built workflows and supports fully custom configurations. **Current Phase:** Testing and Evaluation. Workflows return the best original response alongside evaluation scores for AB testing. Response conditioning (post-processing) is available but optional. ## Quick Start ### Using a Pre-built Workflow (SDK) ```typescript const neurolink = new NeuroLink(); // Use a pre-built workflow by ID // The `consensus-3` workflow is one of 9 pre-built workflows included with // NeuroLink — no registration required. const result = await neurolink.generate({ input: { text: "Explain the CAP theorem in distributed systems" }, workflow: "consensus-3", }); console.log(result.content); // Best response selected by the judge console.log(result.workflow?.judgeScores); // Scores for each model console.log(result.workflow?.selectedModel); // Which model won console.log(result.workflow?.metrics); // Timing breakdown ``` ### Using a Pre-built Workflow (CLI) ```bash # Execute a workflow neurolink workflow execute consensus-3 "Explain the CAP theorem" # List all available workflows neurolink workflow list # Inspect a workflow's configuration neurolink workflow info consensus-3 ``` ## Pre-built Workflows NeuroLink ships with 9 pre-built workflows covering common orchestration patterns. | Workflow ID | Type | Models | Judges | Use Case | Avg Cost | Avg Latency | | --------------------- | ---------- | ------ | ------ | -------------------------------------------- | -------- | ----------- | | `consensus-3` | `ensemble` | 3 | 1 | Balanced quality across providers | ~$0.02 | ~2s | | `consensus-3-fast` | `ensemble` | 3 | 1 | Fast consensus for simple queries | ~$0.01 | ~1.5s | | `balanced-adaptive` | `adaptive` | 4 | 1 | Balanced speed/quality/cost tradeoff | ~$0.04 | ~2.5s | | `quality-max` | `adaptive` | 5 | 1 | Maximum quality with 3-tier escalation | ~$0.08 | ~4.5s | | `speed-first` | `adaptive` | 3 | 1 | Speed-optimized with quality fallback | ~$0.01 | ~1.5s | | `aggressive-fallback` | `chain` | 3 | 1 | Fast first, then parallel premium fallback | ~$0.03 | ~2.5s | | `fast-fallback` | `chain` | 3 | 1 | Sequential fast-to-premium fallback | ~$0.01 | ~2s | | `multi-judge-3` | `ensemble` | 3 | 2 | Balanced multi-judge evaluation | ~$0.04 | ~3.5s | | `multi-judge-5` | `ensemble` | 5 | 3 | Critical decisions requiring high confidence | ~$0.10 | ~5s | ### Workflow Details **`consensus-3`** runs GPT-4o, Claude 3.5 Sonnet, and Gemini 2.0 Flash in parallel. GPT-4o acts as judge, scoring on accuracy, clarity, and completeness. **`consensus-3-fast`** uses cheaper models (GPT-4o-mini, Claude 3 Haiku, Gemini 2.0 Flash) with GPT-4o-mini as judge. Same consensus pattern at lower cost. **`balanced-adaptive`** uses a 2-tier approach: first runs GPT-4o-mini and Gemini Flash in parallel (standard tier), then escalates to GPT-4o and Claude 3.5 Sonnet (premium tier). **`quality-max`** runs a 3-tier pipeline: validation tier (2 fast models) -> premium tier (GPT-4o + Claude 3.5 Sonnet) -> expert tier (Claude 3.5 Sonnet with specialized prompt). All responses are judged for maximum quality. **`speed-first`** tries GPT-4o-mini first (5s timeout), falls back to Gemini 2.0 Flash, then GPT-4o. Optimized for latency-sensitive applications. **`aggressive-fallback`** tries GPT-4o-mini first; if it fails, runs both GPT-4o and Claude 3.5 Sonnet in parallel for guaranteed quality. **`fast-fallback`** is a 3-tier sequential chain: GPT-4o-mini -> Gemini 2.0 Flash -> GPT-4o. Each tier only executes if the previous one fails. **`multi-judge-3`** runs 3 models and uses 2 independent judges (GPT-4o and Claude 3.5 Sonnet) with averaged scores. **`multi-judge-5`** runs 5 models across OpenAI, Anthropic, and Google, with 3 independent judges each evaluating different criteria (accuracy, reasoning, completeness). Scores are averaged and consensus level is reported. ## Workflow Types ### Ensemble (`type: "ensemble"`) All models execute in parallel. A judge (or multiple judges) evaluates every response and selects the best one. ``` User Prompt │ ├──▶ Model A ──▶ Response A ─┐ ├──▶ Model B ──▶ Response B ──┼──▶ Judge ──▶ Best Response └──▶ Model C ──▶ Response C ─┘ ``` Best for: General-purpose quality improvement, cross-validation, critical decisions. ### Chain (`type: "chain"`) Model groups execute sequentially. Each group is a "tier" that runs only if previous tiers failed or the workflow configuration requires it. Uses `modelGroups` for layer-based execution. ``` User Prompt │ ▼ Fast Tier (GPT-4o-mini) │ ├── Success? ──▶ Judge ──▶ Best Response │ ▼ (on failure) Mid Tier (Gemini Flash) │ ├── Success? ──▶ Judge ──▶ Best Response │ ▼ (on failure) Premium Tier (GPT-4o) │ └──▶ Judge ──▶ Best Response ``` Best for: Cost optimization with quality guarantee, variable-complexity queries. ### Adaptive (`type: "adaptive"`) Similar to chain but designed for quality escalation. All tiers execute and their responses are collected, then the judge selects the best from all tiers. ``` User Prompt │ ▼ Standard Tier (parallel: GPT-4o-mini + Gemini Flash) │ ▼ Premium Tier (parallel: GPT-4o + Claude 3.5 Sonnet) │ ▼ All Responses ──▶ Judge ──▶ Best Response ``` Best for: Quality-critical tasks, complex analysis, production applications. ### Custom (`type: "custom"`) Define your own execution pattern using any combination of flat models, model groups, single or multiple judges, and conditioning. ## SDK Usage ### Using Pre-built Workflows by ID Pass the `workflow` option to `generate()` with a pre-built workflow ID. The workflow must first be registered in the workflow registry. ```typescript NeuroLink, registerWorkflow, CONSENSUS_3_WORKFLOW, } from "@juspay/neurolink"; // Register the workflow (typically done at app startup) registerWorkflow(CONSENSUS_3_WORKFLOW); const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "What are the tradeoffs of microservices vs monoliths?" }, workflow: "consensus-3", }); // The result includes standard fields plus workflow data console.log(result.content); // Best response console.log(result.provider); // Provider of the selected response console.log(result.model); // Model of the selected response console.log(result.responseTime); // Total workflow time // Workflow-specific data console.log(result.workflow?.originalResponse); // Unmodified best response console.log(result.workflow?.processedResponse); // After any conditioning console.log(result.workflow?.ensembleResponses); // All model responses console.log(result.workflow?.judgeScores); // Judge evaluation console.log(result.workflow?.selectedModel); // "openai-gpt-4o" console.log(result.workflow?.metrics); // Timing breakdown ``` ### Using Inline Workflow Configuration Pass `workflowConfig` directly for full control without pre-registration. ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Design a caching strategy for a high-traffic API" }, workflowConfig: { id: "my-custom-workflow", name: "Custom 2-Model Ensemble", type: "ensemble", models: [ { provider: "openai", model: "gpt-4o", temperature: 0.7, }, { provider: "anthropic", model: "claude-3-5-sonnet-20241022", temperature: 0.7, }, ], judge: { provider: "openai", model: "gpt-4o", criteria: ["technical_accuracy", "completeness", "clarity"], outputFormat: "detailed", includeReasoning: true, temperature: 0.1, scoreScale: { min: 0, max: 100 }, }, execution: { parallelism: 2, timeout: 30000, modelTimeout: 25000, minResponses: 1, }, }, }); ``` ### Using the Low-Level API For advanced use cases, call the workflow runner directly. ```typescript const result = await runWorkflow(CONSENSUS_3_WORKFLOW, { prompt: "Explain quantum entanglement", timeout: 30000, verbose: true, metadata: { userId: "user-123", requestId: "req-456" }, }); console.log("Best response:", result.content); console.log("Score:", result.score); // 0-100 console.log("Confidence:", result.confidence); // 0-1 console.log("Reasoning:", result.reasoning); console.log("Ensemble time:", result.ensembleTime, "ms"); console.log("Judge time:", result.judgeTime, "ms"); console.log("Total time:", result.totalTime, "ms"); ``` ### Progressive Streaming The workflow engine supports progressive streaming, yielding a preliminary response from the first model that completes, followed by the final judged response. ```typescript runWorkflowWithStreaming, CONSENSUS_3_WORKFLOW, } from "@juspay/neurolink"; for await (const chunk of runWorkflowWithStreaming(CONSENSUS_3_WORKFLOW, { prompt: "Explain quantum entanglement", streaming: true, })) { if (chunk.type === "preliminary") { console.log("Fast preliminary response:", chunk.content); } else { console.log("Final judged response:", chunk.content); console.log("Score:", chunk.partialResult?.score); } } ``` ### Workflow Registry Register, list, and manage workflows programmatically. ```typescript registerWorkflow, unregisterWorkflow, getWorkflow, listWorkflows, getRegistryStats, clearRegistry, CONSENSUS_3_WORKFLOW, MULTI_JUDGE_5_WORKFLOW, } from "@juspay/neurolink"; // Register workflows registerWorkflow(CONSENSUS_3_WORKFLOW); registerWorkflow(MULTI_JUDGE_5_WORKFLOW); // Register with options registerWorkflow(myCustomWorkflow, { validateBeforeRegister: true, // Validate config (default: true) allowOverwrite: false, // Overwrite existing (default: false) }); // List all registered workflows const workflows = listWorkflows(); const ensembleOnly = listWorkflows({ type: "ensemble" }); const taggedWorkflows = listWorkflows({ tags: ["high-confidence"] }); // Get a specific workflow const config = getWorkflow("consensus-3"); // Get registry statistics const stats = getRegistryStats(); console.log("Total workflows:", stats.totalWorkflows); console.log("By type:", stats.byType); console.log("Most used:", stats.mostUsed); // Unregister unregisterWorkflow("consensus-3"); // Clear all clearRegistry(); ``` ### Factory Functions for Custom Workflows Use the built-in factory functions to create variations of pre-built workflows. ```typescript createConsensus3WithPrompt, createAdaptiveWorkflow, createMultiJudgeWorkflow, } from "@juspay/neurolink"; // Consensus-3 with a custom system prompt const techWorkflow = createConsensus3WithPrompt( "You are a technical expert. Provide detailed, accurate responses with code examples.", ); // Adaptive workflow with strategy const speedWorkflow = createAdaptiveWorkflow(3, "speed"); // 3-tier, speed-optimized const qualityWorkflow = createAdaptiveWorkflow(3, "quality"); // 3-tier, quality-optimized const balancedWorkflow = createAdaptiveWorkflow(2, "balanced"); // 2-tier, balanced // Custom multi-judge workflow const customMultiJudge = createMultiJudgeWorkflow(5, 3); // 5 models, 3 judges const lightMultiJudge = createMultiJudgeWorkflow(3, 2); // 3 models, 2 judges ``` ## CLI Usage ### List Workflows ```bash neurolink workflow list ``` Output: ``` Available Workflows: consensus-3 Consensus-3 Ensemble 3-model parallel ensemble with judge-based selection Tags: ensemble, consensus, balanced, multi-provider consensus-3-fast Consensus-3 Fast 3-model fast ensemble (lower cost) Tags: ensemble, fast, low-cost, consensus fast-fallback Fast-Fallback Chain Sequential fallback: fast -> mid -> premium Tags: chain, fallback, cost-optimized, reliable ... Total: 9 workflows ``` ### Inspect a Workflow ```bash neurolink workflow info consensus-3 ``` Output: ``` Workflow: Consensus-3 Ensemble ID: consensus-3 Type: ensemble Version: 1.0.0 Description: 3-model parallel ensemble with judge-based selection Models: - GPT-4o (openai) - Claude 3.5 Sonnet (anthropic) - Gemini 2.0 Flash (google-ai-studio) Judge: gpt-4o (openai) Criteria: accuracy, clarity, completeness Execution: Timeout: 30000ms Parallelism: 3 Min Responses: 2 Tags: ensemble, consensus, balanced, multi-provider ``` ### Execute a Workflow ```bash # Basic execution neurolink workflow execute consensus-3 "Explain the CAP theorem" # With options neurolink workflow execute multi-judge-5 "Should we use Kubernetes?" \ --timeout 45000 \ --verbose # Override provider/model for all models in the workflow neurolink workflow execute consensus-3 "Explain REST vs GraphQL" \ --provider openai \ --model gpt-4o ``` ## Custom Workflow Configuration ### WorkflowConfig Reference ```typescript type WorkflowConfig = { // Required id: string; // Unique workflow identifier name: string; // Human-readable name type: WorkflowType; // "ensemble" | "chain" | "adaptive" | "custom" models: ModelConfig[]; // Flat model array (required, used if modelGroups absent) // Optional description?: string; version?: string; modelGroups?: ModelGroup[]; // Layer-based execution (overrides models) defaultSystemPrompt?: string; // Default system prompt for all models defaultJudgePrompt?: string; // Default evaluation prompt for judges judge?: JudgeConfig; // Single judge judges?: JudgeConfig[]; // Multiple judges (cannot use both judge and judges) conditioning?: ConditioningConfig; // Response post-processing execution?: ExecutionConfig; // Timeout, parallelism, cost controls tags?: string[]; metadata?: Record; createdAt?: string; updatedAt?: string; }; ``` ### ModelConfig ```typescript type ModelConfig = { provider: AIProviderName; // "openai", "anthropic", "google-ai-studio", etc. model: string; // Model identifier (e.g., "gpt-4o") weight?: number; // Weighted voting (0-1, default: 1.0) temperature?: number; // 0-2 (default: provider default) maxTokens?: number; // Max output tokens systemPrompt?: string; // Model-specific system prompt timeout?: number; // Per-model timeout in ms topP?: number; topK?: number; presencePenalty?: number; frequencyPenalty?: number; label?: string; // Human-readable label metadata?: Record; }; ``` ### ModelGroup (Layer-based Execution) ```typescript type ModelGroup = { id: string; // Group identifier name?: string; description?: string; models: ModelConfig[]; // Models in this group executionStrategy: "parallel" | "sequential"; // How models run within group continueOnFailure?: boolean; // Continue to next group if this fails (default: true) minSuccessful?: number; // Minimum successful models to proceed (default: 1) parallelism?: number; // Max parallel models in this group timeout?: number; // Group-level timeout (ms) metadata?: Record; }; ``` ### JudgeConfig ```typescript type JudgeConfig = { provider: AIProviderName; // Judge provider model: string; // Judge model criteria: string[]; // Evaluation criteria (e.g., ["accuracy", "clarity"]) outputFormat: "scores" | "ranking" | "best" | "detailed"; includeReasoning: boolean; // Always include explanation scoreScale: { min: 0; max: 100 }; // Fixed 0-100 scale temperature?: number; // Low recommended (e.g., 0.1) maxTokens?: number; // Max judge output tokens timeout?: number; // Judge timeout (ms) customPrompt?: string; // Custom evaluation prompt systemPrompt?: string; // System instructions for judge blindEvaluation?: boolean; // Hide provider names from judge synthesizeImprovedResponse?: boolean; // Judge synthesizes improved response label?: string; metadata?: Record; }; ``` ### ExecutionConfig ```typescript type ExecutionConfig = { timeout?: number; // Total workflow timeout (ms, default: 30000) modelTimeout?: number; // Per-model timeout (ms, default: 15000) judgeTimeout?: number; // Judge timeout (ms, default: 10000) retries?: number; // Max retries on failure (default: 1) retryDelay?: number; // Delay between retries (ms, default: 1000) parallelism?: number; // Max parallel models (default: 10) minResponses?: number; // Minimum required responses (default: 1) maxCost?: number; // Max cost per execution ($) costThreshold?: number; // Warn at cost threshold ($) enableMetrics?: boolean; // Enable metrics collection (default: true) enableTracing?: boolean; // Enable tracing (default: false) }; ``` ### Full Custom Example ```typescript const myWorkflow: WorkflowConfig = { id: "medical-review", name: "Medical Document Review", description: "Multi-model review with synthesis for medical accuracy", version: "1.0.0", type: "ensemble", models: [ { provider: "openai", model: "gpt-4o", label: "GPT-4o", temperature: 0.3, systemPrompt: "You are a medical expert. Provide accurate, evidence-based responses.", }, { provider: "anthropic", model: "claude-3-5-sonnet-20241022", label: "Claude 3.5 Sonnet", temperature: 0.3, systemPrompt: "You are a medical expert. Be thorough and cite relevant guidelines.", }, { provider: "google-ai-studio", model: "gemini-2.0-flash", label: "Gemini 2.0 Flash", temperature: 0.3, }, ], judge: { provider: "openai", model: "gpt-4o", criteria: [ "medical_accuracy", "evidence_quality", "completeness", "safety", ], outputFormat: "detailed", includeReasoning: true, blindEvaluation: true, // Hide model names from judge synthesizeImprovedResponse: true, // Judge creates improved response temperature: 0.1, scoreScale: { min: 0, max: 100 }, }, execution: { parallelism: 3, timeout: 45000, modelTimeout: 30000, minResponses: 2, costThreshold: 0.1, }, tags: ["medical", "high-accuracy", "synthesis"], }; // Register and use registerWorkflow(myWorkflow); const result = await runWorkflow(myWorkflow, { prompt: "What are the current guidelines for managing type 2 diabetes?", verbose: true, }); // When synthesizeImprovedResponse is enabled, result.content contains // the judge's synthesized response combining the best elements. console.log("Synthesized response:", result.content); console.log("Original best:", result.originalContent); console.log("Score:", result.score); ``` ### Layer-based Execution Example ```typescript const tieredWorkflow: WorkflowConfig = { id: "tiered-analysis", name: "Tiered Analysis Pipeline", type: "adaptive", // Placeholder (required by schema) models: [{ provider: "openai", model: "gpt-4o-mini" }], // Layer-based execution: groups run sequentially modelGroups: [ { id: "fast-tier", name: "Fast Assessment", models: [ { provider: "openai", model: "gpt-4o-mini", timeout: 8000 }, { provider: "google-ai-studio", model: "gemini-2.0-flash", timeout: 8000, }, ], executionStrategy: "parallel", continueOnFailure: true, minSuccessful: 1, parallelism: 2, }, { id: "deep-tier", name: "Deep Analysis", models: [ { provider: "openai", model: "gpt-4o", systemPrompt: "Provide deep, thorough analysis.", timeout: 20000, }, { provider: "anthropic", model: "claude-3-5-sonnet-20241022", systemPrompt: "Think carefully. Provide nuanced analysis.", timeout: 20000, }, ], executionStrategy: "parallel", continueOnFailure: false, minSuccessful: 1, parallelism: 2, }, ], judge: { provider: "openai", model: "gpt-4o", criteria: ["depth", "accuracy", "completeness"], outputFormat: "detailed", includeReasoning: true, temperature: 0.1, scoreScale: { min: 0, max: 100 }, }, execution: { timeout: 60000, minResponses: 2, }, }; ``` ## WorkflowResult The `WorkflowResult` returned by `runWorkflow()` contains the full execution data. | Field | Type | Description | | ------------------- | --------------------------- | ------------------------------------------------------ | | `content` | `string` | Final output (processed/synthesized if enabled) | | `originalContent` | `string` | Original unmodified best response | | `score` | `number` | Judge score for best response (0-100) | | `reasoning` | `string` | Judge's evaluation reasoning (max 200 chars) | | `ensembleResponses` | `EnsembleResponse[]` | All model responses with status and timing | | `judgeScores` | `JudgeScores` | Full judge evaluation data | | `selectedResponse` | `EnsembleResponse` | The response selected as best | | `confidence` | `number` | Judge confidence in the evaluation (0-1) | | `consensus` | `number` | Agreement level between judges (0-1, multi-judge only) | | `totalTime` | `number` | Total workflow execution time (ms) | | `ensembleTime` | `number` | Time spent executing models (ms) | | `judgeTime` | `number` | Time spent on judge evaluation (ms) | | `conditioningTime` | `number` | Time spent on response conditioning (ms) | | `workflow` | `string` | Workflow ID | | `workflowName` | `string` | Workflow name | | `usage` | `AggregatedUsage` | Token usage across all models | | `metadata` | `Record` | Pass-through metadata | | `timestamp` | `string` | ISO 8601 execution timestamp | When using `generate()` with a workflow, the result includes a `workflow` field on the `GenerateResult`: ```typescript result.workflow?.originalResponse; // Raw best response before processing result.workflow?.processedResponse; // After conditioning result.workflow?.ensembleResponses; // All model outputs result.workflow?.judgeScores?.scores; // { "response-0": 85, "response-1": 92 } result.workflow?.judgeScores?.reasoning; // Judge explanation result.workflow?.selectedModel; // "openai-gpt-4o" result.workflow?.metrics?.totalTime; // Total execution time result.workflow?.metrics?.ensembleTime; // Model execution time result.workflow?.metrics?.judgeTime; // Judge evaluation time result.workflow?.workflowId; // Workflow ID result.workflow?.workflowName; // Workflow name ``` ## Architecture The workflow engine follows a four-phase pipeline: ``` ┌──────────────────────────────────────────────────────────┐ │ Workflow Runner │ │ │ │ 1. ENSEMBLE EXECUTION │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ │ Model A │ │ Model B │ │ Model C │ (parallel) │ │ └────┬────┘ └────┬────┘ └────┬────┘ │ │ │ │ │ │ │ ▼ ▼ ▼ │ │ 2. JUDGE SCORING │ │ ┌──────────────────────────────────┐ │ │ │ Judge evaluates all responses │ │ │ │ Scores: 0-100 per response │ │ │ │ Ranking + reasoning │ │ │ └──────────────┬───────────────────┘ │ │ │ │ │ ▼ │ │ 3. RESPONSE SELECTION / SYNTHESIS │ │ Best response selected by score │ │ (or synthesized if judge synthesis enabled) │ │ │ │ │ ▼ │ │ 4. RESULT ASSEMBLY │ │ Metrics, usage, confidence, consensus │ └──────────────────────────────────────────────────────────┘ ``` **Key components:** | Component | File | Purpose | | ----------------------- | ---------------------------------------------- | --------------------------------------- | | **WorkflowRunner** | `src/lib/workflow/core/workflowRunner.ts` | Main orchestrator, drives the pipeline | | **EnsembleExecutor** | `src/lib/workflow/core/ensembleExecutor.ts` | Parallel/sequential model execution | | **JudgeScorer** | `src/lib/workflow/core/judgeScorer.ts` | Judge evaluation and multi-judge voting | | **ResponseConditioner** | `src/lib/workflow/core/responseConditioner.ts` | Optional response post-processing | | **WorkflowRegistry** | `src/lib/workflow/core/workflowRegistry.ts` | In-memory workflow storage and lookup | | **Config/Validation** | `src/lib/workflow/config.ts` | Zod schemas, defaults, validation | ### System Prompt Resolution System prompts follow a hierarchical fallback: 1. **Direct parameter** (highest priority) -- passed in `RunWorkflowOptions` 2. **Model-specific** `systemPrompt` -- set on individual `ModelConfig` 3. **Workflow-level** `defaultSystemPrompt` -- set on `WorkflowConfig` 4. **Provider default** (lowest priority) Judge prompts follow the same pattern: 1. **Judge-specific** `customPrompt` 2. **Workflow-level** `defaultJudgePrompt` 3. **Built-in default** evaluation template ### Multi-Judge Voting When multiple judges are configured (`judges` array), each judge evaluates all responses independently in parallel. Scores are aggregated by averaging, and a consensus level (0-1) measures agreement between judges on the best response. ## Configuration Reference ### Execution Defaults | Setting | Default | Description | | --------------- | ------- | ------------------------------------- | | `timeout` | 30000 | Total workflow timeout (ms) | | `modelTimeout` | 15000 | Per-model timeout (ms) | | `judgeTimeout` | 10000 | Judge timeout (ms) | | `retries` | 1 | Max retries on failure | | `retryDelay` | 1000 | Delay between retries (ms) | | `parallelism` | 10 | Max parallel model executions | | `minResponses` | 1 | Minimum successful responses required | | `enableMetrics` | true | Enable metrics collection | | `enableTracing` | false | Enable OpenTelemetry tracing | ### Judge Defaults | Setting | Default | Description | | ------------------ | ---------------------- | ------------------------------ | | `temperature` | 0.1 | Low for consistent evaluation | | `outputFormat` | `"detailed"` | Include full scoring details | | `blindEvaluation` | false | Whether to hide provider names | | `includeReasoning` | true | Always required | | `scoreScale` | `{ min: 0, max: 100 }` | Fixed scale for testing phase | ### Environment Variables | Variable | Description | Required | | ------------------- | -------------------------------------- | -------- | | `OPENAI_API_KEY` | For OpenAI models and judges | Yes\* | | `ANTHROPIC_API_KEY` | For Anthropic models and judges | Yes\* | | `GOOGLE_AI_API_KEY` | For Google AI Studio models and judges | Yes\* | \*Required if using the corresponding provider in your workflow configuration. ## Validation Workflow configurations are validated using Zod schemas before execution. ```typescript const validation = validateWorkflow(myConfig); if (!validation.valid) { console.error("Errors:", validation.errors); console.warn("Warnings:", validation.warnings); } ``` **Validation rules include:** - `id` and `name` are required and non-empty - At least one model is required - Ensemble and adaptive workflows require at least 2 models - Cannot specify both `judge` and `judges` (use one or the other) - Score scale must be `{ min: 0, max: 100 }` - Temperature must be between 0 and 2 - Weights must be between 0 and 1 ## Metrics and Analytics ```typescript calculateModelMetrics, calculateConfidence, calculateConsensus, generateSummaryStats, compareWorkflows, formatMetricsForLogging, } from "@juspay/neurolink"; // Calculate metrics from a workflow result const metrics = calculateModelMetrics(result.ensembleResponses); const confidence = calculateConfidence(result.judgeScores); const consensus = calculateConsensus(result.judgeScores); // Generate summary statistics from multiple results const stats = generateSummaryStats(results); // Compare two workflows const comparison = compareWorkflows(statsA, statsB); console.log("Winner:", comparison.winner); console.log("Reason:", comparison.reasoning); // Format metrics for logging const formatted = formatMetricsForLogging(result); ``` ## Best Practices 1. **Start with `consensus-3-fast`** for development and testing. It is the cheapest pre-built workflow while still providing multi-model validation. 2. **Use `minResponses`** to control fault tolerance. Setting `minResponses: 2` means the workflow requires at least 2 successful model responses before judging. 3. **Keep judge temperature low** (0.1-0.2). Higher temperatures make judge evaluations less consistent. 4. **Enable `blindEvaluation`** when you want unbiased judging. This hides provider and model names from the judge prompt. 5. **Use `synthesizeImprovedResponse`** when you want the judge to create a new response that combines the best elements from all models, rather than just selecting one. 6. **Use `modelGroups` for cost optimization.** Chain and adaptive workflows with tiers allow cheaper models to handle simple queries, escalating to premium models only when needed. 7. **Set appropriate timeouts.** Per-model timeouts should be shorter than the total workflow timeout. Account for both ensemble execution and judge evaluation time. 8. **Monitor costs.** Use `costThreshold` to get warnings when workflow execution costs exceed your budget. ## Troubleshooting | Problem | Solution | | --------------------------------- | ---------------------------------------------------------------------------------- | | Workflow not found in registry | Register it with `registerWorkflow()` before calling `generate()` with `workflow:` | | All models failed | Check API keys, increase `timeout`, verify provider availability | | Judge returns neutral scores (50) | Judge response parsing failed; check judge model supports JSON output | | Slow execution | Reduce model count, use faster models, increase `parallelism` | | High costs | Use `consensus-3-fast`, chain/adaptive workflows, or set `costThreshold` | | Low consensus in multi-judge | Normal for subjective queries; increase judge count or align criteria | ## API Reference ### Core Exports **Execution:** - `runWorkflow(config, options)` -- Execute a complete workflow - `runWorkflowWithStreaming(config, options)` -- Execute with progressive streaming - `executeEnsemble(options)` -- Low-level parallel model execution - `executeModelGroups(groups, prompt, config)` -- Low-level layer-based execution - `scoreEnsemble(options)` -- Low-level judge scoring - `conditionResponse(options)` -- Low-level response conditioning **Configuration:** - `createWorkflowConfig(partial)` -- Create config with defaults - `validateWorkflow(config)` -- Validate workflow configuration - `validateForExecution(config)` -- Validate for execution readiness **Registry:** - `registerWorkflow(config, options)` -- Register a workflow - `unregisterWorkflow(workflowId)` -- Remove a workflow - `getWorkflow(workflowId)` -- Retrieve by ID - `listWorkflows(options)` -- List with filtering - `getRegistryStats()` -- Registry statistics - `clearRegistry()` -- Remove all workflows **Pre-built Workflows:** - `CONSENSUS_3_WORKFLOW` -- 3-model ensemble with judge - `CONSENSUS_3_FAST_WORKFLOW` -- Fast/cheap 3-model ensemble - `BALANCED_ADAPTIVE_WORKFLOW` -- 2-tier balanced adaptive - `QUALITY_MAX_WORKFLOW` -- 3-tier quality-maximizing adaptive - `SPEED_FIRST_WORKFLOW` -- Speed-optimized adaptive - `AGGRESSIVE_FALLBACK_WORKFLOW` -- Fast + parallel premium fallback - `FAST_FALLBACK_WORKFLOW` -- Sequential 3-tier fallback - `MULTI_JUDGE_3_WORKFLOW` -- 3 models, 2 judges - `MULTI_JUDGE_5_WORKFLOW` -- 5 models, 3 judges **Factory Functions:** - `createConsensus3WithPrompt(systemPrompt)` -- Consensus-3 with custom prompt - `createAdaptiveWorkflow(tiers, strategy)` -- Custom adaptive workflow - `createMultiJudgeWorkflow(modelCount, judgeCount)` -- Custom multi-judge **Metrics:** - `calculateModelMetrics(responses)` -- Per-model metrics - `calculateConfidence(scores)` -- Confidence calculation - `calculateConsensus(scores)` -- Consensus calculation - `generateSummaryStats(results)` -- Summary statistics - `compareWorkflows(stats1, stats2)` -- Workflow comparison - `formatMetricsForLogging(result)` -- Formatted logging output **Types:** - `WorkflowConfig`, `WorkflowType`, `WorkflowResult` - `ModelConfig`, `ModelGroup`, `ExecutionStrategy` - `JudgeConfig`, `JudgeScores`, `MultiJudgeScores` - `EnsembleResponse`, `ExecutionConfig` - `ConditioningConfig`, `RunWorkflowOptions` - `WorkflowError`, `WorkflowValidationResult` ## See Also - [Provider Orchestration Guide](/docs/features/provider-orchestration) -- Multi-provider configuration - [Observability Guide](/docs/observability/health-monitoring) -- Tracing workflow executions with Langfuse - [Structured Output Guide](/docs/cookbook/structured-output) -- JSON schema output (note: incompatible with Gemini tools) --- # Examples ## Examples & Tutorials # Examples & Tutorials Learn NeuroLink through practical examples and step-by-step tutorials for real-world applications. ## What You'll Find Here This section contains practical implementations, use cases, and tutorials to help you integrate NeuroLink into your projects effectively. - **[Basic Usage](/docs/examples/basic-usage)** — Fundamental examples for both CLI and SDK usage, covering core functionality and common patterns. - **[Advanced Examples](/docs/advanced)** — Complex implementations showcasing advanced features like custom tools, analytics, and streaming. - **[Use Cases](/docs/use-cases)** — Real-world scenarios and applications across different industries and project types. - **[Business Applications](/docs/examples/business)** — Enterprise-focused examples for production deployments and business automation. ## Quick Examples ```bash # CLI - Get started immediately npx @juspay/neurolink generate "Write a professional email" # With specific provider npx @juspay/neurolink gen "Explain AI" --provider google-ai ``` ```typescript // SDK - Basic integration const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Create a product description" }, }); console.log(result.content); ``` ```bash # CLI - Track usage and costs npx @juspay/neurolink generate "Business proposal" \ --enable-analytics \ --enable-evaluation \ --debug ``` ```typescript // SDK - Monitor performance const result = await neurolink.generate({ input: { text: "Market analysis report" }, enableAnalytics: true, enableEvaluation: true, }); console.log(`Cost: $${result.analytics.cost}`); console.log(`Quality: ${result.evaluation.overall}/10`); ``` ```typescript // Register a custom weather tool neurolink.registerTool("weather", { description: "Get weather for a city", parameters: z.object({ city: z.string(), units: z.enum(["C", "F"]).default("C"), }), execute: async ({ city, units }) => { const data = await fetchWeather(city); return { city, temperature: units === "F" ? (data.temp * 9/5) + 32 : data.temp, condition: data.condition, }; }, }); // Use the tool const result = await neurolink.generate({ input: { text: "What's the weather in Tokyo?" }, }); ``` ## ️ Framework Integration Examples ```typescript // app/api/ai/route.ts export async function POST(request: Request) { const { prompt, context } = await request.json(); const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: prompt }, context, enableAnalytics: true, }); return Response.json({ content: result.content, usage: result.analytics, }); } ``` ```typescript // src/routes/api/stream/+server.ts export const POST: RequestHandler = async ({ request }) => { const { message } = await request.json(); const provider = createBestAIProvider(); const result = await provider.stream({ input: { text: message }, timeout: "2m", }); // Manually create ReadableStream from AsyncIterable const readable = new ReadableStream({ async start(controller) { try { for await (const chunk of result.stream) { if (chunk && typeof chunk === "object" && "content" in chunk) { controller.enqueue(new TextEncoder().encode(chunk.content)); } } controller.close(); } catch (error) { controller.error(error); } }, }); return new Response(readable, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", }, }); }; ``` ```typescript const app = express(); const neurolink = new NeuroLink(); app.post('/api/generate', async (req, res) => { try { const result = await neurolink.generate({ input: { text: req.body.prompt }, provider: req.body.provider, enableAnalytics: true, }); res.json({ success: true, content: result.content, analytics: result.analytics, }); } catch (error) { res.status(500).json({ success: false, error: error.message, }); } }); ``` ## Common Use Cases ### Content Creation ```typescript // Blog post generator with SEO optimization const generateBlogPost = async (topic: string, keywords: string[]) => { const result = await neurolink.generate({ input: { text: `Write a comprehensive blog post about ${topic}. Include these keywords naturally: ${keywords.join(", ")}`, }, maxTokens: 2000, temperature: 0.7, enableAnalytics: true, }); return { content: result.content, wordCount: result.content.split(" ").length, cost: result.analytics.cost, }; }; ``` ### Code Generation ```typescript // Code review and suggestions const reviewCode = async (codeSnippet: string, language: string) => { const result = await neurolink.generate({ input: { text: `Review this ${language} code and provide suggestions: \`\`\`${language} ${codeSnippet} \`\`\``, }, enableEvaluation: true, }); return { review: result.content, confidence: result.evaluation.overall, }; }; ``` ### Data Analysis ```typescript // Automated report generation const generateReport = async (data: any[], reportType: string) => { const summary = JSON.stringify(data.slice(0, 5)); // Sample data const result = await neurolink.generate({ input: { text: `Generate a ${reportType} report based on this data sample: ${summary}`, }, context: { reportType, dataSize: data.length, timestamp: new Date().toISOString(), }, enableAnalytics: true, }); return result; }; ``` ## Batch Processing ```bash # CLI batch processing echo -e "Product description for laptop\nProduct description for phone\nProduct description for tablet" > products.txt npx @juspay/neurolink batch products.txt --output descriptions.json ``` ```typescript // SDK batch processing const generateMultiple = async (prompts: string[]) => { const results = await Promise.all( prompts.map((prompt) => neurolink.generate({ input: { text: prompt }, enableAnalytics: true, }), ), ); const totalCost = results.reduce( (sum, result) => sum + (result.analytics?.cost || 0), 0, ); return { results, totalCost }; }; ``` ## Learning Path 1. **Start with [Basic Usage](/docs/examples/basic-usage)** - Core functionality 2. **Explore [Use Cases](/docs/use-cases)** - Find relevant scenarios 3. **Try [Advanced Examples](/docs/advanced)** - Complex implementations 4. **Study [Business Applications](/docs/examples/business)** - Production patterns ## Related Resources - **[CLI Guide](/docs/)** - Complete command reference - **[SDK Reference](/docs/)** - API documentation - **[Advanced Features](/docs/)** - Enterprise capabilities - **[Visual Demos](/docs/)** - See examples in action --- ## Advanced Examples # Advanced Examples Complex integration patterns, enterprise workflows, and sophisticated use cases for NeuroLink. ## ️ Enterprise Architecture ### Multi-Provider Load Balancing ```typescript class LoadBalancedNeuroLink { private instances: Map; private usage: Map; private limits: Map; constructor() { this.instances = new Map([ ["openai", new NeuroLink({ defaultProvider: "openai" })], ["google-ai", new NeuroLink({ defaultProvider: "google-ai" })], ["anthropic", new NeuroLink({ defaultProvider: "anthropic" })], ]); this.usage = new Map([ ["openai", 0], ["google-ai", 0], ["anthropic", 0], ]); // Daily rate limits this.limits = new Map([ ["openai", 1000], ["google-ai", 2000], ["anthropic", 500], ]); } async generate( prompt: string, priority: "cost" | "speed" | "quality" = "speed", ) { const provider = this.selectOptimalProvider(priority); try { const result = await this.instances.get(provider)!.generate({ input: { text: prompt }, }); this.usage.set(provider, this.usage.get(provider)! + 1); return { ...result, selectedProvider: provider }; } catch (error) { console.warn(`Provider ${provider} failed, trying fallback...`); return this.generateWithFallback(prompt, provider); } } private selectOptimalProvider(priority: string): Provider { const available = Array.from(this.instances.keys()).filter( (provider) => this.usage.get(provider)! this.getCost(a) - this.getCost(b))[0]; case "speed": return available.sort((a, b) => this.getSpeed(a) - this.getSpeed(b))[0]; case "quality": return available.sort( (a, b) => this.getQuality(b) - this.getQuality(a), )[0]; default: return available[0]; } } private async generateWithFallback(prompt: string, failedProvider: Provider) { const remaining = Array.from(this.instances.keys()).filter( (p) => p !== failedProvider, ); for (const provider of remaining) { try { const result = await this.instances.get(provider)!.generate({ input: { text: prompt }, }); this.usage.set(provider, this.usage.get(provider)! + 1); return { ...result, selectedProvider: provider, fallback: true }; } catch (error) { console.warn(`Fallback provider ${provider} also failed`); } } throw new Error("All providers failed"); } private getCost(provider: Provider): number { const costs = { "google-ai": 1, openai: 2, anthropic: 3 }; return costs[provider] || 999; } private getSpeed(provider: Provider): number { const speeds = { "google-ai": 1, openai: 2, anthropic: 3 }; return speeds[provider] || 999; } private getQuality(provider: Provider): number { const quality = { anthropic: 10, openai: 9, "google-ai": 8 }; return quality[provider] || 1; } getUsageStats() { return { usage: Object.fromEntries(this.usage), limits: Object.fromEntries(this.limits), remaining: Object.fromEntries( Array.from(this.limits.entries()).map(([provider, limit]) => [ provider, limit - this.usage.get(provider)!, ]), ), }; } } // Usage const balancer = new LoadBalancedNeuroLink(); const result = await balancer.generate( "Write a technical analysis", "quality", // Prioritize quality ); console.log(`Used provider: ${result.selectedProvider}`); console.log("Usage stats:", balancer.getUsageStats()); ``` ### Caching and Performance Optimization ```typescript class CachedNeuroLink { private neurolink: NeuroLink; private cache: LRUCache; private analytics: Map; constructor() { this.neurolink = new NeuroLink(); this.cache = new LRUCache({ max: 1000, ttl: 1000 * 60 * 60, // 1 hour TTL sizeCalculation: (value) => JSON.stringify(value).length, }); this.analytics = new Map(); } async generate(params: any, options: { useCache?: boolean } = {}) { const cacheKey = this.createCacheKey(params); const startTime = Date.now(); // Check cache first if (options.useCache !== false) { const cached = this.cache.get(cacheKey); if (cached) { this.recordAnalytics(cacheKey, "cache_hit", Date.now() - startTime); return { ...cached, fromCache: true }; } } // Generate new response try { const result = await this.neurolink.generate(params); const duration = Date.now() - startTime; // Cache the result if (options.useCache !== false) { this.cache.set(cacheKey, result); } this.recordAnalytics(cacheKey, "api_call", duration); return { ...result, fromCache: false }; } catch (error) { this.recordAnalytics(cacheKey, "error", Date.now() - startTime); throw error; } } private createCacheKey(params: any): string { const normalized = { text: params.input?.text, provider: params.provider, temperature: params.temperature, maxTokens: params.maxTokens, }; return crypto .createHash("sha256") .update(JSON.stringify(normalized)) .digest("hex"); } private recordAnalytics(key: string, type: string, duration: number) { if (!this.analytics.has(key)) { this.analytics.set(key, []); } this.analytics.get(key).push({ type, duration, timestamp: new Date().toISOString(), }); } getCacheStats() { return { size: this.cache.size, hits: Array.from(this.analytics.values()) .flat() .filter((event) => event.type === "cache_hit").length, misses: Array.from(this.analytics.values()) .flat() .filter((event) => event.type === "api_call").length, errors: Array.from(this.analytics.values()) .flat() .filter((event) => event.type === "error").length, }; } clearCache() { this.cache.clear(); this.analytics.clear(); } } // Usage const cachedNeuroLink = new CachedNeuroLink(); // First call - will hit API const result1 = await cachedNeuroLink.generate({ input: { text: "Explain caching" }, }); // Second identical call - will hit cache const result2 = await cachedNeuroLink.generate({ input: { text: "Explain caching" }, }); console.log("Cache stats:", cachedNeuroLink.getCacheStats()); ``` ## Workflow Automation ### Document Processing Pipeline ```typescript class DocumentProcessor { private neurolink: NeuroLink; constructor() { this.neurolink = new NeuroLink(); } async processDocument(document: string, workflow: string[]) { const results = { originalDocument: document, steps: [] }; let currentContent = document; for (const [index, step] of workflow.entries()) { console.log(`Processing step ${index + 1}: ${step}`); try { const result = await this.executeStep(currentContent, step); results.steps.push({ step, input: currentContent, output: result.content, provider: result.provider, usage: result.usage, }); currentContent = result.content; } catch (error) { results.steps.push({ step, error: error.message, }); break; } } return results; } private async executeStep(content: string, instruction: string) { return await this.neurolink.generate({ input: { text: `${instruction}\n\nContent to process:\n${content}`, }, provider: "anthropic", // Claude is good for document processing temperature: 0.3, }); } } // Usage - Document improvement workflow const processor = new DocumentProcessor(); const workflow = [ "Fix any grammar and spelling errors", "Improve clarity and readability", "Add section headings where appropriate", "Create a table of contents", "Add a conclusion summary", ]; const result = await processor.processDocument(rawDocument, workflow); console.log( "Final processed document:", result.steps[result.steps.length - 1].output, ); ``` ### Multi-Stage Content Creation ```typescript class ContentCreationPipeline { private neurolink: NeuroLink; constructor() { this.neurolink = new NeuroLink(); } async createArticle( topic: string, audience: string, length: "short" | "medium" | "long", ) { const stages = [ { name: "research", provider: "google-ai" }, { name: "outline", provider: "anthropic" }, { name: "draft", provider: "openai" }, { name: "review", provider: "anthropic" }, { name: "finalize", provider: "openai" }, ]; const context = { topic, audience, length }; let content = ""; const stageResults = []; for (const stage of stages) { const result = await this.executeStage(stage, content, context); stageResults.push(result); content = result.content; } return { finalContent: content, stages: stageResults, metadata: { topic, audience, length, createdAt: new Date().toISOString(), wordCount: content.split(" ").length, }, }; } private async executeStage( stage: any, previousContent: string, context: any, ) { const prompts = { research: `Research key points about "${context.topic}" for ${context.audience}. Provide 5-7 main points with brief explanations.`, outline: `Create a detailed outline for a ${context.length} article about "${context.topic}" for ${context.audience}. Base it on this research: ${previousContent}`, draft: `Write a ${context.length} article based on this outline: ${previousContent}. Target audience: ${context.audience}. Make it engaging and informative.`, review: `Review and improve this article: ${previousContent}. Check for clarity, flow, and engagement. Suggest improvements.`, finalize: `Apply these improvements to create the final version: ${previousContent}`, }; const result = await this.neurolink.generate({ input: { text: prompts[stage.name] }, provider: stage.provider, temperature: stage.name === "draft" ? 0.8 : 0.5, }); return { stage: stage.name, provider: stage.provider, content: result.content, usage: result.usage, }; } } // Usage const pipeline = new ContentCreationPipeline(); const article = await pipeline.createArticle( "AI automation in healthcare", "healthcare professionals", "long", ); console.log("Final article:", article.finalContent); console.log("Creation metadata:", article.metadata); ``` ## AI Agent Framework ### Specialized AI Agents ```typescript abstract class AIAgent { protected neurolink: NeuroLink; protected specialization: string; protected temperature: number; protected preferredProvider: string; constructor(specialization: string, config: any = {}) { this.neurolink = new NeuroLink(); this.specialization = specialization; this.temperature = config.temperature || 0.7; this.preferredProvider = config.provider || "auto"; } abstract getSystemPrompt(): string; async process(input: string, context: any = {}): Promise { const systemPrompt = this.getSystemPrompt(); const fullPrompt = `${systemPrompt}\n\nTask: ${input}`; const result = await this.neurolink.generate({ input: { text: fullPrompt }, provider: this.preferredProvider, temperature: this.temperature, context: { agent: this.specialization, ...context }, }); return this.postProcess(result); } protected postProcess(result: any): any { return result; } } class CodeReviewAgent extends AIAgent { constructor() { super("code_reviewer", { temperature: 0.3, provider: "anthropic", }); } getSystemPrompt(): string { return `You are a senior software engineer conducting code reviews. Analyze code for: - Security vulnerabilities - Performance issues - Best practices violations - Maintainability concerns Provide specific, actionable feedback with examples.`; } protected postProcess(result: any): any { // Parse structured feedback const feedback = result.content; return { ...result, issues: this.extractIssues(feedback), suggestions: this.extractSuggestions(feedback), severity: this.assessSeverity(feedback), }; } private extractIssues(feedback: string): string[] { // Extract issues using regex or LLM parsing return feedback.match(/Issue: (.+)/g) || []; } private extractSuggestions(feedback: string): string[] { return feedback.match(/Suggestion: (.+)/g) || []; } private assessSeverity(feedback: string): "low" | "medium" | "high" { if (feedback.includes("security") || feedback.includes("vulnerability")) { return "high"; } if (feedback.includes("performance") || feedback.includes("bug")) { return "medium"; } return "low"; } } class BusinessAnalystAgent extends AIAgent { constructor() { super("business_analyst", { temperature: 0.5, provider: "openai", }); } getSystemPrompt(): string { return `You are a senior business analyst. Analyze business requirements and provide: - Stakeholder analysis - Risk assessment - Success metrics - Implementation recommendations Be data-driven and consider business impact.`; } async analyzeRequirement(requirement: string, businessContext: any) { return await this.process(requirement, { department: businessContext.department, budget: businessContext.budget, timeline: businessContext.timeline, }); } } // Agent Manager class AgentManager { private agents: Map; constructor() { this.agents = new Map([ ["code_review", new CodeReviewAgent()], ["business_analysis", new BusinessAnalystAgent()], ]); } async processTask(agentType: string, task: string, context: any = {}) { const agent = this.agents.get(agentType); if (!agent) { throw new Error(`Unknown agent type: ${agentType}`); } return await agent.process(task, context); } addAgent(name: string, agent: AIAgent) { this.agents.set(name, agent); } } // Usage const manager = new AgentManager(); // Code review const codeReview = await manager.processTask( "code_review", ` function processPayment(amount, cardNumber) { // Store card number in localStorage localStorage.setItem('card', cardNumber); // Process payment return fetch('/api/payment', { method: 'POST', body: JSON.stringify({ amount, cardNumber }) }); } `, ); console.log("Code review results:", codeReview); // Business analysis const bizAnalysis = await manager.processTask( "business_analysis", "Implement real-time analytics dashboard for customer behavior tracking", { department: "product", budget: 50000, timeline: "3 months", }, ); console.log("Business analysis:", bizAnalysis.content); ``` ## Advanced Analytics Integration ### Custom Analytics Collection ```typescript class AdvancedAnalytics { private neurolink: NeuroLink; private metrics: Map; private webhookUrl?: string; constructor(webhookUrl?: string) { this.neurolink = new NeuroLink({ analytics: { enabled: true }, }); this.metrics = new Map(); this.webhookUrl = webhookUrl; } async generateWithAnalytics( prompt: string, metadata: any = {}, customMetrics: string[] = [], ) { const startTime = Date.now(); const sessionId = this.generateSessionId(); try { const result = await this.neurolink.generate({ input: { text: prompt }, context: { sessionId, metadata, customMetrics, }, }); const duration = Date.now() - startTime; // Collect detailed metrics const analytics = { sessionId, timestamp: new Date().toISOString(), prompt: prompt.substring(0, 100), // Truncated for privacy provider: result.provider, duration, tokenUsage: result.usage, success: true, metadata, customMetrics: await this.collectCustomMetrics(result, customMetrics), }; await this.recordMetrics(analytics); return { ...result, analytics }; } catch (error) { const analytics = { sessionId, timestamp: new Date().toISOString(), duration: Date.now() - startTime, success: false, error: error.message, metadata, }; await this.recordMetrics(analytics); throw error; } } private async collectCustomMetrics(result: any, metrics: string[]) { const customData: any = {}; for (const metric of metrics) { switch (metric) { case "sentiment": customData.sentiment = await this.analyzeSentiment(result.content); break; case "readability": customData.readability = this.calculateReadability(result.content); break; case "keyword_density": customData.keywords = this.extractKeywords(result.content); break; } } return customData; } private async analyzeSentiment(text: string): Promise { const result = await this.neurolink.generate({ input: { text: `Analyze the sentiment of this text (positive/negative/neutral): ${text}`, }, temperature: 0.1, maxTokens: 50, }); return { sentiment: result.content.toLowerCase().trim() }; } private calculateReadability(text: string): any { const sentences = text.split(/[.!?]+/).length; const words = text.split(/\s+/).length; const avgWordsPerSentence = words / sentences; return { wordCount: words, sentenceCount: sentences, avgWordsPerSentence: Math.round(avgWordsPerSentence * 100) / 100, readabilityScore: this.getReadabilityScore(avgWordsPerSentence), }; } private getReadabilityScore(avgWords: number): string { if (avgWords array.indexOf(word) === index) ?.slice(0, 10) || [] ); } private async recordMetrics(analytics: any) { // Store locally const key = analytics.sessionId || "general"; if (!this.metrics.has(key)) { this.metrics.set(key, []); } this.metrics.get(key)!.push(analytics); // Send to webhook if configured if (this.webhookUrl) { try { await fetch(this.webhookUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(analytics), }); } catch (error) { console.warn("Failed to send analytics to webhook:", error); } } } generateReport(timeRange: { start: Date; end: Date }) { const allMetrics = Array.from(this.metrics.values()).flat(); const filtered = allMetrics.filter((m) => { const timestamp = new Date(m.timestamp); return timestamp >= timeRange.start && timestamp m.success).length / filtered.length; const avgDuration = filtered.reduce((sum, m) => sum + m.duration, 0) / filtered.length; const providerUsage = this.groupBy(filtered, "provider"); return { totalRequests: filtered.length, successRate: Math.round(successRate * 100), avgDuration: Math.round(avgDuration), providerBreakdown: providerUsage, timeRange, }; } private groupBy(array: any[], key: string) { return array.reduce((groups, item) => { const group = item[key] || "unknown"; groups[group] = (groups[group] || 0) + 1; return groups; }, {}); } private generateSessionId(): string { return Date.now().toString(36) + Math.random().toString(36).substr(2); } } // Usage const analytics = new AdvancedAnalytics( "https://analytics.company.com/webhook", ); const result = await analytics.generateWithAnalytics( "Write a product description for our new AI tool", { department: "marketing", campaign: "Q4_launch", user_id: "user123", }, ["sentiment", "readability", "keyword_density"], ); console.log("Response:", result.content); console.log("Analytics:", result.analytics); // Generate report const report = analytics.generateReport({ start: new Date(Date.now() - 24 * 60 * 60 * 1000), // Last 24 hours end: new Date(), }); console.log("Analytics report:", report); ``` This advanced examples documentation provides sophisticated patterns for enterprise usage, workflow automation, AI agent frameworks, and comprehensive analytics integration. These examples demonstrate how NeuroLink can be extended for complex, production-ready applications. ## Related Documentation - [Basic Usage](/docs/examples/basic-usage) - Simple examples to get started - [Business Examples](/docs/examples/business) - Business-focused use cases - [CLI Advanced Usage](/docs/cli/advanced) - Command-line patterns - [SDK Reference](/docs/sdk/api-reference) - Complete API documentation --- ## Basic Usage Examples # Basic Usage Examples Simple examples to get started with NeuroLink in different scenarios and programming languages. **Prerequisites**: Before running these examples, ensure you have configured at least one AI provider. See [Provider Configuration Guide](/docs/getting-started/provider-setup) for setup instructions. ## Quick Start Examples ### Simple Text Generation ```typescript const neurolink = new NeuroLink(); // Basic text generation const result = await neurolink.generate({ input: { text: "Explain TypeScript in simple terms" }, }); console.log(result.content); ``` ### CLI Basic Usage ```bash # Simple generation npx @juspay/neurolink gen "Write a haiku about programming" # With specific provider npx @juspay/neurolink gen "Explain quantum computing" --provider google-ai # Save to file npx @juspay/neurolink gen "Create a README template" > README.md ``` ## SDK Integration Examples ### Node.js Application ```typescript class AIAssistant { private neurolink: NeuroLink; constructor() { this.neurolink = new NeuroLink(); } async generateResponse(userMessage: string): Promise { const result = await this.neurolink.generate({ input: { text: userMessage }, provider: "auto", // Auto-select best provider temperature: 0.7, }); return result.content; } async summarizeText(text: string): Promise { const result = await this.neurolink.generate({ input: { text: `Summarize this text in 2-3 sentences: ${text}`, }, maxTokens: 150, }); return result.content; } } // Usage const assistant = new AIAssistant(); const response = await assistant.generateResponse( "How do I deploy a Node.js app?", ); console.log(response); ``` ### Express.js API ```typescript const app = express(); const neurolink = new NeuroLink(); app.use(express.json()); // AI generation endpoint app.post("/api/generate", async (req, res) => { try { const { prompt, provider = "auto" } = req.body; const result = await neurolink.generate({ input: { text: prompt }, provider: provider, }); res.json({ success: true, content: result.content, provider: result.provider, usage: result.usage, }); } catch (error) { res.status(500).json({ success: false, error: error.message, }); } }); // Text summarization endpoint app.post("/api/summarize", async (req, res) => { try { const { text, maxLength = 150 } = req.body; const result = await neurolink.generate({ input: { text: `Provide a concise summary of this text: ${text}`, }, maxTokens: maxLength, temperature: 0.3, // Lower temperature for factual summarization }); res.json({ success: true, summary: result.content, originalLength: text.length, summaryLength: result.content.length, }); } catch (error) { res.status(500).json({ success: false, error: error.message, }); } }); app.listen(3000, () => { console.log("AI API server running on port 3000"); }); ``` ## ⚛️ React Integration ### Basic React Component ```typescript const neurolink = new NeuroLink(); function AIChat() { const [message, setMessage] = useState(""); const [response, setResponse] = useState(""); const [loading, setLoading] = useState(false); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!message.trim()) return; setLoading(true); try { const result = await neurolink.generate({ input: { text: message }, provider: "google-ai" }); setResponse(result.content); } catch (error) { setResponse(`Error: ${error.message}`); } finally { setLoading(false); } }; return ( setMessage(e.target.value)} placeholder="Ask me anything..." disabled={loading} /> {loading ? "Generating..." : "Send"} {response && ( Response: {response} )} ); } export default AIChat; ``` ### React Hook for AI ```typescript const neurolink = new NeuroLink(); export function useAI() { const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const generate = useCallback(async (prompt: string, options = {}) => { setLoading(true); setError(null); try { const result = await neurolink.generate({ input: { text: prompt }, ...options }); return result; } catch (err) { const errorMessage = err instanceof Error ? err.message : "Unknown error"; setError(errorMessage); throw err; } finally { setLoading(false); } }, []); return { generate, loading, error }; } // Usage in component function MyComponent() { const { generate, loading, error } = useAI(); const [result, setResult] = useState(""); const handleGenerate = async () => { try { const response = await generate("Explain React hooks"); setResult(response.content); } catch (err) { console.error("Generation failed:", err); } }; return ( {loading ? "Generating..." : "Generate"} {error && Error: {error}} {result && {result}} ); } ``` ## Common Use Cases ### Code Generation ```typescript async function generateCode(description: string, language: string) { const result = await neurolink.generate({ input: { text: `Write ${language} code for: ${description}. Include comments and error handling.`, }, provider: "anthropic", // Claude is great for code temperature: 0.3, // Lower temperature for precise code }); return result.content; } // Usage const pythonCode = await generateCode( "function to calculate compound interest", "Python", ); console.log(pythonCode); ``` ### Content Creation ```typescript async function createBlogPost(topic: string, audience: string) { const result = await neurolink.generate({ input: { text: `Write a blog post about ${topic} for ${audience}. Include: introduction, main points, conclusion, and call-to-action.`, }, provider: "openai", temperature: 0.8, // Higher temperature for creative content maxTokens: 1500, }); return result.content; } // Usage const blogPost = await createBlogPost( "AI automation in business", "small business owners", ); ``` ### Data Analysis ```typescript async function analyzeData(data: any[], question: string) { const dataString = JSON.stringify(data, null, 2); const result = await neurolink.generate({ input: { text: `Analyze this data and answer: ${question} Data: ${dataString}`, }, provider: "google-ai", maxTokens: 800, }); return result.content; } // Usage const salesData = [ { month: "Jan", sales: 10000, region: "North" }, { month: "Feb", sales: 12000, region: "North" }, // ... more data ]; const analysis = await analyzeData( salesData, "What trends do you see in the sales data?", ); ``` ### Multi-Model Access with LiteLLM ```typescript async function compareResponses(prompt: string) { const models = [ "openai/gpt-4o", "anthropic/claude-3-5-sonnet", "google/gemini-2.0-flash", ]; const comparisons = await Promise.all( models.map(async (model) => { const result = await neurolink.generate({ input: { text: prompt }, provider: "litellm", model: model, temperature: 0.7, }); return { model: model, response: result.content, provider: result.provider, }; }), ); return comparisons; } // Usage const prompt = "Explain the benefits of renewable energy"; const responses = await compareResponses(prompt); responses.forEach(({ model, response }) => { console.log(`\n${model}:`); console.log(response); }); ``` ### Custom Model Access with SageMaker ```typescript async function useCustomSageMakerModel(prompt: string, endpoint?: string) { const result = await neurolink.generate({ input: { text: prompt }, provider: "sagemaker", model: endpoint || "my-custom-model", // Use specific endpoint or default temperature: 0.7, timeout: "45s", // Longer timeout for custom models }); return { response: result.content, endpoint: result.model, provider: result.provider, usage: result.usage, }; } // Usage with default endpoint const defaultResult = await useCustomSageMakerModel( "Analyze this customer feedback for sentiment", ); // Usage with specific endpoint const specificResult = await useCustomSageMakerModel( "Generate domain-specific recommendations", "my-domain-expert-model-endpoint", ); console.log("Default model response:", defaultResult.response); console.log("Domain model response:", specificResult.response); ``` ### SageMaker Model Comparison ```typescript async function compareSageMakerModels(prompt: string) { const endpoints = [ "general-purpose-model", "domain-specific-model", "fine-tuned-customer-model", ]; const comparisons = await Promise.all( endpoints.map(async (endpoint) => { try { const result = await neurolink.generate({ input: { text: prompt }, provider: "sagemaker", model: endpoint, temperature: 0.7, timeout: "30s", }); return { endpoint: endpoint, response: result.content, success: true, responseTime: result.responseTime, }; } catch (error) { return { endpoint: endpoint, error: error.message, success: false, }; } }), ); return comparisons; } // Usage const prompt = "Provide recommendations for improving customer satisfaction"; const modelComparisons = await compareSageMakerModels(prompt); modelComparisons.forEach(({ endpoint, response, success, error }) => { console.log(`\n${endpoint}:`); if (success) { console.log(response); } else { console.log(`❌ Error: ${error}`); } }); ``` ### Production SageMaker Integration ```typescript class SageMakerModelManager { private neurolink: NeuroLink; private defaultEndpoint: string; constructor(defaultEndpoint: string) { this.neurolink = new NeuroLink(); this.defaultEndpoint = defaultEndpoint; } async predict( input: string, options: { endpoint?: string; temperature?: number; maxTokens?: number; timeout?: string; } = {}, ) { const { endpoint = this.defaultEndpoint, temperature = 0.7, maxTokens = 1000, timeout = "30s", } = options; try { const result = await this.neurolink.generate({ input: { text: input }, provider: "sagemaker", model: endpoint, temperature, maxTokens, timeout, }); return { success: true, prediction: result.content, endpoint: endpoint, usage: result.usage, responseTime: result.responseTime, }; } catch (error) { return { success: false, error: error.message, endpoint: endpoint, }; } } async batchPredict(inputs: string[], endpoint?: string) { const results = []; for (const input of inputs) { const result = await this.predict(input, { endpoint }); results.push(result); // Rate limiting between requests await new Promise((resolve) => setTimeout(resolve, 1000)); } return results; } async healthCheck(endpoint?: string): Promise { try { const result = await this.predict("test", { endpoint, timeout: "10s", }); return result.success; } catch { return false; } } } // Usage const modelManager = new SageMakerModelManager("production-model-endpoint"); // Single prediction const prediction = await modelManager.predict( "Analyze this business scenario and provide recommendations", ); // Batch predictions const inputs = [ "Predict market trends for Q4", "Analyze customer churn risk", "Recommend product improvements", ]; const batchResults = await modelManager.batchPredict(inputs); // Health check const isHealthy = await modelManager.healthCheck(); console.log(`Model endpoint healthy: ${isHealthy}`); ``` ### Multi-Provider Strategy with SageMaker ```typescript async function hybridModelStrategy(prompt: string, useCase: string) { const strategies = { general: { primary: { provider: "google-ai", model: "gemini-2.5-flash" }, fallback: { provider: "openai", model: "gpt-4o-mini" }, }, "domain-specific": { primary: { provider: "sagemaker", model: "domain-expert-model" }, fallback: { provider: "anthropic", model: "claude-3-haiku" }, }, "code-generation": { primary: { provider: "anthropic", model: "claude-3-5-sonnet" }, fallback: { provider: "sagemaker", model: "code-specialized-model" }, }, }; const strategy = strategies[useCase] || strategies["general"]; try { // Try primary model const result = await neurolink.generate({ input: { text: prompt }, provider: strategy.primary.provider, model: strategy.primary.model, timeout: "30s", }); return { ...result, modelUsed: "primary", strategy: strategy.primary, }; } catch (primaryError) { console.log(`Primary model failed, trying fallback...`); try { // Fallback to secondary model const result = await neurolink.generate({ input: { text: prompt }, provider: strategy.fallback.provider, model: strategy.fallback.model, timeout: "30s", }); return { ...result, modelUsed: "fallback", strategy: strategy.fallback, primaryError: primaryError.message, }; } catch (fallbackError) { throw new Error( `Both models failed. Primary: ${primaryError.message}, Fallback: ${fallbackError.message}`, ); } } } // Usage const generalResult = await hybridModelStrategy( "Explain artificial intelligence", "general", ); const domainResult = await hybridModelStrategy( "Provide industry-specific analysis for healthcare", "domain-specific", ); const codeResult = await hybridModelStrategy( "Generate a Python function for data processing", "code-generation", ); console.log("General query result:", generalResult.content); console.log("Used model:", generalResult.strategy); ``` ## Configuration Examples ### Environment-based Configuration ```typescript // Development configuration const devNeuroLink = new NeuroLink({ conversationMemory: { enabled: false }, enableOrchestration: false, }); // Production configuration const prodNeuroLink = new NeuroLink({ conversationMemory: { enabled: true, enableSummarization: true }, enableOrchestration: true, observability: { langfuse: { enabled: true, publicKey: process.env.LANGFUSE_PUBLIC_KEY!, secretKey: process.env.LANGFUSE_SECRET_KEY!, }, }, }); // Use appropriate instance const neurolink = process.env.NODE_ENV === "production" ? prodNeuroLink : devNeuroLink; ``` ### Provider Fallback ```typescript async function generateWithFallback(prompt: string) { const providers = ["google-ai", "openai", "anthropic"]; for (const provider of providers) { try { const result = await neurolink.generate({ input: { text: prompt }, provider: provider, timeout: 10000, }); console.log(`✅ Success with ${provider}`); return result; } catch (error) { console.warn(`❌ ${provider} failed:`, error.message); } } throw new Error("All providers failed"); } ``` ## ️ Utility Functions ### Text Processing Helpers ```typescript class TextProcessor { private neurolink: NeuroLink; constructor() { this.neurolink = new NeuroLink(); } async translate(text: string, targetLanguage: string): Promise { const result = await this.neurolink.generate({ input: { text: `Translate this text to ${targetLanguage}: ${text}`, }, temperature: 0.2, }); return result.content; } async improveWriting(text: string): Promise { const result = await this.neurolink.generate({ input: { text: `Improve the clarity and readability of this text: ${text}`, }, temperature: 0.4, }); return result.content; } async extractKeyPoints(text: string): Promise { const result = await this.neurolink.generate({ input: { text: `Extract the key points from this text as a bullet list: ${text}`, }, temperature: 0.3, }); // Parse bullet points from response return result.content .split("\n") .filter( (line) => line.trim().startsWith("•") || line.trim().startsWith("-"), ) .map((line) => line.replace(/^[•\-]\s*/, "").trim()); } } // Usage const processor = new TextProcessor(); const improvedText = await processor.improveWriting( "This text needs improvement.", ); const keyPoints = await processor.extractKeyPoints(longArticle); ``` ### Batch Processing ```typescript async function batchProcess(prompts: string[], batchSize = 3) { const results = []; for (let i = 0; i { return await neurolink.generate({ input: { text: prompt }, provider: "auto", }); }); const batchResults = await Promise.all(batchPromises); results.push(...batchResults); // Rate limiting delay if (i + batchSize setTimeout(resolve, 2000)); } } return results; } // Usage const prompts = [ "Explain machine learning", "What is blockchain?", "How does quantum computing work?", ]; const results = await batchProcess(prompts); results.forEach((result, i) => { console.log(`Response ${i + 1}:`, result.content); }); ``` ## Related Documentation - [CLI Examples](/docs/cli/examples) - Command-line usage examples - [Advanced Examples](/docs/advanced) - Complex integration patterns - [Framework Integration](/docs/sdk/framework-integration) - Specific framework guides - [Provider Setup](/docs/getting-started/provider-setup) - API key configuration --- ## Business Applications # Business Applications Enterprise-focused examples demonstrating NeuroLink's value in business environments, ROI optimization, and organizational workflows. ## Executive Decision Support ### Strategic Planning Assistant **Scenario**: C-level executives need AI-powered insights for strategic decisions. ```typescript class StrategyAssistant { private neurolink: NeuroLink; constructor() { this.neurolink = new NeuroLink({ analytics: { enabled: true }, }); } async analyzeMarketOpportunity(opportunity: any, companyContext: any) { const prompt = `Analyze this market opportunity for strategic decision-making: Opportunity: ${JSON.stringify(opportunity, null, 2)} Company context: ${JSON.stringify(companyContext, null, 2)} Provide: 1. Market size and growth potential 2. Competitive landscape analysis 3. Required investment and resources 4. Risk assessment and mitigation strategies 5. ROI projections and timeline 6. Go/no-go recommendation with rationale`; return await this.neurolink.generate({ input: { text: prompt }, provider: "anthropic", temperature: 0.4, maxTokens: 1500, context: { role: "strategic_analysis", department: "executive", priority: "high", }, }); } async generateBoardPresentation(quarterlyData: any, initiatives: any[]) { const prompt = `Create a board presentation summary based on: Quarterly performance: ${JSON.stringify(quarterlyData, null, 2)} Key initiatives: ${JSON.stringify(initiatives, null, 2)} Include: - Executive summary (3 key points) - Financial highlights - Strategic progress - Challenges and solutions - Next quarter priorities Format for C-level audience.`; return await this.neurolink.generate({ input: { text: prompt }, provider: "openai", temperature: 0.5, context: { audience: "board_of_directors", format: "executive_summary", }, }); } async competitorAnalysis(competitors: string[], marketSegment: string) { const prompt = `Conduct comprehensive competitor analysis: Competitors: ${competitors.join(", ")} Market segment: ${marketSegment} For each competitor analyze: - Market position and share - Key strengths and weaknesses - Pricing strategy - Recent moves and partnerships - Threats and opportunities they present Conclude with strategic recommendations.`; return await this.neurolink.generate({ input: { text: prompt }, provider: "google-ai", temperature: 0.6, maxTokens: 2000, }); } } // Usage const strategy = new StrategyAssistant(); // Analyze new market entry const marketAnalysis = await strategy.analyzeMarketOpportunity( { market: "AI-powered customer service", geography: "European Union", targetSegment: "SMB", entryStrategy: "acquisition", }, { currentRevenue: "$50M", employees: 200, marketPresence: ["North America"], coreCompetencies: ["AI/ML", "SaaS platforms"], }, ); // Generate quarterly board presentation const boardDeck = await strategy.generateBoardPresentation( { revenue: "$12.5M", growth: "23%", customers: 1850, churn: "2.1%", }, [ { name: "Product V2 Launch", status: "on-track", impact: "high" }, { name: "EU Expansion", status: "delayed", impact: "medium" }, ], ); console.log("Strategic Analysis:", marketAnalysis.content); console.log("Board Presentation:", boardDeck.content); ``` ### CLI for Executive Workflows ```bash #!/bin/bash # Executive daily briefing automation DATE=$(date +"%Y-%m-%d") echo " Generating Executive Daily Briefing for $DATE" # Market analysis npx @juspay/neurolink gen " Analyze today's key business news and market trends relevant to SaaS companies. Focus on: AI/ML industry, enterprise software, regulatory changes, competitive moves. Provide 3-5 key insights with business implications. " --enable-analytics \ --context '{"role":"executive","type":"market_briefing","date":"'$DATE'"}' \ > briefing-market-$DATE.md # Industry intelligence npx @juspay/neurolink gen " Generate strategic intelligence for enterprise AI software company: 1. Emerging technology trends affecting our market 2. New competitors or competitive threats 3. Partnership and acquisition opportunities 4. Regulatory developments 5. Customer behavior shifts Format as executive summary with action items. " --provider anthropic \ --enable-evaluation \ --evaluation-domain "Business Strategy Consultant" \ > briefing-intelligence-$DATE.md # Performance analysis npx @juspay/neurolink gen " Based on typical SaaS metrics, create analysis framework for: - Revenue growth assessment - Customer acquisition cost optimization - Churn reduction strategies - Market expansion opportunities Include KPIs to track and red flags to monitor. " --context '{"company_stage":"growth","sector":"b2b_saas"}' \ > performance-framework-$DATE.md echo "✅ Executive briefing complete" echo " Files generated:" echo " - briefing-market-$DATE.md" echo " - briefing-intelligence-$DATE.md" echo " - performance-framework-$DATE.md" ``` ## Operations & Process Optimization ### Business Process Analysis ```typescript class ProcessOptimizer { private neurolink: NeuroLink; constructor() { this.neurolink = new NeuroLink(); } async analyzeWorkflow(processData: any, painPoints: string[]) { const prompt = `Analyze this business process for optimization opportunities: Current process: ${JSON.stringify(processData, null, 2)} Known pain points: ${painPoints.join(", ")} Provide: 1. Process efficiency analysis 2. Bottleneck identification 3. Automation opportunities 4. Resource optimization suggestions 5. Implementation roadmap 6. Expected ROI and timeline`; return await this.neurolink.generate({ input: { text: prompt }, provider: "anthropic", temperature: 0.4, context: { analysis_type: "process_optimization", focus: "efficiency_roi", }, }); } async generateSOPs(processName: string, steps: any[], compliance: string[]) { const prompt = `Create comprehensive Standard Operating Procedures for: ${processName} Process steps: ${JSON.stringify(steps, null, 2)} Compliance requirements: ${compliance.join(", ")} Include: - Step-by-step procedures - Quality checkpoints - Error handling protocols - Escalation procedures - Training requirements - Compliance verification`; return await this.neurolink.generate({ input: { text: prompt }, provider: "google-ai", temperature: 0.3, maxTokens: 1500, }); } async costBenefitAnalysis( currentCosts: any, proposedSolution: any, timeframe: string, ) { const prompt = `Conduct detailed cost-benefit analysis: Current costs: ${JSON.stringify(currentCosts, null, 2)} Proposed solution: ${JSON.stringify(proposedSolution, null, 2)} Analysis timeframe: ${timeframe} Calculate: - Implementation costs - Operational savings - Productivity gains - Risk mitigation value - ROI and payback period - Sensitivity analysis`; return await this.neurolink.generate({ input: { text: prompt }, provider: "openai", temperature: 0.3, context: { analysis_type: "financial", output_format: "business_case", }, }); } } // Usage const optimizer = new ProcessOptimizer(); // Analyze customer onboarding process const onboardingAnalysis = await optimizer.analyzeWorkflow( { name: "Customer Onboarding", steps: [ { step: "Lead qualification", duration: "2 days", owner: "Sales" }, { step: "Contract signing", duration: "5 days", owner: "Legal" }, { step: "Technical setup", duration: "10 days", owner: "Engineering" }, { step: "Training delivery", duration: "3 days", owner: "Success" }, ], currentDuration: "20 days", customerSatisfaction: "6.5/10", }, [ "Long lead times", "Manual handoffs", "Limited visibility", "Inconsistent experience", ], ); // Generate SOPs for incident response const incidentSOPs = await optimizer.generateSOPs( "Security Incident Response", [ { step: "Detection", tools: ["SIEM", "Monitoring"], timeframe: "5 minutes", }, { step: "Assessment", team: ["Security", "Engineering"], timeframe: "15 minutes", }, { step: "Containment", actions: ["Isolate", "Preserve evidence"], timeframe: "30 minutes", }, { step: "Recovery", validation: ["Service restoration", "Security verification"], }, ], ["SOX", "GDPR", "ISO 27001"], ); // Cost-benefit analysis for automation const automationROI = await optimizer.costBenefitAnalysis( { manualProcessing: "$50000/month", errorRate: "5%", processingTime: "4 hours/task", }, { automationTool: "$10000/month", implementationCost: "$100000", expectedErrorRate: "0.5%", expectedProcessingTime: "15 minutes/task", }, "24 months", ); ``` ## Financial Planning & Analysis ### Financial Decision Support ```bash # Budget analysis and planning npx @juspay/neurolink gen " Analyze our Q4 budget performance and create Q1 planning recommendations: Q4 Performance: - Revenue: $2.8M (target: $3M) - OpEx: $2.1M (budget: $2M) - Customer Acquisition Cost: $450 - Gross margin: 78% Create Q1 budget recommendations focusing on: 1. Revenue optimization strategies 2. Cost structure improvements 3. Investment priorities 4. Risk mitigation measures " --provider anthropic \ --enable-analytics \ --context '{"department":"finance","type":"budget_planning"}' \ > q1-budget-analysis.md # Investment proposal evaluation npx @juspay/neurolink gen " Evaluate this investment proposal: - New AI development team: $500K annual cost - Expected output: 2x faster feature development - Market opportunity: $10M TAM expansion - Timeline: 18 month payback projected Analyze from CFO perspective: - Financial viability - Risk assessment - Alternative approaches - Investment committee recommendation " --enable-evaluation \ --evaluation-domain "Chief Financial Officer" \ > investment-proposal-analysis.md # Cash flow forecasting npx @juspay/neurolink gen " Create 12-month cash flow forecast model framework for SaaS business: Include considerations for: - Subscription revenue recognition - Seasonal variations - Customer churn impact - Growth investment timing - Working capital requirements Provide Excel-ready formulas and scenarios (conservative, base, optimistic). " --max-tokens 1500 \ > cashflow-model-framework.md ``` ## Sales & Revenue Optimization ### Sales Intelligence ```typescript class SalesIntelligence { private neurolink: NeuroLink; constructor() { this.neurolink = new NeuroLink(); } async analyzeSalesPerformance( salesData: any[], territory: string, period: string, ) { const prompt = `Analyze sales performance for ${territory} in ${period}: Sales data: ${JSON.stringify(salesData, null, 2)} Provide analysis of: 1. Performance vs targets and trends 2. Top performing segments/products 3. Underperforming areas requiring attention 4. Seasonal or cyclical patterns 5. Competitive win/loss insights 6. Pipeline health assessment 7. Actionable recommendations for improvement`; return await this.neurolink.generate({ input: { text: prompt }, provider: "google-ai", temperature: 0.4, context: { department: "sales", analysis_type: "performance_review", territory: territory, }, }); } async generateSalesPlaybook( industry: string, buyerPersonas: any[], salesCycle: any, ) { const prompt = `Create a comprehensive sales playbook for ${industry}: Buyer personas: ${JSON.stringify(buyerPersonas, null, 2)} Sales cycle: ${JSON.stringify(salesCycle, null, 2)} Include: - Discovery question frameworks - Objection handling scripts - Value proposition messaging - Competitive battle cards - Closing techniques - Follow-up sequences - Success metrics and KPIs`; return await this.neurolink.generate({ input: { text: prompt }, provider: "anthropic", temperature: 0.6, maxTokens: 2000, }); } async optimizePricing( marketData: any, competitorPricing: any[], valueDrivers: string[], ) { const prompt = `Develop pricing optimization strategy: Market data: ${JSON.stringify(marketData, null, 2)} Competitor pricing: ${JSON.stringify(competitorPricing, null, 2)} Value drivers: ${valueDrivers.join(", ")} Recommend: 1. Optimal pricing structure and tiers 2. Value-based pricing justification 3. Competitive positioning strategy 4. Price sensitivity analysis 5. A/B testing framework 6. Implementation timeline and change management`; return await this.neurolink.generate({ input: { text: prompt }, provider: "openai", temperature: 0.5, context: { analysis_type: "pricing_strategy", focus: "revenue_optimization", }, }); } } // Usage const salesIntel = new SalesIntelligence(); // Analyze quarterly sales performance const performanceAnalysis = await salesIntel.analyzeSalesPerformance( [ { rep: "John", target: 100000, actual: 120000, deals: 12 }, { rep: "Sarah", target: 100000, actual: 85000, deals: 8 }, { rep: "Mike", target: 100000, actual: 110000, deals: 15 }, ], "North America", "Q4 2024", ); // Generate industry-specific sales playbook const playbook = await salesIntel.generateSalesPlaybook( "Financial Services", [ { role: "CFO", painPoints: ["Cost control", "Compliance"], budget: "High" }, { role: "IT Director", painPoints: ["Security", "Integration"], influence: "High", }, ], { averageLength: "6 months", keyStages: [ "Discovery", "Technical Evaluation", "Business Case", "Legal Review", ], }, ); // Optimize pricing strategy const pricingStrategy = await salesIntel.optimizePricing( { marketSize: "$5B", growth: "15%", averageDealSize: "$50K", }, [ { competitor: "CompetitorA", startingPrice: "$10K", enterprise: "$50K" }, { competitor: "CompetitorB", startingPrice: "$15K", enterprise: "$75K" }, ], [ "ROI improvement", "Time savings", "Risk reduction", "Compliance automation", ], ); ``` ## Marketing & Customer Success ### Marketing Intelligence ```bash # Campaign performance analysis npx @juspay/neurolink gen " Analyze our Q4 marketing campaign performance: Campaign Results: - Email marketing: 4.2% CTR, 18% open rate, $15 CPA - Paid search: 3.8% CTR, $22 CPA, 1.2M impressions - Content marketing: 125K blog views, 850 leads - Social media: 15K engagement, 320 qualified leads - Events: 3 conferences, 180 leads, $45K spend Provide: 1. Performance assessment vs industry benchmarks 2. Channel effectiveness and ROI analysis 3. Attribution modeling insights 4. Optimization recommendations for Q1 5. Budget reallocation suggestions " --enable-analytics \ --context '{"department":"marketing","type":"campaign_analysis"}' \ > marketing-performance-q4.md # Customer segmentation strategy npx @juspay/neurolink gen " Develop customer segmentation strategy for B2B SaaS: Current customer base: - 2,500 total customers - Industries: Tech (40%), Financial (25%), Healthcare (20%), Other (15%) - Company sizes: SMB (5000, 10%) - Usage patterns: Power users (25%), Regular users (50%), Light users (25%) Create segmentation framework for: - Targeted messaging and positioning - Product development priorities - Customer success strategies - Upselling and expansion opportunities " --provider anthropic \ --enable-evaluation \ --evaluation-domain "VP of Marketing" \ > customer-segmentation-strategy.md # Content marketing strategy npx @juspay/neurolink gen " Create comprehensive content marketing strategy: Target audience: IT decision makers at mid-market companies Key topics: AI adoption, digital transformation, security, compliance Content goals: Brand awareness, lead generation, thought leadership Develop: 1. Content pillar framework 2. Editorial calendar structure 3. Content distribution strategy 4. Performance measurement framework 5. Resource requirements and budget 6. 90-day implementation plan " --temperature 0.7 \ --max-tokens 1500 \ > content-marketing-strategy.md ``` ### Customer Success Optimization ```typescript class CustomerSuccessIntelligence { private neurolink: NeuroLink; constructor() { this.neurolink = new NeuroLink(); } async analyzeChurnRisk(customerData: any[], usageMetrics: any[]) { const prompt = `Analyze customer churn risk and provide retention strategies: Customer data: ${JSON.stringify(customerData.slice(0, 5), null, 2)} Usage metrics: ${JSON.stringify(usageMetrics.slice(0, 5), null, 2)} Identify: 1. High-risk churn indicators and patterns 2. Customer segments most at risk 3. Early warning signals to monitor 4. Proactive intervention strategies 5. Success metrics for retention programs 6. Resource allocation recommendations`; return await this.neurolink.generate({ input: { text: prompt }, provider: "anthropic", temperature: 0.4, context: { department: "customer_success", analysis_type: "churn_prevention", }, }); } async generateExpansionStrategy(accountData: any, productCatalog: any[]) { const prompt = `Develop account expansion strategy: Account data: ${JSON.stringify(accountData, null, 2)} Available products: ${JSON.stringify(productCatalog, null, 2)} Recommend: 1. Expansion opportunities and prioritization 2. Cross-sell and upsell scenarios 3. Value proposition for each opportunity 4. Implementation timeline and approach 5. Success probability assessment 6. Revenue impact projections`; return await this.neurolink.generate({ input: { text: prompt }, provider: "google-ai", temperature: 0.5, context: { focus: "revenue_expansion", account_tier: accountData.tier, }, }); } async optimizeOnboarding(currentProcess: any, customerFeedback: string[]) { const prompt = `Optimize customer onboarding process: Current process: ${JSON.stringify(currentProcess, null, 2)} Customer feedback: ${customerFeedback.join("\n")} Provide recommendations for: 1. Onboarding flow optimization 2. Milestone and checkpoint improvements 3. Self-service vs assisted touch points 4. Success criteria and measurement 5. Automation opportunities 6. Resource requirements`; return await this.neurolink.generate({ input: { text: prompt }, provider: "openai", temperature: 0.5, maxTokens: 1200, }); } } // Usage const csIntel = new CustomerSuccessIntelligence(); // Analyze churn risk across customer base const churnAnalysis = await csIntel.analyzeChurnRisk( [ { id: "cust1", tier: "enterprise", tenure: 24, health: "yellow" }, { id: "cust2", tier: "mid-market", tenure: 6, health: "red" }, ], [ { customer: "cust1", logins: 45, features: 8, support_tickets: 2 }, { customer: "cust2", logins: 12, features: 3, support_tickets: 8 }, ], ); // Generate expansion opportunities const expansionStrategy = await csIntel.generateExpansionStrategy( { companySize: 1500, currentARR: 120000, products: ["Core Platform"], industry: "Financial Services", }, [ { name: "Advanced Analytics", price: 50000, fit: "high" }, { name: "Compliance Module", price: 30000, fit: "high" }, { name: "API Access", price: 20000, fit: "medium" }, ], ); ``` ## Performance Management ### Executive KPI Dashboard ```bash #!/bin/bash # Automated executive dashboard generation # Generate weekly executive summary npx @juspay/neurolink gen " Create executive dashboard summary for SaaS company: Key Metrics (Week over Week): - MRR: $850K (+3.2%) - New customers: 45 (+12%) - Churn rate: 2.1% (-0.3%) - CAC: $420 (-8%) - NPS: 67 (+2 points) - Team productivity: 87% (+5%) Generate executive summary including: 1. Key performance highlights 2. Concerning trends requiring attention 3. Strategic recommendations 4. Resource allocation suggestions 5. Risk mitigation priorities Format for C-level consumption. " --provider anthropic \ --enable-analytics \ --context '{"audience":"executives","format":"dashboard_summary"}' \ > executive-summary-$(date +%Y%m%d).md # Department performance analysis npx @juspay/neurolink gen " Analyze cross-departmental performance alignment: Sales: 108% of target, strong pipeline health Marketing: 95% lead target, improved conversion rates Engineering: 92% sprint completion, technical debt concerns Customer Success: 98% retention target, expansion opportunities Finance: On budget, cash flow positive Identify: - Inter-departmental dependencies and bottlenecks - Resource reallocation opportunities - Performance improvement initiatives - Cross-functional collaboration needs " --enable-evaluation \ --evaluation-domain "Chief Operating Officer" \ > departmental-performance-$(date +%Y%m%d).md echo "✅ Executive dashboards generated" ``` ## Compliance & Risk Management ### Regulatory Compliance ```typescript class ComplianceAssistant { private neurolink: NeuroLink; constructor() { this.neurolink = new NeuroLink(); } async assessComplianceGap( currentPolicies: any[], regulations: string[], industry: string, ) { const prompt = `Conduct compliance gap analysis for ${industry} industry: Current policies: ${JSON.stringify(currentPolicies, null, 2)} Applicable regulations: ${regulations.join(", ")} Identify: 1. Compliance gaps and deficiencies 2. Risk levels and potential penalties 3. Required policy updates and new procedures 4. Implementation timeline and priorities 5. Training and awareness requirements 6. Ongoing monitoring and audit needs`; return await this.neurolink.generate({ input: { text: prompt }, provider: "anthropic", temperature: 0.3, context: { domain: "compliance", industry: industry, urgency: "high", }, }); } async generateRiskRegister( businessActivities: any[], riskCategories: string[], ) { const prompt = `Create comprehensive risk register: Business activities: ${JSON.stringify(businessActivities, null, 2)} Risk categories: ${riskCategories.join(", ")} For each identified risk provide: 1. Risk description and impact assessment 2. Probability and severity ratings 3. Current controls and mitigation measures 4. Residual risk assessment 5. Additional controls needed 6. Risk ownership and monitoring requirements`; return await this.neurolink.generate({ input: { text: prompt }, provider: "google-ai", temperature: 0.4, maxTokens: 1800, }); } } // Usage const compliance = new ComplianceAssistant(); // Assess GDPR compliance const gdprGap = await compliance.assessComplianceGap( [ { name: "Data Processing Policy", lastUpdated: "2023-01-15" }, { name: "Privacy Notice", lastUpdated: "2023-06-01" }, { name: "Incident Response", lastUpdated: "2022-11-30" }, ], ["GDPR", "CCPA", "SOX"], "Financial Technology", ); // Generate operational risk register const riskRegister = await compliance.generateRiskRegister( [ { activity: "Customer data processing", volume: "high", sensitivity: "high", }, { activity: "Third-party integrations", count: 15, criticality: "medium" }, { activity: "Cloud infrastructure", dependency: "high", redundancy: "partial", }, ], ["Operational", "Cyber Security", "Regulatory", "Financial", "Reputational"], ); ``` These business applications demonstrate how NeuroLink can drive value across all organizational functions, from strategic decision-making to operational optimization, providing measurable ROI and competitive advantages. ## Related Documentation - [Use Cases](/docs/use-cases) - Industry-specific applications - [Advanced Examples](/docs/advanced) - Complex integration patterns - [Analytics Features](/docs/reference/analytics) - Business intelligence capabilities - [Enterprise Setup](/docs/getting-started/provider-setup) - Enterprise configuration --- ## Tool Blocking Feature Example # Tool Blocking Feature Example This example demonstrates how to use the `blockedTools` feature to prevent specific tools from being executed on external MCP servers. ## Example Configuration Create or update your `.mcp-config.json` file: ```json { "mcpServers": { "filesystem": { "name": "filesystem", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."], "transport": "stdio", "blockedTools": ["move_file", "delete_file", "remove_directory"] }, "github": { "name": "github", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "transport": "stdio", "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "your_token_here" }, "blockedTools": ["delete_repository", "transfer_repository"] }, "bitbucket": { "name": "bitbucket", "command": "npx", "args": ["-y", "@nexus2520/bitbucket-mcp-server"], "transport": "stdio", "env": { "BITBUCKET_USERNAME": "your-bitbucket-username", "BITBUCKET_APP_PASSWORD": "your-app-password" }, "blockedTools": ["delete_repository", "delete_branch"] } } } ``` ## Testing the Feature ### 1. Load the Configuration ```typescript // The .mcp-config.json in the working directory is loaded automatically // the first time MCP is used (getMCPStatus(), generate(), stream(), ...) const neurolink = new NeuroLink(); ``` ### 2. List Available Tools ```typescript // Get MCP status to see loaded servers const status = await neurolink.getMCPStatus(); console.log(`Loaded ${status.totalServers} servers`); // List all available tools (blocked tools won't appear here) const tools = await neurolink.getAllAvailableTools(); console.log( "Available tools:", tools.map((t) => t.name), ); ``` ### 3. Attempt to Execute a Blocked Tool ```typescript try { // This will fail because 'delete_file' is blocked await neurolink.executeExternalMCPTool("filesystem", "delete_file", { path: "/some/file.txt", }); } catch (error) { console.error("Expected error:", error.message); // Output: "Tool 'delete_file' is blocked on server 'filesystem' by configuration" } ``` ### 4. Execute an Allowed Tool ```typescript // This will succeed because 'read_file' is not blocked const content = await neurolink.executeExternalMCPTool( "filesystem", "read_file", { path: "/some/file.txt", }, ); console.log("File content:", content); ``` ## Use Cases ### 1. Production Safety Block destructive operations in production: ```json { "mcpServers": { "filesystem-prod": { "blockedTools": [ "delete_file", "remove_directory", "move_file", "write_file" ] } } } ``` ### 2. Read-Only GitHub Access Allow read operations but block writes: ```json { "mcpServers": { "github-readonly": { "blockedTools": [ "create_repository", "delete_repository", "create_issue", "close_issue", "create_pull_request", "merge_pull_request" ] } } } ``` ### 3. Compliance and Audit Block sensitive operations that require audit trails: ```json { "mcpServers": { "database": { "blockedTools": [ "drop_table", "truncate_table", "delete_all_records", "update_schema" ] } } } ``` ## Verification Run tests to verify the feature works correctly: ```bash # Run the blocklist tests pnpm test test/unit/mcp/externalServerBlocklist.test.ts # Or run all tests pnpm test ``` ## Notes - Blocked tools are filtered during discovery, so they won't appear in the list of available tools - Attempts to execute blocked tools will throw an error with a clear message - The blockedTools array can be empty or omitted if no tools need to be blocked - Tool names are case-sensitive and must match exactly --- ## Use Cases This page has moved to [Real-World Use Cases](/docs/guides/examples/use-cases). --- # Cookbook ## NeuroLink Cookbook # NeuroLink Cookbook Welcome to the NeuroLink Cookbook! This collection of recipes provides practical, copy-paste ready solutions for common use cases and challenges when building with NeuroLink. ## What's in the Cookbook? Each recipe follows a consistent structure: - **Problem**: What challenge does this solve? - **Solution**: High-level approach - **Code**: Complete, working TypeScript example - **Explanation**: Step-by-step breakdown - **Variations**: Alternative approaches - **See Also**: Related recipes and documentation ## Recipe Categories ### Getting Started - [**Basic Streaming**](/docs/cookbook/basic-streaming) - Stream AI responses in real time with the `result.stream` pattern - [**Multimodal Images**](/docs/cookbook/multimodal-images) - Send images to vision models for analysis, OCR, and comparison - [**Provider Switching**](/docs/cookbook/provider-switching) - Switch providers at runtime, compare outputs, and implement fallback - [**Embeddings Basics**](/docs/cookbook/embeddings-basics) - Generate embeddings, compare similarity, and build semantic search ### Reliability & Error Handling - [**Streaming with Retry Logic**](/docs/cookbook/streaming-with-retry) - Handle network interruptions and implement automatic retry for streaming responses - [**Error Recovery Patterns**](/docs/cookbook/error-recovery) - Graceful degradation and error handling strategies - [**Multi-Provider Fallback**](/docs/cookbook/multi-provider-fallback) - Automatically switch providers when one fails ### Performance & Optimization - [**Cost Optimization**](/docs/cookbook/cost-optimization) - Minimize token usage and API costs - [**Rate Limit Handling**](/docs/cookbook/rate-limit-handling) - Manage rate limits across providers - [**Batch Processing**](/docs/cookbook/batch-processing) - Efficiently process multiple requests ### Context Management - [**Context Window Management**](/docs/cookbook/context-window-management) - Handle large conversations within token limits - [**Conversation Summarization**](/docs/cookbook/conversation-summarization) - Automatically summarize long conversations ### Advanced Features - [**Structured Output with JSON Schema**](/docs/cookbook/structured-output) - Extract structured data with type safety - [**Tool Chaining**](/docs/cookbook/tool-chaining) - Chain multiple MCP tool calls together - [**AutoResearch Quickstart**](/docs/cookbook/autoresearch-quickstart) - Set up an autonomous AI experiment loop in under 5 minutes ## How to Use These Recipes 1. **Find your use case**: Browse the categories above 2. **Copy the code**: All examples are production-ready 3. **Customize**: Adapt the code to your specific needs 4. **Test**: Verify the solution works in your environment ## Prerequisites Most recipes assume you have: - NeuroLink installed: `npm install @juspay/neurolink` - At least one provider configured (API keys in `.env`) - Basic TypeScript/JavaScript knowledge ## Contributing Found a common pattern not covered here? [Contribute a recipe](/docs/community/contributing)! ## See Also - [Getting Started Guide](/docs/getting-started/installation) - [API Reference](/docs/sdk/api-reference) - [Troubleshooting Guide](/docs/reference/troubleshooting) --- ## AutoResearch Quickstart # AutoResearch Quickstart ## Problem You have a training script and a metric you want to optimize (e.g., validation loss), and you want an AI agent to autonomously iterate on the code — proposing changes, running experiments, keeping improvements, and reverting failures — without manual intervention. ## Solution Use NeuroLink's AutoResearch engine. Initialize a config pointing at your repo, define the metric to optimize, and run experiment cycles. Each cycle: the AI reads your code, proposes a change, commits it to a branch, runs the experiment, parses the metric, and keeps or reverts the change. ## Code ### CLI — Single Experiment Cycle ```bash # 1. Initialize AutoResearch in your repo neurolink autoresearch init /path/to/repo \ --tag "run1" \ --target "train.py" \ --immutable "program.md" \ --run-command "python3 train.py" \ --metric-name val_bpb \ --metric-pattern "^val_bpb:\\s+([\\d.]+)" \ --metric-direction lower \ --timeout 120 # 2. Run one cycle (propose → execute → evaluate → keep/revert) neurolink autoresearch run-once /path/to/repo # 3. Check results neurolink autoresearch status /path/to/repo neurolink autoresearch results /path/to/repo ``` ### SDK — Single Experiment Cycle ```typescript async function runOneExperiment() { const neurolink = new NeuroLink({ provider: "google-vertex", model: "gemini-2.5-flash", }); const worker = new ResearchWorker({ repoPath: "/path/to/repo", mutablePaths: ["train.py"], immutablePaths: ["program.md"], runCommand: "python3 train.py", metric: { name: "val_bpb", pattern: "^val_bpb:\\s+([\\d.]+)", direction: "lower", }, timeoutMs: 120_000, }); // Attach the emitter and listeners before initialize(), which emits // autoresearch:initialized itself (resume() emits autoresearch:resumed) const emitter = neurolink.getEventEmitter(); worker.setEmitter(emitter); emitter.on("autoresearch:experiment-started", (e) => { console.log(`Experiment ${e.runCount} starting`); }); emitter.on("autoresearch:experiment-completed", (e) => { console.log(`Experiment ${e.runCount}: ${e.status}, metric=${e.metric}`); }); await worker.initialize("run1"); // Run one cycle const result = await worker.runExperimentCycle( "Reduce validation loss by improving the learning rate schedule", ); console.log("Status:", result.status); console.log("Metric:", result.metric); console.log("Commit:", result.commit); } runOneExperiment(); ``` ### SDK — Scheduled via TaskManager ```typescript async function scheduleResearch() { const neurolink = new NeuroLink({ provider: "google-vertex", model: "gemini-2.5-flash", }); // Create a scheduled autoresearch task const task = await neurolink.tasks.create({ name: "research-lr-schedule", prompt: "Run autoresearch experiment cycle", type: "autoresearch", schedule: { type: "interval", every: 5 * 60 * 1000 }, // Every 5 minutes autoresearch: { repoPath: "/path/to/repo", mutablePaths: ["train.py"], runCommand: "python3 train.py", metric: { name: "val_bpb", pattern: "^val_bpb:\\s+([\\d.]+)", direction: "lower", }, }, }); // Pause, resume or delete it later await neurolink.tasks.pause(task.id); await neurolink.tasks.resume(task.id); } scheduleResearch(); ``` > **Note:** `neurolink.tasks.create()` registers the task with the configured TaskManager backend, and the schedule runs there. With the default in-process backend the timers live only as long as your process, so keep it running. From the CLI, `neurolink autoresearch start` only saves the task and `neurolink task start` runs the worker. ## Explanation ### 1. Initialization `autoresearch init` (CLI) or `new ResearchWorker(config)` (SDK) sets up the config: - **`mutablePaths`** — Files the AI is allowed to edit (your training script) - **`immutablePaths`** — Files the AI can read but not modify (research program, dataset configs) - **`runCommand`** — Shell command to execute the experiment - **`metric`** — Name, regex pattern to extract the value from stdout, and optimization direction (`lower` or `higher`) - **`timeoutMs`** — Max wall-clock time per experiment run The CLI writes this to `.autoresearch/config.json` and creates a dedicated git branch. ### 2. Experiment Cycle Each `runExperimentCycle()` call goes through 9 phases: 1. **bootstrap** — Read the research program and understand the codebase 2. **analyze** — Study current results and identify improvement opportunities 3. **plan** — Propose a specific code change 4. **implement** — Apply the change to mutable files 5. **validate** — Verify the code is syntactically valid 6. **commit** — Git-commit the candidate change 7. **execute** — Run the experiment command 8. **evaluate** — Parse the metric from stdout using the regex pattern 9. **decide** — Keep the commit if the metric improved, revert otherwise ### 3. Artifacts After running, check `.autoresearch/` in your repo: | File | Contents | | ------------- | ------------------------------------------------------------------------------ | | `config.json` | Persisted configuration | | `state.json` | Current best metric, cycle count, phase, branch name | | `results.tsv` | Tab-separated log: `commit`, metric name, `memory_gb`, `status`, `description` | | `runs.jsonl` | Full JSON audit log — one JSON object per completed cycle | ### 4. Events The SDK emits 10 typed events via `neurolink.getEventEmitter()`. A `ResearchWorker` created directly emits them once you pass it that emitter with `worker.setEmitter()`; tasks created through `neurolink.tasks` are wired for you: | Event | Fired when | | ----------------------------------- | ----------------------------------------------- | | `autoresearch:initialized` | A research session is created | | `autoresearch:resumed` | An existing research session is resumed | | `autoresearch:phase-changed` | The worker moves to a new phase | | `autoresearch:experiment-started` | An experiment cycle begins | | `autoresearch:experiment-completed` | An experiment cycle completes (success or fail) | | `autoresearch:metric-improved` | The best metric value improves | | `autoresearch:revert` | A candidate commit is reverted | | `autoresearch:revert-failed` | Reverting a candidate commit fails | | `autoresearch:state-updated` | The persisted state is updated | | `autoresearch:error` | An error occurs | ## Variations ### Use a Different Provider Replace the provider/model in the config. AutoResearch works with any NeuroLink-supported provider: ```typescript const worker = new ResearchWorker({ // ... same config ... provider: "anthropic", model: "claude-sonnet-4-20250514", }); ``` Or via CLI: ```bash neurolink autoresearch init /path/to/repo \ --provider anthropic --model claude-sonnet-4-20250514 \ # ... other flags ... ``` ### Optimize a Higher-is-Better Metric Set `direction: "higher"` for metrics like accuracy: ```typescript metric: { name: "accuracy", pattern: "^accuracy:\\s+([\\d.]+)", direction: "higher", } ``` ### Reset and Start Over ```bash # Deletes entire .autoresearch/ directory (config, state, results) neurolink autoresearch reset /path/to/repo ``` ### Pause and Resume (TaskManager) ```bash neurolink autoresearch pause /path/to/repo # ... later ... neurolink autoresearch resume /path/to/repo ``` > **Note:** `pause`, `resume`, and `stop` update the stored task status but do not interact with the TaskManager runtime directly. The task worker checks status before each cycle. ## See Also - [AutoResearch Feature Guide](/docs/features/autoresearch) — Full reference with phase diagrams, configuration, and architecture - [Tool Chaining](/docs/cookbook/tool-chaining) — AutoResearch uses phase-gated tool chaining internally - [Structured Output with JSON Schema](/docs/cookbook/structured-output) — Extract structured data from experiment outputs - [API Reference](/docs/sdk/api-reference) --- ## Basic Streaming # Basic Streaming ## Problem Waiting for a complete AI response before displaying anything creates a sluggish user experience. Users see nothing for seconds, then the entire response appears at once. For long responses, this delay is especially painful. ## Solution Use `neurolink.stream()` to receive the response in real time, chunk by chunk. The result contains a `.stream` async iterable that yields content objects as they arrive from the provider. ## Code ```typescript async function basicStream() { const neurolink = new NeuroLink(); // Start a streaming request const result = await neurolink.stream({ input: { text: "Explain how neural networks learn, step by step." }, provider: "openai", model: "gpt-4", }); // Consume the stream chunk by chunk for await (const chunk of result.stream) { if ("content" in chunk && chunk.content) { process.stdout.write(chunk.content); } } console.log("\n"); // After the stream completes, metadata is available console.log("Provider:", result.provider); console.log("Model:", result.model); if (result.usage) { console.log("Prompt tokens:", result.usage.promptTokens); console.log("Completion tokens:", result.usage.completionTokens); } } basicStream(); ``` ## Explanation ### 1. Calling `neurolink.stream()` The `stream()` method accepts the same `input` object as `generate()`. The key difference is the return type: instead of a single `content` string, you get a `StreamResult` with a `.stream` async iterable. ```typescript const result = await neurolink.stream({ input: { text: "Your prompt here" }, provider: "openai", }); ``` ### 2. Consuming the Stream The `.stream` property is an `AsyncIterable` that yields objects with a `content` field. Use a `for await...of` loop to process each chunk as it arrives: ```typescript for await (const chunk of result.stream) { if ("content" in chunk && chunk.content) { process.stdout.write(chunk.content); } } ``` The `"content" in chunk` guard handles the discriminated union -- stream chunks can be text, audio, or image types depending on your configuration. ### 3. Accessing Metadata After Completion Token usage, provider name, model name, and finish reason are available on the `result` object. Some fields (like `usage`) resolve after the stream finishes. ### 4. Stream Options `stream()` accepts the same core options as `generate()`: | Option | Description | | -------------- | ------------------------------------- | | `provider` | AI provider name (e.g., `"openai"`) | | `model` | Specific model (e.g., `"gpt-4"`) | | `temperature` | Response randomness (0.0 - 1.0) | | `maxTokens` | Maximum tokens in the response | | `systemPrompt` | System-level instructions | | `timeout` | Request timeout (number or string) | | `abortSignal` | External cancellation via AbortSignal | ## Variations ### Accumulate the Full Response Collect all chunks into a single string while still displaying them in real time: ```typescript async function streamAndCollect(neurolink: NeuroLink, prompt: string) { const result = await neurolink.stream({ input: { text: prompt }, provider: "anthropic", model: "claude-sonnet-4-20250514", }); let fullResponse = ""; for await (const chunk of result.stream) { if ("content" in chunk && chunk.content) { fullResponse += chunk.content; process.stdout.write(chunk.content); } } console.log("\n\nTotal length:", fullResponse.length, "characters"); return fullResponse; } ``` ### Stream with a System Prompt Set instructions that guide the model's behavior: ```typescript const result = await neurolink.stream({ input: { text: "What are the benefits of TypeScript?" }, provider: "openai", model: "gpt-4", systemPrompt: "You are a senior software engineer. Be concise and use bullet points.", temperature: 0.3, maxTokens: 500, }); for await (const chunk of result.stream) { if ("content" in chunk && chunk.content) { process.stdout.write(chunk.content); } } ``` ### Cancel a Stream with AbortSignal Stop a long-running stream programmatically: ```typescript const controller = new AbortController(); // Cancel after 5 seconds setTimeout(() => controller.abort(), 5000); try { const result = await neurolink.stream({ input: { text: "Write a very long essay about the history of computing." }, provider: "openai", abortSignal: controller.signal, }); for await (const chunk of result.stream) { if ("content" in chunk && chunk.content) { process.stdout.write(chunk.content); } } } catch (error: any) { if (error.name === "AbortError") { console.log("\nStream cancelled by user."); } else { throw error; } } ``` ### Stream to a Web Response (Server-Side) Pipe the stream to an HTTP response for real-time delivery to a browser: ```typescript async function handleStreamRequest(req: Request): Promise { const neurolink = new NeuroLink(); const result = await neurolink.stream({ input: { text: "Explain distributed systems" }, provider: "openai", }); const encoder = new TextEncoder(); const readable = new ReadableStream({ async start(controller) { for await (const chunk of result.stream) { if ("content" in chunk && chunk.content) { controller.enqueue(encoder.encode(chunk.content)); } } controller.close(); }, }); return new Response(readable, { headers: { "Content-Type": "text/plain; charset=utf-8" }, }); } ``` ## See Also - [Streaming with Retry Logic](/docs/cookbook/streaming-with-retry) - [Error Recovery Patterns](/docs/cookbook/error-recovery) - [Multi-Provider Fallback](/docs/cookbook/multi-provider-fallback) - [API Reference](/docs/sdk/api-reference) --- ## Batch Processing # Batch Processing ## Problem Processing many requests sequentially is slow and inefficient: - High latency (wait for each request) - Underutilized rate limits - Poor resource usage - Slow time-to-completion Applications often need to process: - Multiple documents - Large datasets - User-generated content - Batch analytics ## Solution Implement efficient batch processing with: 1. Concurrent request handling 2. Rate limit awareness 3. Progress tracking 4. Error recovery 5. Result aggregation ## Code ```typescript type BatchConfig = { concurrency?: number; // Max parallel requests rateLimit?: number; // Max requests per second onProgress?: (completed: number, total: number) => void; onError?: (error: Error, item: any, index: number) => void; retryFailures?: boolean; }; type BatchResult = { results: R[]; errors: Array; duration: number; successRate: number; }; class BatchProcessor { private neurolink: NeuroLink; constructor() { this.neurolink = new NeuroLink(); } /** * Process items in batches with concurrency control */ async processBatch( items: T[], processFn: (item: T, index: number) => Promise, config: BatchConfig = {}, ): Promise> { const { concurrency = 5, rateLimit = 10, // requests per second onProgress, onError, retryFailures = true, } = config; const startTime = Date.now(); const results: R[] = new Array(items.length); const errors: Array = []; let completed = 0; let inFlight = 0; let currentIndex = 0; const minDelay = 1000 / rateLimit; // ms between requests return new Promise((resolve) => { const processNext = async () => { if (currentIndex >= items.length && inFlight === 0) { // All done const duration = Date.now() - startTime; const successRate = (results.filter((r) => r !== undefined).length / items.length) * 100; resolve({ results, errors, duration, successRate, }); return; } if (inFlight >= concurrency || currentIndex >= items.length) { return; } const index = currentIndex++; const item = items[index]; inFlight++; try { const result = await processFn(item, index); results[index] = result; completed++; onProgress?.(completed, items.length); } catch (error: any) { errors.push({ item, error, index }); onError?.(error, item, index); if (retryFailures) { // Add to end of queue for retry items.push(item); } } finally { inFlight--; // Rate limiting await new Promise((r) => setTimeout(r, minDelay)); processNext(); } processNext(); }; // Start concurrent workers for (let i = 0; i > { return this.processBatch( texts, async (text, index) => { const result = await this.neurolink.generate({ input: { text: `${prompt}\n\n${text}` }, provider: config.provider || "anthropic", model: "claude-3-haiku-20240307", // Fast, cheap model }); return result.content; }, config, ); } /** * Process with structured output */ async processStructured( items: string[], prompt: string, schema: any, config: BatchConfig = {}, ): Promise> { return this.processBatch( items, async (item) => { const result = await this.neurolink.generate({ input: { text: `${prompt}\n\n${item}` }, provider: "openai", structuredOutput: { type: "json", schema }, }); return JSON.parse(result.content) as T; }, config, ); } /** * Process files in parallel */ async processFiles( filePaths: string[], processFn: (content: string, path: string) => Promise, config: BatchConfig = {}, ) { const fs = await import("fs/promises"); return this.processBatch( filePaths, async (path, index) => { const content = await fs.readFile(path, "utf-8"); return processFn(content, path); }, config, ); } } // Usage Example 1: Sentiment Analysis async function example1_SentimentAnalysis() { const processor = new BatchProcessor(); const reviews = [ "This product is amazing! Highly recommend.", "Terrible quality, waste of money.", "It's okay, nothing special.", "Best purchase I've made this year!", "Disappointed, expected much better.", ]; console.log("=== Sentiment Analysis ==="); const result = await processor.processTexts( reviews, "Classify the sentiment of this review as positive, negative, or neutral. Return only the sentiment.", { concurrency: 3, rateLimit: 5, onProgress: (completed, total) => { console.log( `Progress: ${completed}/${total} (${((completed / total) * 100).toFixed(0)}%)`, ); }, }, ); console.log("\n✅ Results:"); result.results.forEach((sentiment, i) => { console.log(` ${i + 1}. ${reviews[i].slice(0, 30)}... → ${sentiment}`); }); console.log(`\n Stats:`); console.log(` Duration: ${result.duration}ms`); console.log(` Success rate: ${result.successRate.toFixed(1)}%`); console.log(` Errors: ${result.errors.length}`); } // Example 2: Data Extraction type ProductInfo = { name: string; price: number; category: string; }; const productSchema = { type: "object", properties: { name: { type: "string" }, price: { type: "number" }, category: { type: "string" }, }, required: ["name", "price", "category"], }; async function example2_DataExtraction() { const processor = new BatchProcessor(); const descriptions = [ "The UltraBook Pro laptop costs $1299 and is perfect for professionals.", "Get the SmartWatch X for only $299 - the best fitness tracker available.", "Premium wireless headphones, $199, audiophile quality sound.", ]; console.log("\n=== Data Extraction ==="); const result = await processor.processStructured( descriptions, "Extract product information:", productSchema, { concurrency: 2, rateLimit: 3, }, ); console.log("\n✅ Extracted Products:"); result.results.forEach((product, i) => { console.log( ` ${i + 1}. ${product.name} - $${product.price} (${product.category})`, ); }); } // Example 3: Document Summarization async function example3_DocumentSummarization() { const processor = new BatchProcessor(); const documents = [ "Long document about artificial intelligence and machine learning...", "Article discussing climate change impacts on global economy...", "Research paper on quantum computing applications in cryptography...", ]; console.log("\n=== Document Summarization ==="); let startTime = Date.now(); const result = await processor.processTexts( documents, "Summarize this in 1-2 sentences:", { concurrency: 3, rateLimit: 10, onProgress: (completed, total) => { const elapsed = ((Date.now() - startTime) / 1000).toFixed(1); console.log(`Progress: ${completed}/${total} (${elapsed}s)`); }, onError: (error, item, index) => { console.error(`❌ Error processing item ${index}:`, error.message); }, }, ); console.log("\n✅ Summaries:"); result.results.forEach((summary, i) => { console.log(` ${i + 1}. ${summary}`); }); } // Main async function main() { await example1_SentimentAnalysis(); await example2_DataExtraction(); await example3_DocumentSummarization(); } main(); ``` ## Explanation ### 1. Concurrency Control Process multiple requests simultaneously: ```typescript concurrency: 5; // 5 requests in parallel ``` Benefits: - 5x faster than sequential - Efficient resource usage - Respects provider limits ### 2. Rate Limiting Prevent exceeding provider rate limits: ```typescript rateLimit: 10 // 10 requests per second minDelay = 1000 / 10 = 100ms between requests ``` ### 3. Progress Tracking Monitor batch processing in real-time: ```typescript onProgress: (completed, total) => { console.log(`${completed}/${total} (${percentage}%)`); }; ``` ### 4. Error Handling Individual failures don't stop the batch: ```typescript onError: (error, item, index) => { // Log, retry, or skip }; ``` ### 5. Retry Logic Automatically retry failed items: ```typescript retryFailures: true; // Add to queue end ``` ## Variations ### Chunked Batch Processing Process very large datasets in chunks: ```typescript async function processInChunks( items: T[], chunkSize: number, processFn: (items: T[]) => Promise, ): Promise { const results: R[] = []; for (let i = 0; i setTimeout(r, 1000)); } return results; } // Usage const results = await processInChunks(allItems, 100, async (chunk) => processor.processBatch(chunk, processFn).then((r) => r.results), ); ``` ### Priority Queue Process high-priority items first: ```typescript type PriorityItem = { item: T; priority: number; }; async function processPriorityBatch( items: PriorityItem[], processFn: (item: T) => Promise, ) { // Sort by priority (higher first) const sorted = items.sort((a, b) => b.priority - a.priority); return processor.processBatch( sorted.map((p) => p.item), processFn, ); } ``` ### Result Streaming Stream results as they complete: ```typescript async function* processBatchStreaming( items: T[], processFn: (item: T) => Promise, ): AsyncIterable { const promises = items.map((item, index) => processFn(item).then((result) => ({ index, result })), ); for (const promise of promises) { yield await promise; } } // Usage for await (const { index, result } of processBatchStreaming(items, processFn)) { console.log(`Completed item ${index}:`, result); } ``` ### Cost Tracking Track costs per batch: ```typescript class CostTrackingProcessor extends BatchProcessor { private totalCost = 0; async processBatch( items: T[], processFn: Function, config: BatchConfig, ) { const startCost = this.totalCost; const result = await super.processBatch( items, async (item, index) => { const result = await processFn(item, index); // Estimate cost (rough) const cost = 0.001; // $0.001 per request this.totalCost += cost; return result; }, config, ); const batchCost = this.totalCost - startCost; console.log(` Batch cost: $${batchCost.toFixed(4)}`); return result; } } ``` ## Performance Comparison | Approach | 100 Items | 1000 Items | Notes | | ------------------- | --------- | ---------- | ------------------- | | **Sequential** | 200s | 2000s | Baseline | | **Concurrency: 5** | 40s | 400s | 5x faster | | **Concurrency: 10** | 20s | 200s | 10x faster | | **Concurrency: 20** | 15s | 150s | May hit rate limits | ## Best Practices 1. **Start conservative**: Begin with low concurrency (3-5) 2. **Monitor rate limits**: Track 429 errors 3. **Implement retries**: Handle transient failures 4. **Track progress**: Show completion status 5. **Use cheap models**: Batch processing doesn't need GPT-4 6. **Cache results**: Save completed work 7. **Handle partial failures**: Don't block on errors ## See Also - [Rate Limit Handling](/docs/cookbook/rate-limit-handling) - [Cost Optimization](/docs/cookbook/cost-optimization) - [Error Recovery](/docs/cookbook/error-recovery) - [Structured Output](/docs/cookbook/structured-output) --- ## Context Window Management # Context Window Management ## Problem AI models have limited context windows (token limits): - GPT-4o: 128K tokens (~96K words) - Claude 4 Sonnet: 200K tokens (~150K words) - Gemini 2.5 Flash: 1M tokens (~750K words) - GPT-4.1: 1M tokens (~750K words) Long conversations exceed these limits, causing: - Truncated context - Lost conversation history - Inconsistent responses - API errors ## Solution Implement intelligent context management: 1. Track token usage 2. Sliding window approach 3. Automatic summarization 4. Strategic message pruning 5. Context compression ## Code ```typescript type Message = { role: "system" | "user" | "assistant"; content: string; tokens?: number; }; class ContextWindowManager { private neurolink: NeuroLink; private messages: Message[] = []; private maxTokens: number; private systemMessage?: Message; constructor(maxTokens: number = 8000) { this.neurolink = new NeuroLink(); this.maxTokens = maxTokens; } /** * Estimate tokens in text (rough approximation) */ private estimateTokens(text: string): number { // Rough estimate: 4 characters per token return Math.ceil(text.length / 4); } /** * Calculate total tokens in message array */ private calculateTotalTokens(messages: Message[]): number { return messages.reduce( (sum, msg) => sum + (msg.tokens || this.estimateTokens(msg.content)), 0, ); } /** * Set system message (always preserved) */ setSystemMessage(content: string) { this.systemMessage = { role: "system", content, tokens: this.estimateTokens(content), }; } /** * Add message with automatic pruning */ addMessage(role: "user" | "assistant", content: string) { const message: Message = { role, content, tokens: this.estimateTokens(content), }; this.messages.push(message); this.pruneIfNeeded(); } /** * Prune old messages when approaching limit */ private pruneIfNeeded() { const allMessages = this.systemMessage ? [this.systemMessage, ...this.messages] : this.messages; const totalTokens = this.calculateTotalTokens(allMessages); if (totalTokens = 0; i--) { const msg = this.messages[i]; const msgTokens = msg.tokens || this.estimateTokens(msg.content); if (currentTokens + msgTokens `${m.role}: ${m.content}`) .join("\n\n"); console.log(" Summarizing old messages..."); const summary = await this.neurolink.generate({ input: { text: `Summarize this conversation concisely, preserving key information:\n\n${conversationText}`, }, provider: "anthropic", model: "claude-3-5-haiku-20241022", // Fast, cheap model for summaries maxTokens: 500, }); // Replace old messages with summary this.messages = [ { role: "assistant", content: `[Previous conversation summary: ${summary.content}]`, tokens: this.estimateTokens(summary.content), }, ...toKeep, ]; console.log(`✅ Summarized ${toSummarize.length} messages`); } /** * Generate with managed context */ async chat(userMessage: string) { this.addMessage("user", userMessage); const contextMessages = this.systemMessage ? [this.systemMessage, ...this.messages] : this.messages; // Convert to NeuroLink format const prompt = contextMessages .map((m) => `${m.role}: ${m.content}`) .join("\n\n"); const result = await this.neurolink.generate({ input: { text: prompt }, }); this.addMessage("assistant", result.content); return result.content; } /** * Get current context statistics */ getStats() { const totalTokens = this.calculateTotalTokens(this.messages); return { messages: this.messages.length, tokens: totalTokens, capacity: this.maxTokens, usage: ((totalTokens / this.maxTokens) * 100).toFixed(1) + "%", }; } /** * Clear all messages (keep system message) */ clear() { this.messages = []; } } // Usage Example async function main() { const manager = new ContextWindowManager(4000); // 4K token limit manager.setSystemMessage( "You are a helpful AI assistant. Be concise and accurate.", ); // Simulate a long conversation console.log("Starting conversation...\n"); for (let i = 1; i 3000) { await manager.summarizeOldMessages(); } } console.log("\n✅ Conversation complete"); console.log("Final stats:", manager.getStats()); } main(); ``` ## Explanation ### 1. Token Estimation Estimate tokens before sending to API: ```typescript estimateTokens(text) ≈ text.length / 4 ``` This is approximate but sufficient for context management. ### 2. Sliding Window Keep most recent messages, discard oldest: - **System message**: Always preserved - **Recent messages**: Keep in full - **Old messages**: Remove or summarize ### 3. Automatic Pruning When reaching 100% capacity: - Remove oldest messages - Target 80% capacity (leave buffer) - Preserve conversation coherence ### 4. Intelligent Summarization Instead of discarding, summarize old messages: ``` [10 messages] → [1 summary message] + [Recent messages] ``` Preserves context while reducing tokens. ### 5. Progressive Strategy ``` 0-70% capacity: No action 70-90% capacity: Summarize old messages 90-100% capacity: Remove oldest messages >100% capacity: Aggressive pruning ``` ## Variations ### Keep Important Messages Tag and preserve important messages: ```typescript type MessageWithMetadata = Message & { important?: boolean; timestamp: number; }; private pruneIfNeeded() { // Always keep important messages const important = this.messages.filter(m => m.important); const regular = this.messages.filter(m => !m.important); // Prune regular messages only const pruned = this.pruneMessages(regular); this.messages = [...important, ...pruned]; } ``` ### Semantic Compression Use embeddings to identify redundant messages: ```typescript async compressSemanticDuplicates() { // Group similar messages using embeddings const embeddings = await this.getEmbeddings(this.messages); // Find and merge similar messages const compressed = this.mergeSimiar(this.messages, embeddings); this.messages = compressed; } ``` ### Provider-Specific Limits Different models, different limits: ```typescript const CONTEXT_LIMITS = { "gpt-4o": 128000, "gpt-4o-mini": 128000, "gpt-4.1": 1047576, "o3": 200000, "claude-opus-4-20250514": 200000, "claude-sonnet-4-20250514": 200000, "claude-3-5-sonnet-20241022": 200000, "gemini-2.5-flash": 1048576, "gemini-2.5-pro": 1048576, }; constructor(model: string) { this.maxTokens = CONTEXT_LIMITS[model] || 128000; // Leave 20% buffer for response this.maxTokens = Math.floor(this.maxTokens * 0.8); } ``` ### Rolling Summary Maintain a rolling summary that updates: ```typescript class RollingSummaryManager extends ContextWindowManager { private summary = ""; async updateSummary() { const recentMessages = this.messages.slice(-5); const context = `${this.summary}\n\nRecent: ${recentMessages.map((m) => m.content).join("\n")}`; const newSummary = await this.neurolink.generate({ input: { text: `Update this summary with recent messages:\n${context}` }, maxTokens: 300, }); this.summary = newSummary.content; this.messages = recentMessages; // Keep only recent } } ``` ## Token Budgets by Use Case | Use Case | Recommended Limit | Reasoning | | ----------------- | ----------------- | ------------------------------- | | Chatbot | 4K-8K tokens | Quick responses, recent context | | Code assistant | 16K-32K tokens | Need file context | | Document analysis | 32K-100K tokens | Large documents | | Long-form writing | 8K-16K tokens | Story continuity | | Customer support | 4K tokens | Short interactions | ## Using Built-in Context Compaction The manual patterns shown above (token estimation, sliding windows, summarization) are now available as built-in components in NeuroLink. See [Context Compaction Guide](/docs/features/context-compaction) for full details. - **ContextCompactor** (`src/lib/context/contextCompactor.ts`) implements a 5-stage pipeline: relevance drop (Stage 0 — asks a decision model which earlier messages the current request still needs; skipped entirely without a decision provider), tool-output pruning, file-read deduplication, LLM summarization, and sliding-window truncation. It replaces the need to build custom `ContextWindowManager` classes. - **BudgetChecker** (`src/lib/context/budgetChecker.ts`) validates context size against per-model token limits before every generation call. Compaction is triggered automatically when usage exceeds the configured threshold. - **`getContextStats()`** provides live token counts, remaining capacity, and a `shouldCompact` flag -- a production-grade replacement for the manual `getStats()` helper shown in this cookbook. - **`compactSession()`** runs the full 5-stage pipeline on demand and returns a `CompactionResult` with the compacted messages and token savings. Provider-specific context window sizes are maintained in `src/lib/constants/contextWindows.ts`, removing the need for hard-coded `CONTEXT_LIMITS` maps. ### Configuration Enable context compaction through the `conversationMemory.contextCompaction` config when creating a NeuroLink instance: ```typescript const neurolink = new NeuroLink({ conversationMemory: { enabled: true, contextCompaction: { enabled: true, // Trigger compaction when context usage exceeds 80% (default: 0.80) threshold: 0.8, // Enable individual compaction stages (all default to true) enablePruning: true, // Replace old tool outputs with placeholders enableDeduplication: true, // Keep only the latest read of each file enableSlidingWindow: true, // Tag oldest messages for removal as last resort // Fine-tune limits maxToolOutputBytes: 50_000, // Max tool output size before pruning (default: 50KB) maxToolOutputLines: 2000, // Max tool output lines before pruning fileReadBudgetPercent: 0.6, // File reads share of remaining context (default: 60%) }, }, }); ``` ### Checking Context Usage Use `getContextStats()` to inspect how much of the context window a session is consuming. The method returns token estimates, a usage ratio, and a `shouldCompact` flag based on the configured threshold: ```typescript // Get context usage for a session against a specific provider/model const stats = await neurolink.getContextStats( "session-1", "vertex", "gemini-2.5-flash", ); if (stats) { console.log(`Messages: ${stats.messageCount}`); console.log(`Input tokens: ${stats.estimatedInputTokens}`); console.log(`Available: ${stats.availableInputTokens}`); console.log(`Context usage: ${(stats.usageRatio * 100).toFixed(1)}%`); console.log(`Needs compact: ${stats.shouldCompact}`); } ``` ### Manual Compaction When `shouldCompact` is `true`, or at any time you want to free up context space, call `compactSession()`: ```typescript const result = await neurolink.compactSession("session-1"); if (result?.compacted) { const tokensSaved = result.originalTokenCount - result.compactedTokenCount; console.log(`Compaction saved ${tokensSaved} tokens`); console.log(`Stages applied: ${result.stagesApplied.join(", ")}`); } ``` ### Full Example: Auto-Monitoring Loop Combining the APIs above into a conversation loop that monitors context usage and compacts automatically: ```typescript const neurolink = new NeuroLink({ conversationMemory: { enabled: true, contextCompaction: { enabled: true, threshold: 0.8, }, }, }); const sessionId = "demo-session"; async function chat(userMessage: string) { // Check context budget before generating const stats = await neurolink.getContextStats( sessionId, "anthropic", "claude-sonnet-4-20250514", ); if (stats?.shouldCompact) { console.log( `Context at ${(stats.usageRatio * 100).toFixed(1)}% — compacting...`, ); const result = await neurolink.compactSession(sessionId); if (result?.compacted) { const saved = result.originalTokenCount - result.compactedTokenCount; console.log( `Freed ${saved} tokens via ${result.stagesApplied.join(", ")}`, ); } } const response = await neurolink.generate({ input: { text: userMessage }, provider: "anthropic", model: "claude-sonnet-4-20250514", sessionId, }); return response.content; } // Simulate a long conversation for (let i = 1; i <= 50; i++) { const reply = await chat(`Tell me fact #${i} about distributed systems.`); console.log(`[${i}] ${reply.slice(0, 120)}...`); } ``` ## See Also - [Conversation Summarization](/docs/cookbook/conversation-summarization) - [Cost Optimization](/docs/cookbook/cost-optimization) - [Memory Management Guide](/docs/features/conversation-history) - [Provider Comparison](/docs/reference/provider-comparison) --- ## Conversation Summarization # Conversation Summarization ## Problem Long conversations consume excessive tokens and costs: - Context window fills quickly - API costs scale with message count - Response quality degrades with very long context - Important information gets buried ## Solution Automatically summarize conversation history to: 1. Preserve key information 2. Reduce token usage 3. Maintain context continuity 4. Enable indefinite conversations ## Code ```typescript type ConversationMessage = { role: "user" | "assistant" | "system"; content: string; timestamp: Date; important?: boolean; }; class ConversationSummarizer { private neurolink: NeuroLink; private messages: ConversationMessage[] = []; private summary: string = ""; private maxMessages: number; private summaryModel: string; constructor( options: { maxMessages?: number; summaryModel?: string; } = {}, ) { this.neurolink = new NeuroLink(); this.maxMessages = options.maxMessages || 10; this.summaryModel = options.summaryModel || "claude-3-haiku-20240307"; } /** * Add message to conversation */ addMessage(role: "user" | "assistant", content: string, important = false) { this.messages.push({ role, content, timestamp: new Date(), important, }); // Summarize if threshold reached if (this.messages.length >= this.maxMessages) { this.summarizeAsync(); } } /** * Summarize old messages (async, non-blocking) */ private async summarizeAsync() { if (this.messages.length m.important); const regularMessages = this.messages.filter((m) => !m.important); // Split: summarize first half, keep second half const toSummarize = regularMessages.slice( 0, Math.floor(regularMessages.length / 2), ); const toKeep = regularMessages.slice( Math.floor(regularMessages.length / 2), ); if (toSummarize.length === 0) { return; } console.log(` Summarizing ${toSummarize.length} messages...`); try { const newSummary = await this.createSummary(toSummarize); // Update state this.summary = this.combineSummaries(this.summary, newSummary); this.messages = [...importantMessages, ...toKeep]; console.log(`✅ Summary updated. Messages: ${this.messages.length}`); } catch (error: any) { console.error("❌ Summarization failed:", error.message); } } /** * Create summary of messages */ private async createSummary( messages: ConversationMessage[], ): Promise { const conversationText = messages .map((m) => `${m.role}: ${m.content}`) .join("\n\n"); const result = await this.neurolink.generate({ input: { text: `Summarize this conversation concisely, preserving key facts, decisions, and context:\n\n${conversationText}`, }, provider: "anthropic", model: this.summaryModel, maxTokens: 500, }); return result.content; } /** * Combine old and new summaries */ private combineSummaries(oldSummary: string, newSummary: string): string { if (!oldSummary) return newSummary; // If both exist, combine them (could also summarize the summaries) return `${oldSummary}\n\nRecent updates: ${newSummary}`; } /** * Get conversation context for AI */ async getContext(): Promise { const parts: string[] = []; // Add summary if exists if (this.summary) { parts.push(`[Previous conversation summary: ${this.summary}]`); } // Add recent messages const recentMessages = this.messages .slice(-5) .map((m) => `${m.role}: ${m.content}`) .join("\n\n"); if (recentMessages) { parts.push(recentMessages); } return parts.join("\n\n"); } /** * Chat with automatic summarization */ async chat(userMessage: string, markImportant = false): Promise { this.addMessage("user", userMessage, markImportant); const context = await this.getContext(); const result = await this.neurolink.generate({ input: { text: context }, }); this.addMessage("assistant", result.content); return result.content; } /** * Get statistics */ getStats() { return { messages: this.messages.length, hasSummary: !!this.summary, summaryLength: this.summary.length, importantMessages: this.messages.filter((m) => m.important).length, }; } /** * Export full conversation */ export() { return { summary: this.summary, messages: this.messages, timestamp: new Date(), }; } /** * Import conversation */ import(data: { summary: string; messages: ConversationMessage[] }) { this.summary = data.summary; this.messages = data.messages; } } // Usage Example async function main() { const summarizer = new ConversationSummarizer({ maxMessages: 8, summaryModel: "claude-3-haiku-20240307", }); // Simulate a long conversation console.log("Starting long conversation...\n"); const topics = [ "Tell me about quantum computing", "How does quantum entanglement work?", "What are practical applications?", "Compare quantum vs classical computers", "Explain quantum supremacy", "What is Shor's algorithm?", "How close are we to practical quantum computers?", "What are the main challenges?", "Explain quantum error correction", "What companies are leading in quantum computing?", ]; for (let i = 0; i = maxMessages) { summarize(); // Default: 10 messages } ``` ### 2. Preserve Important Messages Mark critical messages to preserve: ```typescript summarizer.addMessage("user", "Process this payment", true); // Never summarized, always in full context ``` ### 3. Split Strategy - **First half**: Summarize - **Second half**: Keep in full - **Important**: Always keep ### 4. Hierarchical Summaries Combine summaries over time: ``` [Summary 1-10] + [Summary 11-20] → [Combined Summary] ``` ### 5. Cost Optimization Use cheap model for summarization: - Claude Haiku: $0.00025/1K tokens - Gemini Pro: $0.00025/1K tokens ## Variations ### Progressive Summarization Summarize at multiple levels: ```typescript class ProgressiveSummarizer extends ConversationSummarizer { private detailedSummary: string = ""; private briefSummary: string = ""; async summarize() { // Level 1: Detailed summary (300 tokens) this.detailedSummary = await this.createSummary(this.messages, 300); // Level 2: Brief summary (100 tokens) this.briefSummary = await this.summarizeText(this.detailedSummary, 100); } private async summarizeText( text: string, maxTokens: number, ): Promise { const result = await this.neurolink.generate({ input: { text: `Summarize concisely: ${text}` }, maxTokens, }); return result.content; } } ``` ### Topic-Based Summarization Organize summaries by topic: ```typescript type TopicSummary = { topic: string; summary: string; messageCount: number; }; class TopicalSummarizer { private topics = new Map(); async addMessage(topic: string, message: ConversationMessage) { if (!this.topics.has(topic)) { this.topics.set(topic, []); } this.topics.get(topic)!.push(message); // Summarize if topic has many messages if (this.topics.get(topic)!.length >= 10) { await this.summarizeTopic(topic); } } } ``` ### Time-Based Summarization Summarize by time windows: ```typescript class TimeBasedSummarizer { async summarizeByTime(hours: number = 24) { const cutoff = new Date(Date.now() - hours * 60 * 60 * 1000); const oldMessages = this.messages.filter((m) => m.timestamp m.timestamp >= cutoff); if (oldMessages.length > 0) { const summary = await this.createSummary(oldMessages); this.summary = this.combineSummaries(this.summary, summary); this.messages = recentMessages; } } } ``` ### Extractive Summarization Keep actual message excerpts: ```typescript function extractKeyPoints(messages: ConversationMessage[]): string[] { // Simple heuristic: sentences with key indicators const keyIndicators = [ "important", "remember", "decision", "agreed", "action", ]; const keyPoints: string[] = []; messages.forEach((msg) => { const sentences = msg.content.split(/[.!?]+/); sentences.forEach((sentence) => { if (keyIndicators.some((kw) => sentence.toLowerCase().includes(kw))) { keyPoints.push(sentence.trim()); } }); }); return keyPoints; } ``` ## Summarization Strategies | Strategy | When to Use | Token Savings | Context Preservation | | --------------------------------------- | ------------------------- | ------------- | -------------------- | | **Simple**: Remove old messages | Short conversations | 90% | Low | | **Abstractive**: AI-generated summary | Long conversations | 80% | Medium | | **Extractive**: Key sentence selection | Factual conversations | 60% | High | | **Hierarchical**: Multi-level summaries | Very long conversations | 85% | Medium-High | | **Topic-based**: Group by subject | Multi-topic conversations | 75% | High | ## Best Practices 1. **Summarize early**: Don't wait until context is full 2. **Preserve decisions**: Mark important messages 3. **Use cheap models**: Summarization doesn't need GPT-4 4. **Test summaries**: Verify important info isn't lost 5. **Export regularly**: Save full conversation for debugging ## See Also - [Context Window Management](/docs/cookbook/context-window-management) - [Cost Optimization](/docs/cookbook/cost-optimization) - [Memory Management Guide](/docs/features/conversation-history) - [Redis Persistence](/docs/guides/redis-configuration) --- ## Cost Optimization # Cost Optimization ## Problem AI API costs can accumulate quickly, especially with: - Large context windows - Frequent API calls - Expensive models (GPT-4, Claude Opus) - Inefficient prompt engineering ## Solution Implement cost optimization strategies: 1. Use cheaper models when appropriate 2. Minimize context size 3. Cache responses 4. Implement token counting 5. Use model routing based on complexity ## Code ```typescript type CostOptimizer = { maxTokens?: number; cacheResponses?: boolean; useSmartRouting?: boolean; }; class CostEfficientNeuroLink { private neurolink: NeuroLink; private cache = new Map(); private tokenCosts = { "gpt-4": { input: 0.03, output: 0.06 }, "gpt-3.5-turbo": { input: 0.0015, output: 0.002 }, "claude-3-opus": { input: 0.015, output: 0.075 }, "claude-3-sonnet": { input: 0.003, output: 0.015 }, "claude-3-haiku": { input: 0.00025, output: 0.00125 }, "gemini-pro": { input: 0.00025, output: 0.0005 }, }; constructor(options: CostOptimizer = {}) { this.neurolink = new NeuroLink(); } /** * Route to cheaper model for simple queries */ selectModel( prompt: string, forceModel?: string, ): { provider: string; model: string; } { if (forceModel) { return { provider: "openai", model: forceModel }; } // Simple heuristics for model selection const isComplex = prompt.length > 500 || prompt.includes("analyze") || prompt.includes("complex") || prompt.includes("reasoning"); const requiresCreativity = prompt.includes("creative") || prompt.includes("story") || prompt.includes("poem"); if (isComplex && requiresCreativity) { return { provider: "openai", model: "gpt-4" }; } if (isComplex) { return { provider: "anthropic", model: "claude-3-sonnet-20240229" }; } // Simple queries → cheapest model return { provider: "anthropic", model: "claude-3-haiku-20240307" }; } /** * Generate cache key from prompt */ private getCacheKey(prompt: string, model: string): string { const normalized = prompt.trim().toLowerCase(); return `${model}:${normalized}`; } /** * Estimate cost for a request */ estimateCost( inputTokens: number, outputTokens: number, model: string, ): number { const costs = this.tokenCosts[model as keyof typeof this.tokenCosts]; if (!costs) return 0; return ( (inputTokens / 1000) * costs.input + (outputTokens / 1000) * costs.output ); } /** * Generate with cost optimization */ async generateCostEffective( prompt: string, options: { useCache?: boolean; maxTokens?: number; forceModel?: string; } = {}, ) { const { provider, model } = this.selectModel(prompt, options.forceModel); const cacheKey = this.getCacheKey(prompt, model); // Check cache first if (options.useCache !== false && this.cache.has(cacheKey)) { console.log(" Using cached response (cost: $0.00)"); return this.cache.get(cacheKey); } // Truncate very long prompts const maxPromptLength = 2000; const truncatedPrompt = prompt.length > maxPromptLength ? prompt.slice(0, maxPromptLength) + "..." : prompt; const result = await this.neurolink.generate({ input: { text: truncatedPrompt }, provider, model, maxTokens: options.maxTokens || 500, // Limit output tokens }); // Estimate and log cost const inputTokens = this.estimateTokens(truncatedPrompt); const outputTokens = this.estimateTokens(result.content); const cost = this.estimateCost(inputTokens, outputTokens, model); console.log(` Cost estimate: $${cost.toFixed(4)} (${model})`); // Cache the response if (options.useCache !== false) { this.cache.set(cacheKey, result); } return result; } /** * Estimate token count (rough approximation) */ private estimateTokens(text: string): number { // Rough estimate: ~4 characters per token return Math.ceil(text.length / 4); } /** * Batch similar requests to minimize overhead */ async batchGenerate(prompts: string[]) { const results = []; let totalCost = 0; for (const prompt of prompts) { const result = await this.generateCostEffective(prompt, { useCache: true, }); results.push(result); // Track cumulative cost const cost = (this.estimateTokens(result.content) * 0.002) / 1000; totalCost += cost; } console.log(`\n Total batch cost: $${totalCost.toFixed(4)}`); return results; } /** * Clear cache to free memory */ clearCache() { this.cache.clear(); } /** * Get cache statistics */ getCacheStats() { return { entries: this.cache.size, estimatedSavings: this.cache.size * 0.01, // Rough estimate }; } } // Usage Example async function main() { const optimizer = new CostEfficientNeuroLink(); // Simple query → uses cheap model (Haiku) const simple = await optimizer.generateCostEffective("What is 2+2?", { useCache: true, }); console.log("Simple:", simple.content); // Complex query → uses better model (Sonnet) const complex = await optimizer.generateCostEffective( "Analyze the economic implications of quantum computing on financial markets", { maxTokens: 300 }, ); console.log("Complex:", complex.content); // Batch processing with caching const prompts = [ "What is TypeScript?", "What is TypeScript?", // Cached! "Explain async/await", ]; await optimizer.batchGenerate(prompts); // Check savings const stats = optimizer.getCacheStats(); console.log( `\n Cache stats: ${stats.entries} entries, ~$${stats.estimatedSavings.toFixed(2)} saved`, ); } main(); ``` ## Explanation ### 1. Smart Model Routing The `selectModel()` method analyzes the prompt to choose the most cost-effective model: - **Simple queries** → Claude Haiku ($0.00025/1K input tokens) - **Complex queries** → Claude Sonnet ($0.003/1K input tokens) - **Complex + Creative** → GPT-4 ($0.03/1K input tokens) ### 2. Response Caching Identical prompts return cached responses at zero cost. Perfect for: - Repeated queries - Development/testing - Common questions in production ### 3. Token Limiting Set `maxTokens` to prevent unexpectedly long (expensive) responses: - Summaries: 200-300 tokens - Explanations: 500-1000 tokens - Creative content: 1000-2000 tokens ### 4. Cost Tracking Estimate costs per request to monitor spending: ``` Input: 250 tokens × $0.003/1K = $0.00075 Output: 500 tokens × $0.015/1K = $0.00750 Total: $0.00825 ``` ### 5. Prompt Truncation Very long prompts increase costs without adding value. Truncate to essential context. ## Variations ### Context Window Compression Compress conversation history to reduce tokens: ```typescript function compressContext(messages: Array) { // Keep system message and last N messages const system = messages.find((m) => m.role === "system"); const recent = messages.slice(-5); // Last 5 messages // Summarize older messages const older = messages.slice(1, -5); const summary = older.length > 0 ? `[Previous conversation: ${older.length} messages covering ${older.map((m) => m.content.slice(0, 20)).join(", ")}...]` : ""; return [system, { role: "assistant", content: summary }, ...recent].filter( Boolean, ); } ``` ### Model Tier System Explicitly define cost tiers: ```typescript enum ModelTier { ULTRA_CHEAP = "claude-3-haiku-20240307", // $0.00025/1K CHEAP = "gpt-3.5-turbo", // $0.0015/1K BALANCED = "claude-3-sonnet-20240229", // $0.003/1K POWERFUL = "gpt-4", // $0.03/1K } async function generateWithTier(prompt: string, tier: ModelTier) { return neurolink.generate({ input: { text: prompt }, model: tier, }); } ``` ### Budget Enforcement Set spending limits: ```typescript class BudgetEnforcer { private spentToday = 0; private dailyLimit = 10.0; // $10/day async generate(neurolink: NeuroLink, prompt: string) { const estimatedCost = 0.01; // Rough estimate if (this.spentToday + estimatedCost > this.dailyLimit) { throw new Error( `Budget exceeded: $${this.spentToday.toFixed(2)}/$${this.dailyLimit}`, ); } const result = await neurolink.generate({ input: { text: prompt } }); this.spentToday += estimatedCost; return result; } } ``` ## Cost Comparison | Task Type | Best Model | Cost (per 1K tokens) | Use Case | | ---------------- | ------------- | -------------------- | ---------------------------- | | Simple Q&A | Claude Haiku | $0.00025 | FAQs, basic queries | | Data extraction | GPT-3.5 Turbo | $0.0015 | JSON parsing, classification | | Analysis | Claude Sonnet | $0.003 | Summaries, explanations | | Deep reasoning | GPT-4 | $0.03 | Complex problem-solving | | Creative writing | GPT-4 | $0.03 | Stories, marketing copy | ## See Also - [Batch Processing](/docs/cookbook/batch-processing) - [Context Window Management](/docs/cookbook/context-window-management) - [Provider Selection Guide](/docs/reference/provider-selection) - [Rate Limit Handling](/docs/cookbook/rate-limit-handling) --- ## Embeddings Basics # Embeddings Basics ## Problem Many AI applications need to compare text semantically -- finding similar documents, powering search, clustering content, or building recommendation systems. Raw text comparison (string matching) misses synonyms, paraphrases, and conceptual similarity. ## Solution Use NeuroLink's `embed()` and `embedMany()` provider methods to generate vector embeddings. These fixed-length number arrays capture the semantic meaning of text, enabling similarity comparisons with cosine similarity or dot product. ## Code ```typescript // ----------------------------------------------------------- // 1. Generate a single embedding // ----------------------------------------------------------- async function singleEmbedding() { const provider = await ProviderFactory.createProvider( "openai", "text-embedding-3-small", ); const embedding = await provider.embed( "The quick brown fox jumps over the lazy dog.", ); console.log("Embedding dimensions:", embedding.length); console.log("First 5 values:", embedding.slice(0, 5)); } // ----------------------------------------------------------- // 2. Generate embeddings for multiple texts // ----------------------------------------------------------- async function batchEmbeddings() { const provider = await ProviderFactory.createProvider( "openai", "text-embedding-3-small", ); const texts = [ "Machine learning is a subset of artificial intelligence.", "Deep learning uses neural networks with many layers.", "The weather forecast predicts rain tomorrow.", "Neural networks are inspired by the human brain.", ]; const embeddings = await provider.embedMany(texts); console.log(`Generated ${embeddings.length} embeddings`); console.log(`Each has ${embeddings[0].length} dimensions`); } // ----------------------------------------------------------- // 3. Compare similarity between texts // ----------------------------------------------------------- function cosineSimilarity(a: number[], b: number[]): number { if (a.length !== b.length) { throw new Error(`Vector length mismatch: ${a.length} vs ${b.length}`); } let dotProduct = 0; let normA = 0; let normB = 0; for (let i = 0; i Security > Reset Password.", // [1] Relevant "Our office hours are 9am to 5pm Monday through Friday.", // [2] Irrelevant "Forgot your password? Click the reset link on the login page.", // [3] Relevant ]; const embeddings = await provider.embedMany(texts); const query = embeddings[0]; console.log('Similarity scores against: "How do I reset my password?"'); console.log("---"); for (let i = 1; i ({ document: doc, score: cosineSimilarity(queryEmbedding, docEmbeddings[i]), })); // Sort by score descending and return top K scored.sort((a, b) => b.score - a.score); return scored.slice(0, topK); } // ----------------------------------------------------------- // Usage // ----------------------------------------------------------- async function main() { console.log("=== Single Embedding ===\n"); await singleEmbedding(); console.log("\n=== Batch Embeddings ===\n"); await batchEmbeddings(); console.log("\n=== Similarity Comparison ===\n"); await compareSimilarity(); console.log("\n=== Semantic Search ===\n"); const results = await semanticSearch("How do I deploy to production?", [ "Deployment guide: Use CI/CD pipelines to push to production.", "Our company was founded in 2015 in San Francisco.", "To deploy, run `npm run build` then `npm run deploy`.", "Production deployments require approval from the team lead.", "The cafeteria menu changes every week.", ]); for (const result of results) { console.log(`${result.score.toFixed(4)} | "${result.document}"`); } } main(); ``` ## Explanation ### 1. Provider Setup for Embeddings Embedding models are accessed through the provider directly via `ProviderFactory`. Nine providers implement `embed()` / `embedMany()` natively, each with its own default embedding model: | Provider | Default Embedding Model | Dimensions | | ---------------- | ------------------------------ | ---------- | | OpenAI | `text-embedding-3-small` | 1536 | | Google AI Studio | `gemini-embedding-001` | 3072 | | Google Vertex | `text-embedding-004` | 768 | | Amazon Bedrock | `amazon.titan-embed-text-v2:0` | 1024 | | Cohere | `embed-english-v3.0` | 1024 | | Voyage AI | `voyage-3.5` | 1024 | | Jina AI | `jina-embeddings-v3` | 1024 | | Ollama | `nomic-embed-text` | 768 | | LiteLLM | proxied to the upstream model | varies | Nine providers implement `embed()` / `embedMany()` natively. Voyage AI and Jina AI are embedding-focused and don't serve `generate()` / `stream()` chat completions — Voyage is embedding-only, and Jina also does reranking. Cohere additionally implements `embed()` / `embedMany()`, but its default model (`command-r-plus`) is a full chat model, so unlike Voyage and Jina, Cohere also serves `generate()` / `stream()`. > **Note:** Google's `text-embedding-004` is being retired. The recommended replacement is `gemini-embedding-001` (3072 dimensions). Override the default with `VERTEX_EMBEDDING_MODEL=gemini-embedding-001`. ```typescript const provider = await ProviderFactory.createProvider( "openai", "text-embedding-3-small", ); ``` ### 2. `embed()` vs `embedMany()` - **`embed(text)`**: Generates a single embedding vector. Use for one-off queries. - **`embedMany(texts)`**: Generates embeddings for an array of texts in one API call. More efficient for batches. ```typescript const single = await provider.embed("Hello world"); // number[] const batch = await provider.embedMany(["Hello", "World"]); // number[][] ``` ### 3. Cosine Similarity Cosine similarity measures the angle between two vectors. Values range from -1 to 1: - **1.0**: Identical meaning - **0.0**: Unrelated - **-1.0**: Opposite meaning (rare with embedding models) In practice, similar texts score above 0.7 and unrelated texts score below 0.4. ### 4. Semantic Search Pattern The core semantic search pattern is: 1. Embed all documents once (store the vectors) 2. Embed the user's query at search time 3. Compute cosine similarity between the query and each document 4. Return the top K highest-scoring documents ## Variations ### Cache Embeddings for Repeated Searches Avoid re-embedding documents on every search: ```typescript class EmbeddingCache { private cache = new Map(); private provider: any; constructor(provider: any) { this.provider = provider; } async getEmbedding(text: string): Promise { if (this.cache.has(text)) { return this.cache.get(text)!; } const embedding = await this.provider.embed(text); this.cache.set(text, embedding); return embedding; } async getEmbeddings(texts: string[]): Promise { const uncached = texts.filter((t) => !this.cache.has(t)); if (uncached.length > 0) { const newEmbeddings = await this.provider.embedMany(uncached); uncached.forEach((text, i) => this.cache.set(text, newEmbeddings[i])); } return texts.map((t) => this.cache.get(t)!); } } ``` ### Use with Google AI Studio Switch to Google's embedding model: ```typescript const provider = await ProviderFactory.createProvider( "google-ai", "gemini-embedding-001", ); const embedding = await provider.embed( "Semantic search with Gemini embeddings.", ); console.log("Dimensions:", embedding.length); // 3072 ``` ### Combine Embeddings with RAG Use embeddings as the foundation for RAG (Retrieval-Augmented Generation): ```typescript async function ragWithEmbeddings() { const neurolink = new NeuroLink(); // NeuroLink handles embedding + search automatically via the rag option const result = await neurolink.generate({ input: { text: "What are the deployment requirements?" }, provider: "openai", rag: { files: ["./docs/deployment.md", "./docs/requirements.md"], topK: 5, }, }); console.log(result.content); } ``` ### Clustering Documents Group similar documents together using embeddings: ```typescript async function clusterDocuments(documents: string[], threshold: number = 0.8) { const provider = await ProviderFactory.createProvider( "openai", "text-embedding-3-small", ); const embeddings = await provider.embedMany(documents); const clusters: number[][] = []; const assigned = new Set(); for (let i = 0; i = threshold) { cluster.push(j); assigned.add(j); } } clusters.push(cluster); } return clusters.map((indices) => ({ documents: indices.map((i) => documents[i]), size: indices.length, })); } ``` ## Tips 1. **Embed once, query many times**: Embedding documents is the expensive step. Store embeddings in a database or vector store for fast repeated searches. 2. **Use `embedMany()` for batches**: It is significantly faster than calling `embed()` in a loop because it makes a single API call. 3. **Match embedding and search models**: Always use the same model to embed both documents and queries. Vectors from different models are incompatible. 4. **Consider dimensions**: `text-embedding-3-small` (1536d) is a good balance of quality and size. For storage-constrained systems, OpenAI also offers a 256d variant. ## See Also - [Batch Processing](/docs/cookbook/batch-processing) - [Cost Optimization](/docs/cookbook/cost-optimization) - [Provider Switching](/docs/cookbook/provider-switching) - [API Reference](/docs/sdk/api-reference) --- ## Error Recovery Patterns # Error Recovery Patterns ## Problem Production AI applications face various errors: - Network failures - Provider outages - Invalid API keys - Model unavailability - Timeout errors - Rate limiting - Malformed responses Without proper error handling, applications crash or produce poor user experiences. ## Solution Implement comprehensive error recovery with: 1. Error classification (retryable vs fatal) 2. Graceful degradation 3. User-friendly error messages 4. Automatic fallback strategies 5. Error monitoring and alerting ## Code ```typescript enum ErrorType { RETRYABLE, FALLBACK, FATAL, } type ErrorRecoveryConfig = { maxRetries?: number; fallbackProvider?: string; fallbackResponse?: string; onError?: (error: Error, context: any) => void; }; class RobustNeuroLink { private neurolink: NeuroLink; private config: ErrorRecoveryConfig; constructor(config: ErrorRecoveryConfig = {}) { this.neurolink = new NeuroLink(); this.config = { maxRetries: config.maxRetries || 3, fallbackProvider: config.fallbackProvider, fallbackResponse: config.fallbackResponse || "I'm having trouble processing your request. Please try again.", onError: config.onError, }; } /** * Classify error to determine recovery strategy */ private classifyError(error: any): ErrorType { // Network errors - retryable if ( error.code === "ECONNRESET" || error.code === "ETIMEDOUT" || error.code === "ENOTFOUND" || error.message?.includes("network") || error.message?.includes("timeout") ) { return ErrorType.RETRYABLE; } // Provider errors - may fallback if ( error.status === 429 || // Rate limit error.status === 503 || // Service unavailable error.status === 502 || // Bad gateway error.status === 504 || // Gateway timeout error.message?.includes("overloaded") || error.message?.includes("capacity") ) { return ErrorType.FALLBACK; } // Authentication errors - fatal if ( error.status === 401 || error.status === 403 || error.message?.includes("API key") || error.message?.includes("authentication") ) { return ErrorType.FATAL; } // Invalid request - fatal if ( error.status === 400 || error.message?.includes("invalid") || error.message?.includes("malformed") ) { return ErrorType.FATAL; } // Default: retryable return ErrorType.RETRYABLE; } /** * Get user-friendly error message */ private getUserMessage(error: any): string { const messages: Record = { 401: "Authentication failed. Please check your API key.", 403: "Access denied. You may not have permission for this operation.", 429: "Rate limit exceeded. Please wait a moment and try again.", 500: "The AI service encountered an error. Please try again.", 503: "The AI service is temporarily unavailable. Please try again later.", }; return ( messages[error.status] || error.message || "An unexpected error occurred." ); } /** * Generate with automatic error recovery */ async generateSafe( prompt: string, options: { provider?: string; model?: string; fallbackProvider?: string; } = {}, ): Promise { const provider = options.provider || "openai"; let attempt = 0; while (attempt 0, }; } catch (error: any) { attempt++; const errorType = this.classifyError(error); // Log error console.error( `❌ Error (attempt ${attempt}/${this.config.maxRetries}):`, error.message, ); this.config.onError?.(error, { prompt, provider, attempt }); // Fatal errors - don't retry if (errorType === ErrorType.FATAL) { return { content: this.config.fallbackResponse!, error: new Error(this.getUserMessage(error)), recovered: false, }; } // Fallback to alternative provider if (errorType === ErrorType.FALLBACK && options.fallbackProvider) { try { console.log( ` Trying fallback provider: ${options.fallbackProvider}`, ); const fallbackResult = await this.neurolink.generate({ input: { text: prompt }, provider: options.fallbackProvider, }); return { content: fallbackResult.content, recovered: true, }; } catch (fallbackError: any) { console.error("❌ Fallback also failed:", fallbackError.message); } } // Retryable errors - wait and retry if (attempt setTimeout(r, delay)); } } } // All retries exhausted return { content: this.config.fallbackResponse!, error: new Error("All retry attempts failed"), recovered: false, }; } /** * Stream with error recovery */ async streamSafe( prompt: string, options: { provider?: string } = {}, ): Promise> { const provider = options.provider || "openai"; try { const result = await this.neurolink.stream({ input: { text: prompt }, provider, }); // Wrap stream to handle errors return this.wrapStreamWithRecovery(result.stream, prompt, provider); } catch (error: any) { console.error("❌ Stream failed:", error.message); // Return fallback as async iterable return (async function* () { yield "I'm having trouble streaming the response. "; yield "Please try again or rephrase your request."; })(); } } /** * Wrap stream with error recovery */ private async *wrapStreamWithRecovery( stream: AsyncIterable, prompt: string, provider: string, ): AsyncIterable { try { for await (const chunk of stream) { if ("content" in chunk) yield chunk.content; } } catch (error: any) { console.error("❌ Stream interrupted:", error.message); // Try to recover with non-streaming try { const fallback = await this.generateSafe(prompt, { provider }); yield "\n\n[Recovered via non-streaming]\n"; yield fallback.content; } catch { yield "\n\n[Stream failed and recovery failed]"; } } } } // Usage Example async function main() { const robust = new RobustNeuroLink({ maxRetries: 3, fallbackProvider: "anthropic", onError: (error, context) => { // Log to monitoring service console.error("Error logged:", { error: error.message, context, timestamp: new Date().toISOString(), }); }, }); // Generate with automatic recovery const result = await robust.generateSafe("Explain quantum computing", { provider: "openai", fallbackProvider: "anthropic", }); if (result.error) { console.log("⚠️ Recovered from error:", result.error.message); } console.log("Response:", result.content); // Stream with error recovery console.log("\nStreaming..."); const stream = await robust.streamSafe("Tell me a story"); for await (const chunk of stream) { process.stdout.write(chunk); } } main(); ``` ## Explanation ### 1. Error Classification Errors fall into three categories: **Retryable**: Temporary issues that may resolve - Network timeouts - Connection resets - Temporary service issues **Fallback**: Use alternative provider - Rate limits - Service overload - Provider outages **Fatal**: Don't retry - Invalid API keys - Malformed requests - Unauthorized access ### 2. Retry Strategy - **Exponential backoff**: 1s, 2s, 4s, 8s (max 10s) - **Max retries**: 3 attempts by default - **Smart delays**: Longer delays for repeated failures ### 3. Graceful Degradation When all else fails: - Return fallback response - Log error for monitoring - Preserve application stability ### 4. User-Friendly Messages Map technical errors to user-friendly messages: ``` 401 → "Authentication failed. Please check your API key." 503 → "Service temporarily unavailable. Please try again later." ``` ### 5. Error Monitoring Call `onError` callback for: - Logging to monitoring service - Alerting on critical errors - Analytics and debugging ## Variations ### Circuit Breaker Prevent cascading failures: ```typescript class CircuitBreaker { private failures = 0; private lastFailure = 0; private state: "CLOSED" | "OPEN" | "HALF_OPEN" = "CLOSED"; async call(fn: () => Promise): Promise { if (this.state === "OPEN") { if (Date.now() - this.lastFailure > 60000) { this.state = "HALF_OPEN"; } else { throw new Error("Circuit breaker is OPEN"); } } try { const result = await fn(); this.reset(); return result; } catch (error) { this.recordFailure(); throw error; } } private recordFailure() { this.failures++; this.lastFailure = Date.now(); if (this.failures >= 5) { this.state = "OPEN"; console.log(" Circuit breaker OPEN"); } } private reset() { this.failures = 0; this.state = "CLOSED"; } } ``` ### Health Checks Monitor provider health: ```typescript class ProviderHealthMonitor { private health = new Map(); async checkHealth(provider: string): Promise { try { await neurolink.generate({ input: { text: "test" }, provider, maxTokens: 10, }); this.health.set(provider, true); return true; } catch { this.health.set(provider, false); return false; } } isHealthy(provider: string): boolean { return this.health.get(provider) ?? true; } } ``` ### Automatic Provider Selection Choose healthy provider automatically: ```typescript async function selectHealthyProvider(providers: string[]): Promise { for (const provider of providers) { const healthy = await healthMonitor.checkHealth(provider); if (healthy) return provider; } throw new Error("No healthy providers available"); } ``` ## Best Practices 1. **Log all errors**: Track patterns for debugging 2. **Monitor error rates**: Alert on unusual spikes 3. **Test error paths**: Simulate failures in testing 4. **Provide context**: Include request details in errors 5. **User communication**: Clear, actionable error messages ## See Also - [Streaming with Retry](/docs/cookbook/streaming-with-retry) - [Multi-Provider Fallback](/docs/cookbook/multi-provider-fallback) - [Rate Limit Handling](/docs/cookbook/rate-limit-handling) - [Troubleshooting Guide](/docs/reference/troubleshooting) --- ## Multi-Provider Fallback # Multi-Provider Fallback ## Problem Relying on a single AI provider creates a single point of failure: - Provider outages affect your entire application - Rate limits halt all operations - Regional availability issues block access - Model deprecation requires code changes ## Solution Implement automatic fallback across multiple providers: 1. Primary → Secondary → Tertiary provider chain 2. Health monitoring for each provider 3. Automatic failover on errors 4. Load balancing across providers 5. Cost-aware routing ## Code ```typescript type ProviderConfig = { name: string; model?: string; priority: number; // Lower = higher priority costPerToken?: number; // For cost-aware routing maxRetries?: number; }; class MultiProviderNeuroLink { private neurolink: NeuroLink; private providers: ProviderConfig[]; private healthStatus = new Map(); constructor(providers: ProviderConfig[]) { this.neurolink = new NeuroLink(); this.providers = providers.sort((a, b) => a.priority - b.priority); // Initialize all providers as healthy providers.forEach((p) => this.healthStatus.set(p.name, true)); } /** * Mark provider as unhealthy */ private markUnhealthy(provider: string, duration: number = 60000) { console.log(`⚠️ Marking ${provider} as unhealthy for ${duration}ms`); this.healthStatus.set(provider, false); // Auto-recover after duration setTimeout(() => { console.log(`✅ ${provider} marked as healthy again`); this.healthStatus.set(provider, true); }, duration); } /** * Get healthy providers in priority order */ private getHealthyProviders(): ProviderConfig[] { return this.providers.filter( (p) => this.healthStatus.get(p.name) !== false, ); } /** * Generate with automatic fallback */ async generate( prompt: string, options: { preferCheap?: boolean; timeout?: number } = {}, ): Promise { let providers = this.getHealthyProviders(); if (providers.length === 0) { throw new Error("No healthy providers available"); } // Sort by cost if preferred if (options.preferCheap) { providers = providers.sort( (a, b) => (a.costPerToken || 0) - (b.costPerToken || 0), ); } let attempts = 0; const errors: Error[] = []; for (const config of providers) { attempts++; console.log(`\n Attempt ${attempts}: Trying ${config.name}...`); try { const result = await this.tryProvider(prompt, config, options.timeout); console.log(`✅ Success with ${config.name}`); return { content: result.content, provider: config.name, attempts, }; } catch (error: any) { console.error(`❌ ${config.name} failed:`, error.message); errors.push(error); // Mark unhealthy if specific error types if (this.shouldMarkUnhealthy(error)) { this.markUnhealthy(config.name); } // Continue to next provider continue; } } // All providers failed throw new Error( `All ${attempts} providers failed:\n${errors .map((e, i) => `${i + 1}. ${e.message}`) .join("\n")}`, ); } /** * Try a specific provider */ private async tryProvider( prompt: string, config: ProviderConfig, timeout: number = 30000, ) { const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error("Request timeout")), timeout), ); const generatePromise = this.neurolink.generate({ input: { text: prompt }, provider: config.name, model: config.model, }); return Promise.race([generatePromise, timeoutPromise]); } /** * Determine if error should mark provider unhealthy */ private shouldMarkUnhealthy(error: any): boolean { return ( error.status === 503 || // Service unavailable error.status === 502 || // Bad gateway error.code === "ECONNREFUSED" || error.message?.includes("overloaded") || error.message?.includes("capacity") ); } /** * Stream with fallback */ async stream(prompt: string): Promise; provider: string; }> { const providers = this.getHealthyProviders(); for (const config of providers) { try { console.log(` Trying to stream with ${config.name}...`); const stream = await this.neurolink.stream({ input: { text: prompt }, provider: config.name, model: config.model, }); return { stream, provider: config.name, }; } catch (error: any) { console.error(`❌ ${config.name} streaming failed:`, error.message); if (this.shouldMarkUnhealthy(error)) { this.markUnhealthy(config.name); } continue; } } throw new Error("All providers failed to stream"); } /** * Get provider health status */ getHealthStatus() { return Array.from(this.healthStatus.entries()).map(([name, healthy]) => ({ provider: name, healthy, })); } /** * Manually set provider health */ setProviderHealth(provider: string, healthy: boolean) { this.healthStatus.set(provider, healthy); } } // Usage Example async function main() { const multiProvider = new MultiProviderNeuroLink([ { name: "openai", model: "gpt-4", priority: 1, costPerToken: 0.03, }, { name: "anthropic", model: "claude-3-sonnet-20240229", priority: 2, costPerToken: 0.003, }, { name: "google-ai", model: "gemini-pro", priority: 3, costPerToken: 0.00025, }, ]); // Generate with automatic fallback try { const result = await multiProvider.generate( "Explain quantum entanglement", { timeout: 10000 }, ); console.log( `\n✅ Response from ${result.provider} (after ${result.attempts} attempts):`, ); console.log(result.content); } catch (error: any) { console.error("❌ All providers failed:", error.message); } // Check health status console.log("\n Provider Health:"); const health = multiProvider.getHealthStatus(); health.forEach((h) => { console.log( ` ${h.provider}: ${h.healthy ? "✅ Healthy" : "❌ Unhealthy"}`, ); }); // Stream with fallback try { const { stream, provider } = await multiProvider.stream( "Tell me a short story about AI", ); console.log(`\n Streaming from ${provider}:`); for await (const chunk of stream) { if (chunk.type === "content-delta") { process.stdout.write(chunk.delta); } } } catch (error: any) { console.error("\n❌ Streaming failed:", error.message); } } main(); ``` ## Explanation ### 1. Provider Priority Providers are ordered by priority (1 = highest). The default `getBestProvider()` order prioritizes self-hosted providers first (no rate limits, no external costs): ```typescript providers = [ { name: "litellm", priority: 1 }, // Self-hosted proxy (no rate limits) { name: "ollama", priority: 2 }, // Local models (no rate limits) { name: "openai", priority: 3 }, // Cloud fallback { name: "anthropic", priority: 4 }, // Cloud fallback { name: "google-ai", priority: 5 }, // Cloud fallback ]; ``` ### 2. Health Monitoring Track provider health automatically: - **Healthy**: Available for requests - **Unhealthy**: Temporarily skipped (auto-recovers after 60s) - **Failure triggers**: 503, 502, connection errors ### 3. Automatic Failover On error, automatically try next provider: ``` OpenAI fails → Try Anthropic → Try Google AI → Throw error ``` ### 4. Error Classification Not all errors trigger failover: - **503, 502**: Provider issue → Mark unhealthy, try next - **401, 403**: Auth issue → Try next (may have different credentials) - **400**: Bad request → Don't retry (same error on all providers) ### 5. Timeout Protection Set timeouts to prevent hanging on slow providers: ```typescript timeout: 10000; // 10 seconds ``` ## Variations ### Cost-Aware Routing Prefer cheaper providers when quality is similar: ```typescript async generateCheap(prompt: string) { return this.generate(prompt, { preferCheap: true }); } ``` ### Region-Aware Routing Choose provider based on region: ```typescript type RegionalConfig = ProviderConfig & { regions: string[]; }; function getProvidersForRegion(region: string): ProviderConfig[] { return providers.filter( (p) => p.regions.includes(region) || p.regions.includes("global"), ); } ``` ### Load Balancing Distribute load across providers: ```typescript class LoadBalancedNeuroLink extends MultiProviderNeuroLink { private currentIndex = 0; async generateBalanced(prompt: string) { const providers = this.getHealthyProviders(); // Round-robin selection const provider = providers[this.currentIndex % providers.length]; this.currentIndex++; try { return await this.tryProvider(prompt, provider); } catch (error) { // Fallback to standard failover return this.generate(prompt); } } } ``` ### Model-Specific Fallback Different models for different tasks: ```typescript const TASK_PROVIDERS = { coding: [ { name: "openai", model: "gpt-4" }, { name: "anthropic", model: "claude-3-opus-20240229" }, ], summarization: [ { name: "anthropic", model: "claude-3-haiku-20240307" }, { name: "google-ai", model: "gemini-pro" }, ], creative: [ { name: "openai", model: "gpt-4" }, { name: "anthropic", model: "claude-3-sonnet-20240229" }, ], }; async function generateForTask(task: string, prompt: string) { const providers = TASK_PROVIDERS[task as keyof typeof TASK_PROVIDERS]; const multiProvider = new MultiProviderNeuroLink( providers.map((p, i) => ({ ...p, priority: i + 1, })), ); return multiProvider.generate(prompt); } ``` ### Health Check Endpoint Proactive health checking: ```typescript async function checkAllProviders() { const results = await Promise.allSettled( providers.map(async (p) => { const start = Date.now(); await tryProvider("test", p, 5000); return { provider: p.name, latency: Date.now() - start }; }), ); results.forEach((result, i) => { if (result.status === "fulfilled") { console.log(`✅ ${providers[i].name}: ${result.value.latency}ms`); } else { console.log(`❌ ${providers[i].name}: Failed`); markUnhealthy(providers[i].name); } }); } // Run health checks every 5 minutes setInterval(checkAllProviders, 5 * 60 * 1000); ``` ## Provider Comparison | Provider | Availability | Rate Limits | Global Regions | Cost | | ------------ | ------------ | ------------ | -------------- | ---- | | OpenAI | 99.9% | 3500 req/min | Yes | $$$ | | Anthropic | 99.9% | 1000 req/min | Limited | $$ | | Google AI | 99.5% | 60 req/min | Yes | $ | | Azure OpenAI | 99.95% | Custom | Global | $$$ | ## Best Practices 1. **Configure at least 2 providers**: Minimum for true failover 2. **Mix provider types**: Different infrastructure = better reliability 3. **Monitor health actively**: Don't wait for failures 4. **Set appropriate timeouts**: Balance speed vs reliability 5. **Log all failovers**: Track patterns for optimization ## See Also - [Error Recovery Patterns](/docs/cookbook/error-recovery) - [Rate Limit Handling](/docs/cookbook/rate-limit-handling) - [Cost Optimization](/docs/cookbook/cost-optimization) - [Provider Comparison Guide](/docs/reference/provider-comparison) --- ## Multimodal Images # Multimodal Images ## Problem Many AI tasks require visual understanding -- analyzing screenshots, describing photos, comparing diagrams, or extracting text from images. Text-only prompts cannot handle these use cases. ## Solution Pass images to NeuroLink via the `input.images` array in `generate()` or `stream()`. NeuroLink handles the encoding and provider-specific formatting automatically. Images can be URLs, base64 strings, or Buffers. ## Code ```typescript async function analyzeImage() { const neurolink = new NeuroLink(); // Option 1: Image from a URL const result = await neurolink.generate({ input: { text: "Describe what you see in this image.", images: ["https://example.com/photo.jpg"], }, provider: "openai", model: "gpt-4o", }); console.log("Description:", result.content); } async function analyzeLocalImage() { const neurolink = new NeuroLink(); // Option 2: Image from a local file (Buffer) const imageBuffer = readFileSync("./screenshot.png"); const result = await neurolink.generate({ input: { text: "What does this screenshot show? List the main UI elements.", images: [imageBuffer], }, provider: "anthropic", model: "claude-sonnet-4-20250514", }); console.log("Analysis:", result.content); } async function compareImages() { const neurolink = new NeuroLink(); // Option 3: Multiple images in a single request const before = readFileSync("./before.png"); const after = readFileSync("./after.png"); const result = await neurolink.generate({ input: { text: "Compare these two images. What changed between the first and second?", images: [before, after], }, provider: "openai", model: "gpt-4o", }); console.log("Differences:", result.content); } analyzeImage(); ``` ## Explanation ### 1. The `input.images` Array The `images` field accepts an array of image sources. Each element can be: | Type | Example | When to Use | | -------- | ---------------------------------- | ------------------------------ | | `string` | `"https://example.com/photo.jpg"` | Public image URLs | | `string` | `"data:image/png;base64,iVBOR..."` | Base64-encoded data URIs | | `Buffer` | `readFileSync("./image.png")` | Local files loaded into memory | NeuroLink's `MessageBuilder` and `ProviderImageAdapter` handle the conversion to each provider's required format automatically. ### 2. Vision Model Requirements Not all models support images. You must use a vision-capable model: | Provider | Vision Models | | --------- | -------------------------------------------------------------------- | | OpenAI | `gpt-4o`, `gpt-4o-mini`, `gpt-4-turbo` | | Anthropic | `claude-sonnet-4-20250514`, `claude-3-5-sonnet-*`, `claude-3-opus-*` | | Google AI | `gemini-2.5-flash`, `gemini-2.5-pro`, `gemini-2.0-flash` | | Vertex AI | `gemini-2.5-flash`, `gemini-2.5-pro` | | Bedrock | `anthropic.claude-3-*`, `anthropic.claude-sonnet-4-*` | ### 3. Multiple Images Pass multiple images and reference them in your prompt. The model sees them in order: ```typescript input: { text: "The first image is the original design. The second is the implementation. How closely does the implementation match?", images: [designMockup, implementationScreenshot], } ``` ### 4. Alt Text for Accessibility For production applications, provide alt text with the `ImageWithAltText` format: ```typescript input: { text: "Analyze these product photos for our catalog.", images: [ { data: imageBuffer, altText: "Front view of the blue sneaker" }, { data: "https://example.com/side.jpg", altText: "Side profile showing sole design" }, ], } ``` ## Variations ### Stream Image Analysis Stream the response while analyzing an image: ```typescript async function streamImageAnalysis(imagePath: string, question: string) { const neurolink = new NeuroLink(); const imageBuffer = readFileSync(imagePath); const result = await neurolink.stream({ input: { text: question, images: [imageBuffer], }, provider: "openai", model: "gpt-4o", }); for await (const chunk of result.stream) { if ("content" in chunk && chunk.content) { process.stdout.write(chunk.content); } } console.log("\n"); } streamImageAnalysis("./chart.png", "Summarize the trends shown in this chart."); ``` ### Extract Text from an Image (OCR) Use a vision model as an OCR tool: ```typescript async function extractText(imagePath: string) { const neurolink = new NeuroLink(); const image = readFileSync(imagePath); const result = await neurolink.generate({ input: { text: "Extract all visible text from this image. Return it as plain text, preserving the layout as much as possible.", images: [image], }, provider: "openai", model: "gpt-4o", temperature: 0, }); return result.content; } ``` ### Base64 String Input When you already have a base64-encoded image (e.g., from a database or API): ```typescript const base64Image = "iVBORw0KGgoAAAANSUhEUg..."; // Base64 data const result = await neurolink.generate({ input: { text: "What is in this image?", images: [`data:image/png;base64,${base64Image}`], }, provider: "google-ai", model: "gemini-2.5-flash", }); ``` ### Batch Image Classification Classify multiple images in sequence: ```typescript async function classifyImages(directory: string) { const neurolink = new NeuroLink(); const files = readdirSync(directory).filter((f) => /\.(jpg|jpeg|png|webp)$/i.test(f), ); const results: Array = []; for (const file of files) { const image = readFileSync(join(directory, file)); const result = await neurolink.generate({ input: { text: 'Classify this image into exactly one category: "landscape", "portrait", "product", "document", or "other". Respond with only the category name.', images: [image], }, provider: "openai", model: "gpt-4o-mini", temperature: 0, maxTokens: 10, }); results.push({ file, category: result.content.trim().toLowerCase() }); console.log(`${file}: ${result.content.trim()}`); } return results; } ``` ## Tips 1. **Use the right model for cost**: `gpt-4o-mini` and `gemini-2.5-flash` are cheaper for simple image tasks. Reserve `gpt-4o` and `claude-sonnet-4-20250514` for complex visual reasoning. 2. **Resize large images**: Very large images consume more tokens. Resize to the minimum resolution needed before sending. 3. **Be specific in your prompt**: Instead of "describe this image", ask "list all the text visible in the top-right corner of this screenshot." 4. **One image or many**: Some tasks work better with a single detailed image; comparison tasks benefit from passing 2-3 images in one request. ## See Also - [Basic Streaming](/docs/cookbook/basic-streaming) - [Structured Output with JSON Schema](/docs/cookbook/structured-output) - [Cost Optimization](/docs/cookbook/cost-optimization) - [API Reference](/docs/sdk/api-reference) --- ## Provider Switching # Provider Switching ## Problem Different AI providers have different strengths, costs, and availability. You may need to: - Compare outputs across providers for quality evaluation - Switch providers at runtime based on user preference or task type - Implement graceful fallback when a provider is down - Optimize cost by routing different workloads to different providers ## Solution NeuroLink's unified API makes provider switching a one-line change. The `provider` and `model` fields on `generate()` and `stream()` accept any registered provider name. This recipe shows how to leverage that for comparison, runtime switching, and basic fallback. ## Code ```typescript // ----------------------------------------------------------- // 1. Compare the same prompt across multiple providers // ----------------------------------------------------------- async function compareProviders(prompt: string) { const neurolink = new NeuroLink(); const providers = [ { provider: "openai", model: "gpt-4o" }, { provider: "anthropic", model: "claude-sonnet-4-20250514" }, { provider: "google-ai", model: "gemini-2.5-flash" }, ] as const; const results = await Promise.allSettled( providers.map(async (config) => { const start = Date.now(); const result = await neurolink.generate({ input: { text: prompt }, provider: config.provider, model: config.model, temperature: 0.3, }); return { provider: config.provider, model: config.model, content: result.content, responseTime: Date.now() - start, tokens: result.usage?.total, }; }), ); // Print comparison for (const entry of results) { if (entry.status === "fulfilled") { const r = entry.value; console.log(`\n--- ${r.provider} (${r.model}) ---`); console.log(`Response time: ${r.responseTime}ms`); console.log(`Tokens used: ${r.tokens ?? "N/A"}`); console.log(`Response:\n${r.content.slice(0, 200)}...`); } else { console.log(`\nFailed: ${entry.reason}`); } } } // ----------------------------------------------------------- // 2. Runtime provider selection // ----------------------------------------------------------- async function generateWithProvider( prompt: string, providerName: string, modelName?: string, ) { const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: prompt }, provider: providerName, model: modelName, }); console.log(`[${result.provider}/${result.model}] ${result.content}`); return result; } // ----------------------------------------------------------- // 3. Simple fallback chain // ----------------------------------------------------------- async function generateWithFallback(prompt: string) { const neurolink = new NeuroLink(); const fallbackChain = [ { provider: "openai", model: "gpt-4o" }, { provider: "anthropic", model: "claude-sonnet-4-20250514" }, { provider: "google-ai", model: "gemini-2.5-flash" }, ]; for (const config of fallbackChain) { try { const result = await neurolink.generate({ input: { text: prompt }, provider: config.provider, model: config.model, timeout: 15000, }); console.log(`Success with ${config.provider}`); return result; } catch (error: any) { console.warn( `${config.provider} failed: ${error.message}. Trying next...`, ); } } throw new Error("All providers failed"); } // ----------------------------------------------------------- // Usage // ----------------------------------------------------------- async function main() { // Compare providers on the same prompt await compareProviders("What are the three laws of thermodynamics?"); // Switch provider at runtime (e.g., from user config or CLI flag) const userPreference = process.env.AI_PROVIDER || "openai"; await generateWithProvider( "Summarize quantum computing in one paragraph.", userPreference, ); // Fallback chain const result = await generateWithFallback("Explain the CAP theorem."); console.log(result.content); } main(); ``` ## Explanation ### 1. Unified API Across Providers NeuroLink abstracts away provider-specific APIs. The same `input` object works with every provider: ```typescript // These three calls have identical structure -- only provider/model differ await neurolink.generate({ input: { text: prompt }, provider: "openai", model: "gpt-4o", }); await neurolink.generate({ input: { text: prompt }, provider: "anthropic", model: "claude-sonnet-4-20250514", }); await neurolink.generate({ input: { text: prompt }, provider: "google-ai", model: "gemini-2.5-flash", }); ``` ### 2. Provider Names and Aliases NeuroLink supports both canonical names and aliases: | Canonical Name | Aliases | | -------------- | ------------------------------------ | | `openai` | `gpt`, `chatgpt` | | `anthropic` | `claude` | | `google-ai` | `googleAiStudio`, `google`, `gemini` | | `vertex` | `googleVertex`, `google-vertex` | | `bedrock` | `amazonBedrock`, `aws-bedrock` | | `azure` | `azureOpenai`, `azure-openai` | | `mistral` | `mistralai` | | `litellm` | `lite-llm`, `lite` | | `ollama` | (none) | ### 3. Parallel Comparison with `Promise.allSettled` Use `Promise.allSettled` (not `Promise.all`) so that one provider's failure does not cancel the others: ```typescript const results = await Promise.allSettled( providers.map((config) => neurolink.generate({ ... })), ); ``` Each result is either `{ status: "fulfilled", value: ... }` or `{ status: "rejected", reason: ... }`. ### 4. Timeout for Fallback Set a `timeout` to prevent a slow provider from blocking the fallback chain: ```typescript await neurolink.generate({ input: { text: prompt }, provider: "openai", timeout: 15000, // 15 seconds }); ``` ## Variations ### Task-Based Routing Route different tasks to the best provider for each: ```typescript type TaskType = "code" | "creative" | "analysis" | "simple"; const TASK_ROUTING: Record = { code: { provider: "anthropic", model: "claude-sonnet-4-20250514" }, creative: { provider: "openai", model: "gpt-4o" }, analysis: { provider: "google-ai", model: "gemini-2.5-pro" }, simple: { provider: "google-ai", model: "gemini-2.5-flash" }, }; async function routeByTask(task: TaskType, prompt: string) { const neurolink = new NeuroLink(); const config = TASK_ROUTING[task]; return neurolink.generate({ input: { text: prompt }, provider: config.provider, model: config.model, }); } ``` ### Stream with Provider Switching The same pattern works for streaming: ```typescript async function streamFromProvider(prompt: string, provider: string) { const neurolink = new NeuroLink(); const result = await neurolink.stream({ input: { text: prompt }, provider, }); for await (const chunk of result.stream) { if ("content" in chunk && chunk.content) { process.stdout.write(chunk.content); } } console.log("\n"); } ``` ### A/B Testing Providers Run a percentage of traffic through different providers: ```typescript function selectProvider(): { provider: string; model: string } { const random = Math.random(); if (random < 0.7) { return { provider: "openai", model: "gpt-4o" }; // 70% of traffic } else if (random < 0.9) { return { provider: "anthropic", model: "claude-sonnet-4-20250514" }; // 20% } else { return { provider: "google-ai", model: "gemini-2.5-flash" }; // 10% } } async function generateABTest(prompt: string) { const neurolink = new NeuroLink(); const config = selectProvider(); const start = Date.now(); const result = await neurolink.generate({ input: { text: prompt }, provider: config.provider, model: config.model, }); // Log for analysis console.log( JSON.stringify({ provider: config.provider, model: config.model, responseTime: Date.now() - start, tokens: result.usage?.total, }), ); return result; } ``` ## Tips 1. **Default models**: If you omit the `model` field, each provider uses its default model. This is fine for quick testing but specify the model explicitly in production. 2. **Environment variables**: Each provider reads its API key from standard environment variables (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GOOGLE_AI_API_KEY`, etc.). Configure only the providers you need. 3. **Cost awareness**: Provider pricing varies significantly. Use cheaper models (e.g., `gemini-2.5-flash`, `gpt-4o-mini`) for simple tasks and reserve expensive models for complex reasoning. 4. **Consistency**: Different providers may produce different response styles. If you need consistent formatting, use a `systemPrompt` to enforce structure. ## See Also - [Multi-Provider Fallback](/docs/cookbook/multi-provider-fallback) - [Cost Optimization](/docs/cookbook/cost-optimization) - [Error Recovery Patterns](/docs/cookbook/error-recovery) - [Streaming with Retry Logic](/docs/cookbook/streaming-with-retry) --- ## Rate Limit Handling # Rate Limit Handling ## Problem AI providers enforce rate limits to prevent abuse and ensure fair usage. Exceeding these limits results in: - HTTP 429 errors - Request failures - Service disruption - Temporary bans Different providers have different limits: - OpenAI: 3,500 requests/min (paid tier) - Anthropic: 50 requests/min (free tier) - Google AI: 60 requests/min ## Solution Implement intelligent rate limiting with: 1. Token bucket algorithm 2. Request queuing 3. Automatic backoff 4. Per-provider limits 5. Request prioritization ## Code ```typescript type RateLimitConfig = { requestsPerMinute: number; burstSize?: number; retryAfter?: number; }; class RateLimiter { private queue: Array Promise> = []; private processing = false; private tokens: number; private lastRefill: number; private config: Required; constructor(config: RateLimitConfig) { this.config = { requestsPerMinute: config.requestsPerMinute, burstSize: config.burstSize || config.requestsPerMinute, retryAfter: config.retryAfter || 60000, }; this.tokens = this.config.burstSize; this.lastRefill = Date.now(); } /** * Refill tokens based on time elapsed */ private refillTokens() { const now = Date.now(); const elapsed = now - this.lastRefill; const tokensToAdd = (elapsed / 60000) * this.config.requestsPerMinute; this.tokens = Math.min(this.tokens + tokensToAdd, this.config.burstSize); this.lastRefill = now; } /** * Wait until a token is available */ private async waitForToken(): Promise { this.refillTokens(); if (this.tokens >= 1) { this.tokens -= 1; return; } // Calculate wait time for next token const tokensNeeded = 1 - this.tokens; const waitTime = (tokensNeeded / this.config.requestsPerMinute) * 60000; console.log( `⏳ Rate limit: waiting ${Math.ceil(waitTime)}ms for next token`, ); await new Promise((resolve) => setTimeout(resolve, waitTime)); this.tokens = 0; // Token consumed } /** * Execute a request with rate limiting */ async execute(fn: () => Promise): Promise { await this.waitForToken(); try { return await fn(); } catch (error: any) { // Handle rate limit error if (error.status === 429) { const retryAfter = error.headers?.["retry-after"] || this.config.retryAfter / 1000; console.log(`⚠️ Rate limit hit. Retrying after ${retryAfter}s`); // Reset tokens on rate limit this.tokens = 0; await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000)); return this.execute(fn); } throw error; } } } /** * Multi-provider rate limiter */ class ProviderRateLimiter { private limiters = new Map(); private neurolink: NeuroLink; constructor() { this.neurolink = new NeuroLink(); // Configure per-provider limits this.limiters.set( "openai", new RateLimiter({ requestsPerMinute: 3000, burstSize: 100 }), ); this.limiters.set( "anthropic", new RateLimiter({ requestsPerMinute: 50, burstSize: 10 }), ); this.limiters.set( "google-ai", new RateLimiter({ requestsPerMinute: 60, burstSize: 15 }), ); } /** * Generate with automatic rate limiting */ async generate( prompt: string, provider: string = "openai", options: any = {}, ) { const limiter = this.limiters.get(provider); if (!limiter) { throw new Error(`Unknown provider: ${provider}`); } return limiter.execute(async () => { const result = await this.neurolink.generate({ input: { text: prompt }, provider, ...options, }); console.log(`✅ Request completed (${provider})`); return result; }); } /** * Batch requests with rate limiting */ async batchGenerate(prompts: string[], provider: string = "openai") { const results = []; for (let i = 0; i `Question ${i + 1}: What is ${i + 1} + ${i + 1}?`); const results = await limiter.batchGenerate(prompts, "anthropic"); console.log(`\n✅ Completed ${results.length} requests`); } main(); ``` ## Explanation ### 1. Token Bucket Algorithm The rate limiter uses a token bucket: - **Bucket capacity**: `burstSize` (max requests in burst) - **Refill rate**: `requestsPerMinute / 60` tokens per second - **Token consumption**: 1 token per request This allows bursts while maintaining average rate. ### 2. Automatic Refill Tokens refill continuously based on elapsed time: ```typescript tokensToAdd = (elapsed_ms / 60000) * requestsPerMinute; ``` ### 3. Wait Strategy When no tokens available: - Calculate time until next token - Sleep for that duration - Consume token and proceed ### 4. 429 Error Handling When provider returns 429: - Read `Retry-After` header - Reset token bucket - Wait and retry automatically ### 5. Per-Provider Configuration Different providers have different limits. Configure each separately: | Provider | Free Tier | Paid Tier | Burst Size | | --------- | ---------- | ------------ | ---------- | | OpenAI | 3 req/min | 3500 req/min | 100 | | Anthropic | 50 req/min | 1000 req/min | 10 | | Google AI | 60 req/min | 1000 req/min | 15 | ## Variations ### Priority Queue Prioritize important requests: ```typescript type QueuedRequest = { fn: () => Promise; priority: number; timestamp: number; }; class PriorityRateLimiter extends RateLimiter { private queue: QueuedRequest[] = []; async executeWithPriority( fn: () => Promise, priority: number = 0, ): Promise { return new Promise((resolve, reject) => { this.queue.push({ fn: async () => { try { const result = await this.execute(fn); resolve(result); } catch (error) { reject(error); } }, priority, timestamp: Date.now(), }); // Sort by priority (higher first), then timestamp (earlier first) this.queue.sort((a, b) => b.priority !== a.priority ? b.priority - a.priority : a.timestamp - b.timestamp, ); this.processQueue(); }); } private async processQueue() { if (this.queue.length === 0) return; const request = this.queue.shift()!; await request.fn(); if (this.queue.length > 0) { this.processQueue(); } } } ``` ### Adaptive Rate Limiting Adjust limits based on errors: ```typescript class AdaptiveRateLimiter extends RateLimiter { private consecutiveErrors = 0; async execute(fn: () => Promise): Promise { try { const result = await super.execute(fn); this.consecutiveErrors = 0; // Reset on success return result; } catch (error: any) { if (error.status === 429) { this.consecutiveErrors++; // Reduce rate after repeated errors if (this.consecutiveErrors >= 3) { this.config.requestsPerMinute *= 0.8; console.log( `⚠️ Reducing rate to ${this.config.requestsPerMinute} req/min`, ); } } throw error; } } } ``` ### Distributed Rate Limiting with Redis For multi-instance deployments: ```typescript class RedisRateLimiter { private redis: RedisClientType; private key: string; private limit: number; private window: number; // seconds constructor( redis: RedisClientType, key: string, limit: number, window: number = 60, ) { this.redis = redis; this.key = key; this.limit = limit; this.window = window; } async execute(fn: () => Promise): Promise { const now = Date.now(); const windowStart = now - this.window * 1000; // Remove old entries await this.redis.zRemRangeByScore(this.key, 0, windowStart); // Count current requests const count = await this.redis.zCard(this.key); if (count >= this.limit) { const [oldestEntry] = await this.redis.zRangeWithScores(this.key, 0, 0); const waitTime = oldestEntry?.score ? oldestEntry.score + this.window * 1000 - now : 1000; console.log(`⏳ Rate limit: waiting ${waitTime}ms`); await new Promise((r) => setTimeout(r, waitTime)); return this.execute(fn); } // Add current request await this.redis.zAdd(this.key, [ { score: now, value: `${now}-${Math.random()}` }, ]); await this.redis.expire(this.key, this.window * 2); return fn(); } } ``` ## Best Practices 1. **Set conservative limits**: Start with 80% of provider's limit 2. **Monitor usage**: Track request patterns to optimize limits 3. **Use burst capacity**: Allow occasional spikes while maintaining average rate 4. **Implement backoff**: Exponential backoff on repeated rate limit errors 5. **Cache responses**: Reduce duplicate requests (see [Cost Optimization](/docs/cookbook/cost-optimization)) ## See Also - [Cost Optimization](/docs/cookbook/cost-optimization) - [Batch Processing](/docs/cookbook/batch-processing) - [Error Recovery](/docs/cookbook/error-recovery) - [Streaming with Retry](/docs/cookbook/streaming-with-retry) --- ## Streaming with Retry Logic # Streaming with Retry Logic ## Problem Network interruptions, temporary provider outages, and transient errors can cause streaming responses to fail mid-stream. Without retry logic, users experience incomplete responses and poor reliability. ## Solution Implement automatic retry with exponential backoff for streaming responses. Handle different failure scenarios: - Network timeouts - Connection drops - Provider rate limits - Transient API errors ## Code ```typescript type RetryConfig = { maxRetries: number; initialDelay: number; maxDelay: number; backoffMultiplier: number; }; async function streamWithRetry( neurolink: NeuroLink, prompt: string, config: RetryConfig = { maxRetries: 3, initialDelay: 1000, maxDelay: 10000, backoffMultiplier: 2, }, ) { let attempt = 0; let delay = config.initialDelay; while (attempt config.maxRetries) { console.error( `❌ Stream failed after ${attempt} attempts:`, error.message, ); throw error; } console.log( `⚠️ Stream interrupted (attempt ${attempt}/${config.maxRetries}). Retrying in ${delay}ms...`, ); await new Promise((resolve) => setTimeout(resolve, delay)); delay = Math.min(delay * config.backoffMultiplier, config.maxDelay); } } } // Usage example async function main() { const neurolink = new NeuroLink(); try { const response = await streamWithRetry( neurolink, "Write a detailed explanation of quantum computing", { maxRetries: 5, initialDelay: 500, maxDelay: 8000, backoffMultiplier: 2, }, ); console.log("Final response length:", response.length); } catch (error) { console.error("Failed after all retries:", error); } } main(); ``` ## Explanation ### 1. Retry Configuration The `RetryConfig` interface defines retry behavior: - `maxRetries`: Maximum number of retry attempts - `initialDelay`: Starting delay between retries (milliseconds) - `maxDelay`: Maximum delay to prevent excessive waiting - `backoffMultiplier`: How quickly delays increase (exponential backoff) ### 2. Retry Loop The while loop attempts streaming up to `maxRetries + 1` times (initial attempt + retries). ### 3. Error Classification Not all errors should trigger retries: - **Retryable**: Network errors, rate limits, temporary service issues - **Non-retryable**: Authentication errors, invalid requests, missing models ### 4. Exponential Backoff Each retry waits longer than the previous: - First retry: 1000ms - Second retry: 2000ms - Third retry: 4000ms - Fourth retry: 8000ms (capped at maxDelay) This prevents overwhelming the provider and gives transient issues time to resolve. ### 5. Stream Consumption The code accumulates chunks to provide a complete response even if earlier attempts partially succeeded. ## Variations ### Resume from Last Position For very long streams, resume from the last received position: ```typescript async function streamWithResume( neurolink: NeuroLink, prompt: string, onProgress?: (text: string) => void, ) { let accumulated = ""; let attempt = 0; const maxRetries = 3; while (attempt maxRetries) throw error; await new Promise((r) => setTimeout(r, 1000 * attempt)); } } } ``` ### Circuit Breaker Pattern Prevent repeated failures with a circuit breaker: ```typescript class StreamCircuitBreaker { private failures = 0; private lastFailureTime = 0; private readonly threshold = 5; private readonly resetTimeout = 60000; // 1 minute async executeStream(fn: () => Promise) { // Check if circuit is open if (this.failures >= this.threshold) { const timeSinceFailure = Date.now() - this.lastFailureTime; if (timeSinceFailure neurolink.stream({ input: { text: prompt } }), ); ``` ### Provider Fallback on Retry Try different providers on subsequent retries: ```typescript const providers = ["openai", "anthropic", "google-ai"] as const; async function streamWithProviderFallback(prompt: string) { for (const provider of providers) { try { console.log(`Trying provider: ${provider}`); const stream = await neurolink.stream({ input: { text: prompt }, provider, }); let response = ""; for await (const chunk of stream) { if (chunk.type === "content-delta") { response += chunk.delta; } } console.log(`✅ Success with ${provider}`); return response; } catch (error) { console.log(`❌ ${provider} failed, trying next...`); continue; } } throw new Error("All providers failed"); } ``` ## See Also - [Error Recovery Patterns](/docs/cookbook/error-recovery) - [Multi-Provider Fallback](/docs/cookbook/multi-provider-fallback) - [Rate Limit Handling](/docs/cookbook/rate-limit-handling) - [Streaming API Reference](/docs/sdk/api-reference) --- ## Structured Output with JSON Schema # Structured Output with JSON Schema ## Problem AI models return unstructured text by default: - Inconsistent formatting - Manual parsing required - Type safety missing - Error-prone extraction - Difficult validation Applications need structured, typed data: - JSON objects for APIs - Type-safe TypeScript interfaces - Database records - Form data ## Solution Use JSON schema to enforce structured output: 1. Define TypeScript interfaces 2. Generate JSON schemas 3. Validate responses 4. Type-safe parsing 5. Error handling ## Code ```typescript // Define your data structure type ProductReview = { productName: string; rating: number; sentiment: "positive" | "negative" | "neutral"; pros: string[]; cons: string[]; recommendationScore: number; summary: string; }; // JSON Schema for validation const productReviewSchema = { type: "object", properties: { productName: { type: "string", description: "Name of the product being reviewed", }, rating: { type: "number", minimum: 1, maximum: 5, description: "Rating from 1 to 5 stars", }, sentiment: { type: "string", enum: ["positive", "negative", "neutral"], description: "Overall sentiment of the review", }, pros: { type: "array", items: { type: "string" }, description: "List of positive aspects", }, cons: { type: "array", items: { type: "string" }, description: "List of negative aspects", }, recommendationScore: { type: "number", minimum: 0, maximum: 100, description: "Likelihood to recommend (0-100)", }, summary: { type: "string", description: "Brief summary of the review", }, }, required: [ "productName", "rating", "sentiment", "pros", "cons", "recommendationScore", "summary", ], }; class StructuredOutputGenerator { private neurolink: NeuroLink; constructor() { this.neurolink = new NeuroLink(); } /** * Extract structured data from text */ async extractStructured( prompt: string, schema: any, provider: string = "openai", ): Promise { const result = await this.neurolink.generate({ input: { text: prompt }, provider, structuredOutput: { type: "json", schema, }, }); // Parse and validate JSON try { const parsed = JSON.parse(result.content); this.validateAgainstSchema(parsed, schema); return parsed as T; } catch (error: any) { throw new Error(`Failed to parse structured output: ${error.message}`); } } /** * Basic schema validation */ private validateAgainstSchema(data: any, schema: any): void { // Check required fields if (schema.required) { for (const field of schema.required) { if (!(field in data)) { throw new Error(`Missing required field: ${field}`); } } } // Check types for (const [key, value] of Object.entries(data)) { const fieldSchema = schema.properties?.[key]; if (!fieldSchema) continue; const actualType = Array.isArray(value) ? "array" : typeof value; if (fieldSchema.type !== actualType) { throw new Error( `Field "${key}" has wrong type. Expected ${fieldSchema.type}, got ${actualType}`, ); } // Validate enum if (fieldSchema.enum && !fieldSchema.enum.includes(value)) { throw new Error( `Field "${key}" must be one of: ${fieldSchema.enum.join(", ")}`, ); } // Validate number ranges if (fieldSchema.type === "number") { if (fieldSchema.minimum !== undefined && value = ${fieldSchema.minimum}`); } if (fieldSchema.maximum !== undefined && value > fieldSchema.maximum) { throw new Error(`Field "${key}" must be ( prompt: string, schema: any, maxRetries: number = 3, ): Promise { let lastError: Error | null = null; for (let attempt = 1; attempt (prompt, schema); } catch (error: any) { lastError = error; console.error(`❌ Attempt ${attempt} failed: ${error.message}`); if (attempt ( `Extract a structured review from this text: ${reviewText}`, productReviewSchema, ); console.log("✅ Extracted Review:"); console.log(JSON.stringify(review, null, 2)); } // Example 2: Contact Information Extraction type ContactInfo = { name: string; email: string; phone?: string; company?: string; role?: string; }; const contactSchema = { type: "object", properties: { name: { type: "string" }, email: { type: "string", format: "email" }, phone: { type: "string" }, company: { type: "string" }, role: { type: "string" }, }, required: ["name", "email"], }; async function example2_ContactExtraction() { const generator = new StructuredOutputGenerator(); const text = ` Hi, I'm John Smith, Senior Engineer at TechCorp Inc. You can reach me at john.smith@techcorp.com or call me at +1-555-0123. Looking forward to connecting! `; const contact = await generator.extractStructured( `Extract contact information from: ${text}`, contactSchema, ); console.log("✅ Extracted Contact:"); console.log(contact); } // Example 3: Database Record Generation type UserProfile = { userId: string; username: string; age: number; interests: string[]; subscriptionTier: "free" | "basic" | "premium"; joinedDate: string; }; const userProfileSchema = { type: "object", properties: { userId: { type: "string", pattern: "^[A-Z0-9]{8}$" }, username: { type: "string", minLength: 3, maxLength: 20 }, age: { type: "number", minimum: 13, maximum: 120 }, interests: { type: "array", items: { type: "string" } }, subscriptionTier: { type: "string", enum: ["free", "basic", "premium"] }, joinedDate: { type: "string", format: "date" }, }, required: [ "userId", "username", "age", "interests", "subscriptionTier", "joinedDate", ], }; async function example3_DatabaseRecord() { const generator = new StructuredOutputGenerator(); const userData = ` Create a user profile for Sarah Chen, a 28-year-old photography enthusiast who also loves hiking and cooking. She's on our premium plan and joined last month. `; const profile = await generator.extractStructured( userData, userProfileSchema, "anthropic", // Claude handles structured output well ); console.log("✅ User Profile:"); console.log(profile); } // Main async function main() { console.log("=== Example 1: Product Review ===\n"); await example1_ProductReview(); console.log("\n=== Example 2: Contact Extraction ===\n"); await example2_ContactExtraction(); console.log("\n=== Example 3: Database Record ===\n"); await example3_DatabaseRecord(); } main(); ``` ## Explanation ### 1. JSON Schema Definition Define structure upfront: ```typescript const schema = { type: "object", properties: { field: { type: "string" }, }, required: ["field"], }; ``` ### 2. Type Safety Use TypeScript interfaces for compile-time checking: ```typescript type MyData = { field: string; }; const data = await extract(prompt, schema); // data.field is typed as string ``` ### 3. Validation Validate parsed JSON against schema: - Required fields present - Correct types - Enum values valid - Number ranges respected ### 4. Error Handling Retry with enhanced prompt on validation failure: ```typescript prompt += `\nPrevious failed: ${error.message}`; ``` ### 5. Provider Selection Different providers handle structured output differently: - **OpenAI**: Excellent JSON mode - **Anthropic**: Good with clear schemas - **Google AI**: NOTE - Cannot use tools with structured output ## Variations ### Nested Objects Handle complex nested structures: ```typescript type Company = { name: string; employees: Array; }; const companySchema = { type: "object", properties: { name: { type: "string" }, employees: { type: "array", items: { type: "object", properties: { name: { type: "string" }, role: { type: "string" }, department: { type: "object", properties: { name: { type: "string" }, budget: { type: "number" }, }, required: ["name", "budget"], }, }, required: ["name", "role", "department"], }, }, }, required: ["name", "employees"], }; ``` ### Streaming Structured Output Stream and validate incrementally: ```typescript async function streamStructuredOutput( prompt: string, schema: any, ): Promise { let buffer = ""; const stream = await neurolink.stream({ input: { text: prompt }, structuredOutput: { type: "json", schema }, }); for await (const chunk of stream) { if (chunk.type === "content-delta") { buffer += chunk.delta; process.stdout.write(chunk.delta); } } return JSON.parse(buffer) as T; } ``` ### Union Types Handle multiple possible schemas: ```typescript type Response = SuccessResponse | ErrorResponse; type SuccessResponse = { status: "success"; data: any; }; type ErrorResponse = { status: "error"; error: string; code: number; }; async function parseResponse(text: string): Promise { const result = await generator.extractStructured(text, responseSchema); if (result.status === "success") { return result as SuccessResponse; } else { return result as ErrorResponse; } } ``` ### Schema from TypeScript Auto-generate schemas from interfaces: ```typescript const UserSchema = z.object({ name: z.string(), age: z.number().min(0).max(120), email: z.string().email(), }); const jsonSchema = zodToJsonSchema(UserSchema); const user = await generator.extractStructured>( prompt, jsonSchema, ); ``` ## Use Cases | Use Case | Schema Complexity | Recommended Provider | | ------------------ | ----------------- | -------------------- | | Data extraction | Simple | OpenAI, Anthropic | | Form filling | Medium | OpenAI | | API responses | Medium | OpenAI, Google AI | | Database records | Complex | OpenAI | | Classification | Simple | Any provider | | Sentiment analysis | Simple | Anthropic | ## Best Practices 1. **Define schemas upfront**: Don't rely on prompt engineering alone 2. **Use TypeScript types**: Compile-time safety prevents runtime errors 3. **Validate responses**: Don't trust AI output blindly 4. **Retry on failure**: Validation errors can be recovered 5. **Test schemas**: Verify with sample data before production 6. **Keep schemas simple**: Complex nesting reduces accuracy ## See Also - [Batch Processing](/docs/cookbook/batch-processing) - [Error Recovery](/docs/cookbook/error-recovery) - [API Reference - Generate Method](/docs/sdk/api-reference) - [Provider Comparison](/docs/reference/provider-comparison) --- ## Tool Chaining with MCP # Tool Chaining with MCP ## Problem Complex tasks require multiple MCP tool calls in sequence: - Search → Read → Analyze → Write - Query database → Process → Store results - Fetch data → Transform → Send notification Manually orchestrating tool calls is: - Error-prone - Difficult to manage state - Hard to handle failures - Not reusable ## Solution Implement intelligent tool chaining with: 1. Automatic tool selection 2. State management 3. Error recovery 4. Result validation 5. Chain composition ## Code ```typescript type ChainStep = { toolName: string; args: Record; validateResult?: (result: any) => boolean; onError?: (error: Error) => "retry" | "skip" | "abort"; }; type ChainContext = { steps: ChainStep[]; results: any[]; currentStep: number; metadata: Record; }; class ToolChain { private neurolink: NeuroLink; private context: ChainContext; constructor() { this.neurolink = new NeuroLink({ mcpServers: { filesystem: { command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "."], }, github: { command: "npx", args: ["-y", "@modelcontextprotocol/server-github"], env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN || "", }, }, }, }); this.context = { steps: [], results: [], currentStep: 0, metadata: {}, }; } /** * Add step to chain */ addStep(step: ChainStep): this { this.context.steps.push(step); return this; // Fluent interface } /** * Execute tool chain */ async execute(): Promise { const errors: Error[] = []; console.log( ` Executing chain with ${this.context.steps.length} steps...\n`, ); for (let i = 0; i { // Replace placeholders in args with previous results const processedArgs = this.processArgs(step.args); // Use AI to execute tool const result = await this.neurolink.generate({ input: { text: `Execute the tool "${step.toolName}" with these arguments: ${JSON.stringify(processedArgs)}`, }, enableTools: true, }); return this.extractToolResult(result); } /** * Process args to replace placeholders with previous results */ private processArgs(args: Record): Record { const processed: Record = {}; for (const [key, value] of Object.entries(args)) { if (typeof value === "string" && value.startsWith("$")) { // Reference to previous result const stepIndex = parseInt(value.slice(1)); processed[key] = this.context.results[stepIndex]; } else { processed[key] = value; } } return processed; } /** * Extract tool result from AI response */ private extractToolResult(response: any): any { // Implementation depends on response format return response.toolResults?.[0] || response.content; } /** * Get chain context */ getContext(): ChainContext { return this.context; } /** * Reset chain */ reset(): this { this.context = { steps: [], results: [], currentStep: 0, metadata: {}, }; return this; } } /** * Pre-built chain templates */ class ChainTemplates { /** * Search → Read → Summarize chain */ static searchAnalyzeChain(query: string, maxFiles: number = 3): ToolChain { const chain = new ToolChain(); return chain .addStep({ toolName: "search_files", args: { query, max_results: maxFiles }, }) .addStep({ toolName: "read_file", args: { path: "$0" }, // Use result from step 0 }) .addStep({ toolName: "analyze_content", args: { content: "$1" }, }); } /** * Fetch → Process → Save chain */ static fetchProcessSaveChain(url: string, outputPath: string): ToolChain { const chain = new ToolChain(); return chain .addStep({ toolName: "fetch_url", args: { url }, validateResult: (result) => result.status === 200, }) .addStep({ toolName: "process_data", args: { data: "$0" }, }) .addStep({ toolName: "write_file", args: { path: outputPath, content: "$1", }, onError: () => "retry", }); } /** * GitHub workflow: Create issue → Create branch → Push → Create PR */ static githubWorkflowChain( repo: string, issueTitle: string, branchName: string, ): ToolChain { const chain = new ToolChain(); return chain .addStep({ toolName: "github_create_issue", args: { repo, title: issueTitle, body: "Auto-generated issue", }, }) .addStep({ toolName: "github_create_branch", args: { repo, branch: branchName, from: "main", }, }) .addStep({ toolName: "github_push_files", args: { repo, branch: branchName, files: [], message: `Fixes #$0`, // Reference issue from step 0 }, }) .addStep({ toolName: "github_create_pr", args: { repo, title: `Fix: ${issueTitle}`, head: branchName, base: "main", body: `Closes #$0`, }, }); } } // Usage Example 1: File Processing Chain async function example1_FileProcessing() { const chain = new ToolChain(); chain .addStep({ toolName: "list_directory", args: { path: "./docs" }, }) .addStep({ toolName: "read_file", args: { path: "$0" }, // Read first file from listing validateResult: (content) => content.length > 0, }) .addStep({ toolName: "analyze_content", args: { content: "$1" }, }); const result = await chain.execute(); console.log("\n=== Results ==="); console.log("Success:", result.success); console.log("Results:", result.results); } // Example 2: Data Pipeline Chain async function example2_DataPipeline() { const chain = new ToolChain(); chain .addStep({ toolName: "query_database", args: { query: "SELECT * FROM users WHERE active = true", }, }) .addStep({ toolName: "transform_data", args: { data: "$0" }, onError: () => "skip", // Skip transformation errors }) .addStep({ toolName: "send_notification", args: { message: "Data pipeline completed: $1", }, }); await chain.execute(); } // Example 3: Using Pre-built Templates async function example3_Templates() { // Search and analyze const searchChain = ChainTemplates.searchAnalyzeChain("authentication", 5); await searchChain.execute(); // GitHub workflow const githubChain = ChainTemplates.githubWorkflowChain( "myorg/myrepo", "Fix authentication bug", "fix/auth-bug", ); await githubChain.execute(); } // Main async function main() { console.log("=== Example 1: File Processing ===\n"); await example1_FileProcessing(); console.log("\n=== Example 2: Data Pipeline ===\n"); await example2_DataPipeline(); console.log("\n=== Example 3: Templates ===\n"); await example3_Templates(); } main(); ``` ## Explanation ### 1. Fluent Interface Chain steps with method chaining: ```typescript chain .addStep({...}) .addStep({...}) .addStep({...}); ``` ### 2. Result References Reference previous step results: ```typescript args: { content: "$1"; } // Use result from step 1 ``` ### 3. Validation Validate step results: ```typescript validateResult: (result) => result.status === 200; ``` ### 4. Error Handling Control flow on errors: - **"abort"**: Stop chain - **"retry"**: Retry current step - **"skip"**: Continue to next step ### 5. Reusable Templates Pre-built chains for common patterns: ```typescript ChainTemplates.searchAnalyzeChain(query); ``` ## Variations ### Conditional Chains Branch based on results: ```typescript class ConditionalChain extends ToolChain { addConditionalStep( condition: (context: ChainContext) => boolean, trueStep: ChainStep, falseStep: ChainStep, ) { return this.addStep({ ...trueStep, args: condition(this.context) ? trueStep.args : falseStep.args, }); } } // Usage chain.addConditionalStep( (ctx) => ctx.results[0].count > 100, { toolName: "process_large", args: {} }, { toolName: "process_small", args: {} }, ); ``` ### Parallel Chains Execute independent chains in parallel: ```typescript async function executeParallel(chains: ToolChain[]) { const results = await Promise.all(chains.map((chain) => chain.execute())); return { success: results.every((r) => r.success), results: results.map((r) => r.results), errors: results.flatMap((r) => r.errors), }; } // Usage await executeParallel([ ChainTemplates.searchAnalyzeChain("auth"), ChainTemplates.searchAnalyzeChain("database"), ]); ``` ### Loop Chains Repeat steps until condition met: ```typescript class LoopChain extends ToolChain { async executeLoop( step: ChainStep, condition: (result: any) => boolean, maxIterations: number = 10, ) { let iterations = 0; let result: any; while (iterations result.status === "complete", 20, ); ``` ### Chain Composition Combine multiple chains: ```typescript class CompositeChain { private chains: ToolChain[] = []; add(chain: ToolChain): this { this.chains.push(chain); return this; } async execute() { const results = []; for (const chain of this.chains) { const result = await chain.execute(); results.push(result); if (!result.success) { break; // Stop on first failure } } return results; } } ``` ## Common Patterns ### Data Processing Pipeline ``` Fetch → Validate → Transform → Store → Notify ``` ### Content Workflow ``` Search → Read → Analyze → Summarize → Publish ``` ### GitHub Automation ``` Create Issue → Create Branch → Commit → Push → Create PR ``` ### Monitoring Pipeline ``` Query Metrics → Analyze → Alert → Create Ticket → Notify ``` ## Best Practices 1. **Keep chains short**: 3-5 steps maximum 2. **Validate early**: Check results at each step 3. **Handle errors**: Define recovery strategy 4. **Use templates**: Standardize common patterns 5. **Log extensively**: Track chain execution 6. **Test chains**: Verify each step independently 7. **Document dependencies**: Clear step relationships ## See Also - [MCP Integration Guide](/docs/features/mcp-tools-showcase) - [Error Recovery](/docs/cookbook/error-recovery) - [Batch Processing](/docs/cookbook/batch-processing) - [SDK Custom Tools](/docs/sdk/custom-tools) --- # MCP Integration ## MCP Foundation (Model Context Protocol) # MCP Foundation (Model Context Protocol) **NeuroLink** features a groundbreaking **MCP Foundation** that transforms NeuroLink from an AI SDK into a **Universal AI Development Platform** while maintaining the simple factory method interface. ## Production Achievement **MCP Foundation Production Ready: 27/27 Tests Passing (100% Success Rate)** - ✅ **Factory-First Architecture**: MCP tools work internally, users see simple factory methods - ✅ **Lighthouse Compatible**: 99% compatible with existing MCP tools and servers - ✅ **Enterprise Grade**: Rich context, permissions, tool orchestration, analytics - ✅ **Performance Validated**: 0-11ms tool execution (target: \; parentContext?: MCPContext; toolChain: string[]; performance: PerformanceMetrics; // + 8 more fields }; ``` #### Tool Registry (5/5 tests ✅) - **Tool discovery**: Automatic detection of available tools - **Registration system**: Dynamic tool registration and management - **Execution tracking**: Statistics and performance monitoring - **Filtering and search**: Find tools by capability and metadata ```typescript // Registry tracks all available tools with metadata const registry = { generate: { description: "Generate AI text content", schema: { /* JSON Schema */ }, provider: "aiCoreServer", executionCount: 1247, averageLatency: 850, }, }; ``` #### Tool Orchestration (4/4 tests ✅) - **Single tool execution**: Direct tool invocation with error handling - **Sequential pipelines**: Chain tools together for complex workflows - **Error recovery**: Automatic retry and fallback mechanisms - **Performance monitoring**: Track execution time and success rates ```typescript // Orchestrate complex workflows with multiple tools const pipeline = [ { tool: "analyze-ai-usage", params: { timeframe: "24h" } }, { tool: "optimize-prompt-parameters", params: { prompt: "user-input" } }, { tool: "generate", params: { optimizedParams: true } }, ]; ``` #### AI Provider Integration (6/6 tests ✅) - **Core AI tools**: 3 essential tools for AI operations - **Schema validation**: JSON Schema validation for all inputs/outputs - **Provider abstraction**: Unified interface across all AI providers - **Error standardization**: Consistent error handling and reporting (now with specific "model not found" errors for Ollama) ```typescript // AI Provider MCP Tools const aiTools = [ "generate", // Text generation with provider selection "select-provider", // Automatic provider selection "check-provider-status", // Provider connectivity and health ]; ``` #### Integration Tests (3/3 tests ✅) - **End-to-end workflow validation**: Complete user journey testing - **Performance benchmarking**: Tool execution time verification - **Error scenario testing**: Comprehensive failure mode validation - **Multi-tool pipeline testing**: Complex workflow verification ## Performance Metrics ### Tool Execution Performance - **Individual Tools**: 0-11ms execution time (target: \<100ms) ✅ - **Pipeline Execution**: 22ms for 2-step sequence ✅ - **Error Handling**: Graceful failures with comprehensive logging ✅ - **Context Management**: Rich context with minimal overhead ✅ ### Enterprise Features - **Rich Context**: 15+ fields including session, user, provider, permissions - **Security Framework**: Permission-based access control and validation - **Performance Analytics**: Detailed execution metrics and monitoring - **Error Recovery**: Automatic retry and fallback mechanisms ## Tool Ecosystem ### Current MCP Tools (10 Total) #### Core AI Tools (3) 1. **`generate`** - AI text generation with provider selection 2. **`select-provider`** - Automatic best provider selection 3. **`check-provider-status`** - Provider connectivity and health checks #### AI Analysis Tools (3) 4. **`analyze-ai-usage`** - Usage patterns and cost optimization 5. **`benchmark-provider-performance`** - Provider performance comparison 6. **`optimize-prompt-parameters`** - Parameter optimization for better output #### AI Workflow Tools (4) 7. **`generate-test-cases`** - Comprehensive test case generation 8. **`refactor-code`** - AI-powered code optimization 9. **`generate-documentation`** - Automatic documentation creation 10. **`debug-ai-output`** - AI output validation and debugging ### Tool Categories - **Production Ready**: All 10 tools with comprehensive testing - **Enterprise Grade**: Rich context, permissions, error handling - **Performance Optimized**: Sub-millisecond execution for most tools - **Lighthouse Compatible**: Standard MCP protocol compliance ## Lighthouse Compatibility ### Migration Strategy - **99% Compatible**: Existing Lighthouse tools work with minimal changes - **Import Statement Updates**: Change import statements, functionality preserved - **Enhanced Context**: Lighthouse tools gain rich context automatically - **Performance Improvements**: Better error handling and monitoring ```typescript // Before (Lighthouse) // After (NeuroLink MCP) ``` ### Compatibility Features - **Standard MCP Protocol**: Full compliance with MCP 2024-11-05 specification - **Transport Support**: stdio, SSE, WebSocket, and HTTP transports supported - **HTTP Transport**: Remote MCP servers with authentication, retry, and rate limiting - **Schema Validation**: JSON Schema validation for all tool interactions - **Error Handling**: Standardized error responses and recovery ## ️ Security and Permissions ### Permission Framework - **Role-Based Access**: Different permission levels for different user types - **Tool-Level Security**: Granular permissions for individual tools - **Context Isolation**: Secure context boundaries between operations - **Audit Logging**: Comprehensive logging for security monitoring ```typescript // Permission-based tool execution const context = { userId: "user123", permissions: ["ai:generate", "ai:analyze"], securityLevel: "enterprise", }; ``` ### Security Features - **Input Validation**: Comprehensive validation of all tool inputs - **Output Sanitization**: Clean and validate all tool outputs - **Context Boundaries**: Prevent information leakage between contexts - **Error Information**: Sanitized error messages without sensitive data ## Monitoring and Analytics ### Performance Tracking - **Execution Metrics**: Track tool execution time and success rates - **Usage Analytics**: Monitor tool usage patterns and trends - **Error Analysis**: Comprehensive error tracking and analysis - **Performance Optimization**: Identify and optimize slow operations ### Monitoring Features - **Real-time Dashboards**: Live monitoring of tool performance - **Historical Analysis**: Long-term trend analysis and reporting - **Alert System**: Automated alerts for performance issues - **Usage Reports**: Detailed usage and cost reporting ## Lighthouse Integration: 60+ Production-Ready Tools ### Direct Import Approach (1-2 weeks) **BREAKTHROUGH**: Instead of migrating 30+ tools (8-10 weeks), we now **directly import** Lighthouse's 60+ production-ready tools into NeuroLink. Planned: `registerLighthouseServer()` is not in the current release. Today a server is added with `addExternalMCPServer()` or `addInMemoryMCPServer()`. ```typescript planned // Import Lighthouse tools directly // Register in NeuroLink with one method call const neurolink = new NeuroLink(); neurolink.registerLighthouseServer(juspayAnalyticsServer, { contextMapping: { shopId: "context.shopId", merchantId: "context.merchantId", }, }); // AI can now answer e-commerce questions using real production data const result = await neurolink.generate({ input: { text: "What were our payment success rates last month?" }, // AI automatically discovers and uses juspay_get-success-rate-by-time tool }); ``` ### Available Lighthouse Tools (60+ Tools) #### **Payment Analytics Tools:** - `get-success-rate-by-time` - Payment success rates over time - `get-payment-method-wise-sr` - Success rates by payment method - `get-transaction-trends` - Transaction trend analysis - `get-failure-transactional-data` - Failed transaction analysis - `get-gmv-order-value-payment-wise` - Revenue by payment method #### **E-commerce Analytics Tools:** - `get-conversion-rates` - Shop conversion metrics - `process-analytics-data` - Process raw analytics - `get-order-stats` - Order statistics and trends - `get-merchant-data` - Merchant information - `get-shop-performance` - Shop performance metrics #### **Platform Integration Tools:** - **Shopify**: Complete Shopify store integration - **WooCommerce**: WooCommerce integration - **Magento**: Magento store integration ### Integration Benefits - **Zero Duplication**: Import existing tools, don't recreate - **Auto-Updates**: Lighthouse improvements flow to NeuroLink automatically - **Battle-Tested**: Production-ready tools with real API integrations - **Minimal Maintenance**: Lighthouse team maintains tool implementations - **Rich Context**: Full business context (shopId, merchantId, etc.) ** Complete Integration Guide**: [docs/lighthouse-unified-integration.md](/docs/lighthouse-unified-integration) ## Technical Implementation Details ### MCP Server Architecture ```typescript // Core MCP server structure src/lib/mcp/ ├── factory.ts # createMCPServer() - Lighthouse compatible ├── context-manager.ts # Rich context (15+ fields) + tool chain tracking ├── registry.ts # Tool discovery, registration, execution + statistics ├── orchestrator.ts # Single tools + sequential pipelines + error handling └── servers/aiProviders/ # AI Core Server with 3 tools integrated └── aiCoreServer.ts # generate, select-provider, check-provider-status ``` ### Context Flow 1. **Context Creation**: Rich context with user, session, and permission data 2. **Tool Registration**: Tools register with metadata and capabilities 3. **Execution Request**: Tools execute with full context and validation 4. **Result Processing**: Results processed with context and performance tracking 5. **Context Cleanup**: Automatic cleanup and resource management ### Error Handling Strategy - **Graceful Degradation**: Tools continue working even with partial failures - **Comprehensive Logging**: Detailed logging for debugging and monitoring - **Recovery Mechanisms**: Automatic retry and fallback for failed operations - **Error Standardization**: Consistent error formats across all tools ## Related Documentation - **[Main README](/docs/)** - Project overview and quick start - **[AI Analysis Tools](/docs/ai-analysis-tools)** - AI optimization and analysis tools - **[AI Workflow Tools](/docs/ai-workflow-tools)** - Development lifecycle tools - **[MCP Integration Guide](/docs/mcp/integration)** - Complete MCP setup and usage - **[API Reference](/docs/sdk/api-reference)** - Complete TypeScript API --- **Universal AI Development Platform** - MCP Foundation enables unlimited extensibility while preserving the simple interface developers love. --- ## MCP Configuration Locations Across AI Development Tools # MCP Configuration Locations Across AI Development Tools This document provides a comprehensive guide to where different AI development tools store their Model Context Protocol (MCP) configurations. ## Summary of Common Patterns Most AI development tools store MCP configurations in JSON files with a common structure: ```json { "mcpServers": { "server-name": { "command": "node", "args": ["path/to/server.js"], "env": { "KEY": "value" } } } } ``` The most common configuration keys are: - `mcpServers` (most common) - `servers` (alternative) - `mcp.servers` (nested in settings) ## Tool-Specific Configuration Locations ### 1. Claude Desktop - **Location**: `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json` - **Linux**: `~/.config/Claude/claude_desktop_config.json` - **Config Key**: `mcpServers` or `mcp_servers` ### 2. Cline AI Coder (VS Code Extension) - **Location**: VS Code extension globalStorage - macOS: `~/Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json` - Linux: `~/.config/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json` - Windows: `%APPDATA%\Code\User\globalStorage\saoudrizwan.claude-dev\settings\cline_mcp_settings.json` - **Config Key**: `mcpServers` or `servers` ### 3. VS Code - **Workspace Configuration**: - `.vscode/mcp.json` (dedicated MCP file) - `.vscode/settings.json` (in `mcp.servers` section) - **Global Configuration**: - macOS: `~/Library/Application Support/Code/User/settings.json` - Linux: `~/.config/Code/User/settings.json` - Windows: `%APPDATA%\Code\User\settings.json` - **Config Key**: `mcpServers`, `servers`, or `mcp.servers` (in settings.json) ### 4. Cursor - **Global**: `~/.cursor/mcp.json` - **Project**: `.cursor/mcp.json` - **Config Key**: `mcpServers` or `servers` ### 5. Windsurf - **Location**: `~/.codeium/windsurf/mcp_config.json` - **Config Key**: `mcpServers` or `servers` ### 6. Continue Dev - **Global**: `~/.continue/config.json` - **Project**: `.continue/config.json` - **Config Key**: `mcpServers` or `contextProviders.mcp` ### 7. Aider - **Location**: `~/.aider/config.json` or `~/.aider/aider.conf` - **Config Key**: `mcp_servers` ### 8. Generic/Project-Level Configurations Many tools also check for generic MCP configuration files in the project root: - `mcp.json` - `.mcp-config.json` - `mcp_config.json` - `.mcp-servers.json` ## Common Configuration Structure Most tools follow a similar JSON structure: ```json { "mcpServers": { "filesystem": { "command": "npx", "args": [ "@modelcontextprotocol/server-filesystem", "/path/to/allowed/directory" ] }, "github": { "command": "npx", "args": ["@modelcontextprotocol/server-github"], "env": { "GITHUB_TOKEN": "your-github-token" } }, "custom-server": { "command": "node", "args": ["/path/to/custom/server.js"], "cwd": "/path/to/working/directory", "env": { "CUSTOM_VAR": "value" } } } } ``` ## HTTP Transport Configuration For remote MCP servers using HTTP/Streamable HTTP transport: ```json { "mcpServers": { "remote-api": { "transport": "http", "url": "https://api.example.com/mcp", "headers": { "Authorization": "Bearer YOUR_TOKEN" }, "httpOptions": { "connectionTimeout": 30000, "requestTimeout": 60000, "idleTimeout": 120000, "keepAliveTimeout": 30000 }, "retryConfig": { "maxAttempts": 3, "initialDelay": 1000, "maxDelay": 30000, "backoffMultiplier": 2 }, "rateLimiting": { "requestsPerMinute": 60, "maxBurst": 10, "useTokenBucket": true } }, "oauth-protected-api": { "transport": "http", "url": "https://api.secure.com/mcp", "auth": { "type": "oauth2", "oauth": { "clientId": "your-client-id", "clientSecret": "your-client-secret", "authorizationUrl": "https://auth.provider.com/authorize", "tokenUrl": "https://auth.provider.com/token", "redirectUrl": "http://localhost:8080/callback", "scope": "mcp:read mcp:write", "usePKCE": true } } } } } ``` ### HTTP Configuration Options | Option | Type | Description | | -------------- | ------ | -------------------------------------------- | | `transport` | string | Must be `"http"` for HTTP transport | | `url` | string | Remote MCP endpoint URL | | `headers` | object | Custom HTTP headers (e.g., Authorization) | | `httpOptions` | object | Connection timeout settings | | `retryConfig` | object | Retry with exponential backoff | | `rateLimiting` | object | Rate limiting configuration | | `auth` | object | OAuth 2.1, Bearer, or API key authentication | See [MCP HTTP Transport Guide](/docs/mcp/http-transport) for complete documentation. ## Key Observations 1. **Common Pattern**: Almost all tools use JSON files with an `mcpServers` object 2. **Location Hierarchy**: Tools typically check in this order: - Project/workspace specific configs - User/global configs - Default/fallback configs 3. **Platform Differences**: - macOS: Often uses `~/Library/Application Support/` - Linux: Typically uses `~/.config/` - Windows: Usually uses `%APPDATA%` 4. **Extension Storage**: VS Code extensions (like Cline) store configs in VS Code's globalStorage ## Auto-Discovery Priority When multiple configurations exist, tools typically prioritize in this order: 1. Workspace/project-specific configurations (highest priority) 2. Tool-specific global configurations 3. Generic project configurations (lowest priority) ## Best Practices 1. **Project-Specific Servers**: Use `.vscode/mcp.json` or similar for project-specific MCP servers 2. **Global Servers**: Configure frequently-used servers in your tool's global config 3. **Environment Variables**: Store sensitive data (API keys) in environment variables 4. **Version Control**: Commit project-specific configs, exclude global configs with API keys ## NeuroLink Auto-Discovery NeuroLink's MCP auto-discovery system automatically searches all these locations and can discover MCP servers configured in any of these tools. Use the CLI command: ```bash neurolink mcp discover ``` This will find and list all MCP servers configured across your system, regardless of which tool configured them. --- ## MCP Concurrency Control Guide # MCP Concurrency Control Guide > ⚠️ **PLANNED FEATURE**: This documentation describes features that are planned but not yet implemented. The `SemaphoreManager` class referenced in this guide does not currently exist in the codebase. The code examples are illustrative of the intended API design. **NeuroLink Enhanced MCP Platform - Concurrency Management** ## ️ **Architecture & Implementation** ### **Core Semaphore Pattern** ```typescript export class SemaphoreManager { private semaphores: Map> = new Map(); private stats: Map = new Map(); async acquire( key: string, operation: () => Promise, ): Promise> { const startTime = Date.now(); const existing = this.semaphores.get(key); // Wait for existing operation if present if (existing) { await existing; } // Execute operation with automatic cleanup const promise = operation(); this.semaphores.set( key, promise.then( () => {}, () => {}, ), ); try { const result = await promise; return { success: true, result, waitTime: existing ? Date.now() - startTime : 0, executionTime: Date.now() - startTime, queueDepth: this.getQueueDepth(key), }; } finally { this.semaphores.delete(key); } } } ``` ### **Integration with MCP Orchestrator** ```typescript export class MCPOrchestrator { private semaphoreManager: SemaphoreManager; async executeTool( toolName: string, args: unknown, context: NeuroLinkExecutionContext, ): Promise { return await this.semaphoreManager.acquire( toolName, // Use tool name as semaphore key async () => { return await this.registry.executeTool(toolName, args, context); }, ); } } ``` --- ## **Usage Patterns** ### **Basic Usage** ```typescript const semaphoreManager = new SemaphoreManager(); // Execute operation with concurrency control const result = await semaphoreManager.acquire("my-operation", async () => { // Your operation here return await performSomeTask(); }); console.log("Success:", result.success); console.log("Wait Time:", result.waitTime); console.log("Execution Time:", result.executionTime); ``` ### **Tool-Specific Concurrency Control** ```typescript // Same tool executions are serialized const fileOperations = [ semaphoreManager.acquire("file-read", () => readFile("data1.txt")), semaphoreManager.acquire("file-read", () => readFile("data2.txt")), semaphoreManager.acquire("file-read", () => readFile("data3.txt")), ]; // These will execute sequentially to prevent file conflicts const results = await Promise.all(fileOperations); ``` ### **Different Tools Run Concurrently** ```typescript // Different tools can run simultaneously const mixedOperations = [ semaphoreManager.acquire("file-read", () => readFile("data.txt")), semaphoreManager.acquire("http-request", () => fetchData("https://api.example.com"), ), semaphoreManager.acquire("database-query", () => queryDatabase()), ]; // These will execute concurrently for optimal performance const results = await Promise.all(mixedOperations); ``` --- ## **Performance Monitoring** ### **Statistics Interface** ```typescript type SemaphoreStats = { activeOperations: number; // Currently running operations queuedOperations: number; // Operations waiting in queue totalOperations: number; // Total operations processed totalWaitTime: number; // Cumulative wait time (ms) averageWaitTime: number; // Average wait time per operation peakQueueDepth: number; // Maximum queue depth reached }; // Get statistics for monitoring const stats = semaphoreManager.getStats("tool-name"); console.log(`Average wait time: ${stats.averageWaitTime}ms`); console.log(`Peak queue depth: ${stats.peakQueueDepth}`); ``` ### **Performance Metrics** ```typescript // Real-world performance characteristics const PERFORMANCE_BENCHMARKS = { overhead: " { const operations = Array.from({ length: 100 }, (_, i) => semaphoreManager.acquire("test-tool", async () => { await new Promise((resolve) => setTimeout(resolve, 100)); return `Operation ${i} complete`; }), ); const startTime = Date.now(); const results = await Promise.all(operations); const totalTime = Date.now() - startTime; console.log(`100 operations completed in ${totalTime}ms`); console.log(`All successful: ${results.every((r) => r.success)}`); }; ``` ### **Race Condition Prevention Test** ```typescript // Verify serialization of same-tool operations const testSerialization = async () => { let counter = 0; const operations = Array.from({ length: 10 }, () => semaphoreManager.acquire("counter-tool", async () => { const current = counter; await new Promise((resolve) => setTimeout(resolve, 10)); counter = current + 1; return counter; }), ); const results = await Promise.all(operations); const finalValues = results.map((r) => r.result); // Should be [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] in some order console.log("Final counter value:", counter); // Should be 10 console.log("No race conditions:", new Set(finalValues).size === 10); }; ``` --- ## **Configuration & Tuning** ### **Advanced Configuration** ```typescript type SemaphoreManagerOptions = { maxConcurrentOperations?: number; // Global concurrency limit defaultTimeout?: number; // Operation timeout (ms) cleanupInterval?: number; // Stats cleanup interval (ms) enableStatistics?: boolean; // Enable/disable stats collection }; const semaphoreManager = new SemaphoreManager({ maxConcurrentOperations: 50, defaultTimeout: 30000, cleanupInterval: 300000, enableStatistics: true, }); ``` ### **Memory Management** ```typescript // Automatic cleanup configuration const cleanupOptions = { maxHistorySize: 1000, // Max entries in statistics history cleanupThreshold: 0.8, // Cleanup when 80% full forceCleanupInterval: 600000, // Force cleanup every 10 minutes }; ``` --- ## **Troubleshooting** ### **Common Issues & Solutions** #### **High Wait Times** ```typescript // Diagnose high wait times const diagnostics = await semaphoreManager.getDiagnostics(); if (diagnostics.averageWaitTime > 1000) { console.warn("High wait times detected:"); console.log("- Consider reducing operation complexity"); console.log("- Check for blocking I/O operations"); console.log("- Monitor queue depth patterns"); } ``` #### **Memory Growth** ```typescript // Monitor memory usage const memoryUsage = process.memoryUsage(); const activeOperations = semaphoreManager.getActiveOperationCount(); if (memoryUsage.heapUsed > 200 * 1024 * 1024) { // 200MB console.warn("High memory usage detected"); console.log(`Active operations: ${activeOperations}`); console.log("Consider implementing operation timeouts"); } ``` #### **Deadlock Detection** ```typescript // Monitor for potential deadlocks const deadlockCheck = () => { const stats = semaphoreManager.getAllStats(); const stalledOperations = Object.entries(stats) .filter(([_, stat]) => stat.averageWaitTime > 30000) .map(([toolName, _]) => toolName); if (stalledOperations.length > 0) { console.warn("Potential deadlocks detected in:", stalledOperations); } }; ``` --- ## **Best Practices** ### **Operation Design** 1. **Keep Operations Atomic**: Each semaphore-protected operation should be self-contained 2. **Minimize Operation Time**: Reduce wait times by optimizing operation duration 3. **Use Appropriate Keys**: Choose semaphore keys that reflect actual resource conflicts 4. **Avoid Nested Semaphores**: Prevent potential deadlock scenarios ### **Error Handling** ```typescript const robustExecution = async () => { try { const result = await semaphoreManager.acquire( "risky-operation", async () => { // Operation that might fail return await performRiskyTask(); }, ); if (!result.success) { console.error("Operation failed:", result.error); // Handle failure appropriately } } catch (error) { console.error("Semaphore error:", error); // Handle semaphore-level errors } }; ``` ### **Performance Optimization** ```typescript // Batch similar operations when possible const batchOperations = async (items: string[]) => { return await semaphoreManager.acquire("batch-operation", async () => { // Process all items in a single semaphore-protected block return await Promise.all(items.map(processItem)); }); }; ``` --- ## **Integration Examples** ### **File System Operations** ```typescript // Prevent concurrent file modifications const fileManager = { async writeFile(filename: string, content: string) { return await semaphoreManager.acquire(`file:${filename}`, async () => { return await fs.writeFile(filename, content); }); }, async readFile(filename: string) { return await semaphoreManager.acquire(`file:${filename}`, async () => { return await fs.readFile(filename, "utf8"); }); }, }; ``` ### **API Rate Limiting** ```typescript // Prevent API rate limit violations const apiManager = { async makeRequest(endpoint: string, data: any) { return await semaphoreManager.acquire("api-requests", async () => { await new Promise((resolve) => setTimeout(resolve, 100)); // Rate limit return await fetch(endpoint, { method: "POST", body: JSON.stringify(data), }); }); }, }; ``` ### **Database Operations** ```typescript // Serialize database migrations const dbManager = { async runMigration(migrationName: string) { return await semaphoreManager.acquire("database-migration", async () => { console.log(`Running migration: ${migrationName}`); return await executeMigration(migrationName); }); }, }; ``` --- **STATUS**: Production-ready concurrency control system with comprehensive testing and monitoring capabilities. Provides enterprise-grade race condition prevention while maintaining optimal performance for concurrent operations. --- ## NeuroLink Docs MCP Server # NeuroLink Docs MCP Server The NeuroLink Docs MCP Server makes the entire NeuroLink documentation (360+ pages across 27 sections) queryable by AI assistants through the [Model Context Protocol](https://modelcontextprotocol.io). Instead of copy-pasting docs into your prompt, your AI assistant can search, browse, and read NeuroLink documentation on demand. **What it provides:** - **6 tools** — full-text search, page retrieval, section browsing, API reference lookup, example search, and changelog - **Pre-built search index** — generated at build time with MiniSearch for instant results - **Dual transport** — stdio for local use, HTTP for remote/hosted deployments - **Zero configuration** — runs via `npx` with no API keys required ## Quick Start Add the NeuroLink docs server to your AI development tool: ```json { "mcpServers": { "neurolink-docs": { "command": "npx", "args": ["-y", "@juspay/neurolink", "docs"] } } } ``` ```json { "mcpServers": { "neurolink-docs": { "command": "npx", "args": ["-y", "@juspay/neurolink", "docs"] } } } ``` ```bash claude mcp add neurolink-docs -- npx -y @juspay/neurolink docs ``` ```json { "servers": { "neurolink-docs": { "command": "npx", "args": ["-y", "@juspay/neurolink", "docs"] } } } ``` ```json { "mcpServers": { "neurolink-docs": { "command": "npx", "args": ["-y", "@juspay/neurolink", "docs"] } } } ``` :::tip[Same command everywhere] All clients use the same `npx -y @juspay/neurolink docs` command. The only difference is the config file location and JSON key format (`mcpServers` vs `servers`). ::: ## Available Tools The docs server exposes 6 tools to your AI assistant: | Tool | Description | Parameters | | ------------------- | ---------------------------------------------------- | ---------------------------------------- | | `search_docs` | Full-text search across all documentation | `query` (required), `limit?`, `section?` | | `get_page` | Get the full content of a specific doc page | `path` (required) | | `list_sections` | List all documentation sections and their pages | none | | `get_api_reference` | Get SDK API reference, optionally filtered by method | `method?` | | `get_examples` | Get code examples by topic or provider | `topic?`, `provider?` | | `get_changelog` | Get recent changelog entries | `limit?` | ## Tool Examples ### search_docs Search across all NeuroLink documentation with optional section filtering. **Request:** ```json { "query": "RAG pipeline", "limit": 3, "section": "features" } ``` **Response:** ```json { "query": "RAG pipeline", "resultCount": 3, "results": [ { "title": "RAG (Retrieval-Augmented Generation)", "description": "Complete RAG pipeline with 10 chunking strategies...", "section": "features", "path": "features/rag", "url": "https://docs.neurolink.ink/docs/features/rag", "score": 12.45 }, { "title": "File Processors", "description": "Process 50+ file types for AI consumption...", "section": "features", "path": "features/file-processors", "url": "https://docs.neurolink.ink/docs/features/file-processors", "score": 8.21 } ] } ``` ### get_page Retrieve the full content of a specific documentation page by its path. **Request:** ```json { "path": "getting-started/installation" } ``` **Response:** ```json { "title": "Installation", "description": "Install NeuroLink via npm, yarn, or pnpm...", "section": "getting-started", "path": "getting-started/installation", "url": "https://docs.neurolink.ink/docs/getting-started/installation", "content": "# Installation\n\nInstall NeuroLink using your preferred package manager..." } ``` ### list_sections List all documentation sections and the pages they contain. **Request:** _(no parameters)_ **Response:** ```json { "totalSections": 27, "totalPages": 361, "sections": [ { "name": "getting-started", "pageCount": 15, "pages": [ { "title": "Getting Started", "path": "getting-started/index" }, { "title": "Installation", "path": "getting-started/installation" } ] }, { "name": "sdk", "pageCount": 6, "pages": [ { "title": "SDK Overview", "path": "sdk/index" }, { "title": "API Reference", "path": "sdk/api-reference" } ] } ] } ``` ### get_api_reference Get SDK API reference documentation. Pass a method name to filter results. **Request:** ```json { "method": "generate" } ``` **Response:** ```json { "query": "generate", "results": [ { "title": "API Reference", "path": "sdk/api-reference", "url": "https://docs.neurolink.ink/docs/sdk/api-reference" } ] } ``` ### get_examples Find code examples by topic or AI provider. **Request:** ```json { "topic": "streaming", "provider": "anthropic" } ``` **Response:** ```json { "query": "streaming anthropic", "results": [ { "title": "Streaming with Retry", "description": "Implement streaming with automatic retry...", "section": "cookbook", "path": "cookbook/streaming-with-retry", "url": "https://docs.neurolink.ink/docs/cookbook/streaming-with-retry" } ] } ``` ### get_changelog Get recent NeuroLink release notes and changelog entries. **Request:** ```json { "limit": 3 } ``` **Response:** ```json { "entries": [ { "title": "Changelog", "description": "NeuroLink release history...", "path": "community/changelog", "url": "https://docs.neurolink.ink/docs/community/changelog", "content": "## 9.12.0\n\n### Features\n- MCP CLI gap fix..." } ] } ``` ## HTTP Transport For remote or hosted deployments, start the server with HTTP transport: ```bash # Start HTTP server on default port 3001 neurolink docs --transport http # Start on a custom port neurolink docs --transport http --port 8080 ``` The HTTP server exposes: - `POST /mcp` — MCP endpoint (Streamable HTTP transport) - `GET /health` — Health check endpoint Configure your MCP client to connect via HTTP: ```json { "mcpServers": { "neurolink-docs": { "transport": "http", "url": "https://your-server.com/mcp" } } } ``` :::info[Hosted version] The hosted version is available at `https://docs.neurolink.ink/mcp` -- no local installation required. ::: ## Programmatic Usage You can also add the docs server programmatically via the NeuroLink SDK: ```typescript const neurolink = new NeuroLink(); // Add the docs server as an external MCP server await neurolink.addExternalMCPServer("neurolink-docs", { command: "npx", args: ["-y", "@juspay/neurolink", "docs"], transport: "stdio", }); // Now the AI can use docs tools during generation const result = await neurolink.generate({ prompt: "How do I set up RAG with NeuroLink? Search the docs first.", }); ``` Or connect to the HTTP transport: ```typescript await neurolink.addExternalMCPServer("neurolink-docs", { transport: "http", url: "https://docs.neurolink.ink/mcp", }); ``` ## Building the Search Index The search index is generated automatically during the docs site build: ```bash cd docs-site && pnpm build ``` This runs the `docusaurus-plugin-search-index` plugin which: 1. Scans all `docs/**/*.md` and `docs/**/*.mdx` files 2. Parses frontmatter (title, description, tags) 3. Extracts and indexes content with MiniSearch 4. Writes `static/search-index.json` The index is bundled with the npm package, so end users don't need to build it themselves. ## Troubleshooting ### "search-index.json not found" The search index hasn't been built yet. Run: ```bash cd docs-site && pnpm build ``` This generates `docs-site/static/search-index.json` which the MCP server needs to function. ### Outdated search results The search index is generated at build time. To get the latest docs: ```bash cd docs-site && pnpm build ``` If using the npm package, update to the latest version: ```bash npm update @juspay/neurolink ``` ### Server not appearing in Claude Desktop / Cursor 1. Verify the config file is in the correct location (see [Quick Start](#quick-start) above) 2. Ensure the JSON is valid — a trailing comma or missing bracket will silently fail 3. Restart the application after saving the config 4. Check that `npx` is available in your PATH ### Connection timeout If the server takes too long to start: 1. The first run downloads `@juspay/neurolink` via npx — this may take 10-30 seconds 2. Subsequent runs use the npm cache and start faster 3. For faster startup, install globally: `npm install -g @juspay/neurolink` ### Tools not returning results If search returns empty results: 1. Verify the search index exists and is not empty 2. Try broader search terms — the index uses fuzzy matching with prefix search 3. Use `list_sections` first to see available sections, then filter with `section` parameter --- ## HTTP Transport for MCP Servers # HTTP Transport for MCP Servers ## Overview NeuroLink now supports **HTTP/Streamable HTTP transport** for Model Context Protocol (MCP) servers, enabling integration with remote MCP services like GitHub Copilot MCP API and custom HTTP-based MCP endpoints. The HTTP transport implements the [MCP Streamable HTTP specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports), providing: - ✅ Remote MCP server connectivity - ✅ Custom header support for authentication - ✅ Session management and automatic reconnection - ✅ Firewall and proxy compatibility - ✅ Both streaming (SSE) and batch JSON responses ## Quick Start ### GitHub Copilot Integration ```bash # Add GitHub Copilot MCP endpoint npx neurolink mcp add github-copilot "https://api.githubcopilot.com/mcp" \ --transport http \ --url "https://api.githubcopilot.com/mcp" \ --headers '{"Authorization": "Bearer YOUR_GITHUB_COPILOT_TOKEN"}' ``` ### Configuration File Add to `.mcp-config.json`: ```json { "mcpServers": { "github-copilot": { "name": "github-copilot", "command": "https://api.githubcopilot.com/mcp", "transport": "http", "url": "https://api.githubcopilot.com/mcp", "headers": { "Authorization": "Bearer ghp_xxxxxxxxxxxxxxxxxxxx" }, "description": "GitHub Copilot MCP API" } } } ``` ### Programmatic Usage ```typescript const neurolink = new NeuroLink(); // Add HTTP MCP server await neurolink.addInMemoryMCPServer("github-copilot", { server: { title: "GitHub Copilot MCP", description: "GitHub Copilot API integration", tools: {}, }, config: { id: "github-copilot", name: "github-copilot", description: "GitHub Copilot MCP API", command: "https://api.githubcopilot.com/mcp", transport: "http", url: "https://api.githubcopilot.com/mcp", headers: { Authorization: "Bearer YOUR_TOKEN", }, tools: [], status: "initializing", }, }); // Use the MCP server const result = await neurolink.generate({ input: { text: "Use GitHub Copilot to help me write code" }, provider: "openai", disableTools: false, }); ``` ## Authentication HTTP transport supports custom headers for authentication: ### Bearer Token Authentication ```json { "headers": { "Authorization": "Bearer YOUR_TOKEN" } } ``` ### API Key Authentication ```json { "headers": { "X-API-Key": "your-api-key-here" } } ``` ### Custom Headers ```json { "headers": { "Authorization": "Bearer YOUR_TOKEN", "X-Custom-Header": "custom-value", "X-Request-ID": "unique-request-id" } } ``` Header values are sent exactly as written. `${VAR}` references are **not** expanded in `headers` or `url` (a reference there would ship the variable's value to the remote host); they expand only in a server's `env` and `args`. To authenticate with a token from the environment, add the server programmatically with `addExternalMCPServer()` and build the header in code, or use `auth: { "type": "bearer", "token": "…" }` from a secrets manager. The `websocket` transport cannot carry headers or `auth` at all and fails to connect when either is configured — use `http` or `sse`. ### OAuth 2.1 Authentication For enterprise integrations requiring OAuth 2.1 with PKCE: ```json { "mcpServers": { "enterprise-api": { "transport": "http", "url": "https://api.enterprise.com/mcp", "auth": { "type": "oauth2", "oauth": { "clientId": "your-client-id", "clientSecret": "your-client-secret", "authorizationUrl": "https://auth.enterprise.com/oauth/authorize", "tokenUrl": "https://auth.enterprise.com/oauth/token", "redirectUrl": "http://localhost:8080/callback", "scope": "mcp:read mcp:write", "usePKCE": true } } } } } ``` **OAuth Configuration Options:** | Option | Type | Required | Description | | ------------------ | ------- | -------- | ---------------------------------------- | | `clientId` | string | Yes | OAuth client identifier | | `clientSecret` | string | No | OAuth client secret (optional with PKCE) | | `authorizationUrl` | string | Yes | Authorization endpoint URL | | `tokenUrl` | string | Yes | Token endpoint URL | | `redirectUrl` | string | Yes | OAuth callback URL | | `scope` | string | No | Space-separated OAuth scopes | | `usePKCE` | boolean | No | Enable PKCE (recommended, default: true) | ### Authentication Types The `auth` configuration supports three authentication types: **1. OAuth 2.1 (recommended for enterprise)** ```json { "auth": { "type": "oauth2", "oauth": { ... } } } ``` **2. Bearer Token** ```json { "auth": { "type": "bearer", "token": "your-access-token" } } ``` **3. API Key** ```json { "auth": { "type": "api-key", "apiKey": "your-api-key", "apiKeyHeader": "X-API-Key" } } ``` ## Transport Comparison | Feature | stdio | SSE | WebSocket | HTTP | | ------------------ | -------- | -------- | --------- | -------- | | Local servers | ✅ | ❌ | ❌ | ❌ | | Remote servers | ❌ | ✅ | ✅ | ✅ | | Authentication | Env vars | Headers | ❌ (none) | Headers | | Streaming | ✅ | ✅ | ✅ | ✅ | | Firewall friendly | ✅ | ✅ | ⚠️ | ✅ | | Session management | ❌ | ⚠️ | ⚠️ | ✅ | | Reconnection | ❌ | ⚠️ | ⚠️ | ✅ | | Specification | MCP Core | MCP Core | MCP Core | MCP 2025 | ## Configuration Options ### Required Fields - `transport`: Must be set to `"http"` - `url`: The HTTP endpoint URL (e.g., `https://api.example.com/mcp`) - `command`: Usually same as URL for HTTP transport ### Optional Fields - `headers`: Object with HTTP headers for authentication and configuration - `httpOptions`: Fine-grained HTTP connection settings (see below) - `retryConfig`: Automatic retry configuration with exponential backoff - `rateLimiting`: Rate limiting to prevent API throttling - `auth`: Authentication configuration (OAuth 2.1, Bearer, API Key) - `timeout`: Connection timeout in milliseconds (default: 10000) - `retries`: Maximum retry attempts (default: 3) - `autoRestart`: Whether to automatically restart on failure (default: true) - `healthCheckInterval`: Health check interval in milliseconds (default: 30000) ### HTTP Options Configuration Fine-tune HTTP connection behavior: ```typescript { httpOptions: { connectionTimeout: 30000, // Connection timeout (ms), default: 30000 requestTimeout: 60000, // Request timeout (ms), default: 60000 idleTimeout: 120000, // Idle connection timeout (ms), default: 120000 keepAliveTimeout: 30000 // Keep-alive timeout (ms), default: 30000 } } ``` | Option | Type | Default | Description | | ------------------- | ------ | ------- | ------------------------------------ | | `connectionTimeout` | number | 30000 | Maximum time to establish connection | | `requestTimeout` | number | 60000 | Maximum time for request completion | | `idleTimeout` | number | 120000 | Time before closing idle connections | | `keepAliveTimeout` | number | 30000 | Keep-alive connection timeout | ### Retry Configuration Automatic retry with exponential backoff: ```typescript { retryConfig: { maxAttempts: 3, // Maximum retry attempts, default: 3 initialDelay: 1000, // Initial delay (ms), default: 1000 maxDelay: 30000, // Maximum delay (ms), default: 30000 backoffMultiplier: 2 // Backoff multiplier, default: 2 } } ``` | Option | Type | Default | Description | | ------------------- | ------ | ------- | ---------------------------------- | | `maxAttempts` | number | 3 | Maximum number of retry attempts | | `initialDelay` | number | 1000 | Initial delay before first retry | | `maxDelay` | number | 30000 | Maximum delay between retries | | `backoffMultiplier` | number | 2 | Multiplier for exponential backoff | ### Rate Limiting Configuration Prevent API throttling with token bucket rate limiting: ```typescript { rateLimiting: { requestsPerMinute: 60, // Max requests per minute, default: 60 requestsPerHour: 1000, // Max requests per hour (optional) maxBurst: 10, // Max burst size, default: 10 useTokenBucket: true // Use token bucket algorithm, default: true } } ``` | Option | Type | Default | Description | | ------------------- | ------- | ------- | ----------------------------------- | | `requestsPerMinute` | number | 60 | Maximum requests allowed per minute | | `requestsPerHour` | number | - | Maximum requests allowed per hour | | `maxBurst` | number | 10 | Maximum burst size for token bucket | | `useTokenBucket` | boolean | true | Use token bucket algorithm | ### Example: Complete Configuration ```json { "mcpServers": { "custom-api": { "name": "custom-api", "command": "https://your-api.example.com/mcp", "transport": "http", "url": "https://your-api.example.com/mcp", "headers": { "Authorization": "Bearer YOUR_API_TOKEN", "X-Custom-Header": "value" }, "httpOptions": { "connectionTimeout": 30000, "requestTimeout": 60000, "idleTimeout": 120000, "keepAliveTimeout": 30000 }, "retryConfig": { "maxAttempts": 5, "initialDelay": 1000, "maxDelay": 30000, "backoffMultiplier": 2 }, "rateLimiting": { "requestsPerMinute": 100, "maxBurst": 20, "useTokenBucket": true }, "timeout": 15000, "autoRestart": true, "healthCheckInterval": 60000, "description": "Custom MCP API endpoint" } } } ``` ## Use Cases ### 1. GitHub Copilot Integration Access GitHub Copilot's AI capabilities through MCP: ```typescript const neurolink = new NeuroLink(); await neurolink.addInMemoryMCPServer("copilot", { server: { title: "GitHub Copilot", tools: {} }, config: { id: "copilot", name: "copilot", description: "GitHub Copilot MCP", transport: "http", url: "https://api.githubcopilot.com/mcp", headers: { Authorization: "Bearer YOUR_TOKEN" }, tools: [], status: "initializing", }, }); ``` ### 2. Enterprise API Gateway Connect to internal MCP services behind API gateways: ```json { "internal-tools": { "transport": "http", "url": "https://internal-gateway.company.com/mcp", "headers": { "Authorization": "Bearer INTERNAL_TOKEN", "X-Tenant-ID": "tenant-123" } } } ``` ### 3. Multi-Cloud MCP Services Connect to MCP services across different cloud providers: ```json { "aws-mcp": { "transport": "http", "url": "https://mcp.us-east-1.amazonaws.com/api", "headers": { "X-API-Key": "AWS_API_KEY" } }, "azure-mcp": { "transport": "http", "url": "https://mcp.azure.com/api/v1", "headers": { "Ocp-Apim-Subscription-Key": "AZURE_KEY" } } } ``` ## Troubleshooting ### Connection Failed **Problem:** Unable to connect to HTTP MCP server **Solutions:** 1. Verify the URL is correct and accessible 2. Check authentication headers are valid 3. Ensure firewall/proxy allows HTTPS traffic 4. Test with `curl` first: ```bash curl -H "Authorization: Bearer TOKEN" https://api.example.com/mcp ``` ### Authentication Errors **Problem:** 401 Unauthorized or 403 Forbidden **Solutions:** 1. Verify token is valid and not expired 2. Check token has required permissions 3. Ensure header format matches API requirements 4. Try regenerating the authentication token ### Timeout Issues **Problem:** Connection times out **Solutions:** 1. Increase timeout value in configuration 2. Check network connectivity 3. Verify the server is running and responsive 4. Test with a simple HTTP client first ### Invalid Headers **Problem:** Server rejects custom headers **Solutions:** 1. Check header names follow HTTP specification 2. Ensure header values are properly formatted 3. Some headers may be reserved or blocked by proxies 4. Try different header names (e.g., `X-API-Key` instead of `Api-Key`) ## Technical Details ### Implementation HTTP transport uses the `StreamableHTTPClientTransport` from the `@modelcontextprotocol/sdk` package, which implements: - **JSON-RPC 2.0** for message protocol - **Server-Sent Events (SSE)** for streaming responses - **HTTP POST** for sending requests - **Session management** via `Mcp-Session-Id` header - **Automatic reconnection** with exponential backoff ### Security Considerations 1. **TLS is enforced**: a non-loopback `url` must use `https:` (or `wss:`). Plaintext is accepted only for `localhost`, `127.0.0.0/8` and `::1`. 2. **Private addresses are refused**: a host that is, or resolves to, an RFC 1918, link-local (cloud metadata), CGNAT or multicast address is rejected unless that server sets `"allowPrivateNetwork": true`, which also permits plaintext to private addresses. Public hosts always need TLS. 3. **Token Security**: Store tokens securely (environment variables, secrets management). `${VAR}` is never expanded inside `headers` or `url`. 4. **Header Sanitization**: Avoid logging sensitive headers 5. **Project configs are trusted explicitly**: the SDK loads `.mcp-config.json` only through `mcp.configPath` / `mcp.trustProjectConfig`; the CLI asks, or needs `--trust-mcp-config`. See [MCP Integration](/docs/mcp/integration). 6. **Rate Limiting**: Implement client-side rate limiting for public APIs ## Migration Guide ### From SSE to HTTP If you're currently using SSE transport, migration is straightforward: **Before (SSE):** ```json { "transport": "sse", "url": "http://localhost:8080/sse" } ``` **After (HTTP):** ```json { "transport": "http", "url": "https://api.example.com/mcp", "headers": { "Authorization": "Bearer TOKEN" } } ``` ### From stdio to HTTP Migrating from local stdio servers to remote HTTP requires server changes: 1. Deploy your MCP server as an HTTP service 2. Implement authentication endpoint 3. Update client configuration to use HTTP transport 4. Add authentication headers ## Resources - [MCP Specification - Transports](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports) - [GitHub Copilot MCP API Documentation](https://github.com/features/copilot) - [NeuroLink MCP Integration Guide](/docs/mcp/integration) - Example HTTP Transport Configurations: ```json { "mcpServers": { "github-copilot": { "name": "github-copilot", "transport": "http", "url": "https://api.githubcopilot.com/mcp", "headers": { "Authorization": "Bearer ${GITHUB_COPILOT_TOKEN}" }, "httpOptions": { "connectionTimeout": 30000, "requestTimeout": 60000 }, "retryConfig": { "maxAttempts": 3, "initialDelay": 1000, "maxDelay": 30000 }, "rateLimiting": { "requestsPerMinute": 60, "maxBurst": 10 }, "description": "GitHub Copilot MCP API with full configuration" }, "simple-http-server": { "name": "simple-http-server", "transport": "http", "url": "https://api.example.com/mcp", "headers": { "Authorization": "Bearer ${API_TOKEN}" }, "description": "Minimal HTTP transport configuration" }, "enterprise-oauth-server": { "name": "enterprise-oauth-server", "transport": "http", "url": "https://api.enterprise.com/mcp", "auth": { "type": "oauth2", "oauth": { "clientId": "${OAUTH_CLIENT_ID}", "clientSecret": "${OAUTH_CLIENT_SECRET}", "authorizationUrl": "https://auth.enterprise.com/authorize", "tokenUrl": "https://auth.enterprise.com/token", "redirectUrl": "http://localhost:8080/callback", "scope": "mcp:read mcp:write tools:execute", "usePKCE": true } }, "description": "Enterprise MCP server with OAuth 2.1 + PKCE" } } } ``` ## Support For issues or questions: - GitHub Issues: [juspay/neurolink/issues](https://github.com/juspay/neurolink/issues) - Documentation: [NeuroLink Docs](https://github.com/juspay/neurolink/docs) - Examples: [Basic Usage Examples](/docs/examples/basic-usage) --- ## MCP (Model Context Protocol) Integration Guide # MCP (Model Context Protocol) Integration Guide **NeuroLink Universal AI Platform with External Server Connectivity** ## **Quick Start** ### **1. Install Popular MCP Servers** ```bash # Install filesystem server for file operations npx neurolink mcp install filesystem # Install GitHub server for repository management npx neurolink mcp install github # Install database server for SQL operations npx neurolink mcp install postgres ``` ### **2. Test Connectivity** ```bash # Test server connectivity and discover tools npx neurolink mcp test filesystem # List all configured servers with status npx neurolink mcp list --status ``` ### **3. 🆕 Programmatic Server Management** **NEW!** Add MCP servers dynamically at runtime: ```typescript const neurolink = new NeuroLink(); // Add external servers dynamically await neurolink.addExternalMCPServer("bitbucket", { command: "npx", args: ["-y", "@nexus2520/bitbucket-mcp-server"], env: { BITBUCKET_USERNAME: "your-username", BITBUCKET_APP_PASSWORD: "your-token", }, }); // Add database integration await neurolink.addExternalMCPServer("database", { command: "node", args: ["./custom-db-server.js"], env: { DB_CONNECTION: "postgresql://..." }, }); // Verify registration — getMCPStatus() also triggers MCP initialization, // so always call it before listMCPServers() to ensure the subsystem is ready. const status = await neurolink.getMCPStatus(); console.log("Active servers:", status.totalServers); const servers = await neurolink.listMCPServers(); console.log( "Registered servers:", servers.map((s) => s.name), ); ``` ### **4. Execute Tools (Planned)** > This feature is planned for a future release. ```text # Execute tools from connected servers (planned — not yet implemented) npx neurolink mcp exec filesystem read_file --params '{"path": "README.md"}' npx neurolink mcp exec github create_issue --params '{"title": "New feature", "body": "Description"}' ``` --- ## **MCP CLI Commands Reference** ### **Server Management** #### **Install Popular Servers** ```bash neurolink mcp install ``` **Available servers:** - `filesystem` - File and directory operations - `github` - GitHub repository management - `postgres` - PostgreSQL database operations - `brave-search` - Web search capabilities - `puppeteer` - Browser automation **Example:** ```bash neurolink mcp install filesystem # ✅ Installed MCP server: filesystem # Test it with: neurolink mcp test filesystem ``` #### **Add Custom Servers** ```bash neurolink mcp add [options] ``` **Options:** - `--args` - Command arguments (array) - `--transport` - Transport type (stdio|sse|websocket|http) - `--url` - URL for SSE/WebSocket/HTTP transport - `--headers` - HTTP headers for authentication (JSON) - `--env` - Environment variables (JSON) - `--cwd` - Working directory **Examples:** ```bash # Add custom server with arguments neurolink mcp add myserver "python /path/to/server.py" --args "arg1,arg2" # Add SSE server neurolink mcp add webserver "http://localhost:8080" --transport sse --url "http://localhost:8080/mcp" # Add HTTP remote server with authentication neurolink mcp add remote-api "https://api.example.com/mcp" --transport http --url "https://api.example.com/mcp" --headers '{"Authorization": "Bearer YOUR_TOKEN"}' # Add server with environment variables neurolink mcp add dbserver "npx db-mcp-server" --env '{"DB_URL": "postgresql://..."}' ``` #### **List Configured Servers** ```bash neurolink mcp list [--status] ``` **Example output:** ``` Configured MCP servers (2): filesystem Command: npx -y @modelcontextprotocol/server-filesystem / Transport: stdio ✔ filesystem: ✅ Available github Command: npx @modelcontextprotocol/server-github Transport: stdio ✖ github: ❌ Not available ``` #### **Test Server Connectivity** ```bash neurolink mcp test ``` **Example output:** ``` Testing MCP server: filesystem ✔ ✅ Connection successful! Server Capabilities: Protocol Version: 2024-11-05 Tools: ✅ Supported ️ Available Tools: • read_file: Read file contents from filesystem • write_file: Create/overwrite files • edit_file: Make line-based edits • create_directory: Create directories • list_directory: List directory contents + 6 more tools... ``` #### **Remove Servers** ```bash neurolink mcp remove ``` --- ## ⚙️ **Configuration** ### **External Server Configuration** External MCP servers are configured in `.mcp-config.json`: ```json { "mcpServers": { "filesystem": { "name": "filesystem", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/"], "transport": "stdio" }, "github": { "name": "github", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "transport": "stdio" }, "custom": { "name": "custom", "command": "python", "args": ["/path/to/server.py"], "transport": "stdio", "cwd": "/project/directory" } } } ``` ### **Who loads `.mcp-config.json`, and when** A project config names commands to run and URLs to connect to, so **a directory is not a trust boundary**: a cloned repository's `.mcp-config.json` must not run its servers with your credentials just because you ran something inside it. **SDK.** `new NeuroLink()` never reads the working directory's file on its own. Name the file, or opt into the directory, in the constructor: ```typescript // Load a specific file (relative paths resolve against the working directory) const neurolink = new NeuroLink({ mcp: { configPath: "./config/mcp-servers.json" }, }); // Load /.mcp-config.json — only for a directory you control const trusted = new NeuroLink({ mcp: { trustProjectConfig: true } }); ``` Servers added with `addExternalMCPServer()` / `addInMemoryMCPServer()` are unaffected. The legacy `ProviderRegistry.setOptions({ enableManualMCP: true })` switch is now honoured too: set after construction, it re-enables the old working-directory discovery for that process. **CLI.** `neurolink` still discovers `./.mcp-config.json`, but loads it only after you have trusted that exact content. The file's SHA-256 is recorded in `~/.neurolink/trusted-mcp-configs.json` (`0600`, directory `0700`); a file that changes has to be trusted again. - In a terminal, the first tool-enabled command shows the servers (names, commands, URLs, `env` key names — never values) and asks `Trust this file and start these servers? [y/N]`. - Non-interactively (CI, pipes), an untrusted file is refused with exit status 1 at the moment it would load, with the same summary. Decide with one of: - `neurolink generate "…" --trust-mcp-config` or `NEUROLINK_TRUST_MCP_CONFIG=1` — trust and record the hash; - `NEUROLINK_TRUST_MCP_CONFIG=0` — run without the project config; - `--disable-tools` — no MCP server is needed. - `neurolink --help`, `--version`, and any command that never initialises MCP are not affected. ### **`${VAR}` references** `${NAME}` in a server's **`env`** and **`args`** is replaced with `process.env.NAME`. Only names matching `^[A-Z][A-Z0-9_]*$` are expanded; anything else is left as written. `${NAME}` is **never** expanded in `headers` or `url` — those values travel to a remote host, so a reference there would send the variable's value off the machine. A `${…}` left in a header is sent literally and logged as a warning. ```json { "mcpServers": { "github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}" } } } } ``` ### **What a stdio server inherits** A spawned server receives the MCP SDK's minimal default environment (`HOME`, `PATH`, `SHELL`, `TERM`, `USER`, `LOGNAME` on POSIX) plus its own `env`. It no longer receives the whole parent `process.env`, so provider keys and OAuth tokens held by the host do not reach an `npx -y …` server unless you pass them through: `"env": { "OPENAI_API_KEY": "${OPENAI_API_KEY}" }`. A server that genuinely needs everything can set `"inheritParentEnv": true`. ### **Transport URLs** For `http`, `sse` and `websocket` servers the URL must use `https:` / `wss:` unless the host is loopback (`localhost`, `127.0.0.0/8`, `::1`), and the host must not be — or resolve to — a private, link-local, CGNAT or cloud-metadata address. A server on your own network opts out per entry with `"allowPrivateNetwork": true`, which also permits plaintext `http:` / `ws:` to private addresses; public hosts always need TLS. The WebSocket transport cannot send `headers` or `auth` (the handshake carries none), so a WebSocket server configured with either fails to connect instead of connecting unauthenticated — use `http` or `sse` for authenticated servers. ### **Environment Variables** Set these in your `.env` file for server authentication (the CLI loads `.env`; the SDK does not — see [Environment Variables](/docs/getting-started/environment-variables)): ```bash # Custom Server Configuration CUSTOM_API_KEY=your-api-key CUSTOM_ENDPOINT=https://api.example.com ``` --- ## ️ **Available MCP Servers** ### **Filesystem Server** **Purpose:** File and directory operations **Installation:** `neurolink mcp install filesystem` **Available Tools:** - `read_file` - Read file contents - `write_file` - Create or overwrite files - `edit_file` - Make line-based edits - `create_directory` - Create directories - `list_directory` - List directory contents - `directory_tree` - Get recursive tree view - `move_file` - Move/rename files - `search_files` - Search for files by pattern - `get_file_info` - Get file metadata ### **GitHub Server** **Purpose:** GitHub repository management **Installation:** `neurolink mcp install github` **Available Tools:** - `create_repository` - Create new repositories - `search_repositories` - Search public repositories - `get_file_contents` - Read repository files - `create_or_update_file` - Modify repository files - `create_issue` - Create GitHub issues - `create_pull_request` - Create pull requests - `fork_repository` - Fork repositories ### **PostgreSQL Server** **Purpose:** Database operations **Installation:** `neurolink mcp install postgres` **Available Tools:** - `read-query` - Execute SELECT queries - `write-query` - Execute INSERT/UPDATE/DELETE queries - `create-table` - Create database tables - `list-tables` - List available tables - `describe-table` - Get table schema ### **Brave Search Server** **Purpose:** Web search capabilities **Installation:** `neurolink mcp install brave-search` **Available Tools:** - `brave_web_search` - Search the web - `brave_local_search` - Search for local businesses ### **Puppeteer Server** **Purpose:** Browser automation **Installation:** `neurolink mcp install puppeteer` **Available Tools:** - `puppeteer_navigate` - Navigate to URLs - `puppeteer_screenshot` - Take screenshots - `puppeteer_click` - Click elements - `puppeteer_fill` - Fill forms - `puppeteer_evaluate` - Execute JavaScript --- ## **Advanced Usage** ### **Transport Types** #### **STDIO Transport (Default)** Best for local servers and CLI tools: ```bash neurolink mcp add local-server "python server.py" --transport stdio ``` #### **SSE Transport** For web-based servers: ```bash neurolink mcp add web-server "http://localhost:8080" --transport sse --url "http://localhost:8080/sse" ``` #### **HTTP Transport (Streamable HTTP)** For remote MCP servers with authentication, retry, and rate limiting: ```bash neurolink mcp add remote-api "https://api.example.com/mcp" \ --transport http \ --url "https://api.example.com/mcp" \ --headers '{"Authorization": "Bearer YOUR_TOKEN"}' ``` **Configuration in `.mcp-config.json`:** ```json { "mcpServers": { "remote-api": { "transport": "http", "url": "https://api.example.com/mcp", "headers": { "Authorization": "Bearer YOUR_TOKEN" }, "httpOptions": { "connectionTimeout": 30000, "requestTimeout": 60000, "idleTimeout": 120000, "keepAliveTimeout": 30000 }, "retryConfig": { "maxAttempts": 3, "initialDelay": 1000, "maxDelay": 30000, "backoffMultiplier": 2 }, "rateLimiting": { "requestsPerMinute": 60, "maxBurst": 10, "useTokenBucket": true } } } } ``` **HTTP Transport Features:** - Custom headers for authentication (Bearer, API Key) - Configurable connection and request timeouts - Automatic retry with exponential backoff - Rate limiting with token bucket algorithm - OAuth 2.1 support with PKCE See [MCP HTTP Transport Guide](/docs/mcp/http-transport) for complete documentation. ### **Server Environment Configuration** Pass environment variables to servers: ```bash neurolink mcp add secure-server "npx secure-mcp" --env '{"API_KEY": "secret", "DEBUG": "true"}' ``` ### **Working Directory** Set server working directory: ```bash neurolink mcp add project-server "python local-server.py" --cwd "/path/to/project" ``` --- ## Advanced MCP Features NeuroLink provides advanced MCP capabilities for production environments with multiple servers and complex tool ecosystems. ### Tool Router Intelligent tool call routing for multi-server environments with round-robin, least-loaded, capability-based, and session affinity strategies. ### Tool Cache Cache tool results with configurable LRU, FIFO, or LFU eviction strategies, pattern-based invalidation, and cache statistics. ### Request Batcher Batch multiple tool calls for efficient execution with automatic batch sizing and server-grouped batching. ### Tool Annotations Add safety metadata to tools (readOnly, destructive, idempotent) with automatic safety level inference and annotation-based filtering. ### Custom MCP Servers Create custom MCP servers using the `MCPServerBase` abstract class with built-in tool registration, event emission, and lifecycle management. ### Elicitation Protocol Interactive tool input during execution supporting text, select, multi-select, confirmation, file upload, and form elicitation types. ### Multi-Server Manager Load balancing and coordination across multiple MCP servers with server groups and a unified tool interface. > **Full Documentation**: See the [MCP Enhancements Guide](/docs/features/mcp-enhancements) for complete API reference, configuration options, and usage examples. --- ## **Troubleshooting** ### **Common Issues** #### **Server Not Available** ``` ✖ server: ❌ Not available ``` **Solutions:** 1. Check server installation: `npm list -g @modelcontextprotocol/server-*` 2. Verify command path: `which npx` 3. Test command manually: `npx @modelcontextprotocol/server-filesystem /` 4. Check environment variables 5. Verify network connectivity (for SSE servers) #### **Connection Timeout** ``` ❌ Connection failed: Timeout connecting to MCP server ``` **Solutions:** 1. Increase timeout (servers may need time to start) 2. Check server logs for errors 3. Verify server supports MCP protocol version 2024-11-05 4. Test with simpler server first (filesystem) #### **Authentication Errors** ``` ❌ Connection failed: Authentication required ``` **Solutions:** 1. Set required environment variables 2. Check API key/token validity 3. Verify permissions for required resources 4. Review server documentation for auth requirements #### **Tool Execution Errors** ``` ❌ Tool execution failed: Invalid parameters ``` **Solutions:** 1. Check tool parameter schema: `neurolink mcp test ` 2. Validate JSON parameter format 3. Review tool documentation 4. Test with minimal parameters first ### **Debug Mode** Enable verbose logging for troubleshooting: ```bash export NEUROLINK_DEBUG=true neurolink mcp test filesystem ``` --- ## **Integration with AI Providers** ### **Using MCP Tools with AI Generation** ```bash # Generate text that uses MCP tool results neurolink generate "Analyze the README.md file and suggest improvements" --tools filesystem # Stream responses that incorporate MCP data neurolink stream "Create a GitHub issue based on the project status" --tools github ``` ### **Multi-Tool Workflows** ```bash # Combine multiple MCP servers in workflows neurolink workflow " 1. Read project files (filesystem) 2. Analyze codebase (ai) 3. Create GitHub issue (github) 4. Update database (postgres) " ``` --- ## **Resources** ### **Official MCP Resources** - [MCP Specification](https://modelcontextprotocol.io/specification) - [MCP Server Index](https://github.com/modelcontextprotocol/servers) - [MCP Documentation](https://modelcontextprotocol.io/docs) ### **NeuroLink MCP Resources** - [MCP Testing Guide](/docs/mcp/testing) - [CLI Command Reference](/docs/cli/commands.md#mcp) - [API Integration](/docs/sdk/api-reference) ### **Community Servers** - [Awesome MCP Servers](https://github.com/modelcontextprotocol/awesome-mcp-servers) - [Custom Server Development](https://modelcontextprotocol.io/docs/building-servers) --- ## **What's Next?** ### **Get Involved** - Report issues on [GitHub](https://github.com/juspay/neurolink/issues) - Join the [MCP community](https://modelcontextprotocol.io/community) - Contribute server integrations - Share usage examples --- **Ready to extend NeuroLink with unlimited external capabilities! ** --- ## NeuroLink MCP Latency Optimization Implementation Guide # NeuroLink MCP Latency Optimization Implementation Guide ## Executive Summary ### Current Performance Crisis - **CLI Performance**: 26.4s total (24.8s MCP + 1.6s startup) - Unacceptable for production - **SDK Performance**: 46.4s total (46.4s MCP + 0s startup) - Completely unusable - **User Impact**: Every tool-enabled request waits 26-46 seconds before processing - **Business Impact**: Feature cannot ship with current performance ### Target Performance Goals - **CLI Target**: \ { const config = JSON.parse(fs.readFileSync('.mcp-config.json')); // Create promises for all servers const serverPromises = Object.entries(config.mcpServers).map( ([serverId, serverConfig]) => this.addServer(serverId, serverConfig) ); // Start all servers concurrently const results = await Promise.allSettled(serverPromises); // Process results with proper error handling return this.processParallelResults(results); } ``` Modify existing method to support parallel option: ```typescript async loadMCPConfiguration(options: { parallel?: boolean } = {}): Promise { if (options.parallel) { return this.loadMCPConfigurationParallel(); } return this.loadMCPConfigurationSequential(); // Renamed existing method } ``` **File: `src/lib/neurolink.ts`** Update MCP initialization to use parallel loading: ```typescript private async initializeMCP(options?: { parallel?: boolean }): Promise { if (this.mcpInitialized) return; // Register built-in tools (fast) await toolRegistry.registerServer("neurolink-direct", directToolsServer); // Load external servers with optional parallel execution const configResult = await this.externalServerManager.loadMCPConfiguration({ parallel: options?.parallel ?? true // Default to parallel }); this.mcpInitialized = true; } ``` #### Expected Results - **CLI**: 24.8s → 12s (50% reduction) - **SDK**: 46.4s → 23s (50% reduction) ### Phase 2: Smart Tool Detection Implementation #### Files to Create - `src/lib/utils/toolAnalyzer.ts` - New tool prediction logic #### Files to Modify - `src/lib/neurolink.ts` - Add selective initialization - `src/lib/mcp/externalServerManager.ts` - Add selective server loading #### Concept Implementation Create a tool analyzer that predicts required tools from prompt keywords: ```typescript "What time is it?" → analyzePrompt() → ['getCurrentTime'] → Load time server only "Calculate math" → analyzePrompt() → ['calculateMath'] → Load math tools only "Complex task" → analyzePrompt() → ['basic set'] → Load essential tools only ``` #### Detailed Code Changes **File: `src/lib/utils/toolAnalyzer.ts` (NEW)** Create smart tool detection: ```typescript export class ToolAnalyzer { private static readonly TOOL_KEYWORDS = { getCurrentTime: ["time", "date", "when", "now", "current"], calculateMath: [ "calculate", "math", "compute", "+", "-", "*", "/", "equation", ], listDirectory: ["list", "files", "directory", "folder", "ls", "dir"], readFile: ["read", "file", "content", "show", "cat"], writeFile: ["write", "save", "create", "file"], websearchGrounding: ["search", "web", "google", "find", "lookup"], }; static analyzePromptForRequiredTools(prompt: string): string[] { const requiredTools: string[] = []; const lowerPrompt = prompt.toLowerCase(); for (const [toolName, keywords] of Object.entries(this.TOOL_KEYWORDS)) { if (keywords.some((keyword) => lowerPrompt.includes(keyword))) { requiredTools.push(toolName); } } // Fallback to basic tools if no specific tools detected return requiredTools.length > 0 ? requiredTools : ["getCurrentTime", "calculateMath"]; } static getServerForTool(toolName: string): string | null { const toolServerMap: Record = { getCurrentTime: "builtin", // No external server needed calculateMath: "builtin", // No external server needed listDirectory: "filesystem", // Requires filesystem server readFile: "filesystem", // Requires filesystem server writeFile: "filesystem", // Requires filesystem server websearchGrounding: "websearch", // Requires websearch server }; return toolServerMap[toolName] || null; } } ``` **File: `src/lib/neurolink.ts`** Add selective MCP initialization: ```typescript private async initializeMCP(options?: { requiredTools?: string[], parallel?: boolean, prompt?: string }): Promise { if (this.mcpInitialized) return; // Determine which tools are needed let requiredTools = options?.requiredTools; if (!requiredTools && options?.prompt) { requiredTools = ToolAnalyzer.analyzePromptForRequiredTools(options.prompt); } // Load only required servers if (requiredTools) { await this.initializeSelectiveTools(requiredTools, options?.parallel); } else { await this.initializeAllTools(options?.parallel); // Fallback } this.mcpInitialized = true; } private async initializeSelectiveTools(requiredTools: string[], parallel = false): Promise { // Always load built-in tools (fast) await toolRegistry.registerServer("neurolink-direct", directToolsServer); // Determine which external servers are needed const requiredServers = new Set(); requiredTools.forEach(tool => { const server = ToolAnalyzer.getServerForTool(tool); if (server && server !== 'builtin') { requiredServers.add(server); } }); // Load only the required external servers if (requiredServers.size > 0) { await this.externalServerManager.loadSelectiveServers( Array.from(requiredServers), { parallel } ); } } ``` **File: `src/lib/mcp/externalServerManager.ts`** Add selective server loading: ```typescript async loadSelectiveServers(serverIds: string[], options: { parallel?: boolean } = {}): Promise { const config = JSON.parse(fs.readFileSync('.mcp-config.json')); // Filter configuration to only include required servers const filteredServers = Object.fromEntries( Object.entries(config.mcpServers).filter(([id]) => serverIds.includes(id)) ); if (options.parallel) { // Load filtered servers in parallel const serverPromises = Object.entries(filteredServers).map( ([serverId, serverConfig]) => this.addServer(serverId, serverConfig) ); const results = await Promise.allSettled(serverPromises); return this.processParallelResults(results); } else { // Load filtered servers sequentially const results: ExternalMCPOperationResult[] = []; for (const [serverId, serverConfig] of Object.entries(filteredServers)) { const result = await this.addServer(serverId, serverConfig); results.push(result); } return this.processSequentialResults(results); } } ``` #### Expected Results - **CLI**: 12s → 7s (additional 42% reduction) - **SDK**: 23s → 14s (additional 39% reduction) ### Phase 3: CLI Performance Modes Implementation #### Files to Modify - `src/cli/index.ts` - Add CLI performance flags and mode logic #### Concept Implementation Provide explicit user control over tool loading through CLI flags: ```bash pnpm cli generate "prompt" --speed-mode # Fastest: built-in only pnpm cli generate "prompt" --tools=time,math # Selective: specific tools pnpm cli generate "prompt" --parallel-loading # Enhanced: parallel loading ``` #### Detailed Code Changes **File: `src/cli/index.ts`** Add CLI performance options. Planned: `initializeMCP()` does not exist as a public method in the current release. MCP initialises on first use by `generate()`, `stream()`, `getMCPStatus()` and similar calls. ```typescript planned yargs.command( "generate ", "Generate AI content", { // ... existing options "speed-mode": { type: "boolean", default: false, description: "Use only built-in tools for fastest response (1-2s)", }, tools: { type: "array", description: "Specify which tool categories to enable", choices: ["time", "math", "files", "web", "all"], default: ["all"], }, "parallel-loading": { type: "boolean", default: true, description: "Load MCP servers in parallel for faster startup", }, }, async (argv) => { const neurolink = new NeuroLink(); // Determine initialization strategy based on user flags let initOptions: any = { parallel: argv.parallelLoading }; if (argv.speedMode) { // Speed mode: only built-in tools, no external servers initOptions.requiredTools = ["getCurrentTime", "calculateMath"]; console.log(" Speed mode enabled: Using built-in tools only"); } else if (argv.tools && !argv.tools.includes("all")) { // Selective mode: user-specified tool categories initOptions.requiredTools = mapCliToolsToInternal(argv.tools); console.log( ` Selective mode: Loading tools for ${argv.tools.join(", ")}`, ); } else { // Smart mode: analyze prompt for tool requirements initOptions.prompt = argv.prompt; console.log(" Smart mode: Analyzing prompt for required tools"); } const startTime = Date.now(); await neurolink.initializeMCP(initOptions); const initTime = Date.now() - startTime; console.log(`⚡ MCP initialized in ${initTime}ms`); // ... rest of generation logic }, ); function mapCliToolsToInternal(cliTools: string[]): string[] { const mapping: Record = { time: ["getCurrentTime"], math: ["calculateMath"], files: ["listDirectory", "readFile", "writeFile"], web: ["websearchGrounding"], }; return cliTools.flatMap((tool) => mapping[tool] || []); } ``` #### Expected Results - **CLI Speed Mode**: 7s → 1-2s (built-in tools only) - **CLI Selective**: 7s → 3-5s (based on tools needed) ### Phase 4: SDK Background Initialization Implementation #### Files to Modify - `src/lib/neurolink.ts` - Add background warmup and smart initialization #### Concept Implementation Start MCP initialization in the background during SDK instantiation, before any user requests: ```typescript // App startup const neurolink = new NeuroLink({ backgroundWarmup: true }); // Starts MCP loading // Later user request (MCP already warm) await neurolink.generate({ input: { text: "prompt" } }); // Fast response ``` #### Detailed Code Changes **File: `src/lib/neurolink.ts`** Add background warmup to constructor: ```typescript constructor(config?: { conversationMemory?: Partial; backgroundWarmup?: boolean; warmupTools?: string[]; }) { // ... existing constructor logic // Start background MCP warmup if requested if (config?.backgroundWarmup) { this.startBackgroundWarmup(config.warmupTools); } } private startBackgroundWarmup(tools?: string[]): void { // Start MCP initialization in background (non-blocking) setImmediate(async () => { try { await this.initializeMCP({ requiredTools: tools || ['getCurrentTime', 'calculateMath'], // Basic tools parallel: true }); logger.debug('Background MCP warmup completed successfully'); } catch (error) { logger.warn('Background MCP warmup failed, will initialize on first request:', error); } }); } ``` Update generate method for smart initialization: ```typescript private async generateTextInternal(options: TextGenerationOptions): Promise { // Smart initialization: only load MCP if not already initialized if (!this.mcpInitialized) { const requiredTools = ToolAnalyzer.analyzePromptForRequiredTools(options.prompt || ''); await this.initializeMCP({ requiredTools, parallel: true, prompt: options.prompt }); } // ... rest of generation logic } ``` #### Expected Results - **SDK Background**: 14s → 3-5s (warmup during app start) ## Implementation File Structure ### New Files to Create ``` src/lib/utils/toolAnalyzer.ts # Smart tool detection logic src/lib/mcp/mcpConnectionPool.ts # Connection reuse (future enhancement) src/cli/modes/performanceModes.ts # CLI mode definitions (future enhancement) ``` ### Files to Modify ``` src/lib/neurolink.ts # Main SDK class - add optimization options src/lib/mcp/externalServerManager.ts # MCP server management - add parallel/selective loading src/cli/index.ts # CLI command definitions - add performance flags ``` ## Expected Performance Results ### Phase 1 (Parallel Loading) - **CLI**: 24.8s → 12s (50% reduction) - **SDK**: 46.4s → 23s (50% reduction) ### Phase 2 (Smart Tool Detection) - **CLI**: 12s → 7s (additional 42% reduction) - **SDK**: 23s → 14s (additional 39% reduction) ### Phase 3 (CLI Performance Modes) - **CLI Speed Mode**: 7s → 1-2s (built-in tools only) - **CLI Selective**: 7s → 3-5s (based on tools needed) ### Phase 4 (SDK Background Loading) - **SDK Background**: 14s → 3-5s (warmup during app start) ### Final Performance Summary ```bash # Before optimization: CLI: 26.4s (production-blocking) SDK: 46.4s (completely unusable) # After optimization: CLI Speed Mode: 1-2s ✅ Production ready CLI Selective: 3-5s ✅ Production ready CLI Smart: 7s ✅ Acceptable SDK Background: 3-5s ✅ Production ready SDK Optimized: 8-12s ✅ Acceptable ``` ## Implementation Timeline ### Week 1: Parallel Loading Foundation 1. **Day 1-2**: Implement `loadMCPConfigurationParallel()` in `externalServerManager.ts` 2. **Day 3-4**: Add parallel option to `initializeMCP()` in `neurolink.ts` 3. **Day 5**: Test parallel loading with existing CLI and SDK, measure performance gains ### Week 2: Smart Tool Detection 1. **Day 1-2**: Create `toolAnalyzer.ts` with keyword detection logic 2. **Day 3-4**: Implement `initializeSelectiveTools()` in `neurolink.ts` 3. **Day 5**: Add `loadSelectiveServers()` in `externalServerManager.ts` and test ### Week 3: CLI Performance Modes 1. **Day 1-2**: Add CLI flags and options to `index.ts` 2. **Day 3-4**: Implement mode logic and tool mapping functions 3. **Day 5**: Test all CLI performance modes and document usage ### Week 4: SDK Background Loading 1. **Day 1-2**: Add background warmup to SDK constructor 2. **Day 3-4**: Modify generate method for smart initialization 3. **Day 5**: Performance testing, optimization, and final validation ## ✅ Testing & Validation ### Performance Benchmarks ```bash # Test CLI performance modes pnpm cli generate "What time is it?" --speed-mode # Target: <2s pnpm cli generate "Calculate 2+2" --tools=math # Target: <3s pnpm cli generate "List files" --tools=files # Target: <5s pnpm cli generate "Complex task" --parallel-loading # Target: <8s # Test SDK improvements node sdk-latency-test.js # Target: <10s first run node sdk-background-test.js # Target: <5s with warmup ``` ### Success Criteria - **CLI Speed Mode**: \<2s total response time - **CLI Selective**: \<5s total response time - **CLI Smart**: \<8s total response time - **SDK Background**: \<5s after warmup - **SDK First Run**: \<15s (down from 46s) - **Backward Compatibility**: All existing functionality works unchanged - **Error Handling**: Graceful fallback to current behavior on any optimization failure ## Conclusion This implementation guide provides a comprehensive, phase-by-phase approach to solving NeuroLink's MCP initialization performance crisis. By implementing parallel loading, smart tool detection, CLI performance modes, and SDK background initialization, we can transform the user experience from production-blocking (26-46 seconds) to production-ready (1-10 seconds). The approach prioritizes safety through backward compatibility and graceful degradation while delivering dramatic performance improvements that will enable NeuroLink to ship tool-enhanced features in production environments. --- ## MCP Foundation Testing Guide # MCP Foundation Testing Guide > ⚠️ **PLANNED FEATURE**: This documentation describes features that are planned but not yet implemented. The `ContextManager` class referenced in this guide does not currently exist in the codebase. The code examples are illustrative of the intended API design. **NeuroLink v1.3.0 MCP Foundation** - Comprehensive guide for testing MCP functionality and adding custom MCP servers. ## **Testing MCP Foundation Programmatically** ### **1. Basic MCP Server Creation** Create a test file to explore MCP functionality: ```typescript // test-mcp.ts (TypeScript; run with ts-node or compile first) NeuroLinkMCPTool, NeuroLinkExecutionContext, ToolResult, } from "@juspay/neurolink"; // Create a custom MCP server const testServer = createMCPServer({ id: "my-test-server", title: "My Test Server", description: "Testing custom MCP tools", category: "custom", visibility: "private", }); // Add a simple tool testServer.registerTool({ name: "hello-world", description: "Simple hello world tool for testing", execute: async ( params: any, context: NeuroLinkExecutionContext, ): Promise => { console.log("Hello World tool executed!"); console.log("Context:", context.sessionId); return { success: true, data: { message: `Hello, ${params.name || "World"}!` }, metadata: { toolName: "hello-world", timestamp: Date.now(), }, }; }, }); console.log("Test server created:", testServer.id); console.log("Available tools:", Object.keys(testServer.tools)); ``` ### **2. Testing with AI Core Server** ```typescript // test-ai-core.ts async function testAICoreServer() { // Create execution context const context = ContextManager.createExecutionContext({ sessionId: "test-session-123", userId: "test-user", aiProvider: "openai", environmentType: "development", }); console.log(" Testing AI Core Server..."); // Test text generation tool try { const result = await aiCoreServer.tools["generate"].execute( { prompt: "Write a haiku about AI", temperature: 0.7, maxTokens: 100, }, context, ); console.log("✅ Text Generation Result:", result); } catch (error) { console.error("❌ Text Generation Error:", error); } // Test provider selection tool try { const providerResult = await aiCoreServer.tools["select-provider"].execute( { preferred: "openai", requirements: { streaming: true, costEfficient: true, }, }, context, ); console.log("✅ Provider Selection Result:", providerResult); } catch (error) { console.error("❌ Provider Selection Error:", error); } // Test provider status tool try { const statusResult = await aiCoreServer.tools[ "check-provider-status" ].execute( { includeCapabilities: true, }, context, ); console.log("✅ Provider Status Result:", statusResult); } catch (error) { console.error("❌ Provider Status Error:", error); } } testAICoreServer(); ``` ### **3. Testing Tool Registry and Orchestration** ```typescript // test-orchestration.ts async function testOrchestration() { // Initialize registry and orchestrator const registry = new MCPRegistry(); const orchestrator = new ToolOrchestrator(registry); // Register AI Core Server registry.registerServer(aiCoreServer); // Create execution context const context = ContextManager.createExecutionContext({ sessionId: "orchestration-test", environmentType: "development", }); console.log(" Testing Tool Orchestration..."); // Execute single tool try { const result = await orchestrator.executeTool( "neurolink-ai-core", "generate", { prompt: "Explain quantum computing in one sentence", maxTokens: 50 }, context, ); console.log("✅ Single Tool Execution:", result); } catch (error) { console.error("❌ Single Tool Error:", error); } // Execute pipeline (sequential tools) try { const pipelineResult = await orchestrator.executePipeline( [ { serverId: "neurolink-ai-core", toolName: "select-provider", params: { preferred: "openai" }, }, { serverId: "neurolink-ai-core", toolName: "generate", params: { prompt: "Write a technical joke", maxTokens: 100 }, }, ], context, ); console.log("✅ Pipeline Execution:", pipelineResult); } catch (error) { console.error("❌ Pipeline Error:", error); } // Get orchestrator statistics const stats = orchestrator.getStatistics(); console.log(" Orchestrator Statistics:", stats); } testOrchestration(); ``` --- ## **Adding Custom MCP Servers** ### **1. Creating a Development Tools Server** ```typescript // servers/dev-tools-server.ts // Create development tools server export const devToolsServer = createMCPServer({ id: "neurolink-dev-tools", title: "NeuroLink Development Tools", description: "Code generation, testing, and development utilities", category: "development", version: "1.0.0", capabilities: [ "code-generation", "test-creation", "documentation", "refactoring", ], }); // Code Generation Tool devToolsServer.registerTool({ name: "generate-component", description: "Generate React/Vue/Svelte components with TypeScript", inputSchema: z.object({ framework: z.enum(["react", "vue", "svelte"]), componentName: z.string(), props: z .array( z.object({ name: z.string(), type: z.string(), required: z.boolean().default(false), }), ) .optional(), styling: z .enum(["css", "scss", "styled-components", "tailwind"]) .optional(), }), execute: async ( params: any, context: NeuroLinkExecutionContext, ): Promise => { const { framework, componentName, props = [], styling = "css" } = params; // Generate component code based on framework let componentCode = ""; if (framework === "react") { const propsInterface = props.length > 0 ? `interface ${componentName}Props {\n${props.map((p) => ` ${p.name}${p.required ? "" : "?"}: ${p.type};`).join("\n")}\n}\n\n` : ""; componentCode = `${propsInterface}export function ${componentName}(${props.length > 0 ? `props: ${componentName}Props` : ""}) { return ( ${componentName} Component {/* Add your component logic here */} ); }`; } else if (framework === "svelte") { const scriptProps = props.length > 0 ? `\n${props.map((p) => ` export let ${p.name}: ${p.type}${p.required ? "" : " | undefined"};`).join("\n")}\n\n\n` : ""; componentCode = `${scriptProps} ${componentName} Component .${componentName.toLowerCase()} { /* Add your styles here */ } `; } return { success: true, data: { code: componentCode, framework, componentName, propsCount: props.length, styling, }, metadata: { toolName: "generate-component", serverId: "neurolink-dev-tools", timestamp: Date.now(), }, }; }, }); // Test Generation Tool devToolsServer.registerTool({ name: "generate-tests", description: "Generate unit tests for components or functions", inputSchema: z.object({ testFramework: z.enum(["vitest", "jest", "playwright"]), targetFile: z.string(), functions: z.array(z.string()), coverage: z.enum(["basic", "comprehensive"]).default("basic"), }), execute: async ( params: any, context: NeuroLinkExecutionContext, ): Promise => { const { testFramework, targetFile, functions, coverage } = params; const testTemplate = `import { describe, it, expect } from '${testFramework}'; ${functions .map( (fn) => `describe('${fn}', () => { it('should ${coverage === "comprehensive" ? "handle all edge cases" : "work correctly"}', () => { // Test implementation for ${fn} expect(${fn}).toBeDefined(); }); });`, ) .join("\n\n")}`; return { success: true, data: { testCode: testTemplate, testFramework, functionsCount: functions.length, coverage, }, metadata: { toolName: "generate-tests", serverId: "neurolink-dev-tools", timestamp: Date.now(), }, }; }, }); console.log( "[DevTools] Development Tools Server created with tools:", Object.keys(devToolsServer.tools), ); ``` ### **2. Creating a Content Creation Server** ```typescript // servers/content-server.ts export const contentServer = createMCPServer({ id: "neurolink-content", title: "NeuroLink Content Creation", description: "Blog posts, documentation, and marketing content generation", category: "content", version: "1.0.0", }); // Blog Post Generation Tool contentServer.registerTool({ name: "generate-blog-post", description: "Generate blog posts with SEO optimization", inputSchema: z.object({ topic: z.string(), audience: z.enum(["technical", "business", "general"]), length: z.enum(["short", "medium", "long"]), tone: z.enum(["professional", "casual", "educational"]), includeSEO: z.boolean().default(true), }), execute: async ( params: any, context: NeuroLinkExecutionContext, ): Promise => { // Use AI Core Server for content generation const aiResult = (await context.toolChain?.includes("neurolink-ai-core")) ? { content: `Generated blog post about ${params.topic}...` } : { content: `Mock blog post about ${params.topic} for ${params.audience} audience`, }; const metadata = { wordCount: params.length === "short" ? 500 : params.length === "medium" ? 1000 : 2000, readingTime: params.length === "short" ? 2 : params.length === "medium" ? 5 : 8, seoOptimized: params.includeSEO, }; return { success: true, data: { content: aiResult.content, ...metadata, topic: params.topic, audience: params.audience, }, metadata: { toolName: "generate-blog-post", serverId: "neurolink-content", timestamp: Date.now(), }, }; }, }); console.log( "[Content] Content Creation Server created with tools:", Object.keys(contentServer.tools), ); ``` --- ## ️ **Adding MCP Commands to CLI** To integrate MCP functionality into the CLI, add these commands to `src/cli/index.ts`: ### **1. MCP Server Management Commands** ```typescript // Add to CLI (src/cli/index.ts) .command('mcp ', 'Manage MCP servers and tools', (yargsMCP) => { yargsMCP .usage('Usage: $0 mcp [options]') .command('list-servers', 'List all registered MCP servers', () => {}, async (argv) => { const registry = new MCPRegistry(); // Register default servers registry.registerServer(aiCoreServer); const servers = registry.listServers(); console.log(chalk.blue(' Registered MCP Servers:')); servers.forEach(server => { console.log(` • ${chalk.green(server.id)} - ${server.title}`); console.log(` Category: ${server.category}, Tools: ${server.toolCount}`); }); } ) .command('list-tools [serverId]', 'List tools for all servers or specific server', (y) => y.positional('serverId', { type: 'string', description: 'Optional server ID to filter tools' }), async (argv) => { const registry = new MCPRegistry(); registry.registerServer(aiCoreServer); const tools = argv.serverId ? registry.getServerTools(argv.serverId) : registry.listAllTools(); console.log(chalk.blue(' Available MCP Tools:')); tools.forEach(tool => { console.log(` • ${chalk.green(tool.name)} (${tool.serverId})`); console.log(` ${tool.description}`); }); } ) .command('execute ', 'Execute an MCP tool', (y) => y .positional('serverId', { type: 'string', demandOption: true }) .positional('toolName', { type: 'string', demandOption: true }) .option('params', { type: 'string', description: 'JSON parameters for the tool' }) .option('session', { type: 'string', default: 'cli-session', description: 'Session ID' }), async (argv) => { const registry = new MCPRegistry(); const orchestrator = new ToolOrchestrator(registry); // Register servers registry.registerServer(aiCoreServer); const context = ContextManager.createExecutionContext({ sessionId: argv.session, environmentType: 'development', aiProvider: 'auto' }); try { const params = argv.params ? JSON.parse(argv.params) : {}; const result = await orchestrator.executeTool( argv.serverId, argv.toolName, params, context ); console.log(chalk.green('✅ Tool execution successful:')); console.log(JSON.stringify(result, null, 2)); } catch (error) { console.error(chalk.red('❌ Tool execution failed:'), error); } } ) .demandCommand(1, 'Please specify an MCP subcommand'); } ) ``` ### **2. Quick MCP Testing Commands** ```typescript // Add convenience commands .command('mcp-generate ', 'Quick AI text generation via MCP', (y) => y .positional('prompt', { type: 'string', demandOption: true }) .option('provider', { type: 'string', description: 'Preferred AI provider' }), async (argv) => { const registry = new MCPRegistry(); const orchestrator = new ToolOrchestrator(registry); registry.registerServer(aiCoreServer); const context = ContextManager.createExecutionContext({ sessionId: 'mcp-cli-' + Date.now(), aiProvider: argv.provider }); try { const result = await orchestrator.executeTool( 'neurolink-ai-core', 'generate', { prompt: argv.prompt, maxTokens: 200 }, context ); if (result.success) { console.log('\n' + result.data.text + '\n'); console.log(chalk.blue(`Provider: ${result.data.provider}`)); } else { console.error(chalk.red('Generation failed:'), result.error); } } catch (error) { console.error(chalk.red('MCP execution error:'), error); } } ) ``` --- ## **Running MCP Tests** ### **1. Run Existing Test Suite** ```bash # Run comprehensive MCP tests pnpm run test:run # Run specific MCP tests npx vitest run test/mcp-comprehensive.test.ts ``` ### **2. Test Custom MCP Server** Create and run a test file: ```bash # Create test file cat > test-custom-mcp.ts ({ success: true, data: 'Hello from MCP!' }) }); console.log('Server created:', myServer.id); console.log('Tools:', Object.keys(myServer.tools)); EOF # Install ts-node if not available npm install -g ts-node typescript # Or use npx for one-time execution without global install # Run test npx ts-node test-custom-mcp.ts ``` ### **3. Test MCP via Node.js REPL** ```bash # Start Node.js REPL with NeuroLink node -r ts-node/register # In REPL: > const { createMCPServer } = require('@juspay/neurolink'); > const server = createMCPServer({ id: 'repl-test', title: 'REPL Test' }); > console.log('Server created:', server.id); ``` --- ## **MCP Development Workflow** ### **1. Development Cycle** 1. **Create MCP Server** - Use `createMCPServer()` 2. **Add Tools** - Register tools with validation 3. **Test Tools** - Use registry and orchestrator 4. **Integrate with CLI** - Add CLI commands 5. **Run Tests** - Validate functionality ### **2. Best Practices** - **Use TypeScript** for full type safety - **Validate inputs** with Zod schemas - **Handle errors** gracefully in tools - **Log execution** for debugging - **Test thoroughly** before deployment ### **3. Performance Monitoring** ```typescript // Monitor tool performance const stats = orchestrator.getStatistics(); console.log("Tool execution stats:", stats); // Track context usage const contextStats = ContextManager.getStatistics(); console.log("Context management stats:", contextStats); ``` --- ## **Next Steps** 1. **✅ Test Current Implementation** - Use programmatic testing examples 2. ** Add CLI Integration** - Implement MCP CLI commands 3. **️ Create Custom Servers** - Build domain-specific tool servers 4. ** Monitor Performance** - Track tool execution and usage 5. ** Iterate and Improve** - Enhance based on real usage **MCP Foundation is production-ready and waiting for your custom tools!** --- # Advanced ## Advanced Features # Advanced Features Explore NeuroLink's enterprise-grade capabilities that set it apart from basic AI integration libraries. ## What Makes NeuroLink Advanced NeuroLink goes beyond simple API wrappers to provide a comprehensive AI development platform with: - **Production-ready architecture** with factory patterns - **Built-in tool ecosystem** via Model Context Protocol (MCP) - **Real-time analytics** and performance monitoring - **Dynamic model management** with cost optimization - **Enterprise streaming** with multi-modal support ## Feature Overview - **[MCP Integration](/docs/mcp/integration)** — Model Context Protocol support: 6 built-in tools, plus connect any MCP-compliant external server. - **[Analytics & Evaluation](/docs/reference/analytics)** — Built-in usage tracking, cost monitoring, performance metrics, and AI response quality evaluation. - **[Factory Patterns](/docs/advanced/factory-patterns)** — Unified provider architecture using the Factory Pattern for consistent interfaces and easy extensibility. - **[Dynamic Models](/docs/guides/dynamic-models)** — Self-updating model configurations, automatic cost optimization, and smart model resolution. - **[Streaming](/docs/advanced/streaming)** — Real-time streaming architecture with analytics support and multi-modal readiness. - **[Middleware Architecture](/docs/advanced/middleware-architecture)** — Comprehensive middleware system for request/response processing, logging, and custom transformations. - **[Built-in Middleware](/docs/advanced/builtin-middleware)** — Pre-built middleware for analytics, guardrails, and auto-evaluation. ## ️ Middleware System NeuroLink includes a powerful middleware architecture for extending functionality: - **[Middleware Architecture](/docs/advanced/middleware-architecture)** - Complete middleware lifecycle and factory patterns - **[Built-in Middleware](/docs/advanced/builtin-middleware)** - Analytics, Guardrails, Auto-Evaluation middleware reference - **[Custom Middleware Guide](/docs/workflows/custom-middleware)** - Build your own middleware with examples ## Architecture Highlights ### Factory Pattern Implementation ```typescript // All providers inherit from BaseProvider class OpenAIProvider extends BaseProvider { protected getProviderName(): AIProviderName { return "openai"; } protected async getAISDKModel(): Promise { return openai(this.modelName); } } // Unified interface across all providers const provider = createBestAIProvider(); const result = await provider.generate({ /* options */ }); ``` ### Built-in Tool System ```typescript // Tools are always available by default const result = await neurolink.generate({ input: { text: "What time is it?" }, // Built-in tools automatically handle time requests }); // Disable tools for pure text generation const pureResult = await neurolink.generate({ input: { text: "Write a poem" }, disableTools: true, }); ``` ### Real-time Analytics ```typescript const result = await neurolink.generate({ input: { text: "Generate a report" }, enableAnalytics: true, }); console.log(result.analytics); // { // provider: "google-ai", // model: "gemini-2.5-flash", // tokens: { input: 10, output: 150, total: 160 }, // cost: 0.000012, // responseTime: 1250, // toolsUsed: ["getCurrentTime"] // } ``` ## Enterprise Capabilities ### Performance Optimization - **68% faster provider status checks** (16s → 5s via parallel execution) - **Automatic memory management** for operations >50MB - **Circuit breakers** and retry logic for resilience - **Rate limiting** to prevent API quota exhaustion ### Edge Case Handling - **Input validation** with helpful error messages - **Timeout warnings** for long-running operations - **Network resilience** with automatic retries - **Graceful degradation** when providers fail ### Production Features - **Comprehensive error handling** with detailed logging - **Type safety** with full TypeScript support - **Configurable timeouts** and resource limits - **Environment-aware configuration** loading ## Use Case Examples ```typescript // Automated content pipeline with analytics const pipeline = new NeuroLink({ enableAnalytics: true }); const articles = await Promise.all( topics.map(topic => pipeline.generate({ input: { text: `Write article about ${topic}` }, maxTokens: 2000, temperature: 0.7, }) ) ); // Analyze costs and performance const totalCost = articles.reduce((sum, article) => sum + (article.analytics?.cost || 0), 0 ); ``` ```typescript // Future-ready streaming with multi-modal support const stream = await neurolink.stream({ input: { text: "Analyze this data", // Future: image, audio, video inputs }, enableAnalytics: true, enableEvaluation: true, }); for await (const chunk of stream.stream) { // Real-time processing with tool calls if (chunk.toolCall) { console.log(`Tool used: ${chunk.toolCall.name}`); } process.stdout.write(chunk.content); } ``` ```typescript // Production monitoring and alerting const result = await neurolink.generate({ input: { text: prompt }, enableAnalytics: true, context: { userId, sessionId, environment: process.env.NODE_ENV }, }); // Custom monitoring integration if (result.analytics.responseTime > 5000) { logger.warn(`Slow AI response: ${result.analytics.responseTime}ms`); } if (result.analytics.cost > 0.10) { logger.warn(`High cost request: $${result.analytics.cost}`); } ``` ## Future Roadmap - **Real-time WebSocket Infrastructure** (in development) - **Advanced caching** strategies ## Deep Dive Resources Each advanced feature has comprehensive documentation with examples, best practices, and troubleshooting guides: - **[Factory Pattern Migration Guide](/docs/development/factory-migration)** - Upgrade from older architectures - **[MCP Testing Guide](/docs/development/testing)** - Test tool integrations - **[Performance Tuning](/docs/deployment/configuration)** - Optimize for your use case - **[Production Deployment](/docs/examples/business)** - Enterprise deployment patterns --- ## Analytics & Evaluation # Analytics & Evaluation Advanced analytics and AI response evaluation features for monitoring usage, performance, and quality. ## Overview NeuroLink provides comprehensive analytics and evaluation capabilities to help you monitor AI usage, track performance, and assess response quality. These features are essential for production applications and enterprise deployments. ## Analytics Features ### Usage Analytics Track detailed metrics about your AI interactions: ```typescript const neurolink = new NeuroLink({ analytics: { enabled: true, endpoint: "https://analytics.yourcompany.com", apiKey: process.env.ANALYTICS_API_KEY, }, }); // Analytics automatically tracked const result = await neurolink.generate({ input: { text: "Generate report" }, context: { userId: "user123", sessionId: "sess456", department: "engineering", }, }); ``` ### CLI Analytics Enable analytics in CLI commands: ```bash # Enable analytics for single command npx @juspay/neurolink gen "Analyze data" --enable-analytics # With custom context npx @juspay/neurolink gen "Business analysis" \ --enable-analytics \ --context '{"team":"product","project":"dashboard"}' \ --debug ``` ### Tracked Metrics - **Usage Statistics**: Request count, frequency, patterns - **Performance Metrics**: Response time, token usage, costs - **Provider Statistics**: Success rates, error patterns, latency - **Cost Analysis**: Per-provider costs, budget tracking - **User Analytics**: Usage by user, team, or department - **Quality Metrics**: Response evaluation scores ## Response Evaluation ### AI-Powered Quality Assessment ```typescript // Enable evaluation for quality scoring const result = await neurolink.generate({ input: { text: "Write production code" }, enableEvaluation: true, evaluationDomain: "Senior Software Engineer", evaluationCriteria: ["accuracy", "completeness"], }); console.log(result.evaluation); // { // overall: 9.2, // relevance: 9.5, // accuracy: 9.0, // completeness: 8.8, // reasoning: "Code follows best practices...", // alertSeverity: "none" // } ``` ### CLI Evaluation ```bash # Basic evaluation npx @juspay/neurolink gen "Write API documentation" --enable-evaluation # Domain-specific evaluation npx @juspay/neurolink gen "Design system architecture" \ --enable-evaluation \ --evaluation-domain "Solutions Architect" # Combined analytics and evaluation npx @juspay/neurolink gen "Create test plan" \ --enable-analytics \ --enable-evaluation \ --evaluation-domain "QA Engineer" \ --debug ``` ### Evaluation Domains Specialized evaluation contexts: - **Technical**: `Senior Software Engineer`, `DevOps Specialist`, `Data Scientist` - **Business**: `Product Manager`, `Business Analyst`, `Marketing Manager` - **Creative**: `Content Writer`, `UX Designer`, `Creative Director` - **Academic**: `Research Scientist`, `Technical Writer`, `Educator` ## Analytics Collection ### Per-Request Analytics Analytics are collected on a per-request basis and included in each result: ```typescript // Enable analytics for a single request const result = await neurolink.generate({ input: { text: "Generate documentation" }, enableAnalytics: true, }); // Access analytics from the result console.log(result.analytics); // { // totalTokens: 1523, // promptTokens: 421, // completionTokens: 1102, // cost: 0.0045, // durationMs: 1456, // provider: "openai", // model: "gpt-4o" // } ``` ### Middleware-Based Analytics For application-wide analytics collection, use the analytics middleware: ```typescript // Analytics are automatically collected by the middleware const metrics = getAnalyticsMetrics(); // Process or export metrics as needed console.log(metrics); // Clear metrics after processing clearAnalyticsMetrics(); ``` ## Configuration ### Environment Variables ```bash # Evaluation Configuration NEUROLINK_EVALUATION_PROVIDER="google-ai" NEUROLINK_EVALUATION_MODEL="gemini-2.5-flash" NEUROLINK_EVALUATION_THRESHOLD="7" ``` ### Per-Request Configuration Analytics and evaluation are configured on a per-request basis: ```typescript // Enable analytics and evaluation for specific requests const result = await neurolink.generate({ input: { text: "Your prompt" }, enableAnalytics: true, enableEvaluation: true, evaluationDomain: "Senior Software Engineer", evaluationCriteria: ["accuracy", "completeness"], }); ``` ## Available Methods The following methods are fully available in the SDK for advanced analytics, performance monitoring, and cost calculations: | Method | Description | | -------------------------------------- | ------------------------------------------------- | | `neurolink.getProviderMetrics()` | Get aggregated provider metrics and performance | | `neurolink.getCostAnalysis()` | Get granular cost breakdown and projections | | `neurolink.getTeamAnalytics()` | Get team-wide usage, unique users, and quality | | `neurolink.getProviderStatus()` | Get provider availability status | | `neurolink.getProviderHealthSummary()` | Get health summary for all providers | | `neurolink.getToolExecutionMetrics()` | Get tool execution statistics | | `getAnalyticsMetrics()` | Standalone middleware function for analytics data | ```typescript const neurolink = new NeuroLink(); // Get provider metrics const providerMetrics = await neurolink.getProviderMetrics({ timeRange: "last_7_days", }); console.log(providerMetrics); // Get granular cost analysis const costAnalysis = await neurolink.getCostAnalysis({ includeProjections: true, }); console.log(costAnalysis); // Get team usage analytics const teamAnalytics = await neurolink.getTeamAnalytics({ teamId: "engineering-core", }); console.log(teamAnalytics); ``` --- ## Use Cases ### Performance Monitoring ```typescript // Monitor provider performance const perfMetrics = await neurolink.getProviderMetrics({ providers: ["openai", "google", "anthropic"], timeRange: "last_24_hours", }); // Identify best performing provider by average latency const bestProvider = perfMetrics.providers.sort( (a, b) => a.averageLatency - b.averageLatency, )[0]; console.log(`Best provider: ${bestProvider.name}`); ``` ### Cost Optimization ```typescript // Track costs and project future spend const costAnalysis = await neurolink.getCostAnalysis({ timeRange: "current_month", groupBy: ["provider", "model"], includeProjections: true, }); console.log(`Current spend: $${costAnalysis.totalCost}`); console.log(`Projected next month: $${costAnalysis.projections?.nextMonth}`); ``` ### Quality Assurance ```bash # Batch evaluate responses for quality cat prompts.txt | while read prompt; do npx @juspay/neurolink gen "$prompt" \ --enable-evaluation \ --evaluation-domain "Senior Engineer" \ --json >> evaluations.json done # Analyze quality trends jq '.evaluation.overall' evaluations.json | awk '{sum+=$1} END {print "Average quality:", sum/NR}' ``` ## Enterprise Features ### Team Analytics ```typescript // Department-level analytics and user attribution const teamMetrics = await neurolink.getTeamAnalytics({ departments: ["engineering", "product", "marketing"], timeRange: "last_30_days", }); console.log(`Total active unique users: ${teamMetrics.uniqueUsers}`); ``` ### Custom Metrics ```typescript // Define custom analytics tracking const result = await neurolink.generate({ input: { text: "Generate report" }, analytics: { customMetrics: { feature: "report_generation", complexity: "high", businessValue: "critical", }, }, }); ``` ### Compliance Monitoring ```bash # Audit trail with evaluation npx @juspay/neurolink gen "Sensitive analysis" \ --enable-analytics \ --enable-evaluation \ --context '{"compliance":"required","audit":"true"}' \ --evaluation-domain "Compliance Officer" ``` ## Related Documentation - [CLI Commands](/docs/cli/commands) - Analytics CLI commands - [Environment Variables](/docs/getting-started/environment-variables) - Configuration - [SDK Reference](/docs/sdk/api-reference) - Programmatic analytics - [Enterprise Setup](/docs/guides/enterprise) - Enterprise features --- ## Authentication Architecture # Authentication Architecture > **Audience**: Contributors and advanced users who need to understand how authentication is wired into NeuroLink's internals. ## Design Principles NeuroLink's auth system follows the same architectural patterns used for AI providers: 1. **Factory + Registry** -- providers are registered with factory functions and instantiated on demand via dynamic imports to avoid circular dependencies 2. **Lazy initialization** -- the auth provider is not created in the synchronous constructor; it is initialized on first use (generate/stream with `auth.token`) 3. **Fail closed** -- a valid token that does not resolve to a user identity is treated as an authentication failure 4. **Token-derived identity wins** -- when both `auth.token` and `requestContext` are provided, token-derived fields (`userId`, `userEmail`, `userRoles`) override `requestContext` to prevent privilege escalation ## System Overview ``` NeuroLink Constructor | auth config stored (pendingAuthConfig) | ┌─────────────────┴──────────────────┐ | | generate()/stream() setAuthProvider() with auth.token (explicit init) | | ensureAuthProvider() ────────────> AuthProviderFactory | .create(type, config) | | provider.authenticateToken(token) Dynamic import | provider module TokenValidationResult | | AuthProvider userId/email/roles instance returned merged into context ``` ## Factory + Registry Pattern ### AuthProviderFactory `AuthProviderFactory` extends `BaseFactory` and follows the singleton pattern. It registers 11 provider factory functions during initialization, each using dynamic imports: ``` AuthProviderFactory.getInstance() └── registerAll() ├── "auth0" → import("./providers/auth0.js") ├── "clerk" → import("./providers/clerk.js") ├── "firebase" → import("./providers/firebase.js") ├── "supabase" → import("./providers/supabase.js") ├── "cognito" → import("./providers/CognitoProvider.js") ├── "keycloak" → import("./providers/KeycloakProvider.js") ├── "better-auth" → import("./providers/betterAuth.js") ├── "workos" → import("./providers/workos.js") ├── "custom" → import("./providers/custom.js") ├── "oauth2" → import("./providers/oauth2.js") └── "jwt" → import("./providers/jwt.js") ``` Each registration includes: - **Type identifier** -- canonical name (e.g., `"auth0"`) - **Factory function** -- async function that dynamically imports and instantiates the provider - **Aliases** -- alternative names for convenience (e.g., `"auth0-jwt"`, `"auth0-oauth"`) - **Metadata** -- human-readable name, description, documentation URL The `create(type, config)` method: 1. Calls `ensureInitialized()` to lazily run `registerAll()` once 2. Resolves the name through alias lookup via `resolveName()` 3. Calls the registered factory function with the provider config 4. Returns the `AuthProvider` instance ### AuthProviderRegistry `AuthProviderRegistry` extends `BaseRegistry` and layers metadata and discovery on top of the factory: - Tracks provider capabilities (features like `jwt-validation`, `session-management`, `sso`) - Provides discovery APIs (`getProvidersByFeature()`, `getBuiltInProviders()`) - Runs health checks by creating temporary provider instances - Caches health status per provider type The registry does not create providers directly; it delegates to `AuthProviderFactory.create()`. ### Error Factories Both `AuthProviderFactory` and `AuthProviderRegistry` use `createErrorFactory()` from the core infrastructure to produce typed errors with unique codes: | Module | Code Prefix | Example | | -------- | ---------------- | ------------------------------- | | Factory | `AUTH_FACTORY-` | `AUTH_FACTORY-001` (not found) | | Registry | `AUTH_REGISTRY-` | `AUTH_REGISTRY-001` (not found) | ## Provider Interface All providers implement the `AuthProvider` type, which defines: ### Required Methods | Method | Purpose | | -------------------------- | ------------------------------------------------- | | `authenticateToken()` | Validate and decode a token, return user identity | | `extractToken()` | Extract token from request context | | `authorizeUser()` | Check if user has a specific permission | | `authorizeRoles()` | Check if user has any of the required roles | | `authorizePermissions()` | Check if user has all specified permissions | | `createSession()` | Create a new session for a user | | `getSession()` | Get an existing session by ID | | `refreshSession()` | Extend a session's expiration | | `destroySession()` | Invalidate a session | | `getUserSessions()` | Get all active sessions for a user | | `destroyAllUserSessions()` | Global logout | | `authenticateRequest()` | Full request authentication flow | | `healthCheck()` | Check provider connectivity | ### Optional Methods | Method | Purpose | | ------------------------- | ------------------------------- | | `refreshToken()` | Refresh an authentication token | | `revokeToken()` | Revoke a token (logout) | | `getUser()` | Get user by ID | | `getUserByEmail()` | Get user by email | | `updateUserMetadata()` | Update user metadata | | `updateUserRoles()` | Update user roles | | `updateUserPermissions()` | Update user permissions | | `initialize()` | Provider initialization | | `cleanup()` | Resource cleanup | ### BaseAuthProvider The abstract `BaseAuthProvider` class provides default implementations for token extraction, authorization checks, and the full `authenticateRequest()` flow. Concrete providers only need to implement the abstract methods: - `authenticateToken()` -- provider-specific token validation - `createSession()` / `getSession()` / `refreshSession()` / `destroySession()` -- session lifecycle - `getUserSessions()` / `destroyAllUserSessions()` -- multi-session management The base class also: - Defaults token extraction to `Authorization: Bearer` header with case-insensitive lookup - Supports hierarchical wildcard permissions (e.g., `tools:*` matches `tools:execute`) - Supports role hierarchy via `config.rbac.roleHierarchy` - Emits `auth:unauthorized` events via `EventEmitter` ## Request Authentication Flow ### Per-Call Token Validation (generate/stream) When `auth: { token }` is passed to `generate()` or `stream()`: ``` 1. ensureAuthProvider() └── If authProvider is null and pendingAuthConfig exists: └── setAuthProvider(pendingAuthConfig) [one-time lazy init] 2. authProvider.authenticateToken(token) └── 5-second timeout via withTimeout() 3. If result is invalid: └── throw InvalidTokenError(result.error, provider.type) 4. If result is valid and result.user exists: └── Merge into options.context: { userId, userEmail, userRoles } 5. If both auth.token and requestContext exist: └── Token-derived identity fields OVERRIDE requestContext (prevents privilege escalation) 6. Proceed with AI generation ``` ### Server Middleware Flow When using `createAuthMiddleware()`: ``` 1. Check if route is public (isPublicRoute) └── If public: return { proceed: true } 2. Extract token (extractToken) └── Header → Cookie → Query → Custom └── If no token and not optional: return 401 3. Validate token (provider.authenticateToken) └── If invalid and not optional: return 401 4. Fail closed: valid token without user → return 401 5. Build AuthenticatedContext: { ...requestContext, user, token, claims } 6. Call onAuthenticated hook (if configured) 7. Return { proceed: true, context } ``` ### RBAC Enforcement Flow When using `createRBACMiddleware()`: ``` 1. Check user exists └── If no user: return 401 2. Check super admin roles └── If user has any super admin role: bypass all checks 3. Expand roles via hierarchy └── e.g., admin → [admin, moderator, viewer] 4. Build effective permissions └── Direct permissions + rolePermissions mapping for all expanded roles 5. Run custom authorization function (if configured) └── If denied: return 403 6. Check role requirements └── requireAllRoles: every role must be present └── Default: any role must be present └── If insufficient: return 403 7. Check permission requirements (all required) └── Uses effective permissions (includes role-derived) └── If insufficient: return 403 8. Return { proceed: true, context } ``` ## Session Lifecycle ``` authenticateRequest() | extractToken(context) | authenticateToken(token) | ┌──────┴──────┐ | | getUserSessions() (no existing session) | | find valid session createSession(user, context) | | └──────┬──────┘ | AuthenticatedContext { user, session } ``` ### Storage Backends | Backend | Class | Characteristics | | --------- | -------------------------- | ----------------------------------------------------- | | In-memory | `MemorySessionStorage` | Single-instance, sessions lost on restart | | Redis | `RedisSessionStorage` | Distributed, TTL-based expiration, redis (node-redis) | | Custom | Implement `SessionStorage` | User-provided storage backend | `SessionManager` wraps the storage backend and adds: - Automatic session refresh when close to expiration (`refreshThreshold`) - Configurable session duration - Metadata updates - Health checks ## AsyncLocalStorage Context Propagation NeuroLink uses Node.js `AsyncLocalStorage` to make the authenticated context available throughout the request lifecycle: ``` runWithAuthContext(context, callback) └── AsyncLocalStorage.run(context, callback) └── Inside callback (any depth): getAuthContext() → AuthenticatedContext | undefined getCurrentUser() → AuthUser | undefined getCurrentSession() → AuthSession | undefined isAuthenticated() → boolean requireAuth() → AuthenticatedContext (throws if not set) hasPermission(p) → boolean hasRole(r) → boolean requirePermission(p) → void (throws if denied) requireRole(r) → void (throws if denied) ``` For environments where `AsyncLocalStorage` is not available (edge runtimes, etc.), the `globalAuthContext` singleton (`AuthContextHolder`) provides an imperative alternative with the same API surface. ## Integration Points ### NeuroLink SDK | Method | Where | What it does | | ----------------------- | ------------------------- | ---------------------------------------------------------------- | | `constructor({ auth })` | `src/lib/neurolink.ts` | Stores `pendingAuthConfig` for lazy init | | `setAuthProvider()` | `src/lib/neurolink.ts` | Creates or sets the auth provider | | `getAuthProvider()` | `src/lib/neurolink.ts` | Returns the current auth provider | | `ensureAuthProvider()` | `src/lib/neurolink.ts` | Lazy init on first use | | `setAuthContext()` | `src/lib/neurolink.ts` | Sets global auth context | | Per-call auth | `generate()` / `stream()` | Token validation, context merge, privilege escalation prevention | ### Server Routes | Route | Where | Auth Integration | | -------------------------- | -------------------------------------- | ---------------------------------------------- | | `POST /api/agent/generate` | `src/lib/server/routes/agentRoutes.ts` | `requestContext` and `authContext` passthrough | | `POST /api/agent/stream` | `src/lib/server/routes/agentRoutes.ts` | `requestContext` and `authContext` passthrough | ### CLI | Command | Where | What it does | | ---------------------------------- | ----------------------------------- | ----------------------------------- | | `auth providers` | `src/cli/commands/authProviders.ts` | List all 11 providers with metadata | | `auth validate` | `src/cli/commands/authProviders.ts` | Validate a token against a provider | | `auth health` | `src/cli/commands/authProviders.ts` | Health check a provider | | `auth login/logout/status/refresh` | `src/cli/commands/auth.ts` | Anthropic OAuth management | ### Tool Execution Authentication context can be passed to tool execution: ```typescript await neurolink.executeTool("myTool", { input: { query: "..." }, authContext: { userId: "user-123", roles: ["admin"], }, }); ``` ## Error Hierarchy ``` BaseError (from src/lib/types/errors.ts) └── AuthError (auth base class) ├── AuthenticationFailedError ├── MissingTokenError ├── InvalidTokenError ├── TokenExpiredError ├── InsufficientPermissionsError ├── SessionNotFoundError ├── SessionExpiredError ├── UserNotFoundError ├── ProviderInitializationError ├── InvalidConfigurationError ├── ProviderAPIError └── AuthRateLimitError ``` Each error carries the provider type (`error.provider`) so error handlers can distinguish provider-specific failures. ## Rate Limiting Architecture The rate limiter uses the **token bucket algorithm**: - Each user gets a bucket with `maxRequests` tokens - Tokens are continuously refilled at `maxRequests / windowMs` rate - Each request consumes one token - When the bucket is empty, requests are rejected with `429 Too Many Requests` ### Concurrency Safety - **In-memory**: Single-threaded Node.js guarantees atomicity - **Redis**: Uses a Lua script (`atomicConsume`) that performs refill-and-consume in a single atomic operation, preventing race conditions where parallel requests read the same token count ### Role-Based Differentiation - `roleLimits` assigns per-role limits (highest limit wins for multi-role users) - `userLimits` assigns per-user overrides - `skipRoles` bypasses rate limiting entirely for specified roles (e.g., `super-admin`) ## Adding a New Auth Provider 1. Create a provider class in `src/lib/auth/providers/myProvider.ts` that extends `BaseAuthProvider` 2. Implement the abstract methods: `authenticateToken()`, `createSession()`, `getSession()`, `refreshSession()`, `destroySession()`, `getUserSessions()`, `destroyAllUserSessions()` 3. Register the provider in `AuthProviderFactory.registerAll()` with a dynamic import 4. Register metadata in `AuthProviderRegistry.registerAll()` 5. Add the type name to `AuthProviderType` union in `src/lib/types/authTypes.ts` 6. Add a typed config to `src/lib/types/authTypes.ts` and a discriminated union branch to `NeuroLinkAuthConfig` in `src/lib/types/configTypes.ts` 7. Add environment variable mappings to `buildProviderConfig()` in `src/cli/commands/authProviders.ts` 8. Export the provider from `src/lib/auth/index.ts` 9. Add tests ## See Also - [Authentication Providers Guide](/docs/features/authentication-providers) -- user-facing guide with configuration examples - [Factory Pattern Architecture](/docs/development/factory-architecture) -- how NeuroLink uses factory + registry across the codebase - [Middleware Architecture](/docs/advanced/middleware-architecture) -- the broader middleware system --- ## Built-in Middleware Reference # Built-in Middleware Reference NeuroLink includes three built-in middleware components for common use cases: **Analytics**, **Guardrails**, and **Auto-Evaluation**. They ship ready to wire into your generate/stream calls. ## Quick Start Enable all built-in middleware with a single preset: ```typescript const factory = new MiddlewareFactory({ preset: "all", // Enables analytics + guardrails }); ``` Or enable specific middleware: ```typescript const factory = new MiddlewareFactory({ enabledMiddleware: ["analytics", "guardrails", "autoEvaluation"], }); ``` ### Defaults for every call Instead of repeating `middleware` on each `generate()` or `stream()` call, set it once. From lowest to highest precedence: | Layer | How | | ----------- | ---------------------------------------------------- | | Environment | `NEUROLINK_MIDDLEWARE_PRESET=default\|all\|security` | | Global | `configureGlobalMiddleware({ preset: "all" })` | | Instance | `new NeuroLink({ middleware: { preset: "all" } })` | | Per call | `generate({ middleware: { preset: "all" } })` | `middlewareConfig` merges per middleware id; lists and other keys set by a higher layer replace the lower layer's value. With no default set, calls are unchanged. See [Guardrails: Defaults and precedence](/docs/features/guardrails.md#defaults-and-precedence) for the full rules. ----------- | ------ | ---------------------------------- | ------------ | | `requestId` | string | Unique identifier for this request | - | | `timestamp` | string | ISO 8601 timestamp | - | | `responseTime` | number | Total request duration | milliseconds | | `usage.input` | number | Input tokens consumed | tokens | | `usage.output` | number | Output tokens generated | tokens | | `usage.total` | number | Total tokens used | tokens | ### Output Format Analytics data is automatically added to the response metadata: **Generate Response:** ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain quantum computing" }, provider: "openai", model: "gpt-4", }); // Access analytics from response metadata const analytics = result.experimental_providerMetadata?.neurolink?.analytics; console.log(analytics); ``` **Analytics Object Structure:** ```json { "requestId": "analytics-1735689600000", "responseTime": 1523, "timestamp": "2026-01-01T00:00:00.000Z", "usage": { "input": 12, "output": 256, "total": 268 } } ``` **Stream Response:** For streaming responses, analytics are available in the `rawResponse`: ```typescript const result = await neurolink.stream({ input: { text: "Write a story" }, }); // Analytics available in rawResponse const streamAnalytics = result.rawResponse?.neurolink?.analytics; console.log(streamAnalytics); ``` **Stream Analytics Structure:** ```json { "requestId": "analytics-stream-1735689600000", "startTime": 1735689600000, "timestamp": "2026-01-01T00:00:00.000Z", "streamingMode": true } ``` ### Use Cases **1. Cost Tracking:** ```typescript const result = await neurolink.generate({ input: { text: "..." } }); const analytics = result.experimental_providerMetadata?.neurolink?.analytics; // Calculate cost (example: $0.03 per 1K input tokens, $0.06 per 1K output tokens) const inputCost = (analytics.usage.input / 1000) * 0.03; const outputCost = (analytics.usage.output / 1000) * 0.06; const totalCost = inputCost + outputCost; console.log(`Request cost: $${totalCost.toFixed(4)}`); ``` **2. Performance Monitoring:** ```typescript const analytics = result.experimental_providerMetadata?.neurolink?.analytics; if (analytics.responseTime > 3000) { console.warn(`Slow request detected: ${analytics.responseTime}ms`); // Send alert to monitoring system } ``` **3. Usage Analytics Dashboard:** ```typescript // Aggregate analytics over multiple requests const requests = []; for (const prompt of prompts) { const result = await neurolink.generate({ input: { text: prompt } }); const analytics = result.experimental_providerMetadata?.neurolink?.analytics; requests.push(analytics); } // Calculate aggregates const totalTokens = requests.reduce((sum, a) => sum + a.usage.total, 0); const avgResponseTime = requests.reduce((sum, a) => sum + a.responseTime, 0) / requests.length; console.log(`Total tokens used: ${totalTokens}`); console.log(`Average response time: ${avgResponseTime}ms`); ``` ### Integration with External Systems **Send to Datadog:** ```typescript const dogstatsd = new StatsD(); const result = await neurolink.generate({ input: { text: "..." } }); const analytics = result.experimental_providerMetadata?.neurolink?.analytics; dogstatsd.histogram("neurolink.response_time", analytics.responseTime); dogstatsd.increment("neurolink.tokens.total", analytics.usage.total); dogstatsd.increment("neurolink.requests.success"); ``` **Send to Prometheus:** ```typescript const responseTimeHistogram = new Histogram({ name: "neurolink_response_time_ms", help: "Response time in milliseconds", buckets: [100, 500, 1000, 2000, 5000], }); const tokenCounter = new Counter({ name: "neurolink_tokens_total", help: "Total tokens consumed", }); const result = await neurolink.generate({ input: { text: "..." } }); const analytics = result.experimental_providerMetadata?.neurolink?.analytics; responseTimeHistogram.observe(analytics.responseTime); tokenCounter.inc(analytics.usage.total); ``` --- ## Guardrails Middleware ### Purpose The **Guardrails Middleware** provides comprehensive content filtering and policy enforcement to block or redact unsafe content, prevent prompt injection attacks, and maintain compliance with content policies. **Key Capabilities:** - Bad word filtering (configurable word list) - AI model-based content safety evaluation - Precall evaluation (block unsafe prompts before they reach the LLM) - Stream and generate support - Configurable filtering actions (block, redact, log) ### Configuration **Basic Configuration:** ```typescript const factory = new MiddlewareFactory({ middlewareConfig: { guardrails: { enabled: true, config: { badWords: ["inappropriate", "unsafe", "prohibited"], }, }, }, }); ``` **Advanced Configuration with Model-Based Filtering:** ```typescript // `filterModel` takes a model handle. NeuroLink no longer depends on the Vercel // AI SDK, so build the handle from NeuroLink's own factory rather than from // `@ai-sdk/openai`. const filterProvider = await AIProviderFactory.createProvider( "openai", "gpt-4o-mini", ); const factory = new MiddlewareFactory({ middlewareConfig: { guardrails: { enabled: true, config: { // Basic word filtering badWords: ["spam", "scam", "inappropriate"], // AI model-based filtering modelFilter: { enabled: true, filterModel: await filterProvider.getModel(), // A fast model for filtering }, }, }, }, }); ``` **Precall Evaluation (Block Unsafe Prompts):** ```typescript const factory = new MiddlewareFactory({ middlewareConfig: { guardrails: { enabled: true, config: { badWords: ["prohibited"], // Precall evaluation blocks unsafe prompts before they reach the LLM precallEvaluation: { enabled: true, provider: "openai", evaluationModel: "gpt-4", // Model name as string thresholds: { safetyScore: 7, // Safety threshold (1-10 scale, higher = more restrictive) appropriatenessScore: 6, // Appropriateness threshold (1-10 scale) }, blockUnsafeRequests: true, // Block requests that fail evaluation }, }, }, }, }); ``` ### Built-in Filters | Filter Type | Description | Action | Configuration | | ---------------------- | -------------------------------------- | ----------------- | --------------------------------- | | **Bad Words** | Block/redact specific words or phrases | Redact with `***` | `badWords: string[]` | | **Model-Based** | Use AI to evaluate content safety | Block if unsafe | `modelFilter.enabled: true` | | **Precall Evaluation** | Block unsafe prompts before LLM call | Block request | `precallEvaluation.enabled: true` | ### Bad Word Filtering **How It Works:** The bad word filter scans both requests and responses for prohibited terms and replaces them with `***`. **Example:** ```typescript // Input prompt: "This is an inappropriate message" // With badWords: ["inappropriate"] // Output: "This is an *** message" ``` **Configuration:** ```typescript config: { badWords: [ "inappropriate", "prohibited", "unsafe", // Add your organization's blocked terms ]; } ``` ### Model-Based Filtering **How It Works:** Uses a separate AI model to evaluate whether content is safe. The filter sends the content to the model with a safety evaluation prompt. **Safety Evaluation Prompt:** ``` Is the following text safe? Respond with only "safe" or "unsafe". Text: "[content to evaluate]" ``` **Example:** ```typescript // If model responds "unsafe", content is redacted // Output: "" ``` **Configuration:** ```typescript const filterProvider = await AIProviderFactory.createProvider( "openai", "gpt-4o-mini", ); config: { modelFilter: { enabled: true, filterModel: await filterProvider.getModel() // Fast, cost-effective model } } ``` ### Precall Evaluation **How It Works:** Evaluates the safety of the input prompt **before** it reaches the main LLM. If the prompt is deemed unsafe, the request is blocked entirely, saving costs and preventing unsafe content generation. **Evaluation Process:** 1. User submits a prompt 2. Guardrails middleware intercepts in `transformParams` 3. Safety evaluation model scores the prompt (0-1 scale) 4. If score = threshold, request proceeds to main LLM **Blocked Response:** ```json { "text": "", "usage": { "promptTokens": 0, "completionTokens": 0 } } ``` **Configuration:** ```typescript config: { precallEvaluation: { enabled: true, provider: "openai", evaluationModel: "gpt-4", // Model for safety evaluation (string) thresholds: { safetyScore: 7, // Safety threshold (1-10 scale, default 7) appropriatenessScore: 6, // Appropriateness threshold (1-10 scale, default 6) }, blockUnsafeRequests: true, // Block requests that fail evaluation actions: { onUnsafe: "block", onInappropriate: "sanitize", onSuspicious: "warn", }, } } ``` ### Streaming Support Guardrails work seamlessly with streaming responses: ```typescript const result = await neurolink.stream({ input: { text: "Generate a story" }, }); // Each chunk is filtered in real-time for await (const chunk of result.stream) { console.log(chunk); // Filtered content } ``` **Stream Filtering:** - Bad words are replaced with `***` in each text delta - Model-based filtering is not applied to streams (too slow) - Precall evaluation works for streams ### Use Cases **1. Content Moderation for User-Generated Prompts:** ```typescript const factory = new MiddlewareFactory({ middlewareConfig: { guardrails: { enabled: true, config: { badWords: ["spam", "abuse", "harassment"], precallEvaluation: { enabled: true, provider: "openai", evaluationModel: "gpt-4", thresholds: { safetyScore: 9, // Strict filtering (1-10 scale) appropriatenessScore: 8, }, blockUnsafeRequests: true, }, }, }, }, }); ``` **2. Compliance with Content Policies:** ```typescript const factory = new MiddlewareFactory({ middlewareConfig: { guardrails: { enabled: true, config: { badWords: organizationBlocklist, // Your org's blocked terms modelFilter: { enabled: true, filterModel: openai("gpt-3.5-turbo"), }, }, conditions: { providers: ["openai", "anthropic"], // Only for external providers }, }, }, }); ``` **3. Protecting Against Prompt Injection:** ```typescript const factory = new MiddlewareFactory({ middlewareConfig: { guardrails: { enabled: true, config: { precallEvaluation: { enabled: true, provider: "openai", evaluationModel: "gpt-4", thresholds: { safetyScore: 8, // High safety threshold (1-10 scale) appropriatenessScore: 7, }, blockUnsafeRequests: true, actions: { onUnsafe: "block", onInappropriate: "block", onSuspicious: "block", }, }, }, }, }, }); ``` --- ## Auto-Evaluation Middleware ### Purpose The **Auto-Evaluation Middleware** automatically evaluates AI response quality using configurable criteria. It can trigger retries for low-quality responses and provide quality metrics for monitoring. **Key Capabilities:** - Automatic quality evaluation after each response - Configurable evaluation criteria (relevance, accuracy, coherence, etc.) - Blocking and non-blocking modes - Integration with custom evaluation providers - Quality score thresholds ### Configuration **Basic Configuration:** ```typescript const factory = new MiddlewareFactory({ middlewareConfig: { autoEvaluation: { enabled: true, config: { threshold: 7, // Minimum quality score (0-10) blocking: true, // Wait for evaluation before returning }, }, }, }); ``` **Advanced Configuration:** ```typescript const factory = new MiddlewareFactory({ middlewareConfig: { autoEvaluation: { enabled: true, config: { threshold: 8, blocking: false, // Non-blocking: evaluation happens in background // Custom evaluation provider provider: "openai", evaluationModel: "gpt-4", // Custom prompt generator for evaluation promptGenerator: (options, result) => { return `Evaluate the following AI response on a scale of 0-10 for: - Relevance to the prompt - Factual accuracy - Coherence and clarity - Helpfulness Prompt: ${options.prompt} Response: ${result.content} Score (0-10):`; }, // Callback when evaluation completes onEvaluationComplete: async (evaluationResult) => { console.log("Evaluation complete:", evaluationResult); if (evaluationResult.score { // Handle evaluation asynchronously await logEvaluation(evaluationResult); } } // Response returned immediately const result = await neurolink.generate({ input: { text: "..." } }); // Evaluation runs in background ``` ### Evaluation Output **Evaluation Result Structure:** ```typescript type EvaluationResult = { // Overall quality score (0-10) score: number; // Detailed scores per criterion criteria: { relevance: number; accuracy: number; coherence: number; helpfulness: number; safety: number; }; // Whether the response passed the threshold passed: boolean; // Optional feedback from evaluator feedback?: string; // Timestamp of evaluation timestamp: string; }; ``` **Example Output:** ```json { "score": 8.5, "criteria": { "relevance": 9, "accuracy": 8, "coherence": 9, "helpfulness": 8, "safety": 10 }, "passed": true, "feedback": "High-quality response with accurate information and clear structure.", "timestamp": "2026-01-01T00:00:00.000Z" } ``` ### Streaming Support **Important:** Auto-evaluation for streaming responses always runs in **non-blocking mode**, even if `blocking: true` is configured. This is because the stream needs to be returned to the user immediately. ```typescript config: { blocking: true; // Ignored for streams } const result = await neurolink.stream({ input: { text: "..." } }); // Stream returns immediately for await (const chunk of result.stream) { console.log(chunk); } // Evaluation happens in background after stream completes ``` ### Use Cases **1. Quality Assurance for Customer-Facing AI:** ```typescript const factory = new MiddlewareFactory({ middlewareConfig: { autoEvaluation: { enabled: true, config: { threshold: 8, // High quality requirement blocking: true, // Wait for evaluation onEvaluationComplete: async (evaluation) => { if (!evaluation.passed) { // Log low-quality response for review await logQualityIssue({ score: evaluation.score, feedback: evaluation.feedback, }); } }, }, }, }, }); ``` **2. Automatic Response Improvement:** ```typescript const factory = new MiddlewareFactory({ middlewareConfig: { autoEvaluation: { enabled: true, config: { threshold: 7, blocking: true, onEvaluationComplete: async (evaluation) => { if (!evaluation.passed) { // Trigger retry with modified prompt console.log("Quality below threshold, retrying..."); // Implementation would retry the request } }, }, }, }, }); ``` **3. Quality Metrics Dashboard:** ```typescript const evaluationResults = []; const factory = new MiddlewareFactory({ middlewareConfig: { autoEvaluation: { enabled: true, config: { threshold: 7, blocking: false, // Background evaluation onEvaluationComplete: async (evaluation) => { evaluationResults.push(evaluation); // Calculate rolling average quality const avgScore = evaluationResults.slice(-100).reduce((sum, e) => sum + e.score, 0) / 100; console.log(`Average quality (last 100): ${avgScore}`); }, }, }, }, }); ``` ### Environment Variables Configure auto-evaluation via environment variables: ```bash # Set default threshold NEUROLINK_EVALUATION_THRESHOLD=7 # Use in configuration ``` ```typescript const factory = new MiddlewareFactory({ middlewareConfig: { autoEvaluation: { enabled: true, config: { threshold: Number(process.env.NEUROLINK_EVALUATION_THRESHOLD) || 7, }, }, }, }); ``` --- ## Combining Middleware ### Recommended Execution Order Middleware executes in **priority order** (higher priority runs first). Here's the recommended order for combining built-in middleware: ``` Priority 100: Analytics (always run first) Priority 90: Guardrails (security checks) Priority 90: Auto-Evaluation (quality checks) ``` **Why This Order?** 1. **Analytics first**: Capture metrics for all requests, even blocked ones 2. **Guardrails second**: Block unsafe content before it's evaluated 3. **Auto-Evaluation last**: Evaluate quality of safe responses ### Example: Production Configuration ```typescript const factory = new MiddlewareFactory({ preset: "all", // Enables analytics + guardrails // Customize individual middleware middlewareConfig: { analytics: { enabled: true, // Always enabled for production monitoring }, guardrails: { enabled: true, config: { badWords: ["spam", "abuse", "harassment"], precallEvaluation: { enabled: true, provider: "openai", evaluationModel: "gpt-4", thresholds: { safetyScore: 8, // High safety threshold (1-10 scale) appropriatenessScore: 7, }, blockUnsafeRequests: true, }, }, }, autoEvaluation: { enabled: true, config: { threshold: 7, blocking: false, // Non-blocking for performance onEvaluationComplete: async (evaluation) => { // Log to monitoring system await sendMetric("ai.quality.score", evaluation.score); }, }, }, }, }); ``` ### Example: Development Configuration ```typescript const factory = new MiddlewareFactory({ middlewareConfig: { analytics: { enabled: true, // Track usage in development }, guardrails: { enabled: false, // Disable in development for easier testing }, autoEvaluation: { enabled: false, // Disable in development for faster iteration }, }, }); ``` ### Example: Security-First Configuration ```typescript const factory = new MiddlewareFactory({ preset: "security", // Guardrails only middlewareConfig: { guardrails: { enabled: true, config: { badWords: organizationBlocklist, precallEvaluation: { enabled: true, provider: "openai", evaluationModel: "gpt-4", thresholds: { safetyScore: 9, // Very strict (1-10 scale) appropriatenessScore: 9, }, blockUnsafeRequests: true, }, }, }, analytics: { enabled: true, // Track security metrics }, }, }); ``` --- ## Performance Considerations ### Analytics - **Overhead**: Minimal (\ context.options.requireEvaluation === true; } ``` 2. **Use Fast Models for Filtering**: Use GPT-3.5 instead of GPT-4 for guardrails ```typescript filterModel: openai("gpt-3.5-turbo"); // Fast and cost-effective ``` 3. **Batch Evaluations**: For non-blocking auto-evaluation, batch multiple evaluations ```typescript onEvaluationComplete: async (evaluation) => { evaluationQueue.push(evaluation); if (evaluationQueue.length >= 10) { await sendBatchToMonitoring(evaluationQueue); evaluationQueue = []; } }; ``` --- ## Troubleshooting ### Analytics Not Appearing in Response **Problem**: Analytics data is missing from response metadata. **Solution**: 1. Verify analytics is enabled: ```typescript factory.registry.has("analytics"); // Should return true ``` 2. Check preset configuration: ```typescript const factory = new MiddlewareFactory({ preset: "default", // Analytics enabled by default }); ``` 3. Access analytics correctly: ```typescript const analytics = result.experimental_providerMetadata?.neurolink?.analytics; ``` ### Guardrails Blocking Valid Content **Problem**: Guardrails are blocking safe content. **Solution**: 1. Adjust precall evaluation threshold: ```typescript threshold: 0.7; // Lower threshold for less strict filtering ``` 2. Review bad words list: ```typescript badWords: []; // Temporarily disable to test ``` 3. Check model-based filter: ```typescript modelFilter: { enabled: false; // Temporarily disable to test } ``` ### Auto-Evaluation Slowing Down Responses **Problem**: Responses are slower due to evaluation. **Solution**: 1. Use non-blocking mode: ```typescript blocking: false; ``` 2. Reduce evaluation frequency: ```typescript conditions: { custom: (context) => Math.random() < 0.1; // Evaluate 10% of requests } ``` 3. Use faster evaluation model: ```typescript evaluationModel: "gpt-3.5-turbo", ``` --- ## See Also - [Middleware Architecture](/docs/advanced/middleware-architecture) - Deep dive into middleware system design - [Custom Middleware Guide](/docs/workflows/custom-middleware) - Create your own middleware - [HITL Integration](/docs/features/enterprise-hitl) - Combine middleware with human approval workflows - [Provider Comparison](/docs/reference/provider-comparison) - Which providers work best with middleware --- ## CLI Guide This page has moved to [CLI Guide](/docs/). --- ## Enterprise Features # Enterprise Features NeuroLink provides comprehensive enterprise-grade features for production deployments. ## Security ### Authentication - API key management - OAuth integration - Role-based access control ### Data Protection - Encryption at rest and in transit - Data residency compliance - Audit logging ## Scalability ### High Availability - Load balancing - Failover mechanisms - Multi-region deployment ### Performance - Caching strategies - Connection pooling - Request optimization ## Monitoring ### Analytics - Usage metrics - Performance monitoring - Error tracking ### Alerting - Real-time notifications - Threshold-based alerts - Custom alert rules ## Compliance ### Standards - SOC 2 compliance - GDPR compliance - Industry-specific requirements ### Governance - Data governance policies - Access controls - Audit trails ## Enterprise Support ### Service Level Agreements - 99.9% uptime guarantee - Response time commitments - Escalation procedures ### Professional Services - Implementation consulting - Custom development - Training and support For setup instructions, see [Enterprise Proxy Setup](/docs/deployment/enterprise-proxy). --- ## NeuroLink Factory Patterns - Complete Implementation Guide # NeuroLink Factory Patterns - Complete Implementation Guide ## Overview The NeuroLink Factory Infrastructure provides a comprehensive, domain-agnostic framework for enhancing AI interactions with configurable patterns. This Phase 1 implementation delivers a complete factory system that works seamlessly with any domain (healthcare, finance, analytics, etc.) while maintaining 100% backward compatibility. ## Quick Start ### Basic Domain Enhancement ```typescript // Enhance any GenerateOptions with domain configuration const enhancedOptions = DomainConfigurationFactory.enhanceWithDomain( { input: { text: "Analyze patient vital signs trends" }, provider: "google-ai", }, { domainType: "healthcare", validationEnabled: true, }, ); // Use with NeuroLink SDK const sdk = new NeuroLink(); const result = await sdk.generate(enhancedOptions); ``` ### Advanced Enhancement Utilities ```typescript // Domain configuration enhancement const domainResult = OptionsEnhancer.enhanceWithDomain(baseOptions, { domainType: "analytics", validationEnabled: true, }); // Streaming optimization enhancement const streamingResult = OptionsEnhancer.enhanceForStreaming(baseOptions, { chunkSize: 512, enableProgress: true, }); // Legacy business context migration const migrationResult = OptionsEnhancer.migrateFromLegacy( baseOptions, legacyBusinessContext, "ecommerce", ); ``` ## Core Components ### 1. Domain Configuration Factory The `DomainConfigurationFactory` provides domain-specific configuration management: ```typescript // Register custom domain template DomainConfigurationFactory.registerDomainTemplate({ templateName: "financial-analysis", baseConfig: { domainName: "financial-analysis", domainDescription: "Expert in financial analysis and reporting", keyTerms: ["revenue", "profit", "ROI", "market analysis"], failurePatterns: ["insufficient financial data", "incomplete analysis"], successPatterns: ["financial insights show", "analysis indicates"], evaluationCriteria: { relevanceThreshold: 9, accuracyThreshold: 10, completenessThreshold: 9, alertSeverityMapping: { low: { relevanceRange: [9, 10], accuracyRange: [10, 10] }, medium: { relevanceRange: [7, 8], accuracyRange: [8, 9] }, high: { relevanceRange: [0, 6], accuracyRange: [0, 7] }, }, }, toolPreferences: ["financial_calculator", "market_data_analyzer"], }, requiredFields: ["domainName", "domainDescription", "keyTerms"], optionalFields: ["evaluationCriteria", "toolPreferences"], }); // Use the registered template const financialConfig = DomainConfigurationFactory.createDomainConfig({ domainType: "financial-analysis", validationEnabled: true, }); ``` ### 2. Options Enhancement Utilities The `OptionsEnhancer` provides intelligent enhancement of `GenerateOptions`: ```typescript // Enhanced workflow example const baseOptions = { input: { text: "Analyze healthcare compliance requirements" }, provider: "anthropic", model: "claude-3", }; // Step 1: Apply domain enhancement const domainEnhanced = OptionsEnhancer.enhanceWithDomain(baseOptions, { domainType: "healthcare", validationEnabled: true, }); // Step 2: Apply streaming optimization const fullyEnhanced = OptionsEnhancer.enhanceForStreaming( domainEnhanced.options, { chunkSize: 256, enableProgress: true, }, ); // Result includes comprehensive metadata console.log(fullyEnhanced.metadata); // { // enhancementApplied: true, // enhancementType: "streaming-optimization", // processingTime: 5, // configurationUsed: { chunkSize: 256, enableProgress: true }, // warnings: [], // recommendations: ["Monitor streaming performance..."] // } ``` ### 3. Context Conversion Utilities The `ContextConverter` provides migration from legacy business contexts: ```typescript // Convert legacy business context const legacyContext = { sessionId: "business-session-123", userId: "user-456", juspayToken: "token-789", shopUrl: "https://shop.example.com", shopId: "shop-123", merchantId: "merchant-456", customBusinessData: "legacy-value", }; const executionContext = ContextConverter.convertBusinessContext( legacyContext, "ecommerce", { preserveLegacyFields: true, validateDomainData: true, includeMetadata: true, }, ); // Create clean domain context const domainContext = ContextConverter.createDomainContext( "analytics", { analyticsEngine: "advanced", dataSources: ["database", "api"], processingMode: "realtime", }, { sessionId: "analytics-session", userId: "analyst-user", }, ); ``` ## Integration Examples ### CLI Integration Factory patterns work seamlessly with the NeuroLink CLI: ```bash # Basic usage (unchanged) neurolink generate "Analyze data trends" --provider google-ai # Enhanced with analytics neurolink generate "Healthcare analysis" --enable-analytics --evaluation-domain healthcare # Context integration neurolink generate "Custom analysis" --context '{"domain":"finance","userId":"analyst123"}' # Streaming with domain awareness neurolink stream "Real-time analytics" --enable-evaluation --evaluation-domain analytics ``` ### SDK Integration ```typescript NeuroLink, DomainConfigurationFactory, OptionsEnhancer, } from "@juspay/neurolink"; const sdk = new NeuroLink(); // Method 1: Direct domain enhancement const result1 = await sdk.generate( DomainConfigurationFactory.enhanceWithDomain( { input: { text: "Medical diagnosis analysis" } }, { domainType: "healthcare", validationEnabled: true }, ), ); // Method 2: Using OptionsEnhancer workflow const enhanced = OptionsEnhancer.enhanceWithDomain( { input: { text: "Financial market trends" }, enableAnalytics: true, enableEvaluation: true, }, { domainType: "analytics", validationEnabled: true }, ); const result2 = await sdk.generate(enhanced.options); // Method 3: Streaming with factory patterns const streamResult = await sdk.stream( OptionsEnhancer.enhanceForStreaming( DomainConfigurationFactory.enhanceWithDomain( { input: { text: "Live data processing" } }, { domainType: "analytics" }, ), { chunkSize: 512, enableProgress: true }, ).options, ); ``` ### Evaluation and Analytics Integration ```typescript // Enhanced evaluation with domain awareness const evaluationContext = { userQuery: "What are the symptoms of hypertension?", aiResponse: "Hypertension symptoms include headaches and dizziness...", primaryDomain: "healthcare", context: { domainType: "healthcare", domainConfig: healthcareDomainConfig, }, assistantRole: "healthcare assistant", }; const evaluation = await generateUnifiedEvaluation(evaluationContext); // Enhanced analytics with factory metadata const analytics = createAnalytics( "google-ai", "gemini-2.5-flash", result, responseTime, { domainType: "healthcare", enhancementType: "domain-configuration", factoryMetadata: { enhancementApplied: true, processingTime: 5, }, }, ); ``` ## Domain Configuration Reference ### Pre-registered Domains #### Healthcare Domain ```typescript { domainName: "healthcare", domainDescription: "Healthcare and medical information expert", keyTerms: ["healthcare", "medical", "patient", "treatment", "diagnosis", "clinical"], failurePatterns: [ "medical information unavailable", "cannot provide medical advice", "insufficient patient data" ], successPatterns: [ "clinical analysis shows", "medical data indicates", "patient outcomes demonstrate" ], evaluationCriteria: { relevanceThreshold: 9, accuracyThreshold: 10, completenessThreshold: 9 }, toolPreferences: ["medical_analyzer", "patient_data_processor"] } ``` #### Analytics Domain ```typescript { domainName: "analytics", domainDescription: "Data analytics and business intelligence expert", keyTerms: ["analytics", "metrics", "data", "trends", "insights", "performance"], failurePatterns: [ "no data available", "insufficient metrics", "data incomplete" ], successPatterns: [ "analysis shows", "data indicates", "metrics reveal", "trend analysis" ], evaluationCriteria: { relevanceThreshold: 8, accuracyThreshold: 9, completenessThreshold: 8 }, toolPreferences: ["data_analyzer", "metrics_calculator"] } ``` ### Custom Domain Creation ```typescript // Define custom domain template const customDomain: DomainTemplate = { templateName: "legal-analysis", baseConfig: { domainName: "legal-analysis", domainDescription: "Legal document analysis and compliance expert", keyTerms: ["legal", "compliance", "regulation", "contract", "law"], failurePatterns: [ "insufficient legal context", "cannot provide legal advice", ], successPatterns: ["legal analysis indicates", "compliance review shows"], evaluationCriteria: { relevanceThreshold: 10, accuracyThreshold: 10, completenessThreshold: 9, alertSeverityMapping: { low: { relevanceRange: [9, 10], accuracyRange: [10, 10] }, medium: { relevanceRange: [7, 8], accuracyRange: [8, 9] }, high: { relevanceRange: [0, 6], accuracyRange: [0, 7] }, }, }, toolPreferences: ["legal_analyzer", "compliance_checker"], customRules: { disclaimerRequired: true, confidentialityLevel: "high", }, }, requiredFields: ["domainName", "domainDescription", "keyTerms"], optionalFields: ["evaluationCriteria", "toolPreferences", "customRules"], validationRules: [ { field: "domainName", validator: (value) => typeof value === "string" && value.length > 0, errorMessage: "Domain name is required", }, ], }; // Register and use DomainConfigurationFactory.registerDomainTemplate(customDomain); const legalOptions = DomainConfigurationFactory.enhanceWithDomain(baseOptions, { domainType: "legal-analysis", validationEnabled: true, }); ``` ## Advanced Usage Patterns ### Batch Enhancement ```typescript const enhancements = [ { enhancementType: "domain-configuration" as const, domainOptions: { domainType: "healthcare" as const }, }, { enhancementType: "streaming-optimization" as const, streamingOptions: { enabled: true, chunkSize: 256 }, }, ]; const result = batchEnhance(baseOptions, enhancements); ``` ### Legacy Migration Workflow ```typescript // Complete legacy migration example const legacyBusinessContext = { sessionId: "legacy-session-123", userId: "business-user-456", juspayToken: "legacy-token", shopUrl: "https://legacy-shop.com", customBusinessField: "legacy-value", }; // Step 1: Migrate legacy context const migrationResult = OptionsEnhancer.migrateFromLegacy( { input: { text: "Analyze business performance" }, enableAnalytics: true, enableEvaluation: true, }, legacyBusinessContext, "ecommerce", ); // Step 2: Optional streaming enhancement const finalOptions = OptionsEnhancer.enhanceForStreaming( migrationResult.options, { chunkSize: 512 }, ); // Step 3: Execute with full enhancement metadata const result = await sdk.generate(finalOptions.options); ``` ### Performance Optimization ```typescript // Monitor enhancement performance const startTime = Date.now(); const enhanced = OptionsEnhancer.enhanceWithDomain(baseOptions, { domainType: "analytics", validationEnabled: true, }); console.log(`Enhancement time: ${enhanced.metadata.processingTime}ms`); // Track enhancement statistics const stats = OptionsEnhancer.getStatistics(); console.log(`Total enhancements: ${stats.enhancementCount}`); // Reset statistics for new session OptionsEnhancer.resetStatistics(); ``` ## Error Handling and Validation ### Graceful Degradation ```typescript try { const enhanced = DomainConfigurationFactory.enhanceWithDomain(options, { domainType: "custom-domain", validationEnabled: true, }); } catch (error) { // Factory patterns never break core functionality console.log("Enhancement failed, using original options"); const result = await sdk.generate(options); } ``` ### Validation and Warnings ```typescript const result = OptionsEnhancer.enhance(options, enhancementOptions); // Check for warnings if (result.metadata.warnings.length > 0) { console.log("Warnings:", result.metadata.warnings); } // Check recommendations if (result.metadata.recommendations.length > 0) { console.log("Recommendations:", result.metadata.recommendations); } ``` ## Testing and Quality Assurance ### Test Coverage The factory infrastructure includes comprehensive test suites: - **Domain Configuration Tests**: 13 test suites, 50+ tests - **Integration Tests**: 11 test suites covering all interfaces - **Streaming Tests**: 11 additional test suites with factory integration - **CLI Integration Tests**: 14 test suites validating zero breaking changes - **Evaluation Integration**: 6 test suites with domain-aware evaluation - **Analytics Integration**: 6 test suites with factory metadata tracking ### Performance Benchmarks - **Enhancement Processing**: \, domainType: string, ): EnhancementResult; static validateEnhancement( options: GenerateOptions, enhancementOptions: EnhancementOptions, ): ValidationResult; static getStatistics(): EnhancementStatistics; static resetStatistics(): void; } ``` ### ContextConverter ```typescript class ContextConverter { static convertBusinessContext( legacyContext: Record, domainType: string, options?: ContextConversionOptions, ): ExecutionContext; static createDomainContext( domainType: string, domainData: Record, sessionInfo?: SessionInfo, ): ExecutionContext; } ``` ## Conclusion The NeuroLink Factory Infrastructure provides a comprehensive, production-ready framework for domain-agnostic AI enhancement. With zero breaking changes, extensive test coverage, and flexible enhancement patterns, it enables powerful domain-specific AI interactions while maintaining the simplicity and reliability of the existing NeuroLink SDK. The factory patterns scale from simple domain configuration to complex multi-enhancement workflows, making them suitable for any application from basic chatbots to enterprise AI systems requiring sophisticated domain expertise and analytics tracking. --- ## Factory Pattern Migration Guide # Factory Pattern Migration Guide ## Overview NeuroLink has been refactored to use a unified factory pattern architecture where providers inherit from a common `BaseProvider` class. This provides consistent tool support and behavior across supported AI providers. ## What Changed ### 1. Unified BaseProvider Architecture Providers now inherit from `BaseProvider`, which provides: - Built-in tool support (6 core tools) - Consistent `generate()` and `stream()` methods - Analytics and evaluation capabilities - Standardized error handling ### 2. Automatic Tool Support Providers automatically include these tools: - `getCurrentTime` - Get current date and time - `readFile` - Read file contents - `listDirectory` - List directory contents - `calculateMath` - Perform calculations - `writeFile` - Write to files - `searchFiles` - Search for files by pattern ### 3. Simplified Provider Implementation Providers no longer need to implement their own tool handling - they inherit it from BaseProvider. This means: - No more `executeGenerate` methods in individual providers - Consistent tool behavior across supported providers - Less code duplication ## Migration Steps ### For Users **Good news! There are no breaking changes.** Your existing code will continue to work exactly as before. #### Tool Usage (No Changes Required) ```typescript // This works exactly as before const provider = createBestAIProvider("openai"); const result = await provider.generate({ input: { text: "What time is it?" }, }); // Tools are used automatically ``` #### Disabling Tools (New Option) ```typescript // New: You can now disable tools if needed const result = await provider.generate({ input: { text: "What time is it?" }, disableTools: true, // New option }); // Will use training data instead of real-time tools ``` ### For Provider Developers If you've created custom providers, you'll need to update them to use the new pattern: #### Before (Old Pattern) ```typescript export class CustomProvider implements AIProvider { async executeGenerate( options: TextGenerationOptions, ): Promise { // Custom implementation with manual tool handling const tools = await this.getTools(); // ... complex tool execution logic } } ``` #### After (New Pattern) ```typescript export class CustomProvider extends BaseProvider { // No executeGenerate needed - BaseProvider handles it protected getAISDKModel(): LanguageModelV1 { // Return your AI SDK model instance return this.model; } protected getProviderName(): AIProviderName { return "custom"; } protected getDefaultModel(): string { return "custom-model"; } } ``` ## Provider Tool Support Status After the refactoring, here's the current status of tool support: | Provider | Status | Notes | | ------------ | ----------------- | ---------------------------------------------------- | | OpenAI | ✅ Full Support | All tools working correctly | | Google AI | ✅ Full Support | Excellent tool execution | | Anthropic | ✅ Full Support | Working after max_tokens fix | | Azure OpenAI | ✅ Full Support | Same as OpenAI | | Mistral | ✅ Full Support | Good tool support | | HuggingFace | ⚠️ Partial | Model sees tools but may describe instead of execute | | Vertex AI | ⚠️ Partial | Tools available but may not execute | | Ollama | ❌ Limited | Requires specific models (e.g., gemma3n) | | Bedrock | ✅ Full Support\* | Requires valid AWS credentials | ## Benefits of the New Architecture 1. **Consistency**: Providers behave the same way with tools 2. **Maintainability**: Less code duplication, easier to update 3. **Reliability**: Centralized tool handling reduces bugs 4. **Extensibility**: Easy to add new tools for providers at once 5. **Testing**: Simplified testing with consistent behavior ## Common Issues and Solutions ### Issue: Provider Not Using Tools **Solution**: Check if your model supports function calling. Some models (especially older or smaller ones) may not support tools. ```typescript // For providers with limited tool support const result = await provider.generate({ input: { text: "What time is it?" }, disableTools: true, // Explicitly disable tools }); ``` ### Issue: HuggingFace Describing Tools Instead of Using Them **Solution**: This is a model limitation. Use models that support function calling: - `mistralai/Mixtral-8x7B-Instruct-v0.1` - `mistralai/Mistral-7B-Instruct-v0.2` ### Issue: Ollama Returns Empty Content **Solution**: Use models that support tool calling: ```bash export OLLAMA_MODEL="gemma3n:latest" # or export OLLAMA_MODEL="aliafshar/gemma3-it-qat-tools:latest" ``` ### Issue: Vertex AI Not Using Tools **Solution**: This may require schema formatting adjustments. The Vertex provider needs to format tools according to Google's Gemini API schema. ## Future Improvements 1. **Dynamic Tool Loading**: Ability to add custom tools at runtime 2. **Provider-Specific Tool Formatting**: Automatic adaptation of tool schemas for each provider 3. **Tool Usage Analytics**: Detailed metrics on which tools are used most 4. **Tool Caching**: Cache tool results for better performance ## Support If you encounter any issues with the migration: 1. Check the [provider status documentation](/docs/advanced/updated-provider-test-results) 2. Review the [provider configuration guide](/docs/getting-started/provider-setup) 3. Open an issue on GitHub with details about your use case --- Remember: **No breaking changes!** Your existing code continues to work. The factory pattern refactoring improves the internal architecture while maintaining full backward compatibility. --- ## Memory Integration with Hippocampus # Memory Integration with Hippocampus Enhance your AI applications with persistent, context-aware memory using NeuroLink's integrated `@juspay/hippocampus` support. This feature enables your AI to remember user preferences, context, and conversation history across sessions while maintaining complete user isolation. ## Overview NeuroLink's Hippocampus integration provides: - **Cross-Session Memory**: AI remembers context across different conversations and sessions - **User Isolation**: Complete separation of memory contexts between different users - **LLM-Powered Condensation**: Memory is automatically summarized to stay within a configurable word limit - **Multiple Storage Backends**: Support for S3, Redis, and SQLite - **Non-blocking Storage**: Memory operations happen in the background without slowing down responses - **Crash-safe**: Every SDK method is wrapped in try-catch — errors are logged, never thrown ## Architecture ```mermaid graph LR A[NeuroLink SDK] --> B[Hippocampus Memory Layer] B --> C[Storage Backend] B --> D[Condensation LLM] C --> E[S3 / Redis / SQLite] D --> F[Any NeuroLink Provider] A --> G[Generate / Stream] G --> H[memory.get - userId] H --> I[Context Enhancement] I --> J[AI Response] J --> K[Background: memory.add] ``` The memory system operates in three phases: 1. **Memory Retrieval**: The user's condensed memory is fetched before generating a response 2. **Context Enhancement**: Retrieved memory is prepended to the user's prompt 3. **Memory Storage**: The new conversation turn is condensed and stored asynchronously ## Installation `@juspay/hippocampus` is shipped as an **optional peer dependency** of NeuroLink. Memory features are off by default; install the package explicitly when you want them: ```bash pnpm add @juspay/hippocampus # or: npm install @juspay/hippocampus ``` If a memory configuration is supplied without the package installed, NeuroLink logs a warning and proceeds with memory disabled — no exception is thrown and the rest of the SDK continues to work. This packaging change exists to keep NeuroLink's production dependency graph free of the deprecated `@ai-sdk/google` and `@ai-sdk/google-vertex` packages, which Hippocampus's own `@juspay/neurolink` peer was previously dragging in. ## Quick Start ```typescript const neurolink = new NeuroLink({ conversationMemory: { enabled: true, memory: { enabled: true, storage: { type: "s3", bucket: "my-memory-bucket", prefix: "memory/condensed/", }, neurolink: { provider: "google-ai", model: "gemini-2.5-flash", }, maxWords: 50, }, }, }); // First conversation — stores context const response1 = await neurolink.generate({ input: { text: "Hi! I'm Sarah, a frontend developer at TechCorp. I love React and TypeScript.", }, context: { userId: "user_sarah_123", sessionId: "onboarding_session", }, provider: "google-ai", model: "gemini-2.5-flash", }); // Later conversation — memory retrieved automatically const response2 = await neurolink.generate({ input: { text: "What programming languages do I work with?", }, context: { userId: "user_sarah_123", sessionId: "help_session", }, provider: "google-ai", }); // → "You work with React and TypeScript at TechCorp." ``` ## Configuration ### Storage Backends #### S3 (Recommended for production) ```typescript memory: { enabled: true, storage: { type: "s3", bucket: "my-bucket", prefix: "memory/condensed/", }, neurolink: { provider: "google-ai", model: "gemini-2.5-flash" }, maxWords: 50, } ``` Each user's memory is stored as a single S3 object at `{prefix}{userId}`. #### Redis ```typescript memory: { enabled: true, storage: { type: "redis", url: process.env.REDIS_URL, }, neurolink: { provider: "openai", model: "gpt-4o-mini" }, } ``` #### SQLite (Development) ```typescript memory: { enabled: true, storage: { type: "sqlite", path: "./memory.db", }, neurolink: { provider: "google-ai", model: "gemini-2.5-flash" }, } ``` > **Note**: SQLite requires the `better-sqlite3` optional peer dependency: `pnpm add better-sqlite3` ### Condensation LLM The `neurolink` field configures which AI provider and model is used to condense memory. You can use any provider registered with your NeuroLink instance: ```typescript neurolink: { provider: "google-ai", // or "openai", "anthropic", etc. model: "gemini-2.5-flash", } ``` ## Advanced Usage ### User Isolation in Multi-Tenant Applications ```typescript // User Alice await neurolink.generate({ input: { text: "I prefer dark mode and use VSCode." }, context: { userId: "tenant_1_alice_123" }, }); // User Bob (completely isolated memory) await neurolink.generate({ input: { text: "I love light themes and use WebStorm." }, context: { userId: "tenant_2_bob_456" }, }); // Alice's query — only returns Alice's data const aliceQuery = await neurolink.generate({ input: { text: "What IDE do I use?" }, context: { userId: "tenant_1_alice_123" }, }); // → "You use VSCode with dark mode." (not Bob's data) ``` ### Streaming with Memory ```typescript const stream = await neurolink.stream({ input: { text: "Write me a personalized coding tutorial based on my experience.", }, context: { userId: "developer_sarah" }, provider: "anthropic", model: "claude-sonnet-4-5", }); for await (const chunk of stream.stream) { if (chunk.content) process.stdout.write(chunk.content); } // Tutorial is personalized based on Sarah's stored background ``` ### Custom Condensation Prompt Control exactly how memory is condensed by providing a custom prompt: ```typescript memory: { enabled: true, storage: { type: "s3", bucket: "my-bucket" }, neurolink: { provider: "google-ai", model: "gemini-2.5-flash" }, maxWords: 100, prompt: `You are a memory engine. Merge the old memory with new facts into a summary of at most {{MAX_WORDS}} words. Focus on persistent facts: name, job, preferences, goals. Ignore conversational filler. OLD_MEMORY: {{OLD_MEMORY}} NEW_CONTENT: {{NEW_CONTENT}} Condensed memory:`, } ``` | Placeholder | Replaced With | | ----------------- | -------------------------------------------------------- | | `{{OLD_MEMORY}}` | The user's existing condensed memory (may be empty) | | `{{NEW_CONTENT}}` | The new conversation turn: `"User: ...\nAssistant: ..."` | | `{{MAX_WORDS}}` | The configured `maxWords` value | ## Memory Lifecycle ### When Memory Activates For memory to activate on a call, all three conditions must be met: 1. `memory.enabled` is `true` in the config 2. `options.context.userId` is provided in the generate/stream call 3. The response has non-empty content (for storage) ### Retrieval Flow 1. `memory.get(userId)` fetches the condensed memory string 2. If memory exists, it is prepended to the prompt: ``` Context from previous conversations: Current user's request: ``` 3. The LLM generates a response using the enhanced prompt ### Storage Flow After the LLM response completes: 1. `setImmediate()` schedules background storage (non-blocking) 2. A conversation turn is formed: `"User: ...\nAssistant: ..."` 3. `memory.add(userId, content)` sends the old memory + new turn to the condensation LLM 4. The condensed summary is written to the storage backend ## Namespace and Tenant Isolation For multi-tenant apps, use tenant-scoped collection names or key prefixes: ```typescript // Tenant-scoped S3 prefix const getMemoryConfig = (tenantId: string) => ({ storage: { type: "s3" as const, bucket: "my-bucket", prefix: `tenants/${tenantId}/memory/`, }, neurolink: { provider: "google-ai", model: "gemini-2.5-flash" }, }); // User ID should also encode tenant context const userId = `${tenantId}::${localUserId}`; ``` ## Environment Variables | Variable | Default | Description | | ------------------------ | -------- | ---------------------------------------------- | | `HC_LOG_LEVEL` | `warn` | Log level: `debug`, `info`, `warn`, `error` | | `HC_CONDENSATION_PROMPT` | built-in | Default prompt (overridden by config `prompt`) | ## Error Handling Memory is designed to **never crash the host application**: - Every public method is wrapped in try-catch - `get()` returns `null` on error — the call continues without memory context - `add()` silently fails on error — the generate/stream result is not affected - Storage initialization errors disable memory for that instance ```typescript // These warnings appear in logs but never throw: // logger.warn("Memory retrieval failed:", error) // logger.warn("Memory storage failed:", error) ``` ## Type Reference ```typescript // Memory = HippocampusConfig & { enabled?: boolean } type Memory = { enabled?: boolean; storage: { type: "s3" | "redis" | "sqlite"; bucket?: string; // S3 prefix?: string; // S3 url?: string; // Redis path?: string; // SQLite }; neurolink: { provider: string; model: string; }; maxWords?: number; // default: 50 prompt?: string; // custom condensation prompt }; ``` ## Production Checklist - [ ] Use S3 or Redis storage (not SQLite) in production - [ ] Set `HC_LOG_LEVEL=warn` or higher in production - [ ] Ensure `userId` is stable and unique per user across sessions - [ ] For multi-tenant: use tenant-scoped prefixes or collection names - [ ] Monitor `Memory retrieval failed` and `Memory storage failed` warnings in logs - [ ] Verify the condensation LLM provider is configured and has sufficient quota ## See Also - **[Memory Guide](/docs/features/memory)** - Quick start and configuration reference - **[Conversation Memory](/docs/memory/conversation)** - Session-based conversation history - **[Context Compaction](/docs/features/context-compaction)** - Automatic context window management --- ## Middleware System Architecture # Middleware System Architecture ## Overview NeuroLink's middleware system provides a powerful and flexible way to intercept, modify, and enhance AI requests and responses. Middleware enables you to implement cross-cutting concerns like authentication, logging, analytics, content filtering, and auto-evaluation without modifying your core application logic. **Why Middleware Matters:** - **Request Interception**: Modify requests before they reach the AI provider - **Response Processing**: Transform, filter, or validate AI responses - **Cross-Cutting Concerns**: Implement authentication, logging, rate limiting, and caching in a centralized way - **Composability**: Chain multiple middleware components together - **Separation of Concerns**: Keep business logic separate from infrastructure concerns **Key Benefits:** - Production-ready middleware for common use cases (analytics, guardrails, auto-evaluation) - Factory pattern for easy middleware management - Priority-based execution ordering - Provider-specific conditional execution - Built on NeuroLink's own `wrapLanguageModel` (`src/lib/middleware/wrapLanguageModel.ts`), which keeps the familiar wrap-a-model shape without depending on a third-party SDK ## Architecture Diagram ``` ┌─────────────────────────────────────────────────────────────────┐ │ Request Flow │ └─────────────────────────────────────────────────────────────────┘ Client Request │ ├─────────────────────────────────────────────┐ │ │ v │ ┌──────────────────────┐ │ │ MiddlewareFactory │ │ │ - Registry │ │ │ - Configuration │ │ └──────────────────────┘ │ │ │ v │ ┌─────────────────────────────────────────┐ │ │ Pre-Request Middleware Chain │ │ │ (Ordered by Priority - High to Low) │ │ ├─────────────────────────────────────────┤ │ │ 1. transformParams (Guardrails) │ │ │ - Precall evaluation │ │ │ - Input validation │ │ │ - Request transformation │ │ └─────────────────────────────────────────┘ │ │ │ v │ ┌─────────────────────────────────────────┐ │ │ Provider Execution │ │ │ (OpenAI, Anthropic, Vertex, etc.) │ │ └─────────────────────────────────────────┘ │ │ │ v │ ┌─────────────────────────────────────────┐ │ │ Post-Response Middleware Chain │ │ │ (Ordered by Priority - High to Low) │ │ ├─────────────────────────────────────────┤ │ │ 2. wrapGenerate/wrapStream │ │ │ - Analytics (Priority: 100) │ │ │ - Guardrails (Priority: 90) │ │ │ - Auto-Evaluation (Priority: 90) │ │ └─────────────────────────────────────────┘ │ │ │ v │ Client Response │ │ ┌─────────────────────────────────────────┐ │ │ Error Handling Flow │ │ │ (If error occurs at any stage) │◄────────┘ ├─────────────────────────────────────────┤ │ - Error Middleware Chain │ │ - Error logging │ │ - Fallback handling │ │ - Retry logic (if configured) │ └─────────────────────────────────────────┘ │ v Error Response ``` ## Request Lifecycle The middleware system processes requests through four distinct phases: ### Phase 1: Pre-Request (transformParams) Middleware in this phase runs **before** the AI provider call, allowing you to: - **Validate input**: Check request parameters for validity - **Authenticate/Authorize**: Verify user permissions - **Transform requests**: Modify or enrich request parameters - **Apply guardrails**: Block requests with unsafe content using precall evaluation - **Rate limiting**: Enforce request quotas **Example Use Cases:** - Precall guardrails evaluation (blocking unsafe prompts) - Request parameter validation - Adding authentication context - Modifying prompts based on user preferences ```typescript transformParams: async ({ params }) => { // Pre-request logic here console.log("Request received:", params); // Can modify params before they reach the provider return { ...params, temperature: Math.min(params.temperature || 0.7, 1.0), }; }; ``` ### Phase 2: Provider Execution The actual AI provider call happens between middleware phases: - Request sent to configured provider (OpenAI, Anthropic, Vertex, etc.) - Provider processes the request - Response received from provider This phase is **not** middleware - it's the core AI operation that middleware wraps around. ### Phase 3: Post-Response (wrapGenerate/wrapStream) Middleware in this phase runs **after** the AI provider responds, allowing you to: - **Collect analytics**: Track token usage, response times, costs - **Filter content**: Apply guardrails to block/redact unsafe responses - **Evaluate quality**: Auto-evaluate response quality and trigger retries - **Transform responses**: Modify or enrich the response - **Cache results**: Store responses for future use **Example Use Cases:** - Analytics and metrics collection - Content filtering and safety checks - Response quality evaluation - Response caching - Logging and auditing ```typescript wrapGenerate: async ({ doGenerate, params }) => { const startTime = Date.now(); // Execute the provider call const result = await doGenerate(); // Post-response logic here const responseTime = Date.now() - startTime; console.log(`Response in ${responseTime}ms`); return result; }; ``` ### Phase 4: Error Handling If an error occurs at any stage, error handling middleware can: - **Log errors**: Record error details for debugging - **Transform errors**: Convert provider errors to user-friendly messages - **Implement fallbacks**: Retry with different providers - **Alert monitoring**: Send alerts to monitoring systems **Example Use Cases:** - Error logging and tracking - Provider fallback on failure - Retry logic with exponential backoff - User-friendly error messages ## Middleware Chain ### Execution Order Middleware executes in **priority order**, where higher priority values run first: ``` Priority 100: Analytics (runs first) Priority 90: Guardrails Priority 90: Auto-Evaluation (runs last among same priority) ``` **Important Notes:** - `transformParams` runs before `wrapGenerate`/`wrapStream` - Within the same priority, registration order determines execution - Middleware can be conditionally enabled based on provider, model, or custom logic ### Chain Configuration Configure which middleware to enable and their order: ```typescript const factory = new MiddlewareFactory({ // Use a preset for common configurations preset: "all", // Enables analytics + guardrails // Or explicitly enable specific middleware enabledMiddleware: ["analytics", "guardrails"], // Or configure each middleware individually middlewareConfig: { analytics: { enabled: true, config: { collectTokenUsage: true }, }, guardrails: { enabled: true, config: { badWords: ["prohibited", "blocked"], precallEvaluation: { enabled: true }, }, }, }, }); ``` ### Available Presets | Preset | Middleware Enabled | Use Case | | ---------- | ---------------------- | ---------------------- | | `default` | Analytics only | Basic usage tracking | | `all` | Analytics + Guardrails | Production with safety | | `security` | Guardrails only | Security-focused | | Custom | Your choice | Define your own | `security` switches guardrails on and nothing more: it ships no word list and no model filter, so it redacts nothing until `badWords`, `modelFilter` or `precallEvaluation` is configured. A preset, and any other `MiddlewareFactoryOptions`, can also be set as a default for every call: `NEUROLINK_MIDDLEWARE_PRESET` (a preset name only), `configureGlobalMiddleware()` and `new NeuroLink({ middleware })`, each overridden by the next and finally by the call's own `middleware`. See [Guardrails: Defaults and precedence](/docs/features/guardrails.md#defaults-and-precedence). ## Factory Pattern ### MiddlewareFactory Class The `MiddlewareFactory` is the central component for managing middleware: ```typescript class MiddlewareFactory { // Public registry for middleware management public registry: MiddlewareRegistry; // Available presets public presets: Map; // Constructor constructor(options?: MiddlewareFactoryOptions); // Register custom middleware register( middleware: NeuroLinkMiddleware, options?: RegistrationOptions, ): void; // Register a preset registerPreset(preset: MiddlewarePreset, replace?: boolean): void; // Apply middleware to a language model applyMiddleware( model: LanguageModelV1, context: MiddlewareContext, options?: MiddlewareFactoryOptions, ): LanguageModelV1; // Create middleware context createContext( provider: string, model: string, options?: Record, session?: { sessionId?: string; userId?: string }, ): MiddlewareContext; // Validate middleware configuration validateConfig(config: Record): ValidationResult; // Get available presets getAvailablePresets(): PresetInfo[]; // Get middleware chain statistics getChainStats( context: MiddlewareContext, config: Record, ): MiddlewareChainStats; } ``` ### Creating Middleware Instances **Basic Usage:** ```typescript // Create factory with default preset (analytics enabled) const factory = new MiddlewareFactory(); // Create context const context = factory.createContext("openai", "gpt-4", { temperature: 0.7 }); // Apply middleware to a model const wrappedModel = factory.applyMiddleware(baseModel, context); ``` **Advanced Configuration:** ```typescript // Create factory with custom configuration const factory = new MiddlewareFactory({ preset: "all", middlewareConfig: { analytics: { enabled: true, config: { collectTokenUsage: true, collectTiming: true, }, }, guardrails: { enabled: true, config: { badWords: ["unsafe", "prohibited"], precallEvaluation: { enabled: true, provider: "openai", model: "gpt-4", }, }, conditions: { providers: ["openai", "anthropic"], // Only apply to specific providers }, }, }, }); // Or register custom middleware after instantiation const customMiddleware = createMyCustomMiddleware(); factory.register(customMiddleware); ``` ## Registry System ### Registering Middleware The `MiddlewareRegistry` manages all registered middleware: ```typescript class MiddlewareRegistry { // Register a middleware register( middleware: NeuroLinkMiddleware, options?: MiddlewareRegistrationOptions, ): void; // Unregister a middleware unregister(middlewareId: string): boolean; // Get a registered middleware get(middlewareId: string): NeuroLinkMiddleware | undefined; // List all registered middleware list(): NeuroLinkMiddleware[]; // Get middleware IDs sorted by priority getSortedIds(): string[]; // Build middleware chain based on configuration buildChain( context: MiddlewareContext, config?: Record, ): LanguageModelV1Middleware[]; // Get execution statistics getExecutionStats(middlewareId: string): MiddlewareExecutionResult[]; // Get aggregated statistics for all middleware getAggregatedStats(): Record; // Clear execution statistics clearStats(middlewareId?: string): void; // Check if middleware is registered has(middlewareId: string): boolean; // Get number of registered middleware size(): number; // Clear all registered middleware clear(): void; } ``` **Registration Example:** ```typescript const factory = new MiddlewareFactory(); // Register middleware with options factory.register(myCustomMiddleware, { replace: false, // Error if already exists defaultEnabled: true, // Enable by default globalConfig: { // Global configuration logLevel: "debug", }, }); ``` ### Discovering Middleware **List all registered middleware:** ```typescript const allMiddleware = factory.registry.list(); console.log( "Registered middleware:", allMiddleware.map((m) => m.metadata.id), ); ``` **Get specific middleware:** ```typescript const analytics = factory.registry.get("analytics"); if (analytics) { console.log("Analytics middleware found:", analytics.metadata.name); } ``` **Check if middleware is registered:** ```typescript if (factory.registry.has("guardrails")) { console.log("Guardrails middleware is available"); } ``` ### Middleware Metadata Every middleware must provide metadata: ```typescript type NeuroLinkMiddlewareMetadata = { // Unique identifier id: string; // Human-readable name name: string; // Description of what this middleware does description?: string; // Execution priority (higher runs first) priority?: number; // Whether this middleware is enabled by default defaultEnabled?: boolean; }; ``` **Example:** ```typescript const metadata: NeuroLinkMiddlewareMetadata = { id: "my-custom-middleware", name: "My Custom Middleware", description: "Logs all requests and responses", priority: 50, // Run after analytics (100) but before auto-eval (90) defaultEnabled: false, // Require explicit enabling }; ``` ## TypeScript Interfaces ### NeuroLinkMiddleware The core middleware interface, which combines the model-middleware contract with NeuroLink metadata: ```typescript type NeuroLinkMiddleware = LanguageModelMiddleware & { // Metadata about this middleware metadata: NeuroLinkMiddlewareMetadata; }; ``` ### LanguageModelMiddleware NeuroLink declares this contract itself — it no longer comes from the Vercel AI SDK, which is not a dependency. The shape follows the v3 model protocol: ```typescript type LanguageModelMiddleware = { readonly specificationVersion: "v3"; // Override how the model identifies itself overrideProvider?: (options: { model: LanguageModelV3 }) => string; overrideModelId?: (options: { model: LanguageModelV3 }) => string; // Transform request parameters before the provider call transformParams?: (options: { type: "generate" | "stream"; params: LanguageModelV3CallOptions; model: LanguageModelV3; }) => PromiseLike; // Wrap generate() calls wrapGenerate?: (options: { doGenerate: () => PromiseLike; doStream: () => PromiseLike; params: LanguageModelV3CallOptions; model: LanguageModelV3; }) => PromiseLike; // Wrap stream() calls wrapStream?: (options: { doGenerate: () => PromiseLike; doStream: () => PromiseLike; params: LanguageModelV3CallOptions; model: LanguageModelV3; }) => PromiseLike; }; ``` ### MiddlewareContext Context information passed to middleware: ```typescript type MiddlewareContext = { // Provider name (e.g., "openai", "anthropic") provider: string; // Model name (e.g., "gpt-4", "claude-3-5-sonnet") model: string; // Additional options options: Record; // Session information session?: { sessionId?: string; userId?: string; }; // Request metadata metadata: { timestamp: number; requestId: string; }; }; ``` ### MiddlewareConfig Configuration for individual middleware: ```typescript type MiddlewareConfig = { // Whether this middleware is enabled enabled: boolean; // Middleware-specific configuration config?: Record; // Conditions for when this middleware should run conditions?: { // Only run for specific providers providers?: string[]; // Only run for specific models models?: string[]; // Only run when options match options?: Record; // Custom condition function custom?: (context: MiddlewareContext) => boolean; }; }; ``` ### MiddlewareFactoryOptions Options for creating and configuring the factory: ```typescript type MiddlewareFactoryOptions = { // Preset to use (e.g., "default", "all", "security") preset?: string; // Custom middleware to register middleware?: NeuroLinkMiddleware[]; // Configuration for each middleware middlewareConfig?: Record; // List of middleware IDs to enable enabledMiddleware?: string[]; // List of middleware IDs to disable disabledMiddleware?: string[]; }; ``` ### MiddlewareChainStats Statistics about middleware execution: ```typescript type MiddlewareChainStats = { // Total middleware in chain totalMiddleware: number; // Number of middleware actually applied appliedMiddleware: number; // Total execution time across all middleware totalExecutionTime: number; // Per-middleware execution results results: Record; }; type MiddlewareExecutionResult = { // Whether middleware was applied applied: boolean; // Execution time in milliseconds executionTime: number; // Error if execution failed error?: Error; }; ``` ## Conditional Execution Middleware can be configured to run only under specific conditions: ### Provider-Specific Middleware ```typescript factory.applyMiddleware(model, context, { middlewareConfig: { guardrails: { enabled: true, conditions: { providers: ["openai", "anthropic"], // Only for these providers }, }, }, }); ``` ### Model-Specific Middleware ```typescript factory.applyMiddleware(model, context, { middlewareConfig: { analytics: { enabled: true, conditions: { models: ["gpt-4", "claude-3-5-sonnet"], // Only for these models }, }, }, }); ``` ### Custom Conditions ```typescript factory.applyMiddleware(model, context, { middlewareConfig: { myMiddleware: { enabled: true, conditions: { custom: (context) => { // Only run during business hours const hour = new Date().getHours(); return hour >= 9 && hour { try { const result = await doGenerate(); return result; } catch (error) { // Log error but don't break the chain console.error("Middleware error:", error); throw error; // Re-throw to maintain error flow } }; ``` ### 3. Use Conditional Execution ```typescript // Only apply expensive middleware for production middlewareConfig: { expensiveMiddleware: { enabled: true, conditions: { custom: (context) => process.env.NODE_ENV === "production" } } } ``` ### 4. Keep Middleware Focused Each middleware should have a single responsibility: - ✅ Good: Analytics middleware only collects metrics - ❌ Bad: Analytics middleware that also filters content and logs errors ### 5. Test Middleware Independently ```typescript // Test middleware in isolation const middleware = createAnalyticsMiddleware(); const mockDoGenerate = async () => ({ text: "test" }); const result = await middleware.wrapGenerate({ doGenerate: mockDoGenerate, params: { prompt: "test" }, }); ``` ## See Also - [Built-in Middleware Reference](/docs/advanced/builtin-middleware) - Documentation for analytics, guardrails, and auto-evaluation - [Custom Middleware Guide](/docs/workflows/custom-middleware) - Step-by-step guide to creating custom middleware - [HITL Integration](/docs/features/enterprise-hitl) - Integrating middleware with Human-in-the-Loop workflows - [Provider Comparison](/docs/reference/provider-comparison) - Which providers support which middleware features --- ## Streaming Responses # Streaming Responses Real-time streaming capabilities for interactive AI applications with built-in analytics, evaluation, and enterprise-grade features. ## Overview NeuroLink supports real-time streaming for immediate response feedback, perfect for chat interfaces, live content generation, and interactive applications. Streaming works with all supported providers and includes advanced enterprise features: - **Multi-Model Streaming**: Intelligent load balancing across multiple SageMaker endpoints - **Rate Limiting & Backpressure**: Enterprise-grade request management - **Advanced Caching**: Semantic caching with partial response matching - **Real-time Analytics**: Comprehensive monitoring and alerting - **Security & Validation**: Prompt injection detection, content filtering, and compliance - **Tool Calling**: Streaming function calls with structured output parsing - **Error Recovery**: Automatic failover and retry mechanisms - **Performance Optimization**: Adaptive rate limiting and circuit breakers ## Basic Streaming ### SDK Streaming ```typescript const neurolink = new NeuroLink(); // Basic streaming const result = await neurolink.stream({ input: { text: "Tell me a story about AI" }, provider: "openai", }); for await (const chunk of result.stream) { if ("content" in chunk) { console.log(chunk.content); // Incremental content process.stdout.write(chunk.content); } } ``` ### Basic Streaming (Ready to Use) ```typescript const neurolink = new NeuroLink(); // Basic streaming (works immediately) const result = await neurolink.stream({ input: { text: "Generate a business analysis" }, }); for await (const chunk of result.stream) { process.stdout.write(chunk.content || ""); } ``` ### Streaming with Built-in Tools ```typescript const neurolink = new NeuroLink(); // Streaming with tools automatically available const result = await neurolink.stream({ input: { text: "What's the current time and weather in New York?" }, }); for await (const chunk of result.stream) { if ("content" in chunk) { process.stdout.write(chunk.content); } } ``` ### Simple Configuration ```typescript // NeuroLink automatically chooses the best available provider const neurolink = new NeuroLink(); // Streaming works with any configured provider const result = await neurolink.stream({ input: { text: "Analyze quarterly performance" }, maxTokens: 1000, temperature: 0.7, }); for await (const chunk of result.stream) { process.stdout.write(chunk.content || ""); } ``` ### CLI Streaming ```bash # Basic streaming with automatic provider selection npx @juspay/neurolink stream "Tell me a story" # With specific provider (optional) npx @juspay/neurolink stream "Explain quantum computing" --provider google-ai # With debug output to see provider selection npx @juspay/neurolink stream "Write a poem" --debug # JSON format streaming (future-ready) npx @juspay/neurolink stream "Create structured data" --format json --provider google-ai # Streaming with tools enabled npx @juspay/neurolink stream "What's the weather in New York?" --enable-tools # Specify streaming parameters npx @juspay/neurolink stream "Analyze market trends" \ --max-tokens 500 \ --temperature 0.7 \ --stream ``` ## Advanced Features ### Error Handling with Retry ```typescript class StreamingWithRetry { private neurolink = new NeuroLink(); async streamWithRetry(prompt: string, maxRetries = 3) { for (let attempt = 1; attempt setTimeout(resolve, 1000 * attempt)); } else { throw error; // Final attempt failed } } } } } // Usage const service = new StreamingWithRetry(); const result = await service.streamWithRetry("Explain quantum computing"); for await (const chunk of result.stream) { process.stdout.write(chunk.content || ""); } ``` ### Timeout Handling ```typescript async function streamWithTimeout(prompt: string, timeoutMs = 30000) { const neurolink = new NeuroLink(); const timeoutPromise = new Promise((_, reject) => { setTimeout(() => reject(new Error("Stream timeout")), timeoutMs); }); const streamPromise = neurolink.stream({ input: { text: prompt }, }); const result = await Promise.race([streamPromise, timeoutPromise]); return result; } // Usage with 45 second timeout const stream = await streamWithTimeout("Write a detailed report", 45000); ``` ### Collecting Full Response ```typescript async function collectFullResponse(prompt: string) { const neurolink = new NeuroLink(); const result = await neurolink.stream({ input: { text: prompt }, }); const chunks: string[] = []; for await (const chunk of result.stream) { if (chunk.content) { chunks.push(chunk.content); } } return { fullText: chunks.join(""), chunkCount: chunks.length, }; } // Usage const response = await collectFullResponse("Analyze market trends"); console.log(`Response: ${response.fullText}`); console.log(`Stats: ${response.chunkCount} chunks`); ``` ### Automatic Provider Selection ```typescript // NeuroLink automatically handles provider fallback async function smartStreaming(prompt: string) { const neurolink = new NeuroLink(); // NeuroLink automatically selects the best available provider // and falls back to alternatives if the primary fails const result = await neurolink.stream({ input: { text: prompt }, maxTokens: 500, }); return result; } // Usage - NeuroLink handles all provider logic internally const result = await smartStreaming("Explain machine learning"); for await (const chunk of result.stream) { process.stdout.write(chunk.content || ""); } ``` ### Manual Provider Selection (Optional) ```typescript // You can optionally specify a provider preference async function streamWithPreference( prompt: string, preferredProvider?: string, ) { const neurolink = new NeuroLink(); const result = await neurolink.stream({ input: { text: prompt }, provider: preferredProvider, // Optional - NeuroLink will choose if not specified maxTokens: 500, }); return result; } // Usage const result = await streamWithPreference( "Explain quantum computing", "google-ai", ); for await (const chunk of result.stream) { process.stdout.write(chunk.content || ""); } ``` ### Simple Rate Limiting ```typescript class ThrottledStreaming { private neurolink = new NeuroLink(); private lastRequest = 0; private minInterval = 1000; // 1 second between requests async throttledStream(prompt: string) { // Wait if needed const now = Date.now(); const timeSinceLastRequest = now - this.lastRequest; if (timeSinceLastRequest setTimeout(resolve, waitTime)); } this.lastRequest = Date.now(); return await this.neurolink.stream({ input: { text: prompt }, }); } } // Usage const throttled = new ThrottledStreaming(); const result = await throttled.throttledStream("Explain quantum computing"); for await (const chunk of result.stream) { process.stdout.write(chunk.content || ""); } ``` ### Batch Processing ```typescript async function processBatch(prompts: string[], maxConcurrent = 2) { const neurolink = new NeuroLink(); const results = []; // Process in chunks for (let i = 0; i { // Stagger requests to avoid overwhelming providers await new Promise((resolve) => setTimeout(resolve, index * 500)); return await neurolink.stream({ input: { text: prompt }, }); }); const batchResults = await Promise.all(batchPromises); results.push(...batchResults); console.log(`Completed batch ${Math.floor(i / maxConcurrent) + 1}`); // Pause between batches if (i + maxConcurrent setTimeout(resolve, 1000)); } } return results; } // Usage const prompts = ["Explain AI", "Explain ML", "Explain deep learning"]; const results = await processBatch(prompts, 2); console.log(`Processed ${results.length} requests`); ``` ### Simple Caching Pattern ```typescript class SimpleCache { private neurolink = new NeuroLink(); private cache = new Map(); private cacheTTL = 60 * 60 * 1000; // 1 hour private isExpired(timestamp: number) { return Date.now() - timestamp > this.cacheTTL; } async streamWithCache(prompt: string) { const cached = this.cache.get(prompt); // Check cache first if (cached && !this.isExpired(cached.timestamp)) { console.log("⚡ Cache hit!"); // Return cached response as simulated stream const words = cached.response.split(" "); return { async *stream() { for (const word of words) { await new Promise((resolve) => setTimeout(resolve, 50)); yield { content: word + " " }; } }, fromCache: true, }; } console.log(" Cache miss. Generating..."); // Generate new response using NeuroLink's automatic provider selection const result = await this.neurolink.stream({ input: { text: prompt }, }); // Collect response while streaming for caching const chunks: string[] = []; const cache = this.cache; const responseStream = { async *stream() { for await (const chunk of result.stream) { if (chunk.content) { chunks.push(chunk.content); yield chunk; } } // Cache after streaming completes const fullResponse = chunks.join(""); cache.set(prompt, { response: fullResponse, timestamp: Date.now(), }); console.log(` Cached response`); }, }; return { stream: responseStream.stream(), fromCache: false, }; } } // Usage const cache = new SimpleCache(); // First request (cache miss) const result1 = await cache.streamWithCache("Explain renewable energy"); for await (const chunk of result1.stream) { process.stdout.write(chunk.content || ""); } console.log(`\nFrom cache: ${result1.fromCache}`); // Second identical request (cache hit) const result2 = await cache.streamWithCache("Explain renewable energy"); for await (const chunk of result2.stream) { process.stdout.write(chunk.content || ""); } console.log(`\nFrom cache: ${result2.fromCache}`); ``` ### Custom Configuration ```typescript const stream = await neurolink.stream({ input: { text: "Generate comprehensive analysis" }, provider: "anthropic", temperature: 0.7, maxTokens: 2000, output: { format: "json", // Future-ready JSON streaming streaming: { chunkSize: 256, bufferSize: 1024, enableProgress: true, }, }, }); ``` ### JSON Streaming Support ```typescript // Structured data streaming (future-ready) const jsonStream = await neurolink.stream({ input: { text: "Create a detailed project plan with milestones" }, output: { format: "structured", streaming: { chunkSize: 512, enableProgress: true, }, }, schema: { type: "object", properties: { projectName: { type: "string" }, phases: { type: "array", items: { type: "object", properties: { name: { type: "string" }, duration: { type: "string" }, tasks: { type: "array", items: { type: "string" } }, }, }, }, }, }, }); let structuredData = ""; for await (const chunk of jsonStream.stream) { structuredData += chunk.content; // Try to parse partial JSON try { const partial = JSON.parse(structuredData); console.log("Partial structure:", partial); } catch { // Still building complete JSON } } ``` ### Error Handling & Recovery ```typescript const neurolink = new NeuroLink(); // NeuroLink provides built-in error recovery and automatic provider fallback async function robustStreaming(prompt: string) { const maxRetries = 3; let attempts = 0; while (attempts setTimeout(resolve, 1000 * attempts)); } else { throw new Error(`Streaming failed after ${maxRetries} attempts`); } } } } // Usage with automatic error recovery try { await robustStreaming("Generate a comprehensive analysis"); console.log("Stream completed successfully"); } catch (error) { console.error("All retry attempts failed:", error.message); } ``` ### Security & Validation ````typescript const neurolink = new NeuroLink(); // NeuroLink includes built-in security and validation features async function secureStreaming(prompt: string, userId: string) { // Basic input validation if (!prompt || prompt.length > 50000) { throw new Error("Invalid prompt: too long or empty"); } // Basic user authentication check if (!userId || userId.length { console.log("\n✅ Streaming completed with analytics:", analytics); }) .catch((error) => { console.error("Streaming failed:", error.message); }); ```` ### Real-time Analytics ```typescript const stream = await neurolink.stream({ input: { text: "Generate business report" }, analytics: { enabled: true, realTime: true, context: { userId: "user123", sessionId: "session456", feature: "report_generation", }, }, }); for await (const chunk of stream.stream) { if ("content" in chunk) { console.log(chunk.content); } } // Access analytics after streaming completes const analytics = stream.analytics; if (analytics) { console.log(`Tokens used: ${analytics.tokensUsed}`); console.log(`Cost: $${analytics.estimatedCost}`); } ``` ### CLI Streaming with Analytics ```bash # Streaming with analytics npx @juspay/neurolink stream "Create documentation" \ --enable-analytics \ --context '{"project":"docs","team":"engineering"}' \ --debug # With evaluation npx @juspay/neurolink stream "Write production code" \ --enable-analytics \ --enable-evaluation \ --evaluation-domain "Senior Developer" \ --debug ``` ## Use Cases ### Chat Interface ```typescript function ChatComponent() { const [messages, setMessages] = useState([]); const [currentResponse, setCurrentResponse] = useState(""); const neurolink = new NeuroLink(); const sendMessage = async (userMessage) => { setMessages(prev => [...prev, { role: "user", content: userMessage }]); setCurrentResponse(""); const result = await neurolink.stream({ input: { text: userMessage }, provider: "google-ai" }); let fullResponse = ""; for await (const chunk of result.stream) { if ("content" in chunk) { fullResponse += chunk.content; setCurrentResponse(prev => prev + chunk.content); } } setMessages(prev => [...prev, { role: "assistant", content: fullResponse }]); setCurrentResponse(""); }; return ( {messages.map((msg, i) => ( {msg.content} ))} {currentResponse && ( {currentResponse} | )} ); } ``` ### Live Content Generation ```typescript // Real-time blog post generation async function generateBlogPost(topic: string) { const result = await neurolink.stream({ input: { text: `Write a comprehensive blog post about ${topic}. Include introduction, main points, and conclusion.`, }, provider: "anthropic", maxTokens: 3000, }); const sections = []; let currentSection = ""; for await (const chunk of result.stream) { if ("content" in chunk) { currentSection += chunk.content; // Update UI in real-time updateBlogPostPreview(currentSection); // Detect section breaks if (chunk.content.includes("\n\n## ")) { sections.push(currentSection); currentSection = ""; } } } return sections; } ``` ### Interactive Documentation ```bash #!/bin/bash # Interactive documentation generator echo " Interactive Documentation Generator" echo "Enter topic (or 'quit' to exit):" while read -r topic; do if [ "$topic" = "quit" ]; then break fi echo " Generating documentation for: $topic" npx @juspay/neurolink stream " Create comprehensive technical documentation for: $topic Include: - Overview and purpose - Installation/setup instructions - Usage examples - Best practices - Troubleshooting " --provider google-ai --enable-analytics echo -e "\n\n Documentation complete! Enter next topic:" done ``` ## ⚙️ Enterprise Configuration ### Provider Configuration ```typescript // Configure multiple providers for intelligent routing const neurolink = new NeuroLink(); const providerConfigs = [ { modelId: "llama-3-70b", modelName: "LLaMA 3 70B", modelType: "llama", weight: 3, specializations: ["reasoning", "analysis"], config: { maxTokens: 4000, temperature: 0.7, specializations: ["reasoning", "analysis"], }, thresholds: { maxLatency: 5000, maxErrorRate: 2, minThroughput: 20, }, }, { modelId: "claude-3-5-sonnet", modelName: "Claude 3.5 Sonnet", modelType: "anthropic", weight: 4, specializations: ["function_calling", "structured_output"], config: { maxTokens: 8000, temperature: 0.6, specializations: ["function_calling", "structured_output"], }, thresholds: { maxLatency: 3000, maxErrorRate: 1, minThroughput: 25, }, }, { modelId: "gemini-2-flash", modelName: "Gemini 2.0 Flash", modelType: "google", weight: 2, specializations: ["speed", "general"], config: { maxTokens: 2000, temperature: 0.8, specializations: ["speed", "general"], }, thresholds: { maxLatency: 1500, maxErrorRate: 3, minThroughput: 40, }, }, ], { loadBalancingStrategy: "performance_based", autoFailover: { enabled: true, maxRetries: 3, fallbackStrategies: ["model_switch", "endpoint_switch", "provider_switch"], circuitBreakerThreshold: 5, circuitBreakerTimeout: 60000, }, healthCheck: { enabled: true, interval: 30000, timeout: 5000, retryOnFailure: 2, }, monitoring: { enabled: true, metricsInterval: 15000, detailedMetrics: true, performanceThresholds: { responseTime: 3000, errorRate: 2, throughput: 20, }, }, }); ``` ### Production Environment Variables For production deployments, configure these environment variables: ```bash # Basic SageMaker Streaming export AWS_REGION="us-east-1" export AWS_ACCESS_KEY_ID="your-access-key" export AWS_SECRET_ACCESS_KEY="your-secret-key" export SAGEMAKER_DEFAULT_ENDPOINT="your-endpoint-name" # Streaming Configuration export NEUROLINK_STREAMING_ENABLED="true" export NEUROLINK_STREAMING_TIMEOUT="30000" export NEUROLINK_STREAMING_MAX_TOKENS="2000" # Optional: Performance Settings export NEUROLINK_STREAMING_BUFFER_SIZE="1024" export NEUROLINK_STREAMING_FLUSH_INTERVAL="100" export NEUROLINK_STREAMING_ENABLE_ANALYTICS="true" ``` ### Production Configuration File Create `neurolink.config.js` in your project root: ```javascript // neurolink.config.js module.exports = { providers: { sagemaker: { region: process.env.AWS_REGION || "us-east-1", endpointName: process.env.SAGEMAKER_DEFAULT_ENDPOINT, timeout: 30000, maxRetries: 3, streaming: { enabled: true, bufferSize: 1024, timeout: 60000, }, }, }, streaming: { defaultProvider: "sagemaker", enableAnalytics: true, maxTokens: 2000, temperature: 0.7, }, }; ``` ### Simple Production Usage ```typescript // Production service class class AIStreamingService { private neurolink: NeuroLink; constructor() { this.neurolink = new NeuroLink({ providers: { sagemaker: { endpointName: process.env.SAGEMAKER_ENDPOINT, region: process.env.AWS_REGION, }, }, }); } async streamResponse(prompt: string, options: any = {}) { const result = await this.neurolink.stream({ input: { text: prompt }, provider: "sagemaker", maxTokens: options.maxTokens || 500, temperature: options.temperature || 0.7, }); return result.stream; } async getFullResponse(prompt: string) { const stream = await this.streamResponse(prompt); const chunks: string[] = []; for await (const chunk of stream) { if (chunk.content) { chunks.push(chunk.content); } } return chunks.join(""); } } // Usage const aiService = new AIStreamingService(); const response = await aiService.getFullResponse("Explain machine learning"); console.log(response); ``` ### Stream Settings ```typescript type StreamConfig = { bufferSize?: number; // Chunk buffer size (default: 1024) flushInterval?: number; // Flush interval in ms (default: 100) timeout?: number; // Stream timeout in ms (default: 60000) enableChunking?: boolean; // Enable smart chunking (default: true) retryAttempts?: number; // Retry attempts on failure (default: 3) reconnectDelay?: number; // Reconnection delay in ms (default: 1000) }; const stream = await neurolink.stream({ input: { text: "Your prompt" }, stream: { bufferSize: 2048, flushInterval: 50, timeout: 120000, enableChunking: true, retryAttempts: 5, }, }); ``` ### Provider-Specific Options ```typescript // OpenAI streaming const openaiStream = await neurolink.stream({ input: { text: "Generate content" }, provider: "openai", model: "gpt-4o", stream: { enableChunking: true, bufferSize: 1024, }, }); // Google AI streaming const googleStream = await neurolink.stream({ input: { text: "Generate content" }, provider: "google-ai", model: "gemini-2.5-pro", stream: { enableChunking: false, // Google AI handles chunking internally flushInterval: 50, }, }); ``` ## Enterprise Monitoring & Debugging ### Real-time Monitoring Dashboard ```typescript // Built-in monitoring with NeuroLink class EnterpriseStreamingMonitor { private neurolink: NeuroLink; constructor() { this.neurolink = new NeuroLink(); } async getComprehensiveDashboard() { // NeuroLink provides built-in monitoring and analytics const dashboard = { timestamp: Date.now(), system: { health: "healthy", // Built-in health checks performance: await this.getPerformanceMetrics(), providers: await this.getProviderStatus(), }, streaming: { activeStreams: 0, // Built-in tracking totalRequests: 0, averageLatency: 0, }, }; return dashboard; } async generateAlerts() { const alerts = []; const dashboard = await this.getComprehensiveDashboard(); // System health alerts if (dashboard.system.health.status === "unhealthy") { alerts.push({ severity: "critical", type: "system_health", message: "System health is critical", details: dashboard.system.health, }); } // Performance alerts if (dashboard.system.performance.averageResponseTime > 5000) { alerts.push({ severity: "warning", type: "performance", message: "High response times detected", details: { responseTime: dashboard.system.performance.averageResponseTime, }, }); } // Security alerts if (dashboard.security.stats.recentEvents > 10) { alerts.push({ severity: "high", type: "security", message: "High security event volume", details: dashboard.security.stats, }); } // Cache performance alerts if (dashboard.cache.stats.hitMiss.hitRate { const dashboard = await monitor.getComprehensiveDashboard(); console.log("Dashboard Update:", JSON.stringify(dashboard, null, 2)); // Check for alerts const alerts = await monitor.generateAlerts(); if (alerts.length > 0) { console.log(" ALERTS:", alerts); } }, 30000); // Every 30 seconds // Export metrics to monitoring systems setInterval(async () => { await monitor.exportMetrics("prometheus"); await monitor.exportMetrics("cloudwatch"); }, 60000); // Every minute ``` ### CLI Monitoring Commands ```bash # Real-time streaming monitor npx @juspay/neurolink sagemaker stream-monitor \ --endpoint production-endpoint \ --duration 3600 \ --alerts \ --export prometheus \ --export cloudwatch # System health check npx @juspay/neurolink sagemaker diagnose \ --endpoint production-endpoint \ --check-models \ --check-cache \ --check-security \ --check-rate-limits # Performance benchmarking npx @juspay/neurolink sagemaker stream-benchmark \ --endpoint production-endpoint \ --concurrent 50 \ --requests 1000 \ --duration 300 \ --enable-analytics \ --enable-caching \ --model-selection performance_based # Security audit npx @juspay/neurolink sagemaker security-audit \ --endpoint production-endpoint \ --hours 24 \ --export-report \ --include-recommendations # Cache analysis npx @juspay/neurolink sagemaker cache-analyze \ --endpoint production-endpoint \ --strategy semantic \ --optimize \ --report ``` ### Stream Debugging ```bash # Enable verbose streaming debug npx @juspay/neurolink stream "Debug this response" \ --provider openai \ --debug \ --timeout 30000 # Monitor stream performance npx @juspay/neurolink stream "Performance test" \ --enable-analytics \ --debug \ --provider google-ai # Debug streaming with the unified NeuroLink API npx @juspay/neurolink stream "Complex analysis task" \ --provider sagemaker \ --debug \ --max-tokens 500 \ --temperature 0.7 ``` ### Advanced Performance Monitoring ```typescript class PerformanceMonitor { private neurolink: NeuroLink; private startTime: number; private metrics: { tokenCount: number; chunkCount: number; responseTime: number; throughput: number; latencyDistribution: number[]; errorCount: number; } = { tokenCount: 0, chunkCount: 0, responseTime: 0, throughput: 0, latencyDistribution: [], errorCount: 0, }; constructor() { this.neurolink = new NeuroLink(); this.startTime = Date.now(); } async monitorStream(stream: AsyncIterable, requestId: string) { const chunkTimes: number[] = []; let firstChunkTime: number | null = null; let lastChunkTime: number = Date.now(); for await (const chunk of stream) { const chunkTime = Date.now(); if (!firstChunkTime) { firstChunkTime = chunkTime; console.log( `⏱️ Time to first chunk: ${firstChunkTime - this.startTime}ms`, ); } if ("content" in chunk) { this.metrics.tokenCount += this.estimateTokens(chunk.content); this.metrics.chunkCount++; chunkTimes.push(chunkTime - lastChunkTime); // Built-in metrics are automatically tracked by NeuroLink // Real-time throughput calculation const elapsed = (chunkTime - this.startTime) / 1000; this.metrics.throughput = this.metrics.tokenCount / elapsed; // Display real-time metrics every 10 chunks if (this.metrics.chunkCount % 10 === 0) { console.log( ` Tokens: ${this.metrics.tokenCount}, Throughput: ${this.metrics.throughput.toFixed(2)} t/s`, ); } } lastChunkTime = chunkTime; } // After stream completes, calculate final metrics if (this.metrics.chunkCount > 0 && chunkTimes.length > 0) { this.metrics.responseTime = Date.now() - this.startTime; // Calculate latency statistics this.metrics.latencyDistribution = chunkTimes; const avgChunkLatency = chunkTimes.reduce((a, b) => a + b, 0) / chunkTimes.length; const p95ChunkLatency = this.percentile(chunkTimes, 95); const p99ChunkLatency = this.percentile(chunkTimes, 99); // Final metrics console.log(`\n Performance Summary:`); console.log(` Total Response Time: ${this.metrics.responseTime}ms`); console.log( ` Time to First Chunk: ${firstChunkTime! - this.startTime}ms`, ); console.log(` Total Tokens: ${this.metrics.tokenCount}`); console.log(` Total Chunks: ${this.metrics.chunkCount}`); console.log( ` Average Throughput: ${this.metrics.throughput.toFixed(2)} tokens/sec`, ); console.log(` Average Chunk Latency: ${avgChunkLatency.toFixed(2)}ms`); console.log(` P95 Chunk Latency: ${p95ChunkLatency.toFixed(2)}ms`); console.log(` P99 Chunk Latency: ${p99ChunkLatency.toFixed(2)}ms`); console.log(` Error Count: ${this.metrics.errorCount}`); console.log( ` Success Rate: ${(((this.metrics.chunkCount - this.metrics.errorCount) / this.metrics.chunkCount) * 100).toFixed(2)}%`, ); } return this.metrics; } private estimateTokens(text: string): number { // Rough estimation: ~4 characters per token return Math.ceil(text.length / 4); } private percentile(arr: number[], p: number): number { const sorted = [...arr].sort((a, b) => a - b); const index = Math.ceil((p / 100) * sorted.length) - 1; return sorted[index] || 0; } async generatePerformanceReport() { const dashboardMetrics = this.analytics.getDashboardMetrics(); const report = this.analytics.generateReport( Date.now() - 60 * 60 * 1000, // Last hour Date.now(), ); return { timestamp: Date.now(), currentSession: this.metrics, hourlyReport: report, systemHealth: dashboardMetrics.systemHealth, trends: dashboardMetrics.trends, recommendations: this.generateRecommendations(report), }; } private generateRecommendations(report: any): string[] { const recommendations: string[] = []; if (report.performance.averageDuration > 5000) { recommendations.push( "Consider using faster models or increasing instance sizes", ); } if (report.performance.p95Duration > 10000) { recommendations.push( "High latency variance detected - review load balancing strategy", ); } if (report.requests.successRate { res.setHeader("Content-Type", "text/plain"); res.setHeader("Transfer-Encoding", "chunked"); try { const result = await neurolink.stream({ input: { text: req.body.prompt }, provider: "google-ai", }); for await (const chunk of result.stream) { if ("content" in chunk) { res.write(chunk.content); } } res.end(); } catch (error) { res.status(500).json({ error: error.message }); } }); ``` ### WebSocket Streaming ```typescript const wss = new WebSocket.Server({ port: 8080 }); const neurolink = new NeuroLink(); wss.on("connection", (ws) => { ws.on("message", async (message) => { const { prompt } = JSON.parse(message.toString()); try { const result = await neurolink.stream({ input: { text: prompt }, }); for await (const chunk of result.stream) { if ("content" in chunk) { ws.send( JSON.stringify({ type: "chunk", content: chunk.content, }), ); } } ws.send(JSON.stringify({ type: "complete" })); } catch (error) { ws.send(JSON.stringify({ type: "error", error: error.message })); } }); }); ``` ### Server-Sent Events (SSE) ```typescript app.get("/api/stream-sse", async (req, res) => { res.setHeader("Content-Type", "text/event-stream"); res.setHeader("Cache-Control", "no-cache"); res.setHeader("Connection", "keep-alive"); const result = await neurolink.stream({ input: { text: req.query.prompt as string }, }); for await (const chunk of result.stream) { if ("content" in chunk) { res.write( `data: ${JSON.stringify({ content: chunk.content, })}\n\n`, ); } } res.end(); }); ``` ## Error Handling ### Robust Error Handling ```typescript async function robustStreaming(prompt: string) { const maxRetries = 3; let attempts = 0; while (attempts setTimeout(resolve, 1000 * attempts)); } else { throw new Error(`Streaming failed after ${maxRetries} attempts`); } } } } ``` ## Enterprise Use Cases ### Financial Services Streaming ```typescript // High-frequency trading analysis with built-in compliance const neurolink = new NeuroLink(); async function analyzeMarketData(marketData: string, userId: string) { const result = await neurolink.stream({ provider: "anthropic", // Choose best provider for financial analysis input: { text: `Analyze this market data and provide risk assessment: ${marketData}`, }, maxTokens: 1000, temperature: 0.2, // Low temperature for precise financial analysis }); // Audit trail for compliance console.log(`Financial analysis requested by user: ${userId}`); console.log(`Provider: ${result.provider}`); return result; } ``` ### Healthcare AI with HIPAA Compliance ```typescript // HIPAA-compliant medical AI streaming with NeuroLink const neurolink = new NeuroLink(); // Configuration for HIPAA compliance const healthcareConfig = { provider: "anthropic", // Choose provider with strong security maxTokens: 1000, temperature: 0.1, // Low temperature for medical accuracy // Built-in security and compliance features }; async function processMedicalQuery( query: string, patientId: string, providerId: string, ) { // Basic validation for medical queries if (!query || !patientId || !providerId) { throw new Error("Missing required parameters for medical query"); } // Audit logging for HIPAA compliance console.log( `Medical query requested by provider: ${providerId} for patient: ${patientId.slice(0, 3)}***`, ); const result = await neurolink.stream({ ...healthcareConfig, input: { text: query }, }); const sanitizedChunks = []; for await (const chunk of result.stream) { // Basic content filtering for sensitive data if ("content" in chunk) { // Apply basic PII filtering here if needed sanitizedChunks.push(chunk); } } console.log( `Medical query completed for patient: ${patientId.slice(0, 3)}***`, ); return sanitizedChunks; } ``` ### E-commerce Recommendation Engine ```typescript // High-throughput e-commerce streaming with NeuroLink const neurolink = new NeuroLink(); async function generatePersonalizedRecommendations( userId: string, browsingHistory: any[], preferences: any, ) { const result = await neurolink.stream({ input: { text: `Generate personalized product recommendations for user with browsing history: ${JSON.stringify(browsingHistory)} and preferences: ${JSON.stringify(preferences)}`, }, }); const chunks: string[] = []; for await (const chunk of result.stream) { if ("content" in chunk) { chunks.push(chunk.content); } } return { content: chunks.join(""), provider: result.provider, model: result.model, }; } ``` ## Configuration Files ### Enterprise Configuration Template ```yaml # neurolink-enterprise-streaming.yaml streaming: sagemaker: endpoints: production: name: "production-multi-model" models: - id: "llama-3-70b" name: "LLaMA 3 70B" type: "llama" weight: 3 specializations: ["reasoning", "analysis"] thresholds: max_latency: 5000 max_error_rate: 2 min_throughput: 20 - id: "claude-3-5-sonnet" name: "Claude 3.5 Sonnet" type: "anthropic" weight: 4 specializations: ["function_calling", "structured_output"] thresholds: max_latency: 3000 max_error_rate: 1 min_throughput: 25 load_balancing: strategy: "performance_based" health_check: enabled: true interval: 30000 timeout: 5000 failover: enabled: true max_retries: 3 strategies: ["model_switch", "endpoint_switch"] circuit_breaker: threshold: 5 timeout: 60000 rate_limiting: preset: "enterprise" requests_per_second: 100 burst_capacity: 200 adaptive: true target_response_time: 1000 strategy: "queue" max_queue_size: 1000 priority_queue: true caching: preset: "enterprise" storage: "hybrid" max_size_mb: 5000 ttl: 21600000 # 6 hours strategy: "fuzzy" compression: enabled: true algorithm: "brotli" partial_hits: true warming: "scheduled" security: preset: "enterprise" input_validation: enabled: true max_prompt_length: 100000 injection_detection: true content_policy: true output_filtering: enabled: true pii_redaction: true toxicity_filtering: true compliance: true access_control: enabled: true authentication: true api_key_validation: true monitoring: enabled: true real_time_alerts: true threat_detection: true compliance: gdpr: true hipaa: false soc2: true audit_logging: true analytics: preset: "enterprise" sampling_rate: 1.0 retention_days: 365 real_time_monitoring: enabled: true update_interval: 10000 alert_thresholds: error_rate: 1 response_time: 1500 queue_size: 100 export: enabled: true formats: ["prometheus", "cloudwatch"] interval: 60000 destinations: - type: "cloudwatch" config: namespace: "NeuroLink/Enterprise" region: "us-east-1" - type: "prometheus" config: pushgateway: "prometheus:9091" ``` ## Related Documentation - [CLI Commands](/docs/cli/commands) - Streaming CLI commands - [SDK Reference](/docs/sdk/api-reference) - Complete streaming API - [Analytics](/docs/reference/analytics) - Streaming analytics features - [Dynamic Models](/docs/guides/dynamic-models) - Multi-model endpoint setup - [Enterprise Features](/docs/guides/enterprise) - Enterprise security features - [Performance Optimization](/docs/deployment/performance) - Optimization strategies - [Analytics & Monitoring](/docs/reference/analytics) - Comprehensive monitoring - [Provider Setup](/docs/getting-started/provider-setup) - Provider configuration - [Development Guide](/docs/) - Development and deployment guide ## What's Next With Phase 2 complete, NeuroLink now offers enterprise-grade streaming capabilities: - **✅ Multi-Model Streaming**: Intelligent load balancing and automatic failover - **✅ Enterprise Security**: Comprehensive validation, filtering, and compliance - **✅ Advanced Caching**: Semantic caching with partial response matching - **✅ Real-time Analytics**: Complete monitoring and alerting system - **✅ Rate Limiting**: Sophisticated backpressure handling and circuit breakers - **✅ Tool Integration**: Streaming function calls with structured output Upcoming in Phase 3: - **Multi-Provider Streaming**: Seamless streaming across different AI providers - **Edge Deployment**: CDN-based streaming for global latency optimization - **Advanced Tool Orchestration**: Complex multi-step tool workflows - **Custom Model Integration**: Support for proprietary and fine-tuned models --- ## Updated Provider Test Results # Updated Provider Test Results This document contains the latest test results for all supported providers. ## Test Summary ### Provider Status - ✅ OpenAI: All tests passing - ✅ Amazon Bedrock: All tests passing - ✅ Google Vertex AI: All tests passing - ✅ Anthropic: All tests passing - ✅ LiteLLM: All tests passing ### Performance Metrics - Average response time: 2.3s - Success rate: 99.7% - Error rate: 0.3% ### Test Coverage - Unit tests: 95% - Integration tests: 87% - End-to-end tests: 92% ## Detailed Results ### OpenAI Provider - Text generation: ✅ Pass - Streaming: ✅ Pass - Error handling: ✅ Pass ### Amazon Bedrock Provider - Text generation: ✅ Pass - Streaming: ✅ Pass - Error handling: ✅ Pass ### Google Vertex AI Provider - Text generation: ✅ Pass - Streaming: ✅ Pass - Error handling: ✅ Pass For more details, see the [Testing Guide](/docs/development/testing). --- # Reference ## Reference # Reference Complete reference documentation for NeuroLink configuration, troubleshooting, and technical details. ## Reference Hub This section provides comprehensive reference materials for advanced usage, configuration, and problem-solving. - **[Troubleshooting](/docs/reference/troubleshooting)** — Common issues, error messages, and solutions for NeuroLink CLI and SDK usage. - **[Configuration](/docs/deployment/configuration)** — Complete configuration reference including environment variables, provider settings, and optimization. - **[Provider Capabilities Audit](/docs/reference/provider-capabilities-audit)** — Capability matrix for the 13 text/multimodal providers it historically tracks — the other 27 are covered in the per-provider guides with capability matrices and configuration examples. - **[Provider Comparison](/docs/reference/provider-comparison)** — Detailed comparison of the hand-written provider implementations with features, costs, and recommendations. - **[FAQ](/docs/reference/faq)** — Frequently asked questions about NeuroLink features, limitations, and best practices. - **[Error Codes](/docs/reference/error-codes)** — Complete error code reference with categorized codes, severity levels, and resolution guidance. - **[Analytics](/docs/reference/analytics)** — Comprehensive guide to NeuroLink analytics, metrics, token tracking, cost monitoring, and observability integration. - **[Telemetry Guide](/docs/observability/telemetry)** — OTLP setup, exporter behavior, and the local OpenObserve workflow for the Claude proxy. - **[Server Configuration](/docs/reference/server-configuration)** — Configuration reference for server adapters including Hono, Express, Fastify, and Koa framework integration. - **[MCP Enhancements API](/docs/features/mcp-enhancements.md#api-reference)** — API reference for MCP enhancements including ToolRouter, ToolCache, RequestBatcher, tool annotations, and elicitation protocol. ## Quick Reference ### Environment Variables ```bash # Core Provider API Keys OPENAI_API_KEY="sk-your-openai-key" GOOGLE_AI_API_KEY="AIza-your-google-ai-key" ANTHROPIC_API_KEY="sk-ant-your-key" # AWS Bedrock (requires AWS credentials) AWS_ACCESS_KEY_ID="your-access-key" AWS_SECRET_ACCESS_KEY="your-secret-key" AWS_REGION="us-east-1" # Azure OpenAI AZURE_OPENAI_API_KEY="your-azure-key" AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com" # Google Vertex AI GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json" # Hugging Face HUGGINGFACE_API_KEY="hf_your-key" # Mistral AI MISTRAL_API_KEY="your-mistral-key" ``` ### CLI Quick Commands ```bash # Status and diagnostics neurolink status # Check all providers neurolink status --verbose # Detailed diagnostics neurolink provider status # Provider-specific status # Text generation neurolink generate "prompt" # Basic generation neurolink gen "prompt" -p openai # Specific provider neurolink stream "prompt" # Real-time streaming # Configuration neurolink config show # Show current config neurolink config validate # Validate setup neurolink config init # Interactive setup # MCP tools neurolink mcp discover # Find available servers neurolink mcp list # List installed servers neurolink mcp install # Install MCP server # Claude proxy + local telemetry neurolink proxy setup neurolink proxy status --format json neurolink proxy telemetry setup neurolink proxy telemetry status ``` ### SDK Quick Reference ```typescript // Basic usage const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Your prompt" }, provider: "auto", // or specific provider }); // Auto-select best provider const provider = createBestAIProvider(); const result = await provider.generate({ input: { text: "Your prompt" }, }); // With advanced options const result = await neurolink.generate({ input: { text: "Your prompt" }, provider: "google-ai", model: "gemini-2.5-pro", temperature: 0.7, maxTokens: 1000, enableAnalytics: true, enableEvaluation: true, timeout: "30s", }); ``` ## Provider Comparison Matrix **Quick Overview** (see [Provider Capabilities Audit](/docs/reference/provider-capabilities-audit) for complete details): | Feature | OpenAI | Google AI | Anthropic | Bedrock | Azure | Vertex | HuggingFace | Ollama | Mistral | LiteLLM | SageMaker | OpenRouter | OpenAI Compat | | ---------------- | ------ | --------- | --------- | ------- | ----- | ------ | ----------- | ------ | ------- | ------- | --------- | ---------- | ------------- | | **Free Tier** | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | Varies | ❌ | Varies | Varies | | **Tool Support** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ⚠️ | ⚠️ | ✅ | ✅ | ✅ | ✅ | ✅ | | **Streaming** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | **Vision** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ⚠️ | ❌ | ✅ | Varies | ✅ | Varies | | **Local** | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | Varies | | **Enterprise** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ⚠️ | ✅ | ✅ | ✅ | ✅ | ✅ | Varies | For detailed capability matrices, authentication requirements, and configuration examples, see: - **[Provider Capabilities Audit](/docs/reference/provider-capabilities-audit)** - Technical implementation details - **[Provider Comparison](/docs/reference/provider-comparison)** - Feature comparison and selection guide ## Error Code Reference ### Common Error Codes | Code | Description | Solution | | ---------------------- | ------------------------------ | --------------------------------- | | `AUTH_ERROR` | Invalid API key or credentials | Check environment variables | | `RATE_LIMIT` | API rate limit exceeded | Implement delays or upgrade plan | | `TIMEOUT` | Request timeout | Increase timeout or check network | | `MODEL_NOT_FOUND` | Invalid model name | Check available models | | `TOOL_ERROR` | MCP tool execution failed | Check tool configuration | | `PROVIDER_UNAVAILABLE` | Provider service down | Try different provider | ### Debugging Tips ```bash # Enable debug mode neurolink generate "test" --debug # Verbose logging neurolink status --verbose # Check configuration neurolink config validate ``` ```typescript // SDK debugging const neurolink = new NeuroLink({ debug: true, logLevel: "verbose", }); ``` ## Performance Optimization ### Response Time Optimization - **Provider selection**: Use fastest providers for your region - **Model selection**: Choose appropriate model size for task - **Concurrency**: Limit parallel requests to avoid rate limits - **Caching**: Implement response caching for repeated queries ### Cost Optimization - **Model selection**: Use cost-effective models when possible - **Token management**: Optimize prompt length and max tokens - **Provider comparison**: Compare costs across providers - **Monitoring**: Track usage with analytics ### Memory Management - **Streaming**: Use streaming for large responses - **Batch processing**: Process multiple requests efficiently - **Cleanup**: Proper resource cleanup in long-running applications ## Security Best Practices ### API Key Management - **Environment variables**: Store keys in `.env` files - **Never commit**: Keep keys out of version control - **Rotation**: Regularly rotate API keys - **Scope limitation**: Use least-privilege access ### Production Deployment - **Secret management**: Use secure secret management systems - **Network security**: Implement proper network controls - **Monitoring**: Log and monitor API usage - **Error handling**: Don't expose sensitive errors ## 🆘 Getting Help ### Support Channels 1. **[GitHub Issues](https://github.com/juspay/neurolink/issues)** - Bug reports and feature requests 2. **[GitHub Discussions](https://github.com/juspay/neurolink/discussions)** - Community questions 3. **[Documentation](/docs/)** - Comprehensive guides and references 4. **[Examples](/docs/)** - Practical implementation patterns ### Before Asking for Help 1. Check the [Troubleshooting Guide](/docs/reference/troubleshooting) 2. Review the [FAQ](/docs/reference/faq) 3. Search existing [GitHub Issues](https://github.com/juspay/neurolink/issues) 4. Try the `--debug` flag for more information ### Reporting Issues When reporting issues, include: - **NeuroLink version**: `npm list @juspay/neurolink` - **Node.js version**: `node --version` - **Operating system**: OS and version - **Error message**: Complete error output - **Reproduction steps**: Minimal example to reproduce - **Configuration**: Relevant environment variables (without keys) ## External Resources ### AI Provider Documentation - **[OpenAI API](https://platform.openai.com/docs)** - OpenAI official documentation - **[Google AI Studio](https://aistudio.google.com/docs)** - Google AI platform docs - **[Anthropic Claude](https://docs.anthropic.com/)** - Anthropic API reference - **[AWS Bedrock](https://docs.aws.amazon.com/bedrock/)** - Amazon Bedrock guide ### Related Projects - **[Vercel AI SDK](https://github.com/vercel/ai)** - Separate framework NeuroLink interoperates with via the client SDK's `LanguageModelV1` adapter - **[Model Context Protocol](https://modelcontextprotocol.io)** - Tool integration standard - **[TypeScript](https://www.typescriptlang.org/)** - Type safety and development --- ## Analytics Reference # Analytics Reference NeuroLink provides comprehensive analytics capabilities for tracking token usage, costs, performance metrics, and quality evaluation across your configured AI provider interactions. ## Overview The analytics system in NeuroLink consists of several interconnected components: | Component | Purpose | | -------------------------- | --------------------------------------------------------------- | | **Token Usage Tracking** | Monitor input/output tokens, cache tokens, and reasoning tokens | | **Cost Analytics** | Estimate and track costs across providers and models | | **Performance Metrics** | Measure response times, throughput, and memory usage | | **Quality Evaluation** | Assess response relevance, accuracy, and completeness | | **Middleware Integration** | Automatic analytics collection via middleware | ## Token Usage Tracking ### Basic Token Usage NeuroLink automatically tracks token usage for every generation: ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain quantum computing in simple terms" }, provider: "openai", enableAnalytics: true, }); // Access token usage console.log("Token Usage:", { input: result.usage?.input, output: result.usage?.output, total: result.usage?.total, }); // Full analytics data console.log("Analytics:", result.analytics); ``` ### TokenUsage Type The `TokenUsage` type provides detailed token information: ```typescript type TokenUsage = { /** Number of input/prompt tokens */ input: number; /** Number of output/completion tokens */ output: number; /** Total tokens (input + output) */ total: number; /** Tokens used to create cache entries (Anthropic, Google) */ cacheCreationTokens?: number; /** Tokens read from cache (cost savings) */ cacheReadTokens?: number; /** Tokens used for reasoning/thinking (o1, Claude thinking) */ reasoning?: number; /** Percentage of cost saved through caching */ cacheSavingsPercent?: number; }; ``` ### Cache Token Tracking For providers that support prompt caching (Anthropic, Google), NeuroLink tracks cache metrics: ```typescript const result = await neurolink.generate({ input: { text: "Analyze this document..." }, provider: "anthropic", enableAnalytics: true, }); if (result.analytics?.tokenUsage) { const { cacheCreationTokens, cacheReadTokens, cacheSavingsPercent } = result.analytics.tokenUsage; if (cacheCreationTokens) { console.log(`Cache created: ${cacheCreationTokens} tokens`); } if (cacheReadTokens) { console.log(`Cache hit: ${cacheReadTokens} tokens`); console.log(`Cost savings: ${cacheSavingsPercent}%`); } } ``` ### Reasoning Token Tracking For models with extended thinking capabilities (OpenAI o1, Anthropic Claude with thinking, Gemini 3): ```typescript const result = await neurolink.generate({ input: { text: "Solve this complex mathematical proof..." }, provider: "openai", model: "o1-mini", enableAnalytics: true, }); if (result.analytics?.tokenUsage.reasoning) { console.log( `Reasoning tokens used: ${result.analytics.tokenUsage.reasoning}`, ); } ``` ## Cost Analytics ### Automatic Cost Estimation NeuroLink automatically estimates costs based on provider pricing: ```typescript const result = await neurolink.generate({ input: { text: "Write a detailed business plan" }, provider: "openai", model: "gpt-4o", enableAnalytics: true, }); if (result.analytics?.cost !== undefined) { console.log(`Estimated cost: $${result.analytics.cost.toFixed(5)}`); } ``` ### Cost Calculation Formula Costs are calculated using per-token pricing: ```typescript // Internal cost calculation const inputCost = (tokens.input / 1000) * costInfo.input; const outputCost = (tokens.output / 1000) * costInfo.output; const totalCost = inputCost + outputCost; ``` ### Provider Pricing Configuration NeuroLink uses configurable pricing for each provider: | Provider | Default Input Cost (per 1K) | Default Output Cost (per 1K) | | ------------- | --------------------------- | ---------------------------- | | OpenAI | $0.00015 | $0.0006 | | Anthropic | $0.0015 | $0.0075 | | Google AI | $0.000075 | $0.0003 | | Google Vertex | $0.000075 | $0.0003 | | Bedrock | $0.0015 | $0.0075 | | Azure | $0.00015 | $0.0006 | | Mistral | $0.0001 | $0.0003 | | HuggingFace | $0.0002 | $0.0008 | | Ollama | $0 | $0 | ### Custom Cost Configuration Override default pricing via environment variables: ```bash # Custom pricing for Google AI GOOGLE_AI_DEFAULT_INPUT_COST=0.0001 GOOGLE_AI_DEFAULT_OUTPUT_COST=0.0004 # Custom pricing for OpenAI OPENAI_DEFAULT_INPUT_COST=0.0002 OPENAI_DEFAULT_OUTPUT_COST=0.0008 ``` ### Aggregating Costs Track cumulative costs across multiple requests: ```typescript const neurolink = new NeuroLink(); const usages = []; // Collect usage from multiple requests for (const prompt of prompts) { const result = await neurolink.generate({ input: { text: prompt }, enableAnalytics: true, }); if (result.usage) { usages.push(result.usage); } } // Calculate total usage manually const totalUsage = usages.reduce( (total, current) => ({ input: total.input + current.input, output: total.output + current.output, total: total.total + current.total, }), { input: 0, output: 0, total: 0 }, ); console.log(`Total tokens used: ${totalUsage.total}`); ``` ## Performance Metrics ### Response Time Tracking Every request automatically tracks response time: ```typescript const result = await neurolink.generate({ input: { text: "Quick response test" }, enableAnalytics: true, }); console.log(`Response time: ${result.responseTime}ms`); console.log(`Analytics duration: ${result.analytics?.requestDuration}ms`); ``` ### AnalyticsData Structure The complete analytics data structure: ```typescript type AnalyticsData = { /** Provider used for the request */ provider: string; /** Model used for the request */ model?: string; /** Token usage breakdown */ tokenUsage: TokenUsage; /** Request duration in milliseconds */ requestDuration: number; /** ISO timestamp of the request */ timestamp: string; /** Estimated cost in USD */ cost?: number; /** Custom context data */ context?: Record; }; ``` ### Performance Metrics Type For advanced performance tracking: ```typescript type PerformanceMetrics = { /** Start timestamp */ startTime: number; /** End timestamp */ endTime?: number; /** Total duration in ms */ duration?: number; /** Memory usage at start */ memoryStart: NodeJS.MemoryUsage; /** Memory usage at end */ memoryEnd?: NodeJS.MemoryUsage; /** Memory delta */ memoryDelta?: { rss: number; heapTotal: number; heapUsed: number; external: number; }; }; ``` ### Stream Performance Metrics For streaming requests, additional metrics are available: ```typescript type StreamAnalyticsData = { /** Tool execution results with timing */ toolResults?: Promise>; /** Tool calls made during stream */ toolCalls?: Promise>; /** Stream performance metrics */ performance?: { startTime: number; endTime?: number; chunkCount: number; avgChunkSize: number; totalBytes: number; }; /** Provider analytics */ providerAnalytics?: AnalyticsData; }; ``` ### Streaming Example ```typescript const stream = await neurolink.stream({ input: { text: "Write a long story" }, enableAnalytics: true, }); let chunkCount = 0; for await (const chunk of stream.textStream) { chunkCount++; process.stdout.write(chunk); } // Access stream analytics after completion const analytics = await stream.analytics; console.log(`\nChunks received: ${chunkCount}`); console.log(`Total tokens: ${analytics?.tokenUsage?.total}`); ``` ## Quality Evaluation ### Enabling Evaluation NeuroLink can automatically evaluate response quality: ```typescript const result = await neurolink.generate({ input: { text: "Explain machine learning" }, provider: "openai", enableAnalytics: true, enableEvaluation: true, }); if (result.evaluation) { console.log("Evaluation Results:", { relevance: result.evaluation.relevance, accuracy: result.evaluation.accuracy, completeness: result.evaluation.completeness, overall: result.evaluation.overall, reasoning: result.evaluation.reasoning, }); } ``` ### EvaluationData Structure ```typescript type EvaluationData = { // Core scores (1-10 scale) /** How well response addresses query intent */ relevance: number; /** Factual correctness and accuracy */ accuracy: number; /** How completely the response addresses the query */ completeness: number; /** Overall quality score */ overall: number; // Domain-specific scores /** Domain alignment score */ domainAlignment?: number; /** Terminology accuracy */ terminologyAccuracy?: number; /** Tool effectiveness score */ toolEffectiveness?: number; // Quality indicators /** True if response deviates from query/domain */ isOffTopic: boolean; /** Quality alert level: low, medium, high, none */ alertSeverity: "low" | "medium" | "high" | "none"; /** Brief justification for scores */ reasoning: string; /** Suggestions for improvement */ suggestedImprovements?: string; // Metadata /** Model used for evaluation */ evaluationModel: string; /** Time taken for evaluation (ms) */ evaluationTime: number; /** Domain for evaluation */ evaluationDomain?: string; }; ``` ### Domain-Aware Evaluation Configure evaluation for specific domains: ```typescript const result = await neurolink.generate({ input: { text: "What are the side effects of aspirin?" }, provider: "openai", enableEvaluation: true, evaluationDomain: "healthcare", }); if (result.evaluation?.domainEvaluation) { console.log("Domain Evaluation:", { domainRelevance: result.evaluation.domainEvaluation.domainRelevance, terminologyAccuracy: result.evaluation.domainEvaluation.terminologyAccuracy, domainExpertise: result.evaluation.domainEvaluation.domainExpertise, }); } ``` ### Evaluation Providers Evaluation can use different providers: ```typescript type EvaluationProvider = | "openai" | "anthropic" | "vertex" | "google-ai" | "local"; ``` ## Analytics Middleware ### Using Analytics Middleware NeuroLink provides built-in analytics middleware: ```typescript const analyticsMiddleware = createAnalyticsMiddleware(); const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Explain quantum computing in simple terms" }, enableAnalytics: true, middleware: { middleware: [analyticsMiddleware], enabledMiddleware: ["analytics"], }, }); ``` The same two fields attach your own middleware (see Custom Analytics Collection below): registering it with `middleware` does not switch it on, so list its `metadata.id` in `enabledMiddleware` as well. ### Middleware Metadata The analytics middleware provides: ```typescript const metadata = { id: "analytics", name: "Analytics Tracking", description: "Tracks token usage, response times, and model performance metrics", priority: 100, // High priority to ensure capture defaultEnabled: true, }; ``` ### Custom Analytics Collection Implement custom analytics collection: ```typescript function createCustomAnalyticsMiddleware(): NeuroLinkMiddleware { const metrics: Map> = new Map(); return { metadata: { id: "custom-analytics", name: "Custom Analytics", description: "Custom analytics tracking", priority: 90, defaultEnabled: true, }, wrapGenerate: async ({ doGenerate, params }) => { const requestId = `req-${Date.now()}`; const startTime = Date.now(); try { const result = await doGenerate(); const duration = Date.now() - startTime; metrics.set(requestId, { duration, tokens: result.usage, timestamp: new Date().toISOString(), }); return result; } catch (error) { metrics.set(requestId, { error: error instanceof Error ? error.message : String(error), duration: Date.now() - startTime, }); throw error; } }, }; } ``` ## Integration with Observability Tools ### OpenTelemetry Integration Export analytics to OpenTelemetry: ```typescript const tracer = trace.getTracer("my-app"); async function trackedGenerate(options: GenerateOptions) { return tracer.startActiveSpan("tracked-generate", async (span) => { try { const result = await neurolink.generate({ ...options, enableAnalytics: true, }); // Add analytics as span attributes if (result.analytics) { span.setAttributes({ "ai.provider": result.analytics.provider, "ai.model": result.analytics.model || "unknown", "ai.tokens.input": result.analytics.tokenUsage.input, "ai.tokens.output": result.analytics.tokenUsage.output, "ai.tokens.total": result.analytics.tokenUsage.total, "ai.cost": result.analytics.cost || 0, "ai.duration_ms": result.analytics.requestDuration, }); } span.setStatus({ code: SpanStatusCode.OK }); return result; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : String(error), }); throw error; } finally { span.end(); } }); } ``` ### Prometheus Metrics Export metrics to Prometheus: ```typescript // Define metrics const tokenCounter = new Counter({ name: "neurolink_tokens_total", help: "Total tokens used", labelNames: ["provider", "model", "type"], }); const costGauge = new Gauge({ name: "neurolink_cost_dollars", help: "Estimated cost in dollars", labelNames: ["provider", "model"], }); const latencyHistogram = new Histogram({ name: "neurolink_request_duration_ms", help: "Request duration in milliseconds", labelNames: ["provider", "model"], buckets: [100, 250, 500, 1000, 2500, 5000, 10000], }); // Record metrics after each request function recordMetrics(analytics: AnalyticsData) { const labels = { provider: analytics.provider, model: analytics.model || "unknown", }; tokenCounter.inc({ ...labels, type: "input" }, analytics.tokenUsage.input); tokenCounter.inc({ ...labels, type: "output" }, analytics.tokenUsage.output); if (analytics.cost !== undefined) { costGauge.set(labels, analytics.cost); } latencyHistogram.observe(labels, analytics.requestDuration); } ``` ### DataDog Integration Send analytics to DataDog: ```typescript const dogstatsd = new DogStatsDClient(); function sendToDataDog(analytics: AnalyticsData) { const tags = [ `provider:${analytics.provider}`, `model:${analytics.model || "unknown"}`, ]; dogstatsd.increment("neurolink.requests", 1, tags); dogstatsd.gauge("neurolink.tokens.input", analytics.tokenUsage.input, tags); dogstatsd.gauge("neurolink.tokens.output", analytics.tokenUsage.output, tags); dogstatsd.histogram("neurolink.latency", analytics.requestDuration, tags); if (analytics.cost !== undefined) { dogstatsd.gauge("neurolink.cost", analytics.cost, tags); } } ``` ### Custom Logging Structured logging with analytics: ```typescript const logger = pino({ level: "info", formatters: { level: (label) => ({ level: label }), }, }); async function loggedGenerate(options: GenerateOptions) { const result = await neurolink.generate({ ...options, enableAnalytics: true, }); logger.info( { provider: result.analytics?.provider, model: result.analytics?.model, tokens: { input: result.analytics?.tokenUsage.input, output: result.analytics?.tokenUsage.output, total: result.analytics?.tokenUsage.total, }, cost: result.analytics?.cost, duration: result.analytics?.requestDuration, timestamp: result.analytics?.timestamp, }, "AI generation completed", ); return result; } ``` ## Usage Statistics ### Tracking Usage Over Time Build usage dashboards with aggregated statistics: ```typescript type UsageStats = { totalRequests: number; totalTokens: number; totalCost: number; averageLatency: number; byProvider: Map; byModel: Map; }; class UsageTracker { private stats: UsageStats = { totalRequests: 0, totalTokens: 0, totalCost: 0, averageLatency: 0, byProvider: new Map(), byModel: new Map(), }; private latencies: number[] = []; record(analytics: AnalyticsData) { this.stats.totalRequests++; this.stats.totalTokens += analytics.tokenUsage.total; this.stats.totalCost += analytics.cost || 0; this.latencies.push(analytics.requestDuration); this.stats.averageLatency = this.latencies.reduce((a, b) => a + b, 0) / this.latencies.length; // Track by provider const providerStats = this.stats.byProvider.get(analytics.provider) || { requests: 0, tokens: 0, cost: 0, }; providerStats.requests++; providerStats.tokens += analytics.tokenUsage.total; providerStats.cost += analytics.cost || 0; this.stats.byProvider.set(analytics.provider, providerStats); // Track by model if (analytics.model) { const modelStats = this.stats.byModel.get(analytics.model) || { requests: 0, tokens: 0, cost: 0, }; modelStats.requests++; modelStats.tokens += analytics.tokenUsage.total; modelStats.cost += analytics.cost || 0; this.stats.byModel.set(analytics.model, modelStats); } } getStats(): UsageStats { return { ...this.stats }; } getSummary(): string { return ` Total Requests: ${this.stats.totalRequests} Total Tokens: ${this.stats.totalTokens.toLocaleString()} Total Cost: $${this.stats.totalCost.toFixed(4)} Average Latency: ${this.stats.averageLatency.toFixed(0)}ms `; } } ``` ### Rate Limiting Based on Usage Implement rate limiting using analytics: ```typescript class UsageRateLimiter { private tokenBudget: number; private costBudget: number; private usedTokens = 0; private usedCost = 0; private resetInterval: NodeJS.Timeout; constructor( options: { tokenBudget?: number; costBudget?: number; resetIntervalMs?: number; } = {}, ) { this.tokenBudget = options.tokenBudget || 1_000_000; this.costBudget = options.costBudget || 10; // Reset budgets periodically this.resetInterval = setInterval(() => { this.usedTokens = 0; this.usedCost = 0; }, options.resetIntervalMs || 3600000); // 1 hour default } canProceed(estimatedTokens: number): boolean { return this.usedTokens + estimatedTokens COST_ALERT_THRESHOLD) { console.warn( `High cost alert: $${result.analytics.cost.toFixed(4)} for request`, ); } return result; } ``` ### 3. Track Token Efficiency ```typescript function calculateEfficiency(analytics: AnalyticsData): number { // Ratio of output tokens to total tokens const { input, output, total } = analytics.tokenUsage; return total > 0 ? output / total : 0; } ``` ### 4. Implement Budget Controls ```typescript class BudgetController { private dailyBudget: number; private spent = 0; constructor(dailyBudget: number) { this.dailyBudget = dailyBudget; } async generate(options: GenerateOptions): Promise { if (this.spent >= this.dailyBudget) { throw new Error("Daily budget exceeded"); } const result = await neurolink.generate({ ...options, enableAnalytics: true, }); this.spent += result.analytics?.cost || 0; return result; } } ``` ## Related Documentation - [Configuration Reference](/docs/deployment/configuration) - Configure analytics settings - [Provider Comparison](/docs/reference/provider-comparison) - Compare provider costs - [Troubleshooting](/docs/reference/troubleshooting) - Debug analytics issues - [Error Codes](/docs/reference/error-codes) - Analytics-related error codes --- ## Error Code Reference # Error Code Reference This document provides a comprehensive reference for all NeuroLink error codes, including their categories, severity levels, retriability status, and resolution guidance. ## Overview NeuroLink uses a structured error handling system that provides detailed information about failures. Each error includes: | Property | Description | | ----------- | ------------------------------------------------------- | | `code` | Unique identifier for the error type | | `category` | Classification of the error (validation, network, etc.) | | `severity` | Impact level (critical, high, medium, low) | | `retriable` | Whether the operation can be automatically retried | | `message` | Human-readable description of the error | | `context` | Additional metadata about the error circumstances | | `timestamp` | When the error occurred | ## Error Categories NeuroLink classifies errors into the following categories: | Category | Description | Common Causes | | --------------- | ----------------------------------- | -------------------------------------------------------- | | `VALIDATION` | Invalid parameters or configuration | Malformed input, missing required fields, invalid values | | `EXECUTION` | Runtime execution failures | Tool execution errors, provider API failures | | `NETWORK` | Connectivity issues | DNS failures, connection timeouts, SSL errors | | `RESOURCE` | Memory or quota exhaustion | Out of memory, rate limits exceeded | | `TIMEOUT` | Operation timeouts | Slow provider response, long-running operations | | `PERMISSION` | Authorization issues | Invalid API keys, insufficient permissions | | `CONFIGURATION` | Configuration errors | Missing environment variables, invalid config | | `SYSTEM` | System-level failures | Internal errors, unexpected states | ## Severity Levels Errors are classified by severity to help prioritize response: | Severity | Description | Action Required | | ---------- | -------------------------------------------------- | ----------------------------------------- | | `CRITICAL` | System-level failure requiring immediate attention | Stop operation, investigate immediately | | `HIGH` | Operation failed, significant impact | Retry if possible, escalate if persistent | | `MEDIUM` | Validation or recoverable issues | Review parameters, fix and retry | | `LOW` | Minor issues, informational | Log for monitoring, continue operation | ## Tool Errors Errors related to tool registration, discovery, and execution. | Code | Description | Severity | Retriable | Category | | ------------------------ | ------------------------------------ | -------- | --------- | ---------- | | `TOOL_NOT_FOUND` | Requested tool not found in registry | MEDIUM | No | VALIDATION | | `TOOL_EXECUTION_FAILED` | Tool execution encountered an error | HIGH | Yes | EXECUTION | | `TOOL_TIMEOUT` | Tool execution timed out | HIGH | Yes | TIMEOUT | | `TOOL_VALIDATION_FAILED` | Tool parameter validation failed | MEDIUM | No | VALIDATION | ### Resolution Guide **TOOL_NOT_FOUND** ```typescript // Check available tools before calling const tools = await neurolink.getAllAvailableTools(); console.log( "Available tools:", tools.map((t) => t.name), ); // Verify tool registration neurolink.registerTool("myTool", { description: "My custom tool", parameters: z.object({ /* schema */ }), execute: async (params) => { /* implementation */ }, }); ``` **TOOL_EXECUTION_FAILED** ```typescript // Check tool parameters match expected schema // Review tool implementation for errors // Verify external dependencies (APIs, databases) are available ``` **TOOL_TIMEOUT** ```typescript // Increase timeout configuration const result = await neurolink.generate({ input: { text: "Use the slow tool" }, toolTimeout: 60000, // 60 seconds }); ``` ## Provider Errors Errors related to AI provider communication and authentication. | Code | Description | Severity | Retriable | Category | | ------------------------- | ------------------------------------- | -------- | --------- | ---------- | | `PROVIDER_NOT_AVAILABLE` | Provider service unavailable | HIGH | Yes | NETWORK | | `PROVIDER_AUTH_FAILED` | Provider authentication failed | HIGH | No | PERMISSION | | `PROVIDER_QUOTA_EXCEEDED` | Provider rate limit or quota exceeded | HIGH | Yes | RESOURCE | ### Resolution Guide **PROVIDER_NOT_AVAILABLE** ```typescript // Configure automatic failover const neurolink = new NeuroLink({ provider: "openai", fallbackProviders: ["anthropic", "google-ai"], }); // Or name the provider on the call itself await neurolink.generate({ input: { text: "Hello" }, provider: "anthropic", }); ``` **PROVIDER_AUTH_FAILED** ```typescript // Verify API key is set correctly process.env.OPENAI_API_KEY = "sk-..."; // Check API key permissions and validity // Ensure correct environment variables for your provider ``` **PROVIDER_QUOTA_EXCEEDED** ```typescript // Implement exponential backoff const result = await withRetry( () => neurolink.generate({ input: { text: "Hello" } }), { maxAttempts: 3, delayMs: 1000 }, ); ``` ## Video Validation Errors Errors specific to video generation operations. | Code | Description | Severity | Retriable | Category | | ---------------------------- | ----------------------------- | -------- | --------- | ---------- | | `INVALID_VIDEO_RESOLUTION` | Invalid resolution specified | MEDIUM | No | VALIDATION | | `INVALID_VIDEO_LENGTH` | Invalid video duration | MEDIUM | No | VALIDATION | | `INVALID_VIDEO_ASPECT_RATIO` | Invalid aspect ratio | MEDIUM | No | VALIDATION | | `INVALID_VIDEO_AUDIO` | Invalid audio option | MEDIUM | No | VALIDATION | | `INVALID_VIDEO_MODE` | Output mode not set to video | MEDIUM | No | VALIDATION | | `MISSING_VIDEO_IMAGE` | Required input image missing | MEDIUM | No | VALIDATION | | `EMPTY_VIDEO_PROMPT` | Video prompt cannot be empty | MEDIUM | No | VALIDATION | | `VIDEO_PROMPT_TOO_LONG` | Prompt exceeds maximum length | MEDIUM | No | VALIDATION | ### Resolution Guide **INVALID_VIDEO_RESOLUTION** ```typescript // Valid resolutions: '720p' or '1080p' const result = await neurolink.generate({ input: { text: "Camera pan", images: [imageBuffer] }, output: { mode: "video", video: { resolution: "720p" }, // or '1080p' }, }); ``` **INVALID_VIDEO_LENGTH** ```typescript // Valid lengths: 4, 6, or 8 seconds const result = await neurolink.generate({ input: { text: "Smooth motion", images: [imageBuffer] }, output: { mode: "video", video: { length: 6 }, // 4, 6, or 8 }, }); ``` **INVALID_VIDEO_ASPECT_RATIO** ```typescript // Valid aspect ratios: '9:16' (portrait) or '16:9' (landscape) const result = await neurolink.generate({ input: { text: "Cinematic shot", images: [imageBuffer] }, output: { mode: "video", video: { aspectRatio: "16:9" }, }, }); ``` **MISSING_VIDEO_IMAGE** ```typescript // Video generation requires an input image const imageBuffer = readFileSync("./input.png"); const result = await neurolink.generate({ input: { text: "Animate this image with smooth motion", images: [imageBuffer], }, output: { mode: "video" }, }); ``` ## Image Validation Errors Errors specific to image input processing. | Code | Description | Severity | Retriable | Category | | ---------------------- | ---------------------------------- | -------- | --------- | ---------- | | `EMPTY_IMAGE_PATH` | Image path or URL is empty | MEDIUM | No | VALIDATION | | `INVALID_IMAGE_TYPE` | Image must be Buffer, path, or URL | MEDIUM | No | VALIDATION | | `IMAGE_TOO_LARGE` | Image exceeds maximum size | MEDIUM | No | VALIDATION | | `IMAGE_TOO_SMALL` | Image data too small to be valid | MEDIUM | No | VALIDATION | | `INVALID_IMAGE_FORMAT` | Unsupported image format | MEDIUM | No | VALIDATION | ### Resolution Guide **IMAGE_TOO_LARGE** ```typescript // Compress or resize images before sending const compressedImage = await sharp(originalImage) .resize(1920, 1080, { fit: "inside" }) .jpeg({ quality: 80 }) .toBuffer(); ``` **INVALID_IMAGE_FORMAT** ```typescript // Supported formats: JPEG, PNG, WebP // Convert unsupported formats before processing const jpegBuffer = await sharp(bmpImage).jpeg().toBuffer(); ``` ## System and Configuration Errors General system and configuration errors. | Code | Description | Severity | Retriable | Category | | ------------------------ | ------------------------------- | -------- | --------- | ------------- | | `MEMORY_EXHAUSTED` | System memory exhausted | CRITICAL | No | RESOURCE | | `NETWORK_ERROR` | Network connectivity issue | HIGH | Yes | NETWORK | | `PERMISSION_DENIED` | Operation not permitted | HIGH | No | PERMISSION | | `INVALID_CONFIGURATION` | Configuration is invalid | MEDIUM | No | CONFIGURATION | | `MISSING_CONFIGURATION` | Required configuration missing | MEDIUM | No | CONFIGURATION | | `INVALID_PARAMETERS` | Parameters failed validation | MEDIUM | No | VALIDATION | | `MISSING_REQUIRED_PARAM` | Required parameter not provided | MEDIUM | No | VALIDATION | ### Resolution Guide **MEMORY_EXHAUSTED** ```typescript // Process large files in chunks // Increase Node.js heap size: node --max-old-space-size=4096 // Use streaming for large responses ``` **MISSING_CONFIGURATION** ```typescript // Verify all required environment variables are set // Required variables depend on your provider: // - OPENAI_API_KEY for OpenAI // - ANTHROPIC_API_KEY for Anthropic // - GOOGLE_API_KEY for Google AI Studio // - GOOGLE_APPLICATION_CREDENTIALS for Vertex AI // Validate configuration await validateConfig(); ``` ## Video Generation Runtime Errors Runtime errors during video generation (as opposed to validation errors). | Code | Description | Severity | Retriable | Category | | ------------------------------- | ----------------------------------------- | -------- | --------- | ------------- | | `VIDEO_GENERATION_FAILED` | Video generation API call failed | HIGH | Yes | EXECUTION | | `VIDEO_PROVIDER_NOT_CONFIGURED` | Vertex AI not properly configured | HIGH | No | CONFIGURATION | | `VIDEO_POLL_TIMEOUT` | Polling for video completion timed out | HIGH | Yes | TIMEOUT | | `VIDEO_INVALID_INPUT` | Runtime I/O error during input processing | HIGH | Yes | EXECUTION | ### Resolution Guide **VIDEO_PROVIDER_NOT_CONFIGURED** ```bash # Set Google Cloud credentials for Vertex AI video generation export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json export GOOGLE_VERTEX_PROJECT=your-project-id export GOOGLE_VERTEX_LOCATION=us-central1 ``` **VIDEO_POLL_TIMEOUT** ```typescript // Video generation typically takes 1-3 minutes // Consider using shorter duration or lower resolution for faster results const result = await neurolink.generate({ input: { text: "Quick animation", images: [imageBuffer] }, output: { mode: "video", video: { resolution: "720p", // Lower resolution is faster length: 4, // Shorter duration is faster }, }, }); ``` ## PPT Validation Errors Errors specific to PPT (PowerPoint) generation validation. | Code | Description | Severity | Retriable | Category | | ---------------------- | --------------------------------- | -------- | --------- | ---------- | | `INVALID_PPT_PAGES` | Invalid page count (must be 5-50) | MEDIUM | No | VALIDATION | | `INVALID_PPT_THEME` | Invalid theme specified | MEDIUM | No | VALIDATION | | `INVALID_PPT_AUDIENCE` | Invalid audience type | MEDIUM | No | VALIDATION | | `INVALID_PPT_TONE` | Invalid tone specified | MEDIUM | No | VALIDATION | | `INVALID_PPT_ASPECT` | Invalid aspect ratio | MEDIUM | No | VALIDATION | | `INVALID_PPT_FORMAT` | Invalid output format | MEDIUM | No | VALIDATION | | `INVALID_PPT_MODE` | Output mode not set to ppt | MEDIUM | No | VALIDATION | | `EMPTY_PPT_PROMPT` | Prompt cannot be empty | MEDIUM | No | VALIDATION | | `PPT_PROMPT_TOO_SHORT` | Prompt must be at least 10 chars | MEDIUM | No | VALIDATION | | `PPT_PROMPT_TOO_LONG` | Prompt exceeds 1000 characters | MEDIUM | No | VALIDATION | ### Resolution Guide **INVALID_PPT_PAGES** ```typescript // Valid page count: 5-50 slides const result = await neurolink.generate({ input: { text: "Company presentation" }, output: { mode: "ppt", ppt: { pages: 10 }, // Must be between 5 and 50 }, }); ``` **INVALID_PPT_THEME** ```typescript // Valid themes: 'modern', 'corporate', 'creative', 'minimal', 'dark' const result = await neurolink.generate({ input: { text: "Product launch" }, output: { mode: "ppt", ppt: { pages: 12, theme: "corporate", // Valid theme name }, }, }); ``` **INVALID_PPT_AUDIENCE** ```typescript // Valid audiences: 'business', 'students', 'technical', 'general' const result = await neurolink.generate({ input: { text: "Technical architecture overview" }, output: { mode: "ppt", ppt: { pages: 15, audience: "technical", // Valid audience type }, }, }); ``` ## PPT Generation Runtime Errors Runtime errors during PPT generation (as opposed to validation errors). | Code | Description | Severity | Retriable | Category | | ----------------------------- | -------------------------------- | -------- | --------- | ---------- | | `PPT_PLANNING_FAILED` | AI content planning failed | HIGH | Yes | EXECUTION | | `PPT_INVALID_AI_RESPONSE` | AI returned malformed slide data | HIGH | Yes | EXECUTION | | `PPT_IMAGE_GENERATION_FAILED` | AI image generation failed | MEDIUM | Yes | EXECUTION | | `PPT_ASSEMBLY_FAILED` | PPTX file assembly failed | HIGH | No | EXECUTION | | `PPT_FILE_WRITE_FAILED` | Could not write file to disk | HIGH | No | RESOURCE | | `PPT_TIMEOUT` | Generation exceeded timeout | HIGH | Yes | TIMEOUT | | `PPT_INVALID_INPUT` | Invalid input during runtime | HIGH | No | VALIDATION | ### Resolution Guide **PPT_PLANNING_FAILED** ```typescript // Use a more specific prompt or try a different model const result = await neurolink.generate({ input: { text: `Quarterly Sales Report: - Revenue growth 23% YoY - 450 new customers - Top 3 products by region - 2026 targets and roadmap`, }, provider: "anthropic", model: "claude-3.5-sonnet", // Try advanced model output: { mode: "ppt", ppt: { pages: 15, theme: "corporate" }, }, }); ``` **PPT_IMAGE_GENERATION_FAILED** ```typescript // Disable AI image generation if it fails const result = await neurolink.generate({ input: { text: "Technical architecture" }, output: { mode: "ppt", ppt: { pages: 10, generateAIImages: false, // Disable AI images }, }, }); ``` **PPT_TIMEOUT** ```typescript // Reduce slides or disable images for faster generation const result = await neurolink.generate({ input: { text: "Quick summary presentation" }, output: { mode: "ppt", ppt: { pages: 5, // Fewer slides generateAIImages: false, // No AI images }, }, timeout: 300, // 5 minute timeout }); ``` ## SDK Error Handling Example Complete example demonstrating proper error handling in the SDK: ```typescript NeuroLink, NeuroLinkError, ErrorCategory, withRetry, } from "@juspay/neurolink"; const neurolink = new NeuroLink({ provider: "openai" }); async function safeGenerate(prompt: string) { try { const result = await neurolink.generate({ input: { text: prompt }, }); return result; } catch (error) { if (error instanceof NeuroLinkError) { // Access structured error information console.error(`Error Code: ${error.code}`); console.error(`Category: ${error.category}`); console.error(`Severity: ${error.severity}`); console.error(`Retriable: ${error.retriable}`); console.error(`Message: ${error.message}`); console.error(`Context:`, error.context); // Handle by category switch (error.category) { case ErrorCategory.VALIDATION: console.error("Fix input parameters and retry"); break; case ErrorCategory.NETWORK: if (error.retriable) { console.error("Network issue - retrying..."); return withRetry( () => neurolink.generate({ input: { text: prompt } }), { maxAttempts: 3, delayMs: 2000 }, ); } break; case ErrorCategory.PERMISSION: console.error("Check API key and permissions"); break; case ErrorCategory.RESOURCE: console.error("Rate limited - waiting before retry"); await new Promise((resolve) => setTimeout(resolve, 5000)); return safeGenerate(prompt); default: console.error("Unexpected error"); } // Log error in JSON format for structured logging console.error("Structured error:", error.toJSON()); } throw error; } } ``` ## CLI Debugging The CLI provides several options for debugging errors: ### Enable Debug Mode ```bash # Run with debug output neurolink generate "test prompt" --debug # Show verbose output neurolink status --verbose # Validate configuration neurolink config validate # Check provider status neurolink provider status openai ``` ### Environment Validation ```bash # Validate all environment variables pnpm run env:validate # Check specific provider configuration neurolink config check --provider openai ``` ### Debug Logging ```typescript // Enable debug logging in SDK setLogLevel("debug"); // Or via environment variable process.env.NEUROLINK_LOG_LEVEL = "debug"; ``` ## Retry Utilities NeuroLink provides built-in utilities for handling retriable errors: ### withRetry ```typescript const result = await withRetry( () => neurolink.generate({ input: { text: "Hello" } }), { maxAttempts: 3, delayMs: 1000, isRetriable: isRetriableError, onRetry: (attempt, error) => { console.log(`Retry ${attempt}: ${error.message}`); }, }, ); ``` ### withTimeout ```typescript const result = await withTimeout( neurolink.generate({ input: { text: "Hello" } }), 30000, // 30 second timeout new Error("Generation timed out"), ); ``` ### Circuit Breaker ```typescript const breaker = new CircuitBreaker(5, 60000); // 5 failures, 60s reset const result = await breaker.execute(() => neurolink.generate({ input: { text: "Hello" } }), ); // Check circuit state console.log("Circuit state:", breaker.getState()); // closed, open, half-open console.log("Failure count:", breaker.getFailureCount()); ``` ## Provider-Specific Error Codes Some providers have additional error codes: ### SageMaker Errors | Code | Description | HTTP Status | Retriable | | --------------------- | ------------------------------- | ----------- | --------- | | `VALIDATION_ERROR` | Request validation failed | 400 | No | | `MODEL_ERROR` | Model execution error | 500 | No | | `INTERNAL_ERROR` | Internal service error | 500 | Yes | | `SERVICE_UNAVAILABLE` | Service temporarily unavailable | 503 | Yes | | `THROTTLING_ERROR` | Rate limit exceeded | 429 | Yes | | `CREDENTIALS_ERROR` | AWS credentials invalid | 401 | No | | `NETWORK_ERROR` | Network connectivity issue | - | Yes | | `ENDPOINT_NOT_FOUND` | SageMaker endpoint not found | 404 | No | | `UNKNOWN_ERROR` | Unclassified error | 500 | No | ### Voice Errors (STT / TTS / Realtime) STT and Realtime error codes are surfaced via the `STTError` and `RealtimeError` classes, which extend the shared `VoiceError` base. TTS error codes are exposed via the `TTS_ERROR_CODES` enum and surfaced via the `TTSError` class, which extends `NeuroLinkError` directly rather than `VoiceError` (see [TTS / Realtime Errors](#tts--realtime-errors) below). #### STT Error Codes | Code | Description | Retriable | | ----------------------------- | ---------------------------------------------------------------------------------------- | --------- | | `STT_AUDIO_EMPTY` | Empty audio buffer submitted for transcription | No | | `STT_AUDIO_TOO_LONG` | Audio buffer exceeds `maxAudioBytes` (default 25MB) | No | | `STT_INVALID_AUDIO_FORMAT` | Provider doesn't decode the requested audio format. Common trigger: `azure-stt` + `mp3`. | No | | `STT_LANGUAGE_NOT_SUPPORTED` | Requested language not supported by the provider | No | | `STT_TRANSCRIPTION_FAILED` | Transcription failed at the provider | Sometimes | | `STT_PROVIDER_NOT_CONFIGURED` | Required env vars / credentials not set | No | | `STT_PROVIDER_NOT_SUPPORTED` | No handler registered for the requested provider id | No | | `STT_STREAM_ERROR` | Streaming transcription failed mid-stream | Yes | | `STT_STREAMING_NOT_SUPPORTED` | Provider doesn't support streaming transcription | No | #### TTS / Realtime Errors `TTSError` and `RealtimeError` carry provider-specific messages (e.g. synthesis failure, WebSocket disconnect, function-call failure). Inspect `error.cause` for the underlying provider error. #### Common Triggers - **`STT_INVALID_AUDIO_FORMAT`** is thrown by `STTProcessor.transcribe()` when `options.format` doesn't appear in the provider's `getSupportedFormats()` list. The CLI infers the format from the `--input-audio` file extension; the SDK requires you to pass it explicitly. Fix: either convert the audio to a supported format, or use a different STT provider. See `docs/getting-started/providers/azure-speech.md` for the Azure-MP3 case. - **`STT_AUDIO_TOO_LONG`** is thrown when the buffer exceeds the per-call `maxAudioBytes` limit. Default is 25 MB (matches Whisper's documented ceiling). Override via `stt.maxAudioBytes`. ## Related Documentation - [Troubleshooting Guide](/docs/reference/troubleshooting) - Common issues and solutions - [Configuration Reference](/docs/deployment/configuration) - Environment variables and settings - [FAQ](/docs/reference/faq) - Frequently asked questions - [Provider Feature Compatibility](/docs/reference/provider-feature-compatibility) - Provider capabilities matrix --- ## Provider Behavior Guide # Provider Behavior Guide This guide documents provider-specific behaviors, quirks, and recommended usage patterns for optimal results with NeuroLink AI providers. ## Quick Navigation - [Provider-Specific Behaviors](#provider-specific-input-handling) - [Testing Recommendations](#testing-recommendations) - [Factory Pattern Integration](#factory-pattern-integration) - [Troubleshooting](#troubleshooting-common-issues) - [Best Practices](#best-practices) ## Related Documentation - [API Reference](/docs/sdk/api-reference) - Complete API documentation - [CLI Guide](/docs/cli) - Command-line interface usage - [Factory Pattern Migration](/docs/development/factory-migration) - Factory pattern implementation - [Streaming Guide](/docs/advanced/streaming) - Advanced streaming features ## Provider-Specific Input Handling ### Google AI Studio & Vertex AI **Behavior**: Exhibits inconsistent behavior with certain input patterns containing domain keywords. **Affected Inputs**: - Inputs containing keywords like "analytics", "healthcare", "streaming" may return empty responses - Domain-specific terminology can trigger unexpected filtering - This affects both basic streaming AND factory-enhanced streaming equally **Recommended Inputs**: - ✅ "Hello world", "Count from 1 to 5", "Say hello", "Tell me a joke" - ✅ "Write a story", "Explain concepts", "Generate code" - ✅ Generic prompts without domain-specific keywords **Avoid**: - ⚠️ "Test analytics", "healthcare data", "streaming analysis" - ⚠️ Industry-specific jargon in simple test cases - ⚠️ Technical domain terms in basic functionality tests **Workaround**: Use provider-friendly inputs for testing, or switch to alternative providers (OpenAI, Anthropic) for domain-specific content. ### OpenAI (GPT-4, GPT-3.5) **Behavior**: Generally reliable with consistent responses across all input types. **Strengths**: - Handles domain-specific content well - Consistent streaming performance - Good with technical terminology **Considerations**: - Rate limiting may apply based on plan - Longer response times for complex prompts - Higher cost per token compared to some alternatives ### Anthropic Claude **Behavior**: Excellent reasoning capabilities with consistent responses. **Strengths**: - Superior handling of complex, domain-specific content - Reliable streaming with consistent chunk sizes - Good with analytical and healthcare content **Considerations**: - May be more verbose than other providers - Higher token usage for equivalent outputs - Strong safety filtering for sensitive content ### Amazon Bedrock **Behavior**: Enterprise-grade reliability with consistent performance. **Strengths**: - Excellent for production workloads - Consistent behavior across model versions - Good integration with AWS ecosystem **Considerations**: - Requires AWS credentials and proper IAM setup - May have higher latency due to enterprise security layers - Regional availability varies ### Azure OpenAI **Behavior**: Similar to OpenAI with enterprise features. **Strengths**: - Enterprise compliance and security - Consistent with OpenAI behavior patterns - Good integration with Microsoft ecosystem **Considerations**: - Requires Azure setup and endpoint configuration - May have different rate limits than direct OpenAI - Additional latency due to Azure proxy layer ### Ollama (Local Models) **Behavior**: Varies significantly by model, generally more limited tool support. **Strengths**: - Complete privacy (local processing) - No API costs or rate limits - Full control over model versions **Considerations**: - Limited tool execution capabilities - Performance depends on local hardware - Model selection affects behavior significantly - May require specific models (e.g., gemma3n) for tool support ### Hugging Face **Behavior**: Highly variable depending on model selection. **Strengths**: - Access to thousands of open-source models - Free tier available - Good for experimentation **Considerations**: - Model quality varies significantly - Tools may be visible but not execute properly - Response format inconsistencies - Cold start delays for less popular models ### Mistral AI **Behavior**: Good balance of performance and European compliance. **Strengths**: - GDPR compliant (European provider) - Good reasoning capabilities - Consistent tool execution **Considerations**: - Smaller context windows than some competitors - Limited model variety compared to OpenAI/Anthropic - Newer provider with evolving capabilities ## Testing Recommendations ### For Automated Tests 1. **Use Provider-Neutral Inputs**: Choose prompts that work consistently across all providers - See [CLI Guide](/docs/cli) for example commands 2. **Avoid Domain Keywords**: Use generic prompts for functionality testing - Reference [Factory Pattern Migration](/docs/development/factory-migration) for domain-specific usage 3. **Test Provider-Specific Features**: Separate tests for provider-specific capabilities - Check [API Reference](/docs/sdk/api-reference) for provider options 4. **Implement Fallback Strategies**: Design tests to handle provider variations gracefully - See [Streaming Guide](/docs/advanced/streaming) for robust patterns ### For Development 1. **Provider Selection**: Choose appropriate provider based on use case requirements - Reference [Provider Selection Guidelines](#provider-selection-guidelines) below 2. **Input Validation**: Pre-validate inputs for provider compatibility - Use patterns from [Factory Pattern Integration](#factory-pattern-integration) section 3. **Error Handling**: Implement robust error handling for provider-specific failures - See [Troubleshooting](#troubleshooting-common-issues) section for common patterns 4. **Performance Monitoring**: Track provider performance and adjust accordingly - Reference [API Reference](/docs/sdk/api-reference) for monitoring setup ## Provider Selection Guidelines ### For Production Applications - **High Reliability**: OpenAI, Anthropic, Azure OpenAI - **Enterprise Compliance**: Amazon Bedrock, Azure OpenAI - **Cost Optimization**: Google AI Studio, Mistral AI - **Privacy Requirements**: Ollama (local) - **European Compliance**: Mistral AI ### For Development & Testing - **General Development**: OpenAI, Google AI Studio - **Domain-Specific Testing**: Anthropic, OpenAI - **Tool Integration Testing**: OpenAI, Anthropic, Google AI Studio - **Streaming Testing**: Any provider except Ollama (limited) ## Troubleshooting Common Issues ### Empty Responses **Symptoms**: Provider returns empty or minimal content **Likely Causes**: Input contains filtered keywords, provider-specific limitations **Solutions**: - Try alternative provider from [Provider Selection Guidelines](#provider-selection-guidelines) - Rephrase input using [Testing Recommendations](#testing-recommendations) patterns - Check provider status using [CLI Guide](/docs/cli) ### Inconsistent Tool Execution **Symptoms**: Tools work sometimes but not others **Likely Causes**: Provider-specific tool support limitations **Solutions**: - Use providers with full tool support (OpenAI, Anthropic, Google AI) - Configure tools using [CLI Guide](/docs/cli) - Debug with [API Reference](/docs/sdk/api-reference) ### Streaming Interruptions **Symptoms**: Streaming stops mid-response **Likely Causes**: Provider rate limits, network issues, input filtering **Solutions**: - Implement retry logic from [Streaming Guide](/docs/advanced/streaming) - Check provider status and validate inputs - Use error handling patterns from [Streaming Guide](/docs/advanced/streaming) ### Performance Variations **Symptoms**: Significant response time differences **Likely Causes**: Provider load, geographic location, model selection **Solutions**: - Implement provider rotation using [API Reference](/docs/sdk/api-reference) - Monitor performance metrics with [Analytics Integration](/docs/sdk/api-reference) - Optimize based on [Provider Selection Guidelines](#provider-selection-guidelines) ## Factory Pattern Integration When using NeuroLink's factory patterns with specific providers: ### Domain Configuration - **Provider Sensitivity**: Some providers may filter domain-specific keywords - **Configuration Guide**: See [Factory Pattern Migration](/docs/development/factory-migration) for setup - **Testing Strategies**: Reference [Testing Recommendations](#testing-recommendations) above ### Context Processing - **Validation**: Ensure context data compatibility across providers - **Implementation**: Follow patterns in [Factory Pattern Migration](/docs/development/factory-migration) - **Debugging**: Use [API Reference](/docs/sdk/api-reference) for validation tools ### Evaluation Integration - **Provider Variation**: Different providers may have varying evaluation accuracy - **Setup Guide**: See [API Reference](/docs/sdk/api-reference) for configuration - **Best Practices**: Reference [Factory Pattern Migration](/docs/development/factory-migration) ### Tool Integration - **Compatibility Testing**: Test tool execution with each target provider - **Configuration**: Use [CLI Guide](/docs/cli) for MCP tool setup - **Advanced Usage**: See [Streaming Guide](/docs/advanced/streaming) for streaming with tools ## Best Practices ### General Guidelines 1. **Provider Rotation**: Use multiple providers for resilience - Implementation guide: [API Reference](/docs/sdk/api-reference) 2. **Input Validation**: Validate inputs for provider compatibility - See provider-specific sections above for validation patterns 3. **Error Handling**: Implement graceful fallbacks - Follow [Streaming Guide](/docs/advanced/streaming) patterns 4. **Performance Monitoring**: Track provider metrics - Setup: [API Reference](/docs/sdk/api-reference) 5. **Cost Management**: Monitor token usage across providers - Tools: [CLI Guide](/docs/cli) 6. **Testing Strategy**: Use provider-appropriate test cases - Reference [Testing Recommendations](#testing-recommendations) above ### Performance Optimization - **Caching**: Implement response caching for repeated requests - **Batch Processing**: Use batch operations where supported - **Provider Selection**: Choose optimal providers per use case - **Input Optimization**: Format inputs for best provider performance ## See Also - [API Reference](/docs/sdk/api-reference) - Complete API documentation and configuration - [CLI Guide](/docs/cli) - Command-line interface and provider testing - [Factory Pattern Migration](/docs/development/factory-migration) - Advanced factory pattern usage - [Streaming Guide](/docs/advanced/streaming) - Streaming functionality and error handling - [Main Documentation](/docs/) - Getting started guide and overview --- _This guide is maintained as part of the NeuroLink provider ecosystem. For updates or provider-specific issues, please refer to the individual provider documentation or submit an issue in the [project repository](https://github.com/juspay/neurolink)._ --- ## Provider Capabilities Audit # Provider Capabilities Audit Capability audit for the **13 text/multimodal AI providers** historically tracked in this matrix. NeuroLink ships many provider integrations — the additional providers added since this audit was first written (DeepSeek, NVIDIA NIM, LM Studio, llama.cpp, xAI, Groq, Cerebras, SambaNova, Together AI, Fireworks, Perplexity, Cloudflare, Cohere, TypeSafe Jev, and more), the voice providers (OpenAI TTS, ElevenLabs, Deepgram, Azure Speech, Whisper, OpenAI Realtime, Gemini Live), and the embedding/media-only providers are documented in the per-provider docs under [/docs/getting-started/providers/](https://github.com/juspay/neurolink/tree/main/docs/getting-started/providers) and the [Voice Features](https://github.com/juspay/neurolink/blob/main/docs/features/index.md#voice) index, not in this capability matrix. For the canonical product surface, see the [README](https://github.com/juspay/neurolink/blob/main/README.md). **Last Updated:** May 2026 **NeuroLink Version:** 9.62.0 -------------- | -------- | --------- | ----- | ------ | --- | -------- | ----------------- | ------------------ | | OpenAI | ✓ | ✓ | ✓ | ✓ | ✗ | ✗ | ✓ | API Key | | Anthropic | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | API Key | | Google AI Studio | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ⚠️ | API Key | | Google Vertex | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ⚠️ | Service Account | | Amazon Bedrock | ✓ | ✓ | ✓ | ⚠️ | ✓ | ✗ | ✓ | AWS Credentials | | Amazon SageMaker | ✓ | ⚠️ | ✓ | ✗ | ✗ | ✗ | ✗ | AWS Credentials | | Azure OpenAI | ✓ | ✓ | ✓ | ✓ | ✗ | ✗ | ✓ | API Key + Endpoint | | Mistral | ✓ | ✓ | ✓ | ⚠️ | ✗ | ✗ | ✓ | API Key | | HuggingFace | ✓ | ✓ | ⚠️ | ✗ | ✗ | ✗ | ✗ | API Key | | LiteLLM | ✓ | ✓ | ✓ | ⚠️ | ✗ | ✗ | ✓ | Custom | | Ollama | ✓ | ✓ | ✓ | ⚠️ | ✗ | ✗ | ✗ | None | | OpenAI Compatible | ✓ | ✓ | ✓ | ⚠️ | ✗ | ✗ | ✓ | Custom | | OpenRouter | ✓ | ✓ | ⚠️ | ⚠️ | ✗ | ✗ | ✓ | API Key | **Legend:** - ✓ Full Support - ⚠️ Partial/Model-Dependent Support - ✗ Not Supported --- ## 1. OpenAI Provider **File:** `src/lib/providers/openAI.ts` **Provider Name:** `openai` **Default Model:** `gpt-4o` ### Capabilities #### Text Generation ✓ - Full support for all GPT models - Supports temperature, maxTokens, top_p parameters - Multi-turn conversations #### Streaming ✓ - Real-time token streaming via Server-Sent Events (SSE) - Chunk-by-chunk response delivery - Full analytics support #### Tool Calling ✓ - Native function calling support - Automatic tool execution - Multi-step tool workflows - Tool choice: auto, required, none #### Vision/Multimodal ✓ **Supported Models:** - GPT-5.2 series (gpt-5.2, gpt-5.2-pro) - Latest flagship - GPT-5 series (gpt-5, gpt-5-pro, gpt-5-mini, gpt-5-nano) - GPT-4.1 series (gpt-4.1, gpt-4.1-mini, gpt-4.1-nano) - O-series reasoning models (o3, o3-mini, o3-pro, o4, o4-mini) - GPT-4o, GPT-4o-mini, GPT-4-turbo, GPT-4-vision-preview **Image Support:** - Up to 10 images per request - Formats: PNG, JPEG, WEBP, GIF - Base64 and URL input #### PDF Processing ✗ - Not natively supported - Requires external preprocessing #### Extended Thinking ✗ - Standard reasoning only - No extended thinking capability #### Structured Output ✓ - JSON schema validation - Type-safe responses via Zod - Response format enforcement ### Configuration ```bash # Required OPENAI_API_KEY=sk-... # Optional OPENAI_MODEL=gpt-4o OPENAI_BASE_URL=https://api.openai.com/v1 # For proxy/custom endpoints ``` ### Known Limitations - PDF files require preprocessing to text/images - No native extended thinking mode - Rate limits apply per API key tier - Context window varies by model (128K for GPT-4o) --- ## 2. Anthropic Provider **File:** `src/lib/providers/anthropic.ts` **Provider Name:** `anthropic` **Default Model:** `claude-sonnet-4-5-20250929` ### Capabilities #### Text Generation ✓ - All Claude models (3.x, 4.x, 4.5) - Advanced reasoning capabilities - Long context support (200K tokens) #### Streaming ✓ - Real-time streaming with SSE - Tool execution during streaming - Analytics tracking #### Tool Calling ✓ - Native tool use support - Multi-step agentic workflows - Tool result caching - Parallel tool execution #### Vision/Multimodal ✓ **Supported Models:** - Claude 4.5 series (Sonnet, Opus, Haiku) - Claude 4.1 and 4.0 series - Claude 3.7 series - Claude 3.5 series - Claude 3 series (Opus, Sonnet, Haiku) **Image Support:** - Up to 20 images per request - Formats: PNG, JPEG, WEBP, GIF - Base64 encoding required #### PDF Processing ✓ - Native PDF document understanding - No preprocessing required - Extract text, tables, and structure - Visual analysis of PDF pages #### Extended Thinking ✓ **Supported Models:** - Claude 4.5 Sonnet (latest) - Claude 4.5 Opus - Claude 4.1 Opus - Claude 3.7 Sonnet **Thinking Levels:** - `minimal` - Fast responses - `low` - Basic reasoning - `medium` - Moderate reasoning (default) - `high` - Deep reasoning and analysis #### Structured Output ✓ - JSON schema validation - Type-safe responses - Zod schema support ### Configuration ```bash # Required ANTHROPIC_API_KEY=sk-ant-... # Optional ANTHROPIC_MODEL=claude-sonnet-4-5-20250929 ANTHROPIC_VERSION=2023-06-01 ``` ### Known Limitations - 200K token context window (generous but finite) - API rate limits based on tier - Extended thinking increases latency - PDF processing has file size limits --- ## 3. Google AI Studio Provider **File:** `src/lib/providers/googleAiStudio.ts` **Provider Name:** `google-ai` / `googleAiStudio` **Default Model:** `gemini-2.5-flash` ### Capabilities #### Text Generation ✓ - Gemini 1.5, 2.0, 2.5, and 3.0 models - Fast inference - Free tier available #### Streaming ✓ - Real-time streaming - Tool execution during streaming - Analytics support #### Tool Calling ✓ - Native function calling - Parallel tool execution - Tool result integration #### Vision/Multimodal ✓ **Supported Models:** - Gemini 3 series (Pro, Flash) - Preview - Gemini 2.5 series (Pro, Flash, Flash Lite) - Gemini 2.0 series (Flash) - Gemini 1.5 series (Pro, Flash) **Image Support:** - Up to 16 images per request - Formats: PNG, JPEG, WEBP - Base64 and Google Cloud Storage URLs #### PDF Processing ✓ - Native PDF understanding - Text and visual extraction - Document structure analysis #### Extended Thinking ✓ **Supported Models:** - Gemini 3 Pro (Preview) - Gemini 2.5 Pro - Gemini 2.5 Flash **Thinking Levels:** - `minimal`, `low`, `medium`, `high` - Configurable thinking budget #### Structured Output ⚠️ - JSON schema support - **CRITICAL LIMITATION:** Cannot use tools AND structured output simultaneously - When using JSON schema, must set `disableTools: true` - Error: "Function calling with response mime type 'application/json' is unsupported" ### Configuration ```bash # Required GOOGLE_AI_API_KEY=AIza... # Optional GOOGLE_AI_MODEL=gemini-2.5-flash ``` ### Known Limitations - **Cannot combine tools + JSON schema** (Gemini limitation) - Tools OR structured output, not both - Free tier has rate limits - Some features in preview/experimental --- ## 4. Google Vertex AI Provider **File:** `src/lib/providers/googleVertex.ts` **Provider Name:** `vertex` **Default Model:** `gemini-2.5-flash` ### Capabilities Same as Google AI Studio, plus: #### Dual Provider Support - **Gemini models** - Same as AI Studio - **Claude models via Vertex** - Anthropic models hosted on GCP **Anthropic on Vertex:** - Claude 4.5 series (Sonnet, Opus, Haiku) - Claude 4.x and 3.x series - Full tool calling support - No structured output limitation (unlike Gemini) #### Text Generation ✓ - All Gemini models - All Claude models via Vertex Anthropic - Enterprise-grade reliability #### Streaming ✓ - Same as AI Studio - Works for both Gemini and Claude models #### Tool Calling ✓ - Gemini: Full tool support (but not with schemas) - Claude: Full tool support (can combine with schemas) #### Vision/Multimodal ✓ - Gemini: Up to 16 images - Claude: Up to 20 images #### PDF Processing ✓ - Both Gemini and Claude models support PDF #### Extended Thinking ✓ - Gemini 2.5+, Gemini 3: Full support - Claude models: Not supported via Vertex #### Structured Output ⚠️ - Gemini: Cannot combine with tools - Claude: Can combine with tools ### Configuration ```bash # Required (Option 1: Service Account File) GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json VERTEX_PROJECT_ID=my-project # Required (Option 2: Environment Variables) GOOGLE_AUTH_CLIENT_EMAIL=... GOOGLE_AUTH_PRIVATE_KEY=... VERTEX_PROJECT_ID=my-project # Optional VERTEX_LOCATION=us-central1 VERTEX_MODEL=gemini-2.5-flash ``` ### Known Limitations - Requires Google Cloud project setup - Service account authentication complexity - Gemini tools + schema limitation applies - Regional endpoint configuration --- ## 5. Amazon Bedrock Provider **File:** `src/lib/providers/amazonBedrock.ts` **Provider Name:** `bedrock` **Default Model:** `anthropic.claude-3-sonnet-20240229-v1:0` ### Capabilities #### Text Generation ✓ - Claude models on Bedrock - Amazon Titan models - Cohere models - Meta Llama models - AI21 Jurassic models #### Streaming ✓ - Real-time streaming via AWS SDK - Native conversation loop - Tool execution during streaming #### Tool Calling ✓ - Native tool support via Bedrock Converse API - Multi-step tool workflows - Automatic tool execution #### Vision/Multimodal ⚠️ **Model-Dependent:** - Claude models: Full vision support - Titan models: Limited vision support - Other models: Varies by model #### PDF Processing ✓ - Claude models: Native PDF support - Document extraction and analysis #### Extended Thinking ✗ - Not supported via Bedrock - Standard reasoning only #### Structured Output ✓ - JSON schema validation - Type-safe responses ### Configuration ```bash # Required AWS_ACCESS_KEY_ID=AKIA... AWS_SECRET_ACCESS_KEY=... AWS_REGION=us-east-1 # Optional BEDROCK_MODEL=anthropic.claude-3-sonnet-20240229-v1:0 ``` ### Known Limitations - Requires AWS account with Bedrock access - Model availability varies by region - IAM permissions required - No extended thinking support - Vision support depends on model --- ## 6. Amazon SageMaker Provider **File:** `src/lib/providers/amazonSagemaker.ts` **Provider Name:** `sagemaker` **Default Model:** Custom endpoint ### Capabilities #### Text Generation ✓ - Custom SageMaker endpoints - Fine-tuned models - Enterprise model deployments #### Streaming ⚠️ - **Not fully implemented for SageMaker custom endpoints**. Streaming returns a 501 error from SageMaker custom inference endpoints; non-streaming generation works. #### Tool Calling ✓ - Supported for compatible models - Depends on endpoint configuration #### Vision/Multimodal ✗ - Not supported - Depends on custom endpoint #### PDF Processing ✗ - Not supported #### Extended Thinking ✗ - Not supported #### Structured Output ✗ - Not supported via provider - May work with custom endpoints ### Configuration ```bash # Required AWS_ACCESS_KEY_ID=AKIA... AWS_SECRET_ACCESS_KEY=... AWS_REGION=us-east-1 SAGEMAKER_ENDPOINT_NAME=my-endpoint # Optional SAGEMAKER_MODEL=custom-model ``` ### Known Limitations - **Streaming not fully implemented** - Requires SageMaker endpoint deployment - Custom model-dependent capabilities - No built-in multimodal support - Enterprise AWS setup required --- ## 7. Azure OpenAI Provider **File:** `src/lib/providers/azureOpenai.ts` **Provider Name:** `azure` **Default Model:** `gpt-4o` ### Capabilities #### Text Generation ✓ - All Azure OpenAI models - GPT-4, GPT-4o, GPT-3.5-turbo - Enterprise security and compliance #### Streaming ✓ - Real-time streaming - Tool execution during streaming - Analytics support #### Tool Calling ✓ - Full tool support - Same as OpenAI provider - Multi-step workflows #### Vision/Multimodal ✓ **Supported Models:** - GPT-5.1 series - GPT-5 series - GPT-4.1 series - O-series (o3, o4) - GPT-4o, GPT-4o-mini, GPT-4-turbo **Image Support:** - Up to 10 images per request - Same formats as OpenAI #### PDF Processing ✗ - Not natively supported #### Extended Thinking ✗ - Not supported #### Structured Output ✓ - JSON schema validation - Type-safe responses ### Configuration ```bash # Required AZURE_OPENAI_API_KEY=... AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com AZURE_OPENAI_DEPLOYMENT=gpt-4o # Optional AZURE_API_VERSION=2024-05-01-preview ``` ### Known Limitations - Requires Azure subscription - Deployment configuration required - Regional model availability varies - No PDF or extended thinking support --- ## 8. Mistral Provider **File:** `src/lib/providers/mistral.ts` **Provider Name:** `mistral` **Default Model:** `mistral-small-2506` ### Capabilities #### Text Generation ✓ - Mistral Small, Medium, Large models - Fast inference - Cost-effective #### Streaming ✓ - Real-time streaming - Tool execution support #### Tool Calling ✓ - Native function calling - Tool execution workflows #### Vision/Multimodal ⚠️ **Supported Models:** - Mistral Small 2506 (June 2025) - Vision-capable - Mistral Pixtral - Multimodal model **Image Support:** - Up to 10 images per request (conservative limit) - Model-dependent capability #### PDF Processing ✗ - Not supported #### Extended Thinking ✗ - Not supported #### Structured Output ✓ - JSON schema support - Type-safe responses ### Configuration ```bash # Required MISTRAL_API_KEY=... # Optional MISTRAL_MODEL=mistral-small-2506 ``` ### Known Limitations - Vision only on specific models (Small 2506+) - No PDF support - No extended thinking - Limited multimodal compared to GPT-4o/Claude --- ## 9. HuggingFace Provider **File:** `src/lib/providers/huggingFace/client.ts` **Provider Name:** `huggingface` **Default Model:** `Qwen/Qwen2.5-72B-Instruct` ### Capabilities #### Text Generation ✓ - Access to 100,000+ models - Open-source models - Custom fine-tuned models #### Streaming ✓ - Real-time streaming via unified router - OpenAI-compatible endpoint #### Tool Calling ✓ Tools are offered to every model; capability is resolved by the shared `modelSupports()` facade rather than a provider-local list. A 13-entry model-name allowlist used to gate this. It was written for the retired per-model Inference API, where many endpoints rejected the OpenAI `tools` field. Measured against the 142 models the router served on 2026-09-13, it admitted **1** and blocked 141 — including `Qwen/Qwen2.5-72B-Instruct`, `zai-org/GLM-5.3-Flash`, `google/gemma-4-31B-it` and `deepseek-ai/DeepSeek-V4-Flash`, every one of which returns HTTP 200 with `tool_calls`. No served model rejected the field, so the allowlist was removed. A model that cannot use tools simply does not emit `tool_calls`, which the tool loop already handles. Note the legacy ids in the old list (CodeLlama 34B, Mistral 7B Instruct v0.3, Hermes 3 Llama 3.2, Llama 3.1 70B/405B) are **not served by the router** — they answer 400 regardless of tools. #### Vision/Multimodal ✗ - Not supported via unified router - Individual model APIs may support #### PDF Processing ✗ - Not supported #### Extended Thinking ✗ - Not supported #### Structured Output ✗ - Not supported via provider ### Configuration ```bash # Required HUGGINGFACE_API_KEY=hf_... # Optional HUGGINGFACE_MODEL=meta-llama/Llama-3.1-8B-Instruct ``` ### Known Limitations - Tool calling only on specific models - No vision/multimodal support - No PDF processing - Model quality varies significantly - Some models require approval/licensing --- ## 10. LiteLLM Provider **File:** `src/lib/providers/litellm.ts` **Provider Name:** `litellm` **Default Model:** `openai/gpt-4o-mini` ### Capabilities #### Text Generation ✓ - Access to 100+ models via proxy - Unified interface across supported providers - Cost tracking and analytics #### Streaming ✓ - Real-time streaming - Proxies to underlying provider streams #### Tool Calling ✓ - Full tool support - Depends on backend model capabilities #### Vision/Multimodal ⚠️ - Depends on backend model - If proxying to GPT-4o: Vision supported - If proxying to Gemini: Vision supported - Varies by configured model #### PDF Processing ✗ - Not supported via LiteLLM proxy #### Extended Thinking ✗ - Not supported #### Structured Output ✓ - JSON schema support - Type-safe responses ### Configuration ```bash # Required LITELLM_BASE_URL=http://localhost:4000 LITELLM_API_KEY=sk-anything # Optional LITELLM_MODEL=openai/gpt-4o-mini ``` ### Known Limitations - Requires LiteLLM proxy server running - Capabilities depend on backend provider - Model format: `provider/model` - Configuration complexity for enterprise setups --- ## 11. Ollama Provider **File:** `src/lib/providers/ollama.ts` **Provider Name:** `ollama` **Default Model:** `llama3.1:8b` ### Capabilities #### Text Generation ✓ - Local model execution - Privacy-first (no data sent to cloud) - Custom model support #### Streaming ✓ - Real-time streaming - Dual API mode: - Native Ollama API (`/api/generate`) - OpenAI-compatible API (`/v1/chat/completions`) #### Tool Calling ✓ - Supported on compatible models - Llama 3.1+ models - Gemma 3 models with tool training #### Vision/Multimodal ⚠️ **Model-Dependent:** - LLaVA models - Vision support - Gemini models - Vision support - Llama 3.2 Vision - Vision support **Image Support:** - Up to 10 images (conservative limit) - Depends on model capabilities #### PDF Processing ✗ - Not supported #### Extended Thinking ✗ - Not supported #### Structured Output ✗ - Limited structured output support ### Configuration ```bash # Optional OLLAMA_BASE_URL=http://localhost:11434 OLLAMA_MODEL=llama3.1:8b OLLAMA_TIMEOUT=240000 OLLAMA_OPENAI_COMPATIBLE=false ``` ### Known Limitations - Local compute requirements - Model quality varies - No PDF support - Vision only on specific models - Slower inference than cloud providers --- ## 12. OpenAI Compatible Provider **File:** `src/lib/providers/openaiCompatible.ts` **Provider Name:** `openai-compatible` **Default Model:** Auto-discovered or `gpt-3.5-turbo` ### Capabilities #### Text Generation ✓ - Any OpenAI-compatible endpoint - vLLM, FastChat, LocalAI, etc. - Custom deployment support #### Streaming ✓ - Real-time streaming - OpenAI-compatible SSE #### Tool Calling ✓ - Full tool support - Depends on backend compatibility #### Vision/Multimodal ⚠️ - Depends on backend endpoint - Auto-discovery not available for capabilities #### PDF Processing ✗ - Not supported #### Extended Thinking ✗ - Not supported #### Structured Output ✓ - JSON schema support - Type-safe responses ### Configuration ```bash # Required OPENAI_COMPATIBLE_BASE_URL=https://api.custom.com/v1 OPENAI_COMPATIBLE_API_KEY=... # Optional OPENAI_COMPATIBLE_MODEL=model-name # Auto-discovers if not set ``` ### Known Limitations - Capabilities depend entirely on backend - No standardized capability detection - Authentication varies by provider - Model discovery may fail --- ## 13. OpenRouter Provider **File:** `src/lib/providers/openRouter.ts` **Provider Name:** `openrouter` **Default Model:** `anthropic/claude-3-5-sonnet` ### Capabilities #### Text Generation ✓ - Access to 300+ models from 60+ providers - Unified API for all models - Automatic failover - Cost tracking #### Streaming ✓ - Real-time streaming - Proxies to underlying provider #### Tool Calling ⚠️ **Model-Dependent Support:** **Supported Models:** - Anthropic Claude models - OpenAI GPT-4 models - Google Gemini models - Mistral Large/Small models - Meta Llama 3.3, 3.2 **Unsupported Models:** - Many older/smaller models - Check model page for tool support #### Vision/Multimodal ⚠️ - Depends on selected model - GPT-4o, Claude, Gemini support vision - Check model-specific capabilities #### PDF Processing ✗ - Not supported via OpenRouter #### Extended Thinking ✗ - Not supported #### Structured Output ✓ - JSON schema support - Type-safe responses ### Configuration ```bash # Required OPENROUTER_API_KEY=sk-or-... # Optional OPENROUTER_MODEL=anthropic/claude-3-5-sonnet OPENROUTER_REFERER=https://your-app.com OPENROUTER_APP_NAME=YourApp ``` ### Known Limitations - Tool support varies by model - Vision support varies by model - Credit-based pricing system - Model availability can change - No PDF support --- ## Summary Tables ### Provider Comparison by Use Case #### Best for Production Text Generation 1. **OpenAI** - Most reliable, best quality 2. **Anthropic** - Long context, advanced reasoning 3. **Google Vertex** - Enterprise-grade, multi-model #### Best for Multimodal (Vision + Text) 1. **Anthropic** - Best vision + PDF support 2. **OpenAI** - Strong vision, no PDF 3. **Google AI Studio** - Good vision + PDF, free tier #### Best for Tool Calling 1. **Anthropic** - Most advanced agentic workflows 2. **OpenAI** - Reliable function calling 3. **Google Vertex** - Dual provider (Gemini + Claude) #### Best for Local/Privacy 1. **Ollama** - Fully local, no cloud 2. N/A - Only Ollama provides local execution #### Best for Cost Optimization 1. **Google AI Studio** - Free tier available 2. **OpenRouter** - Access to free models 3. **LiteLLM** - Cost tracking, routing #### Best for Extended Thinking 1. **Anthropic** - Native extended thinking 2. **Google AI Studio** - Gemini 2.5+, 3.0 thinking 3. **Google Vertex** - Same as AI Studio ### Authentication Quick Reference | Provider | Auth Type | Env Vars | Complexity | | ----------------- | ------------------ | --------------------------------------------------------- | ---------- | | OpenAI | API Key | `OPENAI_API_KEY` | Low | | Anthropic | API Key | `ANTHROPIC_API_KEY` | Low | | Google AI Studio | API Key | `GOOGLE_AI_API_KEY` | Low | | Google Vertex | Service Account | `GOOGLE_APPLICATION_CREDENTIALS` | High | | Amazon Bedrock | AWS Credentials | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` | Medium | | Amazon SageMaker | AWS Credentials | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` | High | | Azure OpenAI | API Key + Endpoint | `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_ENDPOINT` | Medium | | Mistral | API Key | `MISTRAL_API_KEY` | Low | | HuggingFace | API Key | `HUGGINGFACE_API_KEY` | Low | | LiteLLM | Custom | `LITELLM_BASE_URL`, `LITELLM_API_KEY` | Medium | | Ollama | None | Optional `OLLAMA_BASE_URL` | Low | | OpenAI Compatible | Custom | `OPENAI_COMPATIBLE_BASE_URL`, `OPENAI_COMPATIBLE_API_KEY` | Medium | | OpenRouter | API Key | `OPENROUTER_API_KEY` | Low | --- ## Provider Implementation Notes ### BaseProvider Architecture Providers extend the `BaseProvider` class, which provides: - Unified interface for text generation and streaming - Tool registration and execution - Middleware support - Analytics and telemetry - Error handling - Message building for multimodal content ### Dynamic Provider Loading Providers are registered via dynamic imports in `ProviderRegistry`: - Avoids circular dependencies - Lazy loading for better performance - Clean provider isolation ### Tool Execution Flow 1. Tools registered with `MCPToolRegistry` 2. Provider calls `getAllTools()` to get available tools 3. AI model receives tool definitions 4. Model calls tools during generation 5. Tool results sent back to model 6. Process repeats until completion --- ## Version History - **v9.62.0** (May 2026) - Multi-provider voice (TTS/STT/realtime); 24 providers - **v9.60.0** (April 2026) - Added DeepSeek, NVIDIA NIM, LM Studio, llama.cpp providers - **v9.59.0** - Typed `ModelAccessDeniedError` + `sdk.checkCredentials()` - **v9.58.0** - `providerFallback` callback + `modelChain` config - **v9.53.0** - AutoResearch autonomous experiment engine - **v9.52.0** - Per-request and per-instance credentials for all providers - **v8.26.1** (January 2026) - 13 providers (historical) - **v8.26.0** - Added video output types - **v8.25.0** - Gemini 3 support improvements - **v8.24.0** - Enhanced provider capabilities --- **Next Steps:** - See [Provider Comparison Guide](/docs/reference/provider-comparison) for feature matrix - See [Provider Selection Wizard](/docs/reference/provider-selection) for recommendations - See [API Reference](/docs/sdk/api-reference) for usage examples --- ## AI Provider Comparison Guide # AI Provider Comparison Guide > ⚠️ **STALE DOCUMENT** — This comparison predates the current provider roster, including the JSON-catalog providers, and is due for a fresh pass. Provider rows below may be missing or out of date; see the [README](https://github.com/juspay/neurolink/blob/release/README.md) for the current provider list. **Last Updated:** May 2026 **NeuroLink Version:** 9.62.0 Comparison of NeuroLink's text and multimodal AI providers, including capabilities, pricing, and use case recommendations. (Note: voice providers — OpenAI TTS, ElevenLabs, Deepgram, Azure Speech, Google TTS/STT, [60db](/docs/getting-started/providers/sixtydb), Whisper, OpenAI Realtime, Gemini Live — are documented separately under [Voice Providers](/docs/).) -------------- | ---- | ------ | ----- | ------ | --- | -------- | ---------- | --------- | ---------- | | OpenAI | ✓ | ✓ | ✓ | ✓ | ✗ | ✗ | ✓ | ✗ | 2 min | | Anthropic ^1^ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ⚠️ | 2 min | | Google AI Studio | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ⚠️ | ✓ | 2 min | | Google Vertex | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ⚠️ | ✗ | 15 min | | Amazon Bedrock | ✓ | ✓ | ✓ | ⚠️ | ✓ | ✗ | ✓ | ✗ | 10 min | | Amazon SageMaker | ✓ | ⚠️ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | 30 min | | Azure OpenAI | ✓ | ✓ | ✓ | ✓ | ✗ | ✗ | ✓ | ✗ | 20 min | | Mistral | ✓ | ✓ | ✓ | ⚠️ | ✗ | ✗ | ✓ | ✓ | 2 min | | HuggingFace | ✓ | ✓ | ⚠️ | ✗ | ✗ | ✗ | ✗ | ✓ | 2 min | | LiteLLM | ✓ | ✓ | ✓ | ⚠️ | ✗ | ✗ | ✓ | ⚠️ | 5 min | | Ollama | ✓ | ✓ | ✓ | ⚠️ | ✗ | ✗ | ✗ | ✓ | 5 min | | OpenAI Compatible | ✓ | ✓ | ✓ | ⚠️ | ✗ | ✗ | ✓ | ⚠️ | 5 min | | OpenRouter | ✓ | ✓ | ⚠️ | ⚠️ | ✗ | ✗ | ✓ | ⚠️ | 2 min | | DeepSeek | ✓ | ✓ | ✓ | ✗ | ✗ | ✓ | ✓ | ✗ | 2 min | | NVIDIA NIM | ✓ | ✓ | ✓ | ⚠️ | ✗ | ✓ | ✓ | ✗ | 5 min | | LM Studio | ✓ | ✓ | ⚠️ | ⚠️ | ✗ | ⚠️ | ⚠️ | ✓ | 5 min | | llama.cpp | ✓ | ✓ | ⚠️ | ⚠️ | ✗ | ⚠️ | ⚠️ | ✓ | 10 min | **Legend:** - ✓ Full Support - ⚠️ Partial/Model-Dependent - ✗ Not Supported ^1^ Anthropic supports both API Key and OAuth authentication. Free tier access is available via Claude subscription (OAuth). See [Anthropic Deep Dive](#2-anthropic) for details. --- ## Pricing Comparison ### Pay-per-Token Providers | Provider | Input (per 1M tokens) | Output (per 1M tokens) | Vision | Best Value Model | | -------------------- | --------------------- | ---------------------- | -------------- | ----------------------------- | | **OpenAI** | $2.50 - $60.00 | $10.00 - $180.00 | $5.00 - $60.00 | GPT-4o-mini: $0.15/$0.60 | | **Anthropic** ^2^ | $3.00 - $15.00 | $15.00 - $75.00 | Same | Claude Haiku: $0.25/$1.25 | | **Google AI Studio** | FREE - $7.00 | FREE - $21.00 | FREE - $7.00 | Gemini 2.5 Flash: FREE | | **Google Vertex** | $0.35 - $35.00 | $1.05 - $105.00 | $0.35 - $35.00 | Gemini 2.5 Flash: $0.35/$1.05 | | **Amazon Bedrock** | $3.00 - $15.00 | $15.00 - $75.00 | $3.00 - $15.00 | Claude Haiku: $0.25/$1.25 | | **Azure OpenAI** | $2.50 - $60.00 | $10.00 - $180.00 | $5.00 - $60.00 | GPT-4o-mini: $0.15/$0.60 | | **Mistral** | $0.25 - $8.00 | $0.75 - $24.00 | $0.25 - $8.00 | Mistral Small: $0.20/$0.60 | | **HuggingFace** | FREE - $1.00 | FREE - $1.00 | N/A | Qwen 2.5 72B: FREE | | **OpenRouter** | $0.00 - $60.00 | $0.00 - $180.00 | Varies | Many free models | | **DeepSeek** | $0.14 - $2.19 | $0.28 - $8.75 | N/A | deepseek-chat: $0.14/$0.28 | | **NVIDIA NIM** | Varies by model | Varies by model | Varies | Free credits for new users | ^2^ Anthropic also offers subscription-based pricing as an alternative to per-token API pricing: Free tier (limited), Pro ($20/mo), Max ($100+/mo with 5x-20x usage). NeuroLink supports both API key and OAuth (subscription) authentication. See [Anthropic Deep Dive](#2-anthropic). ### Self-Hosted / Custom Pricing | Provider | Model | Cost Structure | Notes | | --------------------- | ------ | ------------------------ | ------------------------------------------------- | | **Amazon SageMaker** | Custom | Instance hours + storage | Varies by instance type (ml.g5.xlarge: ~$1.41/hr) | | **LiteLLM** | Proxy | Backend provider costs | No additional fee, proxy overhead only | | **Ollama** | Local | Hardware costs only | FREE (uses local compute) | | **OpenAI Compatible** | Custom | Backend-dependent | Varies by endpoint provider | | **LM Studio** | Local | Hardware costs only | FREE (uses local compute) | | **llama.cpp** | Local | Hardware costs only | FREE (uses local compute) | ### Free Tier Details **Anthropic (via Claude subscription):** - Free tier available via OAuth authentication (claude.ai account) - Limited daily messages and lower rate limits - Access to Claude Haiku models - No API key required (uses OAuth 2.0 flow) **Google AI Studio:** - 15 requests/minute - 1,500 requests/day - Up to 1M tokens/day - Gemini 2.5 Flash completely FREE **HuggingFace:** - Rate-limited free tier - 1,000 requests/month on free models - Inference API access **Mistral:** - Limited free tier for testing - Mistral Small free quota **Ollama:** - Completely FREE - Uses local compute - No API limits **LM Studio:** - Completely FREE - Uses local compute (GPU or CPU) - No API limits or network dependency - Requires LM Studio desktop app **llama.cpp:** - Completely FREE - Uses local compute (GPU or CPU) - No API limits or network dependency - Requires llama-server binary **OpenRouter:** - Many FREE models available: - Google Gemini 2.0 Flash (free) - Meta Llama 3.3 70B (free) - Qwen models (free) --- ## Detailed Feature Comparison ### Text Generation **Providers support text generation**, but quality varies: **Tier 1 (Highest Quality):** - OpenAI GPT-4o, GPT-5 series - Anthropic Claude 4.5 series - Google Gemini 3 Pro **Tier 2 (High Quality):** - Azure OpenAI (same as OpenAI) - Google Gemini 2.5 Pro - Anthropic Claude 4.0 Sonnet **Tier 3 (Good Quality):** - Mistral Large - Amazon Bedrock (Claude models) - OpenRouter (Claude/GPT-4 routing) **Tier 4 (Variable Quality):** - HuggingFace (model-dependent) - Ollama (model-dependent) - LiteLLM (backend-dependent) --- ### Streaming Support **Full Streaming (Real-time SSE):** - ✓ OpenAI - ✓ Anthropic - ✓ Google AI Studio - ✓ Google Vertex - ✓ Amazon Bedrock - ✓ Azure OpenAI - ✓ Mistral - ✓ HuggingFace - ✓ LiteLLM - ✓ Ollama - ✓ OpenAI Compatible - ✓ OpenRouter - ✓ DeepSeek - ✓ NVIDIA NIM - ✓ LM Studio - ✓ llama.cpp **Partial/Limited Streaming:** - ⚠️ Amazon SageMaker (not fully implemented in v8.26.1) --- ### Tool Calling / Function Calling **Native Full Support:** - ✓ OpenAI - Industry-leading function calling - ✓ Anthropic - Advanced tool use, parallel execution - ✓ Azure OpenAI - Same as OpenAI - ✓ Mistral - Native function calling - ✓ Google Vertex - Gemini + Claude models - ✓ Google AI Studio - Gemini models - ✓ Amazon Bedrock - Converse API tool support - ✓ LiteLLM - Proxies to backend providers - ✓ DeepSeek - Both deepseek-chat and deepseek-reasoner **Model-Dependent Support:** - ⚠️ NVIDIA NIM - Depends on hosted model (Llama 3.x: yes; embedding-only models: no) - ⚠️ LM Studio - Depends on loaded model (Llama 3.1+, Mistral 7B Instruct v0.3, etc.) - ⚠️ llama.cpp - Requires `--jinja` server flag; depends on loaded model - ⚠️ HuggingFace - Only specific models: - Llama 3.1+ series - Hermes 3 models - CodeLlama 34B - Mistral 7B Instruct v0.3 - ⚠️ Ollama - Only compatible models: - Llama 3.1+ - Gemma 3 with tool training - ⚠️ OpenRouter - Check model capabilities: - Claude models: ✓ - GPT-4 models: ✓ - Gemini models: ✓ - Many others vary - ⚠️ OpenAI Compatible - Depends on backend - ⚠️ Amazon SageMaker - Depends on custom endpoint --- ### Vision / Multimodal Capabilities **Native Vision Support:** **Tier 1 (Best Vision):** - **OpenAI** - GPT-4o, GPT-5 series, O-series - 10 images max - PNG, JPEG, WEBP, GIF - **Anthropic** - Claude 4.5 Sonnet/Haiku, Claude 4.0 Opus/Sonnet - 20 images max - Excellent vision quality - **Google Vertex/AI Studio** - Gemini 2.5+, 3.x - 16 images max - Native multimodal architecture **Tier 2 (Good Vision):** - **Azure OpenAI** - Same models as OpenAI - 10 images max - **Mistral** - Small 2506, Pixtral - 10 images max (conservative) **Model-Dependent Vision:** - ⚠️ **LiteLLM** - Depends on backend (e.g., GPT-4o via LiteLLM = vision) - ⚠️ **Ollama** - LLaVA, Llama 3.2 Vision, Gemini models - ⚠️ **OpenAI Compatible** - Backend-dependent - ⚠️ **OpenRouter** - Model-dependent (Claude, GPT-4o, Gemini support vision) - ⚠️ **Amazon Bedrock** - Claude models support vision - ⚠️ **NVIDIA NIM** - Depends on hosted model (e.g., Phi-3-vision, Llama 3.2 Vision) - ⚠️ **LM Studio** - Depends on loaded model (LLaVA, Llama 3.2 Vision, Qwen-VL, etc.) - ⚠️ **llama.cpp** - Depends on loaded model (LLaVA, Llama 3.2 Vision, etc.) **No Vision Support:** - ✗ HuggingFace - ✗ Amazon SageMaker - ✗ DeepSeek (API does not accept image input) --- ### PDF Document Processing **Native PDF Support:** - ✓ **Anthropic** - Native PDF understanding (best) - ✓ **Google AI Studio** - Gemini PDF processing - ✓ **Google Vertex** - Gemini + Claude PDF support - ✓ **Amazon Bedrock** - Claude models **No PDF Support (Requires Preprocessing):** - ✗ OpenAI - ✗ Azure OpenAI - ✗ Mistral - ✗ HuggingFace - ✗ LiteLLM - ✗ Ollama - ✗ OpenAI Compatible - ✗ OpenRouter - ✗ Amazon SageMaker - ✗ DeepSeek - ✗ NVIDIA NIM - ✗ LM Studio - ✗ llama.cpp --- ### Extended Thinking / Reasoning **Native Extended Thinking:** - ✓ **Anthropic** - All Claude 4.0+ models (best) - Claude Sonnet 4, Opus 4, Opus 4.1, Sonnet 4.5, Opus 4.5, Haiku 4.5, Sonnet 4.6, Opus 4.6 - Thinking levels: minimal, low, medium, high - Transparent reasoning process - Available on Pro and Max subscription tiers (not Free) - ✓ **Google AI Studio** - Gemini 2.5 Pro, Gemini 2.5 Flash, Gemini 3 Flash, Gemini 3.1 Pro - Thinking levels: minimal, low, medium, high - Configurable thinking budget - ✓ **Google Vertex** - Same as AI Studio (Gemini only, not Claude) **Native Extended Thinking (continued):** - ✓ **DeepSeek** - deepseek-reasoner (R1) model exposes chain-of-thought natively; deepseek-chat supports opt-in thinking mode - ✓ **NVIDIA NIM** - Reasoning depends on the hosted model: the default `openai/gpt-oss-20b` returns a reasoning trace on every request. `thinkingLevel` is an on/off switch on `stream()` only (see the [NVIDIA NIM guide](/docs/getting-started/providers/nvidia-nim.md#reasoning-and-thinkinglevel)) **Model-Dependent Thinking:** - ⚠️ **LM Studio** - Depends on loaded model (Qwen3, DeepSeek-R1-distill variants expose reasoning) - ⚠️ **llama.cpp** - Depends on loaded model (DeepSeek-R1-distill GGUF variants expose reasoning) **No Extended Thinking:** - ✗ OpenAI (standard reasoning only) - ✗ Azure OpenAI - ✗ Amazon Bedrock - ✗ Amazon SageMaker - ✗ Mistral - ✗ HuggingFace - ✗ LiteLLM - ✗ Ollama - ✗ OpenAI Compatible - ✗ OpenRouter --- ### Structured Output / JSON Schema **Full Support (Tools + Schema Together):** - ✓ **OpenAI** - Native JSON mode - ✓ **Anthropic** - Full schema + tools - ✓ **Azure OpenAI** - Same as OpenAI - ✓ **Amazon Bedrock** - Schema validation - ✓ **Mistral** - JSON schema support - ✓ **LiteLLM** - Proxies to backend - ✓ **OpenAI Compatible** - OpenAI-compatible endpoints - ✓ **OpenRouter** - Model-dependent - ✓ **DeepSeek** - JSON schema support via OpenAI-compatible API **Partial Support (Tools OR Schema, Not Both):** - ⚠️ **Google AI Studio** - ❌ Cannot combine - Must use `disableTools: true` with schemas - Gemini API limitation - ⚠️ **Google Vertex** - ❌ Cannot combine (Gemini models only) - Claude models on Vertex CAN combine - Gemini models have same limitation as AI Studio **Model-Dependent Structured Output:** - ⚠️ **NVIDIA NIM** - Model-dependent reliability; capable frontier models work well - ⚠️ **LM Studio** - Model-dependent reliability; small local models may struggle with strict schemas - ⚠️ **llama.cpp** - Model-dependent reliability; small local models may struggle with strict schemas **No Structured Output:** - ✗ HuggingFace - ✗ Ollama - ✗ Amazon SageMaker --- ## Provider Deep Dive ### 1. OpenAI **Provider ID:** `openai` **Default Model:** `gpt-4o-mini` **Strengths:** - Industry-leading model quality - Best-in-class developer experience - Extensive ecosystem and integrations - Excellent documentation - Reliable uptime and performance **Weaknesses:** - Expensive at scale - No free tier - No PDF support - No extended thinking **Best For:** - Production applications requiring highest quality - Critical customer-facing features - Complex reasoning tasks - When budget allows premium pricing **Pricing:** - GPT-4o: $2.50/$10.00 per 1M tokens - GPT-4o-mini: $0.15/$0.60 per 1M tokens - GPT-5 series: $15.00-$60.00 input, $45.00-$180.00 output --- ### 2. Anthropic **Provider ID:** `anthropic` **Default Model:** `claude-sonnet-4-6` **Auth Methods:** API Key, OAuth 2.0 (unique among providers) **Strengths:** - **Extended thinking** - Best reasoning capabilities - **Native PDF support** - Document understanding - **Dual auth support** - API key for developers, OAuth for subscription users - **Subscription tiers** - Free, Pro ($20/mo), Max ($100+/mo) as alternatives to per-token pricing - 200K token context window - Strong safety features - Excellent for analysis and research **Weaknesses:** - Higher cost than some alternatives (API pricing) - Smaller ecosystem than OpenAI - Limited regional availability - Subscription tiers have model access restrictions (e.g., Opus requires Max tier) **Best For:** - Complex reasoning and analysis - Document processing workflows - Agentic workflows with tools - When extended thinking is valuable - Subscription users who prefer flat-rate pricing over per-token costs **Pricing:** _Per-Token API Pricing:_ - Claude Haiku 4.5: $0.25/$1.25 per 1M tokens - Claude Sonnet 4.5: $3.00/$15.00 per 1M tokens - Claude Opus 4.5: $15.00/$75.00 per 1M tokens _Subscription Pricing (via OAuth):_ - **Free**: Limited daily messages, Sonnet access - **Pro** ($20/mo): Higher limits, priority access, extended thinking - **Max** ($100+/mo): 5x-20x usage, Opus access, highest rate limits --- ### 3. Google AI Studio **Provider ID:** `google-ai` / `googleAiStudio` **Default Model:** `gemini-2.5-flash` **Strengths:** - **Generous FREE tier** - 1M tokens/day free - **Extended thinking** - Gemini 2.5+, 3.0 - **PDF support** - Native document processing - Fast inference (Gemini Flash models) - Simple setup (just API key) **Weaknesses:** - Cannot combine tools + JSON schema (Gemini limitation) - Rate limits on free tier - Newer platform (less mature than OpenAI) **Best For:** - Startups and developers (free tier) - Prototyping and experimentation - Budget-conscious production apps - When extended thinking + PDF support needed **Pricing:** - Gemini 2.5 Flash: **FREE** (up to 1M tokens/day) - Gemini 2.5 Pro: $1.25/$5.00 per 1M tokens - Gemini 3 Flash: **FREE** (up to 1M tokens/day) - Gemini 3 Pro: $7.00/$21.00 per 1M tokens --- ### 4. Google Vertex AI **Provider ID:** `vertex` **Default Model:** `claude-sonnet-4-6` **Strengths:** - **Dual provider** - Gemini + Claude models - Enterprise-grade reliability - GCP integration - Multiple authentication methods - Claude models support tools + schema together **Weaknesses:** - Complex setup (service accounts) - Gemini models cannot combine tools + schema - Higher latency than AI Studio - Requires GCP project **Best For:** - Enterprise Google Cloud users - When you need both Gemini AND Claude - Production deployments requiring SLAs - Regulated industries **Pricing:** - Gemini 2.5 Flash: $0.35/$1.05 per 1M tokens - Gemini 3 Pro: $7.00/$21.00 per 1M tokens - Claude on Vertex: Same as Bedrock pricing --- ### 5. Amazon Bedrock **Provider ID:** `bedrock` **Default Model:** env-based (`BEDROCK_MODEL`); recommend `anthropic.claude-sonnet-4-6` **Strengths:** - Multiple model providers (Claude, Titan, Cohere, Llama) - AWS integration - Enterprise security and compliance - Pay-as-you-go pricing **Weaknesses:** - Complex AWS setup - Regional model availability varies - No extended thinking support - Requires IAM configuration **Best For:** - AWS-based enterprises - Multi-model strategies - Compliance-heavy industries (HIPAA, SOC2) - When you need Claude + Llama + others **Pricing:** - Claude Haiku: $0.25/$1.25 per 1M tokens - Claude Sonnet: $3.00/$15.00 per 1M tokens - Claude Opus: $15.00/$75.00 per 1M tokens - Amazon Titan: $0.30/$0.40 per 1M tokens --- ### 6. Amazon SageMaker **Provider ID:** `sagemaker` **Default Model:** env-based (`SAGEMAKER_MODEL`) **Strengths:** - Custom model deployment - Fine-tuned models - Enterprise control - Autoscaling infrastructure **Weaknesses:** - **Streaming not fully implemented** (v8.26.1) - Complex setup (requires SageMaker endpoints) - Higher operational overhead - No multimodal support **Best For:** - Custom fine-tuned models - Enterprise ML teams - When you need full model control - Specialized domain models **Pricing:** - Instance-based: ml.g5.xlarge ~$1.41/hour - ml.g5.2xlarge ~$2.03/hour - Plus storage and data transfer costs --- ### 7. Azure OpenAI **Provider ID:** `azure` **Default Model:** `gpt-4o-mini` **Strengths:** - Enterprise security and compliance - Microsoft ecosystem integration - SLA guarantees - Same models as OpenAI **Weaknesses:** - Most complex setup of all providers - Requires Azure subscription - Deployment configuration required - Limited regional availability **Best For:** - Enterprise Microsoft shops - When you need SLAs and support - Azure-based infrastructure - Regulated industries **Pricing:** - Same as OpenAI pricing - Billed through Azure subscription - GPT-4o: $2.50/$10.00 per 1M tokens - GPT-4o-mini: $0.15/$0.60 per 1M tokens --- ### 8. Mistral **Provider ID:** `mistral` **Default Model:** `mistral-large-latest` **Strengths:** - GDPR compliant (European data centers) - Competitive pricing - Vision support (Small 2506+) - Open-weight models available **Weaknesses:** - Smaller model selection than OpenAI - Less ecosystem support - Vision only on specific models - No PDF or extended thinking **Best For:** - European compliance needs (GDPR) - Cost-conscious deployments - When you prefer European hosting - Open-source friendly organizations **Pricing:** - Mistral Small: $0.20/$0.60 per 1M tokens - Mistral Medium: $2.50/$7.50 per 1M tokens - Mistral Large: $8.00/$24.00 per 1M tokens --- ### 9. HuggingFace **Provider ID:** `huggingface` **Default Model:** `Qwen/Qwen2.5-72B-Instruct` **Strengths:** - Access to 100,000+ models - Open-source focus - Community-driven - Free tier available **Weaknesses:** - Variable model quality - Tool calling only on specific models - No vision or multimodal - Rate limits on free tier **Best For:** - Research and experimentation - Open-source projects - Testing cutting-edge models - Budget-constrained projects **Pricing:** - Free tier: 1,000 requests/month - Inference API: From FREE to ~$1.00 per 1M tokens - PRO tier: $9/month for higher limits --- ### 10. LiteLLM **Provider ID:** `litellm` **Default Model:** `openai/gpt-4o-mini` **Strengths:** - Access to 100+ models via proxy - Unified interface across supported providers - Cost tracking and analytics - Load balancing and failover **Weaknesses:** - Requires proxy server running - Adds proxy overhead - Configuration complexity - Capabilities depend on backend **Best For:** - Multi-provider strategies - Cost optimization and tracking - Load balancing across providers - A/B testing different models **Pricing:** - No additional cost (uses backend provider pricing) - Self-hosted proxy is FREE - Cloud-hosted option available --- ### 11. Ollama **Provider ID:** `ollama` **Default Model:** `llama3.2:latest` **Strengths:** - **Completely FREE** (local execution) - Maximum privacy (no data sent to cloud) - Works offline - Fast local inference - No API rate limits **Weaknesses:** - Requires local compute resources - Model quality varies - Manual model management - Vision only on specific models **Best For:** - Privacy-critical applications - Offline/air-gapped environments - Cost-sensitive projects - Development and testing **Pricing:** - **FREE** (hardware costs only) - Requires local GPU for best performance - No API costs or rate limits --- ### 12. OpenAI Compatible **Provider ID:** `openai-compatible` **Default Model:** Auto-discovered **Strengths:** - Works with any OpenAI-compatible endpoint - vLLM, FastChat, LocalAI support - Custom deployment flexibility - Auto-discovers available models **Weaknesses:** - Capabilities entirely backend-dependent - No standardized capability detection - Configuration varies by provider - Authentication varies **Best For:** - Custom deployments (vLLM, FastChat) - Internal model serving - Private cloud deployments - When you control the backend **Pricing:** - Depends entirely on backend provider - Self-hosted: Infrastructure costs only - Cloud-hosted: Provider-specific pricing --- ### 13. OpenRouter **Provider ID:** `openrouter` **Default Model:** `anthropic/claude-3-5-sonnet` **Strengths:** - Access to 300+ models from 60+ providers - Many **FREE models** available - Automatic failover - Unified API for all models - Cost tracking **Weaknesses:** - Tool support varies by model - Vision support varies by model - Credit-based pricing system - Model availability can change **Best For:** - Access to many providers via one API - Cost optimization (free models available) - Rapid prototyping - When you want provider flexibility **Pricing:** - **Free models available:** - Google Gemini 2.0 Flash: FREE - Meta Llama 3.3 70B: FREE - Qwen models: FREE - **Paid models:** - Claude 3.5 Sonnet: $3.00/$15.00 per 1M tokens - GPT-4o: $2.50/$10.00 per 1M tokens --- ### 14. DeepSeek **Provider ID:** `deepseek` **Default Model:** `deepseek-chat` **Aliases:** `ds` **Strengths:** - Very competitive pricing (among the cheapest frontier-quality models) - deepseek-reasoner (R1) — strong open-weight reasoning model - OpenAI-compatible API — minimal integration overhead - Tool calling supported on both models **Weaknesses:** - No vision / multimodal support - Cloud-only (data sent to DeepSeek servers in China — consider for compliance) - No PDF support **Best For:** - Cost-sensitive text and reasoning workloads - Agentic tool-calling pipelines where budget matters - Experimenting with open-weight-quality reasoning at low cost **Pricing:** - deepseek-chat (V3): ~$0.14/$0.28 per 1M tokens - deepseek-reasoner (R1): ~$0.55/$2.19 per 1M tokens --- ### 15. NVIDIA NIM **Provider ID:** `nvidia-nim` **Default Model:** `openai/gpt-oss-20b` **Aliases:** `nvidia`, `nim` **Strengths:** - Access to NVIDIA-hosted Llama, Mistral, Nemotron, DeepSeek models - Reasoning is model-dependent: the default `openai/gpt-oss-20b` returns a reasoning trace on every request; `thinkingLevel` toggles NIM's thinking flags on `stream()` only - Vision supported on vision-capable models (Phi-3-vision, Llama 3.2 Vision) - OpenAI-compatible API with NIM-specific extras (top_k, min_p, reasoning_budget) - Graceful retry on 400 errors — drops unsupported extras automatically **Weaknesses:** - Tool and vision capability depends entirely on the specific hosted model - Requires NVIDIA NGC API key - No PDF support **Best For:** - Running NVIDIA-optimized Llama/Mistral/Nemotron models in the cloud - Reasoning workloads on hosted reasoning models such as `openai/gpt-oss-20b` - Developers already in the NVIDIA ecosystem (NGC, DGX Cloud) **Pricing:** - Varies by model; new accounts receive free credits - See https://build.nvidia.com/models for per-model pricing --- ### 16. LM Studio **Provider ID:** `lm-studio` **Default Model:** Auto-discovered from running server **Aliases:** `lmstudio`, `lms` **Strengths:** - **Completely FREE** (local execution via LM Studio desktop app) - Maximum privacy — no data sent to cloud - Auto-discovers the currently loaded model via `/v1/models` - Vision supported on compatible models (LLaVA, Llama 3.2 Vision, Qwen-VL, etc.) - Tool calling supported on compatible models **Weaknesses:** - Requires LM Studio app and a loaded model - Model quality and capability depend entirely on what is loaded - No PDF support - Small local models may give inconsistent structured output **Best For:** - Privacy-critical local inference - Offline / air-gapped environments - Development and experimentation without cloud costs - Testing multiple open-weight models via a GUI **Pricing:** - **FREE** (hardware costs only) - Requires local GPU for best performance --- ### 17. llama.cpp **Provider ID:** `llamacpp` **Default Model:** Auto-discovered from running llama-server **Aliases:** `llama.cpp`, `llama-cpp` **Strengths:** - **Completely FREE** (local execution via llama-server) - Maximum privacy — no data sent to cloud - GGUF model support — run quantized models on CPU or GPU - Auto-discovers loaded model via `/v1/models` - Vision supported on compatible models (LLaVA, Llama 3.2 Vision) - Tool calling supported when server started with `--jinja` flag **Weaknesses:** - Requires building / downloading llama-server and a GGUF model - Tool calling requires `--jinja` flag at server startup - Model quality depends on the GGUF model loaded - No PDF support - Small local models may give inconsistent structured output **Best For:** - Maximum privacy and air-gapped deployments - CPU inference without a GPU - Running heavily quantized models at low resource cost - Power users who want direct control over model serving **Pricing:** - **FREE** (hardware costs only) - No API costs or rate limits --- --- ## Voice Providers Voice providers handle audio I/O and are distinct from LLM text-generation providers. They are categorised by function: Text-to-Speech (TTS), Speech-to-Text (STT), and Realtime (bidirectional audio over WebSocket). | Provider | Type | Protocol | Streaming | Formats | Auth | | ------------------- | -------- | ---------------- | --------- | ----------------------------------------------------- | -------------------------------------------------- | | **google-ai** (TTS) | TTS | REST (gRPC SDK) | No | MP3, WAV, OGG | Service Account (`GOOGLE_APPLICATION_CREDENTIALS`) | | **openai-tts** | TTS | REST | No | MP3, WAV, OGG, Opus | API Key | | **elevenlabs** | TTS | REST | No | MP3, WAV (PCM), Opus | API Key | | **azure-tts** | TTS | REST | No | MP3, WAV (PCM), Opus | API Key + Region | | **whisper** | STT | REST | No | WAV, MP3, M4A, FLAC, OGG, Opus, WebM, MP4, MPEG, MPGA | API Key | | **google-stt** | STT | REST | No | WAV, FLAC, MP3, OGG | API Key or Service Account | | **deepgram** | STT | REST + WebSocket | Yes | WAV, MP3, OGG, FLAC | API Key | | **azure-stt** | STT | REST | No | WAV¹, OGG, Opus | API Key + Region | | **openai-realtime** | Realtime | WebSocket | Yes | PCM16, WAV, Opus | API Key | | **gemini-live** | Realtime | WebSocket | Yes | WAV, Opus | API Key (or Service Account) | ¹ Azure STT's short-audio REST endpoint does not decode MP3 — passing `format: "mp3"` to `azure-stt` throws `STT_INVALID_AUDIO_FORMAT` early. Convert to WAV first (`ffmpeg -i in.mp3 -ar 16000 -ac 1 out.wav`) or use a different STT provider for MP3 input. See `docs/getting-started/providers/azure-speech.md`. **Legend:** - **TTS** — Text-to-Speech: converts text to audio - **STT** — Speech-to-Text: transcribes audio to text - **Realtime** — Bidirectional voice session with the model over a persistent WebSocket See also: [Voice Provider Selection](#voice-provider-selection) | [Voice Providers Index](/docs/getting-started/providers/index.md#voice-providers) --- ## Use Case Recommendations ### For Startups (Limited Budget) ** Best Choice: Google AI Studio** - Generous FREE tier (1M tokens/day) - Extended thinking support - PDF processing - Professional quality ** Alternative: OpenRouter** - Many free models - Access to premium models when needed - Cost tracking ** Alternative: Mistral** - Competitive pricing - Good quality - GDPR compliant --- ### For Enterprises ** Best Choice: Amazon Bedrock** - Enterprise security (AWS) - Multiple model providers - HIPAA/SOC2 compliant - SLAs available ** Alternative: Azure OpenAI** - Microsoft ecosystem integration - Enterprise security - SLA guarantees ** Alternative: Google Vertex** - GCP integration - Dual provider (Gemini + Claude) - Enterprise-grade --- ### For Privacy-Conscious Users ** Best Choice: Ollama** - 100% local execution - No data sent to cloud - Works offline - Completely FREE ** Alternative: LM Studio** - 100% local execution via desktop app - No data sent to cloud - GUI-driven model management ** Alternative: llama.cpp** - 100% local execution — even CPU-only deployments - Maximum control over model serving - Completely FREE **Also Consider: Mistral** - GDPR compliant - European data centers - No training on user data --- ### For Developers/Researchers ** Best Choice: HuggingFace** - 100,000+ models - Open-source focus - Cutting-edge research models - Community support ** Alternative: LiteLLM** - Test multiple providers easily - Cost tracking - Unified interface --- ### For Complex Reasoning ** Best Choice: Anthropic** - **Extended thinking** (best) - 200K context window - Native PDF support - Advanced tool use ** Alternative: Google AI Studio** - Extended thinking (Gemini 2.5+, 3) - FREE tier - PDF support --- ### For Multimodal (Vision + Text + PDF) ** Best Choice: Anthropic** - Best vision quality (20 images) - Native PDF support - Extended thinking ** Alternative: Google AI Studio** - Good vision (16 images) - PDF support - Extended thinking - FREE tier ** Alternative: OpenAI** - Excellent vision (10 images) - Industry-leading quality - No PDF support --- ## Cost Optimization Strategies ### 1. Tier-Based Strategy ```typescript // Use free tier for development const devProvider = "google-ai"; // FREE // Use mid-tier for staging const stagingProvider = "mistral"; // Low cost // Use premium for production const prodProvider = "anthropic"; // High quality ``` ### 2. Task-Based Routing ```typescript // Simple tasks → Cheap models if (taskComplexity === "simple") { provider = "google-ai"; // FREE Gemini Flash } // Complex reasoning → Premium models if (taskComplexity === "complex") { provider = "anthropic"; // Extended thinking } // Vision tasks → Vision-capable models if (hasImages) { provider = "openai"; // Good vision } ``` ### 3. Hybrid Approach ```typescript // Use local for privacy-sensitive if (sensitiveData) { provider = "ollama"; // Local, FREE — or "lm-studio" / "llamacpp" } // Use cloud for complex tasks if (needsAdvancedReasoning) { provider = "anthropic"; // Extended thinking } // Use DeepSeek for cost-efficient reasoning if (needsReasoningButBudgetConstrained) { provider = "deepseek"; // Low-cost frontier-quality reasoning model = "deepseek-reasoner"; } ``` --- ## Quick Decision Tree ``` Need highest quality? ├─ Yes → OpenAI or Anthropic └─ No → Continue │ Need extended thinking? ├─ Yes → Anthropic (best) or Google AI Studio (free) └─ No → Continue │ Need complete privacy? ├─ Yes → Ollama / LM Studio / llama.cpp (local, free) └─ No → Continue │ Need PDF processing? ├─ Yes → Anthropic or Google AI Studio or Vertex └─ No → Continue │ On AWS? ├─ Yes → Bedrock └─ No → Continue │ On Azure? ├─ Yes → Azure OpenAI └─ No → Continue │ Need free tier? ├─ Yes → Google AI Studio (best) or Anthropic (OAuth) or OpenRouter or HuggingFace └─ No → Continue │ Need EU compliance? ├─ Yes → Mistral AI (GDPR) └─ No → Continue │ Need many models? ├─ Yes → OpenRouter (300+ models) or HuggingFace (100k+ models) └─ No → OpenAI (industry standard) ``` --- ## Security & Compliance ### Most Secure 1. **Ollama** - Completely local, no cloud transmission 2. **Azure OpenAI** - Enterprise security, Microsoft backing 3. **Amazon Bedrock** - AWS security features, HIPAA-ready ### Compliance Certifications | Provider | GDPR | HIPAA | SOC2 | ISO 27001 | | ---------------- | ---- | ----- | ---- | --------- | | OpenAI | ✓ | ✓\* | ✓ | ✓ | | Anthropic ^3^ | ✓ | ✓\* | ✓ | ✓ | | Google AI Studio | ✓ | ✗ | ✓ | ✓ | | Google Vertex | ✓ | ✓\* | ✓ | ✓ | | Amazon Bedrock | ✓ | ✓\* | ✓ | ✓ | | Azure OpenAI | ✓ | ✓\* | ✓ | ✓ | | Mistral | ✓ | ✗ | ✓ | ✓ | | Ollama | ✓ | ✓ | N/A | N/A | \* HIPAA compliance requires Business Associate Agreement (BAA) ^3^ Anthropic supports API Key and OAuth 2.0 authentication. OAuth uses PKCE flow with automatic token refresh. Credentials stored in `~/.neurolink/tokens.json` with 0600 permissions. --- ## Performance Benchmarks ### Average Latency (Time to First Token) | Provider | TTFT (ms) | Tokens/sec | Quality Score | | ---------------- | --------- | ---------- | ------------- | | Ollama (local) | 50-200 | 30-50 | 8.5/10 | | OpenAI | 300-800 | 40-60 | 9.5/10 | | Anthropic | 400-900 | 35-55 | 9.4/10 | | Google AI Studio | 300-700 | 45-65 | 9.0/10 | | Azure OpenAI | 350-850 | 40-60 | 9.5/10 | | Mistral | 300-700 | 40-55 | 8.8/10 | | OpenRouter | 400-1000 | 30-50 | 8.5-9.5/10 | _Note: Benchmarks vary by model, region, and load_ --- ## Migration Guide ### From OpenAI to Anthropic **Why migrate:** - Extended thinking - PDF support - Better for complex analysis - Subscription-based pricing option (Pro $20/mo, Max $100+/mo) as alternative to per-token **Code changes:** ```typescript // Before const result = await neurolink.generate({ provider: "openai", model: "gpt-4o", prompt: "Analyze this document", }); // After (API key auth - same as before) const result = await neurolink.generate({ provider: "anthropic", model: "claude-sonnet-4-6", prompt: "Analyze this document", thinkingLevel: "high", // New capability }); // After (OAuth subscription auth - auto-detected from stored credentials) // Run `neurolink auth login --provider anthropic` first to authenticate const result = await neurolink.generate({ provider: "anthropic", model: "claude-sonnet-4-6", prompt: "Analyze this document", thinkingLevel: "high", }); ``` ### From Paid to Free (Google AI Studio) **Why migrate:** - FREE tier (1M tokens/day) - Extended thinking - PDF support **Cost savings:** - OpenAI GPT-4o: ~$15/day for 1M tokens - Google AI Studio: **$0/day for 1M tokens** - **Savings: $450/month** --- ## Voice Provider Selection ### Text-to-Speech (TTS) **Best quality: `openai-tts` with model tts-1-hd** ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Hello, world!" }, tts: { enabled: true, provider: "openai-tts", voice: "nova", model: "tts-1-hd", }, }); // result.audio contains the synthesized speech ``` **Best multilingual: `elevenlabs`** ElevenLabs supports the widest range of languages and voice cloning, making it the default choice for multilingual or branded voice experiences. ```typescript const result = await neurolink.generate({ input: { text: "Hola, ¿cómo estás?" }, tts: { enabled: true, provider: "elevenlabs", voice: "your-voice-id" }, }); ``` **Most cost-effective: `google-ai` (1M chars free tier)** Google Cloud Text-to-Speech provides a generous free tier (1M characters/month for standard voices) and is ideal for high-volume applications on GCP. ```typescript const result = await neurolink.generate({ input: { text: "Cost-effective synthesis at scale." }, tts: { enabled: true, provider: "google-ai", voice: "en-US-Standard-A" }, }); ``` **Enterprise: `azure-tts` (SSML support)** Azure Cognitive Services TTS has the most comprehensive SSML support, including fine-grained prosody control, making it the standard choice for enterprise IVR and accessibility pipelines. ```typescript const result = await neurolink.generate({ input: { text: "Welcome to Neurolink." }, tts: { enabled: true, provider: "azure-tts", voice: "en-US-AriaNeural" }, }); ``` --- ### Speech-to-Text (STT) **Best accuracy: `whisper` (OpenAI)** OpenAI Whisper consistently ranks highest on transcription benchmarks across languages and noisy environments. ```typescript const result = await neurolink.generate({ input: { text: "" }, stt: { enabled: true, provider: "whisper", audio: audioBuffer }, }); // result.transcription.text contains the transcribed text ``` **Best streaming: `deepgram` (WebSocket real-time)** Deepgram is the only STT provider with native WebSocket streaming support, enabling sub-300 ms word-level transcription for live audio. ```typescript const result = await neurolink.generate({ input: { text: "" }, stt: { enabled: true, provider: "deepgram", audio: audioBuffer }, }); ``` **Best for Google Cloud users: `google-stt`** Tight integration with GCP infrastructure, support for 125+ languages, and speaker diarization make `google-stt` the natural choice when already on Google Cloud. ```typescript const result = await neurolink.generate({ input: { text: "" }, stt: { enabled: true, provider: "google-stt", audio: audioBuffer }, }); ``` **Enterprise: `azure-stt`** Azure Cognitive Services STT offers custom model training, batch transcription, and fine-grained compliance controls for regulated industries. ```typescript const result = await neurolink.generate({ input: { text: "" }, stt: { enabled: true, provider: "azure-stt", audio: audioBuffer }, }); ``` --- ## Conclusion **Choose based on priorities:** 1. **Budget Priority** → Google AI Studio (free) or OpenRouter (free models) or Anthropic Free tier (via OAuth) 2. **Quality Priority** → OpenAI or Anthropic 3. **Privacy Priority** → Ollama / LM Studio / llama.cpp (local) 4. **Reasoning Priority** → Anthropic (extended thinking) or DeepSeek-R1 (cost-efficient) 5. **Document Priority** → Anthropic or Google AI Studio (PDF support) 6. **Compliance Priority** → Azure OpenAI or Bedrock 7. **Flexibility Priority** → OpenRouter (300+ models) or NVIDIA NIM (curated NVIDIA-hosted models) 8. **Flat-Rate Pricing** → Anthropic subscription (Pro $20/mo, Max $100+/mo) 9. **Zero Cloud Cost** → LM Studio or llama.cpp (local execution) 10. **TTS Quality** → `openai-tts` (tts-1-hd) or `elevenlabs` (multilingual) 11. **TTS Cost** → `google-ai` TTS (1M chars/month free tier) 12. **STT Accuracy** → `whisper` (OpenAI) 13. **STT Streaming** → `deepgram` (WebSocket, sub-300 ms) 14. **Realtime Voice** → `openai-realtime` or `gemini-live` **NeuroLink Advantage:** - Switch providers anytime (single line of code) - Use multiple providers simultaneously - Test and compare providers easily - No vendor lock-in See also: - [Provider Capabilities Audit](/docs/reference/provider-capabilities-audit) - Detailed technical capabilities - [Provider Selection Wizard](/docs/reference/provider-selection) - Interactive decision guide - [Claude Subscription Support](/docs/features/claude-subscription) - OAuth authentication and subscription tiers for Anthropic - [Voice Provider Selection](/docs/reference/provider-comparison#voice-provider-selection) - TTS, STT, and Realtime provider recommendations - [Voice Providers Index](/docs/getting-started/providers/index.md#voice-providers) - Voice provider setup cards --- ## Provider Feature Compatibility Reference # Provider Feature Compatibility Reference > This is a dated point-in-time test run covering the providers listed below, not the broader set of provider integrations NeuroLink ships today. For the current roster, see [Provider Setup](/docs/getting-started/provider-setup) and the [Provider Capabilities Audit](/docs/reference/provider-capabilities-audit). **Last Updated:** 2025-12-31 **Test Suite:** continuous-test-suite.ts (19 comprehensive tests) **Providers Tested:** 11 providers across CSV, PDF, MCP tools, business tools, and enterprise features ----------------- | ------------ | -------- | ---------- | --------------------------------------------- | | **Google AI Studio** | 19/19 (100%) | 401s | ✅ Perfect | Fast prototyping, full multimodal support | | **Vertex AI** | 19/19 (100%) | 449s | ✅ Perfect | Enterprise deployments, excellent performance | | **OpenAI** | 19/19 (100%) | 1413s | ✅ Perfect | Industry standard, comprehensive features | | **LiteLLM** | 19/19 (100%) | 552s | ✅ Perfect | Universal proxy for 100+ models | **All features supported:** - ✅ CSV processing (6/6 tests) - ✅ PDF processing (6/6 tests) - ✅ MCP external tools (4/4 tests) - ✅ Business tools (2/2 tests) - ✅ Enterprise features (1/1 test) --- ## Complete Feature Support Matrix | Provider | CSV | PDF | MCP Tools | Business Tools | Structured Output | Enterprise | Score | Status | | -------------------- | -------- | ------ | --------- | -------------- | ----------------- | ---------- | --------- | ------------ | | **Google AI Studio** | ✅ 6/6 | ✅ 6/6 | ✅ 4/4 | ✅ 2/2 | ⚠️ Partial\* | ✅ 1/1 | **19/19** | Production | | **Vertex AI** | ✅ 6/6 | ✅ 6/6 | ✅ 4/4 | ✅ 2/2 | ⚠️ Partial\* | ✅ 1/1 | **19/19** | Production | | **LiteLLM** | ✅ 6/6 | ✅ 6/6 | ✅ 4/4 | ✅ 2/2 | ✅ Full | ✅ 1/1 | **19/19** | Production | | **OpenAI** | ✅ 6/6 | ✅ 6/6 | ✅ 4/4 | ✅ 2/2 | ✅ Full | ✅ 1/1 | **19/19** | Production | | **Azure OpenAI** | ✅ 6/6 | ❌ 0/6 | ✅ 4/4 | ✅ 2/2 | ✅ Full | ✅ 1/1 | 13/19 | Production\* | | **Mistral** | ✅ 6/6 | ❌ 0/6 | ⚠️ 2/4 | ❌ 0/2 | ✅ Full | ✅ 1/1 | 9/19 | Development | | **Ollama** | ⚠️ 3/6 | ⚠️ 1/6 | ❌ 0/4 | ❌ 0/2 | ⚠️ Limited | ✅ 1/1 | 7/19 | Development | | **Anthropic** | 0/6 | 0/6 | 0/4 | 0/2 | ✅ Full | ✅ 1/1 | 2/19\*\* | Config | | **Bedrock** | 0/6 | 0/6 | 0/4 | 0/2 | ✅ Full | ✅ 1/1 | 2/19\*\* | Config | | **Hugging Face** | 0/6 | 0/6 | 0/4 | 0/2 | ⚠️ Limited | ✅ 1/1 | 2/19\*\* | Config | | **SageMaker** | 0/6 | 0/6 | 0/4 | 0/2 | ⚠️ Limited | ✅ 1/1 | 2/19\*\* | Config | | **DeepSeek** | ✅ 6/6 | ❌ 0/6 | ✅ 4/4 | ✅ 2/2 | ✅ Full | ✅ 1/1 | N/A† | Cloud | | **NVIDIA NIM** | ✅ 6/6 | ❌ 0/6 | ⚠️ Model | ⚠️ Model | ⚠️ Model | ✅ 1/1 | N/A† | Cloud | | **LM Studio** | ⚠️ Model | ❌ 0/6 | ⚠️ Model | ⚠️ Model | ⚠️ Model | ✅ 1/1 | N/A† | Local | | **llama.cpp** | ⚠️ Model | ❌ 0/6 | ⚠️ Model | ⚠️ Model | ⚠️ Model | ✅ 1/1 | N/A† | Local | \*Google providers: Cannot combine tools + schemas (use `disableTools: true`). Google API limitation, not NeuroLink bug. †Not yet run through the standard 19-test suite. Capability flags based on provider source code audit (PR #997). **Legend:** - ✅ Fully supported - ⚠️ Partially supported - ❌ Not supported (technical limitation) - Configuration/billing issue - \* Production-ready for non-PDF workloads - \*\* Configuration issue, not technical limitation --- ## Model-Level Feature Compatibility ### Gemini 3 Models | Model | Streaming | Tools | Vision | Extended Thinking | JSON Schema | | ------------------ | --------- | ----- | ------ | ----------------- | ----------- | | **gemini-3-flash** | ✓ | ✓ | ✓ | ✓ | ✓† | | **gemini-3-pro** | ✓ | ✓ | ✓ | ✓ | ✓† | †**JSON Schema Limitation:** Gemini 3 models support JSON Schema for structured output, but **cannot combine tools with JSON Schema** in the same request. When using structured output with a schema, you must disable tools by setting `disableTools: true`. This is a Google API limitation, not a NeuroLink bug. **Example Usage:** ```typescript // Structured output with JSON Schema (tools must be disabled) await neurolink.generate({ prompt: "Extract user information", schema: UserSchema, provider: "google-ai-studio", model: "gemini-3-flash", disableTools: true, // Required when using schema }); // Tools work normally without schema await neurolink.generate({ prompt: "Search for documents", provider: "google-ai-studio", model: "gemini-3-pro", // Tools enabled by default }); ``` --- ## Provider Tier Classification ### Tier 1: Perfect (100%) - Production Ready for All Features ⭐⭐⭐ **Recommended for production use with full feature support** #### Google AI Studio - **Score:** 19/19 (100%) - **Duration:** 401 seconds - **Strengths:** Fastest test execution, reliable, full multimodal support - **Use Cases:** - Rapid prototyping with free tier - Production deployments requiring speed - Full CSV + PDF + image processing - MCP tool integration - **Setup:** Simple API key configuration #### Vertex AI - **Score:** 19/19 (100%) - **Duration:** 449 seconds - **Strengths:** Enterprise-grade, excellent performance, Google Cloud integration - **Use Cases:** - Enterprise deployments with SLA requirements - Google Cloud Platform integration - Multi-region deployments - Advanced analytics pipelines - **Setup:** GCP service account or ADC #### OpenAI - **Score:** 19/19 (100%) - **Duration:** 1413 seconds (slower due to rate limits) - **Strengths:** Industry standard, comprehensive ecosystem, extensive documentation - **Use Cases:** - Production applications requiring proven stability - Integration with OpenAI ecosystem - GPT-4o and o1 model access - **Setup:** API key configuration - **Note:** Longer duration due to conservative rate limiting (30,000 TPM) #### LiteLLM - **Score:** 19/19 (100%) - **Duration:** 552 seconds - **Strengths:** Universal proxy for 100+ models, automatic load balancing - **Use Cases:** - Multi-provider routing and fallback - Access to 100+ models through single interface - Cost optimization across providers - Load balancing and caching - **Setup:** LiteLLM proxy server + provider credentials ### Structured Output Support Details **Full Support (✅):** - OpenAI, Anthropic, Azure OpenAI, Bedrock, Mistral, LiteLLM - Can use tools and schemas simultaneously - No configuration required **Partial Support (⚠️):** - **Google AI Studio** and **Vertex AI (Gemini models)** - **Limitation:** Cannot combine tools with schemas - **Solution:** Use `disableTools: true` when using schemas - **Reason:** Google API limitation (documented by Google) - **Future:** Future Gemini versions may support both - check official documentation for updates **Example:** ```typescript // Google providers require disableTools await neurolink.generate({ schema: MySchema, provider: "vertex", disableTools: true, // Required for Google }); // Other providers work without restriction await neurolink.generate({ schema: MySchema, provider: "openai", // No restriction }); ``` --- ### Tier 2: Good (68%) - Production Ready for CSV + Tools ⭐⭐ **Recommended for production use when PDF support is not required** #### Azure OpenAI - **Score:** 13/19 (68.4%) - **Duration:** 351 seconds - **Status:** ⚠️ Production-ready with limitations **✅ Passing Tests (13/19):** - ✅ CSV processing (6/6) - All CSV tests pass - ✅ MCP external tools (4/4) - Full tool integration support - ✅ Business tools (2/2) - Custom tool execution works - ✅ Enterprise features (1/1) - Proxy and compliance support **❌ Failing Tests (6/19):** - ❌ All PDF tests (6/6) - Model limitation - CLI Generate PDF - CLI Stream PDF - CLI Stream Two PDF Comparison - CLI Stream PDF and CSV - SDK Generate PDF - SDK Stream PDF **Root Cause:** ``` Error: Invalid Value: 'file'. This model does not support file content types. ``` **Technical Explanation:** Azure OpenAI models reject the `file` content type that PDF processing requires — the error above comes from the model API itself. This is a **model architecture limitation**, not a configuration issue. **Production Recommendation:** - ✅ Use for: CSV data analysis, MCP tool integration, business logic - ❌ Avoid for: PDF processing - Fallback strategy: Use Vertex AI or Google AI Studio for PDF requirements --- ### Tier 3: Partial (36-47%) - Development/Testing Only ⭐ **NOT recommended for production use - limited feature support** #### Mistral AI - **Score:** 9/19 (47.4%) - **Duration:** 363 seconds - **Status:** ⚠️ Development/testing only **✅ Passing Tests (9/19):** - ✅ CSV processing (6/6) - All CSV tests pass - ✅ SDK tools (2/2) - SDK Generate and Stream work - ✅ Enterprise features (1/1) - Proxy support **❌ Failing Tests (10/19):** - ❌ All PDF tests (6/6) - API limitation - ❌ CLI external tools (2/2) - CLI tool integration issues - ❌ Business tools (2/2) - Limited tool support **Root Cause (PDF failures):** ``` Error: UnsupportedFunctionalityError: 'File content parts in user messages' functionality not supported. ``` **Technical Explanation:** Mistral's API fundamentally does not support file content parts in user messages. This is a **core API limitation**, not a bug or configuration issue. **Production Recommendation:** - ✅ Use for: CSV data analysis in SDK mode - ❌ Avoid for: PDF processing, CLI tool integration - Reference: See `MISTRAL_PDF_FIX_SUMMARY.md` for detailed investigation #### Ollama - **Score:** 7/19 (36.8%) - **Duration:** 1236 seconds - **Status:** ⚠️ Local development only **✅ Passing Tests (7/19):** - ✅ Some CSV tests (3/6) - Partial support - ✅ SDK tools (2/2) - Basic tool execution - ✅ CLI Stream PDF and CSV (1/1) - Limited multimodal - ✅ Enterprise features (1/1) - Local proxy support **❌ Failing Tests (12/19):** - ❌ Most CSV tests (3/6) - Inconsistent results - ❌ Most PDF tests (5/6) - Model-dependent - ❌ CLI external tools (2/2) - Tool integration issues - ❌ Business tools (2/2) - Limited support **Technical Explanation:** Ollama is designed for local model execution. Performance and feature support varies significantly based on the specific model being used (Llama, Mistral, etc.). **Production Recommendation:** - ✅ Use for: Local development, privacy-critical testing - ❌ Avoid for: Production workloads, consistent behavior requirements - Best for: Experimentation with local models --- ### Tier 4: Limited (10.5%) - Configuration Issues Only **Configuration/billing issues preventing testing - NOT technical limitations** These providers are currently limited to 2/19 tests passing due to configuration or billing issues, **not technical capabilities**. With proper setup, they are expected to achieve much higher compatibility scores. | Provider | Score | Issue Type | Fix Required | Expected Score After Fix | | ---------------- | ------------ | -------------- | ------------------ | ------------------------ | | **Anthropic** | 2/19 (10.5%) | Billing | Add API credits | 90%+ (full multimodal) | | **Bedrock** | 2/19 (10.5%) | Credentials | Fix AWS token | 70%+ (model-dependent) | | **Hugging Face** | 2/19 (10.5%) | Billing | Add payment method | 60%+ (model-dependent) | | **SageMaker** | 2/19 (10.5%) | Credentials | Fix AWS token | 60%+ (model-dependent) | #### Anthropic (Claude) - API Credit Exhaustion **Error:** ``` APICallError: Your credit balance is too low to access the Anthropic API. Please go to Plans & Billing to upgrade or purchase credits. ``` **Status:** All 17 test failures are due to insufficient API credits, **NOT** technical limitations. **Passing Tests (2/19):** - ✅ CLI Stream CSV and Screenshot (skipped - no fixture available) - ✅ Enterprise Proxy Support (no API call required) **Expected Capability:** Anthropic Claude models (3.5 Sonnet, 3.7 Sonnet) support multimodal content including images and PDFs. Expected to achieve **90%+ compatibility** once credits are added. **Fix:** Add credits at https://console.anthropic.com/settings/plans #### AWS Bedrock - Credential Issue **Error:** ``` BedrockServiceException: The security token included in the request is invalid Region: ap-south-1 ``` **Status:** AWS credentials are invalid or expired. **Passing Tests (2/19):** - ✅ CLI Stream CSV and Screenshot (skipped) - ✅ Enterprise Proxy Support **Expected Capability:** Bedrock provides access to multiple foundation models (Claude, Llama, Titan) and should support multimodal features once credentials are configured. Expected **70%+ compatibility** (varies by model). **Fix:** ```bash # Check current credentials aws sts get-caller-identity # Configure valid credentials aws configure ``` #### Hugging Face - Payment Required **Error:** ``` APICallError: Payment Required ``` **Status:** Payment/billing configuration needed. **Passing Tests (2/19):** - ✅ CLI Stream CSV and Screenshot (skipped) - ✅ Enterprise Proxy Support **Expected Capability:** Hugging Face provides access to open-source models via inference endpoints. Multimodal support depends on selected model. Expected **60%+ compatibility** after billing setup. **Fix:** Add payment method to Hugging Face account #### AWS SageMaker - Credential Issue **Error:** ``` SageMaker endpoint invocation failed: The security token included in the request is invalid ``` **Status:** AWS credentials are invalid or expired (same as Bedrock). **Passing Tests (2/19):** - ✅ CLI Stream CSV and Screenshot (skipped) - ✅ Enterprise Proxy Support **Expected Capability:** SageMaker allows deployment of custom models. Feature support depends on the deployed model. Expected **60%+ compatibility** after credential fix. **Fix:** Update AWS credentials (same as Bedrock) --- ## Technical Limitations Summary ### Azure OpenAI - **Limitation:** Model does not support file content type for PDFs - **Impact:** Cannot process PDF documents natively - **Workaround:** Extract text from PDFs before sending to Azure, or use fallback provider - **Affected Features:** All PDF processing (6 tests) ### Mistral - **Limitation:** API does not support file content parts in user messages - **Impact:** Cannot process PDF documents at all - **Workaround:** None available - fundamental API limitation - **Affected Features:** All PDF processing (6 tests), CLI tool integration (2 tests) - **Reference:** See `MISTRAL_PDF_FIX_SUMMARY.md` for investigation details ### Ollama - **Limitation:** Local model performance varies significantly by model - **Impact:** Inconsistent results across different models and operations - **Workaround:** Carefully select models, use for development/testing only - **Affected Features:** Various tests show inconsistent behavior ### DeepSeek - **Limitation:** No vision / multimodal support; no PDF support - **Impact:** Cannot process images or documents - **Workaround:** Use OpenAI or Anthropic for vision/PDF workflows; DeepSeek for text-only tasks - **Affected Features:** All PDF tests (6/6), image processing ### NVIDIA NIM - **Limitation:** Tool calling and vision are model-dependent; no PDF support - **Impact:** Not all hosted models support tools or vision - **Workaround:** Choose a tool-capable model (e.g., Llama 3.3 70B Instruct); use a vision-capable model for multimodal tasks - **Affected Features:** Model-dependent — check https://build.nvidia.com/models for capabilities per model ### LM Studio - **Limitation:** All capabilities depend on the currently loaded model; requires LM Studio app running - **Impact:** ECONNREFUSED error if app is not started or no model is loaded - **Workaround:** Start LM Studio, load a model, click "Start Server" - **Affected Features:** CSV/PDF/tool support all model-dependent; structured output reliability varies on small models ### llama.cpp - **Limitation:** Tool calling requires `--jinja` server flag; all capabilities depend on loaded GGUF model; requires llama-server process running - **Impact:** 400 error on tool calls if server was not started with `--jinja`; ECONNREFUSED if server is not running - **Workaround:** Start llama-server with: `./llama-server -m model.gguf --port 8080 --jinja` - **Affected Features:** Tool support model + flag dependent; structured output reliability varies on small quantized models --- ## Production Deployment Recommendations ### For Maximum Feature Compatibility (100%) **Recommended Providers:** - **Google AI Studio** - Best for: Speed, free tier, prototyping - **Vertex AI** - Best for: Enterprise, GCP integration, SLA requirements - **OpenAI** - Best for: Proven stability, ecosystem integration - **LiteLLM** - Best for: Multi-provider routing, 100+ model access **All features available:** - ✅ CSV data analysis - ✅ PDF document processing - ✅ Image analysis - ✅ MCP external tool integration - ✅ Custom business tools - ✅ Enterprise proxy support ### For CSV + Tools (No PDFs Required) **Recommended Providers:** - **Azure OpenAI** - Best for: Microsoft ecosystem, enterprise security, Azure integration **Features available:** - ✅ CSV data analysis (68% compatibility) - ✅ MCP external tools - ✅ Custom business tools - ✅ Enterprise features - ❌ PDF processing (use fallback provider) **Fallback Strategy:** ```typescript // Primary provider for CSV and tools const primaryProvider = "azure"; // Fallback to Vertex for PDF processing const pdfProvider = "vertex"; if (hasPDFFiles(input)) { result = await neurolink.generate({ ...options, provider: pdfProvider }); } else { result = await neurolink.generate({ ...options, provider: primaryProvider }); } ``` ### For Development/Testing **Recommended Providers:** - **Mistral** - Best for: CSV-only workflows, European compliance - **Ollama** - Best for: Local development, privacy testing **Use Cases:** - CSV data analysis only - Privacy-critical testing - Local development without cloud dependencies - Experimentation with different models **Not Recommended For:** - Production deployments - PDF processing requirements - Critical business workflows --- ## Test Suite Details ### Test Categories (19 total tests) #### CSV Processing Tests (6 tests) 1. CLI Generate CSV - Generate mode with CSV input 2. CLI Stream CSV - Streaming mode with CSV input 3. CLI Stream Two CSV Comparison - Compare multiple CSV files 4. CLI Stream CSV and Screenshot - Mixed CSV and image analysis 5. SDK Generate CSV - SDK generate with CSV 6. SDK Stream CSV - SDK streaming with CSV #### PDF Processing Tests (6 tests) 7. CLI Generate PDF - Generate mode with PDF input 8. CLI Stream PDF - Streaming mode with PDF input 9. CLI Stream Two PDF Comparison - Compare multiple PDF files 10. CLI Stream PDF and CSV - Mixed PDF and CSV analysis 11. SDK Generate PDF - SDK generate with PDF 12. SDK Stream PDF - SDK streaming with PDF #### MCP External Tools Tests (4 tests) 13. CLI Generate - External MCP tools via CLI generate 14. CLI Stream - External MCP tools via CLI stream 15. SDK Generate - External MCP tools via SDK generate 16. SDK Stream - External MCP tools via SDK stream #### Business Tools Tests (2 tests) 17. SDK Business Tools - Custom tool registration and execution 18. CLI Business Tools - Custom tools via CLI interface #### Enterprise Features Tests (1 test) 19. Enterprise Proxy Support - Proxy configuration and environment handling ### Test Execution **Sequential Execution:** Tests run one provider at a time to avoid resource contention and rate limit issues. **Rate Limiting:** - OpenAI: 60-second delay between tests (30,000 TPM limit) - Other providers: 10-second delay between tests **Total Duration:** Approximately 30-40 minutes for all 11 providers --- ## Configuration Fixes Needed ### Immediate Actions Required 1. **Anthropic:** Add API credits - URL: https://console.anthropic.com/settings/plans - Expected improvement: 2/19 → 17+/19 (90%+) 2. **Bedrock:** Fix AWS credentials ```bash aws configure # Or update AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY ``` - Expected improvement: 2/19 → 13+/19 (70%+) 3. **SageMaker:** Fix AWS credentials (same as Bedrock) - Expected improvement: 2/19 → 11+/19 (60%+) 4. **Hugging Face:** Add payment method - URL: https://huggingface.co/settings/billing - Expected improvement: 2/19 → 11+/19 (60%+) ### No Fix Available 1. **Azure OpenAI:** PDF limitation is a model architecture constraint - Recommendation: Use for CSV and tools, fallback to Vertex/Google AI Studio for PDFs 2. **Mistral:** PDF limitation is a fundamental API constraint - Recommendation: Use for CSV-only workflows in SDK mode --- ## Test Logs All test logs are available in `/tmp/neurolink-sequential-tests/`: - `test-openai.log` - OpenAI 19/19 (100%) - `test-vertex.log` - Vertex 19/19 (100%) - `test-google-ai-studio.log` - Google AI Studio 19/19 (100%) - `test-litellm.log` - LiteLLM 19/19 (100%) - `test-azure.log` - Azure 13/19 (68%) - `test-mistral.log` - Mistral 9/19 (47%) - `test-ollama.log` - Ollama 7/19 (37%) - `test-anthropic.log` - Anthropic 2/19 (billing issue) - `test-bedrock.log` - Bedrock 2/19 (credential issue) - `test-huggingface.log` - Hugging Face 2/19 (billing issue) - `test-sagemaker.log` - SageMaker 2/19 (credential issue) --- ## Recent Fixes and Improvements ### Fix 1: File Handling System Prompt Enhancement (2025-11-02) **Providers affected:** OpenAI, Vertex AI **Issue:** AI attempting to use GitHub MCP `get_file_contents` for local files **Root Cause:** File paths visible in context, AI confused about tool usage **Solution:** Enhanced system prompt in `src/lib/utils/messageBuilder.ts` (lines 622-657) with file handling guidance: ```typescript if (hasCSVFiles || hasPDFFiles) { systemPrompt += `\n\nIMPORTANT FILE HANDLING INSTRUCTIONS: - File content (${fileTypes.join(", ")}, images) is already processed and included in this message - DO NOT use GitHub tools (get_file_contents, search_code, etc.) for local files - Analyze the provided file content directly without attempting to fetch files - GitHub MCP tools are ONLY for remote repository operations - Use the file content shown in this message for your analysis`; } ``` **Result:** - OpenAI: 18/19 → 19/19 (100%) - Vertex: CLI Stream PDF and CSV test passing ### Fix 2: Case-Insensitive Test Validation (2025-11-02) **Provider affected:** Vertex AI **Issue:** Test expecting "strict" but Vertex responding "Strict mode" **Root Cause:** Case-sensitive string matching with provider-specific capitalization **Solution:** Case-insensitive comparison in `test/continuous-test-suite.ts` (lines 801-806): ```typescript // Before const foundData = expectedData.filter((data) => result.content.includes(data)); // After const contentLower = result.content.toLowerCase(); const foundData = expectedData.filter((data) => contentLower.includes(data.toLowerCase()), ); ``` **Result:** Vertex: 18/19 → 19/19 (100%) --- ## Conclusion **Primary Achievement:** ✅ **4 providers at 100% compatibility** The comprehensive testing reveals a mature ecosystem with multiple production-ready providers. Most "failures" are configuration/billing issues rather than technical limitations. **Key Insights:** 1. **Production-Ready Options:** 4 providers (Google AI Studio, Vertex AI, OpenAI, LiteLLM) provide full feature support 2. **Partial Support is Useful:** Azure OpenAI at 68% is excellent for non-PDF workloads 3. **Technical Limitations are Clear:** Only Azure and Mistral have actual feature limitations 4. **Configuration is Key:** 4 providers need credential/billing fixes, not code changes **Next Steps for Users:** 1. **For new projects:** Start with Google AI Studio (free tier) or Vertex AI (enterprise) 2. **For existing Azure users:** Use Azure for CSV/tools, add Vertex fallback for PDFs 3. **For cost optimization:** Implement LiteLLM routing across multiple providers 4. **For privacy:** Use Ollama for local development and testing **Maintenance:** - Re-run test suite after provider API updates - Monitor provider changelog for new feature releases - Update this document quarterly or when adding new providers --- ## Provider Selection Guide # Provider Selection Guide **Last Updated:** January 2026 **NeuroLink Version:** 8.26.1+ This guide helps you choose the optimal AI provider for your specific use case, budget, and requirements. Whether you're building a startup prototype or deploying enterprise-grade AI systems, this guide provides actionable recommendations. ---------------------- | --------------------- | -------------------- | ----------------------- | | **Highest Quality** | OpenAI GPT-4o/GPT-5 | Anthropic Claude 4.5 | Google Gemini 2.5 Pro | | **Extended Thinking** | Anthropic Claude 4.5 | Google Gemini 2.5+ | Google AI Studio (Free) | | **PDF Processing** | Anthropic | Google AI Studio | Google Vertex | | **Complete Privacy** | Ollama (Local) | Self-hosted LiteLLM | - | | **Enterprise Security** | Azure OpenAI | Amazon Bedrock | Google Vertex | | **GDPR Compliance** | Mistral | Ollama (Local) | - | | **Free Tier** | Google AI Studio | OpenRouter | HuggingFace | | **Multi-Provider Access** | OpenRouter | LiteLLM | - | | **AWS Integration** | Amazon Bedrock | Amazon SageMaker | - | | **Azure Integration** | Azure OpenAI | - | - | | **GCP Integration** | Google Vertex | Google AI Studio | - | | **Vision/Multimodal** | OpenAI GPT-4o | Anthropic Claude 4.5 | Google Gemini | | **Tool Calling** | OpenAI | Anthropic | Google AI Studio | | **Custom Models** | Amazon SageMaker | OpenAI Compatible | Ollama | | **Budget Reasoning** | DeepSeek (R1) | NVIDIA NIM | llama.cpp (local) | | **Local GUI Inference** | LM Studio | Ollama | llama.cpp | | **Local CLI Inference** | llama.cpp | Ollama | LM Studio | | **NVIDIA GPU Cloud** | NVIDIA NIM | - | - | | **TTS Quality** | openai-tts (tts-1-hd) | elevenlabs | google-ai (free tier) | | **TTS Multilingual** | elevenlabs | openai-tts | azure-tts | | **STT Accuracy** | whisper | deepgram | google-stt | | **STT Streaming** | deepgram | - | - | | **Realtime Voice** | openai-realtime | gemini-live | - | --- ## Selection Criteria Deep Dive ### 1. Quality and Accuracy When output quality is paramount, consider these factors: | Provider | Quality Tier | Best Models | Strengths | | ------------------------ | ------------ | ---------------------------- | ----------------------------------------------------- | | **OpenAI** | Tier 1 | GPT-4o, GPT-5, O-series | Industry-leading accuracy, extensive training data | | **Anthropic** | Tier 1 | Claude 4.5 Opus, Sonnet | Superior reasoning, safety-focused, extended thinking | | **Google** | Tier 1-2 | Gemini 3 Pro, Gemini 2.5 Pro | Native multimodal, large context windows | | **Mistral** | Tier 2 | Mistral Large | European-trained, efficient architecture | | **Meta (via providers)** | Tier 2-3 | Llama 3.3 70B | Open-source leader, good general performance | ```typescript // Quality-first configuration const neurolink = new NeuroLink(); // For highest quality output const result = await neurolink.generate({ input: { text: "Complex analysis requiring nuanced reasoning" }, provider: "anthropic", model: "claude-opus-4-5-20250929", thinkingConfig: { thinkingLevel: "high" }, // Enable extended thinking for complex tasks temperature: 0.3, // Lower temperature for more consistent output }); ``` ### 2. Cost Optimization Choose providers based on your budget constraints: | Budget Level | Recommended Provider | Monthly Cost (1M tokens) | Notes | | -------------------- | ------------------------ | ------------------------ | -------------------------------------- | | **Free** | Google AI Studio | $0 | 1M tokens/day free limit | | **Free** | OpenRouter (free models) | $0 | Gemini, Llama, Qwen models | | **Free** | Ollama | $0 | Hardware costs only | | **Low ($0-50)** | Mistral Small | ~$20 | Good quality, European compliance | | **Medium ($50-200)** | GPT-4o-mini | ~$75 | Excellent quality/cost ratio | | **High ($200+)** | Claude 4.5 Sonnet | ~$180 | Premium quality with extended thinking | | **Enterprise** | Azure/Bedrock | Negotiated | Volume discounts, SLA guarantees | ```typescript // Cost-optimized multi-tier strategy const neurolink = new NeuroLink(); async function generateWithCostOptimization( prompt: string, complexity: "simple" | "medium" | "complex", ) { const configs = { simple: { provider: "google-ai", model: "gemini-2.5-flash" }, // FREE medium: { provider: "openai", model: "gpt-4o-mini" }, // Low cost complex: { provider: "anthropic", model: "claude-sonnet-4-5-20250929" }, // Premium }; return neurolink.generate({ input: { text: prompt }, ...configs[complexity], }); } // Route based on task complexity const simpleResult = await generateWithCostOptimization( "Summarize this text", "simple", ); const complexResult = await generateWithCostOptimization( "Analyze legal implications and provide recommendations", "complex", ); ``` ### 3. Latency and Performance Time-to-first-token (TTFT) and throughput considerations: | Provider | Average TTFT | Tokens/sec | Best For | | -------------------- | ------------ | ---------- | --------------------------------- | | **Ollama (Local)** | 50-200ms | 30-50 | Local development, lowest latency | | **Google AI Studio** | 300-700ms | 45-65 | Fast cloud inference | | **OpenAI** | 300-800ms | 40-60 | Balanced performance | | **Anthropic** | 400-900ms | 35-55 | Complex reasoning tasks | | **Azure OpenAI** | 350-850ms | 40-60 | Enterprise with SLA | ```typescript // Latency-optimized streaming configuration const neurolink = new NeuroLink(); // For real-time user-facing applications const result = await neurolink.stream({ input: { text: "Generate response quickly" }, provider: "google-ai", // Fast TTFT model: "gemini-2.5-flash", // Optimized for speed maxTokens: 500, // Limit for faster completion }); for await (const chunk of result.stream) { process.stdout.write(chunk.content); } ``` ### 4. Feature Requirements Match provider capabilities to your feature needs: | Feature | Full Support | Partial Support | No Support | | --------------------- | ------------------------------------------------------------ | ------------------------------------------------------ | ----------------------------------------------------------- | | **Streaming** | All text-generation providers except SageMaker | SageMaker | - | | **Tool Calling** | OpenAI, Anthropic, Google, Azure, Bedrock, Mistral, DeepSeek | HuggingFace, Ollama, NIM†, LM Studio†, llama.cpp† | SageMaker | | **Vision** | OpenAI, Anthropic, Google, Azure | Mistral, Ollama, LiteLLM, NIM†, LM Studio†, llama.cpp† | HuggingFace, SageMaker, DeepSeek | | **PDF Native** | Anthropic, Google AI Studio, Vertex | Bedrock (Claude) | OpenAI, Azure, Mistral, DeepSeek, NIM, LM Studio, llama.cpp | | **Extended Thinking** | Anthropic, Google (Gemini 2.5+), DeepSeek (R1), NVIDIA NIM‡ | LM Studio†, llama.cpp† | Others | | **Structured Output** | OpenAI, Anthropic, Azure, Mistral, DeepSeek | Google\*, NIM†, LM Studio†, llama.cpp† | HuggingFace, Ollama | | **Local Execution** | Ollama, LM Studio, llama.cpp | - | All cloud providers | | **Zero API Cost** | Ollama, LM Studio, llama.cpp | - | All cloud providers | \*Google providers cannot combine tools + JSON schema simultaneously † Model-dependent: capability depends on the specific model loaded / hosted. Check provider documentation. ‡ NVIDIA NIM reasoning is model-dependent: the default `openai/gpt-oss-20b` returns a reasoning trace on every request. The `thinkingLevel` option is an on/off switch on `stream()` only; `generate()` does not forward it and `reasoning_effort` is never sent. Decision-only providers (TypeSafe Jev, Laya, XOR, SubQ, Perplexity Decisions, Cloudflare Clef, OpenAI Decisions, ScaleDown) generate no text, so they do not stream; use `decide()` with them. ```typescript // Feature-specific provider selection const neurolink = new NeuroLink(); // PDF processing - use Anthropic or Google const pdfResult = await neurolink.generate({ input: { text: "Analyze this contract", files: ["./contract.pdf"], }, provider: "anthropic", model: "claude-sonnet-4-5-20250929", }); // Extended thinking for complex reasoning const reasoningResult = await neurolink.generate({ input: { text: "Solve this multi-step problem with detailed reasoning" }, provider: "anthropic", model: "claude-sonnet-4-5-20250929", thinkingConfig: { thinkingLevel: "high" }, }); // Structured output with Google (tools disabled) const structuredResult = await neurolink.generate({ input: { text: "Extract user data" }, provider: "google-ai", model: "gemini-2.5-pro", schema: { type: "object", properties: { name: { type: "string" }, email: { type: "string" }, }, }, disableTools: true, // Required for Google providers with schema }); ``` ### 5. Compliance and Security Choose based on regulatory and security requirements: | Requirement | Best Providers | Configuration Notes | | ---------------------- | ----------------------------- | ------------------------------------------ | | **GDPR** | Mistral, Ollama | European data centers, no US data transfer | | **HIPAA** | Azure OpenAI, Bedrock, Vertex | Requires BAA agreement | | **SOC 2** | All major cloud providers | Available on enterprise tiers | | **Data Privacy** | Ollama, Self-hosted | Zero data transmission | | **Air-gapped** | Ollama, SageMaker | On-premise deployment | | **Financial Services** | Azure OpenAI, Bedrock | Enterprise compliance packages | ```typescript // Privacy-focused configuration const neurolink = new NeuroLink(); // For sensitive data - use local Ollama const privateResult = await neurolink.generate({ input: { text: "Process this sensitive customer data" }, provider: "ollama", model: "llama3.1:70b", // Data never leaves your infrastructure }); // For GDPR compliance - use Mistral const gdprResult = await neurolink.generate({ input: { text: "Process EU customer request" }, provider: "mistral", model: "mistral-large-latest", // Data stays in European data centers }); ``` --- ## Use Case Recommendations ### Startup / MVP Development **Recommended Stack:** ```typescript const neurolink = new NeuroLink(); // Development: Free tier for iteration const devConfig = { provider: "google-ai" as const, model: "gemini-2.5-flash", }; // Production: Affordable quality const prodConfig = { provider: "openai" as const, model: "gpt-4o-mini", }; // Use environment-based configuration const config = process.env.NODE_ENV === "production" ? prodConfig : devConfig; const result = await neurolink.generate({ input: { text: "Your application prompt" }, ...config, }); ``` **Cost Projection:** - Development: $0/month (Google AI Studio free tier) - Production (10K users): ~$50-150/month (GPT-4o-mini) ### Enterprise Production **Recommended Stack:** ```typescript const neurolink = new NeuroLink(); // Primary: Enterprise-grade with SLA const primaryConfig = { provider: "azure" as const, model: "gpt-4o", }; // Fallback: Alternative provider for resilience const fallbackConfig = { provider: "bedrock" as const, model: "anthropic.claude-3-5-sonnet-20240620-v1:0", }; async function generateWithFallback(prompt: string) { try { return await neurolink.generate({ input: { text: prompt }, ...primaryConfig, timeout: 30000, }); } catch (error) { console.warn("Primary provider failed, using fallback"); return await neurolink.generate({ input: { text: prompt }, ...fallbackConfig, }); } } ``` **Enterprise Requirements Checklist:** - [x] SLA guarantees (99.9%+) - [x] HIPAA/SOC2 compliance - [x] Multi-region deployment - [x] Provider failover strategy - [x] Cost monitoring and alerts ### Research and Analysis **Recommended Stack:** ```typescript const neurolink = new NeuroLink(); // Use extended thinking for deep analysis const analysisResult = await neurolink.generate({ input: { text: `Analyze the following research paper and provide: 1. Key findings and methodology 2. Potential limitations 3. Implications for the field 4. Suggested follow-up research`, files: ["./research-paper.pdf"], }, provider: "anthropic", model: "claude-opus-4-5-20250929", thinkingConfig: { thinkingLevel: "high" }, maxTokens: 8000, }); // For document-heavy workflows const documentResult = await neurolink.generate({ input: { text: "Compare these three documents", files: ["./doc1.pdf", "./doc2.pdf", "./doc3.pdf"], }, provider: "google-ai", model: "gemini-2.5-pro", }); ``` ### Cost-Efficient Reasoning (DeepSeek) Choose DeepSeek when you need frontier-quality reasoning at a fraction of the cost of Anthropic or OpenAI. - **When to choose:** Text-only agentic workflows, chain-of-thought reasoning tasks, budget-constrained production. - **Provider ID:** `deepseek` - **Key models:** `deepseek-chat` (V3 — general purpose), `deepseek-reasoner` (R1 — reasoning) - **Not suitable for:** Vision, PDF, or image processing tasks. - **Credential needed:** `DEEPSEEK_API_KEY` (get one at https://platform.deepseek.com) ```typescript // Reasoning at low cost const result = await neurolink.generate({ input: { text: "Step through the implications of this decision" }, provider: "deepseek", model: "deepseek-reasoner", }); ``` ### NVIDIA-Hosted Models (NVIDIA NIM) Choose NVIDIA NIM when you want NVIDIA-curated hosted inference — Llama, Nemotron, Mistral, and DeepSeek-R1 — accessed via an NVIDIA API key. - **When to choose:** You want Llama 3.x or Nemotron models served at scale; you need a hosted reasoning model such as `openai/gpt-oss-20b`; you are already an NGC customer. - **Provider ID:** `nvidia-nim` - **Key models:** `openai/gpt-oss-20b` (default), `nvidia/nemotron-4-340b-instruct`, DeepSeek-R1 variants - **Vision:** Available on select models (Phi-3-vision, Llama 3.2 Vision); check https://build.nvidia.com/models. - **Not suitable for:** PDF processing; vision on non-vision models. - **Credential needed:** `NVIDIA_NIM_API_KEY` (get one at https://build.nvidia.com/settings/api-keys) ```typescript // NVIDIA NIM with thinking enabled const result = await neurolink.generate({ input: { text: "Reason through this math problem step by step" }, provider: "nvidia-nim", model: "nvidia/nemotron-reasoning-70b", thinkingLevel: "high", }); ``` ### Local Inference via LM Studio Choose LM Studio when you want a desktop GUI for managing and running local models, with zero cloud cost and maximum privacy. - **When to choose:** You want a GUI to browse, download, and switch models; you need local inference without managing llama-server manually; vision models like LLaVA or Qwen-VL are attractive. - **Provider ID:** `lm-studio` - **Model:** Auto-discovered from the loaded model (or pass an explicit model name). - **Default base URL:** `http://localhost:1234/v1` - **Not suitable for:** Production at scale (single machine); PDF processing. - **Setup:** Download LM Studio, load a model, click "Start Server". ```typescript // LM Studio — auto-discovers the loaded model const result = await neurolink.generate({ input: { text: "Summarize this article" }, provider: "lm-studio", // No model needed — auto-discovered from running LM Studio app }); ``` ### Local Inference via llama.cpp Choose llama.cpp when you want the lowest-level, most resource-efficient local inference — especially on CPU or with heavily quantized GGUF models. - **When to choose:** You need CPU-only inference; you want direct llama-server process control; you are running in a headless / server environment. - **Provider ID:** `llamacpp` - **Model:** Auto-discovered from the running llama-server (or pass an explicit model name). - **Default base URL:** `http://localhost:8080/v1` - **Tool calling:** Requires server to be started with `--jinja` flag. - **Not suitable for:** PDF processing; production at scale without additional infrastructure. - **Setup:** `./llama-server -m model.gguf --port 8080 [--jinja]` ```typescript // llama.cpp — auto-discovers the loaded GGUF model const result = await neurolink.generate({ input: { text: "Classify this text" }, provider: "llamacpp", // No model needed — auto-discovered from running llama-server }); ``` --- ### Privacy-Critical Applications **Recommended Stack:** ```typescript const neurolink = new NeuroLink(); // Tier 1: Completely local (maximum privacy) const localResult = await neurolink.generate({ input: { text: "Process sensitive patient data" }, provider: "ollama", model: "llama3.1:70b", }); // Tier 2: EU-only processing (GDPR compliant) const euResult = await neurolink.generate({ input: { text: "Process EU customer request" }, provider: "mistral", model: "mistral-large-latest", }); // Tier 3: Enterprise cloud with compliance (when cloud is acceptable) const enterpriseResult = await neurolink.generate({ input: { text: "Process data with enterprise security" }, provider: "azure", model: "gpt-4o", }); ``` --- ## Multi-Provider Strategy ### Intelligent Routing Implement smart provider selection based on request characteristics: ```typescript const neurolink = new NeuroLink(); type RequestContext = { prompt: string; hasImages?: boolean; hasPDFs?: boolean; requiresReasoning?: boolean; isSensitive?: boolean; maxBudget?: "free" | "low" | "medium" | "high"; }; function selectProvider(context: RequestContext): { provider: string; model: string; } { // Privacy-first: sensitive data stays local if (context.isSensitive) { return { provider: "ollama", model: "llama3.1:70b" }; } // PDF processing: use Anthropic or Google if (context.hasPDFs) { return { provider: "anthropic", model: "claude-sonnet-4-5-20250929" }; } // Complex reasoning: use extended thinking if (context.requiresReasoning) { return { provider: "anthropic", model: "claude-sonnet-4-5-20250929" }; } // Vision tasks: use GPT-4o if (context.hasImages) { return { provider: "openai", model: "gpt-4o" }; } // Budget-based selection switch (context.maxBudget) { case "free": return { provider: "google-ai", model: "gemini-2.5-flash" }; case "low": return { provider: "openai", model: "gpt-4o-mini" }; case "medium": return { provider: "openai", model: "gpt-4o" }; case "high": return { provider: "anthropic", model: "claude-opus-4-5-20250929" }; default: return { provider: "openai", model: "gpt-4o-mini" }; } } // Usage async function intelligentGenerate(context: RequestContext) { const { provider, model } = selectProvider(context); return neurolink.generate({ input: { text: context.prompt }, provider: provider as any, model, thinkingConfig: context.requiresReasoning ? { thinkingLevel: "high" } : undefined, }); } // Examples const result1 = await intelligentGenerate({ prompt: "Summarize this text", maxBudget: "free", }); const result2 = await intelligentGenerate({ prompt: "Analyze this medical document", hasPDFs: true, isSensitive: true, }); ``` ### Failover and Redundancy Implement robust failover for production reliability: ```typescript const neurolink = new NeuroLink(); type ProviderConfig = { provider: string; model: string; priority: number; }; // Default priority: self-hosted first, then cloud providers const providerChain: ProviderConfig[] = [ { provider: "litellm", model: "openai/gpt-4o", priority: 1 }, { provider: "ollama", model: "llama3.1:8b", priority: 2 }, { provider: "openai", model: "gpt-4o", priority: 3 }, { provider: "anthropic", model: "claude-sonnet-4-5-20250929", priority: 4 }, { provider: "google-ai", model: "gemini-2.5-pro", priority: 5 }, { provider: "mistral", model: "mistral-large-latest", priority: 6 }, ]; async function generateWithFailover( prompt: string, options: { maxRetries?: number; retryDelay?: number } = {}, ) { const { maxRetries = providerChain.length, retryDelay = 1000 } = options; const errors: Error[] = []; for (let i = 0; i setTimeout(resolve, retryDelay)); } } } // All providers failed throw new Error( `All providers failed. Errors: ${errors.map((e) => e.message).join("; ")}`, ); } // Usage const result = await generateWithFailover("Generate a response", { maxRetries: 3, retryDelay: 2000, }); ``` ### Cost-Aware Load Balancing Distribute load across providers based on cost and availability: ```typescript const neurolink = new NeuroLink(); type ProviderStats = { provider: string; model: string; costPer1MTokens: number; currentLoad: number; maxLoad: number; isHealthy: boolean; }; class CostAwareLoadBalancer { private providers: ProviderStats[] = [ { provider: "google-ai", model: "gemini-2.5-flash", costPer1MTokens: 0, currentLoad: 0, maxLoad: 1000, isHealthy: true, }, { provider: "openai", model: "gpt-4o-mini", costPer1MTokens: 0.75, currentLoad: 0, maxLoad: 500, isHealthy: true, }, { provider: "anthropic", model: "claude-sonnet-4-5-20250929", costPer1MTokens: 18, currentLoad: 0, maxLoad: 200, isHealthy: true, }, ]; selectProvider(): ProviderStats { // Filter healthy providers with capacity const available = this.providers.filter( (p) => p.isHealthy && p.currentLoad a.costPer1MTokens - b.costPer1MTokens)[0]; } async generate(prompt: string) { const provider = this.selectProvider(); provider.currentLoad++; try { return await neurolink.generate({ input: { text: prompt }, provider: provider.provider as any, model: provider.model, }); } finally { provider.currentLoad--; } } } // Usage const balancer = new CostAwareLoadBalancer(); const result = await balancer.generate("Process this request"); ``` --- ## Migration Guides ### From OpenAI to Multi-Provider If you're currently using OpenAI exclusively, here's how to add provider flexibility: ```typescript // Before: OpenAI only const openai = new OpenAI(); const response = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "user", content: "Hello" }], }); // After: NeuroLink with provider flexibility const neurolink = new NeuroLink(); // Same OpenAI model, but now portable const result = await neurolink.generate({ input: { text: "Hello" }, provider: "openai", // Can easily switch to any provider model: "gpt-4o", }); // Switch to Anthropic for extended thinking const resultWithThinking = await neurolink.generate({ input: { text: "Complex reasoning task" }, provider: "anthropic", model: "claude-sonnet-4-5-20250929", thinkingConfig: { thinkingLevel: "high" }, }); // Use free tier for development const devResult = await neurolink.generate({ input: { text: "Development testing" }, provider: "google-ai", model: "gemini-2.5-flash", }); ``` ### From Single Provider to Redundant Setup ```typescript const neurolink = new NeuroLink(); // Step 1: Define provider hierarchy const providers = { primary: { provider: "openai", model: "gpt-4o" }, secondary: { provider: "anthropic", model: "claude-sonnet-4-5-20250929" }, fallback: { provider: "google-ai", model: "gemini-2.5-pro" }, }; // Step 2: Implement health checking async function checkProviderHealth(config: { provider: string; model: string; }) { try { await neurolink.generate({ input: { text: "Health check" }, provider: config.provider as any, model: config.model, maxTokens: 10, }); return true; } catch { return false; } } // Step 3: Route to healthy provider async function generateWithRedundancy(prompt: string) { for (const [tier, config] of Object.entries(providers)) { if (await checkProviderHealth(config)) { console.log(`Using ${tier} provider: ${config.provider}`); return neurolink.generate({ input: { text: prompt }, provider: config.provider as any, model: config.model, }); } } throw new Error("All providers unhealthy"); } ``` --- ## Provider Selection Flowchart ``` START: What's your primary constraint? │ ├─ COST → Need it free? │ ├─ Yes → Google AI Studio (1M tokens/day FREE) │ └─ No → What's your budget? │ ├─ Low → GPT-4o-mini or Mistral Small │ ├─ Medium → GPT-4o or Claude Sonnet │ └─ High → Claude Opus or GPT-5 │ ├─ PRIVACY → How sensitive is your data? │ ├─ Critical (no cloud) → Ollama / LM Studio / llama.cpp (local, free) │ ├─ EU only → Mistral (GDPR) │ └─ Enterprise compliant → Azure/Bedrock │ ├─ FEATURES → What capabilities do you need? │ ├─ Extended Thinking → Anthropic or Google Gemini 2.5+ or DeepSeek-R1 (budget) │ ├─ PDF Processing → Anthropic or Google │ ├─ Vision → OpenAI, Anthropic, or Google │ ├─ Tool Calling → OpenAI or Anthropic (or DeepSeek for budget) │ └─ Local / Zero Cost → LM Studio, llama.cpp, or Ollama │ ├─ CLOUD PLATFORM → Which cloud are you on? │ ├─ AWS → Amazon Bedrock │ ├─ Azure → Azure OpenAI │ ├─ GCP → Google Vertex AI │ └─ Multi-cloud → LiteLLM or OpenRouter │ ├─ PERFORMANCE → What matters most? │ ├─ Latency → Ollama (local) or Google AI Studio │ ├─ Throughput → OpenAI or Google │ └─ Quality → OpenAI GPT-4o or Anthropic Claude │ └─ VOICE → What kind of audio I/O do you need? ├─ Text-to-Speech (quality) → openai-tts (tts-1-hd) or elevenlabs (multilingual) ├─ Text-to-Speech (cost) → google-ai (1M chars/month free) ├─ Text-to-Speech (enterprise) → azure-tts (full SSML) ├─ Speech-to-Text (accuracy) → whisper ├─ Speech-to-Text (real-time streaming) → deepgram (WebSocket) ├─ Speech-to-Text (GCP users) → google-stt ├─ Speech-to-Text (enterprise) → azure-stt └─ Realtime bidirectional voice → openai-realtime or gemini-live ``` --- ## Summary Recommendations ### For Most Users **Start with Google AI Studio** - Free tier, good quality, full features including PDF and extended thinking. ### For Production **Use OpenAI or Anthropic** - Industry-leading quality with reliable APIs and enterprise support. ### For Enterprise **Use Azure OpenAI or Amazon Bedrock** - Enterprise security, SLA guarantees, compliance certifications. ### For Privacy **Use Ollama, LM Studio, or llama.cpp** - Complete data privacy with local execution. LM Studio offers a GUI; llama.cpp offers maximum CPU efficiency. ### For Cost-Efficient Reasoning **Use DeepSeek** - deepseek-reasoner (R1) delivers strong chain-of-thought reasoning at a fraction of Anthropic/OpenAI pricing. ### For NVIDIA Ecosystem **Use NVIDIA NIM** - Curated Llama, Nemotron, and DeepSeek-R1 models served at scale via NVIDIA's cloud. ### Text-to-Speech (TTS) **Best quality: `openai-tts` with model tts-1-hd** ```typescript const neurolink = new NeuroLink(); const result = await neurolink.generate({ input: { text: "Hello, world!" }, tts: { enabled: true, provider: "openai-tts", voice: "nova", model: "tts-1-hd", }, }); ``` **Best multilingual: `elevenlabs`** ```typescript const result = await neurolink.generate({ input: { text: "Hola, ¿cómo estás?" }, tts: { enabled: true, provider: "elevenlabs", voice: "your-voice-id" }, }); ``` **Most cost-effective: `google-ai` (1M chars free tier)** ```typescript const result = await neurolink.generate({ input: { text: "Cost-effective synthesis at scale." }, tts: { enabled: true, provider: "google-ai", voice: "en-US-Standard-A" }, }); ``` **Enterprise: `azure-tts` (SSML support)** ```typescript const result = await neurolink.generate({ input: { text: "Welcome to Neurolink." }, tts: { enabled: true, provider: "azure-tts", voice: "en-US-AriaNeural" }, }); ``` ### Speech-to-Text (STT) **Best accuracy: `whisper` (OpenAI)** ```typescript const result = await neurolink.generate({ input: { text: "" }, stt: { enabled: true, provider: "whisper", audio: audioBuffer }, }); ``` **Best streaming: `deepgram` (WebSocket real-time)** ```typescript const result = await neurolink.generate({ input: { text: "" }, stt: { enabled: true, provider: "deepgram", audio: audioBuffer }, }); ``` **Best for Google Cloud users: `google-stt`** ```typescript const result = await neurolink.generate({ input: { text: "" }, stt: { enabled: true, provider: "google-stt", audio: audioBuffer }, }); ``` **Enterprise: `azure-stt`** ```typescript const result = await neurolink.generate({ input: { text: "" }, stt: { enabled: true, provider: "azure-stt", audio: audioBuffer }, }); ``` ### For Cost Optimization **Implement multi-provider routing** - Use free/cheap providers for simple tasks, premium for complex ones. --- ## Related Resources - **[Provider Comparison](/docs/reference/provider-comparison)** - Detailed feature and pricing comparison - **[Provider Capabilities Audit](/docs/reference/provider-capabilities-audit)** - Technical compatibility matrix - **[Configuration Reference](/docs/deployment/configuration)** - Environment setup for all providers - **[Troubleshooting](/docs/reference/troubleshooting)** - Common issues and solutions - **[Multi-Provider Fallback Cookbook](/docs/cookbook/multi-provider-fallback)** - Implementation patterns - **[Cost Optimization Cookbook](/docs/cookbook/cost-optimization)** - Strategies to reduce costs - **[Voice Providers Comparison](/docs/reference/provider-comparison#voice-providers)** - TTS, STT, and Realtime provider matrix - **[Voice Providers Index](/docs/getting-started/providers/index.md#voice-providers)** - Voice provider setup cards --- ## NeuroLink Troubleshooting Guide # NeuroLink Troubleshooting Guide **Version**: v9.26.1 **Last Updated**: March 2026 ## Quick Fixes | Symptom | Resolution | | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `Image not found` when using `--image` | Provide an absolute path or run the command from the directory containing the asset. URLs must be HTTPS. | | `Evaluation model not configured` | Set `NEUROLINK_EVALUATION_PROVIDER`/`NEUROLINK_EVALUATION_MODEL`, or disable `--enableEvaluation` until credentials are added. | | `Redis connection failed` in loop mode | Export `REDIS_URL` before running `neurolink loop` or start the session with `--no-auto-redis`. | | `Model not available in region` | Confirm the model supports the requested region and update `AWS_REGION` / `GOOGLE_VERTEX_LOCATION` accordingly. | | CLI exits after error inside loop | Upgrade to latest `@juspay/neurolink` and restart the loop; new builds catch errors without exiting. | --- ## Q4 2025 Features -- Common Issues ### Human-in-the-Loop (HITL) | Issue | Solution | | --------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | Tool executes without asking permission | Add `requiresConfirmation: true` to tool definition. See [HITL Guide](/docs/features/hitl.md#configuration) | | Confirmation dialog doesn't appear | Handle `USER_CONFIRMATION_REQUIRED` error in your UI. See [HITL Guide](/docs/features/hitl.md#troubleshooting) | | Permission flag not resetting | Call `setUserConfirmation(false)` after tool execution. See [HITL Guide](/docs/features/hitl.md#how-it-works) | ### Guardrails Middleware | Issue | Solution | | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Content not being filtered | `preset: "security"` only turns guardrails on; also set `badWords` (with `enabled: true` and a `list`) or `modelFilter`. See [Guardrails Guide](/docs/features/guardrails.md#problem-guardrails-not-filtering-content) | | Too many false positives | Terms match as substrings, so a short term catches unrelated words. Use specific terms, or `regexPatterns` with `\b` word boundaries. See [Guardrails Guide](/docs/features/guardrails.md#problem-too-many-false-positives-legitimate-content-filtered) | | Model-based filter is slow | Switch to `openai:gpt-4o-mini` for faster filtering. See [Guardrails Guide](/docs/features/guardrails.md#troubleshooting) | ### Redis Conversation Export | Issue | Solution | | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | Export returns empty history | Verify Redis connection and session ID exists. See [Conversation History Guide](/docs/features/conversation-history.md#troubleshooting) | | `getConversationHistory` returns empty array | Ensure `conversationMemory.enabled: true` is configured. See [Conversation History Guide](/docs/features/conversation-history.md#configuration) | | Missing metadata in export | Set `includeMetadata: true` in export options. See [Conversation History Guide](/docs/features/conversation-history.md#advanced-usage) | ### Video Generation (Veo 3.1) | Issue | Solution | | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `PROVIDER_NOT_CONFIGURED` error | Set `GOOGLE_APPLICATION_CREDENTIALS` to your service account JSON path. See [Video Generation Guide](/docs/features/video-generation.md#prerequisites) | | `VIDEO_POLL_TIMEOUT` after 3 minutes | Video generation can take 1-2 minutes; increase timeout or check Vertex AI quota. See [Video Generation Guide](/docs/features/video-generation.md#troubleshooting) | | `VIDEO_INVALID_INPUT` for image format | Ensure image is PNG, JPEG, or WebP under 20MB; check aspect ratio compatibility. See [Video Generation Guide](/docs/features/video-generation.md#limitations) | | Video generation uses wrong provider | Video gen only supports Vertex AI; provider auto-switches to `vertex` when `output.mode: "video"` | | `Project not found` error | Set `GOOGLE_VERTEX_PROJECT` or `GOOGLE_CLOUD_PROJECT` environment variable | | Audio missing from generated video | Set `output.video.audio: true` (enabled by default) and ensure Veo 3.1 model is used | ### PPT Generation (PowerPoint Presentations) - `PPT_PLANNING_FAILED` -- Check AI provider connection and ensure valid prompt. See [PPT Generation Guide](/docs/features/ppt-generation.md#troubleshooting) - `PPT_INVALID_AI_RESPONSE` during generation -- Simplify prompt/topic and retry. See [PPT Generation Guide](/docs/features/ppt-generation.md#error-codes) - `PPT_FILE_WRITE_FAILED` -- Check write permissions for output directory and disk space. See [PPT Generation Guide](/docs/features/ppt-generation.md#error-codes) - Empty slides in presentation -- Ensure content plan has enough detail; try more specific prompts - Images not generating -- Set `generateAIImages: true` in `output.ppt` (SDK) or avoid `--pptNoImages` (CLI), and configure `VERTEX_IMAGE_MODEL`. See [PPT Generation Guide](/docs/features/ppt-generation.md#troubleshooting) - Theme not applying correctly -- Verify theme name: `modern`, `corporate`, `creative`, `minimal`, or `dark` --- ## Generate Function Migration Issues ### Migration Questions **Q: Should I update my existing code to use the new `generate()` API?** A: Optional. Your existing legacy `generate()` code continues working unchanged. Prefer the new `stream()` API for new projects. **Q: I see deprecation warnings with the legacy `generate()` call style** A: These are informational only. The legacy API remains supported. To remove warnings, use the newer options-based `generate()` call style (pass `input: { text: "..." }` instead of `prompt: "..."`). ### Migration Examples ```typescript // NEW: Recommended usage const result = await neurolink.generate({ input: { text: "Your prompt" }, provider: "google-ai", }); // LEGACY: Still fully supported const result = await neurolink.generate({ prompt: "Your prompt", provider: "google-ai", }); ``` ### CLI Migration ```bash # NEW: Options-based API npx @juspay/neurolink generate --prompt "Your prompt" --provider openai # LEGACY: Positional arguments (still works, shows deprecation warning) npx @juspay/neurolink generate "Your prompt" --provider openai ``` --- ## Connection Issues ### Provider Connection Failures **Symptoms:** - `ECONNREFUSED` or `ECONNRESET` errors - `Network timeout` errors - `Failed to connect to provider` messages **Common Causes & Solutions:** #### 1. Network/Firewall Issues ```bash # Test direct connectivity curl -I https://api.openai.com curl -I https://api.anthropic.com # If behind corporate proxy, set proxy: export HTTP_PROXY=http://proxy.company.com:8080 export HTTPS_PROXY=http://proxy.company.com:8080 ``` **Solution**: Configure proxy in your application: ```typescript const neurolink = new NeuroLink({ provider: "openai", httpProxy: process.env.HTTP_PROXY, httpsProxy: process.env.HTTPS_PROXY, }); ``` #### 2. DNS Resolution Issues ```bash # Test DNS resolution nslookup api.openai.com nslookup api.anthropic.com ``` **Solution**: Use alternative DNS or add to `/etc/hosts` #### 3. SSL/TLS Errors ```bash # Test SSL certificate openssl s_client -connect api.openai.com:443 ``` **Solution**: Update Node.js or disable SSL verification (not recommended for production): ```typescript process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; // DANGER: Dev only! ``` ### Redis Connection Issues **Symptoms:** - `Redis connection failed` - `ECONNREFUSED` to Redis - `Authentication failed` for Redis **Solutions:** #### 1. Redis Not Running ```bash # Check if Redis is running redis-cli ping # Should return: PONG # Start Redis docker run -d --name neurolink-redis -p 6379:6379 redis:7-alpine # Or with Homebrew (macOS) brew services start redis ``` #### 2. Wrong Connection String ```bash # Check format export REDIS_URL=redis://localhost:6379 # With password: export REDIS_URL=redis://:password@localhost:6379 # With TLS: export REDIS_URL=rediss://redis.example.com:6380 ``` #### 3. Authentication Issues ```typescript const neurolink = new NeuroLink({ conversationMemory: { enabled: true, store: "redis", redis: { host: "localhost", port: 6379, password: process.env.REDIS_PASSWORD, }, }, }); ``` ### Timeout Errors **Symptoms:** - Request hangs indefinitely - `Request timeout` errors - No response after long wait **Solutions:** #### 1. Increase Timeout ```typescript const result = await neurolink.generate({ input: { text: prompt }, timeout: 60000, // 60 seconds }); ``` #### 2. Check Provider Status Visit provider status pages: - OpenAI: https://status.openai.com - Anthropic: https://status.anthropic.com - Google: https://status.cloud.google.com #### 3. Use Shorter Prompts Long prompts increase processing time. Try reducing context size: ```typescript // Instead of 10,000 word context const longPrompt = generateLongPrompt(); // Use summary const summary = await summarizeContext(longPrompt); const result = await neurolink.generate({ input: { text: summary } }); ``` --- ## MCP Integration Issues ### Built-in Tools Not Working **Previous Issue**: Time tool and other built-in tools were not loading due to circular dependencies. This was resolved in earlier versions. **If still having issues**: 1. Ensure you're using the latest version: `npm list @juspay/neurolink` 2. Clear node modules and reinstall: `rm -rf node_modules && npm install` 3. Rebuild the project: `npm run build` ### External MCP Server Discovery Issues **Symptom**: No external MCP servers found during discovery **Diagnosis**: ```bash # Check if discovery is working npx @juspay/neurolink mcp discover --format table # Should show 58+ discovered servers # Check discovery with debug info npx @juspay/neurolink mcp discover --format json | jq '.servers | length' # Should return a number > 50 ``` **Solutions**: 1. **No Servers Found**: ```bash # Check if you have AI tools installed (VS Code, Claude, Cursor, etc.) ls -la ~/Library/Application\ Support/Claude/ ls -la ~/.config/Code/User/ ls -la ~/.cursor/ ``` 2. **Partial Discovery**: ```bash # Check for configuration file issues npx @juspay/neurolink mcp discover --format json > discovery.json # Review discovery.json for parsing errors ``` 3. **Discovery Errors**: ```bash # Enable debug mode export NEUROLINK_DEBUG=true npx @juspay/neurolink mcp discover --format table ``` ### Tool Discovery Failures **Symptoms:** - `No tools discovered` - `MCP server not responding` - `Tool not found` **Solutions:** #### 1. Verify MCP Server Configuration ```typescript const neurolink = new NeuroLink({ mcpServers: { filesystem: { command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "."], }, }, }); // List available tools const tools = await neurolink.getAllAvailableTools(); console.log("Available tools:", tools); ``` #### 2. Check Server Installation ```bash # Test MCP server directly npx -y @modelcontextprotocol/server-filesystem . # Verify permissions chmod +x node_modules/.bin/mcp-server-* ``` #### 3. Enable Debug Logging ```bash DEBUG=neurolink:mcp node your-app.js ``` ### Tool Execution Errors **Symptoms:** - `Tool execution failed` - `Permission denied` - `Tool timeout` **Solutions:** #### 1. Check Permissions ```typescript // Filesystem tools need read/write access const neurolink = new NeuroLink({ mcpServers: { filesystem: { command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"], }, }, }); ``` #### 2. Increase Timeout ```typescript const result = await neurolink.generate({ input: { text: "Use the slow_tool" }, enableTools: true, toolTimeout: 60000, // 60 seconds }); ``` #### 3. Validate Tool Arguments ```typescript // Tools may fail with invalid arguments // Check schema first: const tools = await neurolink.getAllAvailableTools(); const tool = tools.find((t) => t.name === "my_tool"); console.log("Tool schema:", tool.inputSchema); ``` ### HTTP Transport Issues (Remote MCP Servers) #### Connection Timeout **Symptom**: `ETIMEDOUT` or `Connection timeout` when connecting to remote MCP servers **Diagnosis**: ```bash # Test remote endpoint directly curl -v https://api.example.com/mcp # Check with custom timeout curl --max-time 30 https://api.example.com/mcp ``` **Solutions**: 1. **Increase Connection Timeout**: ```json { "mcpServers": { "remote-api": { "transport": "http", "url": "https://api.example.com/mcp", "httpOptions": { "connectionTimeout": 60000, "requestTimeout": 120000 } } } } ``` 2. **Check Network/Firewall**: - Verify the remote endpoint is accessible - Check corporate firewall allows outbound connections - Verify proxy settings if behind corporate network #### Authentication Errors **Symptom**: `401 Unauthorized` or `403 Forbidden` errors **Diagnosis**: ```bash # Test authentication curl -H "Authorization: Bearer YOUR_TOKEN" https://api.example.com/mcp ``` **Solutions**: 1. **Check Bearer Token**: ```json { "mcpServers": { "remote-api": { "transport": "http", "url": "https://api.example.com/mcp", "headers": { "Authorization": "Bearer YOUR_VALID_TOKEN" } } } } ``` 2. **Check API Key**: ```json { "headers": { "X-API-Key": "your-valid-api-key" } } ``` 3. **Refresh OAuth Token**: - OAuth tokens may expire; check token validity - Verify OAuth configuration has correct scopes #### Rate Limiting Errors **Symptom**: `429 Too Many Requests` errors **Solutions**: 1. **Configure Rate Limiting**: ```json { "mcpServers": { "remote-api": { "transport": "http", "url": "https://api.example.com/mcp", "rateLimiting": { "requestsPerMinute": 30, "maxBurst": 5, "useTokenBucket": true } } } } ``` 2. **Add Retry Configuration**: ```json { "retryConfig": { "maxAttempts": 5, "initialDelay": 2000, "maxDelay": 60000, "backoffMultiplier": 2 } } ``` #### SSL/TLS Errors **Symptom**: `CERT_HAS_EXPIRED` or `UNABLE_TO_VERIFY_LEAF_SIGNATURE` **Solutions**: 1. **Check Certificate**: ```bash openssl s_client -connect api.example.com:443 -servername api.example.com ``` 2. **For Development Only** (not recommended for production): ```bash export NODE_TLS_REJECT_UNAUTHORIZED=0 ``` #### HTTP Transport Debug Mode ```bash # Enable debug logging for HTTP transport export NEUROLINK_DEBUG=true # Test with verbose output npx @juspay/neurolink mcp test remote-api --debug ``` See [MCP HTTP Transport Guide](/docs/mcp/http-transport) for complete configuration options. --- ## AI Provider Issues ### Provider Authentication Errors **Symptom**: "Authentication failed" or "Invalid API key" errors **Diagnosis**: ```bash # Check provider status npx @juspay/neurolink status --verbose ``` **Solutions**: 1. **OpenAI Issues**: ```bash # Set API key export OPENAI_API_KEY="sk-your-openai-api-key" # Test connection npx @juspay/neurolink generate "Hello" --provider openai ``` 2. **Google AI Studio Issues**: ```bash # Set API key (recommended for free tier) export GOOGLE_AI_API_KEY="AIza-your-google-ai-api-key" # Test connection npx @juspay/neurolink generate "Hello" --provider google-ai ``` 3. **Google Vertex AI Issues**: ```bash # Complete Vertex AI setup export GOOGLE_VERTEX_PROJECT="your-project-id" export GOOGLE_VERTEX_LOCATION="us-east5" export GOOGLE_AUTH_CLIENT_EMAIL="service-account@project.iam.gserviceaccount.com" export GOOGLE_AUTH_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----" # Test Claude Sonnet 4 (recommended model) npx @juspay/neurolink generate "test" --provider vertex --model claude-sonnet-4@20250514 ``` **Common Vertex AI Issues**: - **"Not configured" despite valid credentials**: Use `GOOGLE_VERTEX_PROJECT` instead of `GOOGLE_CLOUD_PROJECT_ID` - **Authentication failed**: Ensure both `GOOGLE_AUTH_CLIENT_EMAIL` and `GOOGLE_AUTH_PRIVATE_KEY` are set - **Model not found**: Use `claude-sonnet-4@20250514` format for Anthropic models via Vertex AI **Debugging Commands**: ```bash # Check provider status npx @juspay/neurolink status # Test basic connectivity npx @juspay/neurolink generate "hello" --provider vertex --model claude-sonnet-4@20250514 # Debug with verbose output npx @juspay/neurolink generate "test" --provider vertex --debug ``` 4. **Multiple Provider Setup**: ```bash # Create .env file cat > .env { return neurolink.generate({ input: { text: prompt } }); }); ``` #### 2. Upgrade Tier or Add Payment Method Most rate limits increase with: - Paid accounts - Higher tiers - Usage history ### Memory Issues **Symptoms:** - `JavaScript heap out of memory` - Process crashes - Slow performance **Solutions:** #### 1. Increase Node.js Memory ```bash # Increase heap size to 4GB node --max-old-space-size=4096 your-app.js # Or in package.json { "scripts": { "start": "node --max-old-space-size=4096 index.js" } } ``` #### 2. Clear Conversation Memory ```typescript // Clear periodically await neurolink.clearAllConversations(); // Or limit history const neurolink = new NeuroLink({ conversationMemory: { enabled: true, maxMessages: 50, // Keep only last 50 messages }, }); ``` #### 3. Stream Instead of Buffer ```typescript // Instead of buffering entire response const result = await neurolink.generate({ input: { text: prompt } }); console.log(result.content); // Large string in memory // Stream to reduce memory const stream = await neurolink.stream({ input: { text: prompt } }); for await (const chunk of stream) { if (chunk.type === "content-delta") { process.stdout.write(chunk.delta); // Write immediately } } ``` --- ## Streaming Issues ### Stream Interruption **Symptoms:** - Stream stops mid-response - Incomplete responses - `Stream ended unexpectedly` **Solutions:** #### 1. Implement Retry See [Streaming with Retry](/docs/cookbook/streaming-with-retry): ```typescript async function streamWithRetry(prompt: string, maxRetries = 3) { for (let i = 0; i setTimeout(r, 1000 * (i + 1))); } } } ``` #### 2. Handle Stream Errors ```typescript try { const stream = await neurolink.stream({ input: { text: prompt } }); for await (const chunk of stream) { if (chunk.type === "content-delta") { process.stdout.write(chunk.delta); } } } catch (error) { console.error("Stream failed:", error); // Fallback to non-streaming const fallback = await neurolink.generate({ input: { text: prompt } }); console.log(fallback.content); } ``` ### Incomplete Responses **Symptoms:** - Response cuts off mid-sentence - Missing conclusion - Shorter than expected **Solutions:** #### 1. Check Max Tokens ```typescript const result = await neurolink.generate({ input: { text: prompt }, maxTokens: 2000, // Increase if needed }); ``` #### 2. Verify Stream Completion ```typescript let complete = false; for await (const chunk of stream) { if (chunk.type === "content-delta") { process.stdout.write(chunk.delta); } if (chunk.type === "done") { complete = true; } } if (!complete) { console.warn("Stream did not complete normally"); } ``` --- ## Configuration Management Issues ### Config Update Failures **Symptoms**: Config updates fail with validation errors or backup issues **Solutions**: ```bash # Check config validation npx @juspay/neurolink config validate # Check backup system ls -la .neurolink.backups/ # Manual backup creation npx @juspay/neurolink config backup --reason "manual-backup" # Restore from backup npx @juspay/neurolink config restore --backup latest ``` ### Backup System Issues **Symptoms**: Backups not created or corrupted **Solutions**: ```bash # Verify backup directory permissions ls -la .neurolink.backups/ # Check backup integrity npx @juspay/neurolink config verify-backups # Cleanup corrupted backups npx @juspay/neurolink config cleanup --verify # Reset backup system rm -rf .neurolink.backups/ mkdir .neurolink.backups/ ``` ### Provider Configuration Issues **Symptoms**: Providers not loading or failing validation **Solutions**: ```bash # Test individual provider npx @juspay/neurolink test-provider google # Check provider status npx @juspay/neurolink status # Reset provider configuration npx @juspay/neurolink config reset-provider google # Validate environment variables npx @juspay/neurolink env check ``` --- ## TypeScript Compilation Issues ### Build Failures **Symptoms**: `pnpm run build:cli` fails with TypeScript errors **Common Errors & Solutions**: ```typescript // ERROR: Argument of type 'unknown' is not assignable to parameter of type 'string' // SOLUTION: Use type casting const value = String(unknownValue || "default"); // ERROR: Property 'success' does not exist on type 'unknown' // SOLUTION: Cast to expected type const result = response as ToolResult; if (result.success) { /* ... */ } // ERROR: Interface compatibility issues // SOLUTION: Use optional methods if (registry.executeTool) { const result = await registry.executeTool("tool", args, context); } ``` **Build Validation**: ```bash # Check TypeScript compilation npx tsc --noEmit --project tsconfig.cli.json # Full CLI build pnpm run build:cli # Check for type errors npx tsc --listFiles --project tsconfig.cli.json ``` ### Interface Compatibility Issues **Symptoms**: Type errors when using new interfaces **Solutions**: ```typescript // Use optional chaining for new methods registry.registerServer?.("server", config, context); // Type casting for unknown returns const result = (await registry.executeTool("tool", args)) as ToolResult; // Handle both legacy and new interfaces if ("registerServer" in registry) { await registry.registerServer("server", config, context); } else { registry.register_server("server", config); } ``` --- ## Performance Issues ### Slow Tool Execution **Symptoms**: Tool execution taking longer than expected (>1ms target) **Solutions**: ```bash # Enable performance monitoring NEUROLINK_PERFORMANCE_MONITORING=true # Check execution statistics npx @juspay/neurolink stats # Optimize cache settings NEUROLINK_CACHE_ENABLED=true NEUROLINK_CACHE_TTL=300 # Reduce timeout for faster failures NEUROLINK_DEFAULT_TIMEOUT=10000 ``` ### Pipeline Performance **Symptoms**: Sequential pipeline execution slower than ~22ms target **Solutions**: ```typescript // Use parallel execution where possible const results = await Promise.all([ registry.executeTool("tool1", args1, context), registry.executeTool("tool2", args2, context), ]); // Enable caching for repeated operations const context: ExecutionContext = { cacheOptions: { enabled: true, ttl: 300, key: "operation-cache", }, }; // Use fallback options for reliability const context: ExecutionContext = { fallbackOptions: { enabled: true, maxRetries: 2, providers: ["openai", "anthropic"], }, }; ``` --- ## Interface Migration Issues ### Property Name Errors **Symptoms**: `Property 'session_id' does not exist` type errors **Solutions**: ```typescript // OLD (snake_case) - causes errors const context = { session_id: "session123", user_id: "user456", ai_provider: "google", }; // NEW (camelCase) - correct const context: ExecutionContext = { sessionId: "session123", userId: "user456", aiProvider: "google", }; ``` ### Method Call Issues **Symptoms**: `Cannot call undefined method` runtime errors **Solutions**: ```typescript // WRONG: Direct call may fail registry.executeTool("tool", args); // CORRECT: Use optional chaining registry.executeTool?.("tool", args, context); // ALTERNATIVE: Check method exists if (registry.executeTool) { const result = await registry.executeTool("tool", args, context); } ``` ### Generic Type Issues **Symptoms**: `Type 'unknown' is not assignable` errors **Solutions**: ```typescript // WRONG: Unknown return type const result = await registry.executeTool("tool", args); // CORRECT: Use generics const result = await registry.executeTool("tool", args, context); // ALTERNATIVE: Type assertion const result = (await registry.executeTool("tool", args)) as MyResultType; ``` --- ## Error Recovery ### Automatic Recovery **Config Auto-Restore**: ```bash # Check if auto-restore triggered grep "Config restored" ~/.neurolink/logs/config.log # Verify restored config npx @juspay/neurolink config validate # Manual recovery if needed npx @juspay/neurolink config restore --backup latest ``` **Provider Fallback**: ```typescript // Configure automatic fallback const context: ExecutionContext = { fallbackOptions: { enabled: true, providers: ["google-ai", "openai", "anthropic"], maxRetries: 3, retryDelay: 1000, }, }; ``` ### Manual Recovery **Reset to Defaults**: ```bash # Reset all configuration npx @juspay/neurolink config reset --confirm # Reset specific provider npx @juspay/neurolink config reset-provider google # Restore from specific backup npx @juspay/neurolink config restore --backup neurolink-config-2025-01-07T10-30-00.js ``` **If still having issues**: 1. Ensure you're using the latest version: `npm list @juspay/neurolink` 2. Clear node modules and reinstall: `rm -rf node_modules && npm install` 3. Rebuild the project: `npm run build` --- ## Enterprise Proxy Issues ### Proxy Not Working **Symptoms**: Connection errors when `HTTPS_PROXY` is set **Diagnosis**: ```bash # Check proxy environment variables echo $HTTPS_PROXY echo $HTTP_PROXY # Test proxy connectivity curl -I --proxy $HTTPS_PROXY https://api.openai.com ``` **Solutions**: 1. **Verify proxy format**: ```bash # Correct format export HTTPS_PROXY="http://proxy.company.com:8080" # Not: https:// (use http:// even for HTTPS_PROXY) ``` 2. **Check authentication**: ```bash # URL encode special characters export HTTPS_PROXY="http://user%40domain.com:pass%3Aword@proxy:8080" ``` 3. **Test bypass**: ```bash # Temporarily unset proxy unset HTTPS_PROXY HTTP_PROXY npx @juspay/neurolink generate "test direct connection" ``` ### Corporate Firewall Blocking **Symptoms**: Network timeouts or SSL certificate errors **Solutions**: 1. **Contact IT team** for allowlist: - `generativelanguage.googleapis.com` (Google AI) - `api.anthropic.com` (Anthropic) - `api.openai.com` (OpenAI) - `bedrock.amazonaws.com` (Bedrock) - `aiplatform.googleapis.com` (Vertex AI) 2. **Check SSL verification**: ```bash # Disable SSL verification (not recommended for production) export NODE_TLS_REJECT_UNAUTHORIZED=0 ``` ### Debug Proxy Connection ```bash # Enable detailed proxy logging export DEBUG=neurolink:proxy npx @juspay/neurolink generate "test proxy" --debug ``` **For detailed proxy setup**, see [Enterprise & Proxy Setup Guide](/docs/deployment/enterprise-proxy). --- ## Debugging Tips ### Enable Debug Logging #### SDK Debug Logging ```bash # All NeuroLink debug output DEBUG=neurolink:* node your-app.js # Specific modules DEBUG=neurolink:provider node your-app.js DEBUG=neurolink:mcp node your-app.js DEBUG=neurolink:memory node your-app.js ``` #### Provider-Specific Logging ```typescript const neurolink = new NeuroLink({ debug: true, // Enable debug mode onLog: (level, message, meta) => { console.log(`[${level}] ${message}`, meta); }, }); ``` ### Common Log Messages | Log Message | Meaning | Action | | ----------------------- | -------------------- | ----------------- | | `Provider initialized` | Provider ready | Normal | | `Rate limit hit` | Too many requests | Slow down | | `Tool executed` | Tool call succeeded | Normal | | `Authentication failed` | Bad API key | Check credentials | | `Model not found` | Invalid model name | Verify model | | `Context too large` | Exceeded token limit | Reduce context | ### Request/Response Inspection ```typescript const neurolink = new NeuroLink({ onRequest: (request) => { console.log("Request:", JSON.stringify(request, null, 2)); }, onResponse: (response) => { console.log("Response:", JSON.stringify(response, null, 2)); }, }); ``` ### Network Traffic Inspection ```bash # Use proxy to inspect HTTP traffic export HTTP_PROXY=http://localhost:8888 export HTTPS_PROXY=http://localhost:8888 # Then use Burp Suite, Charles, or mitmproxy to view requests ``` --- ## Testing and Validation ### Comprehensive System Test Run this test suite to validate everything is working: ```bash # 1. Build the system npm run build # 2. Test built-in tools echo "Testing built-in tools..." node dist/cli/index.js generate "What time is it?" --debug # 3. Test tool discovery echo "Testing tool discovery..." node dist/cli/index.js generate "What tools do you have access to?" --debug # 4. Test external server discovery echo "Testing external server discovery..." npx @juspay/neurolink mcp discover --format table # 5. Test AI provider echo "Testing AI provider..." npx @juspay/neurolink status --verbose # 6. Run comprehensive tests echo "Running comprehensive tests..." npm run test:run -- test/mcp-comprehensive.test.ts ``` **Expected Results**: - Build: Successful compilation - Built-in tools: Time tool returns current time - Tool discovery: Lists 5+ built-in tools - External discovery: Shows 58+ discovered servers - AI provider: At least one provider available - Tests: All MCP foundation tests pass ### Debug Mode Enable detailed logging for troubleshooting: ```bash # Enable debug mode export NEUROLINK_DEBUG=true # Run commands with debug output npx @juspay/neurolink generate "Hello" --debug npx @juspay/neurolink mcp discover --format table npx @juspay/neurolink status --verbose ``` --- ## System Requirements ### Minimum Requirements - **Node.js**: v18+ (recommended: v20+) - **NPM**: v8+ - **TypeScript**: v5+ (for development) - **Operating System**: macOS, Linux, Windows ### Recommended Setup ```bash # Check versions node --version # Should be v18+ npm --version # Should be v8+ # For development npx tsc --version # Should be v5+ ``` --- ## Getting Help ### Before Asking for Help Gather this information: 1. **NeuroLink version**: `npx @juspay/neurolink --version` 2. **Node.js version**: `node --version` 3. **Operating system**: `uname -a` (Unix) or `ver` (Windows) 4. **Error message**: Full error stack trace 5. **Minimal reproduction**: Smallest code that reproduces issue 6. **Debug logs**: Output from `DEBUG=neurolink:* node your-app.js` ### Report Issues When reporting issues, please include: 1. **System Information**: ```bash node --version npm --version npm list @juspay/neurolink ``` 2. **Debug Output**: ```bash export NEUROLINK_DEBUG=true npx @juspay/neurolink status --verbose ``` 3. **Error Logs**: Full error messages and stack traces 4. **Steps to Reproduce**: Exact commands that cause the issue ### Creating a Bug Report Use this template: ```markdown ## Bug Description [Clear description of the issue] ## Steps to Reproduce 1. [First step] 2. [Second step] 3. [Error occurs] ## Expected Behavior [What should happen] ## Actual Behavior [What actually happens] ## Environment - NeuroLink version: [version] - Node.js version: [version] - OS: [operating system] - Provider: [OpenAI/Anthropic/etc] ## Code Sample \`\`\`typescript [Minimal code that reproduces issue] \`\`\` ## Error Message \`\`\` [Full error stack trace] \`\`\` ## Debug Logs \`\`\` [Output from DEBUG=neurolink:* node your-app.js] \`\`\` ``` ### Community Resources - **GitHub Issues**: [Report bugs](https://github.com/juspa