using AIStudio.Provider;
using AIStudio.Provider.OpenAI;
namespace AIStudio.Chat;
public static class ListContentBlockExtensions
{
///
/// Processes a list of content blocks by transforming them into a collection of message results asynchronously.
///
/// The list of content blocks to process.
/// A function that transforms each content block into a message result asynchronously.
/// An asynchronous task that resolves to a list of transformed results.
public static async Task> BuildMessagesAsync(this List blocks, Func roleTransformer)
{
var messages = blocks
.Where(n => n.ContentType is ContentType.TEXT && !string.IsNullOrWhiteSpace((n.Content as ContentText)?.Text))
.Select(async n => new TextMessage
{
Role = roleTransformer(n.Role),
Content = n.Content switch
{
ContentText text => await text.PrepareTextContentForAI(),
_ => string.Empty,
}
})
.ToList();
// Await all messages:
await Task.WhenAll(messages);
// Select all results:
return messages.Select(n => n.Result).Cast().ToList();
}
///
/// Processes a list of content blocks using standard role transformations to create message results asynchronously.
///
/// The list of content blocks to process.
/// >An asynchronous task that resolves to a list of transformed message results.
public static async Task> BuildMessagesUsingStandardRolesAsync(this List blocks) => await blocks.BuildMessagesAsync(StandardRoleTransformer);
private static string StandardRoleTransformer(ChatRole role) => role switch
{
ChatRole.USER => "user",
ChatRole.AI => "assistant",
ChatRole.AGENT => "assistant",
ChatRole.SYSTEM => "system",
_ => "user",
};
}