File size: 9,273 Bytes
bfc7d04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
// LLM Service - Multi-provider LLM client for Stack 2.9
//
// Supports: OpenAI, Anthropic, Ollama, and custom endpoints
// with automatic fallback on failure.

export type LLMProviderType = 'openai' | 'anthropic' | 'ollama' | 'custom'

export interface LLMConfig {
  provider: LLMProviderType
  apiKey?: string
  baseURL?: string
  model: string
  maxTokens?: number
  temperature?: number
  topP?: number
}

export interface ChatMessage {
  role: 'system' | 'user' | 'assistant'
  content: string
}

export interface ChatParams {
  messages: ChatMessage[]
  model?: string
  maxTokens?: number
  temperature?: number
  topP?: number
  tools?: unknown[]
}

export interface ChatResponse {
  content: string
  model: string
  usage?: {
    inputTokens: number
    outputTokens: number
  }
  finishReason: 'stop' | 'length' | 'content_filter' | null
}

export interface LLMProvider {
  readonly type: LLMProviderType
  readonly name: string

  isAvailable(): boolean
  chat(params: ChatParams): Promise<ChatResponse>
  listModels(): string[]
}

// ─── OpenAI Provider ───

export class OpenAIProvider implements LLMProvider {
  readonly type: LLMProviderType = 'openai'
  readonly name = 'OpenAI'

  private apiKey: string
  private baseURL: string
  private model: string

  constructor(config: { apiKey: string; baseURL?: string; model?: string }) {
    this.apiKey = config.apiKey
    this.baseURL = config.baseURL ?? 'https://api.openai.com/v1'
    this.model = config.model ?? 'gpt-4'
  }

  isAvailable(): boolean {
    return Boolean(this.apiKey)
  }

  async chat(params: ChatParams): Promise<ChatResponse> {
    const response = await fetch(`${this.baseURL}/chat/completions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.apiKey}`,
      },
      body: JSON.stringify({
        model: params.model ?? this.model,
        messages: params.messages,
        max_tokens: params.maxTokens,
        temperature: params.temperature,
        top_p: params.topP,
        tools: params.tools,
      }),
    })

    if (!response.ok) {
      throw new Error(`OpenAI API error: ${response.status} ${response.statusText}`)
    }

    const data = await response.json() as {
      choices: Array<{ message: { content: string }; finish_reason: string }>
      model: string
      usage: { prompt_tokens: number; completion_tokens: number }
    }

    return {
      content: data.choices[0]?.message?.content ?? '',
      model: data.model,
      usage: {
        inputTokens: data.usage?.prompt_tokens ?? 0,
        outputTokens: data.usage?.completion_tokens ?? 0,
      },
      finishReason: data.choices[0]?.finish_reason as ChatResponse['finishReason'],
    }
  }

  listModels(): string[] {
    return ['gpt-4', 'gpt-4-turbo', 'gpt-3.5-turbo', 'gpt-4o']
  }
}

// ─── Anthropic Provider ───

export class AnthropicProvider implements LLMProvider {
  readonly type: LLMProviderType = 'anthropic'
  readonly name = 'Anthropic'

  private apiKey: string
  private baseURL: string
  private model: string

  constructor(config: { apiKey: string; baseURL?: string; model?: string }) {
    this.apiKey = config.apiKey
    this.baseURL = config.baseURL ?? 'https://api.anthropic.com'
    this.model = config.model ?? 'claude-3-sonnet-20240229'
  }

  isAvailable(): boolean {
    return Boolean(this.apiKey)
  }

  async chat(params: ChatParams): Promise<ChatResponse> {
    // Extract system message
    const systemMessage = params.messages.find(m => m.role === 'system')?.content
    const filteredMessages = params.messages.filter(m => m.role !== 'system')

    const response = await fetch(`${this.baseURL}/v1/messages`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': this.apiKey,
        'anthropic-version': '2023-06-01',
      },
      body: JSON.stringify({
        model: params.model ?? this.model,
        messages: filteredMessages,
        system: systemMessage,
        max_tokens: params.maxTokens ?? 1024,
        temperature: params.temperature,
        top_p: params.topP,
      }),
    })

    if (!response.ok) {
      throw new Error(`Anthropic API error: ${response.status} ${response.statusText}`)
    }

    const data = await response.json() as {
      content: Array<{ type: string; text?: string }>
      model: string
      usage: { input_tokens: number; output_tokens: number }
      stop_reason: string
    }

    return {
      content: data.content.find(c => c.type === 'text')?.text ?? '',
      model: data.model,
      usage: {
        inputTokens: data.usage?.input_tokens ?? 0,
        outputTokens: data.usage?.output_tokens ?? 0,
      },
      finishReason: data.stop_reason as ChatResponse['finishReason'],
    }
  }

  listModels(): string[] {
    return ['claude-3-opus', 'claude-3-sonnet', 'claude-3-haiku']
  }
}

// ─── Ollama Provider ───

export class OllamaProvider implements LLMProvider {
  readonly type: LLMProviderType = 'ollama'
  readonly name = 'Ollama'

  private baseURL: string
  private model: string

  constructor(config: { baseURL?: string; model?: string }) {
    this.baseURL = config.baseURL ?? 'http://localhost:11434'
    this.model = config.model ?? 'llama2'
  }

  isAvailable(): boolean {
    return true // Ollama is local, always available if running
  }

  async chat(params: ChatParams): Promise<ChatResponse> {
    const response = await fetch(`${this.baseURL}/api/chat`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        model: params.model ?? this.model,
        messages: params.messages,
        options: {
          temperature: params.temperature,
          top_p: params.topP,
          num_predict: params.maxTokens,
        },
        stream: false,
      }),
    })

    if (!response.ok) {
      throw new Error(`Ollama error: ${response.status} ${response.statusText}`)
    }

    const data = await response.json() as {
      message: { content: string }
      model: string
    }

    return {
      content: data.message?.content ?? '',
      model: data.model,
      finishReason: 'stop',
    }
  }

  async listModels(): Promise<string[]> {
    try {
      const response = await fetch(`${this.baseURL}/api/tags`)
      if (!response.ok) return [this.model]

      const data = await response.json() as { models: Array<{ name: string }> }
      return data.models.map(m => m.name)
    } catch {
      return [this.model]
    }
  }
}

// ─── LLM Router ───

export class LLMRouter {
  private providers: Map<LLMProviderType, LLMProvider> = new Map()
  private defaultProvider: LLMProviderType = 'ollama'

  addProvider(provider: LLMProvider): void {
    this.providers.set(provider.type, provider)
  }

  setDefault(provider: LLMProviderType): void {
    if (!this.providers.has(provider)) {
      throw new Error(`Provider ${provider} not configured`)
    }
    this.defaultProvider = provider
  }

  getProvider(type?: LLMProviderType): LLMProvider {
    const provider = type ?? this.defaultProvider
    const instance = this.providers.get(provider)
    if (!instance) {
      throw new Error(`Provider ${provider} not configured`)
    }
    return instance
  }

  async chat(params: ChatParams & { provider?: LLMProviderType }): Promise<ChatResponse> {
    const provider = this.getProvider(params.provider)
    return provider.chat(params)
  }
}

// ─── Factory ───

export function createProvider(config: LLMConfig): LLMProvider {
  switch (config.provider) {
    case 'openai':
      return new OpenAIProvider({
        apiKey: config.apiKey ?? '',
        baseURL: config.baseURL,
        model: config.model,
      })
    case 'anthropic':
      return new AnthropicProvider({
        apiKey: config.apiKey ?? '',
        baseURL: config.baseURL,
        model: config.model,
      })
    case 'ollama':
      return new OllamaProvider({
        baseURL: config.baseURL,
        model: config.model,
      })
    default:
      throw new Error(`Unknown provider: ${config.provider}`)
  }
}

export function createRouter(configs: LLMConfig[]): LLMRouter {
  const router = new LLMRouter()

  for (const config of configs) {
    router.addProvider(createProvider(config))
  }

  return router
}

// Default router from environment
export function createRouterFromEnv(): LLMRouter {
  const configs: LLMConfig[] = []

  // Check for OpenAI
  if (process.env.OPENAI_API_KEY) {
    configs.push({
      provider: 'openai',
      apiKey: process.env.OPENAI_API_KEY,
      model: process.env.OPENAI_MODEL ?? 'gpt-4',
    })
  }

  // Check for Anthropic
  if (process.env.ANTHROPIC_API_KEY) {
    configs.push({
      provider: 'anthropic',
      apiKey: process.env.ANTHROPIC_API_KEY,
      model: process.env.ANTHROPIC_MODEL ?? 'claude-3-sonnet-20240229',
    })
  }

  // Always add Ollama (local)
  configs.push({
    provider: 'ollama',
    baseURL: process.env.OLLAMA_BASE_URL,
    model: process.env.OLLAMA_MODEL ?? 'llama2',
  })

  return createRouter(configs)
}

export default {
  OpenAIProvider,
  AnthropicProvider,
  OllamaProvider,
  LLMRouter,
  createProvider,
  createRouter,
  createRouterFromEnv,
}