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.
/// The selected LLM provider.
/// The selected model.
/// An asynchronous task that resolves to a list of transformed results.
public static async Task> BuildMessagesAsync(
this List blocks,
LLMProviders selectedProvider,
Model selectedModel,
Func roleTransformer)
{
var messageTaskList = new List>(blocks.Count);
foreach (var block in blocks)
{
switch (block.Content)
{
case ContentText text when block.ContentType is ContentType.TEXT && !string.IsNullOrWhiteSpace(text.Text):
messageTaskList.Add(CreateTextMessageAsync(block, text));
break;
}
}
// Await all messages:
await Task.WhenAll(messageTaskList);
// Select all results:
return messageTaskList.Select(n => n.Result).ToList();
// Local function to create a text message asynchronously.
Task CreateTextMessageAsync(ContentBlock block, ContentText text)
{
return Task.Run(async () => new TextMessage
{
Role = roleTransformer(block.Role),
Content = await text.PrepareTextContentForAI(),
} as IMessageBase);
}
}
///
/// Processes a list of content blocks using standard role transformations to create message results asynchronously.
///
/// The list of content blocks to process.
/// The selected LLM provider.
/// The selected model.
/// >An asynchronous task that resolves to a list of transformed message results.
public static async Task> BuildMessagesUsingStandardRolesAsync(
this List blocks,
LLMProviders selectedProvider,
Model selectedModel) => await blocks.BuildMessagesAsync(selectedProvider, selectedModel, StandardRoleTransformer);
private static string StandardRoleTransformer(ChatRole role) => role switch
{
ChatRole.USER => "user",
ChatRole.AI => "assistant",
ChatRole.AGENT => "assistant",
ChatRole.SYSTEM => "system",
_ => "user",
};
}