All files / src/failover index.ts

19.14% Statements 18/94
85.71% Branches 6/7
27.27% Functions 3/11
19.14% Lines 18/94

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151                                    1x                                           1x 3x 3x   2x   2x                                           2x 2x       2x       2x                                             2x 1x 1x 2x 2x       1x 1x 1x                                                                                
/**
 * AgentKits — Auto-Failover
 *
 * Wraps createChat/createEmbedding with automatic fallback.
 * If the primary provider fails, seamlessly switches to the next one.
 *
 * Usage:
 *   import { createChatWithFailover } from 'agentkits/failover';
 *   const chat = createChatWithFailover({
 *     providers: [
 *       { provider: 'deepseek', apiKey: 'sk-...' },
 *       { provider: 'dashscope', apiKey: 'sk-...' },
 *       { provider: 'ollama' },
 *     ]
 *   });
 *   const reply = await chat.complete('Hello'); // tries deepseek → dashscope → ollama
 */
 
import { createChat, createEmbedding } from '../index.js';
import type { ChatConfig, ChatClient, ChatMessage, ChatResponse, StreamChunk } from '../llm/index.js';
import type { EmbeddingConfig, EmbeddingClient } from '../embedding/index.js';
 
// ── Types ──────────────────────────────────────────────────────────
 
export interface FailoverChatConfig {
  providers: ChatConfig[];
  /** Max retries per provider before moving to next (default: 1) */
  retriesPerProvider?: number;
  /** Called when a provider fails and we switch to the next */
  onFailover?: (from: string, to: string, error: Error) => void;
}
 
export interface FailoverEmbeddingConfig {
  providers: EmbeddingConfig[];
  retriesPerProvider?: number;
  onFailover?: (from: string, to: string, error: Error) => void;
}
 
// ── Chat Failover ──────────────────────────────────────────────────
 
export function createChatWithFailover(config: FailoverChatConfig): ChatClient {
  const { providers, retriesPerProvider = 1, onFailover } = config;
  if (providers.length === 0) throw new Error('At least one provider is required');
 
  const clients = providers.map(p => createChat(p));
 
  async function withFailover<T>(fn: (client: ChatClient) => Promise<T>): Promise<T> {
    let lastError: Error | null = null;
 
    for (let i = 0; i < clients.length; i++) {
      for (let retry = 0; retry < retriesPerProvider; retry++) {
        try {
          return await fn(clients[i]);
        } catch (e: any) {
          lastError = e;
          if (retry === retriesPerProvider - 1 && i < clients.length - 1) {
            onFailover?.(
              clients[i].config.provider,
              clients[i + 1].config.provider,
              e
            );
          }
        }
      }
    }
    throw lastError ?? new Error('All providers failed');
  }
 
  return {
    async complete(prompt, options) {
      return withFailover(c => c.complete(prompt, options));
    },
 
    async chat(messages, options) {
      return withFailover(c => c.chat(messages, options));
    },
 
    async *stream(messages, options) {
      let lastError: Error | null = null;
 
      for (let i = 0; i < clients.length; i++) {
        try {
          for await (const chunk of clients[i].stream(messages, options)) {
            yield chunk;
          }
          return;
        } catch (e: any) {
          lastError = e;
          if (i < clients.length - 1) {
            onFailover?.(
              clients[i].config.provider,
              clients[i + 1].config.provider,
              e
            );
          }
        }
      }
      throw lastError ?? new Error('All providers failed');
    },
 
    get config() {
      return clients[0].config;
    },
  };
}
 
// ── Embedding Failover ─────────────────────────────────────────────
 
export function createEmbeddingWithFailover(config: FailoverEmbeddingConfig): EmbeddingClient {
  const { providers, retriesPerProvider = 1, onFailover } = config;
  if (providers.length === 0) throw new Error('At least one provider is required');
 
  const clients = providers.map(p => createEmbedding(p));
 
  async function withFailover<T>(fn: (client: EmbeddingClient) => Promise<T>): Promise<T> {
    let lastError: Error | null = null;
 
    for (let i = 0; i < clients.length; i++) {
      for (let retry = 0; retry < retriesPerProvider; retry++) {
        try {
          return await fn(clients[i]);
        } catch (e: any) {
          lastError = e;
          if (retry === retriesPerProvider - 1 && i < clients.length - 1) {
            onFailover?.(
              clients[i].config.provider,
              clients[i + 1].config.provider,
              e
            );
          }
        }
      }
    }
    throw lastError ?? new Error('All providers failed');
  }
 
  return {
    async embed(text) {
      return withFailover(c => c.embed(text));
    },
 
    async embedBatch(texts) {
      return withFailover(c => c.embedBatch(texts));
    },
 
    get config() {
      return clients[0].config;
    },
  };
}