aisop/tests/VisionDecision.Smoke/D3Checks.cs

76 lines
4.8 KiB
C#

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") };
}
}
}