|
| 1 | +using System.Runtime.CompilerServices; |
| 2 | +using AiDotNet.Agentic.Models; |
| 3 | + |
| 4 | +// Disambiguate from the legacy AiDotNet.PromptEngineering.Templates.ChatMessage (global using). |
| 5 | +using ChatMessage = AiDotNet.Agentic.Models.ChatMessage; |
| 6 | + |
| 7 | +namespace AiDotNet.Agentic.Models.Local; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// An <see cref="IChatClient{T}"/> that runs entirely in-process over an <see cref="ICausalLanguageModel{T}"/> |
| 11 | +/// — no network, no API key, no external service. It renders the conversation to a prompt, encodes it, |
| 12 | +/// autoregressively samples tokens until the end-of-sequence token or a length limit, and decodes the |
| 13 | +/// result. This is the flagship "local-first" capability: the same agent code that drives OpenAI or |
| 14 | +/// Anthropic drives AiDotNet's own model. |
| 15 | +/// </summary> |
| 16 | +/// <typeparam name="T">The tensor element type shared with the model.</typeparam> |
| 17 | +/// <remarks> |
| 18 | +/// <para> |
| 19 | +/// Because it implements <see cref="IChatClient{T}"/>, the local engine is a drop-in for every higher layer |
| 20 | +/// (agents, supervisor/swarm, memory). Both non-streaming and streaming generation are supported; streaming |
| 21 | +/// decodes incrementally and yields the new text on each step. Native tool-calling and structured-output |
| 22 | +/// constraints are not applied by this slice (they require constrained decoding, a follow-up) — supplied |
| 23 | +/// tools are ignored and the engine produces plain text. |
| 24 | +/// </para> |
| 25 | +/// <para><b>For Beginners:</b> This is your own chatbot brain running on your machine. You hand it the |
| 26 | +/// conversation; it writes the reply one word-piece at a time until it decides it's done or hits the length |
| 27 | +/// cap. Everything else in this library that talks to a "chat model" can talk to this one instead — so you |
| 28 | +/// can build agents with no cloud dependency at all. |
| 29 | +/// </para> |
| 30 | +/// </remarks> |
| 31 | +public sealed class LocalEngineChatClient<T> : IChatClient<T> |
| 32 | +{ |
| 33 | + private readonly ICausalLanguageModel<T> _model; |
| 34 | + private readonly IGenerationTokenizer _tokenizer; |
| 35 | + private readonly IChatPromptTemplate _template; |
| 36 | + private readonly LocalEngineOptions _options; |
| 37 | + |
| 38 | + /// <summary> |
| 39 | + /// Initializes a new local engine. |
| 40 | + /// </summary> |
| 41 | + /// <param name="model">The in-process language model that produces next-token logits.</param> |
| 42 | + /// <param name="tokenizer">The tokenizer used to encode prompts and decode generated tokens.</param> |
| 43 | + /// <param name="template">The chat prompt template. <c>null</c> uses <see cref="ChatMlPromptTemplate"/>.</param> |
| 44 | + /// <param name="options">Engine settings. <c>null</c> uses defaults.</param> |
| 45 | + /// <exception cref="ArgumentNullException">Thrown when <paramref name="model"/> or <paramref name="tokenizer"/> is <c>null</c>.</exception> |
| 46 | + public LocalEngineChatClient( |
| 47 | + ICausalLanguageModel<T> model, |
| 48 | + IGenerationTokenizer tokenizer, |
| 49 | + IChatPromptTemplate? template = null, |
| 50 | + LocalEngineOptions? options = null) |
| 51 | + { |
| 52 | + Guard.NotNull(model); |
| 53 | + Guard.NotNull(tokenizer); |
| 54 | + _model = model; |
| 55 | + _tokenizer = tokenizer; |
| 56 | + _template = template ?? new ChatMlPromptTemplate(); |
| 57 | + _options = options ?? new LocalEngineOptions(); |
| 58 | + } |
| 59 | + |
| 60 | + /// <inheritdoc/> |
| 61 | + public string ModelId => |
| 62 | + _options.ModelId is { } id && id.Trim().Length > 0 ? id : "local"; |
| 63 | + |
| 64 | + /// <inheritdoc/> |
| 65 | + /// <exception cref="ArgumentNullException">Thrown when <paramref name="messages"/> is <c>null</c>.</exception> |
| 66 | + /// <exception cref="ArgumentException">Thrown when <paramref name="messages"/> is empty.</exception> |
| 67 | + public Task<ChatResponse> GetResponseAsync( |
| 68 | + IReadOnlyList<ChatMessage> messages, |
| 69 | + ChatOptions? options = null, |
| 70 | + CancellationToken cancellationToken = default) |
| 71 | + { |
| 72 | + var promptIds = BuildPromptIds(messages); |
| 73 | + var sampling = ResolveSampling(options); |
| 74 | + var sampler = new TokenSampler<T>(sampling.Seed); |
| 75 | + var maxTokens = ResolveMaxTokens(options); |
| 76 | + |
| 77 | + var generated = new List<int>(); |
| 78 | + var finishReason = RunGeneration(promptIds, maxTokens, sampler, sampling, generated, cancellationToken); |
| 79 | + |
| 80 | + var text = generated.Count > 0 ? _tokenizer.Decode(generated) : string.Empty; |
| 81 | + var usage = new ChatUsage(promptIds.Count, generated.Count); |
| 82 | + var response = new ChatResponse(ChatMessage.Assistant(text), finishReason, usage, ModelId); |
| 83 | + return Task.FromResult(response); |
| 84 | + } |
| 85 | + |
| 86 | + /// <inheritdoc/> |
| 87 | + public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync( |
| 88 | + IReadOnlyList<ChatMessage> messages, |
| 89 | + ChatOptions? options = null, |
| 90 | + [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| 91 | + { |
| 92 | + await Task.CompletedTask.ConfigureAwait(false); |
| 93 | + |
| 94 | + var promptIds = BuildPromptIds(messages); |
| 95 | + var sampling = ResolveSampling(options); |
| 96 | + var sampler = new TokenSampler<T>(sampling.Seed); |
| 97 | + var maxTokens = ResolveMaxTokens(options); |
| 98 | + |
| 99 | + yield return new ChatResponseUpdate(role: ChatRole.Assistant); |
| 100 | + |
| 101 | + var context = new List<int>(promptIds); |
| 102 | + var generated = new List<int>(); |
| 103 | + var previousText = string.Empty; |
| 104 | + var finishReason = ChatFinishReason.Length; |
| 105 | + |
| 106 | + for (var step = 0; step < maxTokens; step++) |
| 107 | + { |
| 108 | + cancellationToken.ThrowIfCancellationRequested(); |
| 109 | + |
| 110 | + var logits = _model.NextTokenLogits(context); |
| 111 | + var next = sampler.Sample(logits, sampling); |
| 112 | + if (next == _tokenizer.EosTokenId) |
| 113 | + { |
| 114 | + finishReason = ChatFinishReason.Stop; |
| 115 | + break; |
| 116 | + } |
| 117 | + |
| 118 | + generated.Add(next); |
| 119 | + context.Add(next); |
| 120 | + |
| 121 | + var fullText = _tokenizer.Decode(generated); |
| 122 | + if (fullText.Length > previousText.Length) |
| 123 | + { |
| 124 | + var delta = fullText.Substring(previousText.Length); |
| 125 | + previousText = fullText; |
| 126 | + yield return ChatResponseUpdate.ForText(delta); |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + yield return ChatResponseUpdate.ForFinish(finishReason, new ChatUsage(promptIds.Count, generated.Count)); |
| 131 | + } |
| 132 | + |
| 133 | + private ChatFinishReason RunGeneration( |
| 134 | + IReadOnlyList<int> promptIds, |
| 135 | + int maxTokens, |
| 136 | + TokenSampler<T> sampler, |
| 137 | + LocalSamplingOptions sampling, |
| 138 | + List<int> generated, |
| 139 | + CancellationToken cancellationToken) |
| 140 | + { |
| 141 | + var context = new List<int>(promptIds); |
| 142 | + for (var step = 0; step < maxTokens; step++) |
| 143 | + { |
| 144 | + cancellationToken.ThrowIfCancellationRequested(); |
| 145 | + |
| 146 | + var logits = _model.NextTokenLogits(context); |
| 147 | + var next = sampler.Sample(logits, sampling); |
| 148 | + if (next == _tokenizer.EosTokenId) |
| 149 | + { |
| 150 | + return ChatFinishReason.Stop; |
| 151 | + } |
| 152 | + |
| 153 | + generated.Add(next); |
| 154 | + context.Add(next); |
| 155 | + } |
| 156 | + |
| 157 | + return ChatFinishReason.Length; |
| 158 | + } |
| 159 | + |
| 160 | + private List<int> BuildPromptIds(IReadOnlyList<ChatMessage> messages) |
| 161 | + { |
| 162 | + Guard.NotNull(messages); |
| 163 | + if (messages.Count == 0) |
| 164 | + { |
| 165 | + throw new ArgumentException("The conversation must contain at least one message.", nameof(messages)); |
| 166 | + } |
| 167 | + |
| 168 | + var prompt = _template.Render(messages); |
| 169 | + return new List<int>(_tokenizer.Encode(prompt)); |
| 170 | + } |
| 171 | + |
| 172 | + private int ResolveMaxTokens(ChatOptions? options) |
| 173 | + { |
| 174 | + if (options?.MaxOutputTokens is { } requested && requested > 0) |
| 175 | + { |
| 176 | + return requested; |
| 177 | + } |
| 178 | + |
| 179 | + return _options.MaxOutputTokens is { } configured && configured > 0 |
| 180 | + ? configured |
| 181 | + : LocalEngineOptions.DefaultMaxOutputTokens; |
| 182 | + } |
| 183 | + |
| 184 | + private LocalSamplingOptions ResolveSampling(ChatOptions? options) |
| 185 | + { |
| 186 | + var defaults = _options.Sampling ?? new LocalSamplingOptions(); |
| 187 | + return new LocalSamplingOptions |
| 188 | + { |
| 189 | + Temperature = options?.Temperature ?? defaults.Temperature, |
| 190 | + TopK = options?.TopK ?? defaults.TopK, |
| 191 | + TopP = options?.TopP ?? defaults.TopP, |
| 192 | + Seed = options?.Seed ?? defaults.Seed, |
| 193 | + }; |
| 194 | + } |
| 195 | +} |
0 commit comments