From d09665c6dce82a5d4cd6187a260db161a69705c2 Mon Sep 17 00:00:00 2001
From: tfarcraw <123211521@163.com>
Date: Thu, 19 Nov 2026 09:20:16 +0800
Subject: [PATCH] =?UTF-8?q?=E6=8C=89=E5=88=A4=E5=AE=9A=E6=A8=A1=E5=BC=8F?=
=?UTF-8?q?=E5=A4=8D=E6=A0=B8=E7=9C=9F=E5=AE=9E=E5=8F=82=E8=80=83=E7=89=87?=
=?UTF-8?q?=E6=AE=B5=E5=B9=B6=E5=8E=8B=E7=BC=A9=E5=9B=9E=E6=B5=8B=E4=B8=AD?=
=?UTF-8?q?=E6=96=87=E4=B8=8A=E4=B8=8B=E6=96=87?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../Training/SopDraftReferenceVerifier.cs | 51 ++++++++++++++----
.../Training/SopDraftVideoVerifier.cs | 4 +-
.../SopAgent/SopAgentJson.cs | 5 ++
.../SopAgent/SopDraftVerification.cs | 6 ++-
.../SopAgent/SopStepDesignPrompt.cs | 4 +-
.../SopAgent/SopVerificationContext.cs | 9 +++-
.../SopAgent/SopVideoAgentClient.cs | 53 +++++++++++--------
.../SopAgent/SopVideoDraftClient.cs | 8 +--
tests/SopVideoAgent.Smoke/Program.cs | 2 +
.../AgentBenchmarkChecks.cs | 19 +++++--
.../LiveVideoFlowChecks.cs | 2 +-
.../ReferenceEvidenceChecks.cs | 28 ++++++++++
12 files changed, 145 insertions(+), 46 deletions(-)
diff --git a/src/SopHelper.Avalonia/Training/SopDraftReferenceVerifier.cs b/src/SopHelper.Avalonia/Training/SopDraftReferenceVerifier.cs
index 6c8992a..925f9d5 100644
--- a/src/SopHelper.Avalonia/Training/SopDraftReferenceVerifier.cs
+++ b/src/SopHelper.Avalonia/Training/SopDraftReferenceVerifier.cs
@@ -5,7 +5,7 @@ using SopHelper.Engine.SopAgent;
namespace SopHelper.Training;
-/// 对草稿引用的完成证据做同服务、同裁剪的静态检查;不替代运行时手部触发及整轮回放。
+/// 按草稿模式用同服务、同裁剪检查完成/前序参考;不替代手部触发及整轮回放。
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();
- 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();
+ 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;
diff --git a/src/SopHelper.Avalonia/Training/SopDraftVideoVerifier.cs b/src/SopHelper.Avalonia/Training/SopDraftVideoVerifier.cs
index d49ee81..f61d6cd 100644
--- a/src/SopHelper.Avalonia/Training/SopDraftVideoVerifier.cs
+++ b/src/SopHelper.Avalonia/Training/SopDraftVideoVerifier.cs
@@ -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)
diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopAgentJson.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopAgentJson.cs
index 2cbfbd2..5b629b1 100644
--- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopAgentJson.cs
+++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopAgentJson.cs
@@ -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 value) => JsonSerializer.Serialize(value, Options);
+
// 部分服务会在最终 JSON 前输出说明。仅接受唯一明确且位于末尾的完整对象,不猜测多个候选或修补残缺 JSON。
public static string Payload(string text)
{
diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopDraftVerification.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopDraftVerification.cs
index e711f71..5d8a608 100644
--- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopDraftVerification.cs
+++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopDraftVerification.cs
@@ -11,9 +11,13 @@ public sealed record SopDraftVerificationImage(int StepId, long FrameId, double
string EvidenceMode = VisionEvidenceMode.SingleFrame,
[property: JsonIgnore] IReadOnlyList? 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? Frames = null,
+ bool InfrastructureFailure = false)
{
[JsonIgnore] public bool Contradicts => Kind == "completion" && Accepted == false || Kind == "previous_state" && Accepted == true;
+ public IReadOnlyList? FrameIds => Frames?.Select(f => f.FrameId).ToArray();
+ public double? StartSeconds => Frames?.FirstOrDefault()?.SourceSeconds;
}
public sealed record SopDraftVerification(bool Passed, string Summary, IReadOnlyList Steps,
[property: JsonIgnore] IReadOnlyList Images, string Fingerprint = "", bool InfrastructureFailure = false,
diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopStepDesignPrompt.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopStepDesignPrompt.cs
index 97c8ef2..1cfccfa 100644
--- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopStepDesignPrompt.cs
+++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopStepDesignPrompt.cs
@@ -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像素后仍须可辨;不能判断区外状态。扩大范围或整帧不保证更准,必须验证。
回测修订:
- 先核对实际送检帧采集时间、范围和内容,再用同服务同裁剪的完成参考及前序未完成对照定位。正例通过而运行失败:检查触发、错过瞬态和选帧;清晰正例也失败:检查判据、范围或服务能力;前序也通过:判据过宽,不得放行。时序参考必须用真实片段,不能用单帧代判。
diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVerificationContext.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVerificationContext.cs
index 66105a4..04e9f4b 100644
--- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVerificationContext.cs
+++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVerificationContext.cs
@@ -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 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 是新增帧预算,已有帧可按目录时间再次请求并复用原编号。"
diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs
index bea0b4a..4b444aa 100644
--- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs
+++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs
@@ -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)
{
diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs
index a7a30c2..6a7d6da 100644
--- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs
+++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs
@@ -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