using System.Text.Json; using System.Text.Json.Nodes; using XFEExtension.NetCore.XUnit.Assertions; using XFEExtension.NetCore.XUnit.Attributes; namespace ChaoXingAutoClass.Test; [TestFixture] public sealed class BatchingTests { [TestCase(1, 1)] [TestCase(30, 1)] [TestCase(31, 2)] [TestCase(61, 3)] public async Task OneAnswerCallPerThirtyQuestionsAndOneResearchPassPerPaper(int count, int calls) { var observed = new List(); var references = new References(); using var http = new HttpClient(new AgentTests.StubHandler(async request => { var rows = Inputs(await request.Content!.ReadAsStringAsync()); observed.Add(rows.Length); return AgentTests.Ok(Response(rows)); })); var agent = new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false }, references); var usage = new List(); agent.UsageReceived += usage.Add; var result = await agent.AnswerAsync("测试作业", "材料", Questions(count), CancellationToken.None); Assert.Equal(calls, observed.Count); Assert.True(observed.All(n => n is > 0 and <= 30)); Assert.Equal(count, observed.Sum()); Assert.Equal(count, result.Answers.Length); Assert.Equal(count, result.Answers.Select(a => a.QuestionId).Distinct().Count()); Assert.Equal(1, references.Calls); Assert.Equal(calls, usage.Count); Assert.True(usage.All(u => u.Purpose == "answer-initial" && u.TotalTokens == 150)); } [Test] public async Task MultipleChoiceReviewIsReturnedInTheSameSingleAnswerCall() { var calls = 0; using var http = new HttpClient(new AgentTests.StubHandler(async request => { calls++; return AgentTests.Ok(Response(Inputs(await request.Content!.ReadAsStringAsync()))); })); var agent = new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false }); var q = Questions(1)[0] with { Kind = QuestionKind.Multiple }; var result = await agent.AnswerAsync("多选", "材料", [q], CancellationToken.None); Assert.Equal(1, calls); Assert.Equal(1, result.Reviews!.Length); Assert.Equal(2, result.Reviews[0].Options.Length); } [Test] public async Task StrictModeUncertainOptionCannotTriggerExtraPaidCallsOrPassReview() { var calls = 0; using var http = new HttpClient(new AgentTests.StubHandler(async request => { calls++; return AgentTests.Ok(Response(Inputs(await request.Content!.ReadAsStringAsync()), .79)); })); var agent = new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false, StopOnUncertainAnswers = true }); var q = Questions(1)[0] with { Kind = QuestionKind.Multiple }; await Assert.ThrowsAsync(() => agent.AnswerAsync("多选", "材料", [q], CancellationToken.None)); Assert.Equal(1, calls); } [TestCase("low-confidence")] [TestCase("no-evidence")] [TestCase("missing-review")] public async Task DefaultUncertainOptionReturnsOriginalAnswerWithWarningAndOneCall(string issue) { var calls = 0; using var http = new HttpClient(new AgentTests.StubHandler(async request => { calls++; var body = JsonNode.Parse(Response(Inputs(await request.Content!.ReadAsStringAsync()), .1))!; var response = JsonNode.Parse(body["choices"]![0]!["message"]!["content"]!.GetValue())!; if (issue == "no-evidence") response["reviews"]![0]!["options"]![0]!["evidence"] = ""; if (issue == "missing-review") response.AsObject().Remove("reviews"); body["choices"]![0]!["message"]!["content"] = response.ToJsonString(); return AgentTests.Ok(body.ToJsonString()); })); var questions = new[] { Questions(1)[0] with { Kind = QuestionKind.Multiple } }; var result = await new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false }).AnswerAsync("多选", "材料", questions, CancellationToken.None); Assert.Equal(1, calls); Assert.Equal(new[] { "A", "B" }, result.Answers[0].Choices); Assert.Equal(.9, result.Answers[0].Confidence); Assert.True(result.Warnings!.Length > 0); if (issue != "missing-review") Assert.Equal(.1, result.Reviews![0].Options[0].Confidence); } [Test] public async Task DefaultMalformedResponseStopsWithoutAnotherAnswerRequest() { var calls = 0; using var http = new HttpClient(new AgentTests.StubHandler(_ => { calls++; return Task.FromResult(AgentTests.Ok("{\"choices\":[{\"message\":{\"content\":\"{broken\"}}]}")); })); var agent = new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false }); await Assert.ThrowsAsync(() => agent.AnswerAsync("题目", "材料", Questions(1), CancellationToken.None)); Assert.Equal(1, calls); } [Test] public async Task ThirtyMixedQuestionsWithInlineOptionReviewsRemainCompleteInOneCall() { var calls = 0; using var http = new HttpClient(new AgentTests.StubHandler(async request => { calls++; var body = JsonNode.Parse(Response(Inputs(await request.Content!.ReadAsStringAsync())))!; var content = body["choices"]![0]!["message"]!; var result = JsonNode.Parse(content["content"]!.GetValue())!; foreach (var review in result["reviews"]!.AsArray()) result["answers"]!.AsArray().Single(a => a!["questionId"]!.GetValue() == review!["questionId"]!.GetValue())!["optionReviews"] = review!["options"]!.DeepClone(); result.AsObject().Remove("reviews"); content["content"] = result.ToJsonString(); return AgentTests.Ok(body.ToJsonString()); })); var questions = Questions(30).Select((q, i) => i >= 20 ? q with { Kind = QuestionKind.Multiple } : q).ToArray(); var result = await new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false }).AnswerAsync("整卷", "材料", questions, CancellationToken.None); Assert.Equal(1, calls); Assert.Equal(30, result.Answers.Length); Assert.Equal(10, result.Reviews!.Length); Assert.Null(AnswerValidator.Validate(questions, result.Answers, .8)); } private static QuestionSnapshot[] Questions(int count) => Enumerable.Range(1, count).Select(i => new QuestionSnapshot("q" + i, QuestionKind.Single, "合成题 " + i, [new("A", "项目一"), new("B", "项目二")], "f", i)).ToArray(); private static JsonElement[] Inputs(string body) { using var document = JsonDocument.Parse(body); return document.RootElement.GetProperty("messages")[1].GetProperty("content").EnumerateArray() .Where(p => p.GetProperty("type").GetString() == "text").Select(p => p.GetProperty("text").GetString()!) .Where(t => t.StartsWith('{')).Select(t => JsonDocument.Parse(t).RootElement.Clone()).Where(q => q.TryGetProperty("id", out _)).ToArray(); } private static string Response(JsonElement[] rows, double optionConfidence = .9) { var answer = new { summary = "合成完整应答", answers = rows.Select(q => new { questionId = q.GetProperty("id").GetString(), choices = q.GetProperty("kind").GetString() == "Multiple" ? new[] { "A", "B" } : new[] { "A" }, text = "", confidence = .9, grounded = true, explanation = "题意符合材料", evidence = "合成规范定义" }), reviews = rows.Where(q => q.GetProperty("kind").GetString() == "Multiple").Select(q => new { questionId = q.GetProperty("id").GetString(), options = new[] { "A", "B" }.Select(key => new { key, selected = true, confidence = optionConfidence, reason = "符合材料", evidence = "合成规范定义" }) }) }; return JsonSerializer.Serialize(new { choices = new[] { new { message = new { content = JsonSerializer.Serialize(answer) } } }, usage = new { prompt_tokens = 100, completion_tokens = 50, total_tokens = 150 } }); } private sealed class References : ILessonReferenceProvider { public int Calls; public Task> GatherAsync(string chapter, string knowledge, IReadOnlyList questions, CancellationToken token) { Calls++; return Task.FromResult>([new("合成规范", "https://example.test/spec", "项目一与项目二符合定义。", DateTimeOffset.Now)]); } } }