aisop/tests/VideoFlowTest.Smoke/AgentBenchmarkChecks.cs

163 lines
12 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.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;
/// <summary>真实服务测速:与界面相同,先生成,再基于当前草稿回测修订。</summary>
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)
{
Directory.CreateDirectory(reportPath);
using var settings = JsonDocument.Parse(File.ReadAllText(settingsPath));
var root = settings.RootElement;
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<object>();
var playback = new List<object>();
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<string>(Log);
var promptLog = new ImmediateProgress<SopAgentPrompt>(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, "按标准视频中的实际工艺生成完整有序步骤。", video,
template.Sop.Regions.Keys.ToArray(), Number("maxFrames", 3), progress,
RegionDefinitions: template.Sop.Regions, PromptSent: promptLog);
SopVideoDraft draft;
if (sourceReportPath is null)
{
draft = await client.AnalyzeAsync(request, connection, cancellation.Token);
generationSeconds = timer.Elapsed.TotalSeconds;
}
else
{
draft = JsonSerializer.Deserialize<SopVideoDraft>(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;
var round = 0;
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) =>
{
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;
}
}, 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,
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<T>(Action<T> report) : IProgress<T>
{ public void Report(T value) => report(value); }
private sealed class MetricsHttp(string reportPath, bool disableThinking) : DelegatingHandler(new HttpClientHandler())
{
public string Stage = "generate";
public List<object> Requests { get; } = [];
protected override async Task<HttpResponseMessage> 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;
}
}
}