将无思考实测参数同步到Agent生成修订及摘要请求

This commit is contained in:
tfarcraw 2026-11-19 10:17:43 +08:00
parent 695705757f
commit 2575d6ac8e
8 changed files with 37 additions and 11 deletions

View File

@ -514,6 +514,7 @@
<TextBox Grid.Column="1" Text="{Binding AgentApiKey, Mode=TwoWay}" PasswordChar="●" />
</Grid>
<CheckBox Content="同时用于过程时序判定(模型须支持多图)" IsChecked="{Binding AgentUseForSequence, Mode=TwoWay}" />
<CheckBox Content="Agent 生成与修订启用模型思考" IsThreeState="True" IsChecked="{Binding AgentEnableThinking, Mode=TwoWay}" ToolTip.Tip="仅适用于支持此参数的服务;横线沿用服务默认,取消勾选与无思考模式实测一致。" />
<CheckBox Content="过程判定启用模型思考" IsThreeState="True" IsEnabled="{Binding AgentUseForSequence}" IsChecked="{Binding AgentSequenceEnableThinking, Mode=TwoWay}" ToolTip.Tip="适用于支持思考开关的服务;横线沿用服务默认,取消勾选可减少推导耗时。" />
<Expander Header="参数">
<Grid ColumnDefinitions="80,*,80,*" RowDefinitions="Auto,Auto,Auto">

View File

@ -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;

View File

@ -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>(T value) => JsonSerializer.Serialize(value, Options);
public static HttpContent ChatContent<T>(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)

View File

@ -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);

View File

@ -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<string> Regions,
int MaxFramesPerRead = 3, IProgress<string>? Progress = null,
string UserMessage = "", IReadOnlyList<SopAgentChatTurn>? 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));

View File

@ -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);

View File

@ -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 = [];

View File

@ -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<TabControl>().Single();