using System.Diagnostics;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Nodes;
using SopHelper.Engine.Sop;
using SopHelper.Engine.SopAgent;
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? 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;
var connection = new SopAgentConnection(Text("endpoint"), Text("model"), Text("apiKey"),
Number("contextLength", 131702), Number("maxTokens", 8192), Decimal("temperature", .2), Decimal("topP", .9), Number("timeoutSeconds", 300));
var template = SopConfigLoader.Load(configPath);
// 与界面未应用草稿的 CreateAgentVerificationTemplate 一致,不能继承不相关旧步骤的送检区。
template.Sop.Steps = [];
var original = File.ReadAllBytes(configPath);
var video = SopVideoSampler.ReadInfo(videoPath, default);
if (template.Sop.Regions.Values.Any(r => r.X1 < 0 || r.Y1 < 0 || r.X2 > video.Width || r.Y2 > video.Height))
throw new ArgumentException("测速配方区域超出当前视频尺寸,请选择匹配的现用配方");
using var handler = new MetricsHttp(reportPath, disableThinking);
using var http = new HttpClient(handler) { Timeout = Timeout.InfiniteTimeSpan };
using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(15));
var timer = Stopwatch.StartNew();
var stage = "generate";
var prompts = new List();
var playback = new List();
void Log(string message)
{
var line = $"{timer.Elapsed.TotalSeconds:F2}s [{stage}] {message}";
Console.WriteLine(line);
File.AppendAllText(Path.Combine(reportPath, "timeline.log"), line + Environment.NewLine);
}
var progress = new ImmediateProgress(Log);
var promptLog = new ImmediateProgress(p =>
{
using var document = JsonDocument.Parse(p.Text);
var messages = document.RootElement.GetProperty("messages");
var images = messages.EnumerateArray().Where(m => m.GetProperty("content").ValueKind == JsonValueKind.Array)
.SelectMany(m => m.GetProperty("content").EnumerateArray()).Count(p => p.GetProperty("type").GetString() == "image_url");
prompts.Add(new { Stage = stage, p.Round, p.EstimatedTokens, Images = images, Messages = messages.GetArrayLength(), Seconds = timer.Elapsed.TotalSeconds });
Save("prompt-metrics.json", prompts);
File.WriteAllText(Path.Combine(reportPath, $"{stage}-prompt-{p.Round}.json"), p.Text);
Log($"请求 {p.Round}:估算输入 {p.EstimatedTokens},{images} 张图,{messages.GetArrayLength()} 条消息");
});
string? error = null;
SopVideoDraft? final = null;
var generationSeconds = 0d;
try
{
var client = new SopVideoAgentClient(http);
var request = new SopVideoAnalysisRequest(template.Sop.Name, instructions ?? "按标准视频中的实际工艺生成完整有序步骤。", video,
template.Sop.Regions.Keys.ToArray(), Number("maxFrames", 3), progress,
RegionDefinitions: template.Sop.Regions, PromptSent: promptLog,
SequenceAvailable: new DesktopSequenceVisionClient(http).SupportsSequences);
SopVideoDraft draft;
if (sourceReportPath is null)
{
draft = await client.AnalyzeAsync(request, connection, cancellation.Token);
generationSeconds = timer.Elapsed.TotalSeconds;
}
else
{
draft = JsonSerializer.Deserialize(File.ReadAllText(draftPath ?? Path.Combine(sourceReportPath, "generated-draft.json")))!;
using var catalog = JsonDocument.Parse(File.ReadAllText(Path.Combine(sourceReportPath, "observed-frames.json")));
draft.ObservedFrames = catalog.RootElement.EnumerateArray().Select(f => new SopVideoFrame(f.GetProperty("Index").GetInt32(),
f.GetProperty("Seconds").GetDouble(), File.ReadAllBytes(Path.Combine(sourceReportPath, $"observed-{f.GetProperty("Index").GetInt32()}.jpg")))).ToArray();
SopVideoDraftClient.Validate(draft, video with { Frames = draft.ObservedFrames }, template.Sop.Regions.Keys.ToArray(), template.Sop.Regions);
Log("复用同一份生成草稿及原始观察帧,排除重复生成的耗时和差异");
}
Save("generated-draft.json", draft);
Save("observed-frames.json", draft.ObservedFrames.Select(f => new { f.Index, f.Seconds }));
foreach (var frame in draft.ObservedFrames) File.WriteAllBytes(Path.Combine(reportPath, $"observed-{frame.Index}.jpg"), frame.Jpeg);
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 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);
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;
}
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 = "请基于当前草稿保留工艺要求,用标准视频回测,并仅按实际失败证据修订,返回完整草稿;不要重新从头生成,不要只回复讨论文字。",
CheckReference = async (candidate, observed, id, token) =>
{
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);
if (final?.Verification?.Passed != true) throw new InvalidOperationException("回测未通过:" + final?.Verification?.Summary);
}
catch (Exception failure) { error = failure.Message; Log("失败:" + error); throw; }
finally
{
var unchanged = original.SequenceEqual(File.ReadAllBytes(configPath));
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, 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("测速修改了原配方");
}
void Save(string name, object? value) => File.WriteAllText(Path.Combine(reportPath, name),
JsonSerializer.Serialize(value, new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }));
}
private sealed class ImmediateProgress(Action report) : IProgress
{ public void Report(T value) => report(value); }
private sealed class MetricsHttp(string reportPath, bool disableThinking) : DelegatingHandler(new HttpClientHandler())
{
public string Stage = "generate";
public List Requests { get; } = [];
protected override async Task SendAsync(HttpRequestMessage request, CancellationToken token)
{
var watch = Stopwatch.StartNew();
// 仅用于已确认支持 enable_thinking 的服务对照实验,不改变产品默认请求。
if (disableThinking)
{
var payload = JsonNode.Parse(await request.Content!.ReadAsStringAsync(token))!.AsObject();
payload["chat_template_kwargs"] = new JsonObject { ["enable_thinking"] = false };
request.Content = new StringContent(payload.ToJsonString(), System.Text.Encoding.UTF8, "application/json");
}
var body = await request.Content!.ReadAsByteArrayAsync(token);
var response = await base.SendAsync(request, token);
var text = await response.Content.ReadAsStringAsync(token);
File.WriteAllText(Path.Combine(reportPath, $"{Stage}-response-{Requests.Count + 1}.json"), text);
using var document = JsonDocument.Parse(text);
var usage = document.RootElement.TryGetProperty("usage", out var value) ? value.Clone() : (JsonElement?)null;
var reasoningChars = document.RootElement.TryGetProperty("choices", out var choices) && choices.GetArrayLength() > 0
&& choices[0].GetProperty("message").TryGetProperty("reasoning_content", out var reasoning) ? reasoning.ToString().Length : 0;
Requests.Add(new { Stage, Seconds = watch.Elapsed.TotalSeconds, Bytes = body.Length, Status = (int)response.StatusCode, Usage = usage, ReasoningChars = reasoningChars });
File.WriteAllText(Path.Combine(reportPath, "request-metrics.json"), JsonSerializer.Serialize(Requests, new JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine($"模型响应:{watch.Elapsed.TotalSeconds:F2}s,HTTP {(int)response.StatusCode},请求 {body.Length:N0} bytes;用量 {usage}");
return response;
}
}
}