按判定模式复核真实参考片段并压缩回测中文上下文

This commit is contained in:
tfarcraw 2026-11-19 09:20:16 +08:00
parent 96f297eb8e
commit d09665c6dc
12 changed files with 145 additions and 46 deletions

View File

@ -5,7 +5,7 @@ using SopHelper.Engine.SopAgent;
namespace SopHelper.Training;
/// <summary>对草稿引用的完成证据做同服务、同裁剪的静态检查;不替代运行时手部触发及整轮回放。</summary>
/// <summary>按草稿模式用同服务、同裁剪检查完成/前序参考;不替代手部触发及整轮回放。</summary>
public sealed class SopDraftReferenceVerifier(IVisionDecisionClient? vision = null)
{
private static readonly HttpClient Http = new() { Timeout = Timeout.InfiniteTimeSpan };
@ -13,7 +13,7 @@ public sealed class SopDraftReferenceVerifier(IVisionDecisionClient? vision = nu
SopVideoSample video, int blockedId, CancellationToken token)
{
var checks = new List<SopDraftReferenceCheck>();
var client = vision ?? new ConfiguredVisionDecisionClient(Http);
var client = vision ?? new ConfiguredVisionDecisionClient(Http, new DesktopSequenceVisionClient(Http));
foreach (var id in new[] { blockedId, blockedId + 1 }.Where(id => id > 0 && id <= draft.Steps.Count))
{
var step = config.Sop.Steps[id - 1]; var source = draft.Steps[id - 1];
@ -25,9 +25,9 @@ public sealed class SopDraftReferenceVerifier(IVisionDecisionClient? vision = nu
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 (options.EvidenceMode == VisionEvidenceMode.Sequence)
if (options.EvidenceMode == VisionEvidenceMode.Sequence && !client.SupportsSequences)
{
checks.Add(new(id, evidence, seconds, scope, null, null, "过程时序需真实连续证据,本单帧参考检查不代判;以运行回放和未完成对照另行验证", [], kind));
checks.Add(new(id, evidence, seconds, scope, null, null, "过程时序服务不可用,不能用单帧参考代判", [], kind, options.EvidenceMode, InfrastructureFailure: true));
continue;
}
if (mode == VisionImageMode.Hand)
@ -49,18 +49,49 @@ public sealed class SopDraftReferenceVerifier(IVisionDecisionClient? vision = nu
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);
var frames = new List<VisionEvidenceFrame>();
if (options.EvidenceMode == VisionEvidenceMode.Sequence)
{
var previousSeconds = id > 1 ? video.Frames[draft.Steps[id - 2].EvidenceFrame].Seconds : 0;
var startSeconds = Math.Max(kind == "completion" ? previousSeconds : 0,
seconds - options.ObservationMaxMs / 1000d);
var startIndex = Math.Clamp((long)Math.Round(startSeconds * capture.Fps), 0, index);
var stride = Math.Max(1, (long)Math.Round(options.ObservationSampleMs * capture.Fps / 1000d));
for (var f = startIndex; f <= index; f = Math.Min(f + stride, index))
{
token.ThrowIfCancellationRequested();
if (!capture.Set(VideoCaptureProperties.PosFrames, f) || !capture.Read(image) || image.Empty())
throw new IOException("无法解码过程参考片段");
frames.Add(new(f, DateTime.UnixEpoch.AddSeconds(f / capture.Fps), VisionDecisionImage.Encode(image, region), f / capture.Fps));
if (frames.Count > options.ObservationMaxFrames)
frames = VisualEvidenceSampler.Select(frames, options.ObservationMaxFrames).ToList();
if (f == index) break;
}
frames = VisualEvidenceSampler.Select(frames, options.ObservationRequestMaxFrames).ToList();
}
return (Jpeg: frames.Count > 0 ? frames[^1].Jpeg : VisionDecisionImage.Encode(image, region), FrameId: index, Frames: frames);
}, token).ConfigureAwait(false);
jpeg = decoded.Jpeg;
if (options.EvidenceMode == VisionEvidenceMode.Sequence && decoded.Frames.Count < 3)
{
checks.Add(new(id, evidence, seconds, scope, kind == "completion" ? false : null, null,
"过程参考不足三张真实不同帧,未复制画面或用单帧代判", jpeg, kind, options.EvidenceMode, decoded.Frames));
continue;
}
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));
var request = new VisionDecisionRequest(config.Sop.Name, id, step.Name, step.Description, step.Description,
decoded.FrameId, DateTime.Now, jpeg, options.EvidenceMode, decoded.Frames, seconds);
var decision = await client.DecideAsync(request, budget.Token).ConfigureAwait(false);
var accepted = decision.EffectiveStatus == VisionDecisionStatus.Completed && decision.Completed
&& double.IsFinite(decision.Confidence) && decision.Confidence >= options.MinConfidence && decision.Confidence <= 1
&& (options.EvidenceMode != VisionEvidenceMode.Sequence || VisionDecisionEvidence.SupportEnd(request, decision) is not null);
bool? known = decision.EffectiveStatus == VisionDecisionStatus.Unsupported ? null : accepted;
checks.Add(new(id, evidence, seconds, scope, known, decision.Confidence, decision.Reason, jpeg, kind, options.EvidenceMode, decoded.Frames,
decision.EffectiveStatus == VisionDecisionStatus.Unsupported));
}
catch (Exception error) when (error is not OperationCanceledException || !token.IsCancellationRequested)
{ checks.Add(new(id, evidence, seconds, scope, null, null, "参考判据检查不可用:" + error.Message, jpeg, kind)); }
{ checks.Add(new(id, evidence, seconds, scope, null, null, "参考判据检查不可用:" + error.Message, jpeg, kind, options.EvidenceMode, InfrastructureFailure: true)); }
}
}
return checks;

View File

@ -85,11 +85,13 @@ public sealed class SopDraftVideoVerifier : ISopDraftVideoVerifier
: blocked is null ? [] : new[] { blocked.Id })
references.AddRange(await new SopDraftReferenceVerifier().CheckAsync(config, draft, video, id, budget.Token));
EnsureSource();
infrastructureFailure |= references.Any(c => c.InfrastructureFailure);
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,
if (infrastructureFailure) summary = "标准视频参考复核服务未返回有效判定,尚未完成验收;不应据此放宽工艺要求";
return new(test.IsCompleted && !contradictory && !infrastructureFailure, summary, test.StepResults,
images.Values.OrderBy(i => i.StepId).ToArray(), fingerprint, infrastructureFailure, diagnostics.Build(), references, test.IsCompleted);
}
catch (OperationCanceledException) when (!token.IsCancellationRequested)

View File

@ -1,3 +1,4 @@
using System.Text.Encodings.Web;
using System.Text.RegularExpressions;
using System.Text.Json;
@ -5,6 +6,10 @@ namespace SopHelper.Engine.SopAgent;
internal static class SopAgentJson
{
// JSON 作为模型消息文本时保留中文,避免重复转义扩大上下文。
private static readonly JsonSerializerOptions Options = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
public static string Serialize<T>(T value) => JsonSerializer.Serialize(value, Options);
// 部分服务会在最终 JSON 前输出说明。仅接受唯一明确且位于末尾的完整对象,不猜测多个候选或修补残缺 JSON。
public static string Payload(string text)
{

View File

@ -11,9 +11,13 @@ public sealed record SopDraftVerificationImage(int StepId, long FrameId, double
string EvidenceMode = VisionEvidenceMode.SingleFrame,
[property: JsonIgnore] IReadOnlyList<VisionEvidenceFrame>? Frames = null);
public sealed record SopDraftReferenceCheck(int StepId, int EvidenceFrame, double Seconds, string Scope,
bool? Accepted, double? Confidence, string Reason, [property: JsonIgnore] byte[] Jpeg, string Kind = "completion")
bool? Accepted, double? Confidence, string Reason, [property: JsonIgnore] byte[] Jpeg, string Kind = "completion",
string EvidenceMode = VisionEvidenceMode.SingleFrame, [property: JsonIgnore] IReadOnlyList<VisionEvidenceFrame>? Frames = null,
bool InfrastructureFailure = false)
{
[JsonIgnore] public bool Contradicts => Kind == "completion" && Accepted == false || Kind == "previous_state" && Accepted == true;
public IReadOnlyList<long>? FrameIds => Frames?.Select(f => f.FrameId).ToArray();
public double? StartSeconds => Frames?.FirstOrDefault()?.SourceSeconds;
}
public sealed record SopDraftVerification(bool Passed, string Summary, IReadOnlyList<SopDraftVerificationStep> Steps,
[property: JsonIgnore] IReadOnlyList<SopDraftVerificationImage> Images, string Fingerprint = "", bool InfrastructureFailure = false,

View File

@ -8,7 +8,7 @@ public static class SopStepDesignPrompt
判定方式:
- 每步 inspection.evidence_mode 默认 single_frame:适合稳定、清晰且能区分前序的可见结果。D3-lite 只看当前送检图,看不到过程、历史或区外状态;description 必须是可直接验证的静态状态,不能写无依据的“符合要求”。
- inspection_capabilities.sequence=true 时可新选 sequence:适合必须看到状态变化、单帧正反例难区分、结果短暂或易被后续动作遮挡的操作。description 保留关键变化及最终结果,模型检查按序真实画面,返回完成/未完成/证据不足。已有时序步骤保留过程要求。服务不可用时说明能力缺口,不能假装配置成功或改成宽松外观来凑通过。
- 不机械统一模式。name 简述动作;description 采用最小充分判据:操作主体及关键结果关系。仅工艺明确要求时附加颜色、左右手、部件、质量等细节;用户明确要求必须保留。手出现或接触不能代替主体完成。operation_requirements 保留最初工艺意图,不能逐轮漂移;相邻步骤必须可区分。
- 不机械统一模式。name 简述动作;description 采用最小充分判据:操作主体及关键结果关系。仅工艺明确要求时附加颜色、左右手、部件、质量等细节;用户明确要求必须保留。触发条件不自动成为验收要求;用户未要求时,不能额外要求手离开或整理收尾。手出现或接触不能代替主体完成。operation_requirements 保留最初工艺意图,不能逐轮漂移;相邻步骤必须可区分。
检查策略 inspection(可省略字段沿用原值):
- evidence_mode=single_frame/sequence;check_window_ms=500–60000;max_checks=1–20;check_settle_ms=100–3000且小于窗口;observation_min_ms=200–30000;observation_max_ms>=min且<=60000;observation_max_frames和observation_request_max_frames各3–32。
@ -18,7 +18,7 @@ public static class SopStepDesignPrompt
触发及范围:
- hand_in_region:手中心在主区域内达到稳定帧数,适合手仍在操作或短暂结果的过程取证。hand_leave_region:先接触再离开,适合离开后仍可见的稳定结果。hand_move:同一只手先经过起点再到终点,必须引用两个不同有效区域;手移动不证明物体已移动。其他规则须有效主区域。
- 不能一律等手离开。新离开/跨区事件须在前序实际结果之后;模型返回时刻不是动作完成时刻。方法、防抖按真实手轨迹及取证时机选择,禁止按固定视频秒数触发或用堆稳定帧代替证据。
- 触发区对应实际操作,送检区可独立覆盖完整判据。新步骤默认裁剪主区域,hand_move 裁剪终点;hand 范围会移动。按 inspection_image_policy、step_image_context 和坐标核对范围,最长边缩至512像素后仍须可辨;不能判断区外状态。扩大范围或整帧不保证更准,必须验证。
- 触发区对应手部事件,送检区独立覆盖关键过程和完整结果。时序必须显式指定 image_mode 及必要的 image_region,不能盲用狭小触发区;整体位置关系可选 full_frame,局部细节应选完整且可辨的区域。新步骤默认裁剪主区域,hand_move 裁剪终点;hand 范围会移动。按 inspection_image_policy、step_image_context 和坐标核对范围,最长边缩至512像素后仍须可辨;不能判断区外状态。扩大范围或整帧不保证更准,必须验证。
回测修订:
- 先核对实际送检帧采集时间、范围和内容,再用同服务同裁剪的完成参考及前序未完成对照定位。正例通过而运行失败:检查触发、错过瞬态和选帧;清晰正例也失败:检查判据、范围或服务能力;前序也通过:判据过宽,不得放行。时序参考必须用真实片段,不能用单帧代判。

View File

@ -39,7 +39,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);
if (image.EvidenceMode == Sop.VisionEvidenceMode.Sequence && image.Frames is { Count: > 0 } frames)
{
parts.Add(new { type = "text", text = "该步骤实际使用过程时序判定;以下仅为最多五张代表画面,不代表完整过程。" + JsonSerializer.Serialize(
parts.Add(new { type = "text", text = "该步骤实际使用过程时序判定;以下仅为最多五张代表画面,不代表完整过程。" + SopAgentJson.Serialize(
frames.Select(f => new { f.FrameId, f.SourceSeconds })) });
foreach (var index in Enumerable.Range(0, Math.Min(5, frames.Count))
.Select(i => (int)Math.Round(i * (frames.Count - 1d) / Math.Max(1, Math.Min(5, frames.Count) - 1))).Distinct())
@ -50,8 +50,13 @@ internal static class SopVerificationContext
}
}
foreach (var reference in report.ReferenceChecks ?? [])
{
if (reference.Jpeg.Length > 0)
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);
if (reference.Frames is { Count: >= 3 } process)
foreach (var frame in Sop.VisualEvidenceSampler.Select(process, 5))
Add($"参考片段:步骤 {reference.StepId},{reference.Kind},原始帧 {frame.FrameId},{frame.SourceSeconds:F3}s;仅相关代表帧,完整送检帧号见参考检查元数据。", frame.Jpeg);
}
}
return parts;
@ -97,7 +102,7 @@ internal static class SopVerificationContext
public static object Catalog(IReadOnlyList<SopVideoFrame> observed) => new
{
role = "user", content = JsonSerializer.Serialize(new
role = "user", content = SopAgentJson.Serialize(new
{
evidence_catalog = observed.Select(f => new { frame_index = f.Index, seconds = f.Seconds }),
note = "仅附相关关键帧和最新失败送检图;目录不代表图片已发送。可保留未修改步骤的已有证据编号;修改判据或区域须有当前可见证据,缺少时按秒数补看。remaining_frames 是新增帧预算,已有帧可按目录时间再次请求并复用原编号。"

View File

@ -32,8 +32,8 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
long jpegBytes = observed.Sum(frame => frame.Jpeg.LongLength);
var estimatedInput = 2048L + request.Instructions.Length * 2L + request.Recipe.Length * 2L
+ request.Regions.Sum(region => region.Length * 2L) + observed.Count * 1700L;
estimatedInput += JsonSerializer.Serialize(request.RegionDefinitions).Length * 2L;
estimatedInput += SopStepDesignPrompt.SingleFrameRules.Length * 2L + JsonSerializer.Serialize(request.ImageScopes).Length * 2L;
estimatedInput += SopAgentJson.Serialize(request.RegionDefinitions).Length * 2L;
estimatedInput += SopStepDesignPrompt.SingleFrameRules.Length * 2L + SopAgentJson.Serialize(request.ImageScopes).Length * 2L;
var validationRetries = 0;
var verificationAttempts = 0;
var referenceAttempts = 0;
@ -53,10 +53,10 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
new { role = "system", content = SopStepDesignPrompt.SingleFrameRules + "\n" + verificationInstructions + "\n" + """
你是本地 SOP Agent。用户给你一个标准操作视频路径。必须调用工具读取视频,不能仅凭文件名、元数据或常识生成步骤。
高效查看策略:
- 首条用户消息已提供 video_info,无需先调用 get_video_info;直接按视频时长自行选择时间点调用 read_video_frames。元数据不是画面证据。
- 首条用户消息已提供 video_info,无需先调用 get_video_info;首批按视频时长覆盖开头、中段、近结尾调用 read_video_frames,避免漏掉末段工序。元数据不是画面证据。
- times_seconds 为秒数数组,每次不超过 max_frames_per_read 和剩余预算;将同一轮所需时间点合并读取,先覆盖全程,再针对动作边界、遮挡或缺失结果补看。
- 每次补看须解决具体证据缺口,避免重复读取已清晰的时间点。通常争取 1–3 批读取后提交;复杂流程可继续补看,不能为减少轮数遗漏步骤或猜测。
- 每步已有结果证据、顺序和有效区域后立即提交,不为措辞润色反复读图。遗漏、模糊和未确认内容写入 warnings/note;证据或标定持续不足时说明阻塞原因。
- 先按用户工艺意图核对全程覆盖,不能遗漏独立监控动作;每步已有结果证据、顺序和有效区域后立即提交,不为措辞润色反复读图。遗漏、模糊和未确认内容写入 warnings/note;证据或标定持续不足时说明阻塞原因。
区域必须引用已有标定或有画面证据的 region_adjustments。不得为通过校验改变动作含义、步骤顺序或编造区域。
若区域偏离目标,可提出校正或新增触发区。region_adjustments 为可选数组,每项含 key、name、x1、y1、x2、y2、evidence_frame、note;坐标为原始视频像素整数,必须有实际画面依据和原因,只进入草稿,不自动保存。缺少依据时返回 blocked_reason 或 draft:null。
每步可指定 inspection(字段、范围和默认值见通用规则)选择判定模式及有限检查/取证策略;note 简述选取依据和证据缺口。每步可指定 stable_frames(1–120)、tolerance、image_mode(fixed_region/full_frame/hand)、image_region。触发区和送检区可以不同:触发区跟踪手部动作,送检区必须完整覆盖完成判据需要的物体。未指定时沿用现有配置或默认值。
@ -67,10 +67,10 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
严格按用户消息的 mode 输出。工具调用结束后只返回完整 JSON,不输出 Markdown。
mode=generate 时直接返回根节点包含 steps 的完整草稿,不套 reply/draft 外层;确实阻塞时仅返回非空 blocked_reason。
mode=chat 时返回 {"reply":"给用户的自然中文答复","draft":完整草稿或null}。草稿格式如下:
{"summary":"流程简述","warnings":[],"steps":[{"name":"操作名称","description":"对应模式能验证的完成要求","start_seconds":0,"end_seconds":2,"method":"hand_leave_region","region":"<实际已标定区域键>","from_region":"","to_region":"","hand":"any","evidence_frame":0,"inspection":{"evidence_mode":"single_frame","check_window_ms":10000,"max_checks":3},"note":"选择触发及判定模式的依据"}]}
{"summary":"流程简述","warnings":[],"steps":[{"name":"操作名称","description":"对应模式能验证的完成要求","start_seconds":0,"end_seconds":2,"method":"hand_leave_region","region":"<实际已标定区域键>","from_region":"","to_region":"","hand":"any","evidence_frame":0,"image_mode":"fixed_region","image_region":"<实际已标定送检区域键>","inspection":{"evidence_mode":"single_frame","check_window_ms":10000,"max_checks":3},"note":"选择触发及判定模式的依据"}]}
region 的示例占位符必须替换为实际区域键,不能照抄占位符或输出空区域草稿。
""" },
new { role = "user", content = JsonSerializer.Serialize(new { mode = chatting ? "chat" : "generate", video_path = request.Video.Path, recipe = request.Recipe,
new { role = "user", content = SopAgentJson.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 }),
@ -93,7 +93,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
historyCount++;
estimatedInput += previous.Text.Length * 2L;
}
var currentDraft = JsonSerializer.Serialize(request.CurrentDraft);
var currentDraft = SopAgentJson.Serialize(request.CurrentDraft);
messages.Add(new { role = "user", content = "当前可编辑草稿:" + currentDraft });
estimatedInput += currentDraft.Length * 2L + request.UserMessage.Length * 2L;
if (observed.Count > 0)
@ -120,7 +120,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
if (request.CheckReference is not null)
{
tools.Add(new { type = "function", function = new { name = "check_draft_reference",
description = "用当前视觉服务与受保护阈值检查候选完整草稿中指定步骤及下一步的完成参考帧和实际裁剪。只检查判据/范围,不运行回放、不修改原配方,不代表工艺通过;最多六次。",
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 } } });
@ -180,7 +180,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
{
// 直接将当前快照送入下方统一校验和回测路径;不伪造模型请求/响应日志。
finish = "stop";
assistant = JsonSerializer.SerializeToElement(new { content = JsonSerializer.Serialize(new
assistant = JsonSerializer.SerializeToElement(new { content = SopAgentJson.Serialize(new
{ reply = "已按当前草稿执行标准视频回测。", draft = request.CurrentDraft }) });
request.Progress?.Report("直接回测当前草稿,失败后再请求 Agent 修订…");
}
@ -274,7 +274,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
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
request.Trace?.Invoke(new("verification_result", turn + 1, SopAgentJson.Serialize(new
{
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 })
@ -283,7 +283,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
if (!report.Passed && !report.InfrastructureFailure && verificationAttempts < 3 && turn < maxTurns - 1)
{
var failedIds = SopVerificationContext.FailedStepIds(report);
var feedback = JsonSerializer.Serialize(new
var feedback = SopAgentJson.Serialize(new
{
verification_feedback = report.Summary, report.Steps,
blocking_step = report.Steps.FirstOrDefault(s => !s.Completed)
@ -300,7 +300,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
messages.Clear();
messages.AddRange(verificationBase!);
if (!verifyCurrent) historyCount = 0; // 首次本地回测失败时,历史摘要推迟至真正请求模型前。
messages.Add(new { role = "user", content = "当前可编辑草稿:" + JsonSerializer.Serialize(draft) });
messages.Add(new { role = "user", content = "当前可编辑草稿:" + SopAgentJson.Serialize(draft) });
messages.Add(SopVerificationContext.Catalog(observed));
messages.Add(new { role = "user", content = feedback });
var images = SopVerificationContext.Images(draft, observed, report);
@ -309,7 +309,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
continue;
}
}
request.Trace?.Invoke(new("final_result", turn + 1, JsonSerializer.Serialize(new { reply, draft })));
request.Trace?.Invoke(new("final_result", turn + 1, SopAgentJson.Serialize(new { reply, draft })));
return new(reply, draft, observed);
}
catch (Exception error) when (observed.Count > 0 && validationRetries < 2 && turn < maxTurns - 1
@ -317,7 +317,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
{
validationRetries++;
request.Trace?.Invoke(new("draft_validation_error", turn + 1, error.ToString()));
var feedback = JsonSerializer.Serialize(new
var feedback = SopAgentJson.Serialize(new
{
validation_error = error is FormatException ? error.Message : "草稿 JSON 格式无效",
required_action = "检查并重新提交完整草稿。保留用户的工艺要求,不得改动作含义、伪造区域或取消规则来凑合法配置;缺少标定时明确说明阻塞原因。",
@ -363,7 +363,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
if (name == "get_video_info")
{
request.Progress?.Report("Agent:读取视频信息");
result = JsonSerializer.Serialize(new { path = request.Video.Path, duration_seconds = request.Video.DurationSeconds,
result = SopAgentJson.Serialize(new { path = request.Video.Path, duration_seconds = request.Video.DurationSeconds,
width = request.Video.Width, height = request.Video.Height, max_frames_per_read = request.MaxFramesPerRead,
remaining_frames = FrameBudget() });
}
@ -404,10 +404,10 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
AddImage(imageParts, frame);
}
request.Trace?.Invoke(new("video_frames", turn + 1,
JsonSerializer.Serialize(frames.Select(f => new { f.Index, f.Seconds })),
SopAgentJson.Serialize(frames.Select(f => new { f.Index, f.Seconds })),
frames.Select(f => new SopAgentTraceImage($"frame_index={f.Index}, time={f.Seconds:F3}s", f.Jpeg)).ToArray()));
estimatedInput += frames.Count * 1700L;
result = JsonSerializer.Serialize(new { frames = frames.Select(frame => new { frame_index = frame.Index, seconds = frame.Seconds }),
result = SopAgentJson.Serialize(new { frames = frames.Select(frame => new { frame_index = frame.Index, seconds = frame.Seconds }),
remaining_frames = FrameBudget() });
}
else if (name == "check_draft_reference" && request.CheckReference is { } check)
@ -425,16 +425,23 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
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),
result = SopAgentJson.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 是前序/起始画面对照,若也通过说明可能未区分相邻步骤,不能只追求正例分数。仅静态检查不等于实际手部触发或流程通过,仍需回放。" });
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;
if (reference.Frames is { Count: >= 3 } process)
foreach (var frame in Sop.VisualEvidenceSampler.Select(process, 5))
{
imageParts.Add(new { type = "text", text = $"候选参考片段:步骤{reference.StepId} {reference.Kind},原始帧{frame.FrameId},{frame.SourceSeconds:F3}s;代表画面,完整帧号见 reference_checks。" });
imageParts.Add(new { type = "image_url", image_url = new { url = "data:image/jpeg;base64," + Convert.ToBase64String(frame.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()));
@ -442,8 +449,8 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
else 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 })));
{ result = SopAgentJson.Serialize(new { error = name == "check_draft_reference" ? error.Message : "参数无效或超出剩余读取预算。检查秒数、每次帧数和上下文预算" }); }
request.Trace?.Invoke(new("tool_result", turn + 1, SopAgentJson.Serialize(new { id, name, result })));
messages.Add(new { role = "tool", tool_call_id = id, content = result });
estimatedInput += result.Length * 2L;
}
@ -473,13 +480,13 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
while (index < history.Length)
{
batch.Add(history[index]);
var candidate = new { role = "user", content = JsonSerializer.Serialize(batch) };
var candidate = new { role = "user", content = SopAgentJson.Serialize(batch) };
if (SopAgentContext.Estimate([.. summaryMessages, candidate]) + outputTokens + 512 > connection.ContextLength)
{ batch.RemoveAt(batch.Count - 1); break; }
index++;
}
if (index == before) throw new InvalidDataException("历史对话单条消息超过摘要预算,请增大上下文长度");
summaryMessages.Add(new { role = "user", content = JsonSerializer.Serialize(batch) });
summaryMessages.Add(new { role = "user", content = SopAgentJson.Serialize(batch) });
request.Progress?.Report("正在压缩历史对话,保留工艺要求与未解决问题…");
if (request.PromptSent is not null || request.Trace is not null)
{

View File

@ -130,7 +130,7 @@ public sealed class SopVideoDraftClient(HttpClient http) : ISopVideoDraftClient
ValidateSettings(connection);
// 图像 token 由模型决定,此处仅使用保守估算控制输入预算。
var estimatedInput = 2048L + SopStepDesignPrompt.SingleFrameRules.Length * 2L
+ JsonSerializer.Serialize(request.ImageScopes).Length * 2L + request.Instructions.Length * 2L + request.Recipe.Length * 2L
+ SopAgentJson.Serialize(request.ImageScopes).Length * 2L + request.Instructions.Length * 2L + request.Recipe.Length * 2L
+ request.Regions.Sum(region => region.Length * 2L) + request.Video.Frames.Count * 1700L;
if (estimatedInput + connection.MaxTokens > connection.ContextLength)
throw new ArgumentException("抽帧数量超出估算上下文预算,请减少抽帧或增大上下文长度");
@ -138,7 +138,7 @@ public sealed class SopVideoDraftClient(HttpClient http) : ISopVideoDraftClient
if (string.IsNullOrWhiteSpace(connection.Model)) throw new ArgumentException("请设置模型名");
var content = new List<object>
{
new { type = "text", text = JsonSerializer.Serialize(new { recipe = request.Recipe, instructions = request.Instructions,
new { type = "text", text = SopAgentJson.Serialize(new { recipe = request.Recipe, instructions = request.Instructions,
duration_seconds = request.Video.DurationSeconds, original_width = request.Video.Width, original_height = request.Video.Height,
available_region_keys = request.Regions, region_definitions = request.RegionDefinitions,
inspection_image_policy = "新步骤固定裁剪主区域,hand_move 裁剪终点区域;D3-lite 每次只看当前裁剪图。",
@ -166,7 +166,7 @@ public sealed class SopVideoDraftClient(HttpClient http) : ISopVideoDraftClient
各步时间段按发生顺序且不重叠,必须处于视频时长内;evidence_frame 是对应结果画面的 frame_index。
不因抽样图里没有看到某物就断言不存在。看不清时写入 warnings/note,不能自信猜测。
只输出 JSON,不输出 Markdown:
{"summary":"流程简述","warnings":[],"steps":[{"name":"操作名称","description":"对应模式能验证的完成要求","start_seconds":0,"end_seconds":2,"method":"hand_leave_region","region":"<实际已标定区域键>","from_region":"","to_region":"","hand":"any","evidence_frame":1,"inspection":{"evidence_mode":"single_frame","check_window_ms":10000,"max_checks":3},"note":"模式及触发的依据"}]}
{"summary":"流程简述","warnings":[],"steps":[{"name":"操作名称","description":"对应模式能验证的完成要求","start_seconds":0,"end_seconds":2,"method":"hand_leave_region","region":"<实际已标定区域键>","from_region":"","to_region":"","hand":"any","evidence_frame":1,"image_mode":"fixed_region","image_region":"<实际已标定送检区域键>","inspection":{"evidence_mode":"single_frame","check_window_ms":10000,"max_checks":3},"note":"模式及触发的依据"}]}
region 的示例占位符必须替换为实际区域键;无法确定时不输出空区域草稿。
""" },
new { role = "user", content }
@ -217,6 +217,8 @@ public sealed class SopVideoDraftClient(HttpClient http) : ISopVideoDraftClient
|| step.ImageMode is not (null or "" or VisionImageMode.FullFrame or VisionImageMode.FixedRegion or VisionImageMode.Hand))
throw new FormatException("步骤防抖、位置容差或送检模式无效");
ValidateInspection(step.Inspection);
if (step.Inspection?.EvidenceMode == VisionEvidenceMode.Sequence && string.IsNullOrWhiteSpace(step.ImageMode))
throw new FormatException("时序步骤须显式指定 image_mode 及必要的 image_region,按关键过程和结果选择完整送检范围,不能盲用手部触发区裁剪");
step.Region = KnownRegion(step.Region); step.FromRegion = KnownRegion(step.FromRegion); step.ToRegion = KnownRegion(step.ToRegion);
if (step.ImageRegion is not null) step.ImageRegion = KnownRegion(step.ImageRegion);
var number = draft.Steps.IndexOf(step) + 1;

View File

@ -69,6 +69,8 @@ try
&&body.RootElement.GetProperty("temperature").GetDouble()==.4&&body.RootElement.GetProperty("top_p").GetDouble()==.8,
"应发送配置的输出长度、温度和Top P");
var parts=body.RootElement.GetProperty("messages")[1].GetProperty("content");
Check(parts[0].GetProperty("text").GetString()!.Contains("装盒")
&& !parts[0].GetProperty("text").GetString()!.Contains("\\u88C5"), "嵌入提示词的中文JSON须保持可读,避免六字符转义放大上下文");
Check(parts.EnumerateArray().Count(p=>p.GetProperty("type").GetString()=="image_url")==3,"必须上传抽样图片");
Check(parts[1].GetProperty("text").GetString()!.Contains("time=0.000s"),"必须发送时间戳");
}

View File

@ -10,11 +10,19 @@ 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, int referenceStep = 0, bool replayOnly = false)
string? sourceReportPath = null, bool verifyCurrentFirst = false, bool disableThinking = false, string? draftPath = null, int referenceStep = 0, bool replayOnly = false,
string? instructions = null)
{
Directory.CreateDirectory(reportPath);
using var settings = JsonDocument.Parse(File.ReadAllText(settingsPath));
var root = settings.RootElement;
// 测试进程已隔离 workspace;让回放和参考检查使用同一显式配置的多图服务,不修改用户设置。
var localSettings = JsonNode.Parse(root.GetRawText())!.AsObject();
localSettings["useForSequence"] = true;
if (disableThinking) localSettings["sequenceEnableThinking"] = false;
var isolatedSettings = Path.Combine(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT") ?? throw new InvalidOperationException("实测必须使用隔离工作区"), "workspace", "sop-agent.json");
Directory.CreateDirectory(Path.GetDirectoryName(isolatedSettings)!);
File.WriteAllText(isolatedSettings, localSettings.ToJsonString());
string Text(string key) => root.TryGetProperty(key, out var v) ? v.GetString() ?? "" : "";
int Number(string key, int fallback) => root.TryGetProperty(key, out var v) ? v.GetInt32() : fallback;
double Decimal(string key, double fallback) => root.TryGetProperty(key, out var v) ? v.GetDouble() : fallback;
@ -58,9 +66,10 @@ internal static class AgentBenchmarkChecks
try
{
var client = new SopVideoAgentClient(http);
var request = new SopVideoAnalysisRequest(template.Sop.Name, "按标准视频中的实际工艺生成完整有序步骤。", video,
var request = new SopVideoAnalysisRequest(template.Sop.Name, instructions ?? "按标准视频中的实际工艺生成完整有序步骤。", video,
template.Sop.Regions.Keys.ToArray(), Number("maxFrames", 3), progress,
RegionDefinitions: template.Sop.Regions, PromptSent: promptLog);
RegionDefinitions: template.Sop.Regions, PromptSent: promptLog,
SequenceAvailable: new DesktopSequenceVisionClient(http).SupportsSequences);
SopVideoDraft draft;
if (sourceReportPath is null)
{
@ -102,11 +111,15 @@ internal static class AgentBenchmarkChecks
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);
Save($"round-{index}-config.json", SopDraftConfigBuilder.Build(template, current));
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);
foreach (var frame in reference.Frames ?? []) File.WriteAllBytes(Path.Combine(reportPath, $"round-{index}-reference-step-{reference.StepId}-{reference.Kind}-frame-{frame.FrameId}.jpg"), frame.Jpeg);
}
Log($"回放 {index} 耗时 {watch.Elapsed.TotalSeconds:F2}s,通过={report.Passed};{report.Summary}");
return report;
}

View File

@ -39,7 +39,7 @@ internal static class LiveVideoFlowChecks
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"),
int.Parse(Value("--reference-step") ?? "0"), args.Contains("--replay-only"))));
int.Parse(Value("--reference-step") ?? "0"), args.Contains("--replay-only"), Value("--instructions"))));
return;
}
if (args.Contains("--agent-generate"))

View File

@ -30,6 +30,17 @@ internal static class ReferenceEvidenceChecks
config.Sop.Steps[0].AiConfirmation!.EvidenceMode = VisionEvidenceMode.Sequence;
checks = new SopDraftReferenceVerifier(probe).CheckAsync(config, draft, video, 1, default).GetAwaiter().GetResult();
Check(checks[0].Accepted is null && checks[0].Reason.Contains("过程时序"), "时序操作不得用单帧参考结果代判");
config.Sop.Steps[0].AiConfirmation!.ImageMode = "fixed_region";
var temporal = new TemporalProbeClient();
checks = new SopDraftReferenceVerifier(temporal).CheckAsync(config, draft, video, 1, default).GetAwaiter().GetResult();
Check(checks[0].Accepted == true && checks[0].Frames is { Count: >= 3 } frames
&& frames.Select(f => f.FrameId).Distinct().Count() == frames.Count
&& frames.Zip(frames.Skip(1)).All(p => p.First.SourceSeconds < p.Second.SourceSeconds),
"时序参考须发送真实不同且按序的过程帧,仍按原阈值验收");
Check(checks[1].Accepted is null && checks[1].Reason.Contains("不足三张"), "零时刻的前序片段不能复制图片冒充过程反例");
temporal.Fabricate = true;
checks = new SopDraftReferenceVerifier(temporal).CheckAsync(config, draft, video, 1, default).GetAwaiter().GetResult();
Check(checks[0].Accepted == false, "参考片段伪造完成帧号也必须拒绝");
using var cancellation = new CancellationTokenSource(); cancellation.Cancel();
var cancelled = false;
try { new SopDraftReferenceVerifier(probe).CheckAsync(config, draft, video, 2, cancellation.Token).GetAwaiter().GetResult(); }
@ -49,4 +60,21 @@ internal static class ReferenceEvidenceChecks
return Task.FromResult(new VisionDecisionResult(true, .9, "参考判据结果"));
}
}
private sealed class TemporalProbeClient : IVisionDecisionClient
{
public bool SupportsSequences => true;
public bool Fabricate;
public Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request, CancellationToken token)
{
if (request.EvidenceMode != "sequence") return Task.FromResult(new VisionDecisionResult(false, .1, "对照"));
foreach (var frame in request.Frames!)
{
using var image = Cv2.ImDecode(frame.Jpeg, ImreadModes.Color);
Check(image.Width == 32 && image.Height == 48, "时序参考必须逐帧使用实际送检裁剪");
}
var ids = request.Frames!.Select(f => f.FrameId).ToArray();
return Task.FromResult(new VisionDecisionResult(true, .99, "真实片段", VisionDecisionStatus.Completed,
Fabricate ? [long.MaxValue, ids[0]] : ids, Fabricate ? long.MaxValue : ids[^1]));
}
}
}