增加模型列表获取与持久化生成参数并默认抽帧三张
This commit is contained in:
parent
5c07df947e
commit
89da02f939
@ -12,9 +12,9 @@
|
||||
|
||||
配方编辑器的“Agent助手”页支持从标准 SOP 视频生成步骤草稿。先在“SOP流程视频”页停止并保存录像,或选择本地视频;填写完整的 Chat Completions 地址(如 `https://your-server/v1/chat/completions`)、视觉模型名和密钥,可补充工艺背景或拆分要求,然后点击“分析视频并生成步骤”。地址可自行设置,不绑定服务商。
|
||||
|
||||
这里需要能够接收多张图片并生成文字的视觉模型。D3-lite 的 `/v1/systemone` 只能判定条件,不用于生成步骤;运行时仍使用原 D3 配置。助手请求采用 `messages`、`image_url` 的 JPEG data URL、`stream=false`、`max_tokens=4096`,模型返回包含步骤、时间段、参考帧和触发规则的 JSON。
|
||||
这里需要能够接收多张图片并生成文字的视觉模型。D3-lite 的 `/v1/systemone` 只能判定条件,不用于生成步骤;运行时仍使用原 D3 配置。助手请求采用 `messages`、`image_url` 的 JPEG data URL、`stream=false`,可设置最大输出(默认 4096)、温度(0.2)和 Top P(0.9)。填写接口或密钥后自动请求相应的 `/models` 获取模型名,也可点击“获取模型”刷新或手动填写;列表包含服务返回的全部模型,是否支持视觉由服务决定。
|
||||
|
||||
视频最长约 5 分钟;均匀抽取最多 4–60 张画面(默认上限 40,短视频实际帧数更少),最长边缩至 640 像素,JPEG 总量限制为 10MB。发送的是带时间戳的抽样图片,不是完整视频,短暂动作或细小物体可能漏掉。服务还需支持所选数量的多图输入。分析总超时为 5 分钟,可取消;取消或失败不修改当前配方。
|
||||
视频最长约 5 分钟;均匀抽取最多 2–60 张画面(默认上限 3,修改后记住),最长边缩至 640 像素,JPEG 总量限制为 10MB。发送的是带时间戳的抽样图片,不是完整视频,短暂动作或细小物体可能漏掉。上下文长度默认 32768,用于本地估算输入与输出预算;图像 token 数依模型而异,此设置不改变服务端实际上限。超时默认 300 秒,可设置 10–1800 秒;取消或失败不修改当前配方。上下文、输出、温度、Top P、超时和最大抽帧数均自动保存并恢复。
|
||||
|
||||
生成后逐步显示时间段、参考画面、名称、说明、区域键和提醒,可先修改。点击“将草稿添加到当前配方”才追加步骤,已有步骤和 ID 保留,同一份草稿不能重复添加。完成条件直接使用生成并编辑后的步骤说明;触发规则使用手在区域、离开区域或区域间移动。缺少区域时保留空值并提醒标定,不猜测坐标。到“步骤”页核对左右手、移动起终点及送检范围,最后点击“保存”写入配方文件。
|
||||
|
||||
|
||||
@ -470,21 +470,36 @@
|
||||
<TextBlock Text="接口地址" VerticalAlignment="Center" />
|
||||
<TextBox x:Name="AgentEndpointBox" Grid.Column="1" Text="{Binding AgentEndpoint, Mode=TwoWay}" PlaceholderText="https://你的服务/v1/chat/completions" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="70,*">
|
||||
<Grid ColumnDefinitions="70,*,Auto">
|
||||
<TextBlock Text="模型名" VerticalAlignment="Center" />
|
||||
<TextBox x:Name="AgentModelBox" Grid.Column="1" Text="{Binding AgentModel, Mode=TwoWay}" />
|
||||
<AutoCompleteBox x:Name="AgentModelBox" Grid.Column="1" Text="{Binding AgentModel, Mode=TwoWay}" ItemsSource="{Binding AgentModels}" MinimumPrefixLength="0" />
|
||||
<Button Grid.Column="2" Content="获取模型" Command="{Binding FetchAgentModelsCommand}" Margin="8,0,0,0" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="70,*">
|
||||
<TextBlock Text="密钥" VerticalAlignment="Center" />
|
||||
<TextBox Grid.Column="1" Text="{Binding AgentApiKey, Mode=TwoWay}" PasswordChar="●" />
|
||||
</Grid>
|
||||
<Expander Header="参数">
|
||||
<Grid ColumnDefinitions="80,*,80,*,80,*" RowDefinitions="Auto,Auto">
|
||||
<TextBlock Text="上下文长度" VerticalAlignment="Center" />
|
||||
<NumericUpDown Grid.Column="1" Value="{Binding AgentContextLength, Mode=TwoWay}" Minimum="2048" Maximum="2097152" Increment="1024" />
|
||||
<TextBlock Grid.Column="2" Text="最大输出" VerticalAlignment="Center" Margin="8,0,0,0" />
|
||||
<NumericUpDown Grid.Column="3" Value="{Binding AgentMaxTokens, Mode=TwoWay}" Minimum="256" Maximum="2097151" Increment="256" />
|
||||
<TextBlock Grid.Column="4" Text="超时(秒)" VerticalAlignment="Center" Margin="8,0,0,0" />
|
||||
<NumericUpDown Grid.Column="5" Value="{Binding AgentTimeoutSeconds, Mode=TwoWay}" Minimum="10" Maximum="1800" Increment="10" />
|
||||
<TextBlock Grid.Row="1" Text="温度" VerticalAlignment="Center" />
|
||||
<NumericUpDown Grid.Row="1" Grid.Column="1" Value="{Binding AgentTemperature, Mode=TwoWay}" Minimum="0" Maximum="2" Increment="0.1" FormatString="0.0" />
|
||||
<TextBlock Grid.Row="1" Grid.Column="2" Text="Top P" VerticalAlignment="Center" Margin="8,0,0,0" />
|
||||
<NumericUpDown Grid.Row="1" Grid.Column="3" Value="{Binding AgentTopP, Mode=TwoWay}" Minimum="0.01" Maximum="1" Increment="0.05" FormatString="0.00" />
|
||||
</Grid>
|
||||
</Expander>
|
||||
</StackPanel>
|
||||
</Expander>
|
||||
<StackPanel Grid.Row="2" Spacing="6" Margin="0,8,0,8">
|
||||
<TextBox Text="{Binding AgentInstructions, Mode=TwoWay}" IsEnabled="{Binding AgentIsIdle}" AcceptsReturn="True" TextWrapping="Wrap" MinHeight="48" PlaceholderText="补充要求" />
|
||||
<WrapPanel>
|
||||
<TextBlock Text="最大抽帧数" VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<NumericUpDown Value="{Binding AgentMaxFrames, Mode=TwoWay}" Minimum="4" Maximum="60" Increment="4" Width="100" IsEnabled="{Binding AgentIsIdle}" />
|
||||
<NumericUpDown Value="{Binding AgentMaxFrames, Mode=TwoWay}" Minimum="2" Maximum="60" Increment="1" Width="100" IsEnabled="{Binding AgentIsIdle}" />
|
||||
<Button Content="生成步骤" Command="{Binding GenerateStepsCommand}" Margin="12,0,0,0" />
|
||||
<Button Content="取消分析" Command="{Binding CancelAgentCommand}" Margin="8,0,0,0" />
|
||||
<Button Content="添加到配方" Command="{Binding ApplyAgentDraftCommand}" Margin="8,0,0,0" />
|
||||
|
||||
@ -166,6 +166,8 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
public Task ShutdownAsync() => _shutdown ??= ShutdownCoreAsync();
|
||||
private async Task ShutdownCoreAsync()
|
||||
{
|
||||
_agentClosed = true;
|
||||
_modelDiscoveryCancellation?.Cancel();
|
||||
_agentCancellation?.Cancel();
|
||||
if (_agentTask is not null) await _agentTask;
|
||||
ClearAgentDraft();
|
||||
|
||||
@ -23,13 +23,23 @@ public partial class RecipeEditorViewModel
|
||||
private bool _agentSettingsLoaded;
|
||||
private string _agentEndpoint = "", _agentModel = "", _agentApiKey = "", _agentVideoPath = "", _agentInstructions = "";
|
||||
private string _agentStatus = "", _agentSummary = "";
|
||||
private int _agentMaxFrames = 40;
|
||||
private int _agentMaxFrames = 3;
|
||||
private int _agentContextLength = 32768, _agentMaxTokens = 4096, _agentTimeoutSeconds = 300;
|
||||
private double _agentTemperature = .2, _agentTopP = .9;
|
||||
private CancellationTokenSource? _modelDiscoveryCancellation;
|
||||
private bool _agentClosed;
|
||||
public ObservableCollection<string> AgentModels { get; } = [];
|
||||
public int AgentContextLength { get => _agentContextLength; set { if (SetProperty(ref _agentContextLength, value)) SaveAgentSettings(); } }
|
||||
public int AgentMaxTokens { get => _agentMaxTokens; set { if (SetProperty(ref _agentMaxTokens, value)) SaveAgentSettings(); } }
|
||||
public int AgentTimeoutSeconds { get => _agentTimeoutSeconds; set { if (SetProperty(ref _agentTimeoutSeconds, value)) SaveAgentSettings(); } }
|
||||
public double AgentTemperature { get => _agentTemperature; set { if (SetProperty(ref _agentTemperature, value)) SaveAgentSettings(); } }
|
||||
public double AgentTopP { get => _agentTopP; set { if (SetProperty(ref _agentTopP, value)) SaveAgentSettings(); } }
|
||||
public ObservableCollection<AgentDraftRow> AgentDraftSteps { get; } = [];
|
||||
public string AgentEndpoint { get => _agentEndpoint; set { if (SetProperty(ref _agentEndpoint, value)) SaveAgentSettings(); } }
|
||||
public string AgentEndpoint { get => _agentEndpoint; set { if (SetProperty(ref _agentEndpoint, value)) { SaveAgentSettings(); ScheduleModelDiscovery(); } } }
|
||||
public string AgentModel { get => _agentModel; set { if (SetProperty(ref _agentModel, value)) SaveAgentSettings(); } }
|
||||
public string AgentApiKey { get => _agentApiKey; set { if (SetProperty(ref _agentApiKey, value)) SaveAgentSettings(); } }
|
||||
public string AgentApiKey { get => _agentApiKey; set { if (SetProperty(ref _agentApiKey, value)) { SaveAgentSettings(); ScheduleModelDiscovery(); } } }
|
||||
public string AgentInstructions { get => _agentInstructions; set => SetProperty(ref _agentInstructions, value); }
|
||||
public int AgentMaxFrames { get => _agentMaxFrames; set => SetProperty(ref _agentMaxFrames, value); }
|
||||
public int AgentMaxFrames { get => _agentMaxFrames; set { if (SetProperty(ref _agentMaxFrames, value)) SaveAgentSettings(); } }
|
||||
public string AgentVideoPath
|
||||
{
|
||||
get => _agentVideoPath;
|
||||
@ -56,11 +66,13 @@ public partial class RecipeEditorViewModel
|
||||
public DelegateCommand CancelAgentCommand { get; private set; } = null!;
|
||||
public DelegateCommand ApplyAgentDraftCommand { get; private set; } = null!;
|
||||
public DelegateCommand BrowseAgentVideoCommand { get; private set; } = null!;
|
||||
public DelegateCommand FetchAgentModelsCommand { get; private set; } = null!;
|
||||
private string AgentSettingsPath => Path.Combine(DesktopPlatform.WorkspaceRoot, "workspace", "sop-agent.json");
|
||||
|
||||
private void InitializeAgentCommands()
|
||||
{
|
||||
GenerateStepsCommand = new DelegateCommand(() => _agentTask = AnalyzeVideoAsync(), () => !IsAgentBusy && !IsCapturing);
|
||||
FetchAgentModelsCommand = new DelegateCommand(() => ScheduleModelDiscovery(immediate: true));
|
||||
CancelAgentCommand = new DelegateCommand(() => _agentCancellation?.Cancel(), () => IsAgentBusy);
|
||||
ApplyAgentDraftCommand = new DelegateCommand(ApplyAgentDraft, () => !IsAgentBusy && !_draftApplied && AgentDraftSteps.Count > 0);
|
||||
BrowseAgentVideoCommand = new DelegateCommand(async () =>
|
||||
@ -81,6 +93,13 @@ public partial class RecipeEditorViewModel
|
||||
AgentEndpoint = document.RootElement.GetProperty("endpoint").GetString() ?? "";
|
||||
AgentModel = document.RootElement.GetProperty("model").GetString() ?? "";
|
||||
AgentApiKey = document.RootElement.TryGetProperty("apiKey", out var key) ? key.GetString() ?? "" : "";
|
||||
var root = document.RootElement;
|
||||
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();
|
||||
if (root.TryGetProperty("temperature", out var temperature)) AgentTemperature = temperature.GetDouble();
|
||||
if (root.TryGetProperty("topP", out var topP)) AgentTopP = topP.GetDouble();
|
||||
if (root.TryGetProperty("timeoutSeconds", out var timeout)) AgentTimeoutSeconds = timeout.GetInt32();
|
||||
}
|
||||
}
|
||||
catch (Exception) { AgentStatus = "模型连接设置无法读取,请重新填写地址和模型名。"; }
|
||||
@ -89,6 +108,7 @@ public partial class RecipeEditorViewModel
|
||||
AgentApiKey = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_API_KEY") ?? AgentApiKey;
|
||||
_agentSettingsLoaded = true;
|
||||
UpdateAgentDefaultVideo();
|
||||
ScheduleModelDiscovery();
|
||||
}
|
||||
|
||||
private void SaveAgentSettings()
|
||||
@ -101,7 +121,9 @@ public partial class RecipeEditorViewModel
|
||||
var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write };
|
||||
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 });
|
||||
JsonSerializer.Serialize(stream, new { endpoint = AgentEndpoint, model = AgentModel, apiKey = AgentApiKey,
|
||||
maxFrames = AgentMaxFrames, contextLength = AgentContextLength, maxTokens = AgentMaxTokens,
|
||||
temperature = AgentTemperature, topP = AgentTopP, timeoutSeconds = AgentTimeoutSeconds });
|
||||
File.Move(temporary, AgentSettingsPath, overwrite: true);
|
||||
}
|
||||
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
|
||||
@ -112,6 +134,37 @@ public partial class RecipeEditorViewModel
|
||||
catch (Exception error) when (error is IOException or UnauthorizedAccessException) { }
|
||||
}
|
||||
}
|
||||
|
||||
private void ScheduleModelDiscovery(bool immediate = false)
|
||||
{
|
||||
if (!_agentSettingsLoaded || _agentClosed) return;
|
||||
_modelDiscoveryCancellation?.Cancel();
|
||||
AgentModels.Clear();
|
||||
if (!Uri.TryCreate(AgentEndpoint.Trim(), UriKind.Absolute, out var endpoint) || endpoint.Scheme is not ("http" or "https")) return;
|
||||
var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(15));
|
||||
_modelDiscoveryCancellation = cancellation;
|
||||
_ = DiscoverModelsAsync(AgentEndpoint.Trim(), AgentApiKey.Trim(), cancellation, immediate);
|
||||
}
|
||||
|
||||
private async Task DiscoverModelsAsync(string endpoint, string key, CancellationTokenSource cancellation, bool immediate)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!immediate) await Task.Delay(600, cancellation.Token);
|
||||
var models = await new SopVideoDraftClient(AgentHttp).GetModelsAsync(endpoint, key, cancellation.Token);
|
||||
cancellation.Token.ThrowIfCancellationRequested();
|
||||
foreach (var model in models) AgentModels.Add(model);
|
||||
if (string.IsNullOrWhiteSpace(AgentModel) && models.Count > 0) AgentModel = models[0];
|
||||
if (immediate && !IsAgentBusy) AgentStatus = $"已获取 {models.Count} 个模型。";
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (Exception) { if (immediate && !IsAgentBusy) AgentStatus = "模型列表获取失败。"; }
|
||||
finally
|
||||
{
|
||||
if (ReferenceEquals(_modelDiscoveryCancellation, cancellation)) _modelDiscoveryCancellation = null;
|
||||
cancellation.Dispose();
|
||||
}
|
||||
}
|
||||
private void UpdateAgentDefaultVideo()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(AgentVideoPath) && SopRecording is not null) AgentVideoPath = SopRecording.StandardVideoPath;
|
||||
@ -124,12 +177,15 @@ public partial class RecipeEditorViewModel
|
||||
if (!File.Exists(AgentVideoPath)) { AgentStatus = "请先录制标准 SOP 视频,或选择已有视频。"; return; }
|
||||
if (!Uri.TryCreate(AgentEndpoint.Trim(), UriKind.Absolute, out var endpoint) || endpoint.Scheme is not ("http" or "https")
|
||||
|| string.IsNullOrWhiteSpace(AgentModel)) { AgentStatus = "请先设置完整的视觉模型接口地址和模型名。"; return; }
|
||||
if (AgentMaxFrames is < 4 or > 60 || AgentInstructions.Length > 4000) { AgentStatus = "最大抽帧数须为 4–60,补充要求须小于 4000 字。"; return; }
|
||||
if (AgentMaxFrames is < 2 or > 60 || AgentInstructions.Length > 4000) { AgentStatus = "最大抽帧数须为 2–60,补充要求须小于 4000 字。"; return; }
|
||||
var path = AgentVideoPath; var maxFrames = AgentMaxFrames;
|
||||
var connection = new SopAgentConnection(endpoint.ToString(), AgentModel.Trim(), AgentApiKey.Trim());
|
||||
var connection = new SopAgentConnection(endpoint.ToString(), AgentModel.Trim(), AgentApiKey.Trim(),
|
||||
AgentContextLength, AgentMaxTokens, AgentTemperature, AgentTopP, AgentTimeoutSeconds);
|
||||
try { SopVideoDraftClient.ValidateSettings(connection); }
|
||||
catch (ArgumentException error) { AgentStatus = error.Message; return; }
|
||||
var regions = Recipe.RegionNames.Where(r => !string.IsNullOrWhiteSpace(r)).ToArray();
|
||||
var recipeName = Recipe.Name; var instructions = AgentInstructions;
|
||||
_agentCancellation = new CancellationTokenSource(TimeSpan.FromMinutes(5));
|
||||
_agentCancellation = new CancellationTokenSource(TimeSpan.FromSeconds(connection.TimeoutSeconds));
|
||||
var token = _agentCancellation.Token;
|
||||
IsAgentBusy = true;
|
||||
AgentStatus = "正在读取标准 SOP 视频…";
|
||||
|
||||
@ -7,7 +7,8 @@ using SopHelper.Engine.Sop;
|
||||
|
||||
namespace SopHelper.Engine.SopAgent;
|
||||
|
||||
public sealed record SopAgentConnection(string Endpoint, string Model, string ApiKey);
|
||||
public sealed record SopAgentConnection(string Endpoint, string Model, string ApiKey,
|
||||
int ContextLength = 32768, int MaxTokens = 4096, double Temperature = .2, double TopP = .9, int TimeoutSeconds = 300);
|
||||
public sealed record SopVideoAnalysisRequest(string Recipe, string Instructions, SopVideoSample Video, IReadOnlyList<string> Regions);
|
||||
public sealed class SopVideoDraft
|
||||
{
|
||||
@ -36,8 +37,40 @@ public interface ISopVideoDraftClient
|
||||
|
||||
public sealed class SopVideoDraftClient(HttpClient http) : ISopVideoDraftClient
|
||||
{
|
||||
public async Task<IReadOnlyList<string>> GetModelsAsync(string endpoint, string apiKey, CancellationToken token)
|
||||
{
|
||||
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || uri.Scheme is not ("http" or "https"))
|
||||
throw new ArgumentException("接口地址无效");
|
||||
var builder = new UriBuilder(uri) { Query = "", Fragment = "" };
|
||||
var path = builder.Path.TrimEnd('/');
|
||||
builder.Path = path.EndsWith("/chat/completions", StringComparison.OrdinalIgnoreCase)
|
||||
? path[..^"/chat/completions".Length] + "/models" : path + "/models";
|
||||
using var message = new HttpRequestMessage(HttpMethod.Get, builder.Uri);
|
||||
if (!string.IsNullOrWhiteSpace(apiKey)) message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
|
||||
using var response = await http.SendAsync(message, token).ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(token).ConfigureAwait(false));
|
||||
return json.RootElement.GetProperty("data").EnumerateArray()
|
||||
.Select(item => item.GetProperty("id").GetString()).OfType<string>().Where(id => !string.IsNullOrWhiteSpace(id))
|
||||
.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();
|
||||
}
|
||||
|
||||
public static void ValidateSettings(SopAgentConnection connection)
|
||||
{
|
||||
if (connection.ContextLength is < 2048 or > 2097152 || connection.MaxTokens < 256 || connection.MaxTokens >= connection.ContextLength
|
||||
|| !double.IsFinite(connection.Temperature) || connection.Temperature is < 0 or > 2
|
||||
|| !double.IsFinite(connection.TopP) || connection.TopP is <= 0 or > 1 || connection.TimeoutSeconds is < 10 or > 1800)
|
||||
throw new ArgumentException("模型参数无效,请检查上下文、输出长度、采样参数和超时");
|
||||
}
|
||||
|
||||
public async Task<SopVideoDraft> AnalyzeAsync(SopVideoAnalysisRequest request, SopAgentConnection connection, CancellationToken token)
|
||||
{
|
||||
ValidateSettings(connection);
|
||||
// 图像 token 由模型决定,此处仅使用保守估算控制输入预算。
|
||||
var estimatedInput = 2048L + request.Instructions.Length * 2L + request.Recipe.Length * 2L
|
||||
+ request.Regions.Sum(region => region.Length * 2L) + request.Video.Frames.Count * 1700L;
|
||||
if (estimatedInput + connection.MaxTokens > connection.ContextLength)
|
||||
throw new ArgumentException("抽帧数量超出估算上下文预算,请减少抽帧或增大上下文长度");
|
||||
if (!Uri.TryCreate(connection.Endpoint, UriKind.Absolute, out var endpoint) || endpoint.Scheme is not ("http" or "https")
|
||||
|| string.IsNullOrWhiteSpace(connection.Model)) throw new ArgumentException("请设置完整的视觉模型接口地址和模型名");
|
||||
if (endpoint.AbsolutePath.TrimEnd('/').EndsWith("systemone", StringComparison.OrdinalIgnoreCase))
|
||||
@ -57,7 +90,8 @@ public sealed class SopVideoDraftClient(HttpClient http) : ISopVideoDraftClient
|
||||
if (!string.IsNullOrWhiteSpace(connection.ApiKey)) message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", connection.ApiKey);
|
||||
message.Content = JsonContent.Create(new
|
||||
{
|
||||
model = connection.Model, stream = false, max_tokens = 4096,
|
||||
model = connection.Model, stream = false, max_tokens = connection.MaxTokens,
|
||||
temperature = connection.Temperature, top_p = connection.TopP,
|
||||
messages = new object[]
|
||||
{
|
||||
new { role = "system", content = """
|
||||
|
||||
@ -9,7 +9,7 @@ public static class SopVideoSampler
|
||||
{
|
||||
public static SopVideoSample Sample(string path, int maxFrames, CancellationToken token, IProgress<string>? progress = null)
|
||||
{
|
||||
if (maxFrames is < 4 or > 60) throw new ArgumentException("抽帧数量须在 4–60 之间");
|
||||
if (maxFrames is < 2 or > 60) throw new ArgumentException("抽帧数量须在 2–60 之间");
|
||||
if (!File.Exists(path)) throw new FileNotFoundException("请先录制标准 SOP 视频,或选择已有视频");
|
||||
var before = new FileInfo(path); var length = before.Length; var modified = before.LastWriteTimeUtc;
|
||||
using var video = new VideoCapture(path);
|
||||
|
||||
@ -723,8 +723,10 @@ internal static class Smoke
|
||||
for(var i=0;i<40;i++){using var frame=new Mat(48,64,MatType.CV_8UC3,new Scalar(i*4,60,90));writer.Write(frame);}
|
||||
}
|
||||
var client=new UiSopAgent();model.AgentClient=client;
|
||||
Check(model.AgentMaxFrames==3,"Assistant defaults to at most three sampled frames");
|
||||
model.AgentVideoPath=video;model.AgentEndpoint="https://custom.invalid/v1/chat/completions";
|
||||
model.AgentModel="custom-vision";model.AgentApiKey="remember-test-key";model.AgentMaxFrames=4;
|
||||
model.AgentModel="custom-vision";model.AgentApiKey="remember-test-key";model.AgentMaxFrames=3;
|
||||
model.AgentContextLength=16384;model.AgentMaxTokens=2048;model.AgentTemperature=.4;model.AgentTopP=.8;model.AgentTimeoutSeconds=90;
|
||||
var settingsPath=Path.Combine(store.Root,"workspace","sop-agent.json");
|
||||
Check(File.ReadAllText(settingsPath).Contains("custom-vision"),"Model settings are saved before any analysis request");
|
||||
async Task<RecipeEditorViewModel> ReopenAgent()
|
||||
@ -737,6 +739,12 @@ internal static class Smoke
|
||||
var reopened=await ReopenAgent();
|
||||
Check(reopened.AgentEndpoint==model.AgentEndpoint&&reopened.AgentModel==model.AgentModel&&reopened.AgentApiKey==model.AgentApiKey,
|
||||
"A fresh editor restores endpoint, model and key without requiring successful analysis");
|
||||
Check(reopened.AgentMaxFrames==3&&reopened.AgentContextLength==16384&&reopened.AgentMaxTokens==2048
|
||||
&&reopened.AgentTemperature==.4&&reopened.AgentTopP==.8&&reopened.AgentTimeoutSeconds==90,
|
||||
"A fresh editor restores sampling, context, output, temperature, top P and timeout settings");
|
||||
model.AgentMaxFrames=5;
|
||||
Check((await ReopenAgent()).AgentMaxFrames==5,"Custom frame count persists across editor restarts");
|
||||
model.AgentMaxFrames=3;
|
||||
model.AgentApiKey="";
|
||||
Check((await ReopenAgent()).AgentApiKey=="","Clearing the key persists across editor restarts");
|
||||
model.AgentApiKey="remember-test-key";
|
||||
@ -748,6 +756,8 @@ internal static class Smoke
|
||||
for(var i=0;i<300&&model.IsAgentBusy;i++)await Task.Delay(10);
|
||||
Check(!model.IsAgentBusy&&model.AgentDraftSteps.Count==2,"Assistant samples video and presents model-generated draft steps");
|
||||
Check(client.Connection?.Endpoint==model.AgentEndpoint&&client.Connection.Model==model.AgentModel&&client.Request?.Video.Frames.Count==3,"Assistant uses current connection and real sampled frames");
|
||||
Check(client.Connection?.MaxTokens==2048&&client.Connection.ContextLength==16384&&client.Connection.Temperature==.4
|
||||
&&client.Connection.TopP==.8&&client.Connection.TimeoutSeconds==90,"Analysis receives the configured generation parameters");
|
||||
Check(model.Recipe.Steps.Count==originalCount&&File.ReadAllBytes(configPath).SequenceEqual(before),"Generating a draft does not replace steps or write the recipe");
|
||||
Check((await ReopenAgent()).AgentApiKey==model.AgentApiKey,"Successful analysis preserves the saved key");
|
||||
model.AgentDraftSteps[0].Description="把连接器放入盒子,盒内可见连接器";
|
||||
|
||||
@ -23,17 +23,31 @@ try
|
||||
using var handler=new AgentHttp();using var http=new HttpClient(handler);
|
||||
var client=new SopVideoDraftClient(http);
|
||||
var request=new SopVideoAnalysisRequest("装盒","按实际动作分两步",sample,["work"]);
|
||||
var connection=new SopAgentConnection("https://vision.invalid/custom/chat/completions","custom-vision","test-key");
|
||||
var connection=new SopAgentConnection("https://vision.invalid/custom/chat/completions","custom-vision","test-key",
|
||||
ContextLength:16384,MaxTokens:2048,Temperature:.4,TopP:.8,TimeoutSeconds:90);
|
||||
var models=await client.GetModelsAsync(connection.Endpoint,connection.ApiKey,default);
|
||||
Check(handler.Url=="https://vision.invalid/custom/models"&&handler.Authorization=="Bearer test-key"
|
||||
&&models.SequenceEqual(new[]{"a-vision","b-vision"}),"应从配置地址获取模型列表、鉴权并去重排序");
|
||||
var draft=await client.AnalyzeAsync(request,connection,default);
|
||||
Check(draft.Steps.Count==2&&draft.Steps[0].Region=="work","应解析并规范化已存在的区域引用");
|
||||
Check(handler.Url==connection.Endpoint&&handler.Authorization=="Bearer test-key","接口地址与密钥应使用用户配置");
|
||||
using(var body=JsonDocument.Parse(handler.Body!))
|
||||
{
|
||||
Check(body.RootElement.GetProperty("model").GetString()==connection.Model,"应使用配置的模型名");
|
||||
Check(body.RootElement.GetProperty("max_tokens").GetInt32()==2048
|
||||
&&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(parts.EnumerateArray().Count(p=>p.GetProperty("type").GetString()=="image_url")==3,"必须上传抽样图片");
|
||||
Check(parts[1].GetProperty("text").GetString()!.Contains("time=0.000s"),"必须发送时间戳");
|
||||
}
|
||||
var limited=false;
|
||||
try{await client.AnalyzeAsync(request,connection with {ContextLength=4096,MaxTokens=2048},default);}catch(ArgumentException){limited=true;}
|
||||
Check(limited,"上下文预算不足时应拒绝发送");
|
||||
var invalidSettings=false;
|
||||
try{SopVideoDraftClient.ValidateSettings(connection with {TopP=0});}catch(ArgumentException){invalidSettings=true;}
|
||||
Check(invalidSettings,"无效采样参数应被拒绝");
|
||||
Check(SopVideoSampler.Sample(path,3,default).Frames.Count==3,"最大抽帧数应支持3张");
|
||||
foreach(var bad in new[]{handler.Json.Replace("\"end_seconds\":4","\"end_seconds\":400"),handler.Json.Replace("\"WORK\"","\"invented\""),handler.Json.Replace("\"evidence_frame\":1","\"evidence_frame\":99"),"{\"steps\":null}"})
|
||||
{
|
||||
handler.Override=bad;var rejected=false;
|
||||
@ -61,7 +75,10 @@ sealed class AgentHttp:HttpMessageHandler
|
||||
public string Json="""{"summary":"放入并取走","warnings":[],"steps":[{"name":"放入零件","description":"盒子里有零件","start_seconds":0,"end_seconds":2,"region":"WORK","evidence_frame":1},{"name":"取走零件","description":"盒子里没有零件","start_seconds":2,"end_seconds":4,"region":"work","evidence_frame":2}]}""";
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage message,CancellationToken token)
|
||||
{
|
||||
Body=await message.Content!.ReadAsStringAsync(token);Url=message.RequestUri!.ToString();Authorization=message.Headers.Authorization?.ToString();
|
||||
Url=message.RequestUri!.ToString();Authorization=message.Headers.Authorization?.ToString();
|
||||
if(message.Method==HttpMethod.Get)
|
||||
return new(Status){Content=new StringContent("""{"data":[{"id":"b-vision"},{"id":"a-vision"},{"id":"a-vision"}]}""")};
|
||||
Body=await message.Content!.ReadAsStringAsync(token);
|
||||
return new(Status){Content=new StringContent(JsonSerializer.Serialize(new{choices=new[]{new{finish_reason=Finish,message=new{content=Override??Json}}}}),Encoding.UTF8,"application/json")};
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user