Skip to content

Commit 050b622

Browse files
committed
a lot of small changes
1 parent b157ab9 commit 050b622

15 files changed

+177
-144
lines changed

AIClient/AsyncContext.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,12 +53,10 @@ public void Dispose()
5353
{
5454
if (!_disposed)
5555
{
56-
if (_holderToRestore != null)
57-
{
58-
}
59-
6056
// 将AsyncLocal的值恢复为进入using之前的状态
57+
#pragma warning disable CS8601 // 引用类型赋值可能为 null。
6158
AsyncLocalContext.Value = _holderToRestore;
59+
#pragma warning restore CS8601 // 引用类型赋值可能为 null。
6260
_disposed = true;
6361
}
6462
}

AIClient/Dialog/DialogViewModel.cs

Lines changed: 43 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -189,49 +189,56 @@ public IList<CheckableFunctionGroupTree>? SelectedFunctionGroups
189189
}
190190
}
191191

192-
public ICommand ExportCommand => new ActionCommand((async o =>
192+
public ICommand ExportCommand => new ActionCommand((async _ =>
193193
{
194-
var saveFileDialog = new SaveFileDialog()
195-
{
196-
AddExtension = true,
197-
DefaultExt = ".md", CheckPathExists = true,
198-
Filter = "markdown files (*.md)|*.md"
199-
};
200-
if (saveFileDialog.ShowDialog() != true)
201-
{
202-
return;
203-
}
204-
205-
var stringBuilder = new StringBuilder(8192);
206-
/*stringBuilder.AppendLine($"# {this.Topic}");
207-
stringBuilder.AppendLine($"### {this.DefaultClient.Name}");*/
208-
foreach (var viewItem in DialogItems.Where((item => item.IsAvailableInContext)))
194+
try
209195
{
210-
if (viewItem is MultiResponseViewItem multiResponseView &&
211-
multiResponseView.AcceptedResponse is ResponseViewItem responseViewItem)
196+
var saveFileDialog = new SaveFileDialog()
197+
{
198+
AddExtension = true,
199+
DefaultExt = ".md", CheckPathExists = true,
200+
Filter = "markdown files (*.md)|*.md"
201+
};
202+
if (saveFileDialog.ShowDialog() != true)
212203
{
213-
var textContent = responseViewItem.TextContent;
214-
stringBuilder.AppendLine("## **Assistant:**");
215-
stringBuilder.Append(textContent ?? string.Empty);
216-
stringBuilder.AppendLine();
217-
stringBuilder.AppendLine();
218-
stringBuilder.AppendLine("***");
219-
stringBuilder.AppendLine();
204+
return;
220205
}
221-
else if (viewItem is RequestViewItem reqViewItem)
206+
207+
var stringBuilder = new StringBuilder(8192);
208+
/*stringBuilder.AppendLine($"# {this.Topic}");
209+
stringBuilder.AppendLine($"### {this.DefaultClient.Name}");*/
210+
foreach (var viewItem in DialogItems.Where((item => item.IsAvailableInContext)))
222211
{
223-
stringBuilder.AppendLine("## **User:**");
224-
stringBuilder.Append(reqViewItem.TextMessage);
225-
stringBuilder.AppendLine();
226-
stringBuilder.AppendLine();
227-
stringBuilder.AppendLine("***");
228-
stringBuilder.AppendLine();
212+
if (viewItem is MultiResponseViewItem multiResponseView &&
213+
multiResponseView.AcceptedResponse is ResponseViewItem responseViewItem)
214+
{
215+
var textContent = responseViewItem.TextContent;
216+
stringBuilder.AppendLine("## **Assistant:**");
217+
stringBuilder.Append(textContent ?? string.Empty);
218+
stringBuilder.AppendLine();
219+
stringBuilder.AppendLine();
220+
stringBuilder.AppendLine("***");
221+
stringBuilder.AppendLine();
222+
}
223+
else if (viewItem is RequestViewItem reqViewItem)
224+
{
225+
stringBuilder.AppendLine("## **User:**");
226+
stringBuilder.Append(reqViewItem.TextMessage);
227+
stringBuilder.AppendLine();
228+
stringBuilder.AppendLine();
229+
stringBuilder.AppendLine("***");
230+
stringBuilder.AppendLine();
231+
}
229232
}
230-
}
231233

232-
var fileName = saveFileDialog.FileName;
233-
await File.WriteAllTextAsync(fileName, stringBuilder.ToString());
234-
MessageEventBus.Publish("已导出");
234+
var fileName = saveFileDialog.FileName;
235+
await File.WriteAllTextAsync(fileName, stringBuilder.ToString());
236+
MessageEventBus.Publish("已导出");
237+
}
238+
catch (Exception e)
239+
{
240+
MessageBox.Show(e.Message);
241+
}
235242
}));
236243

237244

AIClient/Dialog/SummaryRequestViewItem.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ public override long Tokens
1919
public override async IAsyncEnumerable<ChatMessage> GetMessagesAsync(
2020
[EnumeratorCancellation] CancellationToken cancellationToken)
2121
{
22+
await Task.Yield();
2223
if (string.IsNullOrEmpty(SummaryPrompt))
2324
{
2425
throw new InvalidOperationException("SummaryPrompt cannot be null or empty.");

AIClient/Endpoints/ChatContext.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,9 @@ public ChatContext(AdditionalPropertiesDictionary? additionalObjects = null)
2424

2525
public ClientResult? Result { get; set; }
2626

27-
public async Task CompleteStreamResponse(CompletedResult result)
27+
public Task CompleteStreamResponse(CompletedResult result)
2828
{
29+
return Task.CompletedTask;
2930
}
3031

3132
public async Task CompleteResponse(ChatResponse response, CompletedResult result)

AIClient/Extension.cs

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public static class Extension
3636
WriteIndented = true,
3737
};
3838

39-
public static void UpgradeAPIVersion(this ChatCompletionsClient client, string apiVersion = "2024-12-01-preview")
39+
public static void UpgradeApiVersion(this ChatCompletionsClient client, string apiVersion = "2024-12-01-preview")
4040
{
4141
var propertyInfo = client.GetType().GetField("_apiVersion", BindingFlags.Instance | BindingFlags.NonPublic);
4242
propertyInfo?.SetValue(client, apiVersion);
@@ -63,7 +63,7 @@ public static IServiceCollection AddMap(this IServiceCollection collection)
6363
expression.CreateMap<DataContent, DataContentPO>()
6464
.ForMember(po => po.Data, opt => opt.MapFrom(content => content.Data));
6565
expression.CreateMap<DataContentPO, DataContent>()
66-
.ConstructUsing(((po, context) =>
66+
.ConstructUsing(((po, _) =>
6767
{
6868
if (po.Data != null)
6969
{
@@ -81,7 +81,7 @@ public static IServiceCollection AddMap(this IServiceCollection collection)
8181
expression.CreateMap<ErrorContentPO, ErrorContent>();
8282
expression.CreateMap<FunctionResultContent, FunctionResultContentPO>();
8383
expression.CreateMap<FunctionResultContentPO, FunctionResultContent>()
84-
.ConstructUsing((po, context) => new FunctionResultContent(po.CallId, po.Result)
84+
.ConstructUsing((po, _) => new FunctionResultContent(po.CallId, po.Result)
8585
{ Exception = po.Exception });
8686
expression.CreateMap<TextReasoningContent, TextReasoningContentPO>();
8787
expression.CreateMap<TextReasoningContentPO, TextReasoningContent>();
@@ -180,7 +180,7 @@ public static string GetDebuggerString(this FunctionResultContent resultContent)
180180
var exception = resultContent.Exception;
181181
return str + (exception != null
182182
? $"{exception.GetType().Name}(\"{exception.Message}\")"
183-
: (resultContent.Result?.ToString() ?? "(null)") ?? "");
183+
: (resultContent.Result?.ToString() ?? "(null)"));
184184
}
185185

186186

@@ -335,7 +335,7 @@ public static string GetRootPropertyName(string json)
335335
public static ILLMChatClient? CreateChatClient(this ILLMChatModel llmModel)
336336
{
337337
var endpoint = llmModel.Endpoint;
338-
return !endpoint.IsEnabled ? null : endpoint?.NewChatClient(llmModel);
338+
return !endpoint.IsEnabled ? null : endpoint.NewChatClient(llmModel);
339339
}
340340

341341
public static void AddLine(this IList<string> list, string? msg = null)
@@ -383,11 +383,9 @@ public static void NewLine(this IList<string> list, string? msg = null)
383383
if (parentObject == null) return null;
384384

385385
//check if the parent matches the type we're looking for
386-
T? parent = parentObject as T;
387-
if (parent != null)
386+
if (parentObject is T parent)
388387
return parent;
389-
else
390-
return FindVisualParent<T>(parentObject);
388+
return FindVisualParent<T>(parentObject);
391389
}
392390

393391
public static T Clone<T>(T source) where T : class
@@ -439,7 +437,7 @@ public static void TryAddAdditionalFunctionCallResult(this IEnumerable<ChunkNode
439437
}
440438
}
441439

442-
public static void RecursiveAdditionalFunctionCallResult(this ChunkNode node, List<AIContent> contents,
440+
private static void RecursiveAdditionalFunctionCallResult(this ChunkNode node, List<AIContent> contents,
443441
StringBuilder stringBuilder)
444442
{
445443
var chunk = node.Chunk;
@@ -474,6 +472,7 @@ public static IEnumerable<ChunkNode> OrderNode(this IList<ChunkNode> nodes)
474472

475473
public static SemanticKernelStore GetStore(this RagOption ragOption)
476474
{
475+
ragOption.ThrowIfNotValid();
477476
var dbConnection = ragOption.DBConnection;
478477
var embeddingEndpoint = ragOption.EmbeddingEndpoint;
479478
if (embeddingEndpoint == null)
@@ -537,7 +536,7 @@ public static Func<string, CancellationToken, Task<string>> CreateSummaryDelegat
537536
return content;
538537
}
539538

540-
if (cache?.TryGetValue(content, out var result) == true)
539+
if (cache.TryGetValue(content, out var result))
541540
{
542541
return result;
543542
}
@@ -580,10 +579,9 @@ public static Func<string, CancellationToken, Task<string>> CreateSummaryDelegat
580579
}
581580

582581
stringBuilder.Append(content);
583-
var dialogContext = new DialogContext(new[]
584-
{
582+
var dialogContext = new DialogContext([
585583
new RequestViewItem() { TextMessage = stringBuilder.ToString(), }
586-
});
584+
]);
587585
int tryCount = 0;
588586
while (tryCount < retryCount)
589587
{
@@ -592,7 +590,7 @@ public static Func<string, CancellationToken, Task<string>> CreateSummaryDelegat
592590
var textResponse = response.TextResponse;
593591
if (!string.IsNullOrEmpty(textResponse) && !response.IsInterrupt)
594592
{
595-
cache?.TryAdd(content, textResponse);
593+
cache.TryAdd(content, textResponse);
596594
return textResponse;
597595
}
598596
}
@@ -623,7 +621,7 @@ public static int CountRecursive(this PDFNode node)
623621
}
624622

625623
/// <summary>
626-
/// use temp path in current directory. so it can be deleted when exit.
624+
/// use temp path in current directory. so it can be deleted when exited.
627625
/// </summary>
628626
public static string TempPath => Path.GetFullPath("Temp");
629627

AIClient/LLMClient.csproj

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
<PlatformTarget>x64</PlatformTarget>
2020
</PropertyGroup>
2121
<ItemGroup>
22-
<PackageReference Include="AutoMapper" Version="14.0.0"/>
22+
<PackageReference Include="AutoMapper" Version="15.0.1" />
2323
<PackageReference Include="AvalonEdit" Version="6.3.1.120"/>
2424
<PackageReference Include="Azure.AI.TextAnalytics" Version="5.3.0"/>
2525
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0"/>
@@ -52,7 +52,7 @@
5252
<PackageReference Include="ModelContextProtocol" Version="0.3.0-preview.1"/>
5353
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.12.0"/>
5454
<PackageReference Include="System.Drawing.Common" Version="10.0.0-preview.5.25277.114"/>
55-
<PackageReference Include="System.Text.Json" Version="9.0.7" />
55+
<PackageReference Include="System.Text.Json" Version="9.0.8" />
5656
<PackageReference Include="TextMateSharp" Version="1.0.70" />
5757
<PackageReference Include="TextMateSharp.Grammars.Karl" Version="1.0.2" />
5858
</ItemGroup>

AIClient/Rag/ExcelFile.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,13 @@ public override Task<ISearchResult> GetFullDocumentAsync(CancellationToken cance
5252
throw new NotImplementedException();
5353
}
5454

55-
protected override KernelFunctionFromMethodOptions QueryOptions { get; }
55+
protected override KernelFunctionFromMethodOptions QueryOptions
56+
{
57+
get
58+
{
59+
return new KernelFunctionFromMethodOptions();
60+
}
61+
}
5662

5763
protected override Task ConstructCore(CancellationToken cancellationToken = default)
5864
{

AIClient/Rag/RagOption.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,9 @@ public ILLMChatClient? DigestClient
8181
}
8282

8383
return ServiceLocator.GetService<IMapper>()?
84-
.Map<LLMClientPersistModel, ILLMChatClient>(this.DigestClientPersist, (o) => { });
84+
.Map<LLMClientPersistModel, ILLMChatClient>(this.DigestClientPersist, (_) => { });
8585
}
86-
set
86+
private set
8787
{
8888
if (value == null)
8989
{
@@ -92,7 +92,7 @@ public ILLMChatClient? DigestClient
9292
}
9393

9494
this.DigestClientPersist = ServiceLocator.GetService<IMapper>()?
95-
.Map<ILLMChatClient, LLMClientPersistModel>(value, (options => { }));
95+
.Map<ILLMChatClient, LLMClientPersistModel>(value, (_ => { }));
9696
}
9797
}
9898

@@ -117,7 +117,7 @@ public string? DBConnection
117117
}
118118
}
119119

120-
public ICommand SelectDatabaseCommand => new ActionCommand(async o =>
120+
public ICommand SelectDatabaseCommand => new ActionCommand(_ =>
121121
{
122122
var openFileDialog = new OpenFileDialog()
123123
{

AIClient/Rag/SemanticKernelStore.cs

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -35,25 +35,20 @@ public enum SearchAlgorithm
3535
[Description("Based on default search, use search result as query to search child nodes recursively.")]
3636
Recursive,
3737

38-
/// <summary>
39-
/// interact with llm to do the search
40-
/// </summary>
4138
//Interactive
4239
}
4340

4441
public class SemanticKernelStore
4542
{
4643
public const int ChunkDimension = 1536;
4744

48-
private readonly string _dbConnectionString;
49-
5045
private readonly Kernel _kernel;
5146

5247
[Experimental("SKEXP0010")]
5348
public SemanticKernelStore(ILLMEndpoint endpoint, string modelId = "text-embedding-3-small",
5449
string dbConnectionString = "Data Source=file_embedding.db")
5550
{
56-
OpenAIClient? openAiClient = null;
51+
OpenAIClient? openAiClient;
5752
if (endpoint is APIEndPoint apiEndPoint)
5853
{
5954
openAiClient = apiEndPoint.ConfigOption.OpenAIClient;
@@ -70,11 +65,11 @@ public SemanticKernelStore(ILLMEndpoint endpoint, string modelId = "text-embeddi
7065
nameof(endpoint));
7166
}
7267

73-
_dbConnectionString = dbConnectionString;
68+
var s = dbConnectionString;
7469
var kernelBuilder = Kernel.CreateBuilder();
7570
kernelBuilder.Services.AddOpenAIEmbeddingGenerator(modelId, openAiClient)
7671
// 添加 SQLite 向量存储(连接字符串指向本地文件)
77-
.AddSqliteVectorStore(connectionStringProvider: sp => _dbConnectionString, provider =>
72+
.AddSqliteVectorStore(connectionStringProvider: _ => s, provider =>
7873
new SqliteVectorStoreOptions()
7974
{
8075
EmbeddingGenerator =
@@ -343,7 +338,7 @@ private async Task PopulateChildParagraphAsync(VectorStoreCollection<string, Doc
343338
public async Task<IList<ChunkNode>> SearchAsync(string query, string docId,
344339
SearchAlgorithm algorithm, int topK = 6, CancellationToken token = default)
345340
{
346-
IEnumerable<DocChunk>? chunks = null;
341+
IEnumerable<DocChunk>? chunks;
347342
switch (algorithm)
348343
{
349344
case SearchAlgorithm.Default:
@@ -389,7 +384,7 @@ private async Task<IEnumerable<DocChunk>> TopDownSearchAsync(string query, strin
389384
CancellationToken token, int topK = 6)
390385
{
391386
var collection = _kernel.GetRequiredService<VectorStore>().GetCollection<string, DocChunk>(docId);
392-
var embeddingGenerator = _kernel!.GetRequiredService<IEmbeddingGenerator<string, Embedding<float>>>();
387+
var embeddingGenerator = _kernel.GetRequiredService<IEmbeddingGenerator<string, Embedding<float>>>();
393388
var topLevelResults = await InternalSearchAsync(query, new VectorSearchOptions<DocChunk>()
394389
{
395390
Filter = chunk => chunk.Level == 0,
@@ -464,7 +459,7 @@ private async Task<IEnumerable<DocChunk>> RecursiveSearchAsync(string query, str
464459
int level = 2, int topK = 6)
465460
{
466461
var collection = _kernel.GetRequiredService<VectorStore>().GetCollection<string, DocChunk>(docId);
467-
var embeddingGenerator = _kernel!.GetRequiredService<IEmbeddingGenerator<string, Embedding<float>>>();
462+
var embeddingGenerator = _kernel.GetRequiredService<IEmbeddingGenerator<string, Embedding<float>>>();
468463
var vectorSearchOptions = new VectorSearchOptions<DocChunk>()
469464
{
470465
//只搜索没有子节点的文档

AIClient/Rag/TextFileSource.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,13 @@ public override Task<ISearchResult> GetFullDocumentAsync(CancellationToken cance
5050
throw new NotImplementedException();
5151
}
5252

53-
protected override KernelFunctionFromMethodOptions QueryOptions { get; }
53+
protected override KernelFunctionFromMethodOptions QueryOptions
54+
{
55+
get
56+
{
57+
return new KernelFunctionFromMethodOptions();
58+
}
59+
}
5460

5561
protected override Task ConstructCore(CancellationToken cancellationToken = default)
5662
{

0 commit comments

Comments
 (0)