Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
1705 lines (1439 loc) · 76.2 KB
/
Copy pathProgram.cs
File metadata and controls
1705 lines (1439 loc) · 76.2 KB
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Diagnostics;
using System.Net.Http.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using Microsoft.Data.Sqlite;
var builder = WebApplication.CreateBuilder(args);
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
builder.Services.Configure<LocalAiOptions>(builder.Configuration.GetSection("LocalAi"));
builder.Services.AddHttpClient("ollama", (serviceProvider, client) =>
{
var options = serviceProvider.GetRequiredService<Microsoft.Extensions.Options.IOptions<LocalAiOptions>>().Value;
if (options.RequireLoopback && !IsLoopback(options.BaseUrl))
{
throw new InvalidOperationException("LocalAi:BaseUrl must be localhost/loopback when LocalAi:RequireLoopback is true.");
}
client.BaseAddress = new Uri(options.BaseUrl);
client.Timeout = TimeSpan.FromSeconds(options.RequestTimeoutSeconds);
});
builder.Services.AddSingleton<AppState>();
builder.Services.AddSingleton<OllamaClient>();
builder.Services.AddSingleton<MemoryStore>();
builder.Services.AddSingleton<OllamaManager>();
builder.Services.AddSingleton<DocumentProcessor>();
builder.Services.AddSingleton<SpeechTranscriber>();
builder.Services.AddSingleton<LocalToolRegistry>();
var app = builder.Build();
await app.Services.GetRequiredService<MemoryStore>().InitializeAsync(CancellationToken.None);
app.UseDefaultFiles();
app.UseStaticFiles();
app.MapGet("/api/health", async (OllamaClient ollama, CancellationToken cancellationToken) =>
{
var healthy = await ollama.IsHealthyAsync(cancellationToken);
return Results.Ok(new { healthy });
});
app.MapGet("/api/models", async (OllamaClient ollama, CancellationToken cancellationToken) =>
{
var models = await ollama.GetModelsAsync(cancellationToken);
return Results.Ok(models.OrderBy(model => model.Name, StringComparer.OrdinalIgnoreCase));
});
app.MapGet("/api/ollama/status", async (OllamaClient ollama, OllamaManager manager, CancellationToken cancellationToken) =>
{
var healthy = await ollama.IsHealthyAsync(cancellationToken);
var loadedModels = healthy ? await ollama.GetLoadedModelsAsync(cancellationToken) : [];
return Results.Ok(new OllamaStatusResponse(healthy, manager.IsManagedProcessRunning, loadedModels));
});
app.MapPost("/api/ollama/start", async (OllamaManager manager, OllamaClient ollama, CancellationToken cancellationToken) =>
{
await manager.StartAsync(cancellationToken);
var healthy = await ollama.WaitUntilHealthyAsync(TimeSpan.FromSeconds(20), cancellationToken);
return Results.Ok(new { healthy });
});
app.MapPost("/api/ollama/stop", (OllamaManager manager) =>
{
manager.StopManagedProcess();
return Results.Ok(new { stopped = true });
});
app.MapPost("/api/ollama/warm", async (ModelActionRequest request, OllamaClient ollama, CancellationToken cancellationToken) =>
{
if (string.IsNullOrWhiteSpace(request.Model))
{
return Results.BadRequest(new ErrorResponse("Model is required."));
}
var result = await ollama.GenerateAsync(new OllamaGenerateRequest(
Model: request.Model,
Prompt: "Respond with OK.",
Stream: false,
Images: null,
Options: new OllamaOptions(Temperature: 0.0, TopP: 0.9, TopK: 40),
KeepAlive: request.KeepAlive ?? "10m"), cancellationToken);
return Results.Ok(new { response = result.Response.Trim(), stats = OllamaStats.FromGenerateResponse(result) });
});
app.MapPost("/api/ollama/unload", async (ModelActionRequest request, OllamaClient ollama, CancellationToken cancellationToken) =>
{
if (string.IsNullOrWhiteSpace(request.Model))
{
return Results.BadRequest(new ErrorResponse("Model is required."));
}
await ollama.UnloadModelAsync(request.Model, cancellationToken);
return Results.Ok(new { unloaded = request.Model });
});
app.MapPost("/api/ollama/pull", async (ModelActionRequest request, OllamaClient ollama, CancellationToken cancellationToken) =>
{
if (string.IsNullOrWhiteSpace(request.Model))
{
return Results.BadRequest(new ErrorResponse("Model is required."));
}
await ollama.PullModelAsync(request.Model, cancellationToken);
return Results.Ok(new { pulled = request.Model });
});
app.MapGet("/api/memory/search", async (string q, int? limit, MemoryStore memory, CancellationToken cancellationToken) =>
{
if (string.IsNullOrWhiteSpace(q))
{
return Results.BadRequest(new ErrorResponse("Search query is required."));
}
var results = await memory.SearchAsync(q, limit ?? 8, cancellationToken: cancellationToken);
return Results.Ok(results);
});
app.MapGet("/api/memory/recent", (int? limit, MemoryStore memory) =>
{
return Results.Ok(memory.GetRecent(limit ?? 12));
});
app.MapPost("/api/memory", async (MemoryCreateRequest request, MemoryStore memory, CancellationToken cancellationToken) =>
{
if (string.IsNullOrWhiteSpace(request.Content))
{
return Results.BadRequest(new ErrorResponse("Memory content is required."));
}
var item = await memory.RememberAsync("manual", null, request.Title ?? "Manual memory", request.Content, null, cancellationToken);
return Results.Ok(item);
});
app.MapDelete("/api/memory/{id}", async (string id, MemoryStore memory, CancellationToken cancellationToken) =>
{
await memory.DeleteAsync(id, cancellationToken);
return Results.Ok(new { deleted = id });
});
app.MapGet("/api/documents/current", (AppState state) => Results.Ok(state.CurrentDocument));
app.MapPost("/api/documents", async (HttpRequest request, AppState state, IWebHostEnvironment environment, DocumentProcessor processor, MemoryStore memory, CancellationToken cancellationToken) =>
{
if (!request.HasFormContentType)
{
return Results.BadRequest(new ErrorResponse("Expected multipart form data."));
}
var form = await request.ReadFormAsync(cancellationToken);
var file = form.Files.GetFile("file");
var model = form.TryGetValue("model", out var modelValues) ? modelValues.ToString() : string.Empty;
if (file is null || file.Length == 0)
{
return Results.BadRequest(new ErrorResponse("Upload a PDF or image file."));
}
var kind = DocumentProcessor.GetSupportedFileKind(file.FileName);
var uploadsDirectory = Path.Combine(environment.ContentRootPath, "App_Data", "uploads");
Directory.CreateDirectory(uploadsDirectory);
var fileName = $"{DateTimeOffset.UtcNow:yyyyMMddHHmmss}-{Guid.NewGuid():N}{Path.GetExtension(file.FileName).ToLowerInvariant()}";
var filePath = Path.Combine(uploadsDirectory, fileName);
await using (var stream = File.Create(filePath))
{
await file.CopyToAsync(stream, cancellationToken);
}
var document = new UploadedDocument(
Id: Path.GetFileNameWithoutExtension(fileName),
OriginalName: file.FileName,
Path: filePath,
Kind: kind,
SizeBytes: file.Length,
UploadedAt: DateTimeOffset.UtcNow);
state.CurrentDocument = document;
IReadOnlyList<MemorySearchResult> indexed = [];
string? indexMethod = null;
double? indexDurationMs = null;
if (!string.IsNullOrWhiteSpace(model))
{
var result = await processor.ExtractIndexableTextAsync(document, model, 3, cancellationToken);
indexed = await memory.IndexDocumentAsync(document, result.Text, result.Method, cancellationToken);
indexMethod = result.Method;
indexDurationMs = result.DurationMs;
}
return Results.Ok(new DocumentUploadResponse(document, indexed.Count, indexMethod, indexDurationMs));
});
app.MapPost("/api/documents/current/index", async (DocumentIndexRequest request, AppState state, DocumentProcessor processor, MemoryStore memory, CancellationToken cancellationToken) =>
{
var document = state.CurrentDocument;
if (document is null)
{
return Results.BadRequest(new ErrorResponse("Upload a document first."));
}
var result = await processor.ExtractIndexableTextAsync(document, request.Model, request.Pages ?? 3, cancellationToken);
var indexed = await memory.IndexDocumentAsync(document, result.Text, result.Method, cancellationToken);
return Results.Ok(new DocumentIndexResponse(document, indexed.Count, result.Method, indexed, result.DurationMs));
});
app.MapPost("/api/transcribe", async (HttpRequest request, SpeechTranscriber transcriber, CancellationToken cancellationToken) =>
{
try
{
if (!request.HasFormContentType)
{
return Results.BadRequest(new ErrorResponse("Expected multipart form data."));
}
var form = await request.ReadFormAsync(cancellationToken);
var file = form.Files.GetFile("audio");
if (file is null || file.Length == 0)
{
return Results.BadRequest(new ErrorResponse("Record audio before transcribing."));
}
var result = await transcriber.TranscribeAsync(file, cancellationToken);
return Results.Ok(result);
}
catch (Exception exception) when (exception is InvalidOperationException or IOException or UnauthorizedAccessException)
{
return Results.BadRequest(new ErrorResponse(exception.Message));
}
});
app.MapPost("/api/chat", async (ChatRequest request, OllamaClient ollama, LocalToolRegistry tools, MemoryStore memory, CancellationToken cancellationToken) =>
{
if (string.IsNullOrWhiteSpace(request.Model))
{
return Results.BadRequest(new ErrorResponse("Model is required."));
}
if (string.IsNullOrWhiteSpace(request.Message))
{
return Results.BadRequest(new ErrorResponse("Message is required."));
}
var route = ResolveReasoningRoute(request);
var activeTools = route.UseTools ? tools.GetTools() : [];
var relevantMemories = route.UseMemory
? await memory.SearchAsync(request.Message, route.MemoryLimit, minScore: 0.15, cancellationToken: cancellationToken)
: [];
var messages = new List<OllamaMessage>
{
new("system", BuildSystemPrompt(request.SystemPrompt, activeTools, relevantMemories, route)),
new("user", request.Message)
};
var toolResults = new List<ToolResult>();
OllamaChatResponse response = default!;
for (var step = 0; step < 4; step++)
{
response = await ollama.ChatAsync(new OllamaChatRequest(
Model: request.Model,
Stream: false,
Messages: messages,
Options: new OllamaOptions(Temperature: request.Temperature ?? route.Temperature, TopP: 0.95, TopK: 64),
Tools: route.UseTools ? activeTools.Select(ToOllamaTool).ToList() : null,
Think: route.Think), cancellationToken);
var content = response.Message?.Content ?? string.Empty;
var nativeToolCalls = response.Message?.ToolCalls?.Where(call => !string.IsNullOrWhiteSpace(call.Function?.Name)).ToList() ?? [];
var fallbackToolCall = route.UseTools && nativeToolCalls.Count == 0 && TryParseToolCall(content, out var parsedToolCall) ? parsedToolCall : null;
if (nativeToolCalls.Count == 0 && fallbackToolCall is null)
{
return Results.Ok(new ChatResponse(
Response: content,
Reasoning: response.Message?.Thinking ?? response.Message?.Reasoning,
Stats: OllamaStats.FromChatResponse(response),
Route: route,
Memories: relevantMemories,
ToolResults: toolResults));
}
messages.Add(response.Message ?? new OllamaMessage("assistant", content));
if (nativeToolCalls.Count > 0)
{
foreach (var toolCall in nativeToolCalls)
{
var result = await tools.InvokeAsync(toolCall.Function!.Name!, toolCall.Function.Arguments ?? new Dictionary<string, JsonElement>(), request.Model, cancellationToken);
toolResults.Add(result);
messages.Add(new OllamaMessage("tool", result.Content, Name: result.Tool));
}
}
else if (fallbackToolCall is not null)
{
var result = await tools.InvokeAsync(fallbackToolCall.Tool, fallbackToolCall.Arguments, request.Model, cancellationToken);
toolResults.Add(result);
messages.Add(new OllamaMessage("user", $"Tool {result.Tool} returned this result:\n{result.Content}\n\nUse the tool result to answer the original question. Do not emit another tool call unless another tool is required."));
}
}
return Results.Ok(new ChatResponse(
Response: response.Message?.Content ?? "Stopped after maximum tool-calling steps.",
Reasoning: response.Message?.Thinking ?? response.Message?.Reasoning,
Stats: OllamaStats.FromChatResponse(response),
Route: route,
Memories: relevantMemories,
ToolResults: toolResults));
});
app.MapPost("/api/chat/stream", async (ChatRequest request, HttpResponse httpResponse, OllamaClient ollama, LocalToolRegistry tools, MemoryStore memory, CancellationToken cancellationToken) =>
{
httpResponse.ContentType = "application/x-ndjson";
if (string.IsNullOrWhiteSpace(request.Model))
{
await WriteStreamEventAsync(httpResponse, new StreamEvent("error", Error: "Model is required."), cancellationToken);
return;
}
if (string.IsNullOrWhiteSpace(request.Message))
{
await WriteStreamEventAsync(httpResponse, new StreamEvent("error", Error: "Message is required."), cancellationToken);
return;
}
var route = ResolveReasoningRoute(request);
var activeTools = route.UseTools ? tools.GetTools() : [];
await WriteStreamEventAsync(httpResponse, new StreamEvent("route", Route: route), cancellationToken);
var relevantMemories = route.UseMemory
? await memory.SearchAsync(request.Message, route.MemoryLimit, minScore: 0.15, cancellationToken: cancellationToken)
: [];
await WriteStreamEventAsync(httpResponse, new StreamEvent("memory", Memories: relevantMemories), cancellationToken);
var messages = new List<OllamaMessage>
{
new("system", BuildSystemPrompt(request.SystemPrompt, activeTools, relevantMemories, route)),
new("user", request.Message)
};
OllamaChatResponse response = default!;
for (var step = 0; step < 4; step++)
{
response = await ollama.ChatStreamAsync(new OllamaChatRequest(
Model: request.Model,
Stream: true,
Messages: messages,
Options: new OllamaOptions(Temperature: request.Temperature ?? route.Temperature, TopP: 0.95, TopK: 64),
Tools: route.UseTools ? activeTools.Select(ToOllamaTool).ToList() : null,
Think: route.Think), async chunk =>
{
if (!string.IsNullOrEmpty(chunk.Message?.Thinking))
{
await WriteStreamEventAsync(httpResponse, new StreamEvent("reasoning", Text: chunk.Message.Thinking), cancellationToken);
}
if (!string.IsNullOrEmpty(chunk.Message?.Reasoning))
{
await WriteStreamEventAsync(httpResponse, new StreamEvent("reasoning", Text: chunk.Message.Reasoning), cancellationToken);
}
if (!string.IsNullOrEmpty(chunk.Message?.Content))
{
await WriteStreamEventAsync(httpResponse, new StreamEvent("content", Text: chunk.Message.Content), cancellationToken);
}
}, cancellationToken);
await WriteStreamEventAsync(httpResponse, new StreamEvent("stats", Stats: OllamaStats.FromChatResponse(response)), cancellationToken);
var content = response.Message?.Content ?? string.Empty;
var nativeToolCalls = response.Message?.ToolCalls?.Where(call => !string.IsNullOrWhiteSpace(call.Function?.Name)).ToList() ?? [];
var fallbackToolCall = route.UseTools && nativeToolCalls.Count == 0 && TryParseToolCall(content, out var parsedToolCall) ? parsedToolCall : null;
if (nativeToolCalls.Count == 0 && fallbackToolCall is null)
{
await WriteStreamEventAsync(httpResponse, new StreamEvent("done"), cancellationToken);
return;
}
messages.Add(response.Message ?? new OllamaMessage("assistant", content));
if (nativeToolCalls.Count > 0)
{
foreach (var toolCall in nativeToolCalls)
{
var result = await tools.InvokeAsync(toolCall.Function!.Name!, toolCall.Function.Arguments ?? new Dictionary<string, JsonElement>(), request.Model, cancellationToken);
await WriteStreamEventAsync(httpResponse, new StreamEvent("tool", ToolResult: result), cancellationToken);
messages.Add(new OllamaMessage("tool", result.Content, Name: result.Tool));
}
}
else if (fallbackToolCall is not null)
{
var result = await tools.InvokeAsync(fallbackToolCall.Tool, fallbackToolCall.Arguments, request.Model, cancellationToken);
await WriteStreamEventAsync(httpResponse, new StreamEvent("tool", ToolResult: result), cancellationToken);
messages.Add(new OllamaMessage("user", $"Tool {result.Tool} returned this result:\n{result.Content}\n\nUse the tool result to answer the original question. Do not emit another tool call unless another tool is required."));
}
}
await WriteStreamEventAsync(httpResponse, new StreamEvent("content", Text: response.Message?.Content ?? "Stopped after maximum tool-calling steps."), cancellationToken);
await WriteStreamEventAsync(httpResponse, new StreamEvent("done"), cancellationToken);
});
app.MapPost("/api/ocr", async (DocumentActionRequest request, DocumentProcessor processor, AppState state, CancellationToken cancellationToken) =>
{
var document = state.CurrentDocument;
if (document is null)
{
return Results.BadRequest(new ErrorResponse("Upload a document first."));
}
var result = await processor.ProcessAsync(document, request.Model, DocumentOperation.Ocr, request.Pages ?? 3, cancellationToken);
return Results.Ok(result);
});
app.MapPost("/api/invoice", async (DocumentActionRequest request, DocumentProcessor processor, AppState state, CancellationToken cancellationToken) =>
{
var document = state.CurrentDocument;
if (document is null)
{
return Results.BadRequest(new ErrorResponse("Upload a document first."));
}
var result = await processor.ProcessAsync(document, request.Model, DocumentOperation.Invoice, request.Pages ?? 3, cancellationToken);
return Results.Ok(result);
});
app.Run();
static ReasoningRoute ResolveReasoningRoute(ChatRequest request)
{
if (!request.EnableThinking && string.IsNullOrWhiteSpace(request.ReasoningMode))
{
return BuildRoute("fast", "Legacy reasoning toggle is off.", think: false, useMemory: false, useTools: false, memoryLimit: 0, temperature: 0.75);
}
var requested = string.IsNullOrWhiteSpace(request.ReasoningMode) ? "auto" : request.ReasoningMode.Trim().ToLowerInvariant();
return requested switch
{
"fast" or "off" or "none" => BuildRoute("fast", "User forced fast mode.", think: false, useMemory: false, useTools: false, memoryLimit: 0, temperature: 0.75),
"deep" or "high" => BuildRoute("deep", "User forced deep reasoning.", think: true, useMemory: true, useTools: true, memoryLimit: request.MemoryLimit ?? 8, temperature: 0.55),
"balanced" or "normal" => BuildRoute("balanced", "User forced balanced reasoning.", think: true, useMemory: true, useTools: true, memoryLimit: request.MemoryLimit ?? 5, temperature: 0.65),
_ => ClassifyReasoningEffort(request.Message, request.MemoryLimit)
};
}
static ReasoningRoute ClassifyReasoningEffort(string message, int? requestedMemoryLimit)
{
var text = message.Trim();
var lower = text.ToLowerInvariant();
var wordCount = text.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Length;
var casualPhrases = new[]
{
"hello", "hey", "howdy", "hiya", "sup", "wassup", "thanks", "thank you", "okay", "cool", "nice", "awesome", "great",
"how are you", "how's it going", "hows it going", "how's your day", "hows your day", "how are things", "how goes",
"what's up", "whats up", "what's good", "whats good", "good morning", "good afternoon", "good evening", "good night"
};
var complexSignals = new[]
{
"analyze", "compare", "debug", "fix", "implement", "refactor", "architect", "design", "plan", "prove",
"explain why", "step by step", "tradeoff", "trade-off", "invoice", "ocr", "document", "pdf", "tool", "memory", "search",
"summarize", "extract", "calculate", "reason", "deep", "thorough", "capability", "capabilities", "available", "list all"
};
var tokens = Regex.Matches(lower, "[a-z0-9']+").Select(match => match.Value).ToHashSet(StringComparer.OrdinalIgnoreCase);
var looksComplex = text.Length >= 260 || wordCount >= 45 || complexSignals.Any(signal => lower.Contains(signal, StringComparison.Ordinal));
var looksLikeCasualGreeting = casualPhrases.Any(pattern => lower.Contains(pattern, StringComparison.Ordinal))
|| tokens.Overlaps(["hi", "yo", "ok", "gm", "gn", "lol", "haha"])
|| (tokens.Contains("how") && (tokens.Contains("going") || tokens.Contains("goin")))
|| (tokens.Contains("what") && tokens.Contains("up"));
if (!looksComplex && wordCount <= 12 && text.Length <= 90 && looksLikeCasualGreeting)
{
return BuildRoute("fast", "Casual short message; skipping memory, tools, and reasoning for minimum latency.", think: false, useMemory: false, useTools: false, memoryLimit: 0, temperature: 0.82);
}
if (!looksComplex && text.Length <= 55 && wordCount <= 8 && !text.Contains('?'))
{
return BuildRoute("fast", "Short low-risk turn; optimized for conversational speed.", think: false, useMemory: false, useTools: false, memoryLimit: 0, temperature: 0.82);
}
if (looksComplex)
{
return BuildRoute("deep", "Complex or tool/document-like request; enabling memory, tools, and reasoning.", think: true, useMemory: true, useTools: true, memoryLimit: requestedMemoryLimit ?? 8, temperature: 0.55);
}
return BuildRoute("balanced", "Normal request; using memory and tools with moderate reasoning.", think: true, useMemory: true, useTools: true, memoryLimit: requestedMemoryLimit ?? 5, temperature: 0.65);
}
static ReasoningRoute BuildRoute(string effort, string reason, bool think, bool useMemory, bool useTools, int memoryLimit, double temperature) =>
new(effort, reason, think, useMemory, useTools, Math.Clamp(memoryLimit, 0, 12), temperature);
static string BuildSystemPrompt(string? systemPrompt, IReadOnlyList<LocalTool> tools, IReadOnlyList<MemorySearchResult> memories, ReasoningRoute route)
{
var basePrompt = string.IsNullOrWhiteSpace(systemPrompt)
? "You are LLLM, a concise local-only assistant running against Ollama."
: systemPrompt;
var toolDescriptions = tools.Count == 0
? "No tools are enabled for this fast conversational turn."
: string.Join(Environment.NewLine, tools.Select(tool => $"- {tool.Name}: {tool.Description}. Arguments JSON schema: {tool.ParametersJsonSchema}"));
var toolCallExample = "{\"tool\":\"tool_name\",\"arguments\":{}}";
var memoryBlock = memories.Count == 0
? "No relevant local memories were retrieved for this turn."
: string.Join(Environment.NewLine, memories.Select((memory, index) => $"[{index + 1}] {memory.Source}: {memory.Title}\n{memory.Content}"));
return $"""
{basePrompt}
Local-only constraints:
- Use local Ollama models and local tools only.
- Do not suggest cloud AI services unless the user explicitly asks.
Relevant local memory and documents:
{memoryBlock}
Memory instructions:
- Treat local memory as potentially useful context, not absolute truth.
- If you use a memory, naturally mention the source when helpful.
- Do not expose raw memory IDs unless the user asks.
Reasoning route:
- Effort: {route.Effort}.
- Reason: {route.Reason}
- If effort is fast, answer like a relaxed, friendly local assistant: brief, warm, and conversational. Do not mention being an AI system, functioning status, routing, tools, or memory unless directly asked.
Available tools:
{toolDescriptions}
Tool protocol fallback:
- Prefer native Ollama tool calls when available.
- If native tool calls are unavailable, respond with exactly one JSON object and no markdown: {toolCallExample}
- After a tool result is supplied, answer normally.
""";
}
static OllamaTool ToOllamaTool(LocalTool tool) => new(
Type: "function",
Function: new OllamaFunctionTool(
Name: tool.Name,
Description: tool.Description,
Parameters: JsonNode.Parse(tool.ParametersJsonSchema) ?? new JsonObject()));
static bool TryParseToolCall(string content, out ParsedToolCall toolCall)
{
toolCall = default!;
var trimmed = content.Trim();
if (!trimmed.StartsWith('{') || !trimmed.EndsWith('}'))
{
return false;
}
try
{
using var document = JsonDocument.Parse(trimmed);
var root = document.RootElement;
if (!root.TryGetProperty("tool", out var toolElement) || toolElement.GetString() is not { Length: > 0 } tool)
{
return false;
}
var arguments = root.TryGetProperty("arguments", out var argumentsElement)
? JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(argumentsElement.GetRawText(), JsonDefaults.Options) ?? []
: [];
toolCall = new ParsedToolCall(tool, arguments);
return true;
}
catch (JsonException)
{
return false;
}
}
static bool IsLoopback(string url)
{
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
return false;
}
return uri.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase)
|| uri.Host.Equals("127.0.0.1", StringComparison.OrdinalIgnoreCase)
|| uri.Host.Equals("::1", StringComparison.OrdinalIgnoreCase);
}
static async Task WriteStreamEventAsync(HttpResponse response, StreamEvent streamEvent, CancellationToken cancellationToken)
{
await response.WriteAsync(JsonSerializer.Serialize(streamEvent, JsonDefaults.Options), cancellationToken);
await response.WriteAsync("\n", cancellationToken);
await response.Body.FlushAsync(cancellationToken);
}
public sealed class AppState
{
public UploadedDocument? CurrentDocument { get; set; }
}
public sealed class OllamaClient(IHttpClientFactory httpClientFactory)
{
public async Task<bool> IsHealthyAsync(CancellationToken cancellationToken)
{
try
{
using var response = await httpClientFactory.CreateClient("ollama").GetAsync("/api/tags", cancellationToken);
return response.IsSuccessStatusCode;
}
catch (HttpRequestException)
{
return false;
}
}
public async Task<IReadOnlyList<OllamaModel>> GetModelsAsync(CancellationToken cancellationToken)
{
var response = await httpClientFactory.CreateClient("ollama").GetFromJsonAsync<OllamaModelsResponse>("/api/tags", JsonDefaults.Options, cancellationToken)
?? new OllamaModelsResponse([]);
return response.Models;
}
public async Task<IReadOnlyList<LoadedOllamaModel>> GetLoadedModelsAsync(CancellationToken cancellationToken)
{
using var response = await httpClientFactory.CreateClient("ollama").GetAsync("/api/ps", cancellationToken);
if (!response.IsSuccessStatusCode)
{
return [];
}
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
using var document = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken);
if (!document.RootElement.TryGetProperty("models", out var models) || models.GetArrayLength() == 0)
{
return [];
}
var loadedModels = new List<LoadedOllamaModel>();
foreach (var model in models.EnumerateArray())
{
var name = model.TryGetProperty("name", out var nameElement) ? nameElement.GetString() : "unknown";
var size = model.TryGetProperty("size", out var sizeElement) && sizeElement.TryGetInt64(out var sizeBytes) ? sizeBytes : 0;
var processor = model.TryGetProperty("processor", out var processorElement) ? processorElement.GetString() : null;
var context = model.TryGetProperty("context_length", out var contextElement) && contextElement.TryGetInt32(out var contextValue) ? contextValue : (int?)null;
var expiresAt = model.TryGetProperty("expires_at", out var expiresElement) && expiresElement.TryGetDateTimeOffset(out var expiresValue) ? expiresValue : (DateTimeOffset?)null;
loadedModels.Add(new LoadedOllamaModel(name ?? "unknown", size, processor, context, expiresAt));
}
return loadedModels;
}
public async Task<bool> WaitUntilHealthyAsync(TimeSpan timeout, CancellationToken cancellationToken)
{
var deadline = DateTimeOffset.UtcNow.Add(timeout);
while (DateTimeOffset.UtcNow < deadline)
{
if (await IsHealthyAsync(cancellationToken))
{
return true;
}
await Task.Delay(500, cancellationToken);
}
return false;
}
public async Task PullModelAsync(string model, CancellationToken cancellationToken)
{
using var response = await httpClientFactory.CreateClient("ollama").PostAsJsonAsync("/api/pull", new OllamaPullRequest(model, false), JsonDefaults.Options, cancellationToken);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync(cancellationToken);
throw new InvalidOperationException($"Ollama pull returned {(int)response.StatusCode}: {error}");
}
}
public async Task UnloadModelAsync(string model, CancellationToken cancellationToken)
{
using var response = await httpClientFactory.CreateClient("ollama").PostAsJsonAsync("/api/generate", new OllamaGenerateRequest(
Model: model,
Prompt: string.Empty,
Stream: false,
Images: null,
Options: new OllamaOptions(Temperature: 0.0, TopP: 0.9, TopK: 40),
KeepAlive: "0"), JsonDefaults.Options, cancellationToken);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync(cancellationToken);
throw new InvalidOperationException($"Ollama unload returned {(int)response.StatusCode}: {error}");
}
}
public async Task<OllamaChatResponse> ChatAsync(OllamaChatRequest request, CancellationToken cancellationToken)
{
using var response = await httpClientFactory.CreateClient("ollama").PostAsJsonAsync("/api/chat", request, JsonDefaults.Options, cancellationToken);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync(cancellationToken);
throw new InvalidOperationException($"Ollama chat returned {(int)response.StatusCode}: {error}");
}
return await response.Content.ReadFromJsonAsync<OllamaChatResponse>(JsonDefaults.Options, cancellationToken)
?? throw new InvalidOperationException("Ollama returned an empty chat response.");
}
public async Task<OllamaChatResponse> ChatStreamAsync(OllamaChatRequest request, Func<OllamaChatResponse, Task> onChunk, CancellationToken cancellationToken)
{
using var httpRequest = new HttpRequestMessage(HttpMethod.Post, "/api/chat")
{
Content = JsonContent.Create(request, options: JsonDefaults.Options)
};
using var response = await httpClientFactory.CreateClient("ollama").SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync(cancellationToken);
throw new InvalidOperationException($"Ollama chat returned {(int)response.StatusCode}: {error}");
}
var model = request.Model;
var role = "assistant";
var content = new StringBuilder();
var thinking = new StringBuilder();
var reasoning = new StringBuilder();
var toolCalls = new List<OllamaToolCall>();
OllamaChatResponse? lastChunk = null;
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
using var reader = new StreamReader(stream);
while (await reader.ReadLineAsync(cancellationToken) is { } line)
{
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
var chunk = JsonSerializer.Deserialize<OllamaChatResponse>(line, JsonDefaults.Options);
if (chunk is null)
{
continue;
}
lastChunk = chunk;
model = chunk.Model ?? model;
if (chunk.Message is not null)
{
role = string.IsNullOrWhiteSpace(chunk.Message.Role) ? role : chunk.Message.Role;
content.Append(chunk.Message.Content);
thinking.Append(chunk.Message.Thinking);
reasoning.Append(chunk.Message.Reasoning);
if (chunk.Message.ToolCalls is { Count: > 0 })
{
toolCalls.AddRange(chunk.Message.ToolCalls);
}
}
await onChunk(chunk);
}
return new OllamaChatResponse(
Model: model,
Message: new OllamaMessage(role, content.ToString(), thinking.ToString(), reasoning.ToString(), toolCalls.Count > 0 ? toolCalls : null),
TotalDuration: lastChunk?.TotalDuration,
LoadDuration: lastChunk?.LoadDuration,
PromptEvalCount: lastChunk?.PromptEvalCount,
PromptEvalDuration: lastChunk?.PromptEvalDuration,
EvalCount: lastChunk?.EvalCount,
EvalDuration: lastChunk?.EvalDuration);
}
public async Task<OllamaGenerateResponse> GenerateAsync(OllamaGenerateRequest request, CancellationToken cancellationToken)
{
using var response = await httpClientFactory.CreateClient("ollama").PostAsJsonAsync("/api/generate", request, JsonDefaults.Options, cancellationToken);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync(cancellationToken);
throw new InvalidOperationException($"Ollama generate returned {(int)response.StatusCode}: {error}");
}
return await response.Content.ReadFromJsonAsync<OllamaGenerateResponse>(JsonDefaults.Options, cancellationToken)
?? throw new InvalidOperationException("Ollama returned an empty generate response.");
}
public async Task<IReadOnlyList<double>> EmbedAsync(string model, string prompt, CancellationToken cancellationToken)
{
using var response = await httpClientFactory.CreateClient("ollama").PostAsJsonAsync("/api/embeddings", new OllamaEmbeddingRequest(model, prompt), JsonDefaults.Options, cancellationToken);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync(cancellationToken);
throw new InvalidOperationException($"Ollama embedding returned {(int)response.StatusCode}: {error}");
}
var result = await response.Content.ReadFromJsonAsync<OllamaEmbeddingResponse>(JsonDefaults.Options, cancellationToken)
?? throw new InvalidOperationException("Ollama returned an empty embedding response.");
return result.Embedding;
}
}
public sealed class MemoryStore(OllamaClient ollama, Microsoft.Extensions.Options.IOptions<LocalAiOptions> options, IWebHostEnvironment environment)
{
private readonly MemoryOptions _options = options.Value.Memory;
private readonly List<MemoryEntry> _entries = [];
private readonly SemaphoreSlim _gate = new(1, 1);
private string _databasePath = string.Empty;
private string _connectionString = string.Empty;
public async Task InitializeAsync(CancellationToken cancellationToken)
{
var directory = Path.Combine(environment.ContentRootPath, _options.Directory);
Directory.CreateDirectory(directory);
_databasePath = Path.Combine(directory, _options.DatabaseFileName);
_connectionString = new SqliteConnectionStringBuilder { DataSource = _databasePath }.ToString();
await using var connection = new SqliteConnection(_connectionString);
await connection.OpenAsync(cancellationToken);
await using (var command = connection.CreateCommand())
{
command.CommandText = """
create table if not exists memories (
id text primary key,
source text not null,
source_id text null,
title text not null,
content text not null,
metadata_json text null,
embedding_json text not null,
embedding_model text not null,
created_at text not null
);
create index if not exists idx_memories_created_at on memories(created_at);
create index if not exists idx_memories_source_id on memories(source_id);
""";
await command.ExecuteNonQueryAsync(cancellationToken);
}
await LoadCacheAsync(connection, cancellationToken);
}
public IReadOnlyList<MemorySearchResult> GetRecent(int limit)
{
lock (_entries)
{
return _entries
.OrderByDescending(entry => entry.CreatedAt)
.Take(Math.Clamp(limit, 1, 50))
.Select(entry => ToSearchResult(entry, null))
.ToList();
}
}
public async Task<MemorySearchResult> RememberAsync(string source, string? sourceId, string title, string content, string? metadataJson, CancellationToken cancellationToken)
{
var chunks = ChunkText(content, _options.MaxChunkCharacters, _options.ChunkOverlapCharacters);
var text = chunks.Count == 0 ? content.Trim() : chunks[0];
return await StoreChunkAsync(source, sourceId, title, text, metadataJson, cancellationToken);
}
public async Task<IReadOnlyList<MemorySearchResult>> IndexDocumentAsync(UploadedDocument document, string text, string method, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(text))
{
return [];
}
var chunks = ChunkText(text, _options.MaxChunkCharacters, _options.ChunkOverlapCharacters).Take(_options.MaxDocumentChunks).ToList();
var results = new List<MemorySearchResult>();
var metadata = JsonSerializer.Serialize(new { document.Id, document.OriginalName, document.Kind, method }, JsonDefaults.Options);
for (var index = 0; index < chunks.Count; index++)
{
var title = $"{document.OriginalName} chunk {index + 1}/{chunks.Count}";
results.Add(await StoreChunkAsync("document", document.Id, title, chunks[index], metadata, cancellationToken));
}
return results;
}
public async Task<IReadOnlyList<MemorySearchResult>> SearchAsync(string query, int limit, double minScore = 0.0, CancellationToken cancellationToken = default)
{
if (!_options.Enabled)
{
return [];
}
if (string.IsNullOrWhiteSpace(query))
{
return [];
}
var queryEmbedding = await ollama.EmbedAsync(_options.EmbeddingModel, query, cancellationToken);
List<MemoryEntry> snapshot;
lock (_entries)
{
snapshot = _entries.ToList();
}
return snapshot
.Select(entry => ToSearchResult(entry, CosineSimilarity(queryEmbedding, entry.Embedding)))
.Where(result => result.Score is null || result.Score >= minScore)
.OrderByDescending(result => result.Score ?? 0)
.ThenByDescending(result => result.CreatedAt)
.Take(Math.Clamp(limit, 1, 25))
.ToList();
}
public async Task DeleteAsync(string id, CancellationToken cancellationToken)
{
await _gate.WaitAsync(cancellationToken);
try
{
await using var connection = new SqliteConnection(_connectionString);
await connection.OpenAsync(cancellationToken);
await using var command = connection.CreateCommand();
command.CommandText = "delete from memories where id = $id";
command.Parameters.AddWithValue("$id", id);
await command.ExecuteNonQueryAsync(cancellationToken);
lock (_entries)
{
_entries.RemoveAll(entry => entry.Id == id);
}
}
finally
{
_gate.Release();
}
}
private async Task<MemorySearchResult> StoreChunkAsync(string source, string? sourceId, string title, string content, string? metadataJson, CancellationToken cancellationToken)
{
if (!_options.Enabled)
{
throw new InvalidOperationException("Local memory is disabled. Set LocalAi:Memory:Enabled=true.");
}
var normalizedContent = content.Trim();
var embedding = await ollama.EmbedAsync(_options.EmbeddingModel, normalizedContent, cancellationToken);
var entry = new MemoryEntry(
Id: Guid.NewGuid().ToString("N"),
Source: source,
SourceId: sourceId,
Title: title.Trim(),
Content: normalizedContent,
MetadataJson: metadataJson,
Embedding: embedding,
EmbeddingModel: _options.EmbeddingModel,
CreatedAt: DateTimeOffset.UtcNow);
await _gate.WaitAsync(cancellationToken);
try
{
await using var connection = new SqliteConnection(_connectionString);
await connection.OpenAsync(cancellationToken);
await using var command = connection.CreateCommand();
command.CommandText = """
insert into memories (id, source, source_id, title, content, metadata_json, embedding_json, embedding_model, created_at)
values ($id, $source, $sourceId, $title, $content, $metadataJson, $embeddingJson, $embeddingModel, $createdAt)
""";
command.Parameters.AddWithValue("$id", entry.Id);
command.Parameters.AddWithValue("$source", entry.Source);
command.Parameters.AddWithValue("$sourceId", (object?)entry.SourceId ?? DBNull.Value);
command.Parameters.AddWithValue("$title", entry.Title);
command.Parameters.AddWithValue("$content", entry.Content);
command.Parameters.AddWithValue("$metadataJson", (object?)entry.MetadataJson ?? DBNull.Value);
command.Parameters.AddWithValue("$embeddingJson", JsonSerializer.Serialize(entry.Embedding, JsonDefaults.Options));
command.Parameters.AddWithValue("$embeddingModel", entry.EmbeddingModel);
command.Parameters.AddWithValue("$createdAt", entry.CreatedAt.ToString("O"));
await command.ExecuteNonQueryAsync(cancellationToken);