Skip to content

Commit 70a9920

Browse files
committed
refactor!: rename ChatMessage to TextChatMessage
1 parent fa34960 commit 70a9920

File tree

12 files changed

+137
-62
lines changed

12 files changed

+137
-62
lines changed

sample/Cnblogs.DashScope.Sample/Program.cs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
using Json.Schema;
88
using Json.Schema.Generation;
99
using Microsoft.Extensions.AI;
10-
using ChatMessage = Cnblogs.DashScope.Core.ChatMessage;
1110

1211
const string apiKey = "sk-***";
1312
var dashScopeClient = new DashScopeClient(apiKey);
@@ -73,12 +72,12 @@ async Task TextCompletionStreamAsync(string prompt)
7372

7473
async Task ChatStreamAsync()
7574
{
76-
var history = new List<ChatMessage>();
75+
var history = new List<TextChatMessage>();
7776
while (true)
7877
{
7978
Console.Write("user > ");
8079
var input = Console.ReadLine()!;
81-
history.Add(ChatMessage.User(input));
80+
history.Add(TextChatMessage.User(input));
8281
var stream = dashScopeClient
8382
.GetQWenChatStreamAsync(
8483
QWenLlm.QWenMax,
@@ -100,25 +99,25 @@ async Task ChatStreamAsync()
10099
}
101100

102101
Console.WriteLine();
103-
history.Add(new ChatMessage(role, message.ToString()));
102+
history.Add(new TextChatMessage(role, message.ToString()));
104103
}
105104

106105
// ReSharper disable once FunctionNeverReturns
107106
}
108107

109108
async Task ChatWithFilesAsync()
110109
{
111-
var history = new List<ChatMessage>();
110+
var history = new List<TextChatMessage>();
112111
Console.WriteLine("uploading file \"test.txt\" ");
113112
var file = new FileInfo("test.txt");
114113
var uploadedFile = await dashScopeClient.UploadFileAsync(file.OpenRead(), file.Name);
115114
Console.WriteLine("file uploaded, id: " + uploadedFile.Id);
116115
Console.WriteLine();
117116

118-
var fileMessage = ChatMessage.File(uploadedFile.Id);
117+
var fileMessage = TextChatMessage.File(uploadedFile.Id);
119118
history.Add(fileMessage);
120119
Console.WriteLine("system > " + fileMessage.Content);
121-
var userPrompt = ChatMessage.User("该文件的内容是什么");
120+
var userPrompt = TextChatMessage.User("该文件的内容是什么");
122121
history.Add(userPrompt);
123122
Console.WriteLine("user > " + userPrompt.Content);
124123
var stream = dashScopeClient.GetQWenChatStreamAsync(
@@ -141,7 +140,7 @@ async Task ChatWithFilesAsync()
141140
}
142141

143142
Console.WriteLine();
144-
history.Add(new ChatMessage(role, message.ToString()));
143+
history.Add(new TextChatMessage(role, message.ToString()));
145144

146145
Console.WriteLine();
147146
Console.WriteLine("Deleting file by id: " + uploadedFile.Id);
@@ -151,7 +150,7 @@ async Task ChatWithFilesAsync()
151150

152151
async Task ChatWithToolsAsync()
153152
{
154-
var history = new List<ChatMessage>();
153+
var history = new List<TextChatMessage>();
155154
var tools = new List<ToolDefinition>
156155
{
157156
new(
@@ -162,7 +161,7 @@ async Task ChatWithToolsAsync()
162161
new JsonSchemaBuilder().FromType<WeatherReportParameters>().Build()))
163162
};
164163
var chatParameters = new TextGenerationParameters() { ResultFormat = ResultFormats.Message, Tools = tools };
165-
var question = ChatMessage.User("请问现在杭州的天气如何?");
164+
var question = TextChatMessage.User("请问现在杭州的天气如何?");
166165
history.Add(question);
167166
Console.WriteLine($"{question.Role} > {question.Content}");
168167

@@ -174,7 +173,7 @@ async Task ChatWithToolsAsync()
174173

175174
var toolResponse = GetWeather(
176175
JsonSerializer.Deserialize<WeatherReportParameters>(toolCallMessage.ToolCalls[0].Function.Arguments!)!);
177-
var toolMessage = ChatMessage.Tool(toolResponse, nameof(GetWeather));
176+
var toolMessage = TextChatMessage.Tool(toolResponse, nameof(GetWeather));
178177
history.Add(toolMessage);
179178
Console.WriteLine($"{toolMessage.Role} > {toolMessage.Content}");
180179

src/Cnblogs.DashScope.Core/ChatMessage.cs renamed to src/Cnblogs.DashScope.Core/TextChatMessage.cs

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ namespace Cnblogs.DashScope.Core;
1212
/// <param name="Partial">Notify model that next message should use this message as prefix.</param>
1313
/// <param name="ToolCalls">Calls to the function.</param>
1414
[method: JsonConstructor]
15-
public record ChatMessage(
15+
public record TextChatMessage(
1616
string Role,
1717
string Content,
1818
string? Name = null,
@@ -23,7 +23,7 @@ public record ChatMessage(
2323
/// Create chat message from an uploaded DashScope file.
2424
/// </summary>
2525
/// <param name="fileId">The id of the file.</param>
26-
public ChatMessage(DashScopeFileId fileId)
26+
public TextChatMessage(DashScopeFileId fileId)
2727
: this("system", fileId.ToUrl())
2828
{
2929
}
@@ -32,7 +32,7 @@ public ChatMessage(DashScopeFileId fileId)
3232
/// Create chat message from multiple DashScope file.
3333
/// </summary>
3434
/// <param name="fileIds">Ids of the files.</param>
35-
public ChatMessage(IEnumerable<DashScopeFileId> fileIds)
35+
public TextChatMessage(IEnumerable<DashScopeFileId> fileIds)
3636
: this("system", string.Join(',', fileIds.Select(f => f.ToUrl())))
3737
{
3838
}
@@ -42,19 +42,19 @@ public ChatMessage(IEnumerable<DashScopeFileId> fileIds)
4242
/// </summary>
4343
/// <param name="fileId">The id of the file.</param>
4444
/// <returns></returns>
45-
public static ChatMessage File(DashScopeFileId fileId)
45+
public static TextChatMessage File(DashScopeFileId fileId)
4646
{
47-
return new ChatMessage(fileId);
47+
return new TextChatMessage(fileId);
4848
}
4949

5050
/// <summary>
5151
/// Creates a file message.
5252
/// </summary>
5353
/// <param name="fileIds">The file id list.</param>
5454
/// <returns></returns>
55-
public static ChatMessage File(IEnumerable<DashScopeFileId> fileIds)
55+
public static TextChatMessage File(IEnumerable<DashScopeFileId> fileIds)
5656
{
57-
return new ChatMessage(fileIds);
57+
return new TextChatMessage(fileIds);
5858
}
5959

6060
/// <summary>
@@ -63,19 +63,19 @@ public static ChatMessage File(IEnumerable<DashScopeFileId> fileIds)
6363
/// <param name="content">Content of the message.</param>
6464
/// <param name="name">Author name.</param>
6565
/// <returns></returns>
66-
public static ChatMessage User(string content, string? name = null)
66+
public static TextChatMessage User(string content, string? name = null)
6767
{
68-
return new ChatMessage(DashScopeRoleNames.User, content, name);
68+
return new TextChatMessage(DashScopeRoleNames.User, content, name);
6969
}
7070

7171
/// <summary>
7272
/// Create a system message.
7373
/// </summary>
7474
/// <param name="content">The content of the message.</param>
7575
/// <returns></returns>
76-
public static ChatMessage System(string content)
76+
public static TextChatMessage System(string content)
7777
{
78-
return new ChatMessage(DashScopeRoleNames.System, content);
78+
return new TextChatMessage(DashScopeRoleNames.System, content);
7979
}
8080

8181
/// <summary>
@@ -86,9 +86,9 @@ public static ChatMessage System(string content)
8686
/// <param name="name">Author name.</param>
8787
/// <param name="toolCalls">Tool calls by model.</param>
8888
/// <returns></returns>
89-
public static ChatMessage Assistant(string content, bool? partial = null, string? name = null, List<ToolCall>? toolCalls = null)
89+
public static TextChatMessage Assistant(string content, bool? partial = null, string? name = null, List<ToolCall>? toolCalls = null)
9090
{
91-
return new ChatMessage(DashScopeRoleNames.Assistant, content, name, partial, toolCalls);
91+
return new TextChatMessage(DashScopeRoleNames.Assistant, content, name, partial, toolCalls);
9292
}
9393

9494
/// <summary>
@@ -97,8 +97,8 @@ public static ChatMessage Assistant(string content, bool? partial = null, string
9797
/// <param name="content">The output from tool.</param>
9898
/// <param name="name">The name of the tool.</param>
9999
/// <returns></returns>
100-
public static ChatMessage Tool(string content, string? name = null)
100+
public static TextChatMessage Tool(string content, string? name = null)
101101
{
102-
return new ChatMessage(DashScopeRoleNames.Tool, content, name);
102+
return new TextChatMessage(DashScopeRoleNames.Tool, content, name);
103103
}
104104
}

src/Cnblogs.DashScope.Core/TextGenerationChoice.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,5 @@ public class TextGenerationChoice
1313
/// <summary>
1414
/// The generated message.
1515
/// </summary>
16-
public required ChatMessage Message { get; set; }
16+
public required TextChatMessage Message { get; set; }
1717
}

src/Cnblogs.DashScope.Core/TextGenerationInput.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ public class TextGenerationInput
1313
/// <summary>
1414
/// The collection of context messages associated with this chat completions request.
1515
/// </summary>
16-
public IEnumerable<ChatMessage>? Messages { get; set; }
16+
public IEnumerable<TextChatMessage>? Messages { get; set; }
1717

1818
/// <summary>
1919
/// Available tools for model to use.

src/Cnblogs.DashScope.Sdk/BaiChuan/BaiChuanTextGenerationApi.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ public static Task<ModelResponse<TextGenerationOutput, TextGenerationTokenUsage>
5454
public static Task<ModelResponse<TextGenerationOutput, TextGenerationTokenUsage>> GetBaiChuanTextCompletionAsync(
5555
this IDashScopeClient client,
5656
BaiChuan2Llm llm,
57-
IEnumerable<ChatMessage> messages,
57+
IEnumerable<TextChatMessage> messages,
5858
string? resultFormat = null)
5959
{
6060
return client.GetBaiChuanTextCompletionAsync(llm.GetModelName(), messages, resultFormat);
@@ -71,7 +71,7 @@ public static Task<ModelResponse<TextGenerationOutput, TextGenerationTokenUsage>
7171
public static Task<ModelResponse<TextGenerationOutput, TextGenerationTokenUsage>> GetBaiChuanTextCompletionAsync(
7272
this IDashScopeClient client,
7373
string llm,
74-
IEnumerable<ChatMessage> messages,
74+
IEnumerable<TextChatMessage> messages,
7575
string? resultFormat = null)
7676
{
7777
return client.GetTextCompletionAsync(

src/Cnblogs.DashScope.Sdk/Llama2/Llama2TextGenerationApi.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public static async Task<ModelResponse<TextGenerationOutput, TextGenerationToken
1919
GetLlama2TextCompletionAsync(
2020
this IDashScopeClient client,
2121
Llama2Model model,
22-
IEnumerable<ChatMessage> messages,
22+
IEnumerable<TextChatMessage> messages,
2323
string? resultFormat = null)
2424
{
2525
return await client.GetLlama2TextCompletionAsync(model.GetModelName(), messages, resultFormat);
@@ -37,7 +37,7 @@ public static async Task<ModelResponse<TextGenerationOutput, TextGenerationToken
3737
GetLlama2TextCompletionAsync(
3838
this IDashScopeClient client,
3939
string model,
40-
IEnumerable<ChatMessage> messages,
40+
IEnumerable<TextChatMessage> messages,
4141
string? resultFormat = null)
4242
{
4343
return await client.GetTextCompletionAsync(

src/Cnblogs.DashScope.Sdk/QWen/QWenTextGenerationApi.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ public static class QWenTextGenerationApi
2020
public static IAsyncEnumerable<ModelResponse<TextGenerationOutput, TextGenerationTokenUsage>> GetQWenChatStreamAsync(
2121
this IDashScopeClient dashScopeClient,
2222
QWenLlm model,
23-
IEnumerable<ChatMessage> messages,
23+
IEnumerable<TextChatMessage> messages,
2424
TextGenerationParameters? parameters = null,
2525
CancellationToken cancellationToken = default)
2626
{
@@ -48,7 +48,7 @@ public static IAsyncEnumerable<ModelResponse<TextGenerationOutput, TextGeneratio
4848
public static IAsyncEnumerable<ModelResponse<TextGenerationOutput, TextGenerationTokenUsage>> GetQWenChatStreamAsync(
4949
this IDashScopeClient dashScopeClient,
5050
string model,
51-
IEnumerable<ChatMessage> messages,
51+
IEnumerable<TextChatMessage> messages,
5252
TextGenerationParameters? parameters = null,
5353
CancellationToken cancellationToken = default)
5454
{
@@ -75,7 +75,7 @@ public static IAsyncEnumerable<ModelResponse<TextGenerationOutput, TextGeneratio
7575
public static Task<ModelResponse<TextGenerationOutput, TextGenerationTokenUsage>> GetQWenChatCompletionAsync(
7676
this IDashScopeClient dashScopeClient,
7777
QWenLlm model,
78-
IEnumerable<ChatMessage> messages,
78+
IEnumerable<TextChatMessage> messages,
7979
TextGenerationParameters? parameters = null,
8080
CancellationToken cancellationToken = default)
8181
{
@@ -99,7 +99,7 @@ public static Task<ModelResponse<TextGenerationOutput, TextGenerationTokenUsage>
9999
public static Task<ModelResponse<TextGenerationOutput, TextGenerationTokenUsage>> GetQWenChatCompletionAsync(
100100
this IDashScopeClient dashScopeClient,
101101
string model,
102-
IEnumerable<ChatMessage> messages,
102+
IEnumerable<TextChatMessage> messages,
103103
TextGenerationParameters? parameters = null,
104104
CancellationToken cancellationToken = default)
105105
{

src/Cnblogs.Extensions.AI.DashScope/DashScopeChatClient.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,7 @@ public void Dispose()
300300
_ => new ChatFinishReason(finishReason),
301301
};
302302

303-
private static ChatMessage ToChatMessage(Cnblogs.DashScope.Core.ChatMessage message)
303+
private static ChatMessage ToChatMessage(TextChatMessage message)
304304
{
305305
var returnMessage = new ChatMessage()
306306
{
@@ -415,13 +415,13 @@ private List<MultimodalMessageContent> ToMultimodalMessageContents(IList<AIConte
415415
return mapped;
416416
}
417417

418-
private IEnumerable<Cnblogs.DashScope.Core.ChatMessage> ToTextChatMessages(
418+
private IEnumerable<TextChatMessage> ToTextChatMessages(
419419
ChatMessage from,
420420
List<ToolDefinition>? tools)
421421
{
422422
if (from.Role == ChatRole.System || from.Role == ChatRole.User)
423423
{
424-
yield return new Cnblogs.DashScope.Core.ChatMessage(
424+
yield return new TextChatMessage(
425425
from.Role.Value,
426426
from.Text ?? string.Empty,
427427
from.AuthorName);
@@ -445,7 +445,7 @@ private List<MultimodalMessageContent> ToMultimodalMessageContents(IList<AIConte
445445
}
446446
}
447447

448-
yield return new Cnblogs.DashScope.Core.ChatMessage(from.Role.Value, result ?? string.Empty);
448+
yield return new TextChatMessage(from.Role.Value, result ?? string.Empty);
449449
}
450450
}
451451
}
@@ -460,7 +460,7 @@ private List<MultimodalMessageContent> ToMultimodalMessageContents(IList<AIConte
460460
tools?.FindIndex(f => f.Function?.Name == c.Name) ?? -1,
461461
new FunctionCall(c.Name, JsonSerializer.Serialize(c.Arguments, ToolCallJsonSerializerOptions))))
462462
.ToList();
463-
yield return new Cnblogs.DashScope.Core.ChatMessage(
463+
yield return new TextChatMessage(
464464
from.Role.Value,
465465
from.Text ?? string.Empty,
466466
from.AuthorName,
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
using System.Text;
2+
using Cnblogs.DashScope.Sdk.UnitTests.Utils;
3+
using FluentAssertions;
4+
using Microsoft.Extensions.AI;
5+
using NSubstitute;
6+
7+
namespace Cnblogs.DashScope.Sdk.UnitTests;
8+
9+
public class ChatClientTests
10+
{
11+
[Fact]
12+
public async Task ChatClient_TextCompletion_SuccessAsync()
13+
{
14+
// Arrange
15+
const bool sse = false;
16+
var testCase = Snapshots.TextGeneration.MessageFormat.SingleMessage;
17+
var (dashScopeClient, handler) = await Sut.GetTestClientAsync(sse, testCase);
18+
var client = dashScopeClient.AsChatClient(testCase.RequestModel.Model);
19+
var content = testCase.RequestModel.Input.Messages!.First().Content;
20+
var parameter = testCase.RequestModel.Parameters;
21+
22+
// Act
23+
var response = await client.CompleteAsync(
24+
content,
25+
new ChatOptions()
26+
{
27+
FrequencyPenalty = parameter?.RepetitionPenalty,
28+
ModelId = testCase.RequestModel.Model,
29+
MaxOutputTokens = parameter?.MaxTokens,
30+
Seed = (long?)parameter?.Seed,
31+
Temperature = parameter?.Temperature,
32+
});
33+
34+
// Assert
35+
handler.Received().MockSend(
36+
Arg.Any<HttpRequestMessage>(),
37+
Arg.Any<CancellationToken>());
38+
response.Message.Text.Should().Be(testCase.ResponseModel.Output.Choices?.First().Message.Content);
39+
}
40+
41+
[Fact]
42+
public async Task ChatClient_TextCompletionStream_SuccessAsync()
43+
{
44+
// Arrange
45+
const bool sse = true;
46+
var testCase = Snapshots.TextGeneration.MessageFormat.SingleMessageIncremental;
47+
var (dashScopeClient, handler) = await Sut.GetTestClientAsync(sse, testCase);
48+
var client = dashScopeClient.AsChatClient(testCase.RequestModel.Model);
49+
var content = testCase.RequestModel.Input.Messages!.First().Content;
50+
var parameter = testCase.RequestModel.Parameters;
51+
52+
// Act
53+
var response = client.CompleteStreamingAsync(
54+
content,
55+
new ChatOptions()
56+
{
57+
FrequencyPenalty = parameter?.RepetitionPenalty,
58+
ModelId = testCase.RequestModel.Model,
59+
MaxOutputTokens = parameter?.MaxTokens,
60+
Seed = (long?)parameter?.Seed,
61+
Temperature = parameter?.Temperature,
62+
});
63+
var text = new StringBuilder();
64+
await foreach (var update in response)
65+
{
66+
text.Append(update.Text);
67+
}
68+
69+
// Assert
70+
handler.Received().MockSend(
71+
Arg.Any<HttpRequestMessage>(),
72+
Arg.Any<CancellationToken>());
73+
text.ToString().Should().Be(testCase.ResponseModel.Output.Choices?.First().Message.Content);
74+
}
75+
}

0 commit comments

Comments
 (0)