-
Notifications
You must be signed in to change notification settings - Fork 216
Expand file tree
/
Copy pathFoundryLocalChatClientFactory.cs
More file actions
93 lines (80 loc) · 3.18 KB
/
FoundryLocalChatClientFactory.cs
File metadata and controls
93 lines (80 loc) · 3.18 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.AI.Foundry.Local;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging.Abstractions;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AIDevGallery.Samples.SharedCode;
/// <summary>
/// Factory for creating an IChatClient backed by Foundry Local SDK.
/// Handles the multi-step initialization (manager → catalog → model → load → chat client)
/// and wraps the SDK's OpenAIChatClient into an IChatClient via FoundryLocalChatClientAdapter.
/// </summary>
internal static class FoundryLocalChatClientFactory
{
public static async Task<IChatClient?> CreateAsync(string alias, string? variantId = null, CancellationToken cancellationToken = default)
{
try
{
if (!FoundryLocalManager.IsInitialized)
{
var config = new Configuration
{
AppName = "AIDevGallery-FoundryLocalExportedSample"
};
try
{
await FoundryLocalManager.CreateAsync(config, NullLogger.Instance);
}
catch (FoundryLocalException) when (FoundryLocalManager.IsInitialized)
{
Debug.WriteLine("[FoundryLocal] Manager already initialized by another caller; proceeding.");
}
}
var manager = FoundryLocalManager.Instance;
try
{
await manager.EnsureEpsDownloadedAsync();
}
catch (Exception ex)
{
Debug.WriteLine($"[FoundryLocal] EP registration issue: {ex.Message}");
}
var catalog = await manager.GetCatalogAsync();
var model = await catalog.GetModelAsync(alias);
if (model == null)
{
throw new InvalidOperationException($"Model '{alias}' not found in Foundry Local catalog.");
}
// Select the specific variant if requested and it differs from the auto-selected one
if (variantId != null && model.SelectedVariant.Id != variantId)
{
var targetVariant = model.Variants.FirstOrDefault(v => v.Id == variantId);
if (targetVariant != null)
{
model.SelectVariant(targetVariant);
}
}
if (!await model.IsLoadedAsync())
{
if (!await model.IsCachedAsync())
{
await model.DownloadAsync(null, cancellationToken);
}
await model.LoadAsync(cancellationToken);
}
var chatClient = await model.GetChatClientAsync();
var maxOutputTokens = (int?)model.SelectedVariant.Info.MaxOutputTokens;
return new FoundryLocalChatClientAdapter(chatClient, model.Id, maxOutputTokens);
}
catch (Exception ex)
{
Debug.WriteLine($"[FoundryLocal] Failed to create chat client for '{alias}': {ex.Message}");
throw;
}
}
}