-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathServiceCollectionExtensions.cs
More file actions
503 lines (421 loc) · 22.5 KB
/
ServiceCollectionExtensions.cs
File metadata and controls
503 lines (421 loc) · 22.5 KB
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
using System.ClientModel;
using System.ClientModel.Primitives;
using System.Threading.RateLimiting;
using Amazon;
using Amazon.BedrockRuntime;
using Anthropic;
using Azure;
using Azure.AI.Inference;
using Cellm.AddIn;
using Cellm.AddIn.Exceptions;
using Cellm.AddIn.Logging;
using Cellm.Models.Prompts;
using Cellm.Models.Providers;
using Cellm.Models.Providers.Anthropic;
using Cellm.Models.Providers.Aws;
using Cellm.Models.Providers.Azure;
using Cellm.Models.Providers.Cellm;
using Cellm.Models.Providers.DeepSeek;
using Cellm.Models.Providers.Google;
using Cellm.Models.Providers.Mistral;
using Cellm.Models.Providers.Ollama;
using Cellm.Models.Providers.OpenAi;
using Cellm.Models.Providers.OpenAiCompatible;
using Cellm.Models.Providers.OpenRouter;
using Cellm.Models.Resilience;
using Cellm.Users;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OllamaSharp;
using OpenAI;
using Polly;
using Polly.Retry;
using Polly.Telemetry;
using Polly.Timeout;
namespace Cellm.Models;
internal static class ServiceCollectionExtensions
{
internal static IServiceCollection AddRateLimiter(this IServiceCollection services, ResilienceConfiguration resilienceConfiguration)
{
return services.AddResiliencePipeline<string, Prompt>("RateLimiter", (builder, context) =>
{
// Decrease severity of most Polly events
var telemetryOptions = new TelemetryOptions(context.GetOptions<TelemetryOptions>())
{
SeverityProvider = args => args.Event.EventName switch
{
"OnRetry" => ResilienceEventSeverity.Information,
_ => ResilienceEventSeverity.Debug
}
};
builder
.AddRateLimiter(new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions
{
QueueLimit = resilienceConfiguration.RateLimiterConfiguration.RateLimiterQueueLimit,
TokenLimit = resilienceConfiguration.RateLimiterConfiguration.TokenLimit,
ReplenishmentPeriod = TimeSpan.FromSeconds(resilienceConfiguration.RateLimiterConfiguration.ReplenishmentPeriodInSeconds),
TokensPerPeriod = resilienceConfiguration.RateLimiterConfiguration.TokensPerPeriod,
}))
.AddConcurrencyLimiter(new ConcurrencyLimiterOptions
{
QueueLimit = resilienceConfiguration.RateLimiterConfiguration.ConcurrencyLimiterQueueLimit,
PermitLimit = resilienceConfiguration.RateLimiterConfiguration.ConcurrencyLimit,
})
.AddRetry(new RetryStrategyOptions<Prompt>
{
ShouldHandle = args => ValueTask.FromResult(RateLimiterHelpers.ShouldRetry(args.Outcome)),
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
MaxRetryAttempts = resilienceConfiguration.RetryConfiguration.MaxRetryAttempts,
Delay = TimeSpan.FromSeconds(resilienceConfiguration.RetryConfiguration.DelayInSeconds),
})
.ConfigureTelemetry(telemetryOptions)
.Build();
});
}
public static IServiceCollection AddResilientHttpClient(this IServiceCollection services, ResilienceConfiguration resilienceConfiguration, CellmAddInConfiguration cellmAddInConfiguration, Provider provider)
{
var httpClientBuilder = services
.AddHttpClient(provider.ToString(), resilientHttpClient =>
{
// Delegate timeout to resilience pipeline
resilientHttpClient.Timeout = Timeout.InfiniteTimeSpan;
})
.AddAsKeyed(ServiceLifetime.Transient);
// Only add the logging handler if body logging is enabled
if (cellmAddInConfiguration.EnableHttpBodyLogging)
{
httpClientBuilder.AddHttpMessageHandler(serviceProvider =>
new HttpBodyLoggingHandler(
serviceProvider.GetRequiredService<ILogger<HttpBodyLoggingHandler>>(),
cellmAddInConfiguration.HttpBodyLogMaxLengthBytes));
}
// Strip thinking content parts from Magistral responses before the OpenAI SDK deserializes them
if (provider is Provider.Mistral or Provider.Cellm)
{
httpClientBuilder.AddHttpMessageHandler(() => new StripThinkingContentHandler());
}
httpClientBuilder
.AddResilienceHandler("ResilientHttpClientHandler", (builder, context) =>
{
// Decrease severity of most Polly events
var telemetryOptions = new TelemetryOptions(context.GetOptions<TelemetryOptions>())
{
SeverityProvider = args => args.Event.EventName switch
{
"OnRetry" => ResilienceEventSeverity.Information,
_ => ResilienceEventSeverity.Debug
}
};
builder
.AddRetry(new RetryStrategyOptions<HttpResponseMessage>
{
ShouldHandle = args => ValueTask.FromResult(RetryHttpClientHelpers.ShouldRetry(args.Outcome)),
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
MaxRetryAttempts = resilienceConfiguration.RetryConfiguration.MaxRetryAttempts,
Delay = TimeSpan.FromSeconds(resilienceConfiguration.RetryConfiguration.DelayInSeconds),
})
.AddTimeout(new TimeoutStrategyOptions
{
Timeout = TimeSpan.FromSeconds(resilienceConfiguration.RetryConfiguration.HttpTimeoutInSeconds),
})
.ConfigureTelemetry(telemetryOptions)
.Build();
});
return services;
}
public static HttpClient GetResilientHttpClient(this IServiceProvider serviceProvider, Provider provider)
{
return serviceProvider.GetKeyedService<HttpClient>(provider.ToString())
?? throw new InvalidOperationException($"No HttpClient registered for {provider}. Ensure AddRetryHttpClient was called for this provider.");
}
public static IServiceCollection AddAnthropicChatClient(this IServiceCollection services)
{
services
.AddKeyedChatClient(Provider.Anthropic, serviceProvider =>
{
var account = serviceProvider.GetRequiredService<Account>();
account.ThrowIfNotEntitled(Entitlement.EnableAnthropicProvider);
var anthropicConfiguration = serviceProvider.GetRequiredService<IOptionsMonitor<AnthropicConfiguration>>();
var resilienceConfiguration = serviceProvider.GetRequiredService<IOptionsMonitor<ResilienceConfiguration>>();
var resilientHttpClient = serviceProvider.GetResilientHttpClient(Provider.Anthropic);
if (string.IsNullOrWhiteSpace(anthropicConfiguration.CurrentValue.ApiKey))
{
throw new CellmException($"Empty {nameof(AnthropicConfiguration.ApiKey)} for {Provider.Anthropic}. Please set your API key.");
}
var anthropicClient = new AnthropicClient()
{
ApiKey = anthropicConfiguration.CurrentValue.ApiKey,
HttpClient = resilientHttpClient,
MaxRetries = 0, // Retries handled by resilience pipeline
Timeout = TimeSpan.FromSeconds(
resilienceConfiguration.CurrentValue.RetryConfiguration.HttpTimeoutInSeconds)
};
return anthropicClient.AsIChatClient(anthropicConfiguration.CurrentValue.DefaultModel);
}, ServiceLifetime.Transient)
.UseFunctionInvocation();
return services;
}
public static IServiceCollection AddAwsChatClient(this IServiceCollection services)
{
services
.AddKeyedChatClient(Provider.Aws, serviceProvider =>
{
var account = serviceProvider.GetRequiredService<Account>();
account.ThrowIfNotEntitled(Entitlement.EnableAwsProvider);
var awsConfiguration = serviceProvider.GetRequiredService<IOptionsMonitor<AwsConfiguration>>();
if (string.IsNullOrWhiteSpace(awsConfiguration.CurrentValue.ApiKey))
{
throw new CellmException($"Empty {nameof(AwsConfiguration.ApiKey)} {Provider.Aws}. Please set your API key.");
}
var parts = awsConfiguration.CurrentValue.ApiKey.Split(':');
if (parts.Length < 3)
{
throw new CellmException("Invalid AWS API key or invalid format (must be \"Region:AccessKeyId:SecretAccessKey\", e.g. us-east-1:AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY)");
}
var region = parts[0];
var accessKeyId = parts[1];
var secretAccessKey = string.Join(':', parts[2..]);
return new AmazonBedrockRuntimeClient(accessKeyId, secretAccessKey, RegionEndpoint.GetBySystemName(region))
.AsIChatClient(awsConfiguration.CurrentValue.DefaultModel);
}, ServiceLifetime.Transient)
.UseFunctionInvocation();
return services;
}
public static IServiceCollection AddAzureChatClient(this IServiceCollection services)
{
services
.AddKeyedChatClient(Provider.Azure, serviceProvider =>
{
var account = serviceProvider.GetRequiredService<Account>();
account.ThrowIfNotEntitled(Entitlement.EnableAzureProvider);
var azureConfiguration = serviceProvider.GetRequiredService<IOptionsMonitor<AzureConfiguration>>();
if (string.IsNullOrWhiteSpace(azureConfiguration.CurrentValue.ApiKey))
{
throw new CellmException($"Empty {nameof(AzureConfiguration.ApiKey)} for {Provider.Azure}. Please set your API key.");
}
return new ChatCompletionsClient(
azureConfiguration.CurrentValue.BaseAddress,
new AzureKeyCredential(azureConfiguration.CurrentValue.ApiKey))
.AsIChatClient(azureConfiguration.CurrentValue.DefaultModel);
}, ServiceLifetime.Transient)
.UseFunctionInvocation();
return services;
}
public static IServiceCollection AddCellmChatClient(this IServiceCollection services)
{
services
.AddKeyedChatClient(Provider.Cellm, serviceProvider =>
{
var account = serviceProvider.GetRequiredService<Account>();
account.ThrowIfNotEntitled(Entitlement.EnableCellmProvider);
var accountConfiguration = serviceProvider.GetRequiredService<IOptionsMonitor<AccountConfiguration>>();
if (string.IsNullOrWhiteSpace(accountConfiguration.CurrentValue.ApiKey))
{
throw new CellmException($"Invalid {Provider.Cellm} credentials. Please login again.");
}
var cellmConfiguration = serviceProvider.GetRequiredService<IOptionsMonitor<CellmConfiguration>>();
var resilientHttpClient = serviceProvider.GetResilientHttpClient(Provider.Cellm);
var openAiClient = new OpenAIClient(
new ApiKeyCredential(accountConfiguration.CurrentValue.ApiKey),
new OpenAIClientOptions
{
Transport = new HttpClientPipelineTransport(resilientHttpClient),
Endpoint = cellmConfiguration.CurrentValue.BaseAddress
});
return openAiClient.GetChatClient(cellmConfiguration.CurrentValue.DefaultModel).AsIChatClient();
}, ServiceLifetime.Transient)
.UseFunctionInvocation();
return services;
}
public static IServiceCollection AddDeepSeekChatClient(this IServiceCollection services)
{
services
.AddKeyedChatClient(Provider.DeepSeek, serviceProvider =>
{
var account = serviceProvider.GetRequiredService<Account>();
account.ThrowIfNotEntitled(Entitlement.EnableDeepSeekProvider);
var deepSeekConfiguration = serviceProvider.GetRequiredService<IOptionsMonitor<DeepSeekConfiguration>>();
var resilientHttpClient = serviceProvider.GetResilientHttpClient(Provider.DeepSeek);
if (string.IsNullOrWhiteSpace(deepSeekConfiguration.CurrentValue.ApiKey))
{
throw new CellmException($"Empty {nameof(DeepSeekConfiguration.ApiKey)} for {Provider.DeepSeek}. Please set your API key.");
}
var openAiClient = new OpenAIClient(
new ApiKeyCredential(deepSeekConfiguration.CurrentValue.ApiKey),
new OpenAIClientOptions
{
Transport = new HttpClientPipelineTransport(resilientHttpClient),
Endpoint = deepSeekConfiguration.CurrentValue.BaseAddress
});
return openAiClient.GetChatClient(deepSeekConfiguration.CurrentValue.DefaultModel).AsIChatClient();
}, ServiceLifetime.Transient)
.UseFunctionInvocation();
return services;
}
public static IServiceCollection AddGeminiChatClient(this IServiceCollection services)
{
services
.AddKeyedChatClient(Provider.Gemini, serviceProvider =>
{
var account = serviceProvider.GetRequiredService<Account>();
account.ThrowIfNotEntitled(Entitlement.EnableGeminiProvider);
var geminiConfiguration = serviceProvider.GetRequiredService<IOptionsMonitor<GeminiConfiguration>>();
var resilienceConfiguration = serviceProvider.GetRequiredService<IOptionsMonitor<ResilienceConfiguration>>();
if (string.IsNullOrWhiteSpace(geminiConfiguration.CurrentValue.ApiKey))
{
throw new CellmException($"Empty {nameof(GeminiConfiguration.ApiKey)} for {Provider.Gemini}. Please set your API key.");
}
// Google.GenAI does not support custom HttpClient injection,
// so HTTP-level retry/timeout from the resilience pipeline is unavailable.
var geminiClient = new Google.GenAI.Client(
apiKey: geminiConfiguration.CurrentValue.ApiKey,
httpOptions: new Google.GenAI.Types.HttpOptions
{
Timeout = (int)TimeSpan.FromSeconds(
resilienceConfiguration.CurrentValue.RetryConfiguration.HttpTimeoutInSeconds).TotalMilliseconds
});
return geminiClient.AsIChatClient(geminiConfiguration.CurrentValue.DefaultModel);
}, ServiceLifetime.Transient)
.UseFunctionInvocation();
return services;
}
public static IServiceCollection AddMistralChatClient(this IServiceCollection services)
{
services
.AddKeyedChatClient(Provider.Mistral, serviceProvider =>
{
var account = serviceProvider.GetRequiredService<Account>();
account.ThrowIfNotEntitled(Entitlement.EnableMistralProvider);
var mistralConfiguration = serviceProvider.GetRequiredService<IOptionsMonitor<MistralConfiguration>>();
var resilientHttpClient = serviceProvider.GetResilientHttpClient(Provider.Mistral);
if (string.IsNullOrWhiteSpace(mistralConfiguration.CurrentValue.ApiKey))
{
throw new CellmException($"Empty {nameof(MistralConfiguration.ApiKey)} for {Provider.Mistral}. Please set your API key.");
}
var openAiClient = new OpenAIClient(
new ApiKeyCredential(mistralConfiguration.CurrentValue.ApiKey),
new OpenAIClientOptions
{
Transport = new HttpClientPipelineTransport(resilientHttpClient),
Endpoint = mistralConfiguration.CurrentValue.BaseAddress
});
return openAiClient.GetChatClient(mistralConfiguration.CurrentValue.DefaultModel).AsIChatClient();
}, ServiceLifetime.Transient)
.UseFunctionInvocation();
return services;
}
public static IServiceCollection AddOllamaChatClient(this IServiceCollection services)
{
services
.AddKeyedChatClient(Provider.Ollama, serviceProvider =>
{
var account = serviceProvider.GetRequiredService<Account>();
account.ThrowIfNotEntitled(Entitlement.EnableOllamaProvider);
var ollamaConfiguration = serviceProvider.GetRequiredService<IOptionsMonitor<OllamaConfiguration>>();
var resilientHttpClient = serviceProvider.GetResilientHttpClient(Provider.Ollama);
resilientHttpClient.BaseAddress = ollamaConfiguration.CurrentValue.BaseAddress;
return new OllamaApiClient(resilientHttpClient, ollamaConfiguration.CurrentValue.DefaultModel);
}, ServiceLifetime.Transient)
.UseFunctionInvocation();
return services;
}
public static IServiceCollection AddOpenAiChatClient(this IServiceCollection services)
{
services
.AddKeyedChatClient(Provider.OpenAi, serviceProvider =>
{
var account = serviceProvider.GetRequiredService<Account>();
account.ThrowIfNotEntitled(Entitlement.EnableOpenAiProvider);
var openAiConfiguration = serviceProvider.GetRequiredService<IOptionsMonitor<OpenAiConfiguration>>();
if (string.IsNullOrWhiteSpace(openAiConfiguration.CurrentValue.ApiKey))
{
throw new CellmException($"Empty {nameof(OpenAiConfiguration.ApiKey)} for {Provider.OpenAi}. Please set your API key.");
}
return new OpenAIClient(new ApiKeyCredential(openAiConfiguration.CurrentValue.ApiKey))
.GetChatClient(openAiConfiguration.CurrentValue.DefaultModel)
.AsIChatClient();
}, ServiceLifetime.Transient)
.UseFunctionInvocation();
return services;
}
public static IServiceCollection AddOpenAiCompatibleChatClient(this IServiceCollection services)
{
services
.AddKeyedChatClient(Provider.OpenAiCompatible, serviceProvider =>
{
var account = serviceProvider.GetRequiredService<Account>();
account.ThrowIfNotEntitled(Entitlement.EnableOpenAiCompatibleProvider);
var openAiCompatibleConfiguration = serviceProvider.GetRequiredService<IOptionsMonitor<OpenAiCompatibleConfiguration>>();
var resilientHttpClient = serviceProvider.GetResilientHttpClient(Provider.OpenAiCompatible);
if (openAiCompatibleConfiguration.CurrentValue.BaseAddress.IsLoopback)
{
account.ThrowIfNotEntitled(Entitlement.EnableOpenAiCompatibleProviderLocalModels);
}
else
{
account.ThrowIfNotEntitled(Entitlement.EnableOpenAiCompatibleProviderHostedModels);
}
if (string.IsNullOrWhiteSpace(openAiCompatibleConfiguration.CurrentValue.ApiKey))
{
throw new CellmException($"Empty {nameof(OpenAiCompatibleConfiguration.ApiKey)} for {Provider.OpenAiCompatible}. Please set your API key.");
}
var openAiClient = new OpenAIClient(
new ApiKeyCredential(openAiCompatibleConfiguration.CurrentValue.ApiKey),
new OpenAIClientOptions
{
Transport = new HttpClientPipelineTransport(resilientHttpClient),
Endpoint = openAiCompatibleConfiguration.CurrentValue.BaseAddress
});
return openAiClient
.GetChatClient(openAiCompatibleConfiguration.CurrentValue.DefaultModel)
.AsIChatClient();
}, ServiceLifetime.Transient)
.UseFunctionInvocation();
return services;
}
public static IServiceCollection AddOpenRouterChatClient(this IServiceCollection services)
{
services
.AddKeyedChatClient(Provider.OpenRouter, serviceProvider =>
{
var account = serviceProvider.GetRequiredService<Account>();
account.ThrowIfNotEntitled(Entitlement.EnableOpenRouterProvider);
var openRouterConfiguration = serviceProvider.GetRequiredService<IOptionsMonitor<OpenRouterConfiguration>>();
var resilientHttpClient = serviceProvider.GetResilientHttpClient(Provider.OpenRouter);
if (string.IsNullOrWhiteSpace(openRouterConfiguration.CurrentValue.ApiKey))
{
throw new CellmException($"Empty {nameof(OpenRouterConfiguration.ApiKey)} for {Provider.OpenRouter}. Please set your API key.");
}
var openAiClient = new OpenAIClient(
new ApiKeyCredential(openRouterConfiguration.CurrentValue.ApiKey),
new OpenAIClientOptions
{
Transport = new HttpClientPipelineTransport(resilientHttpClient),
Endpoint = openRouterConfiguration.CurrentValue.BaseAddress
});
return openAiClient.GetChatClient(openRouterConfiguration.CurrentValue.DefaultModel).AsIChatClient();
}, ServiceLifetime.Transient)
.UseFunctionInvocation();
return services;
}
public static IServiceCollection AddTools(this IServiceCollection services, params Delegate[] tools)
{
foreach (var tool in tools)
{
services.AddSingleton(AIFunctionFactory.Create(tool));
}
return services;
}
public static IServiceCollection AddTools(this IServiceCollection services, params Func<IServiceProvider, AIFunction>[] toolBuilders)
{
foreach (var toolBuilder in toolBuilders)
{
services.AddSingleton((serviceProvider) => toolBuilder(serviceProvider));
}
return services;
}
}