101 lines
7.8 KiB
C#
101 lines
7.8 KiB
C#
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, CompletionCriteria = "用户当前判据" + 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 == 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", null, null, "等待前序确认", [.. frames[0].Jpeg, 102]),
|
|
new(3, 24, 2.4, "work", .99, true, "已完成", [.. frames[0].Jpeg, 103]) ]));
|
|
}), 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"
|
|
&& current.RootElement.GetProperty("Steps")[0].GetProperty("completion_criteria").GetString() == "用户当前判据0",
|
|
"重建上下文必须保留用户要求和当前手改草稿");
|
|
using var feedback = JsonDocument.Parse(texts.Single(t => t.StartsWith("{") && t.Contains("verification_feedback")));
|
|
Check(feedback.RootElement.GetProperty("decisions").EnumerateArray().Any(d => d.GetProperty("StepId").GetInt32() == 3 && d.GetProperty("Seconds").GetDouble() == 2.4),
|
|
"不发送成功步骤图片时,仍须保留其实际触发时间,以便解释前后步骤阻塞");
|
|
}
|
|
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") };
|
|
}
|
|
}
|
|
}
|