aisop/tests/SopVideoAgent.Smoke/VerificationLoopChecks.cs
tfarcraw c4a831a55c Agent生成步骤后自动回放标准视频并依据真实结果修订草稿
默认执行生成、回测、失败图像反馈与最多三轮修订;支持独立触发与送检区域、防抖参数和有画面证据的区域校正提案。保护AI阈值和步骤顺序;应用与回测共用配置映射,手改草稿或标定后需重新验证,不自动保存配方。

验证通过:SopVideoAgent.Smoke、VideoFlowTest.Smoke、VisionDecision.Smoke、Avalonia.Smoke --vision-only;新的草稿验证器对本地装盒标准视频真实回放通过4/4。
完整生成端到端实测在Agent接口第5轮返回HTTP 503,未宣称通过。全量Avalonia.Smoke既有time_elapsed过程图用例失败,专项回归通过。
2026-11-18 10:04:11 +08:00

120 lines
8.5 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.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 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"));
});
var result = await new SopVideoAgentClient(http).AnalyzeAsync(request, connection, default);
Check(attempts == (mode is "repair" or "shrink" ? 2 : mode == "never" ? 3 : 1), "回测修订最多三轮;基础设施故障不能让模型瞎改工艺");
Check(result.Verification?.Passed == (mode is "repair" or "shrink"), "未通过的回测不能被模型自行宣称通过");
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") >= 3,
"修订请求必须包含实际送检图,不能只有文字分数");
}
}
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") };
}
}
}