diff --git a/CHANGELOG.md b/CHANGELOG.md index 88ac7ec..19a4dd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +- `ChatRunner.SupersedesEarlierContext` sends earlier prompts' context by its label alone: the latest prompt that carries a `PromptContext` the function accepts, and every prompt after it, send their context in full, and each earlier context goes to the model as its label with a note that it is not repeated. An application that sends the same document with each prompt no longer sends a copy of it for every earlier prompt. `SaveHistory` and the views keep every context's text; nothing changes for an application that does not set it. + ## [0.6.0] - 2026-11-30 Details and migration steps: [docs/en/changelogs/0.6.0.md](docs/en/changelogs/0.6.0.md) diff --git a/CHANGELOG.zh-TW.md b/CHANGELOG.zh-TW.md index 244e717..92833a0 100644 --- a/CHANGELOG.zh-TW.md +++ b/CHANGELOG.zh-TW.md @@ -8,6 +8,8 @@ Polhem.Chat 各套件的重要變更,每個版本只列幾項重點。每個 ## [Unreleased] +- `ChatRunner.SupersedesEarlierContext` 讓較早提問的 context 只送標籤:最近一則帶有此函式接受之 `PromptContext` 的提問,以及之後的每則提問,照常送出完整 context;更早的每份 context 只以標籤加一句「不再重送」的說明交給模型。每則提問都附上同一份文件的應用程式,不再為每則較早的提問各送一份。`SaveHistory` 與兩個 view 仍保留每份 context 的全文;沒設定的應用程式行為不變。 + ## [0.6.0] - 2026-11-30 詳細內容與遷移步驟:[docs/zh-TW/changelogs/0.6.0.md](docs/zh-TW/changelogs/0.6.0.md) diff --git a/src/Polhem.Chat/ChatConversation.cs b/src/Polhem.Chat/ChatConversation.cs index af794ed..90a7519 100644 --- a/src/Polhem.Chat/ChatConversation.cs +++ b/src/Polhem.Chat/ChatConversation.cs @@ -264,14 +264,25 @@ public void Clear() /// Returns the history to send to the model: the summaries this package keeps in it are left out, and so are /// messages that had nothing else; a prompt's context is joined with its text. /// - internal List CreateRequestMessages() + /// + /// When set, the context of each prompt before the latest one that carries a context it accepts is sent by its label + /// alone; see . + /// + internal List CreateRequestMessages(Func? supersedesEarlierContext = null) { + var superseding = supersedesEarlierContext is null + ? -1 + : _history.FindLastIndex(message => + message.Role == ChatRole.User && PromptContextRecord.ReadAll(message).Any(supersedesEarlierContext)); var messages = new List(_history.Count); - foreach (var message in _history) + for (var index = 0; index < _history.Count; index++) { + var message = _history[index]; if (!message.Contents.Any(content => content is UsageContent)) { - messages.Add(message.Role == ChatRole.User ? PromptContextRecord.ToRequest(message) : message); + messages.Add(message.Role == ChatRole.User + ? PromptContextRecord.ToRequest(message, labelsOnly: index < superseding) + : message); continue; } var contents = message.Contents.Where(content => content is not UsageContent).ToList(); diff --git a/src/Polhem.Chat/ChatRunner.cs b/src/Polhem.Chat/ChatRunner.cs index e6ed19e..2c68e87 100644 --- a/src/Polhem.Chat/ChatRunner.cs +++ b/src/Polhem.Chat/ChatRunner.cs @@ -72,6 +72,30 @@ public IChatClient Client /// Gets or sets the options sent with every request: model, instructions, tools and so on. public ChatOptions? Options { get; set; } + /// + /// Gets or sets the function that tells whether a prompt's context supersedes the context of earlier prompts, so + /// that those are sent by their labels alone. , the default, sends every prompt's context in + /// full. + /// + /// + /// + /// The model receives the whole history with every request, so an application that sends the same document with each + /// prompt sends a copy of it for every earlier prompt too, most of them out of date. When this is set, the latest + /// prompt that carries a it returns for, and every prompt after it, + /// send their context in full. Each context of an earlier prompt is sent as its label with a short note that it is not + /// repeated, so the model still knows what the prompt was about. When no prompt carries such a context, every + /// context is sent in full. + /// + /// + /// Only the request changes: the history that returns and the entries a view + /// shows keep every context's text. The function is read when a request is sent, so a change applies to the next + /// one. For example, context => context.Label == "Document" sends the document of the latest prompt that + /// carries one, and a function that always returns sends only the context of the latest + /// prompt that has any. + /// + /// + public Func? SupersedesEarlierContext { get; set; } + /// Gets a value indicating whether a turn is in progress. public bool IsRunning { @@ -255,7 +279,7 @@ private void ThrowIfRunning() /// private async Task StreamAsync(ChatTurn turn, CancellationToken cancellationToken) { - var messages = Conversation.CreateRequestMessages(); + var messages = Conversation.CreateRequestMessages(SupersedesEarlierContext); var requests = new RequestCounter(); turn.BeginCall(); while (true) @@ -278,7 +302,7 @@ private async Task StreamAsync(ChatTurn turn, CancellationToken cancellationToke // WARNING: The client runs the approved calls before it asks the model again. A stop that came with the // decision must end the turn here, or the calls would run after the user asked to stop. cancellationToken.ThrowIfCancellationRequested(); - messages = [.. Conversation.CreateRequestMessages(), .. turn.Messages]; + messages = [.. Conversation.CreateRequestMessages(SupersedesEarlierContext), .. turn.Messages]; requests.Continue(); } } diff --git a/src/Polhem.Chat/PromptContextRecord.cs b/src/Polhem.Chat/PromptContextRecord.cs index 6140a63..d7b8eec 100644 --- a/src/Polhem.Chat/PromptContextRecord.cs +++ b/src/Polhem.Chat/PromptContextRecord.cs @@ -17,6 +17,9 @@ internal static class PromptContextRecord { public const string LabelKey = "polhem.chat.contextLabel"; + /// What the model reads in place of a context that a later prompt supersedes. + public const string Superseded = "Sent with this earlier prompt and not repeated; a later prompt carries the current text."; + public static TextContent Create(PromptContext context) => new(context.Text) { @@ -48,7 +51,9 @@ public static string PromptText(ChatMessage message) => /// Returns the message as it is sent to the model: its context wrapped with each label and joined with the prompt's /// text into one text block, ahead of the files; or the message itself when it has no context. /// - public static ChatMessage ToRequest(ChatMessage message) + /// A message of the history. + /// Whether each context is sent as its label with in place of its text. + public static ChatMessage ToRequest(ChatMessage message, bool labelsOnly = false) { if (!message.Contents.Any(IsContext)) { @@ -60,7 +65,7 @@ public static ChatMessage ToRequest(ChatMessage message) { if (Read(content) is { } context) { - Append(builder, context); + Append(builder, labelsOnly ? new PromptContext(context.Label, Superseded) : context); } else { diff --git a/src/Polhem.Chat/PublicAPI.Unshipped.txt b/src/Polhem.Chat/PublicAPI.Unshipped.txt index 7dc5c58..54d330c 100644 --- a/src/Polhem.Chat/PublicAPI.Unshipped.txt +++ b/src/Polhem.Chat/PublicAPI.Unshipped.txt @@ -1 +1,3 @@ #nullable enable +Polhem.Chat.ChatRunner.SupersedesEarlierContext.get -> System.Func? +Polhem.Chat.ChatRunner.SupersedesEarlierContext.set -> void diff --git a/src/Polhem.Chat/README.md b/src/Polhem.Chat/README.md index 3af7c50..1b1b1a8 100644 --- a/src/Polhem.Chat/README.md +++ b/src/Polhem.Chat/README.md @@ -40,6 +40,14 @@ runner.MessageSending += (_, e) => }; ``` +The model receives the whole history with every request, so a document sent with each prompt is sent again for every +earlier prompt. `SupersedesEarlierContext` sends it once: the latest prompt that carries a context it accepts, and every +prompt after it, send their context in full, and earlier prompts send theirs by its label alone: + +```csharp +runner.SupersedesEarlierContext = context => context.Label is "Document" or "Selection"; +``` + `Conversation.SaveHistory()` and `LoadHistory(...)` take the history as `Microsoft.Extensions.AI` messages, which the application stores however it likes; each prompt's context is kept with it. diff --git a/tests/Polhem.Chat.UnitTests/EarlierContextTests.cs b/tests/Polhem.Chat.UnitTests/EarlierContextTests.cs new file mode 100644 index 0000000..50c2e3c --- /dev/null +++ b/tests/Polhem.Chat.UnitTests/EarlierContextTests.cs @@ -0,0 +1,158 @@ +using System.Text.Json; +using Microsoft.Extensions.AI; +using static Polhem.Chat.UnitTests.ScriptedChatClient; + +namespace Polhem.Chat.UnitTests; + +/// +/// : which prompts send their context in full, which send it by its +/// label alone, and what the history keeps. +/// +public class EarlierContextTests +{ + private const string Note = "Sent with this earlier prompt and not repeated; a later prompt carries the current text."; + + private static string Full(string label, string text) => $"\n{text}\n\n\n"; + + private static string ByLabel(string label) => $"\n{Note}\n\n\n"; + + /// Sends each prompt with the context given for it, in order. + private static async Task SendAllAsync(ChatRunner runner, params (string Text, PromptContext[] Context)[] prompts) + { + var next = 0; + runner.MessageSending += (_, e) => + { + foreach (var context in prompts[next].Context) + { + e.Context.Add(context); + } + }; + for (; next < prompts.Length; next++) + { + await runner.SendAsync(prompts[next].Text); + } + } + + [Fact(DisplayName = "Earlier prompts send the document by its label, and the latest one that carries it sends it in full")] + public async Task Send_OptionSet_EarlierContextGoesByLabel() + { + var client = new ScriptedChatClient(Text("Answer")); + var runner = new ChatRunner(client) { SupersedesEarlierContext = context => context.Label == "Document" }; + + await SendAllAsync( + runner, + ("Summarize it", [new PromptContext("Document", "Draft one.")]), + ("Shorten it", [new PromptContext("Document", "Draft two.")]), + ("And the title?", [])); + + Assert.Equal( + [ByLabel("Document") + "Summarize it", "Answer", Full("Document", "Draft two.") + "Shorten it", "Answer", "And the title?"], + client.Requests[^1].Select(message => message.Text)); + Assert.Equal( + [ByLabel("Document") + "Summarize it", "Answer", Full("Document", "Draft two.") + "Shorten it"], + client.Requests[1].Select(message => message.Text)); + } + + [Fact(DisplayName = "Every context before the chosen prompt goes by its label, and every context after it is sent in full")] + public async Task Send_OptionSet_OtherContextFollowsThePromptItBelongsTo() + { + var client = new ScriptedChatClient(Text("Answer")); + var runner = new ChatRunner(client) { SupersedesEarlierContext = context => context.Label == "Document" }; + + await SendAllAsync( + runner, + ("Fix this", [new PromptContext("Selection", "teh"), new PromptContext("Document", "Draft one.")]), + ("Summarize it", [new PromptContext("Document", "Draft two.")]), + ("And this?", [new PromptContext("Selection", "recieve")])); + + Assert.Equal( + [ + ByLabel("Selection") + ByLabel("Document") + "Fix this", + "Answer", + Full("Document", "Draft two.") + "Summarize it", + "Answer", + Full("Selection", "recieve") + "And this?", + ], + client.Requests[^1].Select(message => message.Text)); + } + + [Fact(DisplayName = "When no prompt carries a context the function accepts, every context is sent in full")] + public async Task Send_NothingAccepted_SendsEveryContextInFull() + { + var client = new ScriptedChatClient(Text("Answer")); + var runner = new ChatRunner(client) { SupersedesEarlierContext = context => context.Label == "Document" }; + + await SendAllAsync( + runner, + ("Fix this", [new PromptContext("Selection", "teh")]), + ("And this?", [new PromptContext("Selection", "recieve")])); + + Assert.Equal( + [Full("Selection", "teh") + "Fix this", "Answer", Full("Selection", "recieve") + "And this?"], + client.Requests[^1].Select(message => message.Text)); + } + + [Fact(DisplayName = "Without the option, every prompt sends its context in full, as before")] + public async Task Send_OptionNotSet_SendsEveryContextInFull() + { + var client = new ScriptedChatClient(Text("Answer")); + var runner = new ChatRunner(client); + + await SendAllAsync( + runner, + ("Summarize it", [new PromptContext("Document", "Draft one.")]), + ("Shorten it", [new PromptContext("Document", "Draft two.")])); + + Assert.Equal( + [Full("Document", "Draft one.") + "Summarize it", "Answer", Full("Document", "Draft two.") + "Shorten it"], + client.Requests[^1].Select(message => message.Text)); + } + + [Fact(DisplayName = "A prompt sent by its label keeps its files after the text")] + public async Task Send_OptionSet_EarlierPromptKeepsItsFiles() + { + var client = new ScriptedChatClient(Text("Answer")); + var runner = new ChatRunner(client) { SupersedesEarlierContext = _ => true }; + var picture = new ChatAttachmentLimits().Check("photo.png", AttachmentTests.Png, []).Attachment!; + var first = true; + runner.MessageSending += (_, e) => + { + e.Context.Add(new PromptContext("Document", first ? "Draft one." : "Draft two.")); + first = false; + }; + + await runner.SendAsync("Describe it", [picture], CancellationToken.None); + await runner.SendAsync("Again"); + + Assert.Collection( + client.Requests[^1][0].Contents, + content => Assert.Equal(ByLabel("Document") + "Describe it", Assert.IsType(content).Text), + content => Assert.Same(picture, content)); + } + + [Fact(DisplayName = "The history and the entries keep every context's text, and a saved history keeps every copy")] + public async Task SaveHistory_OptionSet_KeepsEveryContextInFull() + { + var client = new ScriptedChatClient(Text("Answer")); + var runner = new ChatRunner(client) { SupersedesEarlierContext = context => context.Label == "Document" }; + await SendAllAsync( + runner, + ("Summarize it", [new PromptContext("Document", "Draft one.")]), + ("Shorten it", [new PromptContext("Document", "Draft two.")])); + + Assert.Equal( + ["Draft one.", "Draft two."], + runner.Conversation.Entries.OfType().Select(entry => entry.Context.Single().Text)); + + var json = JsonSerializer.Serialize(runner.Conversation.SaveHistory(), AIJsonUtilities.DefaultOptions); + var loaded = new ChatConversation(); + loaded.LoadHistory(JsonSerializer.Deserialize>(json, AIJsonUtilities.DefaultOptions)!); + + Assert.Equal( + ["Draft one.", "Draft two."], + loaded.Entries.OfType().Select(entry => entry.Context.Single().Text)); + Assert.Equal( + [Full("Document", "Draft one.") + "Summarize it", "Answer", Full("Document", "Draft two.") + "Shorten it", "Answer"], + loaded.CreateRequestMessages().Select(message => message.Text)); + } +}