136 lines
10 KiB
C#
136 lines
10 KiB
C#
using System.Net;
|
||
using System.Text;
|
||
using System.Text.Json;
|
||
using SopHelper.Engine.Sop;
|
||
using SopHelper.Engine.SopAgent;
|
||
|
||
internal static class VerificationLoopChecks
|
||
{
|
||
public static async Task RunAsync(SopVideoSample video)
|
||
{
|
||
var connection = new SopAgentConnection("https://verify.invalid/v1", "test", "", ContextLength: 131702, MaxTokens: 2048);
|
||
foreach (var mode in new[] { "repair", "never", "infrastructure", "shrink" })
|
||
{
|
||
using var handler = new LoopHttp { TryShrink = mode == "shrink" }; using var http = new HttpClient(handler);
|
||
var attempts = 0;
|
||
var traces = new List<SopAgentTrace>();
|
||
var request = new SopVideoAnalysisRequest("测试", "保持放入零件工艺", video with { Frames = [] }, ["work"],
|
||
RegionDefinitions: new Dictionary<string, RegionDef> { ["work"] = new() { X2 = 64, Y2 = 48 } },
|
||
VerifyDraft: (draft, observed, token) =>
|
||
{
|
||
attempts++;
|
||
Check(observed.Frames.Count == 2, "回测必须使用模型实际读取的标准视频上下文");
|
||
var passed = mode is "repair" or "shrink" && attempts == 2;
|
||
if (passed) Check(draft.Steps[0].Description == "敞开盒子内可见零件" && draft.Steps[0].StableFrames == 8, "修订应真实改变判据和防抖参数");
|
||
return Task.FromResult(new SopDraftVerification(passed, passed ? "回测通过" : "步骤1取图过早,未见结果",
|
||
[new(1, draft.Steps[0].Name, passed, passed ? "AI确认" : "未确认")],
|
||
[new(1, 10, 1, "work", passed ? .97 : .12, passed, passed ? "完成" : "手部遮挡", observed.Frames[0].Jpeg)],
|
||
"verified-locally", mode == "infrastructure"));
|
||
}, Trace: traces.Add);
|
||
var result = await new SopVideoAgentClient(http).AnalyzeAsync(request, connection, default);
|
||
using(var verificationRequest=JsonDocument.Parse(handler.Bodies[0]))
|
||
Check(verificationRequest.RootElement.GetProperty("messages")[0].GetProperty("content").GetString()!.Contains("本次为显式回测修订"),"只有显式回测请求才能启用回测修订提示词");
|
||
Check(attempts == (mode is "repair" or "shrink" ? 2 : mode == "never" ? 3 : 1), "回测修订最多三轮;基础设施故障不能让模型瞎改工艺");
|
||
Check(result.Verification?.Passed == (mode is "repair" or "shrink"), "未通过的回测不能被模型自行宣称通过");
|
||
foreach (var kind in new[] { "model_request", "model_response", "tool_call", "tool_result", "video_frames", "verification_result", "final_result" })
|
||
Check(traces.Any(t => t.Kind == kind), "分析过程日志必须覆盖:" + kind);
|
||
Check(traces.Single(t => t.Kind == "video_frames").Images?.Count == 2, "日志保留模型实际读取的图片证据");
|
||
if (mode == "shrink") Check(handler.Bodies.Count == 4 && result.Steps.Count == 2, "自动修订删除失败步骤时必须拒绝并反馈,不能通过删步凑通过");
|
||
if (attempts > 1)
|
||
{
|
||
using var feedback = JsonDocument.Parse(handler.Bodies[2]);
|
||
var messages = feedback.RootElement.GetProperty("messages").EnumerateArray().ToArray();
|
||
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") == 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())
|
||
using (var http = new HttpClient(handler))
|
||
using (var cancellation = new CancellationTokenSource(100))
|
||
{
|
||
var cancelled = false;
|
||
try
|
||
{
|
||
await new SopVideoAgentClient(http).AnalyzeAsync(new("测试", "", video with { Frames = [] }, ["work"],
|
||
VerifyDraft: async (_, _, token) => { await Task.Delay(Timeout.Infinite, token); throw new Exception(); }), connection, cancellation.Token);
|
||
}
|
||
catch (OperationCanceledException) { cancelled = true; }
|
||
Check(cancelled, "取消必须能中断回测阶段,不能继续自动修订");
|
||
}
|
||
CheckMapping(video);
|
||
Console.WriteLine("PASS: 标准视频生成-回测-修订闭环、真实图片反馈、三轮上限、故障/取消、区域提案、独立送检与阈值保护");
|
||
}
|
||
|
||
private static void CheckMapping(SopVideoSample video)
|
||
{
|
||
var observed = SopVideoSampler.ReadFrames(video, [1, 3], 0, default);
|
||
var sample = video with { Frames = observed };
|
||
var draft = new SopVideoDraft
|
||
{
|
||
RegionAdjustments = [new() { Key = "trigger", Name = "触发区", X1 = 4, Y1 = 4, X2 = 24, Y2 = 24, EvidenceFrame = 0, Note = "依据画面校正" }],
|
||
Steps = [new() { Name = "放入零件", Description = "盒内可见零件", StartSeconds = 0, EndSeconds = 4,
|
||
Region = "trigger", EvidenceFrame = 0, StableFrames = 8, Tolerance = 5, ImageMode = VisionImageMode.FixedRegion, ImageRegion = "work" }]
|
||
};
|
||
var template = new SopConfig(); template.Sop.Name = "受保护配方";
|
||
template.Sop.Regions["work"] = new() { X2 = 64, Y2 = 48 };
|
||
template.Sop.Steps = [new() { Id = 1, AiConfirmation = new() { MinConfidence = .93, RetryDelayMs = 4000 } }];
|
||
var before = SopConfigLoader.ToYaml(template);
|
||
SopVideoDraftClient.Validate(draft, sample, ["work"], template.Sop.Regions);
|
||
var built = SopDraftConfigBuilder.Build(template, draft);
|
||
Check(built.Sop.Steps[0].Detection is { Region: "trigger", StableFrames: 8, Tolerance: 5 }
|
||
&& built.Sop.Steps[0].AiConfirmation is { ImageRegion: "work", MinConfidence: .93, RetryDelayMs: 4000 },
|
||
"回测和应用必须共享独立触发区/送检区及防抖映射,AI阈值不能调低");
|
||
Check(before == SopConfigLoader.ToYaml(template) && !template.Sop.Regions.ContainsKey("trigger"), "生成回测不能提前改动原区域和配方");
|
||
var fingerprint = SopDraftConfigBuilder.Fingerprint(built, sample);
|
||
draft.Steps[0].Description = "另一个完成要求";
|
||
Check(fingerprint != SopDraftConfigBuilder.Fingerprint(SopDraftConfigBuilder.Build(template, draft), sample), "手改判据后必须使回测签名失效");
|
||
draft.RegionAdjustments.Add(new() { Key = "WORK", X1 = 1, Y1 = 1, X2 = 60, Y2 = 45, EvidenceFrame = 1, Note = "回放证据支持校正" });
|
||
SopVideoDraftClient.Validate(draft, sample, ["work"], template.Sop.Regions);
|
||
var corrected = SopDraftConfigBuilder.Build(template, draft);
|
||
Check(draft.RegionAdjustments.Last().Key == "work" && corrected.Sop.Regions.Count == 2 && corrected.Sop.Regions["work"].X1 == 1,
|
||
"区域校正须规范化已有键名大小写,不能新增同名键而让检测继续引用旧坐标");
|
||
draft.RegionAdjustments[0].X2 = video.Width + 1;
|
||
var rejected = false;
|
||
try { SopVideoDraftClient.Validate(draft, sample, ["work"], template.Sop.Regions); } catch (FormatException) { rejected = true; }
|
||
Check(rejected, "区域提案不能越界或伪造视频坐标");
|
||
}
|
||
|
||
private static void Check(bool value, string message) { if (!value) throw new Exception(message); }
|
||
private sealed class LoopHttp : HttpMessageHandler
|
||
{
|
||
public bool TryShrink;
|
||
public List<string> Bodies { get; } = [];
|
||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
|
||
{
|
||
Bodies.Add(await request.Content!.ReadAsStringAsync(token));
|
||
object reply;
|
||
if (Bodies.Count == 1)
|
||
reply = new { choices = new[] { new { finish_reason = "tool_calls", message = new { role = "assistant", content = (string?)null,
|
||
tool_calls = new[] { new { id = "read", type = "function", function = new { name = "read_video_frames", arguments = "{\"times_seconds\":[1,3]}" } } } } } } };
|
||
else
|
||
{
|
||
var revised = Bodies.Count > 2;
|
||
var draft = new SopVideoDraft { Summary = "工艺不变", Steps = [
|
||
new() { Name = "放入零件", Description = revised ? "敞开盒子内可见零件" : "先拿起再放入", StartSeconds = 0, EndSeconds = 2, Region = "work", EvidenceFrame = 0, StableFrames = revised ? 8 : 3 },
|
||
new() { Name = "取走零件", Description = "盒内为空", StartSeconds = 2, EndSeconds = 4, Region = "work", EvidenceFrame = 1 }] };
|
||
if (TryShrink && Bodies.Count == 3) draft.Steps.RemoveAt(1);
|
||
reply = new { choices = new[] { new { finish_reason = "stop", message = new { content = JsonSerializer.Serialize(draft) } } } };
|
||
}
|
||
return new(HttpStatusCode.OK) { Content = new StringContent(JsonSerializer.Serialize(reply), Encoding.UTF8, "application/json") };
|
||
}
|
||
}
|
||
}
|