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 { 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()); 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()); Check(trace.Contains("必须先装零件后关盒") && trace.Contains("最新完整草稿") && trace.Contains("保护系统规则"), "压缩须保留工艺、系统规则和最新草稿"); using var handler = new SummaryHttp(); using var http = new HttpClient(handler); var prompts = new List(); 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, "压缩不能改写本地原始聊天记录"); using (var verificationHandler = new SummaryHttp()) using (var verificationHttp = new HttpClient(verificationHandler)) { await new SopVideoAgentClient(verificationHttp).ChatAsync(new("回测", "保留工艺", video with { Frames = [] }, ["work"], UserMessage: "最新要求:保留四步", Conversation: history.Take(10).ToArray(), VerifyDraft: (_, _, _) => throw new Exception("讨论回复不应执行回测")), new("https://context.invalid/v1", "model", "", ContextLength: 131702, MaxTokens: 2048), default); Check(verificationHandler.SummaryRequests > 0, "回测长历史应主动摘要,不必等到上下文接近满载"); } 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 prompts) : IProgress { 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 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()); 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") }; } } }