-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_diff.txt
More file actions
1538 lines (1462 loc) · 138 KB
/
test_diff.txt
File metadata and controls
1538 lines (1462 loc) · 138 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
diff --git a/AgentCore.MEAI/MEAIExtensions.cs b/AgentCore.MEAI/MEAIExtensions.cs
index 3f177c7..938159e 100644
--- a/AgentCore.MEAI/MEAIExtensions.cs
+++ b/AgentCore.MEAI/MEAIExtensions.cs
@@ -102,10 +102,13 @@ internal static class MEAIExtensions
{
foreach (var tool in tools)
{
- yield return AIFunctionFactory.Create(
- (string args) => args,
- name: tool.Name,
- description: tool.Description);
+ var schemaElement = JsonSerializer.Deserialize<JsonElement>(
+ tool.ParametersSchema.ToJsonString());
+
+ yield return AIFunctionFactory.CreateDeclaration(
+ name: tool.Name,
+ description: tool.Description,
+ jsonSchema: schemaElement);
}
}
diff --git a/AgentCore.MEAI/MEAILLMClient.cs b/AgentCore.MEAI/MEAILLMClient.cs
index b251c30..ca118a2 100644
--- a/AgentCore.MEAI/MEAILLMClient.cs
+++ b/AgentCore.MEAI/MEAILLMClient.cs
@@ -37,6 +37,10 @@ public sealed class MEAILLMClient(IChatClient _client) : ILLMProvider
meaiOptions.Tools = tools.ToMEAITools().ToList();
}
+ // MEAI gives us COMPLETE FunctionCallContent objects (not streaming deltas).
+ // Each one needs a unique index so LLMExecutor treats them as separate tool calls.
+ int toolCallIndex = 0;
+
await foreach (var update in _client.GetStreamingResponseAsync(meaiMessages, meaiOptions, ct).WithCancellation(ct))
{
if (update.FinishReason.HasValue)
@@ -59,13 +63,15 @@ public sealed class MEAILLMClient(IChatClient _client) : ILLMProvider
break;
case FunctionCallContent fc:
+ var argsDelta = fc.Arguments?.Count > 0
+ ? System.Text.Json.JsonSerializer.Serialize(fc.Arguments)
+ : null;
+
yield return new ToolCallDelta(
- Index: 0,
+ Index: toolCallIndex++, // unique index per tool call
Id: fc.CallId,
Name: fc.Name,
- ArgumentsDelta: fc.Arguments?.Count > 0
- ? System.Text.Json.JsonSerializer.Serialize(fc.Arguments)
- : null
+ ArgumentsDelta: argsDelta
);
break;
@@ -73,7 +79,7 @@ public sealed class MEAILLMClient(IChatClient _client) : ILLMProvider
if (u.Details != null)
{
yield return new MetaDelta(
- AgentCore.LLM.FinishReason.Stop,
+ null,
new TokenUsage(
(int)(u.Details.InputTokenCount ?? 0),
(int)(u.Details.OutputTokenCount ?? 0),
@@ -85,3 +91,4 @@ public sealed class MEAILLMClient(IChatClient _client) : ILLMProvider
}
}
}
+
diff --git a/AgentCore.OpenAI/AgentCore.OpenAI.csproj b/AgentCore.OpenAI/AgentCore.OpenAI.csproj
deleted file mode 100644
index 3d7ad7b..0000000
--- a/AgentCore.OpenAI/AgentCore.OpenAI.csproj
+++ /dev/null
@@ -1,20 +0,0 @@
-<Project Sdk="Microsoft.NET.Sdk">
-
- <PropertyGroup>
- <TargetFramework>net8.0</TargetFramework>
- <ImplicitUsings>enable</ImplicitUsings>
- <LangVersion>latest</LangVersion>
- <Nullable>enable</Nullable>
- <PackageOutputPath>$(MSBuildProjectDirectory)\.nuget</PackageOutputPath>
- </PropertyGroup>
-
- <ItemGroup>
- <ProjectReference Include="..\AgentCore\AgentCore.csproj" />
- </ItemGroup>
-
- <ItemGroup>
- <PackageReference Include="OpenAI" Version="2.9.1" />
- <PackageReference Include="SharpToken" Version="2.0.4" />
- </ItemGroup>
-
-</Project>
diff --git a/AgentCore.OpenAI/OpenAIExtensions.cs b/AgentCore.OpenAI/OpenAIExtensions.cs
deleted file mode 100644
index 1b39230..0000000
--- a/AgentCore.OpenAI/OpenAIExtensions.cs
+++ /dev/null
@@ -1,103 +0,0 @@
-using AgentCore.Conversation;
-using AgentCore.Json;
-using AgentCore.LLM;
-using AgentCore.Tooling;
-using OpenAI.Chat;
-using System.Text.Json.Nodes;
-
-namespace AgentCore.Providers.OpenAI;
-
-public static class OpenAIExtensions
-{
- public static FinishReason ToChatFinishReason(this ChatFinishReason reason) => reason switch
- {
- ChatFinishReason.Stop => FinishReason.Stop,
- ChatFinishReason.ToolCalls => FinishReason.ToolCall,
- _ => FinishReason.Stop
- };
-
- public static ChatToolChoice ToChatToolChoice(this ToolCallMode mode) => mode switch
- {
- ToolCallMode.None => ChatToolChoice.CreateNoneChoice(),
- ToolCallMode.Required => ChatToolChoice.CreateRequiredChoice(),
- _ => ChatToolChoice.CreateAutoChoice()
- };
-
- public static List<ChatTool> ToChatTools(this IEnumerable<Tool> tools)
- => tools.Select(tool => ChatTool.CreateFunctionTool(
- tool.Name,
- tool.Description ?? "",
- BinaryData.FromString(tool.ParametersSchema?.ToJsonString() ?? "{\"type\":\"object\"}")
- )).ToList();
-
- public static IEnumerable<ChatMessage> ToChatMessages(this IReadOnlyList<Message> history)
- {
- foreach (var msg in history)
- {
- switch (msg.Role)
- {
- case Role.System:
- var sysText = msg.Contents.OfType<Text>().FirstOrDefault();
- var sysSummary = msg.Contents.OfType<Summary>().FirstOrDefault();
- var sysContent = sysText?.Value ?? sysSummary?.ForLlm() ?? "";
- if (!string.IsNullOrEmpty(sysContent))
- yield return ChatMessage.CreateSystemMessage(sysContent);
- break;
-
- case Role.User:
- var userText = msg.Contents.OfType<Text>().FirstOrDefault();
- if (userText != null)
- yield return ChatMessage.CreateUserMessage(userText.Value);
- break;
-
- case Role.Assistant:
- var assistantText = msg.Contents.OfType<Text>().FirstOrDefault();
- var reasoning = msg.Contents.OfType<Reasoning>().FirstOrDefault();
- var toolCalls = msg.Contents.OfType<ToolCall>().ToList();
-
- if (toolCalls.Count > 0)
- {
- yield return ChatMessage.CreateAssistantMessage(
- toolCalls: toolCalls.Select(call => ChatToolCall.CreateFunctionToolCall(
- id: call.Id,
- functionName: call.Name,
- functionArguments: BinaryData.FromString(call.Arguments?.ToJsonString() ?? "{}"))).ToList());
- }
- else if (assistantText != null || reasoning != null)
- {
- var text = assistantText?.Value ?? "";
- yield return ChatMessage.CreateAssistantMessage(text);
- }
- break;
-
- case Role.Tool:
- var toolResult = msg.Contents.OfType<ToolResult>().FirstOrDefault();
- if (toolResult != null)
- {
- var payload = toolResult.Result == null ? "{}" : toolResult.Result.AsJsonString();
- yield return ChatMessage.CreateToolMessage(toolResult.CallId, payload);
- }
- break;
- }
- }
- }
-
- public static void ApplySamplingOptions(this ChatCompletionOptions opts, LLMOptions? options)
- {
- var s = options;
- if (s == null) return;
-
- if (s.Temperature.HasValue) opts.Temperature = s.Temperature.Value;
- if (s.TopP.HasValue) opts.TopP = s.TopP.Value;
- if (s.MaxOutputTokens.HasValue) opts.MaxOutputTokenCount = s.MaxOutputTokens.Value;
-#pragma warning disable OPENAI001
- if (s.Seed.HasValue) opts.Seed = s.Seed.Value;
-#pragma warning restore OPENAI001
- if (s.FrequencyPenalty.HasValue) opts.FrequencyPenalty = s.FrequencyPenalty.Value;
- if (s.PresencePenalty.HasValue) opts.PresencePenalty = s.PresencePenalty.Value;
-
- if (s.StopSequences is { Count: > 0 })
- foreach (var stop in s.StopSequences)
- opts.StopSequences.Add(stop);
- }
-}
diff --git a/AgentCore.OpenAI/OpenAILLMClient.cs b/AgentCore.OpenAI/OpenAILLMClient.cs
deleted file mode 100644
index 1efb635..0000000
--- a/AgentCore.OpenAI/OpenAILLMClient.cs
+++ /dev/null
@@ -1,103 +0,0 @@
-using AgentCore.Conversation;
-using AgentCore.LLM;
-using AgentCore.Tooling;
-
-using OpenAI;
-using OpenAI.Chat;
-using System.ClientModel;
-
-namespace AgentCore.Providers.OpenAI;
-
-internal sealed class OpenAILLMClient : ILLMProvider
-{
- private readonly OpenAIClient _client;
- private readonly string _defaultModel;
-
- public OpenAILLMClient(LLMOptions options)
- {
- var opts = options;
- _client = new OpenAIClient(
- new ApiKeyCredential(opts.ApiKey!),
- new OpenAIClientOptions { Endpoint = new Uri(opts.BaseUrl!) }
- );
- _defaultModel = opts.Model ?? throw new InvalidOperationException("Model must be specified in LLMOptions.");
- }
-
- public async IAsyncEnumerable<IContentDelta> StreamAsync(
- IReadOnlyList<Message> messages,
- LLMOptions options,
- IReadOnlyList<Tool>? tools = null,
- [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct = default)
- {
- var model = options.Model ?? _defaultModel;
- var chat = _client.GetChatClient(model);
- var chatOptions = BuildChatOptions(options, tools);
-
- string? pendingToolId = null;
- string? pendingToolName = null;
-
- await foreach (var update in chat.CompleteChatStreamingAsync(
- messages.ToChatMessages(), chatOptions, ct).WithCancellation(ct))
- {
- if (update.ContentUpdate is { } content)
- {
- foreach (var c in content)
- {
- if (c.Text is { } t)
- yield return new TextDelta(t);
- }
- }
-
- if (update.ToolCallUpdates is { } tcuList)
- {
- foreach (var tcu in tcuList)
- {
- pendingToolId ??= tcu.ToolCallId;
- pendingToolName ??= tcu.FunctionName;
-
- if (tcu.FunctionArgumentsUpdate is { } argToken)
- {
- yield return new ToolCallDelta(
- Index: tcu.Index,
- Id: pendingToolId,
- Name: pendingToolName,
- ArgumentsDelta: argToken.ToString()
- );
- }
- }
- }
-
- if (update.Usage is { } usage)
- yield return new MetaDelta(FinishReason.Stop, new global::AgentCore.Tokens.TokenUsage(usage.InputTokenCount, usage.OutputTokenCount));
-
- if (update.FinishReason is { } finish)
- yield return new MetaDelta(finish.ToChatFinishReason(), null);
- }
- }
-
- private static ChatCompletionOptions BuildChatOptions(LLMOptions options, IReadOnlyList<Tool>? tools)
- {
- var o = new ChatCompletionOptions();
-
- // Sampling
- o.ApplySamplingOptions(options);
-
- // Structured output
- if (options.ResponseSchema != null)
- {
- o.ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat(
- "structured_response",
- BinaryData.FromString(options.ResponseSchema.ToJsonString()),
- jsonSchemaIsStrict: true
- );
- }
-
- // Tools
- o.ToolChoice = options.ToolCallMode.ToChatToolChoice();
- if (tools != null)
- foreach (var t in tools.ToChatTools())
- o.Tools.Add(t);
-
- return o;
- }
-}
diff --git a/AgentCore.OpenAI/OpenAIServiceExtensions.cs b/AgentCore.OpenAI/OpenAIServiceExtensions.cs
deleted file mode 100644
index 5535184..0000000
--- a/AgentCore.OpenAI/OpenAIServiceExtensions.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-using AgentCore.LLM;
-using AgentCore.Tokens;
-
-
-namespace AgentCore.Providers.OpenAI;
-
-public static class OpenAIServiceExtensions
-{
- public static AgentBuilder AddOpenAI(this AgentBuilder builder, Action<LLMOptions> configure)
- {
- var options = new LLMOptions();
- configure(options);
-
- var provider = new OpenAILLMClient(options);
- builder.WithProvider(provider, options);
-
- var encoding = options.Model?.StartsWith("gpt-4o") == true ? "o200k_base" : "cl100k_base";
- var tokenCounter = new TikTokenCounter(encoding);
- builder.WithTokenCounter(tokenCounter);
-
- return builder;
- }
-}
diff --git a/AgentCore.OpenAI/TikTokenCounter.cs b/AgentCore.OpenAI/TikTokenCounter.cs
deleted file mode 100644
index 5f41188..0000000
--- a/AgentCore.OpenAI/TikTokenCounter.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-using AgentCore.Conversation;
-using AgentCore.Json;
-using AgentCore.Tokens;
-using SharpToken;
-using System.Runtime.CompilerServices;
-
-namespace AgentCore.Providers.OpenAI;
-
-public sealed class TikTokenCounter(string encodingName) : ITokenCounter
-{
- private readonly GptEncoding _encoding = GptEncoding.GetEncoding(encodingName);
- private static readonly ConditionalWeakTable<Message, IntBox> _cache = new();
- private sealed class IntBox(int count) { public int Count = count; }
-
- public Task<int> CountAsync(IEnumerable<Message> messages, CancellationToken ct = default)
- {
- if (messages == null || !messages.Any()) return Task.FromResult(0);
-
- int total = 0;
- foreach (var m in messages)
- {
- if (_cache.TryGetValue(m, out var box))
- {
- total += box.Count;
- }
- else
- {
- int c = _encoding.Encode(new[] { m }.ToJson()).Count;
- _cache.Add(m, new IntBox(c));
- total += c;
- }
- }
- return Task.FromResult(total);
- }
-}
diff --git a/AgentCore.sln b/AgentCore.sln
index a60ed53..706ce16 100644
--- a/AgentCore.sln
+++ b/AgentCore.sln
@@ -1,3 +1,4 @@
+
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 18
VisualStudioVersion = 18.4.11513.90
diff --git a/AgentCore/Agent.cs b/AgentCore/Agent.cs
index 3512ccc..f7ffa3c 100644
--- a/AgentCore/Agent.cs
+++ b/AgentCore/Agent.cs
@@ -123,6 +123,9 @@ public sealed class LLMAgent : IAgent
}))
{
var chat = await _memory.RecallAsync(sessionId);
+ var isNewSession = chat.Count == 0;
+ _logger.LogInformation("Agent invoked: Session={SessionId} InputLength={Len} NewSession={IsNew}", sessionId, input.ForLlm().Length, isNewSession);
+
var userMessage = new Message(Role.User, input);
chat.Add(userMessage);
@@ -146,6 +149,7 @@ public sealed class LLMAgent : IAgent
var runningTools = new List<Task<ToolResult>>();
var messages = (IReadOnlyList<Message>)chat.GetActiveWindow();
+ _logger.LogDebug("LLM step {Step}: Messages={Count} ContextTokensΓëê{Approx}", consecutiveToolSteps + 1, messages.Count, lastLlmTokens);
await foreach (var evt in _llm.StreamAsync(messages, options, ct))
{
@@ -186,7 +190,15 @@ public sealed class LLMAgent : IAgent
break;
case LLMMetaEvent meta:
- lastLlmTokens = meta.Usage.InputTokens + meta.Usage.OutputTokens;
+ if (meta.Usage.IsEmpty)
+ {
+ lastLlmTokens = await _tokenCounter.CountAsync(chat.GetActiveWindow(), ct).ConfigureAwait(false) + meta.ToolSchemaTokens;
+ _logger.LogDebug("LLM Provider did not report tokens. Counted {TokenCount} natively (including {ToolSchemaTokens} tool schemas).", lastLlmTokens, meta.ToolSchemaTokens);
+ }
+ else
+ {
+ lastLlmTokens = meta.Usage.InputTokens + meta.Usage.OutputTokens;
+ }
break;
}
@@ -213,22 +225,24 @@ public sealed class LLMAgent : IAgent
{
if (options.ContextLength.HasValue)
{
- if (lastLlmTokens == 0)
- {
- lastLlmTokens = await _tokenCounter.CountAsync(chat.GetActiveWindow(), ct).ConfigureAwait(false);
- _logger.LogDebug("LLM Provider did not report tokens. Counted {TokenCount} natively.", lastLlmTokens);
- }
+ _logger.LogDebug("Context reduction requested: {Tokens}/{Limit}", lastLlmTokens, options.ContextLength.Value);
chat = await _ctxManager.ReduceAsync(chat, lastLlmTokens, options, ct).ConfigureAwait(false);
}
+ _logger.LogDebug("Agent completed: Steps={Steps} TotalToolCalls={Count}", consecutiveToolSteps, 0);
await _memory.UpdateAsync(sessionId, chat);
break;
}
consecutiveToolSteps++;
+ var toolStartTime = DateTime.UtcNow;
var results = await Task.WhenAll(runningTools);
+ var toolDuration = (DateTime.UtcNow - toolStartTime).TotalMilliseconds;
foreach (var result in results)
{
+ var resultLength = result.ForLlm()?.Length ?? 0;
+ var toolName = pendingCalls.TryGetValue(result.CallId, out var msg) && msg.Contents.FirstOrDefault() is ToolCall tc ? tc.Name : "unknown";
+ _logger.LogDebug("Tool result: {ToolName} Duration={Ms}ms ResultLength={Len}", toolName, toolDuration, resultLength);
chat.Add(new Message(Role.Tool, result));
yield return new AgentToolResultEvent(result);
}
@@ -237,11 +251,7 @@ public sealed class LLMAgent : IAgent
if (options.ContextLength.HasValue)
{
- if (lastLlmTokens == 0)
- {
- lastLlmTokens = await _tokenCounter.CountAsync(chat.GetActiveWindow(), ct).ConfigureAwait(false);
- _logger.LogDebug("LLM Provider did not report tokens. Counted {TokenCount} natively.", lastLlmTokens);
- }
+ _logger.LogDebug("Context reduction requested: {Tokens}/{Limit}", lastLlmTokens, options.ContextLength.Value);
chat = await _ctxManager.ReduceAsync(chat, lastLlmTokens, options, ct).ConfigureAwait(false);
}
diff --git a/AgentCore/AgentBuilder.cs b/AgentCore/AgentBuilder.cs
index 5675495..0fdc72c 100644
--- a/AgentCore/AgentBuilder.cs
+++ b/AgentCore/AgentBuilder.cs
@@ -13,7 +13,7 @@ public sealed class AgentConfig
{
public string Name { get; set; } = "agent";
public string? SystemPrompt { get; set; }
- public int MaxToolCalls { get; set; } = 15;
+ public int? MaxToolCalls { get; set; } = null;
public ToolOptions ToolOptions { get; set; } = new();
}
@@ -74,7 +74,8 @@ public sealed class AgentBuilder
var toolExecutor = new ToolExecutor(
registry,
- _config.ToolOptions,
+ _config.ToolOptions,
+ loggerFactory.CreateLogger<ToolExecutor>(),
_toolMiddlewares);
var llmExecutor = new LLMExecutor(
diff --git a/AgentCore/Conversation/ContentDelta.cs b/AgentCore/Conversation/ContentDelta.cs
index 2beaa15..8347d01 100644
--- a/AgentCore/Conversation/ContentDelta.cs
+++ b/AgentCore/Conversation/ContentDelta.cs
@@ -16,4 +16,4 @@ public sealed record ToolCallDelta(
string? ArgumentsDelta
) : IContentDelta;
-public sealed record MetaDelta(FinishReason FinishReason, TokenUsage? TokenUsage) : IContentDelta;
+public sealed record MetaDelta(FinishReason? FinishReason, TokenUsage? TokenUsage) : IContentDelta;
diff --git a/AgentCore/Json/JsonSchemaExtensions.cs b/AgentCore/Json/JsonSchemaExtensions.cs
index 4b7ba26..8ef199b 100644
--- a/AgentCore/Json/JsonSchemaExtensions.cs
+++ b/AgentCore/Json/JsonSchemaExtensions.cs
@@ -34,7 +34,7 @@ public static class JsonSchemaExtensions
var result = BuildSchema(type, visited);
if (visited.Count == 0)
- _schemaCache.TryAdd(type, result);
+ _schemaCache.TryAdd(type, (JsonObject)result.DeepClone());
return result;
}
@@ -138,25 +138,25 @@ public static class JsonSchemaExtensions
switch (type)
{
case "string":
- if (kind != JsonValueKind.String) errors.Add(new SchemaValidationError(path, path, "Expected string", "type_error"));
+ if (kind != JsonValueKind.String) errors.Add(new SchemaValidationError(path, path, $"Expected string, got {kind}", "type_error"));
break;
case "integer":
- if (kind != JsonValueKind.Number) errors.Add(new SchemaValidationError(path, path, "Expected integer", "type_error"));
+ if (kind != JsonValueKind.Number) errors.Add(new SchemaValidationError(path, path, $"Expected integer, got {kind}", "type_error"));
break;
case "number":
- if (kind != JsonValueKind.Number) errors.Add(new SchemaValidationError(path, path, "Expected number", "type_error"));
+ if (kind != JsonValueKind.Number) errors.Add(new SchemaValidationError(path, path, $"Expected number, got {kind}", "type_error"));
break;
case "boolean":
- if (kind != JsonValueKind.True && kind != JsonValueKind.False) errors.Add(new SchemaValidationError(path, path, "Expected boolean", "type_error"));
+ if (kind != JsonValueKind.True && kind != JsonValueKind.False) errors.Add(new SchemaValidationError(path, path, $"Expected boolean, got {kind}", "type_error"));
break;
case "array":
- if (kind != JsonValueKind.Array) errors.Add(new SchemaValidationError(path, path, "Expected array", "type_error"));
+ if (kind != JsonValueKind.Array) errors.Add(new SchemaValidationError(path, path, $"Expected array, got {kind}", "type_error"));
else if (schema["items"] is JsonObject itemSchema)
for (int i = 0; i < node.AsArray().Count; i++)
errors.AddRange(itemSchema.Validate(node.AsArray()[i], $"{path}[{i}]"));
break;
case "object":
- if (kind != JsonValueKind.Object) errors.Add(new SchemaValidationError(path, path, "Expected object", "type_error"));
+ if (kind != JsonValueKind.Object) errors.Add(new SchemaValidationError(path, path, $"Expected object, got {kind}", "type_error"));
else if (schema["properties"] is JsonObject props)
{
var objNode = node.AsObject();
@@ -176,6 +176,19 @@ public static class JsonSchemaExtensions
errors.AddRange(childSchema.Validate(objNode[key], $"{path}.{key}".Trim('.')));
}
}
+
+ if (schema[JsonSchemaConstants.AdditionalPropertiesKey] is JsonValue ap
+ && ap.GetValue<bool>() == false)
+ {
+ var schemaKeys = props.Select(p => p.Key).ToHashSet();
+ foreach (var key in objNode.Select(k => k.Key))
+ {
+ if (!schemaKeys.Contains(key))
+ errors.Add(new SchemaValidationError(key, $"{path}.{key}".Trim('.'),
+ $"Unknown property '{key}'. Expected properties: [{string.Join(", ", schemaKeys)}]",
+ "unexpected_key"));
+ }
+ }
}
break;
}
diff --git a/AgentCore/LLM/LLMEvent.cs b/AgentCore/LLM/LLMEvent.cs
index cfe78a3..a31752d 100644
--- a/AgentCore/LLM/LLMEvent.cs
+++ b/AgentCore/LLM/LLMEvent.cs
@@ -16,5 +16,6 @@ public sealed record LLMMetaEvent(
FinishReason FinishReason,
string ModelName,
TimeSpan? Duration = null,
+ int ToolSchemaTokens = 0,
Dictionary<string, object>? Extra = null
) : LLMEvent;
diff --git a/AgentCore/LLM/LLMExecutor.cs b/AgentCore/LLM/LLMExecutor.cs
index d7347d4..90aef43 100644
--- a/AgentCore/LLM/LLMExecutor.cs
+++ b/AgentCore/LLM/LLMExecutor.cs
@@ -59,8 +59,10 @@ public sealed class LLMExecutor : ILLMExecutor
var sw = Stopwatch.StartNew();
var tools = _toolRegistry.Tools;
+ var toolNames = tools?.Select(t => t.Name).ToList() ?? [];
+ var toolNamesStr = string.Join(", ", toolNames);
- _logger.LogTrace("LLM request: {Model} {Options}", options.Model, options);
+ _logger.LogTrace("LLM request: Model={Model} Tools=[{ToolNames}]", options.Model, toolNamesStr);
var content = _provider.StreamAsync(messages, options, tools, ct);
@@ -115,24 +117,45 @@ public sealed class LLMExecutor : ILLMExecutor
if (evt != null) yield return evt;
}
+ var effectiveUsage = tokenUsage ?? TokenUsage.Empty;
+ var toolSchemaTokens = EstimateToolSchemaTokens(tools);
+
if (tokenUsage != null)
{
_tokenManager.Record(tokenUsage);
- yield return new LLMMetaEvent(
- tokenUsage,
- finishReason ?? FinishReason.Stop,
- options.Model,
- sw.Elapsed);
if (_tokenCounter is ApproximateTokenCounter approx)
{
approx.Calibrate(messages, tokenUsage.InputTokens);
}
}
+ else
+ {
+ _logger.LogDebug("Provider did not report token usage for FinishReason={FinishReason}", finishReason);
+ }
+
+ yield return new LLMMetaEvent(
+ effectiveUsage,
+ finishReason ?? FinishReason.Stop,
+ options.Model,
+ sw.Elapsed,
+ toolSchemaTokens);
sw.Stop();
_logger.LogDebug("LLM call finished: {FinishReason} Duration={Ms}ms", finishReason, sw.ElapsedMilliseconds);
- if (tokenUsage != null)
- _logger.LogTrace("Token usage: In={In} Out={Out}", tokenUsage.InputTokens, tokenUsage.OutputTokens);
+ _logger.LogTrace("Token usage: In={In} Out={Out} ToolSchemas={ToolSchemas}", effectiveUsage.InputTokens, effectiveUsage.OutputTokens, toolSchemaTokens);
+ }
+
+ private static int EstimateToolSchemaTokens(IReadOnlyList<AgentCore.Tooling.Tool>? tools)
+ {
+ if (tools == null || tools.Count == 0) return 0;
+
+ int totalChars = 0;
+ foreach (var tool in tools)
+ {
+ var json = System.Text.Json.JsonSerializer.Serialize(tool);
+ totalChars += json?.Length ?? 0;
+ }
+ return (int)(totalChars / 4.0 * 1.15);
}
private static ToolCallEvent? ParseToolCall(string id, string name, string argsStr)
diff --git a/AgentCore/Tokens/SummarizingContextManager.cs b/AgentCore/Tokens/SummarizingContextManager.cs
index 17fc4fe..3ecca44 100644
--- a/AgentCore/Tokens/SummarizingContextManager.cs
+++ b/AgentCore/Tokens/SummarizingContextManager.cs
@@ -22,6 +22,8 @@ public sealed class SummarizingContextManager(
if (usage < 0.90 || _provider == null) return chat;
+ _logger.LogInformation("Context compaction triggered: {Used}/{Limit} ({Pct:F1}%)", totalTokens, ctxLen, usage * 100);
+
int startIndex = 0;
for (int i = chat.Count - 1; i >= 0; i--)
{
@@ -54,9 +56,12 @@ public sealed class SummarizingContextManager(
if (evt is TextDelta td) sb.Append(td.Value);
}
- var summaryMsg = new Message(Role.System, new Summary(sb.ToString().Trim()));
+ var summaryContent = sb.ToString().Trim();
+ var summaryMsg = new Message(Role.System, new Summary(summaryContent));
int insertIndex = chat.Count - keepCount;
chat.Insert(insertIndex, summaryMsg);
+
+ _logger.LogTrace("Summary content produced: {Summary}", summaryContent.Length > 500 ? summaryContent[..500] + "..." : summaryContent);
int after = await _counter.CountAsync(chat.GetActiveWindow(), ct).ConfigureAwait(false);
_logger.LogDebug("Compacted [summarize]: {Before}→{After} ({Saved:P0})",
diff --git a/AgentCore/Tokens/TokenManager.cs b/AgentCore/Tokens/TokenManager.cs
index 11acb3b..aab08ac 100644
--- a/AgentCore/Tokens/TokenManager.cs
+++ b/AgentCore/Tokens/TokenManager.cs
@@ -5,6 +5,8 @@ namespace AgentCore.Tokens;
public sealed record TokenUsage(int InputTokens = 0, int OutputTokens = 0, int ReasoningTokens = 0)
{
public int Total => InputTokens + OutputTokens + ReasoningTokens;
+ public static TokenUsage Empty => new(0, 0, 0);
+ public bool IsEmpty => InputTokens == 0 && OutputTokens == 0 && ReasoningTokens == 0;
}
public interface ITokenManager
diff --git a/AgentCore/Tooling/ToolExecutor.cs b/AgentCore/Tooling/ToolExecutor.cs
index 9b01f4b..ac93ffb 100644
--- a/AgentCore/Tooling/ToolExecutor.cs
+++ b/AgentCore/Tooling/ToolExecutor.cs
@@ -3,6 +3,8 @@ using AgentCore.Diagnostics;
using AgentCore.Execution;
using AgentCore.Json;
using AgentCore.Utils;
+using Microsoft.Extensions.Logging;
+using System.Diagnostics;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Nodes;
@@ -21,14 +23,17 @@ public sealed class ToolExecutor : IToolExecutor
private readonly ToolOptions _options;
private readonly SemaphoreSlim _semaphore;
private readonly PipelineHandler<ToolCall, Task<ToolResult>> _pipeline;
+ private readonly ILogger<ToolExecutor> _logger;
public ToolExecutor(
IToolRegistry tools,
ToolOptions options,
+ ILogger<ToolExecutor> logger,
IEnumerable<PipelineMiddleware<ToolCall, Task<ToolResult>>>? middlewares = null)
{
_tools = tools;
_options = options;
+ _logger = logger;
_semaphore = new SemaphoreSlim(options.MaxConcurrency);
_pipeline = Pipeline<ToolCall, Task<ToolResult>>.Build(
@@ -51,11 +56,15 @@ public sealed class ToolExecutor : IToolExecutor
if (string.IsNullOrWhiteSpace(call.Name))
return new ToolResult(call.Id, new ToolValidationException("Unknown", "Name", "Tool name cannot be empty."));
+ var argsJson = call.Arguments?.ToString() ?? "{}";
+ _logger.LogDebug("Executing tool: {Name} Args={ArgsJson}", call.Name, argsJson.Length > 500 ? argsJson[..500] + "..." : argsJson);
+
await _semaphore.WaitAsync(ct).ConfigureAwait(false);
CancellationTokenSource? timeoutCts = null;
CancellationTokenSource? linkedCts = null;
CancellationToken runCt = ct;
+ var sw = Stopwatch.StartNew();
if (_options.DefaultTimeout.HasValue)
{
@@ -67,16 +76,23 @@ public sealed class ToolExecutor : IToolExecutor
try
{
var result = await InvokeInternalAsync(call, runCt).ConfigureAwait(false);
+ sw.Stop();
+ _logger.LogDebug("Tool completed: {Name} Duration={Ms}ms", call.Name, sw.ElapsedMilliseconds);
+ _logger.LogTrace("Tool result: {Name} Result={Content}", call.Name, result?.ForLlm()?.Length > 200 ? result.ForLlm()[..200] + "..." : result?.ForLlm());
return new ToolResult(call.Id, result);
}
catch (OperationCanceledException ex) when (timeoutCts?.IsCancellationRequested == true)
{
+ sw.Stop();
+ _logger.LogWarning("Tool failed: {Name} Error={Message}", call.Name, $"Tool execution timed out after {_options.DefaultTimeout!.Value.TotalSeconds} seconds.");
return new ToolResult(call.Id, new ToolExecutionException(call.Name, $"Tool execution timed out after {_options.DefaultTimeout!.Value.TotalSeconds} seconds.", ex));
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
+ sw.Stop();
var wrapped = ex is ToolExecutionException tex ? tex : new ToolExecutionException(call.Name, ex.Message, ex);
+ _logger.LogWarning("Tool failed: {Name} Error={Message}", call.Name, wrapped.Message);
return new ToolResult(call.Id, wrapped);
}
finally
@@ -109,6 +125,19 @@ public sealed class ToolExecutor : IToolExecutor
if (parameters.Length == 1 && !parameters[0].ParameterType.IsSimpleType() && !argsObj.ContainsKey(parameters[0].Name!))
argsObj = new JsonObject { [parameters[0].Name!] = argsObj };
+ var expectedNames = parameters
+ .Where(p => p.ParameterType != typeof(CancellationToken) && p.Name != null)
+ .Select(p => p.Name!)
+ .ToHashSet(StringComparer.OrdinalIgnoreCase);
+ var unknownKeys = argsObj.Select(kv => kv.Key)
+ .Where(k => !expectedNames.Contains(k))
+ .ToList();
+ if (unknownKeys.Count > 0)
+ {
+ throw new ToolValidationException(toolName, unknownKeys[0],
+ $"Unknown parameter(s): [{string.Join(", ", unknownKeys)}]. Expected: [{FormatExpectedParams(parameters)}].");
+ }
+
var values = new List<object?>();
foreach (var p in parameters)
@@ -121,7 +150,8 @@ public sealed class ToolExecutor : IToolExecutor
if (node == null)
{
if (p.HasDefaultValue) values.Add(p.DefaultValue);
- else throw new ToolValidationException(toolName, p.Name!, "Missing required parameter.");
+ else throw new ToolValidationException(toolName, p.Name!,
+ $"Missing required parameter '{p.Name}' (type: {p.ParameterType.MapClrTypeToJsonType()}). Expected parameters: [{FormatExpectedParams(parameters)}].");
continue;
}
@@ -136,6 +166,20 @@ public sealed class ToolExecutor : IToolExecutor
return values.ToArray();
}
+ private static string FormatExpectedParams(ParameterInfo[] parameters)
+ => string.Join(", ", parameters
+ .Where(p => p.ParameterType != typeof(CancellationToken) && p.Name != null)
+ .Select(p =>
+ {
+ var type = p.ParameterType.MapClrTypeToJsonType();
+ var opt = p.HasDefaultValue ? ", optional" : "";
+ var underlying = Nullable.GetUnderlyingType(p.ParameterType) ?? p.ParameterType;
+ var enumVals = underlying.IsEnum
+ ? $", one of: {string.Join("|", Enum.GetNames(underlying))}"
+ : "";
+ return $"{p.Name} ({type}{opt}{enumVals})";
+ }));
+
private static readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions
{
Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() }
@@ -173,7 +217,7 @@ public abstract class ToolException : Exception, IContent
ToolName = toolName;
}
public virtual string ForLlm()
- => $"{ToolName}: {Message}";
+ => $"Error calling tool '{ToolName}': {Message}";
}
public sealed class ToolExecutionException : ToolException
{
@@ -188,7 +232,8 @@ public sealed class ToolValidationAggregateException : ToolException
{
Errors = errors.ToList();
}
- public override string ForLlm() => $"{ToolName}: {Message}";
+ public override string ForLlm()
+ => $"Error calling tool '{ToolName}': {string.Join("; ", Errors.Select(e => e.Message))}";
}
public sealed class ToolValidationException : ToolException
{
@@ -198,4 +243,6 @@ public sealed class ToolValidationException : ToolException
{
ParamName = paramName;
}
+ public override string ForLlm()
+ => $"Error calling tool '{ToolName}', parameter '{ParamName}': {Message}";
}
diff --git a/TestApp/ChatBotAgent.cs b/TestApp/ChatBotAgent.cs
index 3e91297..e62313d 100644
--- a/TestApp/ChatBotAgent.cs
+++ b/TestApp/ChatBotAgent.cs
@@ -38,7 +38,7 @@ namespace TestApp
.WithProvider(MEAILLMClient.Create("http://127.0.0.1:1234/v1", "model", "lmstudio"), new LLMOptions
{
ContextLength = 8000,
- ReasoningEffort = AgentCore.LLM.ReasoningEffort.High
+ ReasoningEffort = AgentCore.LLM.ReasoningEffort.Low,
})
.WithTools<GeoTools>()
.WithTools<WeatherTool>()
commit 655b445a1860f1c8120cc2b16dda22af94dc7850
Author: MrRazor22 <senthilvenkat22@gmail.com>
Date: Sun Mar 29 22:34:15 2026 +0530
reasoning works now!
diff --git a/AgentCore.MEAI/AgentCore.MEAI.csproj b/AgentCore.MEAI/AgentCore.MEAI.csproj
index 9a5fe8c..e43de43 100644
--- a/AgentCore.MEAI/AgentCore.MEAI.csproj
+++ b/AgentCore.MEAI/AgentCore.MEAI.csproj
@@ -7,8 +7,10 @@
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="Microsoft.Extensions.AI.Abstractions" Version="10.3.0" />
- <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.1" />
+ <PackageReference Include="Microsoft.Extensions.AI.Abstractions" Version="10.4.1" />
+ <PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="10.4.1" />
+ <PackageReference Include="OpenAI" Version="2.9.1" />
+ <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.2" />
</ItemGroup>
<ItemGroup>
diff --git a/AgentCore.MEAI/MEAIExtensions.cs b/AgentCore.MEAI/MEAIExtensions.cs
index daada5b..3f177c7 100644
--- a/AgentCore.MEAI/MEAIExtensions.cs
+++ b/AgentCore.MEAI/MEAIExtensions.cs
@@ -18,17 +18,24 @@ internal static class MEAIExtensions
Role = msg.Role.ToMEAIChatRole()
};
- if (msg.Content is Text t)
+ foreach (var content in msg.Contents)
{
- chatMsg.Contents.Add(new TextContent(t.Value));
- }
- else if (msg.Content is ToolCall tc)
- {
- chatMsg.Contents.Add(new FunctionCallContent(tc.Id, tc.Name, tc.Arguments.ToDictionary()));
- }
- else if (msg.Content is ToolResult tr)
- {
- chatMsg.Contents.Add(new FunctionResultContent(tr.CallId, tr.Result?.AsJsonString() ?? "{}"));
+ if (content is Text t)
+ {
+ chatMsg.Contents.Add(new TextContent(t.Value));
+ }
+ else if (content is Reasoning r)
+ {
+ chatMsg.Contents.Add(new Microsoft.Extensions.AI.TextReasoningContent(r.Thought));
+ }
+ else if (content is ToolCall tc)
+ {
+ chatMsg.Contents.Add(new FunctionCallContent(tc.Id, tc.Name, tc.Arguments.ToDictionary()));
+ }
+ else if (content is ToolResult tr)
+ {
+ chatMsg.Contents.Add(new FunctionResultContent(tr.CallId, tr.Result?.AsJsonString() ?? "{}"));
+ }
}
yield return chatMsg;
diff --git a/AgentCore.MEAI/MEAILLMClient.cs b/AgentCore.MEAI/MEAILLMClient.cs
index 4e9ed73..b251c30 100644
--- a/AgentCore.MEAI/MEAILLMClient.cs
+++ b/AgentCore.MEAI/MEAILLMClient.cs
@@ -3,12 +3,26 @@ using AgentCore.LLM;
using AgentCore.Tokens;
using AgentCore.Tooling;
using Microsoft.Extensions.AI;
+using OpenAI;
+using OpenAI.Chat;
+using System.ClientModel;
using System.Runtime.CompilerServices;
namespace AgentCore.Providers.MEAI;
-internal sealed class MEAILLMClient(IChatClient _client) : ILLMProvider
+public sealed class MEAILLMClient(IChatClient _client) : ILLMProvider
{
+ public static MEAILLMClient Create(string baseUrl, string model, string? apiKey = null)
+ {
+ var credentials = new ApiKeyCredential(apiKey ?? "not-needed");
+ var options = new OpenAIClientOptions { Endpoint = new Uri(baseUrl) };
+ var openAiClient = new OpenAIClient(credentials, options);
+
+ var chatClient = openAiClient.GetChatClient(model);
+ var meaiClient = chatClient.AsIChatClient();
+ return new MEAILLMClient(meaiClient);
+ }
+
public async IAsyncEnumerable<IContentDelta> StreamAsync(
IReadOnlyList<Message> messages,
LLMOptions options,
@@ -39,8 +53,12 @@ internal sealed class MEAILLMClient(IChatClient _client) : ILLMProvider
yield return new TextDelta(t.Text);
break;
+ case Microsoft.Extensions.AI.TextReasoningContent tr:
+ if (!string.IsNullOrEmpty(tr.Text))
+ yield return new ReasoningDelta(tr.Text);
+ break;
+
case FunctionCallContent fc:
- // MEAI delivers function call updates.
yield return new ToolCallDelta(
Index: 0,
Id: fc.CallId,
@@ -52,12 +70,15 @@ internal sealed class MEAILLMClient(IChatClient _client) : ILLMProvider
break;
case UsageContent u:
- yield return new MetaDelta(
- AgentCore.LLM.FinishReason.Stop,
- new TokenUsage(
- (int)u.Details.InputTokenCount,
- (int)u.Details.OutputTokenCount,
- (int)u.Details.ReasoningTokenCount));
+ if (u.Details != null)
+ {
+ yield return new MetaDelta(
+ AgentCore.LLM.FinishReason.Stop,
+ new TokenUsage(
+ (int)(u.Details.InputTokenCount ?? 0),
+ (int)(u.Details.OutputTokenCount ?? 0),
+ (int)(u.Details.ReasoningTokenCount ?? 0)));
+ }
break;
}
}
diff --git a/AgentCore.OpenAI/AgentCore.OpenAI.csproj b/AgentCore.OpenAI/AgentCore.OpenAI.csproj
index 048af9e..3d7ad7b 100644
--- a/AgentCore.OpenAI/AgentCore.OpenAI.csproj
+++ b/AgentCore.OpenAI/AgentCore.OpenAI.csproj
@@ -13,7 +13,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="OpenAI" Version="2.8.0" />
+ <PackageReference Include="OpenAI" Version="2.9.1" />
<PackageReference Include="SharpToken" Version="2.0.4" />
</ItemGroup>
diff --git a/AgentCore.OpenAI/OpenAIExtensions.cs b/AgentCore.OpenAI/OpenAIExtensions.cs
index aeccdf6..1b39230 100644