精简回测修订上下文并复用关键帧与失败证据

This commit is contained in:
tfarcraw 2026-11-18 23:37:18 +08:00
parent b96600ef7d
commit 04f4d88734
6 changed files with 254 additions and 17 deletions

View File

@ -0,0 +1,80 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace SopHelper.Engine.SopAgent;
/// <summary>仅裁剪模型输入,不改变本地帧索引、草稿或完整回测日志。</summary>
internal static class SopVerificationContext
{
public static List<object> Images(SopVideoDraft draft, IReadOnlyList<SopVideoFrame> observed,
SopDraftVerification? report = null)
{
var parts = new List<object>();
var sent = new Dictionary<string, string>();
var failed = report?.Steps.Where(s => !s.Completed).Select(s => s.Id).ToHashSet();
var indices = draft.Steps.Select((step, index) => (step, index))
.Where(x => failed is null || failed.Contains(x.index + 1) || failed.Contains(x.index) || failed.Contains(x.index + 2))
.Select(x => x.step.EvidenceFrame)
.Concat(draft.RegionAdjustments.Select(r => r.EvidenceFrame)).ToHashSet();
foreach (var frame in observed.Where(f => indices.Contains(f.Index)))
Add($"frame_index={frame.Index}, time={frame.Seconds.ToString("F3", CultureInfo.InvariantCulture)}s", frame.Jpeg);
// 最新失败图放在末尾,预算压缩时优先释放较早的参考图。
// 每个失败步骤、每种裁剪范围保留首尾,避免重试图挤掉其他失败步骤。
if (report is not null)
foreach (var group in report.Images.Where(i => failed!.Count > 0 ? failed.Contains(i.StepId) : i.Accepted != true)
.GroupBy(i => (i.StepId, i.Scope)))
foreach (var image in new[] { group.First(), group.Last() }.Distinct())
Add($"真实回测送检图:步骤 {image.StepId},视频原始帧 {image.FrameId},时间 {image.Seconds.ToString("F3", CultureInfo.InvariantCulture)}s,范围 {image.Scope};AI结果:{image.Reason}。不是 evidence_frame 索引。", image.Jpeg);
return parts;
void Add(string label, byte[] jpeg)
{
var hash = Convert.ToHexString(SHA256.HashData(jpeg));
if (sent.TryGetValue(hash, out var original))
{
parts.Add(new { type = "text", text = label + "(图片字节与上述图片相同,复用图片:" + original + ")" });
return;
}
sent.Add(hash, label);
parts.Add(new { type = "text", text = label });
parts.Add(new { type = "image_url", image_url = new { url = "data:image/jpeg;base64," + Convert.ToBase64String(jpeg) } });
}
}
public static int Deduplicate(List<object> messages)
{
var seen = new Dictionary<string, int>();
var removed = 0;
for (var index = 0; index < messages.Count; index++)
{
var node = JsonSerializer.SerializeToNode(messages[index])!.AsObject();
if (node["content"] is not JsonArray parts) continue;
var changed = false;
for (var part = 0; part < parts.Count; part++)
{
if (parts[part]?["type"]?.ToString() != "image_url") continue;
var url = parts[part]!["image_url"]!["url"]!.ToString();
if (seen.TryGetValue(url, out var ordinal))
{
parts[part] = new JsonObject { ["type"] = "text", ["text"] = $"[重复图片已省略,图像内容复用上文第 {ordinal} 张图片;帧号、时间及用途仍以上方标注为准。]" };
removed++;
changed = true;
}
else seen.Add(url, seen.Count + 1);
}
if (changed) messages[index] = JsonSerializer.SerializeToElement(node);
}
return removed;
}
public static object Catalog(IReadOnlyList<SopVideoFrame> observed) => new
{
role = "user", content = JsonSerializer.Serialize(new
{
evidence_catalog = observed.Select(f => new { frame_index = f.Index, seconds = f.Seconds }),
note = "仅附相关关键帧和最新失败送检图;目录不代表图片已发送。可保留未修改步骤的已有证据编号;修改判据或区域须有当前可见证据,缺少时按秒数补看。remaining_frames 是新增帧预算,已有帧可按目录时间再次请求并复用原编号。"
})
};
}

View File

@ -33,6 +33,8 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
var validationRetries = 0;
var verificationAttempts = 0;
var pendingCompression = "";
List<object>? verificationBase = null;
var previousFailures = new List<object>();
string[]? verificationStepNames = null;
var verificationInstructions = request.VerifyDraft is null
? "本次只生成或编辑草稿,不进行标准视频回测;完成后直接返回,不等待回测反馈,也不能声称已通过回测。"
@ -86,7 +88,12 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
if (observed.Count > 0)
{
var parts = new List<object>();
foreach (var frame in observed) AddImage(parts, frame);
if (request.VerifyDraft is not null && request.CurrentDraft is not null)
{
parts.AddRange(SopVerificationContext.Images(request.CurrentDraft, observed));
messages.Add(SopVerificationContext.Catalog(observed));
}
else foreach (var frame in observed) AddImage(parts, frame);
messages.Add(new { role = "user", content = parts });
}
messages.Add(new { role = "user", content = "聊天模式。" + request.UserMessage });
@ -103,9 +110,12 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
{
token.ThrowIfCancellationRequested();
var inputLimit = connection.ContextLength - connection.MaxTokens - 1024L;
if (request.VerifyDraft is not null && SopVerificationContext.Deduplicate(messages) is > 0 and var duplicates)
pendingCompression += $"回测上下文去除 {duplicates} 张重复图片,保留帧号、时间及用途标注。\n";
var compression = pendingCompression + SopAgentContext.Compact(messages, inputLimit);
pendingCompression = "";
if (historyCount > 4 && SopAgentContext.Estimate(messages) > inputLimit * .8)
if (historyCount > 4 && (SopAgentContext.Estimate(messages) > inputLimit * .8
|| request.VerifyDraft is not null && historyCount > 8))
{
var older = messages.Skip(2).Take(historyCount - 4).ToArray();
var summary = await SummarizeHistoryAsync(older, request, connection, token).ConfigureAwait(false);
@ -115,6 +125,14 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
compression += "\n历史对话已自动摘要,保留最近四条原文、当前完整草稿和最新用户消息。";
}
estimatedInput = SopAgentContext.Estimate(messages);
if (request.VerifyDraft is not null && verificationBase is null)
{
// 保存已压缩的用户约束;排除当前草稿、图片和后续工具往返。
verificationBase = chatting
? messages.Take(messages.FindLastIndex(m => JsonSerializer.SerializeToElement(m).GetProperty("content").ToString().StartsWith("当前可编辑草稿:", StringComparison.Ordinal))).ToList()
: messages.Take(2).ToList();
if (chatting) verificationBase.Add(new { role = "user", content = "聊天模式。" + request.UserMessage });
}
if (!string.IsNullOrEmpty(compression))
{
request.Progress?.Report(compression);
@ -215,19 +233,20 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
{
verification_feedback = report.Summary, report.Steps,
decisions = report.Images.Select(i => new { i.StepId, i.FrameId, i.Seconds, i.Scope, i.Confidence, i.Accepted, i.Reason }),
previous_failures = previousFailures.ToArray(),
required_action = "依据真实回放修订完整草稿;保留工艺、步骤顺序和完成要求,不得调低 AI 阈值。坐标或送检范围错误时可提出带证据的 region_adjustments。"
});
messages.Add(new { role = "assistant", content = assistant.GetProperty("content").Clone() });
previousFailures.Add(new { attempt = verificationAttempts, report.Summary,
failed_steps = draft.Steps.Where((_, index) => report.Steps.Any(s => s.Id == index + 1 && !s.Completed)).ToArray() });
messages.Clear();
messages.AddRange(verificationBase!);
historyCount = 0; // 后续仅保留本次请求已经压缩过的历史约束。
messages.Add(new { role = "user", content = "当前可编辑草稿:" + JsonSerializer.Serialize(draft) });
messages.Add(SopVerificationContext.Catalog(observed));
messages.Add(new { role = "user", content = feedback });
estimatedInput += assistant.GetRawText().Length * 2L + feedback.Length * 2L;
var images = new List<object>();
foreach (var evidence in report.Images.OrderBy(i => i.Accepted == true).Take(6))
{
images.Add(new { type = "text", text = $"真实回测送检图:步骤 {evidence.StepId},视频原始帧 {evidence.FrameId},时间 {evidence.Seconds:F3}s,范围 {evidence.Scope};AI结果:{evidence.Reason}。此图片不是可引用的 evidence_frame 索引,需要时用读取工具查看对应时间。" });
images.Add(new { type = "image_url", image_url = new { url = "data:image/jpeg;base64," + Convert.ToBase64String(evidence.Jpeg) } });
estimatedInput += 1700;
}
var images = SopVerificationContext.Images(draft, observed, report);
if (images.Count > 0) messages.Add(new { role = "user", content = images });
pendingCompression = "回测上下文已重建:保留当前完整草稿、用户约束、相关关键帧和最新失败证据;去除旧草稿、工具历史和重复图片。";
continue;
}
}
@ -291,15 +310,28 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
request.Trace?.Invoke(new("context_compression", turn + 1, readCompression));
}
estimatedInput = SopAgentContext.Estimate(messages);
if (times.Length == 0 || times.Length > request.MaxFramesPerRead || times.Length > FrameBudget())
if (times.Length == 0 || times.Length > request.MaxFramesPerRead
|| times.Any(t => !double.IsFinite(t) || t < 0 || t > request.Video.DurationSeconds))
throw new ArgumentException();
var cached = request.VerifyDraft is null ? new Dictionary<double, SopVideoFrame>()
: times.Distinct().Select(t => (Time: t, Frame: observed.FirstOrDefault(f => Math.Abs(f.Seconds - t) < .0001)))
.Where(x => x.Frame is not null).ToDictionary(x => x.Time, x => x.Frame!);
var missing = request.VerifyDraft is null ? times : times.Where(t => !cached.ContainsKey(t)).Distinct().ToArray();
if (missing.Length > 60 - observed.Count
|| times.Length > (connection.ContextLength - connection.MaxTokens - estimatedInput - 1024L) / 1700)
throw new ArgumentException();
request.Progress?.Report("Agent:查看 " + string.Join("、", times.Select(t => t.ToString("0.0", CultureInfo.InvariantCulture) + "s")));
var frames = await Task.Run(() => SopVideoSampler.ReadFrames(request.Video, times, observed.Count, token), token).ConfigureAwait(false);
if (jpegBytes + frames.Sum(frame => frame.Jpeg.LongLength) > 10 * 1024 * 1024)
var added = missing.Length == 0 ? Array.Empty<SopVideoFrame>()
: await Task.Run(() => SopVideoSampler.ReadFrames(request.Video, missing, observed.Count, token), token).ConfigureAwait(false);
if (jpegBytes + added.Sum(frame => frame.Jpeg.LongLength) > 10 * 1024 * 1024)
throw new InvalidDataException("Agent 读取的画面超过 10MB");
observed.AddRange(added);
jpegBytes += added.Sum(frame => frame.Jpeg.LongLength);
if (request.VerifyDraft is not null)
for (var i = 0; i < missing.Length; i++) cached[missing[i]] = added[i];
var frames = request.VerifyDraft is null ? added : times.Select(t => cached[t]).ToArray();
foreach (var frame in frames)
{
observed.Add(frame); jpegBytes += frame.Jpeg.Length;
AddImage(imageParts, frame);
}
request.Trace?.Invoke(new("video_frames", turn + 1,

View File

@ -39,6 +39,15 @@ internal static class ContextCompressionChecks
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);

View File

@ -81,6 +81,7 @@ try
Check(SopVideoSampler.Sample(path,3,default).Frames.Count==3,"最大抽帧数应支持3张");
var info=SopVideoSampler.ReadInfo(path,default);
await VerificationLoopChecks.RunAsync(info);
await VerificationContextChecks.RunAsync(info);
await ContextCompressionChecks.RunAsync(info);
await ResponseDiagnosticsChecks.RunAsync(info);
Check(info.Frames.Count==0&&info.Path==Path.GetFullPath(path),"Agent 应从视频路径和元数据开始,不预选图片");
@ -136,6 +137,16 @@ try
using(var red=Cv2.ImDecode(agentDraft.ObservedFrames[2].Jpeg,ImreadModes.Color))
Check(red.At<Vec3b>(0,0).Item2>220,"工具应读取 Agent 指定时间的真实视频画面");
}
using(var dedupHandler=new ToolAgentHttp{DirectRead=true})
using(var dedupHttp=new HttpClient(dedupHandler))
{
var result=await new SopVideoAgentClient(dedupHttp).AnalyzeAsync(request with {Video=info,
VerifyDraft=(_,_,_)=>Task.FromResult(new SopDraftVerification(true,"通过",[],[]))},connection with {ContextLength=32768},default);
using var finalRequest=JsonDocument.Parse(dedupHandler.Bodies[^1]);
var images=finalRequest.RootElement.GetProperty("messages").EnumerateArray().Where(m=>m.GetProperty("content").ValueKind==JsonValueKind.Array)
.SelectMany(m=>m.GetProperty("content").EnumerateArray()).Where(p=>p.GetProperty("type").GetString()=="image_url").ToArray();
Check(result.ObservedFrames.Count==4&&images.Length==2,"回测中跨工具批次的相同图片须去重,但本地帧记录和证据索引完整保留");
}
using(var agentHandler=new ToolAgentHttp{SkipTools=true})
using(var agentHttp=new HttpClient(agentHandler))
{

View File

@ -0,0 +1,95 @@
using System.Net;
using System.Text;
using System.Text.Json;
using SopHelper.Engine.SopAgent;
internal static class VerificationContextChecks
{
public static async Task RunAsync(SopVideoSample video)
{
var frames = SopVideoSampler.ReadFrames(video, [0, .4, .8, 1.2, 1.6, 2, 2.4, 2.8, 3.2, 3.9], 0, default)
.Select(f => f with { Jpeg = [.. f.Jpeg, (byte)f.Index] }).ToArray();
var draft = new SopVideoDraft { Steps = Enumerable.Range(0, 4).Select(i => new SopDraftStep
{
Name = "操作" + i, Description = "用户当前判据" + i, StartSeconds = i, EndSeconds = i + 1,
Region = "work", EvidenceFrame = new[] { 1, 3, 6, 9 }[i]
}).ToList(), RegionAdjustments = [new() { Key = "work", X2 = 64, Y2 = 48, EvidenceFrame = 4, Note = "已确认区域" }] };
using var handler = new ContextHttp(draft);
using var http = new HttpClient(handler);
var attempts = 0;
var result = await new SopVideoAgentClient(http).ChatAsync(new("通用流程", "保留工艺", video with { Frames = frames }, ["work"],
UserMessage: "只按失败证据修订", Conversation: [new("user", "禁止改变顺序"), new("assistant", "已确认")], CurrentDraft: draft,
VerifyDraft: (_, sample, _) =>
{
Check(sample.Frames.Count == 10 && sample.Frames.Select(f => f.Index).SequenceEqual(Enumerable.Range(0, 10)), "裁剪传输不能删除本地证据或重排索引");
attempts++;
var passed = attempts == 3;
var crop = new SopDraftVerificationImage(1, 10, .5, "work", .1, false, "遮挡", [.. frames[0].Jpeg, 101]);
return Task.FromResult(new SopDraftVerification(passed, "回测" + attempts,
Enumerable.Range(1, 4).Select(id => new SopDraftVerificationStep(id, "操作" + (id - 1), passed || id is 2 or 3, "结果" + attempts)).ToArray(),
[.. Enumerable.Repeat(crop, 8), new(4, 39, 3.9, "work", .2, false, "未达到判据", [.. frames[0].Jpeg, 104]),
new(2, 12, 1.2, "work", .99, true, "完成", [.. frames[0].Jpeg, 102]) ]));
}), new("https://context.invalid/v1", "test", "", ContextLength: 131702, MaxTokens: 2048), default);
Check(result.Draft?.Verification?.Passed == true && attempts == 3, "精简上下文后仍须按真实回测完成修订");
var first = Parts(handler.Bodies[0]);
Check(first.Count(p => p.GetProperty("type").GetString() == "image_url") == 5, "首次回测只传步骤和区域引用的五张关键帧,不传全部十帧");
for (var index = 1; index < handler.Bodies.Count; index++)
{
var parts = Parts(handler.Bodies[index]);
var images = parts.Where(p => p.GetProperty("type").GetString() == "image_url").Select(p => p.GetProperty("image_url").GetProperty("url").GetString()).ToArray();
Check(images.Length == 7 && images.Distinct().Count() == images.Length, "每轮仅五张关键帧和两个失败步骤的去重图片,不追加成功或旧回测图片");
var text = string.Join("\n", parts.Where(p => p.GetProperty("type").GetString() == "text").Select(p => p.GetProperty("text").GetString()));
Check(text.Contains("步骤 4") && text.Contains("步骤 1"), "大量重试不能挤掉后面失败步骤的证据");
using var body = JsonDocument.Parse(handler.Bodies[index]);
var texts = body.RootElement.GetProperty("messages").EnumerateArray().Where(m => m.GetProperty("content").ValueKind == JsonValueKind.String)
.Select(m => m.GetProperty("content").GetString()!).ToArray();
using var current = JsonDocument.Parse(texts.Single(t => t.StartsWith("当前可编辑草稿:"))[8..]);
Check(texts.Contains("禁止改变顺序") && current.RootElement.GetProperty("Steps")[0].GetProperty("Description").GetString() == "用户当前判据0",
"重建上下文必须保留用户要求和当前手改草稿");
}
using (var cachedHandler = new ContextHttp(draft) { ReadCached = true })
using (var cachedHttp = new HttpClient(cachedHandler))
{
var full = Enumerable.Range(0, 60).Select(i => frames[i % frames.Length] with { Index = i }).ToArray();
var cachedResult = await new SopVideoAgentClient(cachedHttp).ChatAsync(new("复用证据", "", video with { Frames = full }, ["work"],
UserMessage: "回测当前草稿", CurrentDraft: draft,
VerifyDraft: (_, sample, _) =>
{
Check(sample.Frames.Count == 60, "重新查看已有帧不得消耗新增帧预算");
return Task.FromResult(new SopDraftVerification(true, "通过", [], []));
}), new("https://context.invalid/v1", "test", "", ContextLength: 131702, MaxTokens: 2048), default);
Check(cachedHandler.Bodies.Count == 2 && cachedResult.ObservedFrames.Count == 60,
"本地帧预算用满后仍可查看被筛掉的帧,不能因精简上下文失去补看能力");
Check(Parts(cachedHandler.Bodies[1]).Count(p => p.GetProperty("type").GetString() == "image_url") == 6,
"同批两次请求已有帧只发送一次图片");
}
Console.WriteLine("PASS: 回测关键帧筛选、跨步骤失败证据覆盖、图片去重、三轮上下文重建与本地帧索引保护");
}
private static JsonElement[] Parts(string body)
{
using var document = JsonDocument.Parse(body);
return document.RootElement.GetProperty("messages").EnumerateArray().Where(m => m.GetProperty("content").ValueKind == JsonValueKind.Array)
.SelectMany(m => m.GetProperty("content").EnumerateArray()).Select(p => p.Clone()).ToArray();
}
private static void Check(bool condition, string message) { if (!condition) throw new Exception(message); }
private sealed class ContextHttp(SopVideoDraft draft) : HttpMessageHandler
{
public bool ReadCached;
public List<string> Bodies { get; } = [];
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
{
Bodies.Add(await request.Content!.ReadAsStringAsync(token));
if (ReadCached && Bodies.Count == 1)
return new(HttpStatusCode.OK) { Content = new StringContent(JsonSerializer.Serialize(new
{
choices = new[] { new { finish_reason = "tool_calls", message = new { role = "assistant", content = (string?)null,
tool_calls = new[] { new { id = "cached", type = "function", function = new { name = "read_video_frames", arguments = "{\"times_seconds\":[0,0]}" } } } } } }
}), Encoding.UTF8, "application/json") };
return new(HttpStatusCode.OK) { Content = new StringContent(JsonSerializer.Serialize(new
{
choices = new[] { new { finish_reason = "stop", message = new { content = JsonSerializer.Serialize(new { reply = "已修订", draft }) } } }
}), Encoding.UTF8, "application/json") };
}
}
}

View File

@ -43,8 +43,18 @@ internal static class VerificationLoopChecks
Check(messages.Any(m => m.GetProperty("content").ValueKind == JsonValueKind.String
&& m.GetProperty("content").GetString()!.Contains("verification_feedback")), "真实失败原因必须反馈到修订请求");
Check(messages.Where(m => m.GetProperty("content").ValueKind == JsonValueKind.Array)
.SelectMany(m => m.GetProperty("content").EnumerateArray()).Count(p => p.GetProperty("type").GetString() == "image_url") >= 3,
"修订请求必须包含实际送检图,不能只有文字分数");
.SelectMany(m => m.GetProperty("content").EnumerateArray()).Count(p => p.GetProperty("type").GetString() == "image_url") == 2,
"修订请求保留实际送检图和关键帧,相同字节只能发送一次");
Check(!messages.Any(m => m.GetProperty("role").GetString() == "tool"), "每轮修订必须去除旧工具往返,避免上下文持续累积");
Check(messages.Count(m => m.GetProperty("content").ValueKind == JsonValueKind.String
&& m.GetProperty("content").GetString()!.StartsWith("当前可编辑草稿:")) == 1, "每轮修订只携带一份当前完整草稿");
if (mode == "never")
{
using var next = JsonDocument.Parse(handler.Bodies[3]);
var nextMessages = next.RootElement.GetProperty("messages").EnumerateArray().ToArray();
Check(nextMessages.Length == messages.Length && nextMessages.Any(m => m.GetProperty("content").ToString().Contains("previous_failures")),
"第二次失败仍重建固定结构,并保留前轮失败配置以免反复尝试");
}
}
}
using (var handler = new LoopHttp())