diff --git a/README.md b/README.md index 40f6148..704d798 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,8 @@ SOP 流程视频可在配方编辑器中录制和播放,独立保存在该配 “Agent助手”接收本地标准视频路径,通过工具自主查看不同时间点、继续检查细节,再生成步骤草稿。模型需支持 Chat Completions 工具调用和图片输入,不需要上传完整视频。每次工具读取上限默认 3 张,可修改并记住。草稿包含时间段、参考画面、步骤说明和手部规则,修改后追加到配方,最后手动保存。接口地址、模型名、密钥及生成参数自动保存,下次启动恢复;模型列表可自动获取。运行时仍由 djev 确认步骤完成。详细限制与配置见 [HAND_AI.md](HAND_AI.md)。 +“Agent助手 → 优化步骤”优化当前配方已有步骤的完成说明,无需重新分析视频。各步须先填写说明并获取关键帧;Agent保留工艺含义生成9条同义改写,与原说明一起各判定一次,每步共10次。判定复用“测试判定”的整张已保存关键帧、djev接口和全局毫秒超时,选有效结果中置信度最高的说明,同分优先保留原文或较早候选;10次均无有效结果则保留原说明。所有步骤完成后统一更新编辑中的配方,点击“保存”落盘;取消、失败或过程中说明/关键帧发生变化时不应用结果。候选提示词及分数可在判定日志中查看,原说明、选中说明和最高分显示在Agent对话中。最高分只代表这张关键帧的完成概率,使用前仍需核对改写是否完整保留原要求。 + 旧配方的 YOLO 模型绑定会被忽略,物体触发规则会提示已移除;需要手动改成手部/计时规则,并将物品要求写进步骤说明。不会根据旧类别名猜测或重写现场工艺。 Agent 助手右侧可聊天,要求拆分、合并或修改步骤,并保留手动编辑。调整先更新草稿,写入配方时弹窗选择覆盖全部步骤或追加到末尾;完成后弹出提示,最后手动保存。 diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs new file mode 100644 index 0000000..40db975 --- /dev/null +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/OptimizeStepsViewModel.cs @@ -0,0 +1,97 @@ +using OpenCvSharp; +using Prism.Commands; +using SopHelper.Engine.Sop; +using SopHelper.Engine.SopAgent; + +namespace SopHelper.VVMs.RecipeEditor; + +public partial class RecipeEditorViewModel +{ + public ISopDescriptionClient DescriptionClient { get; set; } = new SopDescriptionClient(AgentHttp); + public DelegateCommand OptimizeStepsCommand { get; private set; } = null!; + + private async Task OptimizeStepsAsync() + { + if (IsAgentBusy || IsTestingStep || IsCapturing || _agentClosed) return; + var recipe = Recipe; + var recipeName = recipe.Name; + var steps = recipe.Steps.Select(node => new + { + Node = node, node.Id, node.Name, node.Description, node.KeyFrameBase64, node.KeyFrameSeconds + }).ToArray(); + if (steps.Length == 0) { AgentStatus = "当前配方没有可优化的步骤。"; return; } + var missing = steps.FirstOrDefault(step => string.IsNullOrWhiteSpace(step.Description) || string.IsNullOrWhiteSpace(step.KeyFrameBase64)); + if (missing is not null) { AgentStatus = $"请先为步骤 {missing.Id}「{missing.Name}」填写完成说明并获取关键帧。"; return; } + var connection = new SopAgentConnection(AgentEndpoint.Trim(), AgentModel.Trim(), AgentApiKey.Trim(), + AgentContextLength, AgentMaxTokens, AgentTemperature, AgentTopP, AgentTimeoutSeconds, AgentEnableThinking); + try + { + SopAgentEndpoints.Chat(connection.Endpoint); + SopVideoDraftClient.ValidateSettings(connection); + if (string.IsNullOrWhiteSpace(connection.Model)) throw new ArgumentException("请设置Agent模型名"); + } + catch (ArgumentException error) { AgentStatus = error.Message; return; } + using var cancellation = new CancellationTokenSource(); + _agentCancellation = cancellation; + var token = cancellation.Token; + IsAgentBusy = true; + var results = new List<(StepNode Node, string Description)>(); + var unchanged = 0; + try + { + var timeout = (SopHelper.Models.RuntimeSettingsStore.Current.Read() ?? new()).DjevTimeoutMs; + foreach (var step in steps) + { + var label = $"步骤 {step.Id}「{step.Name}」"; + AgentStatus = $"{label}:正在生成9条同义完成说明…"; + var jpeg = await Task.Run(() => + { + using var image = Cv2.ImDecode(Convert.FromBase64String(step.KeyFrameBase64), ImreadModes.Color); + return VisionDecisionImage.Encode(image, null); + }, token); + var rewrites = await DescriptionClient.RewriteAsync(step.Name, step.Description, connection, token).WaitAsync(token); + // 对注入的客户端同样检查,保证每步始终恰好10个候选。 + var candidates = new[] { step.Description }.Concat(rewrites).ToArray(); + if (candidates.Length != 10 || candidates.Any(string.IsNullOrWhiteSpace) + || candidates.Distinct(StringComparer.Ordinal).Count() != 10) + throw new FormatException("Agent未返回9条有效且不同的同义完成说明"); + string? best = null; + var bestConfidence = double.NegativeInfinity; + for (var i = 0; i < candidates.Length; i++) + { + token.ThrowIfCancellationRequested(); + AgentStatus = $"{label}:测试 {i + 1}/10(当前第 {results.Count + 1}/{steps.Length} 步)…"; + var description = candidates[i]; + var request = new VisionDecisionRequest(recipeName, step.Id, step.Name, description, description, 0, DateTime.Now, jpeg, + SourceSeconds: step.KeyFrameSeconds, TimeoutMs: timeout); + var result = await RunStepDecisionAsync($"{label} · 优化 {i + 1}/10", request, token); + token.ThrowIfCancellationRequested(); + var valid = result.EffectiveStatus is VisionDecisionStatus.Completed or VisionDecisionStatus.NotCompleted + && double.IsFinite(result.Confidence) && result.Confidence is >= 0 and <= 1; + AppendStepDecisionLog($"{label} · 优化 {i + 1}/10:{result.EffectiveStatus};置信度 {result.Confidence:P1};{result.Reason}"); + if (valid && result.Confidence > bestConfidence) { best = description; bestConfidence = result.Confidence; } + } + results.Add((step.Node, best ?? step.Description)); + if (best is null) unchanged++; + AgentChatMessages.Add(new("优化步骤", $"{label}\n原说明:{step.Description}\n选中说明:{best ?? step.Description}\n" + + (best is null ? "10次测试均无有效结果,保留原说明。" : $"最高置信度:{bestConfidence:P1}(相同分数优先保留原说明或较早候选)"))); + } + token.ThrowIfCancellationRequested(); + if (_agentClosed || !ReferenceEquals(Recipe, recipe) || recipe.Name != recipeName + || !recipe.Steps.SequenceEqual(steps.Select(s => s.Node)) + || steps.Any(s => s.Node.Description != s.Description || s.Node.Name != s.Name || s.Node.Id != s.Id + || s.Node.KeyFrameBase64 != s.KeyFrameBase64 || s.Node.KeyFrameSeconds != s.KeyFrameSeconds)) + { AgentStatus = "优化期间配方或关键帧已变化,结果未应用,请重新优化。"; return; } + foreach (var result in results) result.Node.Description = result.Description; + RefreshWarnings(); + AgentStatus = $"已优化 {steps.Length} 步,每步测试10次;{unchanged} 步无有效判定保留原说明。请点击“保存”写入配方文件。"; + } + catch (OperationCanceledException) { AgentStatus = "步骤优化已取消或请求超时,当前配方未修改。"; } + catch (Exception error) + { + AgentStatus = "步骤优化失败,当前配方未修改。请检查Agent设置、关键帧和djev服务。"; + AgentChatMessages.Add(new("系统", AgentStatus + "\n" + error.GetType().Name)); + } + finally { _agentCancellation = null; IsAgentBusy = false; } + } +} diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml index c9c276d..6540c7a 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml @@ -482,10 +482,11 @@