自动保存Agent分析全过程日志并显示具体失败原因
每次分析创建独立JSONL日志,实时记录模型请求与原始响应、工具调用、视频时间点、上下文压缩、回测结果及异常;实际读取和送检截图独立落盘。聊天显示日志位置,鉴权密钥与内联图片数据脱敏。取消和失败保留完整已写日志,额外错误快照关联会话日志。 修复tool_calls为空时的响应兼容问题,检查空choices及服务返回错误,避免吞掉具体解析异常。 验证:SopVideoAgent.Smoke、VideoFlowTest.Smoke通过,涵盖日志实时写入、图片证据、脱敏、异常与取消。真实接口独立分析完成三轮回测,未复现通用异常,草稿实际停在第二步;报告见scratch/agent-failure-live。额外Avalonia.Smoke的旧侧栏数量断言在进入Agent检查前失败,本次未涉及侧栏。
This commit is contained in:
parent
2553adf03f
commit
df044f6c59
45
src/SopHelper.Avalonia/VVMs/RecipeEditor/SopAgentErrors.cs
Normal file
45
src/SopHelper.Avalonia/VVMs/RecipeEditor/SopAgentErrors.cs
Normal file
@ -0,0 +1,45 @@
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using SopHelper.Engine.SopAgent;
|
||||
using SopHelper.Presentation;
|
||||
|
||||
namespace SopHelper.VVMs.RecipeEditor;
|
||||
|
||||
public partial class RecipeEditorViewModel
|
||||
{
|
||||
private void ReportAgentFailure(Exception error, SopAgentConnection connection, SopAgentRunLog? runLog)
|
||||
{
|
||||
var stage = AgentStatus;
|
||||
var reason = error switch
|
||||
{
|
||||
HttpRequestException => "模型接口连接失败:" + error.Message,
|
||||
JsonException => "模型接口返回的 JSON 无法解析:" + error.Message,
|
||||
KeyNotFoundException or InvalidOperationException or IndexOutOfRangeException
|
||||
=> "处理模型响应或草稿时发生异常:" + error.Message,
|
||||
InvalidDataException => error.Message,
|
||||
IOException => "读取视频或本地文件失败:" + error.Message,
|
||||
_ => error.Message
|
||||
};
|
||||
if (error.GetBaseException() is { } cause && !ReferenceEquals(cause, error)) reason += ";根因:" + cause.Message;
|
||||
AgentStatus = "分析失败:" + SopAgentRunLog.Redact(reason, connection.ApiKey, 1600) + ";当前配方未修改。";
|
||||
AgentChatMessages.Add(new("系统", AgentStatus));
|
||||
try
|
||||
{
|
||||
runLog?.Write(new("exception", 0, $"阶段:{stage}\n{error}"));
|
||||
var folder = Path.Combine(DesktopPlatform.WorkspaceRoot, "workspace", "agent-diagnostics");
|
||||
Directory.CreateDirectory(folder);
|
||||
var path = Path.Combine(folder, "error-" + DateTime.Now.ToString("yyyyMMdd-HHmmss-fff") + "-" + Guid.NewGuid().ToString("N")[..8] + ".json");
|
||||
File.WriteAllText(path, JsonSerializer.Serialize(new
|
||||
{
|
||||
Time = DateTimeOffset.Now, Stage = stage, Model = connection.Model, SessionLog = runLog?.Path,
|
||||
connection.ContextLength, connection.MaxTokens, Video = AgentVideoPath,
|
||||
Error = SopAgentRunLog.Redact(error.ToString(), connection.ApiKey, 16000)
|
||||
}, new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }));
|
||||
AgentChatMessages.Add(new("错误详情", $"失败阶段:{stage}\n异常类型:{error.GetType().Name}\n诊断记录:{path}"));
|
||||
}
|
||||
catch (Exception logError) when (logError is IOException or UnauthorizedAccessException)
|
||||
{ AgentChatMessages.Add(new("错误详情", "诊断文件无法写入,具体原因已显示在上一条消息中。")); }
|
||||
}
|
||||
|
||||
}
|
||||
66
src/SopHelper.Avalonia/VVMs/RecipeEditor/SopAgentRunLog.cs
Normal file
66
src/SopHelper.Avalonia/VVMs/RecipeEditor/SopAgentRunLog.cs
Normal file
@ -0,0 +1,66 @@
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using SopHelper.Engine.SopAgent;
|
||||
|
||||
namespace SopHelper.VVMs.RecipeEditor;
|
||||
|
||||
/// <summary>按事件立即落盘,异常、取消和关闭程序后仍可诊断。图片单独保存,不把 Base64 写入日志。</summary>
|
||||
internal sealed class SopAgentRunLog : IDisposable
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly StreamWriter _writer;
|
||||
private readonly string _apiKey;
|
||||
private bool _disposed;
|
||||
private int _imageIndex;
|
||||
public string Path { get; }
|
||||
|
||||
public SopAgentRunLog(string workspace, string apiKey)
|
||||
{
|
||||
_apiKey = apiKey;
|
||||
var folder = System.IO.Path.Combine(workspace, "workspace", "agent-logs");
|
||||
Directory.CreateDirectory(folder);
|
||||
Path = System.IO.Path.Combine(folder, "analysis-" + DateTime.Now.ToString("yyyyMMdd-HHmmss-fff") + "-" + Guid.NewGuid().ToString("N")[..8] + ".jsonl");
|
||||
_writer = new StreamWriter(new FileStream(Path, FileMode.CreateNew, FileAccess.Write, FileShare.Read)) { AutoFlush = true };
|
||||
}
|
||||
|
||||
public void Write(SopAgentTrace trace)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
var images = new List<object>();
|
||||
foreach (var image in trace.Images ?? [])
|
||||
{
|
||||
var folder = System.IO.Path.ChangeExtension(Path, null) + "-images";
|
||||
Directory.CreateDirectory(folder);
|
||||
var path = System.IO.Path.Combine(folder, $"{++_imageIndex:D3}.jpg");
|
||||
File.WriteAllBytes(path, image.Jpeg);
|
||||
images.Add(new { Caption = Redact(image.Name, _apiKey), Path = path });
|
||||
}
|
||||
_writer.WriteLine(JsonSerializer.Serialize(new
|
||||
{
|
||||
Time = DateTimeOffset.Now, trace.Kind, trace.Round,
|
||||
Text = Redact(trace.Text, _apiKey), Images = images
|
||||
}, new JsonSerializerOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }));
|
||||
}
|
||||
}
|
||||
|
||||
internal static string Redact(string text, string apiKey, int maxLength = 512000)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(apiKey)) text = text.Replace(apiKey, "[密钥已隐藏]", StringComparison.Ordinal);
|
||||
text = Regex.Replace(text, @"(?i)bearer\s+[^\s""'<>]+", "Bearer [密钥已隐藏]");
|
||||
text = Regex.Replace(text, @"(?i)data:image/[^;\s]+;base64,[a-z0-9+/=]+", "[图片数据已隐藏]");
|
||||
return text.Length <= maxLength ? text : text[..maxLength] + "…(已截断)";
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_writer.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -232,6 +232,7 @@ public partial class RecipeEditorViewModel
|
||||
IsAgentBusy = true;
|
||||
AgentStatus = "正在读取标准 SOP 视频…";
|
||||
var activeAnalysis = _agentCancellation;
|
||||
SopAgentRunLog? runLog = null;
|
||||
var promptSession = _agentPromptSession = new object();
|
||||
var promptLog = new Progress<SopAgentPrompt>(prompt =>
|
||||
{
|
||||
@ -243,10 +244,26 @@ public partial class RecipeEditorViewModel
|
||||
var progress = new Progress<string>(value => { if (IsAgentBusy && ReferenceEquals(_agentCancellation, activeAnalysis)) AgentStatus = value; });
|
||||
var verificationTemplate = CreateAgentVerificationTemplate();
|
||||
Func<SopVideoDraft, SopVideoSample, CancellationToken, Task<SopDraftVerification>>? verify = AgentAutoVerify
|
||||
? (draft, video, cancellation) => VerifyAgentDraftAsync(draft, video, verificationTemplate, progress, cancellation) : null;
|
||||
? async (draft, video, cancellation) =>
|
||||
{
|
||||
runLog?.Write(new("verification_start", 0, JsonSerializer.Serialize(draft)));
|
||||
var result = await VerifyAgentDraftAsync(draft, video, verificationTemplate, progress, cancellation);
|
||||
runLog?.Write(new("verification_end", 0, JsonSerializer.Serialize(result)));
|
||||
return result;
|
||||
} : null;
|
||||
try
|
||||
{
|
||||
runLog = new SopAgentRunLog(DesktopPlatform.WorkspaceRoot, connection.ApiKey);
|
||||
runLog.Write(new("session_start", 0, JsonSerializer.Serialize(new
|
||||
{
|
||||
Recipe = recipeName, Video = path, Mode = userMessage is null ? "generate" : "chat",
|
||||
instructions, userMessage, Endpoint = new UriBuilder(endpoint) { UserName = "", Password = "", Query = "", Fragment = "" }.Uri.ToString(),
|
||||
connection.Model, connection.ContextLength, connection.MaxTokens,
|
||||
connection.Temperature, connection.TopP, connection.TimeoutSeconds, MaxFrames = maxFrames, AutoVerify = AgentAutoVerify
|
||||
})));
|
||||
AgentChatMessages.Add(new("分析日志", "本次分析过程自动保存:" + runLog.Path));
|
||||
var sample = await Task.Run(() => SopVideoSampler.ReadInfo(path, token), token);
|
||||
runLog.Write(new("video_info", 0, JsonSerializer.Serialize(sample)));
|
||||
SopVideoDraft? draft;
|
||||
string reply;
|
||||
if (userMessage is not null)
|
||||
@ -258,7 +275,7 @@ public partial class RecipeEditorViewModel
|
||||
AgentChatMessages.Add(new("我", userMessage));
|
||||
var result = await AgentClient.ChatAsync(new(recipeName, instructions, sample, regions, maxFrames, progress,
|
||||
userMessage, _agentConversation.ToArray(), CreateAgentDraftSnapshot(), regionDefinitions,
|
||||
CreateAgentImageScopes(), VerifyDraft: verify, PromptSent: promptLog), connection, token).WaitAsync(token);
|
||||
CreateAgentImageScopes(), VerifyDraft: verify, PromptSent: promptLog, Trace: runLog.Write), connection, token).WaitAsync(token);
|
||||
token.ThrowIfCancellationRequested();
|
||||
draft = result.Draft; reply = result.Reply;
|
||||
sample = sample with { Frames = result.ObservedFrames };
|
||||
@ -269,7 +286,7 @@ public partial class RecipeEditorViewModel
|
||||
else
|
||||
{
|
||||
draft = await AgentClient.AnalyzeAsync(new(recipeName, instructions, sample, regions, maxFrames, progress,
|
||||
RegionDefinitions: regionDefinitions, VerifyDraft: verify, PromptSent: promptLog), connection, token).WaitAsync(token);
|
||||
RegionDefinitions: regionDefinitions, VerifyDraft: verify, PromptSent: promptLog, Trace: runLog.Write), connection, token).WaitAsync(token);
|
||||
sample = sample with { Frames = draft.ObservedFrames };
|
||||
reply = string.IsNullOrWhiteSpace(draft.Summary) ? $"已生成 {draft.Steps.Count} 步。" : draft.Summary;
|
||||
}
|
||||
@ -299,19 +316,25 @@ public partial class RecipeEditorViewModel
|
||||
if (userMessage is null) { _agentConversation.Clear(); _agentConversation.Add(new("assistant", reply)); }
|
||||
AgentChatMessages.Add(new("Agent", reply));
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
catch (OperationCanceledException error)
|
||||
{
|
||||
await WaitForAgentVerificationCleanupAsync();
|
||||
AgentStatus = "分析已取消或超时,当前配方未修改。";
|
||||
AgentChatMessages.Add(new("系统", "已取消或超时。"));
|
||||
AgentStatus = token.IsCancellationRequested ? "分析已取消,当前配方未修改。" : "模型请求或本地回测超时,当前配方未修改。";
|
||||
AgentChatMessages.Add(new("系统", AgentStatus));
|
||||
try { runLog?.Write(new("cancelled_or_timeout", 0, error.ToString())); }
|
||||
catch (Exception logError) when (logError is IOException or UnauthorizedAccessException) { }
|
||||
}
|
||||
catch (Exception error) when (error is ArgumentException or InvalidDataException or FileNotFoundException or FormatException)
|
||||
{ AgentStatus = "分析未完成:" + error.Message; AgentChatMessages.Add(new("系统", AgentStatus)); }
|
||||
catch (Exception) { AgentStatus = "分析失败,请检查视频、接口、模型名和密钥;当前配方未修改。"; AgentChatMessages.Add(new("系统", AgentStatus)); }
|
||||
catch (Exception error) { ReportAgentFailure(error, connection, runLog); }
|
||||
finally
|
||||
{
|
||||
_agentCancellation.Dispose(); _agentCancellation = null;
|
||||
IsAgentBusy = false;
|
||||
try { runLog?.Write(new("session_end", 0, AgentStatus)); }
|
||||
catch (Exception logError) when (logError is IOException or UnauthorizedAccessException)
|
||||
{ AgentChatMessages.Add(new("错误详情", "分析日志写入失败:" + logError.Message)); }
|
||||
finally
|
||||
{
|
||||
try { runLog?.Dispose(); }
|
||||
finally { _agentCancellation.Dispose(); _agentCancellation = null; IsAgentBusy = false; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -112,11 +112,19 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
|
||||
compression += "\n历史对话已自动摘要,保留最近四条原文、当前完整草稿和最新用户消息。";
|
||||
}
|
||||
estimatedInput = SopAgentContext.Estimate(messages);
|
||||
if (!string.IsNullOrEmpty(compression)) request.Progress?.Report(compression);
|
||||
if (!string.IsNullOrEmpty(compression))
|
||||
{
|
||||
request.Progress?.Report(compression);
|
||||
request.Trace?.Invoke(new("context_compression", turn + 1, compression));
|
||||
}
|
||||
if (estimatedInput + connection.MaxTokens > connection.ContextLength)
|
||||
throw new InvalidDataException("已压缩历史图片和旧草稿,但系统规则、用户要求与当前草稿仍超出上下文预算;请增大上下文长度或减少预留输出长度");
|
||||
request.PromptSent?.Report(new(turn + 1, estimatedInput, connection.ContextLength, compression,
|
||||
SopAgentContext.Describe(messages, tools)));
|
||||
if (request.PromptSent is not null || request.Trace is not null)
|
||||
{
|
||||
var prompt = SopAgentContext.Describe(messages, tools);
|
||||
request.PromptSent?.Report(new(turn + 1, estimatedInput, connection.ContextLength, compression, prompt));
|
||||
request.Trace?.Invoke(new("model_request", turn + 1, prompt));
|
||||
}
|
||||
request.Progress?.Report($"Agent 分析中(第 {turn + 1} 轮)…");
|
||||
using var message = new HttpRequestMessage(HttpMethod.Post, endpoint);
|
||||
using var requestTimeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
@ -129,12 +137,14 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
|
||||
tool_choice = turn == 11 ? "none" : "auto"
|
||||
});
|
||||
using var response = await http.SendAsync(message, requestTimeout.Token).ConfigureAwait(false);
|
||||
var responseText = await response.Content.ReadAsStringAsync(requestTimeout.Token).ConfigureAwait(false);
|
||||
request.Trace?.Invoke(new("model_response", turn + 1, $"HTTP {(int)response.StatusCode}\n{responseText}"));
|
||||
if (!response.IsSuccessStatusCode) throw new InvalidDataException($"Agent 接口 HTTP {(int)response.StatusCode},请检查连接及模型的工具调用、图片输入支持");
|
||||
using var envelope = JsonDocument.Parse(await response.Content.ReadAsStringAsync(requestTimeout.Token).ConfigureAwait(false));
|
||||
var choice = envelope.RootElement.GetProperty("choices")[0];
|
||||
var finish = choice.GetProperty("finish_reason").GetString();
|
||||
var assistant = choice.GetProperty("message");
|
||||
if (finish == "stop" && (!assistant.TryGetProperty("tool_calls", out var finalCalls) || finalCalls.GetArrayLength() == 0))
|
||||
using var envelope = JsonDocument.Parse(responseText);
|
||||
var (finish, assistant) = ReadResponse(envelope.RootElement);
|
||||
var hasToolCalls = assistant.TryGetProperty("tool_calls", out var finalCalls) && finalCalls.ValueKind != JsonValueKind.Null;
|
||||
if (hasToolCalls && finalCalls.ValueKind != JsonValueKind.Array) throw new FormatException("Agent 接口返回的 tool_calls 不是数组");
|
||||
if (finish == "stop" && (!hasToolCalls || finalCalls.GetArrayLength() == 0))
|
||||
{
|
||||
try
|
||||
{
|
||||
@ -191,6 +201,11 @@ 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;
|
||||
request.Trace?.Invoke(new("verification_result", turn + 1, JsonSerializer.Serialize(new
|
||||
{
|
||||
report.Passed, report.Summary, report.Steps, report.InfrastructureFailure,
|
||||
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)
|
||||
{
|
||||
var feedback = JsonSerializer.Serialize(new
|
||||
@ -213,12 +228,14 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
|
||||
continue;
|
||||
}
|
||||
}
|
||||
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
|
||||
&& error is FormatException or JsonException or KeyNotFoundException)
|
||||
{
|
||||
validationRetries++;
|
||||
request.Trace?.Invoke(new("draft_validation_error", turn + 1, error.ToString()));
|
||||
var feedback = JsonSerializer.Serialize(new
|
||||
{
|
||||
validation_error = error is FormatException ? error.Message : "草稿 JSON 格式无效",
|
||||
@ -232,9 +249,9 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (finish != "tool_calls" || !assistant.TryGetProperty("tool_calls", out var calls)
|
||||
|| calls.GetArrayLength() is < 1 or > 8 || turn == 11)
|
||||
if (finish != "tool_calls" || !hasToolCalls || finalCalls.GetArrayLength() is < 1 or > 8 || turn == 11)
|
||||
throw new FormatException("Agent 响应不完整或不支持工具调用");
|
||||
var calls = finalCalls;
|
||||
var assistantText = assistant.TryGetProperty("content", out var body) ? body.Clone() : JsonSerializer.SerializeToElement((string?)null);
|
||||
messages.Add(new { role = "assistant", content = assistantText, tool_calls = calls.Clone() });
|
||||
estimatedInput += assistant.GetRawText().Length * 2L;
|
||||
@ -245,6 +262,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
|
||||
var id = call.GetProperty("id").GetString();
|
||||
var function = call.GetProperty("function");
|
||||
var name = function.GetProperty("name").GetString();
|
||||
request.Trace?.Invoke(new("tool_call", turn + 1, call.GetRawText()));
|
||||
string result;
|
||||
try
|
||||
{
|
||||
@ -267,6 +285,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
|
||||
{
|
||||
request.Progress?.Report(readCompression);
|
||||
pendingCompression += readCompression + "\n";
|
||||
request.Trace?.Invoke(new("context_compression", turn + 1, readCompression));
|
||||
}
|
||||
estimatedInput = SopAgentContext.Estimate(messages);
|
||||
if (times.Length == 0 || times.Length > request.MaxFramesPerRead || times.Length > FrameBudget())
|
||||
@ -280,6 +299,9 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
|
||||
observed.Add(frame); jpegBytes += frame.Jpeg.Length;
|
||||
AddImage(imageParts, frame);
|
||||
}
|
||||
request.Trace?.Invoke(new("video_frames", turn + 1,
|
||||
JsonSerializer.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 }),
|
||||
remaining_frames = FrameBudget() });
|
||||
@ -288,6 +310,7 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
|
||||
}
|
||||
catch (Exception error) when (error is ArgumentException or JsonException or InvalidOperationException or KeyNotFoundException)
|
||||
{ result = "{\"error\":\"参数无效或超出剩余读取预算。检查秒数、每次帧数和上下文预算\"}"; }
|
||||
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;
|
||||
}
|
||||
@ -325,8 +348,12 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
|
||||
if (index == before) throw new InvalidDataException("历史对话单条消息超过摘要预算,请增大上下文长度");
|
||||
summaryMessages.Add(new { role = "user", content = JsonSerializer.Serialize(batch) });
|
||||
request.Progress?.Report("正在压缩历史对话,保留工艺要求与未解决问题…");
|
||||
request.PromptSent?.Report(new(0, SopAgentContext.Estimate(summaryMessages), connection.ContextLength,
|
||||
"历史对话自动摘要请求", SopAgentContext.Describe(summaryMessages, Array.Empty<object>())));
|
||||
if (request.PromptSent is not null || request.Trace is not null)
|
||||
{
|
||||
var prompt = SopAgentContext.Describe(summaryMessages, Array.Empty<object>());
|
||||
request.PromptSent?.Report(new(0, SopAgentContext.Estimate(summaryMessages), connection.ContextLength, "历史对话自动摘要请求", prompt));
|
||||
request.Trace?.Invoke(new("summary_request", 0, prompt));
|
||||
}
|
||||
using var call = new HttpRequestMessage(HttpMethod.Post, SopAgentEndpoints.Chat(connection.Endpoint));
|
||||
if (!string.IsNullOrWhiteSpace(connection.ApiKey)) call.Headers.Authorization = new AuthenticationHeaderValue("Bearer", connection.ApiKey);
|
||||
call.Content = JsonContent.Create(new { model = connection.Model, stream = false, max_tokens = outputTokens,
|
||||
@ -334,12 +361,14 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(connection.TimeoutSeconds));
|
||||
using var response = await http.SendAsync(call, timeout.Token).ConfigureAwait(false);
|
||||
var responseText = await response.Content.ReadAsStringAsync(timeout.Token).ConfigureAwait(false);
|
||||
request.Trace?.Invoke(new("summary_response", 0, $"HTTP {(int)response.StatusCode}\n{responseText}"));
|
||||
if (!response.IsSuccessStatusCode) throw new InvalidDataException($"历史对话压缩失败:Agent 接口 HTTP {(int)response.StatusCode};原始聊天记录保留");
|
||||
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(timeout.Token).ConfigureAwait(false));
|
||||
var choice = document.RootElement.GetProperty("choices")[0];
|
||||
if (choice.GetProperty("finish_reason").GetString() != "stop")
|
||||
using var document = JsonDocument.Parse(responseText);
|
||||
var (finish, assistant) = ReadResponse(document.RootElement);
|
||||
if (finish != "stop")
|
||||
throw new InvalidDataException("历史对话摘要未完整返回,已停止本次请求;原始聊天记录保留");
|
||||
summary = choice.GetProperty("message").GetProperty("content").GetString() ?? "";
|
||||
summary = assistant.TryGetProperty("content", out var content) && content.ValueKind == JsonValueKind.String ? content.GetString()! : "";
|
||||
if (string.IsNullOrWhiteSpace(summary)) throw new InvalidDataException("历史对话摘要为空;原始聊天记录保留");
|
||||
}
|
||||
return summary;
|
||||
@ -350,4 +379,21 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient
|
||||
parts.Add(new { type = "text", text = $"frame_index={frame.Index}, time={frame.Seconds.ToString("F3", CultureInfo.InvariantCulture)}s" });
|
||||
parts.Add(new { type = "image_url", image_url = new { url = "data:image/jpeg;base64," + Convert.ToBase64String(frame.Jpeg) } });
|
||||
}
|
||||
|
||||
private static (string Finish, JsonElement Message) ReadResponse(JsonElement root)
|
||||
{
|
||||
if (root.ValueKind != JsonValueKind.Object) throw new InvalidDataException("Agent 接口响应根节点不是 JSON 对象,详见分析日志中的原始响应");
|
||||
if (root.TryGetProperty("error", out var error) && error.ValueKind != JsonValueKind.Null)
|
||||
{
|
||||
var detail = error.ValueKind == JsonValueKind.Object && error.TryGetProperty("message", out var message) ? message.ToString() : error.ToString();
|
||||
throw new InvalidDataException("Agent 接口返回错误:" + detail);
|
||||
}
|
||||
if (!root.TryGetProperty("choices", out var choices) || choices.ValueKind != JsonValueKind.Array || choices.GetArrayLength() == 0)
|
||||
throw new InvalidDataException("Agent 接口响应缺少有效的 choices,详见分析日志中的原始响应");
|
||||
var choice = choices[0];
|
||||
if (choice.ValueKind != JsonValueKind.Object || !choice.TryGetProperty("message", out var assistant) || assistant.ValueKind != JsonValueKind.Object
|
||||
|| !choice.TryGetProperty("finish_reason", out var finish) || finish.ValueKind != JsonValueKind.String)
|
||||
throw new InvalidDataException("Agent 接口响应缺少有效的 message 或 finish_reason,详见分析日志中的原始响应");
|
||||
return (finish.GetString()!, assistant);
|
||||
}
|
||||
}
|
||||
|
||||
@ -14,8 +14,10 @@ public sealed record SopVideoAnalysisRequest(string Recipe, string Instructions,
|
||||
string UserMessage = "", IReadOnlyList<SopAgentChatTurn>? Conversation = null, SopVideoDraft? CurrentDraft = null,
|
||||
IReadOnlyDictionary<string, RegionDef>? RegionDefinitions = null, IReadOnlyList<SopAgentImageScope>? ImageScopes = null,
|
||||
Func<SopVideoDraft, SopVideoSample, CancellationToken, Task<SopDraftVerification>>? VerifyDraft = null,
|
||||
IProgress<SopAgentPrompt>? PromptSent = null);
|
||||
IProgress<SopAgentPrompt>? PromptSent = null, Action<SopAgentTrace>? Trace = 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);
|
||||
public sealed record SopAgentImageScope(int StepIndex, string Mode, string Region, int HandPadding, int HandMinSize, int HandMemoryMs);
|
||||
public sealed record SopAgentChatTurn(string Role, string Text);
|
||||
public sealed record SopAgentChatResult(string Reply, SopVideoDraft? Draft, IReadOnlyList<SopVideoFrame> ObservedFrames);
|
||||
|
||||
@ -82,6 +82,7 @@ try
|
||||
var info=SopVideoSampler.ReadInfo(path,default);
|
||||
await VerificationLoopChecks.RunAsync(info);
|
||||
await ContextCompressionChecks.RunAsync(info);
|
||||
await ResponseDiagnosticsChecks.RunAsync(info);
|
||||
Check(info.Frames.Count==0&&info.Path==Path.GetFullPath(path),"Agent 应从视频路径和元数据开始,不预选图片");
|
||||
foreach(var mode in new[]{"repair","blocked","repeat","empty_blocked"})
|
||||
using(var repairHandler=new RepairAgentHttp{Mode=mode})
|
||||
|
||||
35
tests/SopVideoAgent.Smoke/ResponseDiagnosticsChecks.cs
Normal file
35
tests/SopVideoAgent.Smoke/ResponseDiagnosticsChecks.cs
Normal file
@ -0,0 +1,35 @@
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using SopHelper.Engine.SopAgent;
|
||||
|
||||
internal static class ResponseDiagnosticsChecks
|
||||
{
|
||||
public static async Task RunAsync(SopVideoSample video)
|
||||
{
|
||||
foreach (var body in new[]
|
||||
{
|
||||
"{\"choices\":[{\"finish_reason\":\"stop\",\"message\":{\"content\":\"{\\\"reply\\\":\\\"正常\\\",\\\"draft\\\":null}\",\"tool_calls\":null}}]}",
|
||||
"{\"error\":{\"message\":\"视觉后端不可用\"}}", "{\"choices\":[]}", "{\"choices\":[{}]}", "[]"
|
||||
})
|
||||
{
|
||||
using var http = new HttpClient(new ReplyHttp(body));
|
||||
var trace = new List<SopAgentTrace>();
|
||||
try
|
||||
{
|
||||
var result = await new SopVideoAgentClient(http).ChatAsync(new("测试", "", video with { Frames = [] }, ["work"], UserMessage: "讨论", Trace: trace.Add),
|
||||
new("https://invalid.test/v1", "model", ""), default);
|
||||
Check(result.Reply == "正常" && body.Contains("tool_calls"), "空工具调用字段应按普通回复处理");
|
||||
}
|
||||
catch (InvalidDataException error)
|
||||
{ Check(!body.Contains("tool_calls") && error.Message.Contains("Agent 接口"), "异常协议应返回可诊断的具体错误"); }
|
||||
Check(trace.Any(t => t.Kind == "model_response" && t.Text.Contains(body)), "解析失败前须先保存原始服务响应");
|
||||
}
|
||||
Console.WriteLine("PASS: 原始响应诊断、服务错误、空choices与空工具调用兼容");
|
||||
}
|
||||
private static void Check(bool value, string message) { if (!value) throw new Exception(message); }
|
||||
private sealed class ReplyHttp(string body) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
|
||||
=> Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body, Encoding.UTF8, "application/json") });
|
||||
}
|
||||
}
|
||||
@ -13,6 +13,7 @@ internal static class VerificationLoopChecks
|
||||
{
|
||||
using var handler = new LoopHttp { TryShrink = mode == "shrink" }; using var http = new HttpClient(handler);
|
||||
var attempts = 0;
|
||||
var traces = new List<SopAgentTrace>();
|
||||
var request = new SopVideoAnalysisRequest("测试", "保持放入零件工艺", video with { Frames = [] }, ["work"],
|
||||
RegionDefinitions: new Dictionary<string, RegionDef> { ["work"] = new() { X2 = 64, Y2 = 48 } },
|
||||
VerifyDraft: (draft, observed, token) =>
|
||||
@ -25,10 +26,13 @@ internal static class VerificationLoopChecks
|
||||
[new(1, draft.Steps[0].Name, passed, passed ? "AI确认" : "未确认")],
|
||||
[new(1, 10, 1, "work", passed ? .97 : .12, passed, passed ? "完成" : "手部遮挡", observed.Frames[0].Jpeg)],
|
||||
"verified-locally", mode == "infrastructure"));
|
||||
});
|
||||
}, Trace: traces.Add);
|
||||
var result = await new SopVideoAgentClient(http).AnalyzeAsync(request, connection, default);
|
||||
Check(attempts == (mode is "repair" or "shrink" ? 2 : mode == "never" ? 3 : 1), "回测修订最多三轮;基础设施故障不能让模型瞎改工艺");
|
||||
Check(result.Verification?.Passed == (mode is "repair" or "shrink"), "未通过的回测不能被模型自行宣称通过");
|
||||
foreach (var kind in new[] { "model_request", "model_response", "tool_call", "tool_result", "video_frames", "verification_result", "final_result" })
|
||||
Check(traces.Any(t => t.Kind == kind), "分析过程日志必须覆盖:" + kind);
|
||||
Check(traces.Single(t => t.Kind == "video_frames").Images?.Count == 2, "日志保留模型实际读取的图片证据");
|
||||
if (mode == "shrink") Check(handler.Bodies.Count == 4 && result.Steps.Count == 2, "自动修订删除失败步骤时必须拒绝并反馈,不能通过删步凑通过");
|
||||
if (attempts > 1)
|
||||
{
|
||||
|
||||
@ -26,7 +26,7 @@ internal static class AgentDraftVerificationChecks
|
||||
config.Sop.Regions["work"] = new() { X2 = 64, Y2 = 48 };
|
||||
config.Sop.Steps = [new() { Id = 1, Name = "保留人工步骤", Description = "人工要求" }];
|
||||
var model = new RecipeEditorViewModel();
|
||||
var verifier = new ProbeVerifier(); model.DraftVerifier = verifier; model.AgentClient = new ProbeClient();
|
||||
var verifier = new ProbeVerifier(); var client = new ProbeClient(); model.DraftVerifier = verifier; model.AgentClient = client;
|
||||
model.OnDialogOpened(new DialogParameters { { "directory", store.RecipesDirectory }, { "config", config }, { "new", true } });
|
||||
model.SaveCommand.Execute();
|
||||
var path = store.ConfigPath(config.Sop.Name); var before = File.ReadAllBytes(path);
|
||||
@ -45,6 +45,29 @@ internal static class AgentDraftVerificationChecks
|
||||
Check(verifier.Calls == 1 && model.AgentDraftSteps.Count == 1 && model.ApplyAgentDraftCommand.CanExecute(), $"Generated draft passes local verification before it becomes applicable: calls={verifier.Calls}, rows={model.AgentDraftSteps.Count}, status={model.AgentStatus}");
|
||||
Check(model.Recipe.Regions.Count == 1 && model.Recipe.Steps.Count == 1 && File.ReadAllBytes(path).SequenceEqual(before), "Generating and verifying region proposals never edits or saves the recipe");
|
||||
Check(model.AgentRegionAdjustmentsSummary.Contains("trigger"), "Region corrections are visible as draft proposals");
|
||||
var logsFolder = Path.Combine(root, "workspace", "agent-logs");
|
||||
var savedLog = Directory.GetFiles(logsFolder, "analysis-*.jsonl").Single();
|
||||
var logText = File.ReadAllText(savedLog);
|
||||
Check(logText.Contains("session_start") && logText.Contains("video_info") && logText.Contains("model_response")
|
||||
&& logText.Contains("verification_end") && logText.Contains("session_end"), "Every analysis saves its lifecycle and model events automatically");
|
||||
Check(Directory.GetFiles(Path.ChangeExtension(savedLog, null) + "-images", "*.jpg").Length == 1,
|
||||
"Actual model image evidence is saved beside the analysis log");
|
||||
model.AgentApiKey = "never-show-secret";
|
||||
client.Failure = new System.Net.Http.HttpRequestException("连接重置 Bearer never-show-secret data:image/jpeg;base64,AAAA");
|
||||
model.GenerateStepsCommand.Execute(); Until(() => !model.IsAgentBusy);
|
||||
Check(model.AgentStatus.Contains("模型接口连接失败") && model.AgentStatus.Contains("连接重置")
|
||||
&& !model.AgentStatus.Contains("never-show-secret") && !model.AgentStatus.Contains("AAAA"), "Actual network cause is visible while credentials and image bytes are hidden");
|
||||
var diagnostics = Directory.GetFiles(Path.Combine(root, "workspace", "agent-diagnostics"), "error-*.json").Select(File.ReadAllText).ToArray();
|
||||
Check(diagnostics.Any(d => d.Contains("HttpRequestException") && d.Contains("Stage"))
|
||||
&& diagnostics.All(d => !d.Contains("never-show-secret") && !d.Contains("AAAA")), "Agent failures persist a redacted exception and stage for diagnosis");
|
||||
var errorLogs = Directory.GetFiles(logsFolder, "analysis-*.jsonl").Select(File.ReadAllText).ToArray();
|
||||
Check(errorLogs.Any(l => l.Contains("exception") && l.Contains("HttpRequestException"))
|
||||
&& errorLogs.All(l => !l.Contains("never-show-secret") && !l.Contains("AAAA")), "Session logs include the exception and hide credentials and inline image bytes");
|
||||
Check(model.AgentDraftSteps.Count == 1 && File.ReadAllBytes(path).SequenceEqual(before), "Network failure preserves existing draft and recipe");
|
||||
client.Failure = new InvalidOperationException("模型响应 choices 类型错误");
|
||||
model.GenerateStepsCommand.Execute(); Until(() => !model.IsAgentBusy);
|
||||
Check(model.AgentStatus.Contains("choices 类型错误") && model.AgentChatMessages.Any(m => m.Speaker == "错误详情"), "Previously hidden parsing errors now appear in chat with diagnostic location");
|
||||
client.Failure = null;
|
||||
model.AgentDraftSteps[0].Description = "人工补充的静态结果";
|
||||
Check(!model.ApplyAgentDraftCommand.CanExecute() && model.AgentVerificationSummary.Contains("修改"), "Manual draft edits invalidate the verification result");
|
||||
model.VerifyAgentDraftCommand.Execute(); Until(() => !model.IsAgentBusy);
|
||||
@ -65,8 +88,19 @@ internal static class AgentDraftVerificationChecks
|
||||
Check(!model.ApplyAgentDraftCommand.CanExecute() && model.AgentVerificationSummary.Contains("未通过") && model.Recipe.Steps.Count == 2,
|
||||
"Failed verification leaves the draft visible but blocks automatic application");
|
||||
verifier.Hold = true;
|
||||
var completedLogs = Directory.GetFiles(logsFolder, "analysis-*.jsonl");
|
||||
model.GenerateStepsCommand.Execute(); Until(() => verifier.Entered);
|
||||
var runningLog = Directory.GetFiles(logsFolder, "analysis-*.jsonl").Except(completedLogs).Single();
|
||||
using (var stream = new FileStream(runningLog, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||
using (var reader = new StreamReader(stream))
|
||||
{
|
||||
var runningText = reader.ReadToEnd();
|
||||
Check(runningText.Contains("verification_start") && !runningText.Contains("session_end"),
|
||||
"Analysis events are flushed to disk while the operation is still running");
|
||||
}
|
||||
model.CancelAgentCommand.Execute(); Until(() => !model.IsAgentBusy);
|
||||
Check(File.ReadAllText(runningLog).Contains("cancelled_or_timeout") && File.ReadAllText(runningLog).Contains("session_end"),
|
||||
"Cancellation finishes the persistent log without losing earlier events");
|
||||
Check(model.Recipe.Steps.Count == 2 && File.ReadAllBytes(path).SequenceEqual(before), "Cancelling verification leaves the recipe untouched");
|
||||
Pump(model.ShutdownAsync()); window.Close(); model.OnDialogClosed();
|
||||
}
|
||||
@ -82,10 +116,14 @@ internal static class AgentDraftVerificationChecks
|
||||
|
||||
private sealed class ProbeClient : ISopVideoDraftClient
|
||||
{
|
||||
public Exception? Failure;
|
||||
public async Task<SopVideoDraft> AnalyzeAsync(SopVideoAnalysisRequest request, SopAgentConnection connection, CancellationToken token)
|
||||
{
|
||||
if (Failure is { } error) throw error;
|
||||
request.PromptSent?.Report(new(1, 1234, connection.ContextLength, "", "实际系统提示词和当前用户要求"));
|
||||
var frames = SopVideoSampler.ReadFrames(request.Video, [.5, 1.5], 0, token);
|
||||
request.Trace?.Invoke(new("model_request", 1, "实际提示词"));
|
||||
request.Trace?.Invoke(new("model_response", 1, "HTTP 200:模型返回草稿", [new("frame_index=0 time=0.5s", frames[0].Jpeg)]));
|
||||
var draft = request.CurrentDraft ?? new SopVideoDraft
|
||||
{
|
||||
Summary = "生成草稿", RegionAdjustments = [new() { Key = "trigger", X1 = 8, Y1 = 8, X2 = 28, Y2 = 28, EvidenceFrame = 0, Note = "标准画面可见" }],
|
||||
|
||||
Loading…
Reference in New Issue
Block a user