summaryrefslogtreecommitdiff
path: root/tests/Agent.Core.Tests/OllamaClientTests.cs
blob: 87a3e2051f1ba6c143552840e90eac886631d487 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
using System.Net;
using System.Text;
using System.Text.Json;
using Agent.App.Configuration;
using Agent.Core.Ollama;
using Agent.Core.Tools;

namespace Agent.Core.Tests;

public sealed class OllamaClientTests
{
    [Fact]
    public async Task Chat_sends_expected_request_and_returns_usage()
    {
        string? body = null;
        var handler = new StubHandler(async (request, _) =>
        {
            body = await request.Content!.ReadAsStringAsync();
            return Json(HttpStatusCode.OK, """{"message":{"role":"assistant","content":"done"},"prompt_eval_count":12,"eval_count":7}""");
        });
        OllamaClient client = Create(handler, options: new Dictionary<string, JsonElement>
        {
            ["temperature"] = JsonSerializer.SerializeToElement(0.2),
            ["seed"] = JsonSerializer.SerializeToElement(42)
        });

        OllamaResult result = await client.ChatAsync([new OllamaMessage("user", "hello")], 0.7, TestContext.Current.CancellationToken);

        Assert.Equal("done", result.Content);
        Assert.Equal(12, result.InputTokens);
        Assert.Equal(7, result.OutputTokens);
        using JsonDocument document = JsonDocument.Parse(body!);
        JsonElement root = document.RootElement;
        Assert.Equal("test-model", root.GetProperty("model").GetString());
        Assert.False(root.GetProperty("stream").GetBoolean());
        Assert.Equal(0.7, root.GetProperty("options").GetProperty("temperature").GetDouble());
        Assert.Equal(42, root.GetProperty("options").GetProperty("seed").GetInt32());
    }

    [Fact]
    public async Task Thinking_is_separated_from_final_content_and_not_discarded()
    {
        var handler = new StubHandler((_, _) => Task.FromResult(Json(HttpStatusCode.OK,
            """{"message":{"role":"assistant","thinking":"private reasoning","content":"final answer"},"prompt_eval_count":3,"eval_count":5}""")));
        var client = new OllamaClient(new HttpClient(handler),
            new OllamaSettings(new Uri("http://127.0.0.1:11434"), "test-model", true, "0", new Dictionary<string, JsonElement>()));

        OllamaResult result = await client.ChatAsync([new OllamaMessage("user", "hello")], null, TestContext.Current.CancellationToken);

        Assert.Equal("final answer", result.Content);
        Assert.Equal("private reasoning", result.Thinking);
    }

    [Fact]
    public async Task Thinking_level_and_assistant_thinking_history_follow_native_chat_schema()
    {
        string? body = null;
        var handler = new StubHandler(async (request, _) =>
        {
            body = await request.Content!.ReadAsStringAsync();
            return Json(HttpStatusCode.OK, """{"message":{"role":"assistant","content":"done"}}""");
        });
        var client = new OllamaClient(new HttpClient(handler),
            new OllamaSettings(new Uri("http://127.0.0.1:11434"), "test-model", "high", "0", new Dictionary<string, JsonElement>()));

        await client.ChatAsync([new OllamaMessage("assistant", "", ToolCalls: [], Thinking: "prior reasoning")], null,
            TestContext.Current.CancellationToken);

        using JsonDocument document = JsonDocument.Parse(body!);
        Assert.Equal("high", document.RootElement.GetProperty("think").GetString());
        Assert.Equal("prior reasoning", document.RootElement.GetProperty("messages")[0].GetProperty("thinking").GetString());
    }

    [Fact]
    public async Task Explicit_false_override_is_serialized_as_boolean_false()
    {
        string? body = null;
        var handler = new StubHandler(async (request, _) =>
        {
            body = await request.Content!.ReadAsStringAsync();
            return Json(HttpStatusCode.OK, """{"message":{"role":"assistant","content":"{}"}}""");
        });
        var client = new OllamaClient(new HttpClient(handler),
            new OllamaSettings(new Uri("http://127.0.0.1:11434"), "test-model", "high", "0", new Dictionary<string, JsonElement>()));
        using JsonDocument schema = JsonDocument.Parse("""{"type":"object"}""");

        await client.ChatStructuredAsync([new OllamaMessage("user", "json")], null, schema.RootElement.Clone(), false,
            TestContext.Current.CancellationToken);

        using JsonDocument document = JsonDocument.Parse(body!);
        Assert.False(document.RootElement.GetProperty("think").GetBoolean());
    }

    [Fact]
    public async Task Transient_failure_retries_three_times_with_configured_backoff()
    {
        int attempts = 0;
        var delays = new List<TimeSpan>();
        var handler = new StubHandler((_, _) =>
        {
            attempts++;
            return Task.FromResult(attempts < 4
                ? Json(HttpStatusCode.ServiceUnavailable, "busy")
                : Json(HttpStatusCode.OK, """{"message":{"role":"assistant","content":"ok"}}"""));
        });
        var client = new OllamaClient(new HttpClient(handler), Settings(), (delay, _) =>
        {
            delays.Add(delay);
            return Task.CompletedTask;
        });

        OllamaResult result = await client.ChatAsync([new OllamaMessage("user", "hello")], null, TestContext.Current.CancellationToken);

        Assert.Equal("ok", result.Content);
        Assert.Equal(4, attempts);
        Assert.Equal([TimeSpan.FromMilliseconds(250), TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(1000)], delays);
    }

    [Fact]
    public async Task Permanent_failure_is_not_retried()
    {
        int attempts = 0;
        var handler = new StubHandler((_, _) =>
        {
            attempts++;
            return Task.FromResult(Json(HttpStatusCode.BadRequest, "invalid"));
        });
        OllamaClient client = Create(handler);

        OllamaException error = await Assert.ThrowsAsync<OllamaException>(() =>
            client.ChatAsync([new OllamaMessage("user", "hello")], null, TestContext.Current.CancellationToken));

        Assert.False(error.IsTransient);
        Assert.Equal(1, attempts);
    }

    [Fact]
    public void Typed_options_override_extra_options()
    {
        var configuration = new OllamaConfiguration
        {
            Endpoint = "http://127.0.0.1:11434",
            Model = "model",
            Options = new OllamaGenerationOptions { Temperature = 0.4, NumCtx = 8192 },
            ExtraOptions = new Dictionary<string, object?>
            {
                ["temperature"] = 1.9,
                ["num_ctx"] = 256,
                ["custom"] = "preserved"
            }
        };

        OllamaSettings settings = OllamaSettingsFactory.Create(configuration);

        Assert.Equal(0.4, settings.Options["temperature"].GetDouble());
        Assert.Equal(8192, settings.Options["num_ctx"].GetInt32());
        Assert.Equal("preserved", settings.Options["custom"].GetString());
    }

    [Fact]
    public async Task Native_tool_catalog_is_serialized_and_tool_call_is_parsed()
    {
        string? body = null;
        var handler = new StubHandler(async (request, _) =>
        {
            body = await request.Content!.ReadAsStringAsync();
            return Json(HttpStatusCode.OK, """{"message":{"role":"assistant","content":"","tool_calls":[{"function":{"name":"file_read","arguments":{"path":"x","mode":"whole"}}}]},"prompt_eval_count":2,"eval_count":1}""");
        });
        OllamaClient client = Create(handler);

        OllamaResult result = await client.ChatWithToolsAsync([new OllamaMessage("user", "read")], null, InternalToolCatalog.All, TestContext.Current.CancellationToken);

        using JsonDocument document = JsonDocument.Parse(body!);
        Assert.Equal(6, document.RootElement.GetProperty("tools").GetArrayLength());
        Assert.All(document.RootElement.GetProperty("tools").EnumerateArray(), tool =>
            Assert.False(tool.GetProperty("function").GetProperty("parameters").GetProperty("additionalProperties").GetBoolean()));
        OllamaToolCall call = Assert.Single(result.ToolCalls!);
        Assert.Equal("file_read", call.Function.Name);
        Assert.Equal("x", call.Function.Arguments.GetProperty("path").GetString());
    }

    private static OllamaClient Create(HttpMessageHandler handler, IReadOnlyDictionary<string, JsonElement>? options = null) =>
        new(new HttpClient(handler), Settings(options), static (_, _) => Task.CompletedTask);

    private static OllamaSettings Settings(IReadOnlyDictionary<string, JsonElement>? options = null) =>
        new(new Uri("http://127.0.0.1:11434"), "test-model", false, "0", options ?? new Dictionary<string, JsonElement>());

    private static HttpResponseMessage Json(HttpStatusCode statusCode, string content) => new(statusCode)
    {
        Content = new StringContent(content, Encoding.UTF8, "application/json")
    };

    private sealed class StubHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> callback) : HttpMessageHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => callback(request, cancellationToken);
    }
}