From 226f05fa210c28745dabea3488fe8dc00a31a54f Mon Sep 17 00:00:00 2001
From: tfarcraw <123211521@163.com>
Date: Fri, 13 Nov 2026 00:56:35 +0800
Subject: [PATCH] =?UTF-8?q?=E6=8E=A5=E5=85=A5D3=E5=8E=9F=E7=94=9F=E5=9B=BE?=
=?UTF-8?q?=E7=89=87=E6=8E=A5=E5=8F=A3=E5=B9=B6=E9=AA=8C=E8=AF=81=E5=AE=8C?=
=?UTF-8?q?=E6=88=90=E6=A6=82=E7=8E=87=E4=B8=8E=E5=BC=82=E5=B8=B8=E9=97=A8?=
=?UTF-8?q?=E6=8E=A7?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../Sop/D3VisionDecisionClient.cs | 58 ++++++++++++++
.../Sop/LayaVisionDecisionClient.cs | 3 +-
tests/VisionDecision.Smoke/D3Checks.cs | 75 +++++++++++++++++++
tests/VisionDecision.Smoke/Program.cs | 1 +
4 files changed, 136 insertions(+), 1 deletion(-)
create mode 100644 src/SopHelper.CrossPlatform.Engine/Sop/D3VisionDecisionClient.cs
create mode 100644 tests/VisionDecision.Smoke/D3Checks.cs
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/D3VisionDecisionClient.cs b/src/SopHelper.CrossPlatform.Engine/Sop/D3VisionDecisionClient.cs
new file mode 100644
index 0000000..ef425f8
--- /dev/null
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/D3VisionDecisionClient.cs
@@ -0,0 +1,58 @@
+using System.Diagnostics;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Security.Cryptography;
+using System.Text.Json;
+
+namespace SopHelper.Engine.Sop;
+
+/// D3-lite 原生 System One 图片接口;noul 是完成条件的正例概率。
+public sealed class D3VisionDecisionClient(HttpClient http) : IVisionDecisionClient
+{
+ public async Task DecideAsync(VisionDecisionRequest request, CancellationToken cancellationToken)
+ {
+ var endpoint = Environment.GetEnvironmentVariable("SOPHELPER_VISION_ENDPOINT")
+ ?? "http://127.0.0.1:8766/v1/systemone";
+ if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || uri.Scheme is not ("http" or "https"))
+ throw new InvalidOperationException("D3 视觉接口地址无效");
+ if (request.Jpeg.Length is 0 or > 10 * 1024 * 1024 || string.IsNullOrWhiteSpace(request.Criteria))
+ throw new InvalidOperationException("D3 需要有效的判定图和完成条件");
+
+ using var message = new HttpRequestMessage(HttpMethod.Post, uri);
+ var key = Environment.GetEnvironmentVariable("SOPHELPER_VISION_API_KEY");
+ if (!string.IsNullOrWhiteSpace(key)) message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);
+ message.Content = JsonContent.Create(new
+ {
+ state = $"当前步骤:{request.Step}。{request.Description}",
+ images = new[] { "data:image/jpeg;base64," + Convert.ToBase64String(request.Jpeg) },
+ questions = new
+ {
+ step_completed = new
+ {
+ type = "noul",
+ instructions = $"图片里是否满足这个完成条件:{request.Criteria}"
+ }
+ }
+ });
+ var timer = Stopwatch.StartNew();
+ using var response = await http.SendAsync(message, cancellationToken).ConfigureAwait(false);
+ if (!response.IsSuccessStatusCode) throw new InvalidOperationException($"D3 视觉接口 HTTP {(int)response.StatusCode}");
+ using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false));
+ var root = document.RootElement;
+ var answer = root.GetProperty("answers").GetProperty("step_completed");
+ if (answer.TryGetProperty("error", out _) || answer.GetProperty("type").GetString() != "noul")
+ throw new FormatException("D3 未返回有效的是非判定");
+ var probability = answer.GetProperty("noul").GetDouble();
+ if (!double.IsFinite(probability) || probability is < 0 or > 1)
+ throw new FormatException("D3 完成概率无效");
+ // 测试服务附带哈希时核对实际图片;标准 D3 服务没有此扩展字段也可使用。
+ if (root.TryGetProperty("usage", out var usage) && usage.TryGetProperty("image_sha256", out var hashes))
+ {
+ var expected = Convert.ToHexString(SHA256.HashData(request.Jpeg));
+ if (hashes.ValueKind != JsonValueKind.Array || hashes.GetArrayLength() != 1
+ || !string.Equals(hashes[0].GetString(), expected, StringComparison.OrdinalIgnoreCase))
+ throw new FormatException("D3 接收到的图片与判定帧不一致");
+ }
+ return new(probability >= .5, probability, $"D3-lite 完成概率 {probability:P1},请求耗时 {timer.Elapsed.TotalMilliseconds:F0}ms");
+ }
+}
diff --git a/src/SopHelper.CrossPlatform.Engine/Sop/LayaVisionDecisionClient.cs b/src/SopHelper.CrossPlatform.Engine/Sop/LayaVisionDecisionClient.cs
index 16ba2e1..cc6af05 100644
--- a/src/SopHelper.CrossPlatform.Engine/Sop/LayaVisionDecisionClient.cs
+++ b/src/SopHelper.CrossPlatform.Engine/Sop/LayaVisionDecisionClient.cs
@@ -64,8 +64,9 @@ public sealed class ConfiguredVisionDecisionClient(HttpClient http) : IVisionDec
public Task DecideAsync(VisionDecisionRequest request, CancellationToken cancellationToken)
=> Environment.GetEnvironmentVariable("SOPHELPER_VISION_PROVIDER")?.ToLowerInvariant() switch
{
+ "d3" or "d3-lite" => new D3VisionDecisionClient(http).DecideAsync(request, cancellationToken),
"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")
+ _ => throw new InvalidOperationException("SOPHELPER_VISION_PROVIDER 仅支持 d3-lite、laya 或 chat-completions")
};
}
diff --git a/tests/VisionDecision.Smoke/D3Checks.cs b/tests/VisionDecision.Smoke/D3Checks.cs
new file mode 100644
index 0000000..fb5b640
--- /dev/null
+++ b/tests/VisionDecision.Smoke/D3Checks.cs
@@ -0,0 +1,75 @@
+using System.Net;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using SopHelper.Engine.Sop;
+
+internal static class D3Checks
+{
+ 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_VISION_API_KEY"];
+ var before = names.Select(Environment.GetEnvironmentVariable).ToArray();
+ try
+ {
+ Environment.SetEnvironmentVariable(names[0], "d3-lite");
+ Environment.SetEnvironmentVariable(names[1], null);
+ Environment.SetEnvironmentVariable(names[2], null);
+ using var handler = new D3Http(); using var http = new HttpClient(handler);
+ var client = new ConfiguredVisionDecisionClient(http);
+ var request = new VisionDecisionRequest("配方", 1, "放入盒子", "查看盒子内部", "盒子里有红色和蓝色的零件", 42, DateTime.Now, [1, 2, 3]);
+ var decision = await client.DecideAsync(request, default);
+ Check(decision.Completed && decision.Confidence == .96, "D3 必须读取完成正例概率");
+ Check(handler.Url == "http://127.0.0.1:8766/v1/systemone", "D3 默认端点错误");
+ using var body = JsonDocument.Parse(handler.Body!);
+ Check(body.RootElement.GetProperty("images")[0].GetString() == "data:image/jpeg;base64,AQID", "D3 必须发送准确的 JPEG 字节");
+ Check(body.RootElement.GetProperty("questions").GetProperty("step_completed").GetProperty("instructions").GetString()!.Contains(request.Criteria), "D3 必须发送中文完成条件");
+ handler.Content = """{"answers":{"step_completed":{"type":"noul","noul":0.02}}}""";
+ decision = await client.DecideAsync(request, default);
+ Check(!decision.Completed && decision.Confidence == .02, "D3 不得将否定答案的置信度当成完成概率");
+ foreach (var content in new[] {
+ """{"answers":{"step_completed":{"type":"noul","noul":1.2}}}""",
+ """{"answers":{"step_completed":{"type":"choice","noul":0.99}}}""",
+ """{"answers":{"step_completed":{"type":"noul","noul":0.99,"error":"max_length_exceeded"}}}""",
+ """{"answers":{"step_completed":{"type":"noul"}}}""",
+ """{"answers":{"step_completed":{"type":"noul","noul":0.99}},"usage":{"image_sha256":["wrong"]}}""",
+ "not json" })
+ {
+ handler.Content = content;
+ var rejected = false;
+ try { await client.DecideAsync(request, default); } catch (Exception) { rejected = true; }
+ Check(rejected, "D3 异常响应和图片哈希错误必须拒绝");
+ }
+ handler.Content = """{"answers":{"step_completed":{"type":"noul","noul":0.99}}}""";
+ handler.Status = HttpStatusCode.ServiceUnavailable;
+ var httpRejected = false;
+ try { await client.DecideAsync(request, default); } catch (InvalidOperationException) { httpRejected = true; }
+ Check(httpRejected, "D3 HTTP 错误不得放行");
+ if (args.Contains("--d3-live"))
+ {
+ var image = await File.ReadAllBytesAsync(args.Last());
+ using var liveHttp = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };
+ var result = await new ConfiguredVisionDecisionClient(liveHttp).DecideAsync(request with
+ {
+ Step = "颜色检查", Description = "查看手里的物品", Criteria = "手里的东西有红色也有蓝色", Jpeg = image
+ }, default);
+ Check(result.Completed && result.Confidence >= .85, "D3 真实图片未通过已知颜色正样本");
+ Console.WriteLine($"PASS: D3 真实图片接口:{result.Reason}");
+ }
+ }
+ finally { for (int i = 0; i < names.Length; i++) Environment.SetEnvironmentVariable(names[i], before[i]); }
+ }
+
+ private sealed class D3Http : HttpMessageHandler
+ {
+ public string? Body, Url;
+ public HttpStatusCode Status = HttpStatusCode.OK;
+ public string Content = JsonSerializer.Serialize(new { answers = new { step_completed = new { type = "noul", noul = .96 } }, usage = new { image_sha256 = new[] { Convert.ToHexString(SHA256.HashData(new byte[] { 1, 2, 3 })) } } });
+ protected override async Task SendAsync(HttpRequestMessage request, CancellationToken token)
+ {
+ Body = await request.Content!.ReadAsStringAsync(token); Url = request.RequestUri!.ToString();
+ return new(Status) { Content = new StringContent(Content, Encoding.UTF8, "application/json") };
+ }
+ }
+}
diff --git a/tests/VisionDecision.Smoke/Program.cs b/tests/VisionDecision.Smoke/Program.cs
index 5a2c8d8..42b533a 100644
--- a/tests/VisionDecision.Smoke/Program.cs
+++ b/tests/VisionDecision.Smoke/Program.cs
@@ -110,6 +110,7 @@ try
}
finally { for (int i = 0; i < names.Length; i++) Environment.SetEnvironmentVariable(names[i], previous[i]); }
await LayaChecks.RunAsync(args);
+await D3Checks.RunAsync(args);
Console.WriteLine("PASS: 手部触发、单请求、AI 门控、证据帧、限流、超时、旧结果失效、配方往返、兼容 HTTP 消息及错误响应、Laya 原生适配与复核语义");
sealed class FakeDecision : IVisionDecisionClient