Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.zh-TW.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
17 changes: 14 additions & 3 deletions src/Polhem.Chat/ChatConversation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
/// </summary>
internal List<ChatMessage> CreateRequestMessages()
/// <param name="supersedesEarlierContext">
/// When set, the context of each prompt before the latest one that carries a context it accepts is sent by its label
/// alone; see <see cref="ChatRunner.SupersedesEarlierContext"/>.
/// </param>
internal List<ChatMessage> CreateRequestMessages(Func<PromptContext, bool>? supersedesEarlierContext = null)
{
var superseding = supersedesEarlierContext is null
? -1
: _history.FindLastIndex(message =>
message.Role == ChatRole.User && PromptContextRecord.ReadAll(message).Any(supersedesEarlierContext));
var messages = new List<ChatMessage>(_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();
Expand Down
28 changes: 26 additions & 2 deletions src/Polhem.Chat/ChatRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,30 @@ public IChatClient Client
/// <summary>Gets or sets the options sent with every request: model, instructions, tools and so on.</summary>
public ChatOptions? Options { get; set; }

/// <summary>
/// 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. <see langword="null"/>, the default, sends every prompt's context in
/// full.
/// </summary>
/// <remarks>
/// <para>
/// 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 <see cref="PromptContext"/> it returns <see langword="true"/> 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.
/// </para>
/// <para>
/// Only the request changes: the history that <see cref="ChatConversation.SaveHistory"/> 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, <c>context =&gt; context.Label == "Document"</c> sends the document of the latest prompt that
/// carries one, and a function that always returns <see langword="true"/> sends only the context of the latest
/// prompt that has any.
/// </para>
/// </remarks>
public Func<PromptContext, bool>? SupersedesEarlierContext { get; set; }

/// <summary>Gets a value indicating whether a turn is in progress.</summary>
public bool IsRunning
{
Expand Down Expand Up @@ -255,7 +279,7 @@ private void ThrowIfRunning()
/// </summary>
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)
Expand All @@ -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();
}
}
Expand Down
9 changes: 7 additions & 2 deletions src/Polhem.Chat/PromptContextRecord.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ internal static class PromptContextRecord
{
public const string LabelKey = "polhem.chat.contextLabel";

/// <summary>What the model reads in place of a context that a later prompt supersedes.</summary>
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)
{
Expand Down Expand Up @@ -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.
/// </summary>
public static ChatMessage ToRequest(ChatMessage message)
/// <param name="message">A message of the history.</param>
/// <param name="labelsOnly">Whether each context is sent as its label with <see cref="Superseded"/> in place of its text.</param>
public static ChatMessage ToRequest(ChatMessage message, bool labelsOnly = false)
{
if (!message.Contents.Any(IsContext))
{
Expand All @@ -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
{
Expand Down
2 changes: 2 additions & 0 deletions src/Polhem.Chat/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
#nullable enable
Polhem.Chat.ChatRunner.SupersedesEarlierContext.get -> System.Func<Polhem.Chat.PromptContext!, bool>?
Polhem.Chat.ChatRunner.SupersedesEarlierContext.set -> void
8 changes: 8 additions & 0 deletions src/Polhem.Chat/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
158 changes: 158 additions & 0 deletions tests/Polhem.Chat.UnitTests/EarlierContextTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
using System.Text.Json;
using Microsoft.Extensions.AI;
using static Polhem.Chat.UnitTests.ScriptedChatClient;

namespace Polhem.Chat.UnitTests;

/// <summary>
/// <see cref="ChatRunner.SupersedesEarlierContext"/>: which prompts send their context in full, which send it by its
/// label alone, and what the history keeps.
/// </summary>
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) => $"<context label=\"{label}\">\n{text}\n</context>\n\n";

private static string ByLabel(string label) => $"<context label=\"{label}\">\n{Note}\n</context>\n\n";

/// <summary>Sends each prompt with the context given for it, in order.</summary>
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<TextContent>(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<UserPromptEntry>().Select(entry => entry.Context.Single().Text));

var json = JsonSerializer.Serialize(runner.Conversation.SaveHistory(), AIJsonUtilities.DefaultOptions);
var loaded = new ChatConversation();
loaded.LoadHistory(JsonSerializer.Deserialize<List<ChatMessage>>(json, AIJsonUtilities.DefaultOptions)!);

Assert.Equal(
["Draft one.", "Draft two."],
loaded.Entries.OfType<UserPromptEntry>().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));
}
}