增加候选参考探测与前序负例对照并保护修订验收

This commit is contained in:
tfarcraw 2026-11-19 00:38:34 +08:00
parent 5a1395720b
commit 01a79e52e5
16 changed files with 292 additions and 82 deletions

View File

@ -18,39 +18,45 @@ public sealed class SopDraftReferenceVerifier(IVisionDecisionClient? vision = nu
{
var step = config.Sop.Steps[id - 1]; var source = draft.Steps[id - 1];
var options = step.AiConfirmation ?? new(); var mode = VisionImageMode.Resolve(options);
var seconds = video.Frames[source.EvidenceFrame].Seconds;
var scope = mode == VisionImageMode.FixedRegion ? options.ImageRegion : mode;
if (mode == VisionImageMode.Hand)
foreach (var kind in new[] { "completion", "previous_state" })
{
checks.Add(new(id, source.EvidenceFrame, seconds, scope, null, null, "跟随手部的范围依赖运行时跟踪,未用静态替代范围猜测参考结果", []));
continue;
}
byte[] jpeg = [];
try
{
var decoded = await Task.Run(() =>
token.ThrowIfCancellationRequested();
var evidence = kind == "completion" ? source.EvidenceFrame : id > 1 ? draft.Steps[id - 2].EvidenceFrame
: video.Frames.FirstOrDefault(f => f.Seconds == 0)?.Index ?? -1;
var seconds = evidence < 0 ? 0 : video.Frames[evidence].Seconds;
if (mode == VisionImageMode.Hand)
{
token.ThrowIfCancellationRequested();
using var capture = new VideoCapture(video.Path);
if (!capture.IsOpened() || capture.Fps <= 0) throw new IOException("无法读取参考视频");
var index = Math.Clamp((long)Math.Round(seconds * capture.Fps), 0, capture.FrameCount - 1);
if (!capture.Set(VideoCaptureProperties.PosFrames, index)) throw new IOException("无法定位参考画面");
using var image = new Mat();
if (!capture.Read(image) || image.Empty()) throw new IOException("无法解码参考画面");
var region = mode == VisionImageMode.FixedRegion ? config.Sop.Regions.GetValueOrDefault(options.ImageRegion)
?? throw new IOException("参考送检区域不存在") : null;
return (Jpeg: VisionDecisionImage.Encode(image, region), FrameId: index);
}, token).ConfigureAwait(false);
jpeg = decoded.Jpeg;
using var budget = CancellationTokenSource.CreateLinkedTokenSource(token);
budget.CancelAfter(TimeSpan.FromSeconds(options.TimeoutSeconds));
var decision = await client.DecideAsync(new(config.Sop.Name, id, step.Name, step.Description, step.Description,
decoded.FrameId, DateTime.Now, jpeg), budget.Token).ConfigureAwait(false);
var accepted = decision.Completed && double.IsFinite(decision.Confidence) && decision.Confidence >= options.MinConfidence && decision.Confidence <= 1;
checks.Add(new(id, source.EvidenceFrame, seconds, scope, accepted, decision.Confidence, decision.Reason, jpeg));
checks.Add(new(id, evidence, seconds, scope, null, null, "跟随手部的范围依赖运行时跟踪,未用静态替代范围猜测参考结果", [], kind));
continue;
}
byte[] jpeg = [];
try
{
var decoded = await Task.Run(() =>
{
token.ThrowIfCancellationRequested();
using var capture = new VideoCapture(video.Path);
if (!capture.IsOpened() || capture.Fps <= 0) throw new IOException("无法读取参考视频");
var index = Math.Clamp((long)Math.Round(seconds * capture.Fps), 0, capture.FrameCount - 1);
if (!capture.Set(VideoCaptureProperties.PosFrames, index)) throw new IOException("无法定位参考画面");
using var image = new Mat();
if (!capture.Read(image) || image.Empty()) throw new IOException("无法解码参考画面");
var region = mode == VisionImageMode.FixedRegion ? config.Sop.Regions.GetValueOrDefault(options.ImageRegion)
?? throw new IOException("参考送检区域不存在") : null;
return (Jpeg: VisionDecisionImage.Encode(image, region), FrameId: index);
}, token).ConfigureAwait(false);
jpeg = decoded.Jpeg;
using var budget = CancellationTokenSource.CreateLinkedTokenSource(token);
budget.CancelAfter(TimeSpan.FromSeconds(options.TimeoutSeconds));
var decision = await client.DecideAsync(new(config.Sop.Name, id, step.Name, step.Description, step.Description,
decoded.FrameId, DateTime.Now, jpeg), budget.Token).ConfigureAwait(false);
var accepted = decision.Completed && double.IsFinite(decision.Confidence) && decision.Confidence >= options.MinConfidence && decision.Confidence <= 1;
checks.Add(new(id, evidence, seconds, scope, accepted, decision.Confidence, decision.Reason, jpeg, kind));
}
catch (Exception error) when (error is not OperationCanceledException || !token.IsCancellationRequested)
{ checks.Add(new(id, evidence, seconds, scope, null, null, "参考判据检查不可用:" + error.Message, jpeg, kind)); }
}
catch (Exception error) when (error is not OperationCanceledException || !token.IsCancellationRequested)
{ checks.Add(new(id, source.EvidenceFrame, seconds, scope, null, null, "参考判据检查不可用:" + error.Message, jpeg)); }
}
return checks;
}

View File

@ -75,11 +75,18 @@ public sealed class SopDraftVideoVerifier : ISopDraftVideoVerifier
await test.FinishPendingDecisionAsync(budget.Token);
EnsureSource();
var blocked = test.StepResults.FirstOrDefault(s => !s.Completed);
var references = !infrastructureFailure && blocked is not null
? await new SopDraftReferenceVerifier().CheckAsync(config, draft, video, blocked.Id, budget.Token) : null;
var references = new List<SopDraftReferenceCheck>();
if (!infrastructureFailure)
foreach (var id in test.IsCompleted ? Enumerable.Range(0, (draft.Steps.Count + 1) / 2).Select(i => i * 2 + 1)
: blocked is null ? [] : new[] { blocked.Id })
references.AddRange(await new SopDraftReferenceVerifier().CheckAsync(config, draft, video, id, budget.Token));
EnsureSource();
return new(test.IsCompleted, test.Finish("标准视频草稿回测结束"), test.StepResults,
images.Values.OrderBy(i => i.StepId).ToArray(), fingerprint, infrastructureFailure, diagnostics.Build(), references);
var contradictory = references.Any(c => c.Contradicts);
var summary = test.IsCompleted && contradictory
? $"标准视频运行已完成 {draft.Steps.Count} 步,但完成/前序参考对照未通过,草稿未通过验收"
: test.Finish("标准视频草稿回测结束");
return new(test.IsCompleted && !contradictory, summary, test.StepResults,
images.Values.OrderBy(i => i.StepId).ToArray(), fingerprint, infrastructureFailure, diagnostics.Build(), references, test.IsCompleted);
}
catch (OperationCanceledException) when (!token.IsCancellationRequested)
{

View File

@ -9,6 +9,7 @@ using SopHelper.Engine.Sop;
using SopHelper.Engine.SopAgent;
using SopHelper.Presentation;
using SopHelper.Presentation.Imaging;
using SopHelper.Training;
namespace SopHelper.VVMs.RecipeEditor;
@ -276,7 +277,9 @@ public partial class RecipeEditorViewModel
var result = await AgentClient.ChatAsync(new(recipeName, instructions, sample, regions, maxFrames, progress,
userMessage, _agentConversation.ToArray(), CreateAgentDraftSnapshot(), regionDefinitions,
CreateAgentImageScopes(), VerifyDraft: verify, PromptSent: promptLog, Trace: runLog.Write,
VerifyCurrentDraftFirst: verifyDraft), connection, token).WaitAsync(token);
VerifyCurrentDraftFirst: verifyDraft,
CheckReference: verifyDraft ? (candidate, video, id, cancellation) => new SopDraftReferenceVerifier().CheckAsync(
SopDraftConfigBuilder.Build(verificationTemplate!, candidate), candidate, video, id, cancellation) : null), connection, token).WaitAsync(token);
token.ThrowIfCancellationRequested();
draft = result.Draft; reply = result.Reply;
sample = sample with { Frames = result.ObservedFrames };

View File

@ -1,16 +1,55 @@
using System.Text.RegularExpressions;
using System.Text.Json;
namespace SopHelper.Engine.SopAgent;
internal static class SopAgentJson
{
// 部分服务会在最终 JSON 代码块前输出说明。仅接受唯一且位于末尾的完整代码块,不猜测多个候选或残缺 JSON。
// 部分服务会在最终 JSON 前输出说明。仅接受唯一明确且位于末尾的完整对象,不猜测多个候选或修补残缺 JSON。
public static string Payload(string text)
{
text = text.Trim();
if (text.StartsWith('{') || text.StartsWith('[')) return text;
var blocks = Regex.Matches(text, @"(?ms)^```(?:json)?[^\S\r\n]*\r?\n(?<json>.*?)\r?\n```[^\S\r\n]*(?:\r?\n|$)");
return blocks.Count == 1 && string.IsNullOrWhiteSpace(text[(blocks[0].Index + blocks[0].Length)..])
? blocks[0].Groups["json"].Value.Trim() : text;
if (blocks.Count == 1 && string.IsNullOrWhiteSpace(text[(blocks[0].Index + blocks[0].Length)..]))
return blocks[0].Groups["json"].Value.Trim();
if (text.Contains("```", StringComparison.Ordinal)) return text;
// 兼容说明后另起一行的唯一完整根对象;不截取嵌套片段、不选择多个候选、不修补残缺 JSON。
var candidates = new List<(int Start, int End)>();
var consumed = 0;
foreach (Match match in Regex.Matches(text, @"(?m)^[\t ]*\{"))
{
var start = match.Index + match.Length - 1;
if (start < consumed) continue;
var end = EndOfObject(text, start);
if (end < 0) continue;
try
{
using var document = JsonDocument.Parse(text[start..end]);
candidates.Add((start, end)); consumed = end;
}
catch (JsonException) { }
}
return candidates.Count == 1 && string.IsNullOrWhiteSpace(text[candidates[0].End..])
? text[candidates[0].Start..candidates[0].End] : text;
}
private static int EndOfObject(string text, int start)
{
var depth = 0; var quoted = false; var escaped = false;
for (var i = start; i < text.Length; i++)
{
var c = text[i];
if (quoted)
{
if (escaped) escaped = false;
else if (c == '\\') escaped = true;
else if (c == '"') quoted = false;
}
else if (c == '"') quoted = true;
else if (c == '{') depth++;
else if (c == '}' && --depth == 0) return i + 1;
}
return -1;
}
}

View File

@ -9,10 +9,13 @@ public sealed record SopDraftVerificationStep(int Id, string Name, bool Complete
public sealed record SopDraftVerificationImage(int StepId, long FrameId, double Seconds, string Scope,
double? Confidence, bool? Accepted, string Reason, [property: JsonIgnore] byte[] Jpeg);
public sealed record SopDraftReferenceCheck(int StepId, int EvidenceFrame, double Seconds, string Scope,
bool? Accepted, double? Confidence, string Reason, [property: JsonIgnore] byte[] Jpeg);
bool? Accepted, double? Confidence, string Reason, [property: JsonIgnore] byte[] Jpeg, string Kind = "completion")
{
[JsonIgnore] public bool Contradicts => Kind == "completion" && Accepted == false || Kind == "previous_state" && Accepted == true;
}
public sealed record SopDraftVerification(bool Passed, string Summary, IReadOnlyList<SopDraftVerificationStep> Steps,
[property: JsonIgnore] IReadOnlyList<SopDraftVerificationImage> Images, string Fingerprint = "", bool InfrastructureFailure = false,
SopTriggerDiagnostics? TriggerDiagnostics = null, IReadOnlyList<SopDraftReferenceCheck>? ReferenceChecks = null);
SopTriggerDiagnostics? TriggerDiagnostics = null, IReadOnlyList<SopDraftReferenceCheck>? ReferenceChecks = null, bool? RuntimePassed = null);
/// <summary>回测和应用草稿共用同一映射,模型只能调整可观察规则,不能调低 AI 放行门槛。</summary>
public static class SopDraftConfigBuilder

View File

@ -8,6 +8,7 @@ public static class SopStepDesignPrompt
输出原则:
- name:简短自然的动作名称,使用本次画面能确认的对象称谓。
- description:完成后的静态可见状态,可描述对象的位置、形态、连接关系或可读标识;只写有证据且与本步有关的特征,不套用固定场景模板。
- 优先使用最小充分的判据:操作主体及关键结果关系。只有工艺明确要求时才附加颜色、左右手、位置修饰或外观细节,避免把非必要细节强加给视觉服务。不能省略主体或关键关系,不能用手出现、接触辅助物来冒充主体操作完成;operation_requirements 保留本次最初操作意图,改写不能逐轮偏离它。
- D3-lite 每次只看当前一张送检图片,看不到视频、历史帧、动作轨迹或操作顺序;description 直接作为完成判据。不能要求推断动作过程,不用“操作完成”“符合要求”等无可见标准的表述。
- 相邻步骤应有可区分的可见变化,前一步结果不应直接满足后一步判据。

View File

@ -11,6 +11,7 @@ internal static class SopVerificationContext
public static HashSet<int> FailedStepIds(SopDraftVerification report)
{
var ids = report.Images.Where(i => i.Accepted == false).Select(i => i.StepId).ToHashSet();
ids.UnionWith((report.ReferenceChecks ?? []).Where(c => c.Contradicts).Select(c => c.StepId));
if (report.Steps.FirstOrDefault(s => !s.Completed) is { } blocked) ids.Add(blocked.Id);
return ids;
}
@ -37,7 +38,7 @@ internal static class SopVerificationContext
Add($"真实回测送检图:步骤 {image.StepId},视频原始帧 {image.FrameId},时间 {image.Seconds.ToString("F3", CultureInfo.InvariantCulture)}s,范围 {image.Scope};AI结果:{image.Reason}。不是 evidence_frame 索引。", image.Jpeg);
foreach (var reference in report.ReferenceChecks ?? [])
if (reference.Jpeg.Length > 0)
Add($"参考判据检查:步骤 {reference.StepId},源 evidence_frame={reference.EvidenceFrame},{reference.Seconds:F3}s,实际送检范围 {reference.Scope}。结果 {reference.Accepted}:{reference.Reason}。此图只验证判据与裁剪,不代表实际手部触发或整轮通过。", reference.Jpeg);
Add($"参考判据检查:步骤 {reference.StepId},类型 {reference.Kind},源 evidence_frame={reference.EvidenceFrame},{reference.Seconds:F3}s,实际送检范围 {reference.Scope}。结果 {reference.Accepted}:{reference.Reason}。completion 是完成参考;previous_state 是前序状态对照,若也判True说明判据可能过宽,须区分相邻步骤。此图不代表实际触发或整轮通过。", reference.Jpeg);
}
return parts;

View File

@ -25,6 +25,8 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
if (request.MaxFramesPerRead is < 2 or > 60) throw new ArgumentException("每次读取帧数须为 2–60");
if (request.VerifyCurrentDraftFirst && (!chatting || request.CurrentDraft is null || request.VerifyDraft is null))
throw new ArgumentException("直接回测需要当前草稿和回测器");
if (request.CheckReference is not null && request.VerifyDraft is null)
throw new ArgumentException("候选参考检查只用于显式回测修订");
var observed = chatting ? request.Video.Frames.ToList() : new List<SopVideoFrame>();
if (observed.Count > 60 || observed.Where((frame, index) => frame.Index != index).Any()) throw new ArgumentException("视频上下文无效");
long jpegBytes = observed.Sum(frame => frame.Jpeg.LongLength);
@ -34,6 +36,9 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
estimatedInput += SopStepDesignPrompt.SingleFrameRules.Length * 2L + JsonSerializer.Serialize(request.ImageScopes).Length * 2L;
var validationRetries = 0;
var verificationAttempts = 0;
var referenceAttempts = 0;
var referenceBlockingId = 1;
var maxTurns = request.CheckReference is null ? 12 : 20;
var pendingCompression = "";
List<object>? verificationBase = null;
var previousFailures = new List<object>();
@ -41,6 +46,8 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
var verificationInstructions = request.VerifyDraft is null
? "本次只生成或编辑草稿,不进行标准视频回测;完成后直接返回,不等待回测反馈,也不能声称已通过回测。"
: "本次为显式回测修订。软件会用标准视频回放当前草稿,并反馈真实手部触发、实际裁剪图和 AI 判定。收到 verification_feedback 后,先分析是触发、裁剪、防抖、判据还是视觉服务问题,再有依据地修改完整草稿,必要时读取动作前后画面。不得删掉失败步骤、改变工艺顺序、缩减完成要求或声称已通过而不依据回测结果;AI 阈值由软件保护,模型不能修改。";
if (request.CheckReference is not null)
verificationInstructions += " 本次可用 check_draft_reference:若自选完成帧也不通过,先依据清晰画面修订可见判据和送检范围,再用该工具检查候选,避免不断整段回放或无目标重读。保持步骤含义和完成要求,不能为高分删去必要条件;参考通过后仍须实际回放验证触发。";
var messages = new List<object>
{
new { role = "system", content = SopStepDesignPrompt.SingleFrameRules + "\n" + verificationInstructions + "\n" + """
@ -65,6 +72,8 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
""" },
new { role = "user", content = JsonSerializer.Serialize(new { mode = chatting ? "chat" : "generate", video_path = request.Video.Path, recipe = request.Recipe,
instructions = request.Instructions,
operation_requirements = request.VerifyDraft is null ? null : request.CurrentDraft?.Steps.Select((s, i) => new
{ step_id = i + 1, operation = s.Name, original_visible_requirement = s.Description }),
video_info = new { duration_seconds = request.Video.DurationSeconds, width = request.Video.Width, height = request.Video.Height },
available_region_keys = request.Regions, region_definitions = request.RegionDefinitions,
region_coordinate_space = "原始相机图像素;工具返回的图片可能缩放,需结合视频原始宽高判断区域位置",
@ -100,7 +109,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
}
messages.Add(new { role = "user", content = "聊天模式。" + request.UserMessage });
}
var tools = new object[]
var tools = new List<object>
{
new { type = "function", function = new { name = "get_video_info", description = "读取当前标准视频的时长、尺寸和可用读取预算",
parameters = new { type = "object", properties = new { }, additionalProperties = false } } },
@ -108,11 +117,19 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
parameters = new { type = "object", properties = new { times_seconds = new { type = "array", items = new { type = "number" },
minItems = 1, maxItems = request.MaxFramesPerRead } }, required = new[] { "times_seconds" }, additionalProperties = false } } }
};
for (var turn = 0; turn < 12; turn++)
if (request.CheckReference is not null)
{
tools.Add(new { type = "function", function = new { name = "check_draft_reference",
description = "用当前视觉服务与受保护阈值检查候选完整草稿中指定步骤及下一步的完成参考帧和实际裁剪。只检查判据/范围,不运行回放、不修改原配方,不代表工艺通过;最多六次。",
parameters = new { type = "object", properties = new { step_id = new { type = "integer", minimum = 1, maximum = 40 },
draft = new { type = "object", description = "完整候选草稿,字段与最终草稿一致;证据编号须已实际读取。" } },
required = new[] { "step_id", "draft" }, additionalProperties = false } } });
}
for (var turn = 0; turn < maxTurns; turn++)
{
token.ThrowIfCancellationRequested();
var verifyCurrent = turn == 0 && request.VerifyCurrentDraftFirst;
if (turn == 11)
if (turn == maxTurns - 1)
messages.Add(new { role = "user", content = "已到本次分析轮数上限,本轮不能继续调用工具。请按 mode 返回完整 JSON;证据不足时明确说明阻塞原因,不得猜测或声称回测通过。" });
var inputLimit = connection.ContextLength - connection.MaxTokens - 1024L;
if (request.VerifyDraft is not null && SopVerificationContext.Deduplicate(messages) is > 0 and var duplicates)
@ -178,7 +195,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
{
model = connection.Model, stream = false, max_tokens = connection.MaxTokens,
temperature = connection.Temperature, top_p = connection.TopP, messages, tools,
tool_choice = turn == 11 ? "none" : "auto"
tool_choice = turn == maxTurns - 1 ? "none" : "auto"
});
using var response = await http.SendAsync(message, requestTimeout.Token).ConfigureAwait(false);
var responseText = await response.Content.ReadAsStringAsync(requestTimeout.Token).ConfigureAwait(false);
@ -254,24 +271,28 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
var report = await verify(draft, request.Video with { Frames = observed }, token).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
draft.Verification = report;
referenceBlockingId = report.Steps.FirstOrDefault(s => !s.Completed)?.Id
?? (report.ReferenceChecks ?? []).FirstOrDefault(c => c.Contradicts)?.StepId ?? 1;
request.Trace?.Invoke(new("verification_result", turn + 1, JsonSerializer.Serialize(new
{
report.Passed, report.Summary, report.Steps, report.InfrastructureFailure, report.TriggerDiagnostics, report.ReferenceChecks,
report.Passed, report.RuntimePassed, report.Summary, report.Steps, report.InfrastructureFailure, report.TriggerDiagnostics, report.ReferenceChecks,
decisions = report.Images.Select(i => new { i.StepId, i.FrameId, i.Seconds, i.Scope, i.Confidence, i.Accepted, i.Reason })
}), report.Images.Select(i => new SopAgentTraceImage($"步骤{i.StepId} 视频帧{i.FrameId} {i.Seconds:F3}s {i.Scope}", i.Jpeg)).ToArray()));
if (!report.Passed && !report.InfrastructureFailure && verificationAttempts < 3 && turn < 11)
}), report.Images.Select(i => new SopAgentTraceImage($"步骤{i.StepId} 视频帧{i.FrameId} {i.Seconds:F3}s {i.Scope}", i.Jpeg))
.Concat((report.ReferenceChecks ?? []).Where(c => c.Jpeg.Length > 0).Select(c => new SopAgentTraceImage($"参考步骤{c.StepId} evidence_frame={c.EvidenceFrame} {c.Scope}", c.Jpeg))).ToArray()));
if (!report.Passed && !report.InfrastructureFailure && verificationAttempts < 3 && turn < maxTurns - 1)
{
var failedIds = SopVerificationContext.FailedStepIds(report);
var feedback = JsonSerializer.Serialize(new
{
verification_feedback = report.Summary, report.Steps,
blocking_step = report.Steps.FirstOrDefault(s => !s.Completed),
blocking_step = report.Steps.FirstOrDefault(s => !s.Completed)
?? new SopDraftVerificationStep(referenceBlockingId, draft.Steps[referenceBlockingId - 1].Name, false, "实际回放已走完,但参考判据正例/前序对照不通过"),
trigger_diagnostics = report.TriggerDiagnostics is { } diagnostics ? SopTriggerDiagnosticsCollector.ForModel(diagnostics, failedIds) : null,
reference_checks = report.ReferenceChecks,
// 已通过步骤的实际触发时间也可能解释后续阻塞,保留轻量元数据,不重复发送图片。
decisions = report.Images.Select(i => new { i.StepId, i.FrameId, i.Seconds, i.Scope, i.Confidence, i.Accepted, i.Reason }).Distinct(),
previous_failures = previousFailures.ToArray(),
required_action = "先读 reference_checks:这是草稿自选完成证据经实际送检裁剪后的同服务判定,不能替代整轮通过。若参考图也未通过,先检查判据是否混入不可见细节或裁剪缺失,保留操作含义、用可见正向状态修订,不能单靠改触发或堆稳定帧。再读 trigger_diagnostics 对比实际启用/取图/发送时间,结合实际手中心和关键画面修订触发。后续等待前序确认不代表失败,不要无依据修改。返回完整草稿,保留工艺、步骤数量顺序和完成要求,不得降低 AI 阈值;区域调整须有画面证据,不得按固定视频时间触发。"
required_action = "先读 reference_checks:completion 是完成参考,应通过;previous_state 是前序/起始状态对照,应不通过。前序也通过说明判据可能过宽,不能作为成功。参考检查不替代整轮通过。完成参考不通过时先检查不可见细节、裁剪缺失,保留操作主体与关键关系,不得为高分删去要求;不能单靠改触发或堆稳定帧。再读 trigger_diagnostics 对比实际启用/取图/发送时间,结合手轨迹和关键画面修订触发。后续等待前序确认不代表失败。返回完整草稿,保留工艺、数量顺序和完成要求,不得降低 AI 阈值;区域调整须有画面证据,不得按固定视频时间触发。"
});
previousFailures.Add(new { attempt = verificationAttempts, report.Summary,
failed_steps = draft.Steps.Where((_, index) => failedIds.Contains(index + 1)).ToArray() });
@ -290,7 +311,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
request.Trace?.Invoke(new("final_result", turn + 1, JsonSerializer.Serialize(new { reply, draft })));
return new(reply, draft, observed);
}
catch (Exception error) when (observed.Count > 0 && validationRetries < 2 && turn < 11
catch (Exception error) when (observed.Count > 0 && validationRetries < 2 && turn < maxTurns - 1
&& error is FormatException or JsonException or KeyNotFoundException)
{
validationRetries++;
@ -307,12 +328,12 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
request.Progress?.Report($"Agent:校验草稿并重新检查({validationRetries}/2)");
continue;
}
catch (JsonException error) when (turn == 11)
catch (JsonException error) when (turn == maxTurns - 1)
{
throw new FormatException("Agent 已达到分析轮数上限,仍未返回有效 JSON 草稿;请查看分析日志中的原始响应和未解决的证据缺口。本次未接受修订。", error);
}
}
if (finish != "tool_calls" || !hasToolCalls || finalCalls.GetArrayLength() is < 1 or > 8 || turn == 11)
if (finish != "tool_calls" || !hasToolCalls || finalCalls.GetArrayLength() is < 1 or > 8 || turn == maxTurns - 1)
throw new FormatException("Agent 响应不完整或不支持工具调用");
var calls = finalCalls;
var assistantText = assistant.TryGetProperty("content", out var body) ? body.Clone() : JsonSerializer.SerializeToElement((string?)null);
@ -330,7 +351,13 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
try
{
using var args = JsonDocument.Parse(function.GetProperty("arguments").GetString() ?? "{}");
if (args.RootElement.EnumerateObject().Any(p => name == "get_video_info" || p.Name != "times_seconds"))
if (args.RootElement.EnumerateObject().Any(p => name switch
{
"get_video_info" => true,
"read_video_frames" => p.Name != "times_seconds",
"check_draft_reference" => p.Name is not ("step_id" or "draft"),
_ => true
}))
throw new ArgumentException();
if (name == "get_video_info")
{
@ -382,10 +409,38 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
result = JsonSerializer.Serialize(new { frames = frames.Select(frame => new { frame_index = frame.Index, seconds = frame.Seconds }),
remaining_frames = FrameBudget() });
}
else result = "{\"error\":\"未知工具,只能使用当前视频读取工具\"}";
else if (name == "check_draft_reference" && request.CheckReference is { } check)
{
if (++referenceAttempts > 6) throw new ArgumentException("参考检查预算已用尽,请提交草稿或明确阻塞原因");
var candidate = args.RootElement.GetProperty("draft").Deserialize<SopVideoDraft>(new JsonSerializerOptions { PropertyNameCaseInsensitive = true })
?? throw new ArgumentException("缺少完整候选草稿");
var idToCheck = args.RootElement.GetProperty("step_id").GetInt32();
if (idToCheck < 1 || idToCheck > candidate.Steps.Count) throw new ArgumentException("步骤编号无效");
if (idToCheck < referenceBlockingId || idToCheck > referenceBlockingId + 1)
throw new ArgumentException($"先解决当前阻塞步骤 {referenceBlockingId} 及紧邻下一步,再回放验证;不要无目标检查后续步骤");
SopVideoDraftClient.Validate(candidate, request.Video with { Frames = observed }, request.Regions, request.RegionDefinitions);
var names = verificationStepNames ?? request.CurrentDraft?.Steps.Select(s => s.Name).ToArray();
if (names is not null && !names.SequenceEqual(candidate.Steps.Select(s => s.Name)))
throw new ArgumentException("参考检查须保留当前工艺的步骤名称、数量和顺序");
var checks = await check(candidate, request.Video with { Frames = observed }, idToCheck, token).ConfigureAwait(false);
result = JsonSerializer.Serialize(new { reference_checks = checks, remaining_reference_checks = Math.Max(0, 6 - referenceAttempts),
reference_ready = checks.Any(c => c.Kind == "completion") && checks.Any(c => c.Kind == "previous_state")
&& checks.Where(c => c.Kind == "completion").All(c => c.Accepted == true)
&& checks.Where(c => c.Kind == "previous_state").All(c => c.Accepted == false),
note = "completion 应通过;previous_state 是前序/起始画面对照,若也通过说明可能未区分相邻步骤,不能只追求正例分数。仅静态检查不等于实际手部触发或流程通过,仍需回放。" });
foreach (var reference in checks.Where(c => c.Jpeg.Length > 0))
{
imageParts.Add(new { type = "text", text = $"候选参考裁剪:步骤{reference.StepId},类型{reference.Kind},源 evidence_frame={reference.EvidenceFrame},{reference.Seconds:F3}s,范围{reference.Scope},判定{reference.Accepted};previous_state应不满足本步,不能用作完成证据。不是实际触发。" });
imageParts.Add(new { type = "image_url", image_url = new { url = "data:image/jpeg;base64," + Convert.ToBase64String(reference.Jpeg) } });
estimatedInput += 1700;
}
request.Trace?.Invoke(new("reference_check", turn + 1, result, checks.Where(c => c.Jpeg.Length > 0)
.Select(c => new SopAgentTraceImage($"参考步骤{c.StepId} evidence_frame={c.EvidenceFrame}", c.Jpeg)).ToArray()));
}
else result = "{\"error\":\"未知或本次不可用的工具\"}";
}
catch (Exception error) when (error is ArgumentException or JsonException or InvalidOperationException or KeyNotFoundException)
{ result = "{\"error\":\"参数无效或超出剩余读取预算。检查秒数、每次帧数和上下文预算\"}"; }
catch (Exception error) when (error is ArgumentException or JsonException or InvalidOperationException or KeyNotFoundException or FormatException)
{ result = JsonSerializer.Serialize(new { error = name == "check_draft_reference" ? error.Message : "参数无效或超出剩余读取预算。检查秒数、每次帧数和上下文预算" }); }
request.Trace?.Invoke(new("tool_result", turn + 1, JsonSerializer.Serialize(new { id, name, result })));
messages.Add(new { role = "tool", tool_call_id = id, content = result });
estimatedInput += result.Length * 2L;

View File

@ -15,7 +15,8 @@ public sealed record SopVideoAnalysisRequest(string Recipe, string Instructions,
IReadOnlyDictionary<string, RegionDef>? RegionDefinitions = null, IReadOnlyList<SopAgentImageScope>? ImageScopes = null,
Func<SopVideoDraft, SopVideoSample, CancellationToken, Task<SopDraftVerification>>? VerifyDraft = null,
IProgress<SopAgentPrompt>? PromptSent = null, Action<SopAgentTrace>? Trace = null,
bool VerifyCurrentDraftFirst = false);
bool VerifyCurrentDraftFirst = false,
Func<SopVideoDraft, SopVideoSample, int, CancellationToken, Task<IReadOnlyList<SopDraftReferenceCheck>>>? CheckReference = null);
public sealed record SopAgentPrompt(int Round, long EstimatedTokens, int ContextLength, string Compression, string Text);
public sealed record SopAgentTrace(string Kind, int Round, string Text, IReadOnlyList<SopAgentTraceImage>? Images = null);
public sealed record SopAgentTraceImage(string Name, byte[] Jpeg);

View File

@ -84,6 +84,7 @@ try
await VerificationContextChecks.RunAsync(info);
await DirectDraftVerificationChecks.RunAsync(info);
TriggerDiagnosticsChecks.Run();
await ReferenceToolChecks.RunAsync(info);
await ContextCompressionChecks.RunAsync(info);
await ResponseDiagnosticsChecks.RunAsync(info);
Check(info.Frames.Count==0&&info.Path==Path.GetFullPath(path),"Agent 应从视频路径和元数据开始,不预选图片");

View File

@ -0,0 +1,55 @@
using System.Net;
using System.Text;
using System.Text.Json;
using SopHelper.Engine.SopAgent;
internal static class ReferenceToolChecks
{
public static async Task RunAsync(SopVideoSample video)
{
var sample = video with { Frames = SopVideoSampler.ReadFrames(video, [.5, 1.5, 2.5, 3.5], 0, default) };
var current = new SopVideoDraft { Steps = Enumerable.Range(0, 4).Select(i => new SopDraftStep
{ Name = "保留工艺" + i, Description = "主体与可见完成关系", Region = "work", StartSeconds = i, EndSeconds = i + 1, EvidenceFrame = i }).ToList() };
foreach (var mode in new[] { "valid", "renamed", "bad_evidence", "extra_argument", "out_of_focus" })
{
var candidate = JsonSerializer.Deserialize<SopVideoDraft>(JsonSerializer.Serialize(current))!;
if (mode == "renamed") candidate.Steps[0].Name = "另一工艺";
if (mode == "bad_evidence") candidate.Steps[0].EvidenceFrame = 99;
using var handler = new ProbeHttp(current, candidate, mode);
using var http = new HttpClient(handler);
var checks = 0; var replays = 0;
var result = await new SopVideoAgentClient(http).ChatAsync(new("通用流程", "保留顺序", sample, ["work"],
UserMessage: "回测并修订", CurrentDraft: current, VerifyCurrentDraftFirst: true,
VerifyDraft: (_, _, _) => { replays++; return Task.FromResult(new SopDraftVerification(replays > 1, "真实回测", [new(1, "保留工艺", replays > 1, "结果")], [])); },
CheckReference: (_, observed, id, _) =>
{
checks++;
Check(observed.Frames.Count == 4 && id == 1, "候选参考检查只能使用实际读取的证据");
return Task.FromResult<IReadOnlyList<SopDraftReferenceCheck>>([new(1, 0, .5, "work", true, .95, "静态参考通过", sample.Frames[0].Jpeg),
new(1, -1, 0, "work", false, .1, "起始对照不满足", [], "previous_state")]);
}), new("https://probe.invalid/v1", "model", "", ContextLength: 131702), default);
Check(result.Draft?.Verification?.Passed == true && replays == 2 && checks == (mode == "valid" ? 1 : 0),
"参考检查不替代真实回放,改工艺、伪造证据或额外路径参数不得进入本地检查");
using var final = JsonDocument.Parse(handler.Bodies[1]);
var resultText = final.RootElement.GetProperty("messages").EnumerateArray().Single(m => m.GetProperty("role").GetString() == "tool").GetProperty("content").GetString()!;
Check(resultText.Contains(mode == "valid" ? "reference_checks" : "error"), "真实参考结果或具体参数错误须反馈给模型");
}
Console.WriteLine("PASS: 候选参考工具、真实回放不可替代、工艺/证据/参数保护与完整结果反馈");
}
private static void Check(bool value, string message) { if (!value) throw new Exception(message); }
private sealed class ProbeHttp(SopVideoDraft current, SopVideoDraft candidate, string mode) : HttpMessageHandler
{
public List<string> Bodies { get; } = [];
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
{
Bodies.Add(await request.Content!.ReadAsStringAsync(token));
var arguments = JsonSerializer.Serialize(new { step_id = mode == "out_of_focus" ? 4 : 1, draft = candidate });
if (mode == "extra_argument") arguments = arguments[..^1] + ",\"path\":\"other.avi\"}";
object response = Bodies.Count == 1
? new { choices = new[] { new { finish_reason = "tool_calls", message = new { role = "assistant", content = (string?)null,
tool_calls = new[] { new { id = "probe", type = "function", function = new { name = "check_draft_reference", arguments } } } } } } }
: new { choices = new[] { new { finish_reason = "stop", message = new { content = JsonSerializer.Serialize(new { reply = "依据检查修订", draft = current }) } } } };
return new(HttpStatusCode.OK) { Content = new StringContent(JsonSerializer.Serialize(response), Encoding.UTF8, "application/json") };
}
}
}

View File

@ -31,12 +31,20 @@ internal static class ResponseDiagnosticsChecks
("```json\n{\"reply\":\"正常\",\"draft\":null}\n```", true),
("```json\n{\"reply\":\"一\",\"draft\":null}\n```\n```json\n{\"reply\":\"二\",\"draft\":null}\n```", false),
("说明\n```json\n{\"reply\":\"残缺\",\"draft\":null}", false),
("说明{\"reply\":\"无明确最终块\",\"draft\":null}", false)
("说明{\"reply\":\"无明确最终块\",\"draft\":null}", false),
("分析说明\n{\"reply\":\"正常\",\"draft\":null}", true),
("分析说明\n{\"reply\":\"一\",\"draft\":null}\n{\"reply\":\"二\",\"draft\":null}", false),
("分析说明\n{\"reply\":\"正常\",\"draft\":null,\"note\":\"花括号 } 和转义引号 \\\"\"}", true)
})
{
using var http = new HttpClient(new ReplyHttp(JsonSerializer.Serialize(new { choices = new[] { new { finish_reason = "stop", message = new { content } } } })));
var accepted = false;
try { accepted = (await new SopVideoAgentClient(http).ChatAsync(new("兼容", "", video, ["work"], UserMessage: "讨论"), new("https://invalid.test/v1", "model", ""), default)).Reply == "正常"; }
try
{
var result = await new SopVideoAgentClient(http).ChatAsync(new("兼容", "", video, ["work"], UserMessage: "讨论"), new("https://invalid.test/v1", "model", ""), default);
accepted = true;
if (valid) Check(result.Reply == "正常", "唯一最终JSON对象的内容必须准确保留");
}
catch (Exception error) when (error is JsonException or FormatException) { }
Check(accepted == valid, "只接受明确且唯一的最终完整JSON代码块,不能猜测多个候选或截断输出");
}

View File

@ -10,7 +10,7 @@ using SopHelper.Training;
internal static class AgentBenchmarkChecks
{
public static async Task RunAsync(string configPath, string videoPath, string settingsPath, string reportPath,
string? sourceReportPath = null, bool verifyCurrentFirst = false, bool disableThinking = false, string? draftPath = null)
string? sourceReportPath = null, bool verifyCurrentFirst = false, bool disableThinking = false, string? draftPath = null, int referenceStep = 0, bool replayOnly = false)
{
Directory.CreateDirectory(reportPath);
using var settings = JsonDocument.Parse(File.ReadAllText(settingsPath));
@ -82,31 +82,57 @@ internal static class AgentBenchmarkChecks
Log($"生成完成:{draft.Steps.Count} 步,耗时 {generationSeconds:F2}s");
stage = "verify_and_revise";
handler.Stage = stage;
if (referenceStep > 0)
{
var checks = await new SopDraftReferenceVerifier().CheckAsync(SopDraftConfigBuilder.Build(template, draft), draft, video with { Frames = draft.ObservedFrames }, referenceStep, cancellation.Token);
Save("reference-checks.json", checks);
foreach (var check in checks.Where(c => c.Jpeg.Length > 0)) File.WriteAllBytes(Path.Combine(reportPath, $"reference-step-{check.StepId}-{check.Kind}.jpg"), check.Jpeg);
Log("仅静态参考检查,不代表回放通过:" + string.Join(";", checks.Select(c => $"步骤{c.StepId} {c.Kind} {c.Accepted} {c.Confidence:P1}")));
return;
}
var round = 0;
var probeRound = 0;
async Task<SopDraftVerification> Verify(SopVideoDraft current, SopVideoSample observed, CancellationToken token)
{
var index = ++round;
Save("latest-draft.json", current);
Save("observed-frames.json", observed.Frames.Select(f => new { f.Index, f.Seconds }));
foreach (var frame in observed.Frames)
if (!File.Exists(Path.Combine(reportPath, $"observed-{frame.Index}.jpg")))
File.WriteAllBytes(Path.Combine(reportPath, $"observed-{frame.Index}.jpg"), frame.Jpeg);
var watch = Stopwatch.StartNew();
var report = await new SopDraftVideoVerifier().VerifyAsync(current, observed, template, progress, token);
playback.Add(new { Round = index, Seconds = watch.Elapsed.TotalSeconds, report.Passed, report.Summary, report.InfrastructureFailure, Images = report.Images.Count });
Save($"round-{index}-draft.json", current); Save($"round-{index}-result.json", report);
foreach (var image in report.Images) File.WriteAllBytes(Path.Combine(reportPath, $"round-{index}-step-{image.StepId}-frame-{image.FrameId}.jpg"), image.Jpeg);
foreach (var reference in report.ReferenceChecks ?? [])
if (reference.Jpeg.Length > 0) File.WriteAllBytes(Path.Combine(reportPath, $"round-{index}-reference-step-{reference.StepId}-{reference.Kind}-evidence-{reference.EvidenceFrame}.jpg"), reference.Jpeg);
Log($"回放 {index} 耗时 {watch.Elapsed.TotalSeconds:F2}s,通过={report.Passed};{report.Summary}");
return report;
}
if (replayOnly)
{
final = draft;
final.Verification = await Verify(draft, video with { Frames = draft.ObservedFrames }, cancellation.Token);
Save("final-draft.json", final);
if (!final.Verification.Passed) throw new InvalidOperationException("回测未通过:" + final.Verification.Summary);
return;
}
var result = await client.ChatAsync(request with
{
Video = video with { Frames = draft.ObservedFrames }, CurrentDraft = draft, VerifyCurrentDraftFirst = verifyCurrentFirst,
Conversation = [new("assistant", draft.Summary)],
UserMessage = "请基于当前草稿保留工艺要求,用标准视频回测,并仅按实际失败证据修订,返回完整草稿;不要重新从头生成,不要只回复讨论文字。",
VerifyDraft = async (current, observed, token) =>
CheckReference = async (candidate, observed, id, token) =>
{
var index = ++round;
Save("latest-draft.json", current);
Save("observed-frames.json", observed.Frames.Select(f => new { f.Index, f.Seconds }));
foreach (var frame in observed.Frames)
if (!File.Exists(Path.Combine(reportPath, $"observed-{frame.Index}.jpg")))
File.WriteAllBytes(Path.Combine(reportPath, $"observed-{frame.Index}.jpg"), frame.Jpeg);
var watch = Stopwatch.StartNew();
var report = await new SopDraftVideoVerifier().VerifyAsync(current, observed, template, progress, token);
playback.Add(new { Round = index, Seconds = watch.Elapsed.TotalSeconds, report.Passed, report.Summary, report.InfrastructureFailure, Images = report.Images.Count });
Save($"round-{index}-draft.json", current);
Save($"round-{index}-result.json", report);
foreach (var image in report.Images) File.WriteAllBytes(Path.Combine(reportPath, $"round-{index}-step-{image.StepId}-frame-{image.FrameId}.jpg"), image.Jpeg);
foreach (var reference in report.ReferenceChecks ?? [])
if (reference.Jpeg.Length > 0) File.WriteAllBytes(Path.Combine(reportPath, $"round-{index}-reference-step-{reference.StepId}-evidence-{reference.EvidenceFrame}.jpg"), reference.Jpeg);
Log($"回放 {index} 耗时 {watch.Elapsed.TotalSeconds:F2}s,通过={report.Passed};{report.Summary}");
return report;
}
var index = ++probeRound;
var checks = await new SopDraftReferenceVerifier().CheckAsync(SopDraftConfigBuilder.Build(template, candidate), candidate, observed, id, token);
Save($"probe-{index}-draft.json", candidate); Save($"probe-{index}-result.json", checks);
foreach (var image in checks.Where(c => c.Jpeg.Length > 0)) File.WriteAllBytes(Path.Combine(reportPath, $"probe-{index}-step-{image.StepId}-{image.Kind}.jpg"), image.Jpeg);
Log($"候选参考检查 {index}:" + string.Join(";", checks.Select(c => $"步骤{c.StepId} {c.Kind} {c.Accepted} {c.Confidence:P1}")));
return checks;
},
VerifyDraft = Verify
}, connection, cancellation.Token);
final = result.Draft;
Save("final-draft.json", final);
@ -119,7 +145,7 @@ internal static class AgentBenchmarkChecks
Save("benchmark.json", new { connection.Model, connection.MaxTokens, connection.ContextLength, VideoSeconds = video.DurationSeconds,
TotalSeconds = timer.Elapsed.TotalSeconds, GenerationSeconds = generationSeconds,
VerificationSeconds = stage == "verify_and_revise" ? timer.Elapsed.TotalSeconds - generationSeconds : 0,
ReusedDraft = sourceReportPath is not null, VerifyCurrentFirst = verifyCurrentFirst, DisableThinking = disableThinking,
ReusedDraft = sourceReportPath is not null, VerifyCurrentFirst = verifyCurrentFirst, DisableThinking = disableThinking, ReferenceOnly = referenceStep > 0, ReplayOnly = replayOnly,
Passed = final?.Verification?.Passed == true, Error = error, ConfigUnchanged = unchanged,
Prompts = prompts, Requests = handler.Requests, Playback = playback });
if (!unchanged) throw new Exception("测速修改了原配方");

View File

@ -161,6 +161,7 @@ internal static class AgentDraftVerificationChecks
public async Task<SopDraftVerification> VerifyAsync(SopVideoDraft draft, SopVideoSample video, SopConfig template, IProgress<string>? progress, CancellationToken token)
{
Calls++; Entered = Hold;
if (Calls == 1) Check(template.Sop.Steps.Count == 0, "Unapplied drafts do not inherit unrelated recipe step image settings");
if (Hold) await Task.Delay(Timeout.Infinite, token);
return new(Passed, Passed ? "回测通过" : "回测未通过", [new(1, draft.Steps[0].Name, Passed, "本地判定")], [],
SopDraftConfigBuilder.Fingerprint(SopDraftConfigBuilder.Build(template, draft), video));

View File

@ -22,7 +22,8 @@ internal static class LiveVideoFlowChecks
Pump(Task.Run(() => AgentBenchmarkChecks.RunAsync(path, video,
Value("--agent-settings") ?? throw new ArgumentException("需要 --agent-settings"),
Value("--report") ?? throw new ArgumentException("需要 --report"), Value("--reuse-draft"),
args.Contains("--verify-current-first"), args.Contains("--disable-thinking"), Value("--draft-file"))));
args.Contains("--verify-current-first"), args.Contains("--disable-thinking"), Value("--draft-file"),
int.Parse(Value("--reference-step") ?? "0"), args.Contains("--replay-only"))));
return;
}
if (args.Contains("--agent-generate"))

View File

@ -18,10 +18,12 @@ internal static class ReferenceEvidenceChecks
var before = SopConfigLoader.ToYaml(config);
var probe = new ProbeClient();
var checks = new SopDraftReferenceVerifier(probe).CheckAsync(config, draft, video, 1, default).GetAwaiter().GetResult();
Check(checks.Count == 2 && checks[0].Accepted == false && checks[1].Accepted == true, "参考检查必须使用各步骤原有AI阈值,不得降低阈值凑通过");
Check(probe.FrameIds.SequenceEqual(new long[] { 5, 15 }) && checks[0].EvidenceFrame == 0 && checks[0].Seconds == .5,
Check(checks.Count == 4 && checks[0].Accepted == false && checks[2].Accepted == true && checks[1].Kind == "previous_state", "参考检查必须使用各步骤原有AI阈值并包含前序对照,不得降低阈值凑通过");
Check(probe.FrameIds.SequenceEqual(new long[] { 5, 0, 15, 5 }) && checks[0].EvidenceFrame == 0 && checks[0].Seconds == .5,
"参考证据索引、视频原始帧号和时间须区分");
Check(before == SopConfigLoader.ToYaml(config), "参考判据检查不修改原配置或推进流程");
Check(checks[0].Contradicts && checks[3].Contradicts && !checks[1].Contradicts && !checks[2].Contradicts,
"正例失败或前序状态也通过均须标记矛盾,不能把前序误判为本步完成");
config.Sop.Steps[0].AiConfirmation!.ImageMode = "hand";
checks = new SopDraftReferenceVerifier(probe).CheckAsync(config, draft, video, 1, default).GetAwaiter().GetResult();
Check(checks[0].Accepted is null && checks[0].Jpeg.Length == 0, "跟随手部范围不能用伪造静态范围替代实际跟踪");