| 1 | #nullable enable |
| 2 | using System.ClientModel; |
| 3 | using Anthropic; |
| 4 | using Microsoft.Extensions.AI; |
| 5 | |
| 6 | namespace CascadeIDE.Services; |
| 7 | |
| 8 | internal static class CascadeIdeMafChatClientFactories |
| 9 | { |
| 10 | /// <summary>База OpenAI-совместимого API: к SDK нужен суффикс <c>/v1</c> (совпадает с прежним Http-клиентом: base + <c>v1/chat/completions</c>).</summary> |
| 11 | public static Uri NormalizeOpenAiCompatibleEndpoint(string baseUrl) |
| 12 | { |
| 13 | var t = (baseUrl ?? "").Trim().TrimEnd('/'); |
| 14 | if (t.Length == 0) |
| 15 | t = "https://api.openai.com"; |
| 16 | if (!t.EndsWith("/v1", StringComparison.OrdinalIgnoreCase)) |
| 17 | t += "/v1"; |
| 18 | return new Uri(t + "/", UriKind.Absolute); |
| 19 | } |
| 20 | |
| 21 | public static Microsoft.Extensions.AI.IChatClient? CreateOpenAiCompatibleChatClientOrNull(string apiKey, string baseUrl, string modelId) |
| 22 | { |
| 23 | if (string.IsNullOrWhiteSpace(apiKey)) |
| 24 | return null; |
| 25 | var model = (modelId ?? "").Trim(); |
| 26 | if (model.Length == 0) |
| 27 | return null; |
| 28 | |
| 29 | var cred = new ApiKeyCredential(apiKey.Trim()); |
| 30 | var opts = new OpenAI.OpenAIClientOptions { Endpoint = NormalizeOpenAiCompatibleEndpoint(baseUrl) }; |
| 31 | var root = new OpenAI.OpenAIClient(cred, opts); |
| 32 | return root.GetChatClient(model).AsIChatClient(); |
| 33 | } |
| 34 | |
| 35 | public static Microsoft.Extensions.AI.IChatClient? CreateAnthropicChatClientOrNull(string apiKey, string modelId) |
| 36 | { |
| 37 | if (string.IsNullOrWhiteSpace(apiKey)) |
| 38 | return null; |
| 39 | var model = (modelId ?? "").Trim(); |
| 40 | if (model.Length == 0) |
| 41 | return null; |
| 42 | |
| 43 | var native = new AnthropicClient { ApiKey = apiKey.Trim() }; |
| 44 | return native.AsIChatClient(model); |
| 45 | } |
| 46 | } |
| 47 | |