From 2575d6ac8e1c3a98f7f80ab2b1921ba0a9a5363e Mon Sep 17 00:00:00 2001 From: tfarcraw <123211521@163.com> Date: Thu, 19 Nov 2026 10:17:43 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=86=E6=97=A0=E6=80=9D=E8=80=83=E5=AE=9E?= =?UTF-8?q?=E6=B5=8B=E5=8F=82=E6=95=B0=E5=90=8C=E6=AD=A5=E5=88=B0Agent?= =?UTF-8?q?=E7=94=9F=E6=88=90=E4=BF=AE=E8=AE=A2=E5=8F=8A=E6=91=98=E8=A6=81?= =?UTF-8?q?=E8=AF=B7=E6=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../VVMs/RecipeEditor/RecipeEditor.axaml | 1 + .../VVMs/RecipeEditor/SopVideoAgentViewModel.cs | 7 +++++-- .../SopAgent/SopAgentJson.cs | 9 +++++++++ .../SopAgent/SopVideoAgentClient.cs | 8 ++++---- .../SopAgent/SopVideoDraftClient.cs | 6 +++--- tests/SopVideoAgent.Smoke/Program.cs | 11 +++++++++++ tests/VideoFlowTest.Smoke/AgentBenchmarkChecks.cs | 3 ++- .../AgentDraftVerificationChecks.cs | 3 ++- 8 files changed, 37 insertions(+), 11 deletions(-) diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml index 19c72b4..2eb4f55 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml @@ -514,6 +514,7 @@ + diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs index 7f94b85..0dea4b0 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs @@ -25,6 +25,8 @@ public partial class RecipeEditorViewModel private bool _agentSettingsLoaded, _agentUseForSequence; public bool AgentUseForSequence { get => _agentUseForSequence; set { if (SetProperty(ref _agentUseForSequence, value)) SaveAgentSettings(); } } private bool? _agentSequenceEnableThinking; + private bool? _agentEnableThinking; + public bool? AgentEnableThinking { get => _agentEnableThinking; set { if (SetProperty(ref _agentEnableThinking, value)) SaveAgentSettings(); } } public bool? AgentSequenceEnableThinking { get => _agentSequenceEnableThinking; set { if (SetProperty(ref _agentSequenceEnableThinking, value)) SaveAgentSettings(); } } private string _agentEndpoint = "", _agentModel = "", _agentApiKey = "", _agentVideoPath = "", _agentInstructions = ""; private string _agentStatus = "", _agentSummary = ""; @@ -121,6 +123,7 @@ public partial class RecipeEditorViewModel var root = document.RootElement; if (root.TryGetProperty("useForSequence", out var sequence)) AgentUseForSequence = sequence.GetBoolean(); if (root.TryGetProperty("sequenceEnableThinking", out var thinking)) AgentSequenceEnableThinking = thinking.ValueKind == JsonValueKind.Null ? null : thinking.GetBoolean(); + if (root.TryGetProperty("enableThinking", out var agentThinking)) AgentEnableThinking = agentThinking.ValueKind == JsonValueKind.Null ? null : agentThinking.GetBoolean(); if (root.TryGetProperty("maxFrames", out var frames)) AgentMaxFrames = frames.GetInt32(); if (root.TryGetProperty("contextLength", out var context)) AgentContextLength = context.GetInt32(); if (root.TryGetProperty("maxTokens", out var output)) AgentMaxTokens = output.GetInt32(); @@ -149,7 +152,7 @@ public partial class RecipeEditorViewModel if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; using (var stream = new FileStream(temporary, options)) JsonSerializer.Serialize(stream, new { endpoint = AgentEndpoint, model = AgentModel, apiKey = AgentApiKey, - useForSequence = AgentUseForSequence, sequenceEnableThinking = AgentSequenceEnableThinking, + useForSequence = AgentUseForSequence, sequenceEnableThinking = AgentSequenceEnableThinking, enableThinking = AgentEnableThinking, maxFrames = AgentMaxFrames, contextLength = AgentContextLength, maxTokens = AgentMaxTokens, temperature = AgentTemperature, topP = AgentTopP, timeoutSeconds = AgentTimeoutSeconds }); File.Move(temporary, AgentSettingsPath, overwrite: true); @@ -227,7 +230,7 @@ public partial class RecipeEditorViewModel if (userMessage is { Length: > 4000 }) { AgentStatus = "消息须小于 4000 字。"; return; } var path = AgentVideoPath; var maxFrames = AgentMaxFrames; var connection = new SopAgentConnection(endpoint.ToString(), AgentModel.Trim(), AgentApiKey.Trim(), - AgentContextLength, AgentMaxTokens, AgentTemperature, AgentTopP, AgentTimeoutSeconds); + AgentContextLength, AgentMaxTokens, AgentTemperature, AgentTopP, AgentTimeoutSeconds, AgentEnableThinking); try { SopVideoDraftClient.ValidateSettings(connection); } catch (ArgumentException error) { AgentStatus = error.Message; return; } var regionDefinitions = Recipe.ToConfig().Sop.Regions; diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopAgentJson.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopAgentJson.cs index 5b629b1..06f9016 100644 --- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopAgentJson.cs +++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopAgentJson.cs @@ -1,6 +1,8 @@ using System.Text.Encodings.Web; using System.Text.RegularExpressions; using System.Text.Json; +using System.Text.Json.Nodes; +using System.Net.Http.Json; namespace SopHelper.Engine.SopAgent; @@ -9,6 +11,13 @@ internal static class SopAgentJson // JSON 作为模型消息文本时保留中文,避免重复转义扩大上下文。 private static readonly JsonSerializerOptions Options = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; public static string Serialize(T value) => JsonSerializer.Serialize(value, Options); + public static HttpContent ChatContent(T payload, bool? enableThinking) + { + if (enableThinking is null) return JsonContent.Create(payload); + var node = JsonSerializer.SerializeToNode(payload, Options)!.AsObject(); + node["chat_template_kwargs"] = new JsonObject { ["enable_thinking"] = enableThinking.Value }; + return JsonContent.Create(node); + } // 部分服务会在最终 JSON 前输出说明。仅接受唯一明确且位于末尾的完整对象,不猜测多个候选或修补残缺 JSON。 public static string Payload(string text) diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs index 5382bc4..24ba3a8 100644 --- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs +++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs @@ -202,12 +202,12 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient using var requestTimeout = CancellationTokenSource.CreateLinkedTokenSource(token); requestTimeout.CancelAfter(TimeSpan.FromSeconds(connection.TimeoutSeconds)); if (!string.IsNullOrWhiteSpace(connection.ApiKey)) message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", connection.ApiKey); - message.Content = JsonContent.Create(new + message.Content = SopAgentJson.ChatContent(new { model = connection.Model, stream = false, max_tokens = connection.MaxTokens, temperature = connection.Temperature, top_p = connection.TopP, messages, tools, tool_choice = turn == maxTurns - 1 ? "none" : "auto" - }); + }, connection.EnableThinking); 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}")); @@ -592,8 +592,8 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient } 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, - temperature = 0, messages = summaryMessages }); + call.Content = SopAgentJson.ChatContent(new { model = connection.Model, stream = false, max_tokens = outputTokens, + temperature = 0, messages = summaryMessages }, connection.EnableThinking); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); timeout.CancelAfter(TimeSpan.FromSeconds(connection.TimeoutSeconds)); using var response = await http.SendAsync(call, timeout.Token).ConfigureAwait(false); diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs index 6f138a8..b09a490 100644 --- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs +++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs @@ -8,7 +8,7 @@ using SopHelper.Engine.Sop; namespace SopHelper.Engine.SopAgent; public sealed record SopAgentConnection(string Endpoint, string Model, string ApiKey, - int ContextLength = 131702, int MaxTokens = 8192, double Temperature = .2, double TopP = .9, int TimeoutSeconds = 300); + int ContextLength = 131702, int MaxTokens = 8192, double Temperature = .2, double TopP = .9, int TimeoutSeconds = 300, bool? EnableThinking = null); public sealed record SopVideoAnalysisRequest(string Recipe, string Instructions, SopVideoSample Video, IReadOnlyList Regions, int MaxFramesPerRead = 3, IProgress? Progress = null, string UserMessage = "", IReadOnlyList? Conversation = null, SopVideoDraft? CurrentDraft = null, @@ -153,7 +153,7 @@ public sealed class SopVideoDraftClient(HttpClient http) : ISopVideoDraftClient } using var message = new HttpRequestMessage(HttpMethod.Post, endpoint); if (!string.IsNullOrWhiteSpace(connection.ApiKey)) message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", connection.ApiKey); - message.Content = JsonContent.Create(new + message.Content = SopAgentJson.ChatContent(new { model = connection.Model, stream = false, max_tokens = connection.MaxTokens, temperature = connection.Temperature, top_p = connection.TopP, @@ -172,7 +172,7 @@ public sealed class SopVideoDraftClient(HttpClient http) : ISopVideoDraftClient """ }, new { role = "user", content } } - }); + }, connection.EnableThinking); using var response = await http.SendAsync(message, token).ConfigureAwait(false); if (!response.IsSuccessStatusCode) throw new InvalidOperationException($"视频分析接口 HTTP {(int)response.StatusCode},请检查地址、模型和密钥"); using var envelope = JsonDocument.Parse(await response.Content.ReadAsStringAsync(token).ConfigureAwait(false)); diff --git a/tests/SopVideoAgent.Smoke/Program.cs b/tests/SopVideoAgent.Smoke/Program.cs index bb2cd7d..1f30016 100644 --- a/tests/SopVideoAgent.Smoke/Program.cs +++ b/tests/SopVideoAgent.Smoke/Program.cs @@ -77,11 +77,15 @@ try &&body.RootElement.GetProperty("temperature").GetDouble()==.4&&body.RootElement.GetProperty("top_p").GetDouble()==.8, "应发送配置的输出长度、温度和Top P"); var parts=body.RootElement.GetProperty("messages")[1].GetProperty("content"); + Check(!body.RootElement.TryGetProperty("chat_template_kwargs",out _),"未指定思考模式时不能向其他服务追加专用参数"); Check(parts[0].GetProperty("text").GetString()!.Contains("装盒") && !parts[0].GetProperty("text").GetString()!.Contains("\\u88C5"), "嵌入提示词的中文JSON须保持可读,避免六字符转义放大上下文"); Check(parts.EnumerateArray().Count(p=>p.GetProperty("type").GetString()=="image_url")==3,"必须上传抽样图片"); Check(parts[1].GetProperty("text").GetString()!.Contains("time=0.000s"),"必须发送时间戳"); } + await client.AnalyzeAsync(request,connection with {EnableThinking=false},default); + using(var thinkingBody=JsonDocument.Parse(handler.Body!)) + Check(!thinkingBody.RootElement.GetProperty("chat_template_kwargs").GetProperty("enable_thinking").GetBoolean(),"生成步骤须支持显式关闭思考以复现实测参数"); var limited=false; try{await client.AnalyzeAsync(request,connection with {ContextLength=4096,MaxTokens=2048},default);}catch(ArgumentException){limited=true;} Check(limited,"上下文预算不足时应拒绝发送"); @@ -90,6 +94,13 @@ try Check(invalidSettings,"无效采样参数应被拒绝"); Check(SopVideoSampler.Sample(path,3,default).Frames.Count==3,"最大抽帧数应支持3张"); var info=SopVideoSampler.ReadInfo(path,default); + using(var thinkingHandler=new ToolAgentHttp()) + using(var thinkingHttp=new HttpClient(thinkingHandler)) + { + await new SopVideoAgentClient(thinkingHttp).AnalyzeAsync(request with {Video=info},connection with {ContextLength=131702,EnableThinking=false},default); + Check(thinkingHandler.Bodies.All(body=>!JsonDocument.Parse(body).RootElement.GetProperty("chat_template_kwargs").GetProperty("enable_thinking").GetBoolean()), + "Agent每轮生成及工具往返均须沿用显式思考设置"); + } await VerificationLoopChecks.RunAsync(info); await VerificationContextChecks.RunAsync(info); await DirectDraftVerificationChecks.RunAsync(info); diff --git a/tests/VideoFlowTest.Smoke/AgentBenchmarkChecks.cs b/tests/VideoFlowTest.Smoke/AgentBenchmarkChecks.cs index 94bf9ec..5feae8c 100644 --- a/tests/VideoFlowTest.Smoke/AgentBenchmarkChecks.cs +++ b/tests/VideoFlowTest.Smoke/AgentBenchmarkChecks.cs @@ -27,7 +27,8 @@ internal static class AgentBenchmarkChecks 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)); + Number("contextLength", 131702), Number("maxTokens", 8192), Decimal("temperature", .2), Decimal("topP", .9), Number("timeoutSeconds", 300), + disableThinking ? false : root.TryGetProperty("enableThinking", out var agentThinking) && agentThinking.ValueKind != JsonValueKind.Null ? agentThinking.GetBoolean() : null); var template = SopConfigLoader.Load(configPath); // 与界面未应用草稿的 CreateAgentVerificationTemplate 一致,不能继承不相关旧步骤的送检区。 template.Sop.Steps = []; diff --git a/tests/VideoFlowTest.Smoke/AgentDraftVerificationChecks.cs b/tests/VideoFlowTest.Smoke/AgentDraftVerificationChecks.cs index 492cfc3..5323303 100644 --- a/tests/VideoFlowTest.Smoke/AgentDraftVerificationChecks.cs +++ b/tests/VideoFlowTest.Smoke/AgentDraftVerificationChecks.cs @@ -35,8 +35,9 @@ internal static class AgentDraftVerificationChecks var path = store.ConfigPath(config.Sop.Name); var before = File.ReadAllBytes(path); model.AgentVideoPath = video; model.AgentEndpoint = "http://127.0.0.1:1/v1"; model.AgentModel = "unit-test"; model.AgentSequenceEnableThinking = false; + model.AgentEnableThinking = false; using (var saved = System.Text.Json.JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "workspace", "sop-agent.json")))) - Check(!saved.RootElement.GetProperty("sequenceEnableThinking").GetBoolean(), "时序思考设置须可持久化,便于复现实测参数"); + Check(!saved.RootElement.GetProperty("sequenceEnableThinking").GetBoolean() && !saved.RootElement.GetProperty("enableThinking").GetBoolean(), "Agent与时序思考设置须可持久化,便于复现实测参数"); var view = new RecipeEditor { DataContext = model }; var window = new Window { Width = 1040, Height = 900, Content = view }; window.Show(); window.UpdateLayout(); var tabs = view.GetVisualDescendants().OfType().Single();