接入本机Laya视觉决策服务并保留复核语义

This commit is contained in:
tfarcraw 2026-11-12 16:08:13 +08:00
parent e79a58f5b5
commit e9dc0d38d4
6 changed files with 272 additions and 3 deletions

View File

@ -8,9 +8,46 @@
## 配置接口
### 本机 E:\LayaAI
已支持该目录中的 Vega/Laya 原生视觉服务,无需将 Laya 改造成聊天接口。它使用 `POST /v1/vision/decide`,通过 multipart 上传 `file` 和 `questions`,对每个步骤提交一个 `noul` 是非问题。当前步骤完成判据写入问题,正例概率读取 `answers.step_completed.noul`,不使用“否定答案也可能很高”的 `answer_confidence` 作为完成概率。
从仓库根目录运行:
```powershell
# 启动/复用本机服务并打开 SOP 程序,默认保留模型复核状态。
pwsh -File tools/Start-HandAiLaya.ps1
# 显式尝试未标定工位的自动推进:仍检查配方置信度、拒答和无界状态。
pwsh -File tools/Start-HandAiLaya.ps1 -AllowUncalibrated
# 只准备服务并检查健康,不打开 SOP 界面。
pwsh -File tools/Start-HandAiLaya.ps1 -CheckOnly
```
脚本只为其启动的 SOP 子进程设置环境变量,不永久更改系统设置。服务已在运行时复用;未运行时隐藏启动 `E:\LayaAI\server.py`,日志保存至 `artifacts/laya-integration/`,并写入 Laya 的 `server.pid`。关闭 SOP 后服务继续运行,可用 `E:\LayaAI\stop.bat` 停止。
也可以手动设置:
```powershell
$env:SOPHELPER_VISION_PROVIDER = 'laya'
$env:SOPHELPER_VISION_ENDPOINT = 'http://127.0.0.1:8000/v1/vision/decide'
# 只有明确进行未标定自动推进实验时才设置为 true;缺省保留 review。
$env:SOPHELPER_LAYA_ALLOW_UNCALIBRATED = 'false'
```
Laya 不需要 `SOPHELPER_VISION_MODEL`。本机原服务无鉴权,不需要密钥。图像最大 10MB,服务内部缩小到 512×512 以内。细小缺陷或零件可能需要后续增加区域裁剪。
当前服务固定返回 `vision_calibrated=false`、`route=review`。默认不会自动完成步骤;只有显式设置 `-AllowUncalibrated`(或对应环境变量为 `true`)才允许这类结果按实验阈值判断。实验模式仍不绕过 `abstain=true`、`unbound=true`、未知路由或已标定但要求复核的结果。正常的已标定 `route=auto` 结果可按阈值放行。
已用 `E:\LayaAI\vision-dog-sample.jpg` 完成真实 HTTP/本地 CUDA 模型联调,返回正例概率约 99.3%,同时正确保留未标定复核状态。这只验证连通性与协议,没有验证 SOP 工位准确率。
### Chat Completions 服务
在启动程序的 PowerShell 中设置环境变量,再从同一窗口运行实验分支:
```powershell
$env:SOPHELPER_VISION_PROVIDER = 'chat-completions'
$env:SOPHELPER_VISION_ENDPOINT = 'https://你的服务地址/v1/chat/completions'
$env:SOPHELPER_VISION_MODEL = '你的视觉模型名称'
$env:SOPHELPER_VISION_API_KEY = '你的服务密钥'
@ -51,13 +88,15 @@ dotnet run --project src/SopHelper.Avalonia -p:BundlePythonRuntime=false
不要在纯手部实验配方中使用 `object_*`、`hand_near_object`、`must_keep` 或 `required_objects`;这些物体规则仍保留原有 YOLO 路径。请把需要检查的物料与装配结果写入 AI 完成判据。混合配方仍可使用原有目标检测。
模型自报置信度用于实验门控,尚未经过工位数据标定。需要用真实操作、未完成、遮挡和缺件样本验证误判率及响应时间。本次本地检查使用模拟模型服务,没有调用外部视觉模型或验证现场准确率。
模型输出概率/置信度用于实验门控,尚未经过工位数据标定。需要用真实操作、未完成、遮挡和缺件样本验证误判率及响应时间。自动回归检查使用模拟服务,另已验证本机 Laya 的真实图片接口;没有调用外部视觉模型或验证现场准确率。
## 验证
```powershell
dotnet build SopHelper.Avalonia.slnx -p:BundlePythonRuntime=false
dotnet run --project tests/VisionDecision.Smoke
# 可选:服务启动后检查本机真实模型。
dotnet run --project tests/VisionDecision.Smoke -- --laya-live E:\LayaAI\vision-dog-sample.jpg
dotnet run --project tests/Avalonia.Smoke -p:BundlePythonRuntime=false -- --vision-only
dotnet run --project tests/Avalonia.Smoke -p:BundlePythonRuntime=false -- --process-images-only
```

View File

@ -102,7 +102,7 @@ public class SopPageViewModel : ViewModelBase
_camera = camera;
_pipeline = pipeline;
_engine = engine;
_engine.VisionDecisionClient ??= new ChatCompletionsVisionClient(VisionHttp);
_engine.VisionDecisionClient ??= new ConfiguredVisionDecisionClient(VisionHttp);
_pipeline.ShouldDetectHands = () => _engine.RequiresHandDetection;
_dialogs = dialogs;
_dispatcher = Dispatcher.CurrentDispatcher;

View File

@ -0,0 +1,71 @@
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
namespace SopHelper.Engine.Sop;
/// <summary>对接 E:\LayaAI 的图片上传接口,保留模型拒答与复核语义。</summary>
public sealed class LayaVisionDecisionClient(HttpClient http) : IVisionDecisionClient
{
public async Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request, CancellationToken cancellationToken)
{
var endpoint = Environment.GetEnvironmentVariable("SOPHELPER_VISION_ENDPOINT")
?? "http://127.0.0.1:8000/v1/vision/decide";
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || uri.Scheme is not ("http" or "https"))
throw new InvalidOperationException("Laya 视觉接口地址无效");
if (request.Jpeg.Length is 0 or > 10 * 1024 * 1024)
throw new InvalidOperationException("Laya 判定图必须介于 1 字节与 10MB 之间");
var questions = new
{
step_completed = new
{
type = "noul",
instructions = $"请只依据图片判断当前步骤是否已经完成。步骤:{request.Step}。说明:{request.Description}。完成判据:{request.Criteria}。所有判据均须满足;遮挡、不确定、看不到关键部位时回答否。手部动作本身不能作为完成证据。"
}
};
using var message = new HttpRequestMessage(HttpMethod.Post, uri);
using var form = new MultipartFormDataContent();
form.Add(new StringContent(JsonSerializer.Serialize(questions), Encoding.UTF8), "questions");
var image = new ByteArrayContent(request.Jpeg);
image.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
form.Add(image, "file", $"frame-{request.FrameId}.jpg");
message.Content = form;
var key = Environment.GetEnvironmentVariable("SOPHELPER_VISION_API_KEY");
if (!string.IsNullOrWhiteSpace(key)) message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);
using var response = await http.SendAsync(message, cancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode) throw new InvalidOperationException($"Laya 视觉接口 HTTP {(int)response.StatusCode}");
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false));
var root = document.RootElement;
if (root.GetProperty("modality").GetString() != "image") throw new FormatException("Laya 未返回图片判定");
var calibrated = root.GetProperty("vision_calibrated").GetBoolean();
var answer = root.GetProperty("answers").GetProperty("step_completed");
if (answer.GetProperty("type").GetString() != "noul") throw new FormatException("Laya 未返回是非判定");
var probability = answer.GetProperty("noul").GetDouble();
if (!double.IsFinite(probability) || probability is < 0 or > 1) throw new FormatException("Laya 完成概率无效");
var abstain = answer.GetProperty("abstain").GetBoolean();
var unbound = answer.GetProperty("unbound").GetBoolean();
var route = answer.GetProperty("route").GetString();
var experimental = string.Equals(Environment.GetEnvironmentVariable("SOPHELPER_LAYA_ALLOW_UNCALIBRATED"), "true", StringComparison.OrdinalIgnoreCase);
// 仅显式开启工位实验时允许未标定的 review 结果;仍不绕过拒答、无界或其他路由。
var acceptedRoute = route == "auto" && calibrated || route == "review" && !calibrated && experimental;
var completed = probability >= 0.5 && !abstain && !unbound && acceptedRoute;
var reason = $"Laya 完成概率 {probability:P1},route={route},图片标定={(calibrated ? "是" : "否")}";
if (abstain || unbound) reason += ",模型拒答或结果无界,未放行";
else if (!acceptedRoute) reason += ",需要复核,未放行";
else if (!calibrated) reason += ",按显式开启的未标定实验模式判断";
return new(completed, probability, reason);
}
}
/// <summary>每次取图时读取配置,切换服务无需替换引擎实例。</summary>
public sealed class ConfiguredVisionDecisionClient(HttpClient http) : IVisionDecisionClient
{
public Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request, CancellationToken cancellationToken)
=> Environment.GetEnvironmentVariable("SOPHELPER_VISION_PROVIDER")?.ToLowerInvariant() switch
{
"laya" => new LayaVisionDecisionClient(http).DecideAsync(request, cancellationToken),
null or "" or "chat-completions" => new ChatCompletionsVisionClient(http).DecideAsync(request, cancellationToken),
_ => throw new InvalidOperationException("SOPHELPER_VISION_PROVIDER 仅支持 laya 或 chat-completions")
};
}

View File

@ -0,0 +1,100 @@
using System.Net;
using System.Text;
using System.Text.Json;
using SopHelper.Engine.Sop;
internal static class LayaChecks
{
public static async Task RunAsync(string[] args)
{
static void Check(bool value, string message) { if (!value) throw new Exception(message); }
string[] names = ["SOPHELPER_VISION_PROVIDER", "SOPHELPER_VISION_ENDPOINT", "SOPHELPER_LAYA_ALLOW_UNCALIBRATED", "SOPHELPER_VISION_MODEL"];
var before = names.Select(Environment.GetEnvironmentVariable).ToArray();
try
{
Environment.SetEnvironmentVariable(names[0], "laya");
Environment.SetEnvironmentVariable(names[1], null);
Environment.SetEnvironmentVariable(names[2], null);
Environment.SetEnvironmentVariable(names[3], null);
var request = new VisionDecisionRequest("测试配方", 1, "安装底座", "放入夹具", "底座已放入定位夹具", 42, DateTime.Now, [1, 2, 3]);
using var handler = new LayaHttp(); using var http = new HttpClient(handler);
var client = new ConfiguredVisionDecisionClient(http);
var decision = await client.DecideAsync(request, default);
Check(!decision.Completed && decision.Confidence == .97 && decision.Reason.Contains("需要复核"), "Laya 未标定 review 结果默认不能放行");
Check(handler.Url == "http://127.0.0.1:8000/v1/vision/decide", "Laya 默认使用本机原生端点");
Check(handler.Fields?.GetProperty("step_completed").GetProperty("type").GetString() == "noul"
&& handler.Fields?.GetProperty("step_completed").GetProperty("instructions").GetString()?.Contains(request.Criteria) == true,
"Laya 应提交 noul 问题与当前步骤完成判据");
Check(handler.HasImage, "Laya 应使用 multipart 上传准确的图片字节");
Environment.SetEnvironmentVariable(names[2], "true");
Check((await client.DecideAsync(request, default)).Completed, "显式开启后可实验未标定的高概率结果");
handler.Abstain = true;
Check(!(await client.DecideAsync(request, default)).Completed, "实验模式仍不能绕过拒答");
handler.Abstain = false; handler.Unbound = true;
Check(!(await client.DecideAsync(request, default)).Completed, "实验模式仍不能绕过无界结果");
handler.Unbound = false; handler.Probability = .03;
var negative = await client.DecideAsync(request, default);
Check(!negative.Completed && negative.Confidence == .03, "完成概率必须用 noul 正例概率,而非否定答案的高置信度");
handler.Probability = .97; handler.Calibrated = true;
Check(!(await client.DecideAsync(request, default)).Completed, "已标定但需要复核的结果不能被实验开关绕过");
handler.Route = "auto";
Check((await client.DecideAsync(request, default)).Completed, "已标定自动路由可确认完成");
handler.Route = "unknown";
Check(!(await client.DecideAsync(request, default)).Completed, "未知路由不能放行");
handler.BadResponse = true;
var rejected = false;
try { await client.DecideAsync(request, default); } catch (Exception) { rejected = true; }
Check(rejected, "缺失结构字段不能放行");
Environment.SetEnvironmentVariable(names[0], "invalid");
rejected = false;
try { await client.DecideAsync(request, default); } catch (InvalidOperationException) { rejected = true; }
Check(rejected, "未知 provider 不得静默选择其他模型");
if (args.Contains("--laya-live"))
{
Environment.SetEnvironmentVariable(names[0], "laya");
Environment.SetEnvironmentVariable(names[2], null);
using var liveHttp = new HttpClient { Timeout = TimeSpan.FromSeconds(180) };
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(180));
var imagePath = args.Last();
var image = await File.ReadAllBytesAsync(imagePath, timeout.Token);
var live = await new ConfiguredVisionDecisionClient(liveHttp).DecideAsync(
request with { Step = "示例图连通性验证", Description = "检查图片中是否可见狗", Criteria = "图片中可见一只狗", Jpeg = image }, timeout.Token);
Check(!live.Completed && live.Reason.Contains("需要复核"), "本机真实服务未标定结果应保留复核语义");
Console.WriteLine($"PASS: Laya 真实 HTTP/模型联调:{live.Reason}");
}
}
finally { for (int i = 0; i < names.Length; i++) Environment.SetEnvironmentVariable(names[i], before[i]); }
}
private sealed class LayaHttp : HttpMessageHandler
{
public bool Abstain, Unbound, Calibrated, BadResponse, HasImage;
public double Probability = .97;
public string Route = "review";
public string? Url;
public JsonElement? Fields;
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Url = request.RequestUri!.ToString();
var multipart = request.Content as MultipartFormDataContent ?? throw new Exception("Must upload multipart");
foreach (var part in multipart)
{
if (part.Headers.ContentDisposition?.Name?.Trim('"') == "questions")
{
using var document = JsonDocument.Parse(await part.ReadAsStringAsync(cancellationToken));
Fields = document.RootElement.Clone();
}
if (part.Headers.ContentDisposition?.Name?.Trim('"') == "file")
HasImage = (await part.ReadAsByteArrayAsync(cancellationToken)).SequenceEqual(new byte[] { 1, 2, 3 })
&& part.Headers.ContentType?.MediaType == "image/jpeg";
}
var data = BadResponse ? "{}" : JsonSerializer.Serialize(new
{
modality = "image", vision_calibrated = Calibrated,
answers = new { step_completed = new { type = "noul", noul = Probability, answer_confidence = .99, abstain = Abstain, unbound = Unbound, route = Route } }
});
return new(HttpStatusCode.OK) { Content = new StringContent(data, Encoding.UTF8, "application/json") };
}
}
}

View File

@ -109,7 +109,8 @@ try
Check(httpRejected, "HTTP 失败不得完成");
}
finally { for (int i = 0; i < names.Length; i++) Environment.SetEnvironmentVariable(names[i], previous[i]); }
Console.WriteLine("PASS: 手部触发、单请求、AI 门控、证据帧、限流、超时、旧结果失效、配方往返、兼容 HTTP 消息及错误响应");
await LayaChecks.RunAsync(args);
Console.WriteLine("PASS: 手部触发、单请求、AI 门控、证据帧、限流、超时、旧结果失效、配方往返、兼容 HTTP 消息及错误响应、Laya 原生适配与复核语义");
sealed class FakeDecision : IVisionDecisionClient
{

View File

@ -0,0 +1,58 @@
[CmdletBinding()]
param(
[string]$LayaRoot = 'E:\LayaAI',
[switch]$AllowUncalibrated,
[switch]$CheckOnly
)
$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path -Parent $PSScriptRoot
$env:SOPHELPER_VISION_PROVIDER = 'laya'
$env:SOPHELPER_VISION_ENDPOINT = 'http://127.0.0.1:8000/v1/vision/decide'
$env:SOPHELPER_LAYA_ALLOW_UNCALIBRATED = if ($AllowUncalibrated) { 'true' } else { 'false' }
function Get-VisionHealth {
try {
$health = Invoke-RestMethod -Uri 'http://127.0.0.1:8000/health/vision' -TimeoutSec 3
if ($health.status -eq 'ok' -and $health.model -eq 'vega-U/Qwen3.5-0.8B') { return $health }
} catch { }
return $null
}
$health = Get-VisionHealth
if ($null -eq $health) {
$python = Join-Path $LayaRoot '.venv\Scripts\python.exe'
$server = Join-Path $LayaRoot 'server.py'
if (!(Test-Path -LiteralPath $python) -or !(Test-Path -LiteralPath $server)) {
throw "Laya 服务文件缺失:$LayaRoot"
}
$logs = Join-Path $repoRoot 'artifacts\laya-integration'
New-Item -ItemType Directory -Path $logs -Force | Out-Null
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss-fff'
$process = Start-Process -FilePath $python -ArgumentList @('-u', ('"' + $server + '"')) `
-WorkingDirectory $LayaRoot -WindowStyle Hidden -PassThru `
-RedirectStandardOutput (Join-Path $logs "$stamp.stdout.log") `
-RedirectStandardError (Join-Path $logs "$stamp.stderr.log")
# 与 Laya 自带 stop.bat/stop.ps1 共享运行时 PID 记录。
Set-Content -LiteralPath (Join-Path $LayaRoot 'server.pid') -Value $process.Id -Encoding ascii
Write-Host "正在启动 Laya 服务,PID=$($process.Id),日志:$logs"
$deadline = [DateTime]::UtcNow.AddSeconds(120)
do {
$health = Get-VisionHealth
if ($null -ne $health) { break }
if ($process.HasExited) { throw "Laya 启动失败,请查看 $logs" }
Start-Sleep -Milliseconds 500
} while ([DateTime]::UtcNow -lt $deadline)
if ($null -eq $health) { throw "等待 Laya 就绪超时,请查看 $logs" }
}
Write-Host "Laya 视觉接口已就绪,模型:$($health.model),已加载:$($health.loaded)"
if ($AllowUncalibrated) {
Write-Host '当前使用未标定工位实验模式;模型拒答或结果无界时仍不会推进步骤。'
} else {
Write-Host '当前保留模型复核状态,未标定 review 结果不会自动推进步骤。'
}
if ($CheckOnly) { return }
Push-Location $repoRoot
try {
& dotnet run --project src/SopHelper.Avalonia -p:BundlePythonRuntime=false
if ($LASTEXITCODE -ne 0) { throw "SOP 程序退出,代码:$LASTEXITCODE" }
} finally { Pop-Location }