-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathKernelConfigExtensions.cs
More file actions
972 lines (839 loc) · 40.6 KB
/
Copy pathKernelConfigExtensions.cs
File metadata and controls
972 lines (839 loc) · 40.6 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
/**
* Last Modified: 20231207 By FelixJ
* 修改了一些拼写错误
* 更新了部分方法的XML注释以符合代码
*/
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.VectorData;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.InMemory;
using Microsoft.SemanticKernel.Connectors.Qdrant;
using Microsoft.SemanticKernel.Connectors.Redis;
using OllamaSharp.Models;
using Qdrant.Client;
using Senparc.AI.Entities;
using Senparc.AI.Entities.Keys;
using Senparc.AI.Exceptions;
using Senparc.AI.Interfaces;
using Senparc.AI.Kernel.Entities;
using Senparc.AI.Kernel.Helpers;
using Senparc.CO2NET.Extensions;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Senparc.AI.Interfaces.VectorDB;
namespace Senparc.AI.Kernel.Handlers
{
/// <summary>
/// Kernel 及模型设置的扩展类
/// </summary>
public static partial class KernelConfigExtension
{
#region 初始化
public static IWantToConfig IWantTo(this SemanticAiHandler handler, ISenparcAiSetting senparcAiSetting = null)
{
var iWantTo = new IWantToConfig(new IWantTo(handler, senparcAiSetting));
return iWantTo;
}
#endregion
#region 配置 Kernel 生成条件
/// <summary>
/// 配置模型
/// </summary>
/// <param name="iWantToConfig"></param>
/// <param name="configModel"></param>
/// <param name="userId"></param>
/// <param name="modelName">模型名称配置,如果为 null,则从配置中自动获取</param>
/// <param name="senparcAiSetting"></param>
/// <param name="deploymentName"></param>
/// <returns></returns>
/// <exception cref="SenparcAiException"></exception>
public static IWantToConfig ConfigModel(this IWantToConfig iWantToConfig, ConfigModel configModel, string userId, ModelName modelName = null,
ISenparcAiSetting? senparcAiSetting = null, string deploymentName = null)
{
var iWantTo = iWantToConfig.IWantTo;
var existedKernelBuilder = iWantToConfig.IWantTo.KernelBuilder;
senparcAiSetting ??= iWantTo.SenparcAiSetting;
modelName ??= senparcAiSetting.ModelName;
string modelNameStr;
Func<string, string> GetDeploymentName = (modelNameStr) =>
{
if (!deploymentName.IsNullOrEmpty())
{
return deploymentName;
}
else if (!senparcAiSetting.DeploymentName.IsNullOrEmpty())
{
return senparcAiSetting.DeploymentName;
}
return modelNameStr;
};
IKernelBuilder kernelBuilder;
switch (configModel)
{
case AI.ConfigModel.Chat:
modelNameStr = modelName.Chat;
kernelBuilder = iWantTo.SemanticKernelHelper.ConfigChat(userId, modelNameStr, senparcAiSetting,
existedKernelBuilder, GetDeploymentName(modelNameStr));
break;
case AI.ConfigModel.TextCompletion:
modelNameStr = modelName.TextCompletion;
kernelBuilder = iWantTo.SemanticKernelHelper.ConfigTextCompletion(userId, modelNameStr, senparcAiSetting,
existedKernelBuilder, GetDeploymentName(modelNameStr));
break;
case AI.ConfigModel.TextEmbedding:
modelNameStr = modelName.Embedding;
kernelBuilder = iWantTo.SemanticKernelHelper.ConfigTextEmbeddingGeneration(userId, modelNameStr, senparcAiSetting, existedKernelBuilder, GetDeploymentName(modelNameStr));
break;
case AI.ConfigModel.TextToImage:
modelNameStr = modelName.TextToImage;
kernelBuilder = iWantTo.SemanticKernelHelper.ConfigImageGeneration(userId, existedKernelBuilder, modelNameStr, senparcAiSetting, GetDeploymentName(modelNameStr));
//Console.WriteLine($"[调试]GetDeploymentName:{modelNameStr} / {GetDeploymentName(modelNameStr)}");
//Console.WriteLine($"[调试]{senparcAiSetting.AiPlatform}-{senparcAiSetting.AzureOpenAIKeys.DeploymentName}-{senparcAiSetting.AzureOpenAIKeys.AzureEndpoint}\r\n{senparcAiSetting.AzureOpenAIKeys.ModelName.ToJson(true)}");
break;
default:
throw new SenparcAiException("未处理当前 ConfigModel 类型:" + configModel);
}
iWantTo.KernelBuilder = kernelBuilder; //进行 Config 必须提供 Kernel
iWantTo.UserId = userId;
iWantTo.ModelName = modelNameStr;
return iWantToConfig;
}
///// <summary>
///// 添加 TextCompletion 配置
///// </summary>
///// <param name="iWantToConfig"></param>
///// <param name="modelName">如果为 null,则从先前配置中读取</param>
///// <returns></returns>
///// <exception cref="SenparcAiException"></exception>
//public static IWantToConfig AddTextCompletion(this IWantToConfig iWantToConfig, string? modelName = null)
//{
// var aiPlatForm = iWantToConfig.IWantTo.SemanticKernelHelper.AiSetting.AiPlatform;
// var kernel = iWantToConfig.IWantTo.Kernel;
// var skHelper = iWantToConfig.IWantTo.SemanticKernelHelper;
// var aiSetting = skHelper.AiSetting;
// var userId = iWantToConfig.IWantTo.UserId;
// modelName ??= iWantToConfig.IWantTo.ModelName;
// var serviceId = skHelper.GetServiceId(userId, modelName);
// //TODO 需要判断 Kernel.TextCompletionServices.ContainsKey(serviceId),如果存在则不能再添加
// kernel.Config.AddTextCompletionService(serviceId, k =>
// aiPlatForm switch
// {
// AiPlatform.OpenAI => new OpenAITextCompletion(modelName, aiSetting.ApiKey, aiSetting.OrganizationId),
// AiPlatform.AzureOpenAI => new AzureTextCompletion(modelName, aiSetting.AzureEndpoint, aiSetting.ApiKey, aiSetting.AzureOpenAIApiVersion),
// _ => throw new SenparcAiException($"没有处理当前 {nameof(AiPlatform)} 类型:{aiPlatForm}")
// }
// );
// return iWantToConfig;
//}
#endregion
#region Vector Database
/// <summary>
/// Config Vector Database
/// </summary>
/// <param name="iWantToConfig"></param>
/// <param name="vectorDb"></param>
/// <returns></returns>
public static IWantToConfig ConfigVectorStore(this IWantToConfig iWantToConfig, VectorDB vectorDb
/*ISenparcAiSetting? senparcAiSetting = null*/)
{
var kb = iWantToConfig.SemanticKernelHelper.KernelBuilder;
var servives = kb.Services;
switch (vectorDb.Type)
{
case VectorDBType.Memory:
{
servives.AddInMemoryVectorStore();
break;
}
case VectorDBType.HardDisk:
{
servives.AddInMemoryVectorStore();
break;
}
//case VectorDBType.Qdrant:
// {
// servives.AddQdrantVectorStore(vectorDb.ConnectionString);
// break;
// }
case VectorDBType.Redis:
{
servives.AddRedisVectorStore(vectorDb.ConnectionString);
break;
}
case VectorDBType.Milvus:
{
// servives.AddInMemoryVectorStore();
break;
}
case VectorDBType.Chroma:
{
// servives.AddInMemoryVectorStore();
break;
}
case VectorDBType.PostgreSQL:
{
// servives.AddInMemoryVectorStore();
break;
}
case VectorDBType.Sqlite:
{
// servives.AddInMemoryVectorStore();
break;
}
case VectorDBType.SqlServer:
{
break;
}
case VectorDBType.Qdrant:
{
servives.AddQdrantVectorStore(vectorDb.ConnectionString);
break;
}
default:
{
throw new ArgumentOutOfRangeException(nameof(vectorDb.Type), $"Unsupported VectorDB type: {vectorDb.Type}");
}
}
return iWantToConfig;
}
/// <summary>
/// Get Vector Collection
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TRecord"></typeparam>
/// <param name="iWwantToRun"></param>
/// <param name="vectorDb"></param>
/// <param name="name"></param>
/// <param name="vectorStoreRecordDefinition"></param>
/// <returns></returns>
/// <remarks>
/// Note: VectorStore instances created in this method are not explicitly disposed.
/// The VectorStoreCollection returned may maintain a reference to the VectorStore and require it to remain alive.
/// For proper resource management, consider using dependency injection to manage VectorStore lifecycle
/// or ensure the collection is disposed when no longer needed.
/// </remarks>
public static VectorStoreCollection<TKey, TRecord> GetVectorCollection<TKey, TRecord>(this IWantToRun iWwantToRun, VectorDB vectorDb, string name, VectorStoreCollectionDefinition? vectorStoreRecordDefinition = null)
where TKey : notnull
where TRecord : class
{
IDatabase database;
VectorStore vectorStore;
VectorStoreCollection<TKey, TRecord> collection = null;
//TODO: If the logic becomes overly complex in the future, different combinations can be considered to be separated into different libraries
switch (vectorDb.Type)
{
case VectorDBType.Memory:
{
vectorStore = new InMemoryVectorStore();
collection = vectorStore.GetCollection<TKey, TRecord>(name, vectorStoreRecordDefinition);
break;
}
case VectorDBType.HardDisk:
{
break;
}
case VectorDBType.Redis:
{
database = ConnectionMultiplexer.Connect(vectorDb.ConnectionString).GetDatabase();
vectorStore = new RedisVectorStore(database,
new() { StorageType = RedisStorageType.Json });
collection = vectorStore.GetCollection<TKey, TRecord>(name, vectorStoreRecordDefinition);
break;
}
case VectorDBType.Milvus:
{
break;
}
case VectorDBType.Chroma:
{
break;
}
case VectorDBType.PostgreSQL:
{
break;
}
case VectorDBType.Sqlite:
{
break;
}
case VectorDBType.SqlServer:
{
break;
}
case VectorDBType.Qdrant:
{
vectorStore = new QdrantVectorStore(new QdrantClient(vectorDb.ConnectionString), ownsClient: true);
collection = vectorStore.GetCollection<TKey, TRecord>(name, vectorStoreRecordDefinition);
break;
}
default:
vectorStore = new InMemoryVectorStore();
collection = vectorStore.GetCollection<TKey, TRecord>(name, vectorStoreRecordDefinition);
break;
}
return collection;
}
#endregion
#region Build Kernel
public static IWantToRun BuildKernel(this IWantToConfig iWantToConfig, Action<IKernelBuilder>? kernelBuilderAction = null)
{
var iWantTo = iWantToConfig.IWantTo;
var handler = iWantTo.SemanticKernelHelper;
handler.BuildKernel(iWantTo.KernelBuilder, kernelBuilderAction);
return new IWantToRun(new IWantToBuild(iWantToConfig));
}
//#pragma warning disable SKEXP0052
//public static IWantToRun BuildMemoryKernel(this IWantToConfig iWantToConfig, Action<MemoryBuilder>? kernelBuilderAction = null)
//{
// var iWantTo = iWantToConfig.IWantTo;
// var handler = iWantTo.SemanticKernelHelper;
// handler.BuildKernel(iWantTo.KernelBuilder, kernelBuilderAction);
// return new IWantToRun(new IWantToBuild(iWantToConfig));
//}
#endregion
#region 运行准备
/// <summary>
/// 创建请求实体
/// </summary>
/// <param name="iWantToRun"></param>
/// <param name="requestContent"></param>
/// <param name="useAllRegisteredFunctions">是否使用所有已经注册、创建过的 Function</param>
/// <param name="pipeline"></param>
/// <returns></returns>
public static SenparcAiRequest CreateRequest(this IWantToRun iWantToRun, string? requestContent, bool useAllRegisteredFunctions = false,
params KernelFunction[] pipeline)
{
var iWantTo = iWantToRun.IWantToBuild.IWantToConfig.IWantTo;
if (useAllRegisteredFunctions && iWantToRun.Functions.Count > 0)
{
//合并已经注册的对象
pipeline = iWantToRun.Functions.Union(pipeline ?? new KernelFunction[0]).ToArray();
}
var request = new SenparcAiRequest(iWantToRun, iWantTo.UserId, requestContent!, iWantToRun.PromptConfigParameter,
pipeline);
return request;
}
/// <summary>
/// 创建请求实体,使用上下文,不提供单独的 prompt
/// </summary>
/// <param name="iWantToRun"></param>
/// <param name="useAllRegisteredFunctions">是否使用所有已经注册、创建过的 Function</param>
/// <param name="pipeline"></param>
/// <returns></returns>
public static SenparcAiRequest CreateRequest(this IWantToRun iWantToRun, bool useAllRegisteredFunctions = false, params KernelFunction[] pipeline)
{
return CreateRequest(iWantToRun, requestContent: null, useAllRegisteredFunctions, pipeline);
}
/// <summary>
/// 创建请求实体(不使用所有已经注册、创建过的 Function,也不储存行下文)
/// </summary>
/// <param name="iWantToRun"></param>
/// <param name="requestContent"></param>
/// <param name="pipeline"></param>
/// <returns></returns>
public static SenparcAiRequest CreateRequest(this IWantToRun iWantToRun, string requestContent, params KernelFunction[] pipeline)
{
return CreateRequest(iWantToRun, requestContent, false, pipeline);
}
/// <summary>
/// 创建请求实体
/// </summary>
/// <param name="iWantToRun"></param>
/// <param name="arguments"></param>
/// <param name="useAllRegisteredFunctions">是否使用所有已经注册、创建过的 Function</param>
/// <param name="pipeline"></param>
/// <returns></returns>
public static SenparcAiRequest CreateRequest(this IWantToRun iWantToRun, KernelArguments arguments,
bool useAllRegisteredFunctions = false, params KernelFunction[] pipeline)
{
var iWantTo = iWantToRun.IWantToBuild.IWantToConfig.IWantTo;
if (useAllRegisteredFunctions && iWantToRun.Functions.Count > 0)
{
//合并已经注册的对象
pipeline = iWantToRun.Functions.Union(pipeline ?? new KernelFunction[0]).ToArray();
}
var request = new SenparcAiRequest(iWantToRun, iWantTo.UserId, arguments, iWantToRun.PromptConfigParameter,
pipeline);
return request;
}
/// <summary>
/// 创建请求实体(不使用所有已经注册、创建过的 Function,也不储存行下文)
/// </summary>
/// <param name="iWantToRun"></param>
/// <param name="contextVariables"></param>
/// <param name="pipeline"></param>
/// <returns></returns>
public static SenparcAiRequest CreateRequest(this IWantToRun iWantToRun, KernelArguments contextVariables, params KernelFunction[] pipeline)
{
return CreateRequest(iWantToRun, contextVariables, false, pipeline);
}
#endregion
#region 运行阶段,或对生成后的 Kernel 进行补充设置
#region 对上下文的管理
/// <summary>
/// 设置上下文
/// </summary>
/// <param name="request"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static SenparcAiRequest SetTempContext(this SenparcAiRequest request, string key, string value)
{
request.TempAiArguments ??= new SenparcAiArguments();
request.TempAiArguments.KernelArguments.Set(key, value);
return request;
}
/// <summary>
/// 设置上下文
/// </summary>
/// <param name="request"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static SenparcAiRequest SetStoredContext(this SenparcAiRequest request, string key, object value)
{
request.StoreAiArguments.KernelArguments.Set(key, value);
return request;
}
/// <summary>
/// 获取上下文的值
/// </summary>
/// <param name="request"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool GetTempArguments(this SenparcAiRequest request, string key, out object? value)
{
return request.TempAiArguments.KernelArguments.TryGetValue(key, out value);
}
/// <summary>
/// 获取上下文的值
/// </summary>
/// <param name="request"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static bool GetStoredArguments(this SenparcAiRequest request, string key, out object? value)
{
return request.StoreAiArguments.KernelArguments.TryGetValue(key, out value);
}
#endregion
#region 运行
/// <summary>
/// 运行
/// </summary>
/// <param name="iWanToRun"></param>
/// <param name="request"></param>
/// <param name="inStreamItemProceessing">启用流,并指定遍历异步流每一步需要执行的委托。注意:只要此项不为 null,则会触发流式的请求。</param>
/// <returns></returns>
public static Task<SenparcKernelAiResult<string>> RunAsync(this IWantToRun iWanToRun, SenparcAiRequest request, Action<StreamingKernelContent> inStreamItemProceessing = null)
{
return RunAsync<string>(iWanToRun, request, inStreamItemProceessing);
}
/// <summary>
/// 运行
/// </summary>
/// <param name="iWanToRun"></param>
/// <param name="request"></param>
/// <param name="inStreamItemProceessing">启用流,并指定遍历异步流每一步需要执行的委托。注意:只要此项不为 null,则会触发流式的请求。</param>
/// <typeparam name="T">指定返回结果类型</typeparam>
/// <returns></returns>
public static async Task<SenparcKernelAiResult<T>> RunAsync<T>(this IWantToRun iWanToRun, SenparcAiRequest request, Action<StreamingKernelContent> inStreamItemProceessing = null)
{
var iWantTo = iWanToRun.IWantToBuild.IWantToConfig.IWantTo;
var helper = iWanToRun.SemanticKernelHelper;
var kernel = helper.GetKernel();
//var function = iWanToRun.KernelFunction;
var prompt = request.RequestContent;
var functionPipline = request.FunctionPipeline;
//var serviceId = helper.GetServiceId(iWantTo.UserId, iWantTo.ModelName);
//注意:只要使用了 Plugin 和 Function,并且包含输入标识,就需要使用上下文
iWanToRun.StoredAiArguments ??= new SenparcAiArguments();
var storedArguments = iWanToRun.StoredAiArguments.KernelArguments;
var tempArguments = request.TempAiArguments?.KernelArguments;
FunctionResult? functionResult = null;
var result = new SenparcKernelAiResult<T>(iWanToRun, inputContent: null);
var useStream = inStreamItemProceessing != null;
if (tempArguments != null && tempArguments.Count() != 0)
{
//输入特定的本次请求临时上下文
if (useStream)
{
result.StreamResult = kernel.InvokeStreamingAsync(functionPipline.FirstOrDefault(), tempArguments);
}
else
{
functionResult = await kernel.InvokeAsync(functionPipline.FirstOrDefault(), tempArguments);
}
result.InputContext = new SenparcAiArguments(tempArguments);
}
else if (!prompt.IsNullOrEmpty())
{
//tempArguments 为空
//输入纯文字
if (functionPipline?.Length > 0)
{
//使用 Pipleline
tempArguments = new() { ["input"] = prompt };
if (useStream)
{
result.StreamResult = kernel.InvokeStreamingAsync(functionPipline.First(), tempArguments);
}
else
{
//TODO: 此方法在 NeuCharAI 接口中,不会给服务器传送 Body 内容
functionResult = await kernel.InvokeAsync(functionPipline.First(), tempArguments);
}
}
else
{
//不适用 Pipline
//注意:此处即使直接输入 prompt 作为第一个 String 参数,也会被封装到 Context,
// 并赋值给 Key 为 INPUT 的参数
//var kernelFunction = iWanToRun.CreateFunctionFromPrompt(prompt ?? "").function;
if (useStream)
{
result.StreamResult = kernel.InvokePromptStreamingAsync(prompt ?? "", storedArguments);
}
else
{
functionResult = await kernel.InvokePromptAsync(prompt ?? "", storedArguments);
}
}
result.InputContent = prompt;
}
else
{
//输入缓存中的上下文
//botAnswer = await kernel.InvokeAsync(functionPipline.FirstOrDefault(), storedArguments);
if (useStream)
{
result.StreamResult = kernel.InvokeStreamingAsync(functionPipline.FirstOrDefault(), storedArguments);
}
else
{
functionResult = await kernel.InvokeAsync(functionPipline.FirstOrDefault(), storedArguments);
}
result.InputContext = new SenparcAiArguments(storedArguments);
}
result.InputContent = prompt;
if (!useStream)
{
try
{
if (typeof(T) == typeof(string))
{
result.OutputString = functionResult.GetValue<string>()?.TrimStart('\n') ?? "";
}
else
{
result.OutputString = functionResult.GetValue<T>()?.ToJson()?.TrimStart('\n') ?? "";
}
}
catch (Exception)
{
//TODO: 提供 Output 的泛型
result.OutputString = functionResult.GetValue<object>()?.ToJson()?.TrimStart('\n') ?? "";
_ = new SenparcAiException("无法转换为指定类型:" + typeof(T).Name);
}
result.Result = functionResult;
}
else
{
var stringResult = new StringBuilder();
if (result.StreamResult != null)
{
await foreach (var item in result.StreamResult)
{
stringResult.Append(item);
inStreamItemProceessing?.Invoke(item);//执行流
}
}
result.OutputString = stringResult.ToString();
}
//result.LastException = botAnswer.LastException;
return result;
}
/// <summary>
/// 使用 Stream(流)的方式运行
/// </summary>
/// <param name="iWanToRun"></param>
/// <param name="request"></param>
/// <param name="inStreamItemProceessing">启用流,并指定遍历异步流每一步需要执行的委托。</param>
/// <returns></returns>
public static Task<SenparcKernelAiResult<string>> RunStreamAsync(this IWantToRun iWanToRun, SenparcAiRequest request, Action<StreamingKernelContent> inStreamItemProceessing = null)
{
inStreamItemProceessing ??= (item) => { };
return RunAsync(iWanToRun, request, inStreamItemProceessing);
}
/// <summary>
/// 运行
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="iWanToRun"></param>
/// <param name="kernelFunction"></param>
/// <returns></returns>
public static async Task<SenparcKernelAiResult> RunAsync(this IWantToRun iWanToRun, KernelFunction kernelFunction)
{
var iWantTo = iWanToRun.IWantToBuild.IWantToConfig.IWantTo;
var helper = iWanToRun.SemanticKernelHelper;
var kernel = helper.GetKernel();
//var function = iWanToRun.KernelFunction;
var result = new SenparcKernelAiResult(iWanToRun, inputContent: null);
var kernelResult = await kernel.InvokeAsync(kernelFunction);
try
{
result.OutputString = kernelResult.GetValue<string>()?.TrimStart('\n') ?? "";
}
catch (Exception)
{
//TODO: 提供 Output 的泛型
result.OutputString = kernelResult.GetValue<object>()?.ToJson()?.TrimStart('\n') ?? "";
}
result.Result = kernelResult;
return result;
}
/// <summary>
/// 运行
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="iWanToRun"></param>
/// <param name="kernelFunction"></param>
/// <returns></returns>
public static async Task<SenparcAiResult<T>> RunAsync<T>(this IWantToRun iWanToRun, KernelFunction kernelFunction)
{
var iWantTo = iWanToRun.IWantToBuild.IWantToConfig.IWantTo;
var helper = iWanToRun.SemanticKernelHelper;
var kernel = helper.GetKernel();
//var function = iWanToRun.KernelFunction;
var result = new SenparcAiResult<T>(iWanToRun, inputContent: null);
var kernelResult = await kernel.InvokeAsync(kernelFunction);
try
{
if (typeof(T) == typeof(string))
{
result.OutputString = kernelResult.GetValue<string>()?.TrimStart('\n') ?? "";
}
else
{
result.OutputString = kernelResult.GetValue<T>()?.ToJson()?.TrimStart('\n') ?? "";
}
}
catch (Exception)
{
//TODO: 提供 Output 的泛型
result.OutputString = kernelResult.GetValue<object>()?.ToJson()?.TrimStart('\n') ?? "";
_ = new SenparcAiException("无法转换为指定类型:" + typeof(T).Name);
}
result.Result = kernelResult.GetValue<T>();
//result.LastException = botAnswer.LastException;
return result;
}
#endregion
#region Vision 模型运行
/// <summary>
/// 运行 Vision 模型
/// </summary>
/// <param name="iWanToRun"></param>
/// <param name="request"></param>
/// <param name="inStreamItemProceessing">启用流,并指定遍历异步流每一步需要执行的委托。注意:只要此项不为 null,则会触发流式的请求。</param>
/// <returns></returns>
public static Task<SenparcKernelAiResult<string>> RunVisionAsync(this IWantToRun iWanToRun,
SenparcAiRequest request, ChatHistory chatHistory, List<IContentItem> contentList,
Action<StreamingKernelContent> inStreamItemProceessing = null)
{
return RunVisionAsync<string>(iWanToRun, request, chatHistory, contentList, inStreamItemProceessing);
}
/// <summary>
/// 运行 Vision 模型
/// </summary>
/// <param name="iWanToRun"></param>
/// <param name="request"></param>
/// <param name="inStreamItemProceessing">启用流,并指定遍历异步流每一步需要执行的委托。注意:只要此项不为 null,则会触发流式的请求。</param>
/// <typeparam name="T">指定返回结果类型</typeparam>
/// <returns></returns>
public static async Task<SenparcKernelAiResult<T>> RunVisionAsync<T>(this IWantToRun iWanToRun,
SenparcAiRequest request, ChatHistory chatHistory, List<IContentItem> contentList,
Action<StreamingKernelContent> inStreamItemProceessing = null)
{
var iWantTo = iWanToRun.IWantToBuild.IWantToConfig.IWantTo;
var helper = iWanToRun.SemanticKernelHelper;
var kernel = helper.GetKernel();
//var function = iWanToRun.KernelFunction;
var prompt = request.RequestContent;
var functionPipline = request.FunctionPipeline;
//var serviceId = helper.GetServiceId(iWantTo.UserId, iWantTo.ModelName);
//注意:只要使用了 Plugin 和 Function,并且包含输入标识,就需要使用上下文
iWanToRun.StoredAiArguments ??= new SenparcAiArguments();
var storedArguments = iWanToRun.StoredAiArguments.KernelArguments;
var tempArguments = request.TempAiArguments?.KernelArguments;
FunctionResult? functionResult = null;
var result = new SenparcKernelAiResult<T>(iWanToRun, inputContent: null);
var useStream = inStreamItemProceessing != null;
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
ChatMessageContentItemCollection contentItems = new ChatMessageContentItemCollection();
foreach (var contentItem in contentList)
{
//if (contentItem.Type == Helpers.ContentType.Text)
//{
// contentItems.Add(new TextContent(contentItem.TextContent));
//}
//else if (contentItem.Type == Helpers.ContentType.Image)
//{
// contentItems.Add(new ImageContent_ImageBase64(contentItem.ImageData, "image/jpg"));
//}
if (contentItem is ContentItem_Text ciText)
{
contentItems.Add(new TextContent(ciText.TextContent));
}
else if (contentItem is ContentItem_ImageBse64 ciBae64)
{
contentItems.Add(new ImageContent(ciBae64.ImageData, "image/jpg"));
}
else if (contentItem is ContentItem_ImageUrl ciImageUrl)
{
contentItems.Add(new ImageContent("data:image/jpeg;base64," + ciImageUrl.image_url.Url));
}
}
chatHistory.AddUserMessage(contentItems);
var parameter = new PromptConfigParameter()
{
MaxTokens = 3500,
Temperature = 0.7,
TopP = 0.5,
};
PromptExecutionSettings? executionSettings = helper.GetExecutionSetting(parameter, helper.AiSetting);
if (useStream)
{
result.StreamResult = chatCompletionService.GetStreamingChatMessageContentsAsync(chatHistory, executionSettings: executionSettings, kernel: iWanToRun.Kernel);
var stringResult = new StringBuilder();
if (result.StreamResult != null)
{
await foreach (var item in result.StreamResult)
{
stringResult.Append(item);
inStreamItemProceessing?.Invoke(item);//执行流
}
}
result.OutputString = stringResult.ToString();
}
else
{
var contentResult = await chatCompletionService.GetChatMessageContentAsync(chatHistory, executionSettings: executionSettings, kernel: iWanToRun.Kernel);
//result.Result = contentResult;
result.OutputString = contentResult.ToString();
}
return result;
}
#region Chat
/// <summary>
/// 运行 Chat + Vision 模型
/// </summary>
/// <param name="iWanToRun"></param>
/// <param name="request"></param>
/// <param name="inStreamItemProceessing">启用流,并指定遍历异步流每一步需要执行的委托。注意:只要此项不为 null,则会触发流式的请求。</param>
/// <returns></returns>
public static Task<SenparcKernelAiResult<string>> RunChatVisionAsync(this IWantToRun iWanToRun,
SenparcAiRequest request, ChatHistory chatHistory, List<IContentItem> contentList,
PromptConfigParameter? parameter = null,
Action<StreamingKernelContent> inStreamItemProceessing = null)
{
return RunChatVisionAsync<string>(iWanToRun, request, chatHistory, contentList, parameter, inStreamItemProceessing);
}
/// <summary>
/// 运行 Chat + Vision 模型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="iWanToRun"></param>
/// <param name="request"></param>
/// <param name="chatHistory"></param>
/// <param name="contentList"></param>
/// <param name="parameter"></param>
/// <param name="inStreamItemProceessing"></param>
/// <returns></returns>
public static async Task<SenparcKernelAiResult<T>> RunChatVisionAsync<T>(this IWantToRun iWanToRun,
SenparcAiRequest request, ChatHistory chatHistory, List<IContentItem> contentList,
PromptConfigParameter? parameter = null,
Action<StreamingKernelContent> inStreamItemProceessing = null)
{
var iWantTo = iWanToRun.IWantToBuild.IWantToConfig.IWantTo;
var helper = iWanToRun.SemanticKernelHelper;
var kernel = helper.GetKernel();
//var function = iWanToRun.KernelFunction;
//注意:只要使用了 Plugin 和 Function,并且包含输入标识,就需要使用上下文
iWanToRun.StoredAiArguments ??= new SenparcAiArguments();
var storedArguments = iWanToRun.StoredAiArguments.KernelArguments;
var tempArguments = request.TempAiArguments?.KernelArguments;
FunctionResult? functionResult = null;
var result = new SenparcKernelAiResult<T>(iWanToRun, inputContent: null);
var useStream = inStreamItemProceessing != null;
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
ChatMessageContentItemCollection contentItems = new ChatMessageContentItemCollection();
foreach (var contentItem in contentList)
{
//if (contentItem.Type == Helpers.ContentType.Text)
//{
// contentItems.Add(new TextContent(contentItem.TextContent));
//}
//else if (contentItem.Type == Helpers.ContentType.Image)
//{
// contentItems.Add(new ImageContent_ImageBase64(contentItem.ImageData, "image/jpg"));
//}
if (contentItem is ContentItem_Text ciText)
{
contentItems.Add(new TextContent(ciText.TextContent));
}
else if (contentItem is ContentItem_ImageBse64 ciBae64)
{
contentItems.Add(new ImageContent(ciBae64.ImageData, "image/jpg"));
}
else if (contentItem is ContentItem_ImageUrl ciImageUrl)
{
contentItems.Add(new ImageContent("data:image/jpeg;base64," + ciImageUrl.image_url.Url));
}
}
chatHistory.AddUserMessage(contentItems);
parameter ??= new PromptConfigParameter()
{
MaxTokens = 3500,
Temperature = 0.7,
TopP = 0.5,
};
PromptExecutionSettings? executionSettings = helper.GetExecutionSetting(parameter, helper.AiSetting);
if (kernel.Plugins.Count > 0)
{
executionSettings.FunctionChoiceBehavior = FunctionChoiceBehavior.Auto();
}
if (useStream)
{
result.StreamResult = chatCompletionService.GetStreamingChatMessageContentsAsync(chatHistory, executionSettings: executionSettings, kernel: iWanToRun.Kernel);
var stringResult = new StringBuilder();
if (result.StreamResult != null)
{
await foreach (var item in result.StreamResult)
{
stringResult.Append(item);
inStreamItemProceessing?.Invoke(item);//执行流
}
}
result.OutputString = stringResult.ToString();
}
else
{
var contentResult = await chatCompletionService.GetChatMessageContentAsync(chatHistory, executionSettings: executionSettings, kernel: iWanToRun.Kernel);
//result.Result = contentResult;
result.OutputString = contentResult.ToString();
}
return result;
}
#endregion
#endregion
#endregion
}
}