mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-02-13 10:01:37 +00:00
Refactor BuildMessagesAsync to use explicit task creation for improved readability and performance
This commit is contained in:
parent
6abe0374ea
commit
ddb1677bc5
@ -13,24 +13,32 @@ public static class ListContentBlockExtensions
|
|||||||
/// <returns>An asynchronous task that resolves to a list of transformed results.</returns>
|
/// <returns>An asynchronous task that resolves to a list of transformed results.</returns>
|
||||||
public static async Task<IList<IMessageBase>> BuildMessagesAsync(this List<ContentBlock> blocks, Func<ChatRole, string> roleTransformer)
|
public static async Task<IList<IMessageBase>> BuildMessagesAsync(this List<ContentBlock> blocks, Func<ChatRole, string> roleTransformer)
|
||||||
{
|
{
|
||||||
var messages = blocks
|
var messageTaskList = new List<Task<IMessageBase>>(blocks.Count);
|
||||||
.Where(n => n.ContentType is ContentType.TEXT && !string.IsNullOrWhiteSpace((n.Content as ContentText)?.Text))
|
foreach (var block in blocks)
|
||||||
.Select(async n => new TextMessage
|
{
|
||||||
{
|
switch (block.Content)
|
||||||
Role = roleTransformer(n.Role),
|
{
|
||||||
Content = n.Content switch
|
case ContentText text when block.ContentType is ContentType.TEXT && !string.IsNullOrWhiteSpace(text.Text):
|
||||||
{
|
messageTaskList.Add(CreateTextMessageAsync(block, text));
|
||||||
ContentText text => await text.PrepareTextContentForAI(),
|
break;
|
||||||
_ => string.Empty,
|
}
|
||||||
}
|
}
|
||||||
})
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
// Await all messages:
|
|
||||||
await Task.WhenAll(messages);
|
|
||||||
|
|
||||||
|
// Await all messages:
|
||||||
|
await Task.WhenAll(messageTaskList);
|
||||||
|
|
||||||
// Select all results:
|
// Select all results:
|
||||||
return messages.Select(n => n.Result).Cast<IMessageBase>().ToList();
|
return messageTaskList.Select(n => n.Result).ToList();
|
||||||
|
|
||||||
|
// Local function to create a text message asynchronously.
|
||||||
|
Task<IMessageBase> CreateTextMessageAsync(ContentBlock block, ContentText text)
|
||||||
|
{
|
||||||
|
return Task.Run(async () => new TextMessage
|
||||||
|
{
|
||||||
|
Role = roleTransformer(block.Role),
|
||||||
|
Content = await text.PrepareTextContentForAI(),
|
||||||
|
} as IMessageBase);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user