diff --git a/HAND_AI.md b/HAND_AI.md index 59633d8..eb5fa3f 100644 --- a/HAND_AI.md +++ b/HAND_AI.md @@ -10,7 +10,7 @@ ## 标准视频 Agent 助手 -配方编辑器的“Agent助手”页支持从标准 SOP 视频生成步骤草稿。先在“SOP流程视频”页停止并保存录像,或选择本地视频;填写完整的 Chat Completions 地址(如 `https://your-server/v1/chat/completions`)、模型名和密钥,可补充工艺背景或拆分要求,然后点击“生成步骤”。地址可自行设置,不绑定服务商。 +配方编辑器的“Agent助手”页支持从标准 SOP 视频生成步骤草稿。先在“SOP流程视频”页停止并保存录像,或选择本地视频;填写服务基础地址(如 `https://your-server/v1`)或完整 Chat Completions 地址、模型名和密钥,可补充工艺背景或拆分要求,然后点击“生成步骤”。地址可自行设置,不绑定服务商。获取模型时使用同一密钥;401 表示密钥缺失或无效,403 表示无权限,404 表示接口路径不存在,超时和连接失败也会显示原因。 助手采用工具调用循环:首轮将录像路径和任务交给模型,模型调用 `get_video_info` 获取时长、尺寸和读取预算,再调用 `read_video_frames(times_seconds)` 自主选择要查看的时间点,可继续查看其他片段、动作前后和细节,最后提交步骤 JSON。本地工具仅能读取本次选中的视频,不提供任意文件或命令执行。没有实际读取视频便提交草稿会被拒绝。不会固定取三张图一次问答,也不上传整段视频文件。 diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml index c83dbed..d49802a 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml @@ -468,7 +468,7 @@ - + diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs b/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs index 2920cf2..d8ec377 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/SopVideoAgentViewModel.cs @@ -156,6 +156,7 @@ public partial class RecipeEditorViewModel { if (!_agentSettingsLoaded || _agentClosed) return; _modelDiscoveryCancellation?.Cancel(); + _modelDiscoveryCancellation = null; 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)); @@ -172,15 +173,32 @@ public partial class RecipeEditorViewModel 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} 个模型。"; + if (!IsAgentBusy) AgentStatus = models.Count == 0 ? "没有可用模型。" : $"已获取 {models.Count} 个模型。"; } - catch (OperationCanceledException) { } - catch (Exception) { if (immediate && !IsAgentBusy) AgentStatus = "模型列表获取失败。"; } + catch (OperationCanceledException) { ReportDiscoveryError("获取模型超时。"); } + catch (HttpRequestException error) + { + ReportDiscoveryError(error.StatusCode switch + { + System.Net.HttpStatusCode.Unauthorized => "获取模型失败:401,请填写正确的密钥。", + System.Net.HttpStatusCode.Forbidden => "获取模型失败:403,密钥无访问权限。", + System.Net.HttpStatusCode.NotFound => "获取模型失败:404,请检查接口地址。", + { } status => $"获取模型失败:HTTP {(int)status}。", + _ => "无法连接模型服务。" + }); + } + catch (Exception) { ReportDiscoveryError("模型列表响应格式无效。"); } finally { if (ReferenceEquals(_modelDiscoveryCancellation, cancellation)) _modelDiscoveryCancellation = null; cancellation.Dispose(); } + + void ReportDiscoveryError(string message) + { + if (ReferenceEquals(_modelDiscoveryCancellation, cancellation) && !_agentClosed && !IsAgentBusy) + AgentStatus = message; + } } private void UpdateAgentDefaultVideo() { diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopAgentEndpoints.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopAgentEndpoints.cs new file mode 100644 index 0000000..9bda2f9 --- /dev/null +++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopAgentEndpoints.cs @@ -0,0 +1,21 @@ +namespace SopHelper.Engine.SopAgent; + +public static class SopAgentEndpoints +{ + public static Uri Chat(string endpoint) => Resolve(endpoint, "chat/completions"); + public static Uri Models(string endpoint) => Resolve(endpoint, "models"); + + private static Uri Resolve(string endpoint, string route) + { + if (!Uri.TryCreate(endpoint.Trim(), UriKind.Absolute, out var uri) || uri.Scheme is not ("http" or "https")) + throw new ArgumentException("接口地址无效"); + var builder = new UriBuilder(uri) { Fragment = "" }; + var path = builder.Path.TrimEnd('/'); + if (path.EndsWith("/systemone", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("D3 判定接口不支持 Agent"); + if (path.EndsWith("/chat/completions", StringComparison.OrdinalIgnoreCase)) path = path[..^"/chat/completions".Length]; + else if (path.EndsWith("/models", StringComparison.OrdinalIgnoreCase)) path = path[..^"/models".Length]; + builder.Path = path + "/" + route; + return builder.Uri; + } +} diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs index 64339dc..3598cab 100644 --- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs +++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoAgentClient.cs @@ -21,10 +21,8 @@ public sealed class SopVideoAgentClient(HttpClient http) : ISopVideoDraftClient using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); timeout.CancelAfter(TimeSpan.FromSeconds(connection.TimeoutSeconds)); token = timeout.Token; - 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)) - throw new ArgumentException("D3 不支持 Agent 工具调用"); + var endpoint = SopAgentEndpoints.Chat(connection.Endpoint); + if (string.IsNullOrWhiteSpace(connection.Model)) throw new ArgumentException("请设置模型名"); if (request.MaxFramesPerRead is < 2 or > 60) throw new ArgumentException("每次读取帧数须为 2–60"); var observed = chatting ? request.Video.Frames.ToList() : new List(); if (observed.Count > 60 || observed.Where((frame, index) => frame.Index != index).Any()) throw new ArgumentException("视频上下文无效"); diff --git a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs index 4a6390e..8864e27 100644 --- a/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs +++ b/src/SopHelper.CrossPlatform.Engine/SopAgent/SopVideoDraftClient.cs @@ -46,13 +46,7 @@ public sealed class SopVideoDraftClient(HttpClient http) : ISopVideoDraftClient { public async Task> 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); + using var message = new HttpRequestMessage(HttpMethod.Get, SopAgentEndpoints.Models(endpoint)); if (!string.IsNullOrWhiteSpace(apiKey)) message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); using var response = await http.SendAsync(message, token).ConfigureAwait(false); response.EnsureSuccessStatusCode(); @@ -78,10 +72,8 @@ public sealed class SopVideoDraftClient(HttpClient http) : ISopVideoDraftClient + 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)) - throw new ArgumentException("D3 判定接口不能生成步骤,请设置可生成文字的视觉 Chat Completions 接口"); + var endpoint = SopAgentEndpoints.Chat(connection.Endpoint); + if (string.IsNullOrWhiteSpace(connection.Model)) throw new ArgumentException("请设置模型名"); var content = new List { new { type = "text", text = JsonSerializer.Serialize(new { recipe = request.Recipe, instructions = request.Instructions, diff --git a/tests/SopVideoAgent.Smoke/Program.cs b/tests/SopVideoAgent.Smoke/Program.cs index 41101f3..f35a97c 100644 --- a/tests/SopVideoAgent.Smoke/Program.cs +++ b/tests/SopVideoAgent.Smoke/Program.cs @@ -31,6 +31,13 @@ try 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","接口地址与密钥应使用用户配置"); + foreach(var endpoint in new[]{"https://vision.invalid/custom","https://vision.invalid/custom/","https://vision.invalid/custom/models","https://vision.invalid/custom/chat/completions"}) + { + Check(SopAgentEndpoints.Chat(endpoint).ToString()=="https://vision.invalid/custom/chat/completions" + &&SopAgentEndpoints.Models(endpoint).ToString()=="https://vision.invalid/custom/models","基础地址、完整接口和模型列表地址应统一解析"); + } + Check(SopAgentEndpoints.Models("http://192.168.0.188:11438/v1").ToString()=="http://192.168.0.188:11438/v1/models", + "用户提供的v1基础地址应正确获取模型"); using(var body=JsonDocument.Parse(handler.Body!)) { Check(body.RootElement.GetProperty("model").GetString()==connection.Model,"应使用配置的模型名"); @@ -131,12 +138,16 @@ try var truncated=false;try{await client.AnalyzeAsync(request,connection,default);}catch(FormatException){truncated=true;} Check(truncated,"截断输出不能作为步骤草稿"); handler.Finish="stop";handler.Status=HttpStatusCode.Unauthorized; + var authFailure=false; + try{await client.GetModelsAsync("http://192.168.0.188:11438/v1","",default);} + catch(HttpRequestException error){authFailure=error.StatusCode==HttpStatusCode.Unauthorized;} + Check(authFailure,"模型列表鉴权失败必须保留401状态以便界面显示原因"); var failed=false;try{await client.AnalyzeAsync(request,connection,default);}catch(InvalidOperationException){failed=true;} Check(failed,"HTTP 失败不能生成步骤"); using var cancellation=new CancellationTokenSource();cancellation.Cancel(); var cancelled=false;try{SopVideoSampler.Sample(path,4,cancellation.Token);}catch(OperationCanceledException){cancelled=true;} Check(cancelled,"抽帧必须支持取消"); - Console.WriteLine("PASS: Agent路径输入、工具多轮读取真实视频、模型自主选时、未读拒绝、越界拒绝;模型列表、参数、设置、步骤校验与取消"); + Console.WriteLine("PASS: Agent视频工具、聊天修改、模型列表与401鉴权、v1地址解析、参数、步骤校验与取消"); } finally{Directory.Delete(folder,true);}