aisop/tests/SopVideoAgent.Smoke/ContextCompressionChecks.cs
tfarcraw 65c011490f 显示Agent实际提示词并自动压缩视频与聊天上下文
聊天按轮次展示系统规则、输入、工具结果和真实回测反馈,隐藏图片Base64及鉴权信息。接近预算时释放历史图片并替换已过期草稿,长对话分批摘要并保留最近原文、当前草稿及最新要求,取消最近40条的静默截断。摘要失败、截断和取消时停止请求并保留原记录。

验证:SopVideoAgent.Smoke通过,覆盖上下文压缩、摘要成功/失败/取消、日志脱敏及原有生成回测闭环;VideoFlowTest.Smoke通过,覆盖提示词折叠显示和生成后日志保留。使用隔离构建目录,未重启用户程序。
2026-11-18 13:17:50 +08:00

81 lines
6.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Net;
using System.Text;
using System.Text.Json;
using SopHelper.Engine.SopAgent;
internal static class ContextCompressionChecks
{
public static async Task RunAsync(SopVideoSample video)
{
var messages = new List<object>
{
new { role = "system", content = "保护系统规则" },
new { role = "user", content = "必须先装零件后关盒" },
new { role = "assistant", content = "{\"steps\":[{\"name\":\"旧草稿\"}]}" },
new { role = "assistant", content = "", tool_calls = new[] { new { id = "a", type = "function", function = new { name = "get_video_info", arguments = "{}" } } } },
new { role = "tool", tool_call_id = "a", content = "真实视频元数据" },
new { role = "user", content = new object[] { new { type = "text", text = "frame_index=0, time=1s" }, new { type = "image_url", image_url = new { url = "data:image/jpeg;base64,SECRETJPEG" } } } },
new { role = "assistant", content = "{\"steps\":[{\"name\":\"最新完整草稿\"}]}" },
new { role = "user", content = "verification_feedback: 第一步失败,置信度0.12" }
};
var before = SopAgentContext.Estimate(messages);
var trace = SopAgentContext.Describe(messages, Array.Empty<object>());
Check(!trace.Contains("SECRETJPEG") && trace.Contains("frame_index=0"), "提示词日志须隐藏图片字节并保留时间标识");
var result = SopAgentContext.Compact(messages, 3000);
var text = JsonSerializer.Serialize(messages);
Check(result.Contains("1 张") && SopAgentContext.Estimate(messages) < before, "超预算必须自动释放图片并重新估算");
Check(text.Contains("tool_call_id") && text.Contains("verification_feedback") && !text.Contains("SECRETJPEG"), "压缩不能破坏工具配对或删除失败证据文字");
trace = SopAgentContext.Describe(messages, Array.Empty<object>());
Check(trace.Contains("必须先装零件后关盒") && trace.Contains("最新完整草稿") && trace.Contains("保护系统规则"), "压缩须保留工艺、系统规则和最新草稿");
using var handler = new SummaryHttp(); using var http = new HttpClient(handler);
var prompts = new List<SopAgentPrompt>();
var history = Enumerable.Range(0, 48).Select(i => new SopAgentChatTurn(i % 2 == 0 ? "user" : "assistant", $"历史{i}:" + new string('甲', 700))).ToArray();
var chat = await new SopVideoAgentClient(http).ChatAsync(new("测试", "不能降低阈值", video with { Frames = [] }, ["work"],
UserMessage: "最新要求:保留四步", Conversation: history, PromptSent: new ImmediateProgress(prompts)),
new("https://context.invalid/v1", "model", "secret-key", ContextLength: 24000, MaxTokens: 2048), default);
Check(chat.Reply == "继续讨论" && handler.SummaryRequests > 0, "长聊天应先自动摘要再继续请求");
var main = handler.MainBody!;
Check(main.Contains("最新要求") && main.Contains("历史47") && main.Contains("摘要保留工艺"), "最新消息、最近原文与摘要必须进入正式请求");
Check(prompts.Any(p => p.Round == 0) && prompts.Any(p => p.Round == 1) && prompts.All(p => !p.Text.Contains("secret-key")), "摘要和正式提示词均须可见且不含鉴权密钥");
Check(history[0].Text.Length > 700, "压缩不能改写本地原始聊天记录");
foreach (var failure in new[] { "http", "truncated", "cancel" })
{
using var failingHandler = new SummaryHttp { Failure = failure }; using var failingHttp = new HttpClient(failingHandler);
using var cancellation = new CancellationTokenSource();
if (failure == "cancel") cancellation.CancelAfter(100);
var rejected = false;
try
{
await new SopVideoAgentClient(failingHttp).ChatAsync(new("测试", "", video with { Frames = [] }, ["work"],
UserMessage: "继续", Conversation: history), new("https://context.invalid/v1", "model", "", ContextLength: 24000, MaxTokens: 2048), cancellation.Token);
}
catch (Exception error) when (error is InvalidDataException or OperationCanceledException) { rejected = true; }
Check(rejected && failingHandler.MainBody is null, "摘要失败、截断或取消时不可用不完整上下文继续推理");
}
Console.WriteLine("PASS: 图片/旧草稿压缩、聊天分批摘要、最新上下文保护、工具配对和提示词日志脱敏");
}
private static void Check(bool value, string reason) { if (!value) throw new Exception(reason); }
private sealed class ImmediateProgress(List<SopAgentPrompt> prompts) : IProgress<SopAgentPrompt>
{ public void Report(SopAgentPrompt value) => prompts.Add(value); }
private sealed class SummaryHttp : HttpMessageHandler
{
public int SummaryRequests;
public string Failure = "";
public string? MainBody;
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var body = await request.Content!.ReadAsStringAsync(cancellationToken);
using var doc = JsonDocument.Parse(body);
var summary = !doc.RootElement.TryGetProperty("tools", out _);
if (summary && Failure == "cancel") await Task.Delay(Timeout.Infinite, cancellationToken);
if (summary && Failure == "http") return new(HttpStatusCode.ServiceUnavailable);
if (summary) SummaryRequests++; else MainBody = SopAgentContext.Describe(
doc.RootElement.GetProperty("messages").EnumerateArray().Select(m => (object)m.Clone()).ToArray(), Array.Empty<object>());
return new(HttpStatusCode.OK) { Content = new StringContent(JsonSerializer.Serialize(new
{ choices = new[] { new { finish_reason = Failure == "truncated" ? "length" : "stop", message = new { role = "assistant", content = summary ? "摘要保留工艺与全部用户约束" : "{\"reply\":\"继续讨论\",\"draft\":null}" } } } }), Encoding.UTF8, "application/json") };
}
}
}