aisop/tests/SopVideoAgent.Smoke/VerificationLoopChecks.cs
tfarcraw df044f6c59 自动保存Agent分析全过程日志并显示具体失败原因
每次分析创建独立JSONL日志,实时记录模型请求与原始响应、工具调用、视频时间点、上下文压缩、回测结果及异常;实际读取和送检截图独立落盘。聊天显示日志位置,鉴权密钥与内联图片数据脱敏。取消和失败保留完整已写日志,额外错误快照关联会话日志。

修复tool_calls为空时的响应兼容问题,检查空choices及服务返回错误,避免吞掉具体解析异常。

验证:SopVideoAgent.Smoke、VideoFlowTest.Smoke通过,涵盖日志实时写入、图片证据、脱敏、异常与取消。真实接口独立分析完成三轮回测,未复现通用异常,草稿实际停在第二步;报告见scratch/agent-failure-live。额外Avalonia.Smoke的旧侧栏数量断言在进入Agent检查前失败,本次未涉及侧栏。
2026-11-18 14:07:30 +08:00

124 lines
9.0 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 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);
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") >= 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") };
}
}
}