Skip to content

Commit b20cadf

Browse files
authored
Merge pull request #96 from cnblogs/try-make-library-compatible-with-net6
refactor: make library compatible with net6
2 parents 0cabefb + 549770e commit b20cadf

File tree

263 files changed

+1594
-1605
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

263 files changed

+1594
-1605
lines changed

.editorconfig

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -384,5 +384,5 @@ dotnet_naming_style.s_camelcase.capitalization = camel_case
384384
indent_size = 2
385385
tab_width = 2
386386

387-
[*.{props,targets,config,nuspec,json}]
387+
[*.{props,targets,config,nuspec,json,yml}]
388388
indent_size = 2

.github/workflows/ci.yml

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,25 @@ on:
77
branches: [ "main" ]
88

99
jobs:
10-
test:
10+
test-net6:
1111
runs-on: ubuntu-latest
12-
container: mcr.microsoft.com/dotnet/sdk:8.0
12+
container: mcr.microsoft.com/dotnet/sdk:6.0
1313

1414
steps:
15-
- name: Checkout
16-
uses: actions/checkout@v4
17-
- name: Build
18-
run: dotnet build -c Release
19-
- name: Test
20-
run: dotnet test -c Release
15+
- name: Checkout
16+
uses: actions/checkout@v4
17+
- name: Build
18+
run: dotnet build src/Cnblogs.DashScope.AspNetCore -c Release
19+
- name: Test
20+
run: dotnet test test/Cnblogs.DashScope.Sdk.UnitTests -c Release
21+
test-net8:
22+
runs-on: ubuntu-latest
23+
container: mcr.microsoft.com/dotnet/sdk:8.0
24+
steps:
25+
- name: Checkout
26+
uses: actions/checkout@v4
27+
- name: Build
28+
run: dotnet build src/Cnblogs.DashScope.AI -c Release
29+
- name: Test
30+
run: dotnet test test/Cnblogs.DashScope.AI.UnitTests -c Release
2131

Cnblogs.DashScope.Sdk.sln

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cnblogs.DashScope.Sdk.Snaps
2020
EndProject
2121
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cnblogs.DashScope.AI", "src\Cnblogs.DashScope.AI\Cnblogs.DashScope.AI.csproj", "{5D5AD75A-8084-4738-AC56-B8A23E649452}"
2222
EndProject
23+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cnblogs.DashScope.AI.UnitTests", "test\Cnblogs.DashScope.AI.UnitTests\Cnblogs.DashScope.AI.UnitTests.csproj", "{25EE79E1-147B-42FD-AFEA-E1550EDD1D36}"
24+
EndProject
25+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cnblogs.DashScope.Tests.Shared", "test\Cnblogs.DashScope.Tests.Shared\Cnblogs.DashScope.Tests.Shared.csproj", "{06F0AF23-445B-4C6F-9E19-570DA9B7435D}"
26+
EndProject
2327
Global
2428
GlobalSection(SolutionConfigurationPlatforms) = preSolution
2529
Debug|Any CPU = Debug|Any CPU
@@ -33,6 +37,8 @@ Global
3337
{CC389455-A3EA-4F09-B524-4DC351A1E1AA} = {008988ED-0A3B-4272-BCC3-7B4110699345}
3438
{5088DE77-1CE3-46FB-B9D0-27A6C9A5EED1} = {CFC8ECB3-5248-46CD-A56C-EC088F2A3804}
3539
{5D5AD75A-8084-4738-AC56-B8A23E649452} = {008988ED-0A3B-4272-BCC3-7B4110699345}
40+
{25EE79E1-147B-42FD-AFEA-E1550EDD1D36} = {CFC8ECB3-5248-46CD-A56C-EC088F2A3804}
41+
{06F0AF23-445B-4C6F-9E19-570DA9B7435D} = {CFC8ECB3-5248-46CD-A56C-EC088F2A3804}
3642
EndGlobalSection
3743
GlobalSection(ProjectConfigurationPlatforms) = postSolution
3844
{FA6A118A-8D26-4B7A-9952-8504B8A0025B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
@@ -63,5 +69,13 @@ Global
6369
{5D5AD75A-8084-4738-AC56-B8A23E649452}.Debug|Any CPU.Build.0 = Debug|Any CPU
6470
{5D5AD75A-8084-4738-AC56-B8A23E649452}.Release|Any CPU.ActiveCfg = Release|Any CPU
6571
{5D5AD75A-8084-4738-AC56-B8A23E649452}.Release|Any CPU.Build.0 = Release|Any CPU
72+
{25EE79E1-147B-42FD-AFEA-E1550EDD1D36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
73+
{25EE79E1-147B-42FD-AFEA-E1550EDD1D36}.Debug|Any CPU.Build.0 = Debug|Any CPU
74+
{25EE79E1-147B-42FD-AFEA-E1550EDD1D36}.Release|Any CPU.ActiveCfg = Release|Any CPU
75+
{25EE79E1-147B-42FD-AFEA-E1550EDD1D36}.Release|Any CPU.Build.0 = Release|Any CPU
76+
{06F0AF23-445B-4C6F-9E19-570DA9B7435D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
77+
{06F0AF23-445B-4C6F-9E19-570DA9B7435D}.Debug|Any CPU.Build.0 = Debug|Any CPU
78+
{06F0AF23-445B-4C6F-9E19-570DA9B7435D}.Release|Any CPU.ActiveCfg = Release|Any CPU
79+
{06F0AF23-445B-4C6F-9E19-570DA9B7435D}.Release|Any CPU.Build.0 = Release|Any CPU
6680
EndGlobalSection
6781
EndGlobal

Directory.Build.props

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<Project>
22
<PropertyGroup>
3-
<TargetFramework>net8.0</TargetFramework>
3+
<TargetFramework>net6.0</TargetFramework>
44
<Nullable>enable</Nullable>
55
<ImplicitUsings>enable</ImplicitUsings>
66
<Authors>Cnblogs</Authors>

sample/Cnblogs.DashScope.Sample/Program.cs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ async Task ChatWithToolsAsync()
177177
"获得当前天气",
178178
new JsonSchemaBuilder().FromType<WeatherReportParameters>().Build()))
179179
};
180-
var chatParameters = new TextGenerationParameters() { ResultFormat = ResultFormats.Message, Tools = tools };
180+
var chatParameters = new TextGenerationParameters { ResultFormat = ResultFormats.Message, Tools = tools };
181181
var question = TextChatMessage.User("请问现在杭州的天气如何?");
182182
history.Add(question);
183183
Console.WriteLine($"{question.Role} > {question.Content}");
@@ -214,18 +214,15 @@ async Task ChatWithMicrosoftExtensions()
214214
Console.WriteLine("Requesting model...");
215215
var chatClient = dashScopeClient.AsChatClient("qwen-max");
216216
List<ChatMessage> conversation =
217-
[
218-
new(ChatRole.System, "You are a helpful AI assistant"),
219-
new(ChatRole.User, "What is AI?")
220-
];
217+
new() { new(ChatRole.System, "You are a helpful AI assistant"), new(ChatRole.User, "What is AI?") };
221218
var response = await chatClient.GetResponseAsync(conversation);
222219
var serializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web) { WriteIndented = true };
223220
Console.WriteLine(JsonSerializer.Serialize(response, serializerOptions));
224221
}
225222

226223
async Task ApplicationCallAsync(string applicationId, string prompt)
227224
{
228-
var request = new ApplicationRequest() { Input = new ApplicationInput() { Prompt = prompt } };
225+
var request = new ApplicationRequest { Input = new ApplicationInput { Prompt = prompt } };
229226
var response = await dashScopeClient.GetApplicationResponseAsync(applicationId, request);
230227
Console.WriteLine(response.Output.Text);
231228
}

sample/Cnblogs.DashScope.Sample/ToolCallWithExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ public static async Task ToolCallWithExtensionAsync(this IDashScopeClient dashSc
1212
[Description("Gets the weather")]
1313
string GetWeather(string location) => Random.Shared.NextDouble() > 0.5 ? "It's sunny" : "It's raining";
1414

15-
var chatOptions = new ChatOptions { Tools = [AIFunctionFactory.Create(GetWeather)] };
15+
var chatOptions = new ChatOptions { Tools = new List<AITool> { AIFunctionFactory.Create(GetWeather) } };
1616

1717
var client = dashScopeClient.AsChatClient("qwen-max").AsBuilder().UseFunctionInvocation().Build();
1818
await foreach (var message in client.GetStreamingResponseAsync("What is weather of LA today?", chatOptions))

src/Cnblogs.DashScope.AI/Cnblogs.DashScope.AI.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<Project Sdk="Microsoft.NET.Sdk">
22
<PropertyGroup>
3+
<TargetFramework>net8.0</TargetFramework>
34
<Product>Cnblogs.DashScope.AI</Product>
45
<GenerateDocumentationFile>true</GenerateDocumentationFile>
56
<PackageTags>Cnblogs;Dashscope;Microsoft.Extensions.AI;Sdk;Embedding;</PackageTags>
@@ -10,6 +11,7 @@
1011
</ItemGroup>
1112

1213
<ItemGroup>
14+
<PackageReference Include="JsonSchema.Net.Generation" Version="5.0.2" />
1315
<PackageReference Include="Microsoft.Extensions.AI.Abstractions" Version="9.5.0" />
1416
</ItemGroup>
1517

src/Cnblogs.DashScope.AI/DashScopeChatClient.cs

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public sealed class DashScopeChatClient : IChatClient
1717
private readonly string _modelId;
1818

1919
private static readonly JsonSchema EmptyObjectSchema =
20-
JsonSchema.FromText("""{"type":"object","required":[],"properties":{}}""");
20+
JsonSchema.FromText("{\"type\":\"object\",\"required\":[],\"properties\":{}}");
2121

2222
private static readonly TextGenerationParameters
2323
DefaultTextGenerationParameter = new() { ResultFormat = "message" };
@@ -55,15 +55,15 @@ public async Task<ChatResponse> GetResponseAsync(
5555
if (useVl)
5656
{
5757
var response = await _dashScopeClient.GetMultimodalGenerationAsync(
58-
new ModelRequest<MultimodalInput, IMultimodalParameters>()
58+
new ModelRequest<MultimodalInput, IMultimodalParameters>
5959
{
6060
Input = new MultimodalInput { Messages = ToMultimodalMessages(chatMessages) },
6161
Parameters = ToMultimodalParameters(options),
6262
Model = modelId
6363
},
6464
cancellationToken);
6565

66-
var returnMessage = new ChatMessage()
66+
var returnMessage = new ChatMessage
6767
{
6868
RawRepresentation = response, Role = ToChatRole(response.Output.Choices[0].Message.Role),
6969
};
@@ -80,7 +80,7 @@ public async Task<ChatResponse> GetResponseAsync(
8080

8181
if (response.Usage != null)
8282
{
83-
completion.Usage = new UsageDetails()
83+
completion.Usage = new UsageDetails
8484
{
8585
InputTokenCount = response.Usage.InputTokens, OutputTokenCount = response.Usage.OutputTokens,
8686
};
@@ -92,7 +92,7 @@ public async Task<ChatResponse> GetResponseAsync(
9292
{
9393
var parameters = ToTextGenerationParameters(options) ?? DefaultTextGenerationParameter;
9494
var response = await _dashScopeClient.GetTextCompletionAsync(
95-
new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
95+
new ModelRequest<TextGenerationInput, ITextGenerationParameters>
9696
{
9797
Input = new TextGenerationInput
9898
{
@@ -116,7 +116,7 @@ public async Task<ChatResponse> GetResponseAsync(
116116

117117
if (response.Usage != null)
118118
{
119-
completion.Usage = new UsageDetails()
119+
completion.Usage = new UsageDetails
120120
{
121121
InputTokenCount = response.Usage.InputTokens,
122122
OutputTokenCount = response.Usage.OutputTokens,
@@ -147,7 +147,7 @@ public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
147147
var parameter = ToMultimodalParameters(options);
148148
parameter.IncrementalOutput = true;
149149
var stream = _dashScopeClient.GetMultimodalGenerationStreamAsync(
150-
new ModelRequest<MultimodalInput, IMultimodalParameters>()
150+
new ModelRequest<MultimodalInput, IMultimodalParameters>
151151
{
152152
Input = new MultimodalInput { Messages = ToMultimodalMessages(chatMessages) },
153153
Parameters = parameter,
@@ -164,7 +164,7 @@ public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
164164
: ToFinishReason(response.Output.Choices[0].FinishReason);
165165
completionId ??= response.RequestId;
166166

167-
var update = new ChatResponseUpdate()
167+
var update = new ChatResponseUpdate
168168
{
169169
ResponseId = completionId,
170170
CreatedAt = DateTimeOffset.Now,
@@ -199,7 +199,7 @@ public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
199199
{
200200
// qwen does not support streaming with function call, fallback to non-streaming
201201
var completion = await GetResponseAsync(chatMessages, options, cancellationToken);
202-
yield return new ChatResponseUpdate()
202+
yield return new ChatResponseUpdate
203203
{
204204
ResponseId = completion.ResponseId,
205205
Role = completion.Messages[0].Role,
@@ -216,7 +216,7 @@ public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
216216
var parameters = ToTextGenerationParameters(options) ?? DefaultTextGenerationParameter;
217217
parameters.IncrementalOutput = true;
218218
var stream = _dashScopeClient.GetTextCompletionStreamAsync(
219-
new ModelRequest<TextGenerationInput, ITextGenerationParameters>()
219+
new ModelRequest<TextGenerationInput, ITextGenerationParameters>
220220
{
221221
Input = new TextGenerationInput
222222
{
@@ -238,7 +238,7 @@ public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
238238
: ToFinishReason(response.Output.Choices[0].FinishReason);
239239
completionId ??= response.RequestId;
240240

241-
var update = new ChatResponseUpdate()
241+
var update = new ChatResponseUpdate
242242
{
243243
ResponseId = completionId,
244244
CreatedAt = DateTimeOffset.Now,
@@ -257,7 +257,7 @@ public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
257257
{
258258
update.Contents.Add(
259259
new UsageContent(
260-
new UsageDetails()
260+
new UsageDetails
261261
{
262262
InputTokenCount = response.Usage.InputTokens,
263263
OutputTokenCount = response.Usage.OutputTokens,
@@ -299,7 +299,7 @@ public void Dispose()
299299

300300
private static ChatMessage ToChatMessage(TextChatMessage message)
301301
{
302-
var returnMessage = new ChatMessage()
302+
var returnMessage = new ChatMessage
303303
{
304304
RawRepresentation = message, Role = ToChatRole(message.Role),
305305
};
@@ -485,7 +485,7 @@ private IEnumerable<TextChatMessage> ToTextChatMessages(
485485
format = "json_object";
486486
}
487487

488-
return new TextGenerationParameters()
488+
return new TextGenerationParameters
489489
{
490490
ResultFormat = format,
491491
Temperature = options.Temperature,

src/Cnblogs.DashScope.AI/DashScopeTextEmbeddingGenerator.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public async Task<GeneratedEmbeddings<Embedding<float>>> GenerateAsync(
4444
e => new Embedding<float>(e.Embedding) { ModelId = _modelId, CreatedAt = DateTimeOffset.Now });
4545
var rawUsage = rawResponse.Usage;
4646
var usage = rawUsage != null
47-
? new UsageDetails() { InputTokenCount = rawUsage.TotalTokens, TotalTokenCount = rawUsage.TotalTokens }
47+
? new UsageDetails { InputTokenCount = rawUsage.TotalTokens, TotalTokenCount = rawUsage.TotalTokens }
4848
: null;
4949
return new GeneratedEmbeddings<Embedding<float>>(embeddings)
5050
{

src/Cnblogs.DashScope.Core/ApplicationInput.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,6 @@ public class ApplicationInput<TBizParams>
4444
/// <summary>
4545
/// Inputs for application call.
4646
/// </summary>
47-
public class ApplicationInput : ApplicationInput<Dictionary<string, object?>>;
47+
public class ApplicationInput : ApplicationInput<Dictionary<string, object?>>
48+
{
49+
}

src/Cnblogs.DashScope.Core/ApplicationRequest.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ public class ApplicationRequest<TBizParams> : IDashScopeWorkspaceConfig
1313
/// <summary>
1414
/// Content of this call.
1515
/// </summary>
16-
public required ApplicationInput<TBizParams> Input { get; set; }
16+
public ApplicationInput<TBizParams> Input { get; set; } = new();
1717

1818
/// <summary>
1919
/// Optional configurations.
@@ -30,4 +30,6 @@ public class ApplicationRequest<TBizParams> : IDashScopeWorkspaceConfig
3030
/// <summary>
3131
/// Request body for an application call with dictionary biz_content.
3232
/// </summary>
33-
public class ApplicationRequest : ApplicationRequest<Dictionary<string, object?>>;
33+
public class ApplicationRequest : ApplicationRequest<Dictionary<string, object?>>
34+
{
35+
}

src/Cnblogs.DashScope.Core/BackgroundGenerationInput.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public class BackgroundGenerationInput
88
/// <summary>
99
/// The image url to generation background on.
1010
/// </summary>
11-
public required string BaseImageUrl { get; set; }
11+
public string BaseImageUrl { get; set; } = string.Empty;
1212

1313
/// <summary>
1414
/// The reference image url for.

src/Cnblogs.DashScope.Core/BatchGetEmbeddingsInput.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,5 @@ public class BatchGetEmbeddingsInput
88
/// <summary>
99
/// The url of text file to compute embeddings from.
1010
/// </summary>
11-
public required string Url { get; set; }
11+
public string Url { get; set; } = string.Empty;
1212
}

src/Cnblogs.DashScope.Core/Cnblogs.DashScope.Core.csproj

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@
88
</PropertyGroup>
99

1010
<ItemGroup>
11-
<PackageReference Include="Microsoft.ML.Tokenizers" Version="1.0.2" />
11+
<EmbeddedResource Include="Internals\qwen.tiktoken" />
1212
</ItemGroup>
1313

1414
<ItemGroup>
15-
<EmbeddedResource Include="Internals\qwen.tiktoken" />
15+
<PackageReference Include="Microsoft.DeepDev.TokenizerLib" Version="1.3.3" />
1616
</ItemGroup>
1717

1818
</Project>

src/Cnblogs.DashScope.Core/DashScopeClientCore.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public class DashScopeClientCore : IDashScopeClient
1818
new()
1919
{
2020
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
21-
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
21+
PropertyNamingPolicy = JsonSnakeCaseLowerNamingPolicy.SnakeCaseLower,
2222
};
2323

2424
private readonly HttpClient _httpClient;
@@ -332,7 +332,7 @@ private static HttpRequestMessage BuildRequest<TPayload>(
332332
{
333333
var response = await GetSuccessResponseAsync<OpenAiErrorResponse>(
334334
message,
335-
r => new DashScopeError()
335+
r => new DashScopeError
336336
{
337337
Code = r.Error.Type,
338338
Message = r.Error.Message,
@@ -367,7 +367,7 @@ private async IAsyncEnumerable<TResponse> StreamAsync<TResponse>(
367367
if (cancellationToken.IsCancellationRequested)
368368
throw new TaskCanceledException();
369369

370-
var line = await reader.ReadLineAsync(cancellationToken);
370+
var line = await reader.ReadLineAsync();
371371
if (line != null && line.StartsWith("data:"))
372372
{
373373
var data = line["data:".Length..];

src/Cnblogs.DashScope.Core/DashScopeException.cs

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,35 @@
33
/// <summary>
44
/// Represents error detail for DashScope API calls.
55
/// </summary>
6-
/// <param name="apiUrl">The requested api url.</param>
7-
/// <param name="status">The status code of response. Would be 0 if no response is received.</param>
8-
/// <param name="error">The error detail returned by server.</param>
9-
/// <param name="message">The error message.</param>
10-
public class DashScopeException(string? apiUrl, int status, DashScopeError? error, string message) : Exception(message)
6+
public class DashScopeException : Exception
117
{
8+
/// <summary>
9+
/// Represents error detail for DashScope API calls.
10+
/// </summary>
11+
/// <param name="apiUrl">The requested api url.</param>
12+
/// <param name="status">The status code of response. Would be 0 if no response is received.</param>
13+
/// <param name="error">The error detail returned by server.</param>
14+
/// <param name="message">The error message.</param>
15+
public DashScopeException(string? apiUrl, int status, DashScopeError? error, string message)
16+
: base(message)
17+
{
18+
ApiUrl = apiUrl;
19+
Error = error;
20+
Status = status;
21+
}
22+
1223
/// <summary>
1324
/// The requested api url.
1425
/// </summary>
15-
public string? ApiUrl { get; } = apiUrl;
26+
public string? ApiUrl { get; }
1627

1728
/// <summary>
1829
/// The error detail returned by server.
1930
/// </summary>
20-
public DashScopeError? Error { get; } = error;
31+
public DashScopeError? Error { get; }
2132

2233
/// <summary>
2334
/// The status code of response. Would be 0 if no response is received.
2435
/// </summary>
25-
public int Status { get; } = status;
36+
public int Status { get; }
2637
}

0 commit comments

Comments
 (0)