接入D3原生图片接口并验证完成概率与异常门控
This commit is contained in:
parent
09e2481878
commit
226f05fa21
@ -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;
|
||||
|
||||
/// <summary>D3-lite 原生 System One 图片接口;noul 是完成条件的正例概率。</summary>
|
||||
public sealed class D3VisionDecisionClient(HttpClient http) : IVisionDecisionClient
|
||||
{
|
||||
public async Task<VisionDecisionResult> 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");
|
||||
}
|
||||
}
|
||||
@ -64,8 +64,9 @@ public sealed class ConfiguredVisionDecisionClient(HttpClient http) : IVisionDec
|
||||
public Task<VisionDecisionResult> 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")
|
||||
};
|
||||
}
|
||||
|
||||
75
tests/VisionDecision.Smoke/D3Checks.cs
Normal file
75
tests/VisionDecision.Smoke/D3Checks.cs
Normal file
@ -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<HttpResponseMessage> 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") };
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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
|
||||
|
||||
Loading…
Reference in New Issue
Block a user