Refactor components (#80)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2024-08-21 08:30:01 +02:00
1 parent a18cb22263
commit 1d1af91f3e
137 files changed
+220 -220

No files matched your search

@@ -0,0 +1,55 @@
@attribute [Route(Routes.ASSISTANT_AGENDA)]
@inherits AssistantBaseCore
<MudTextField T="string" @bind-Text="@this.inputName" Validation="@this.ValidateName" Label="Meeting Name" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Tag" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Name the meeting, seminar, etc." Placeholder="Weekly jour fixe" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputTopic" Validation="@this.ValidateTopic" Label="Topic" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.EventNote" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Describe the topic of the meeting, seminar, etc. Is it about quantum computing, software engineering, or is it a general business meeting?" Placeholder="Project meeting" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputContent" Validation="@this.ValidateContent" Label="Content list" Variant="Variant.Outlined" Lines="6" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Bullet list the content of the meeting, seminar, etc. roughly. Use dashes (-) to separate the items." Placeholder="@PLACEHOLDER_CONTENT" Class="mb-3" Immediate="@false" DebounceInterval="1_000" OnDebounceIntervalElapsed="@this.OnContentChanged" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.ListAlt"/>
<MudSelect T="string" Label="(Optional) What topics should be the focus?" MultiSelection="@true" @bind-SelectedValues="@this.selectedFoci" Variant="Variant.Outlined" Class="mb-3" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.ListAlt">
@foreach (var contentLine in this.contentLines)
{
@if(!this.justBriefly.Contains(contentLine))
{
<MudSelectItem T="string" Value="@contentLine">@contentLine</MudSelectItem>
}
}
</MudSelect>
<MudSelect T="string" Label="(Optional) What topics should only be briefly addressed?" MultiSelection="@true" @bind-SelectedValues="@this.justBriefly" Variant="Variant.Outlined" Class="mb-3" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.ListAlt">
@foreach (var contentLine in this.contentLines)
{
@if(!this.selectedFoci.Contains(contentLine))
{
<MudSelectItem T="string" Value="@contentLine">@contentLine</MudSelectItem>
}
}
</MudSelect>
<MudTextField T="string" @bind-Text="@this.inputObjective" Validation="@this.ValidateObjective" Label="Objective" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Flag" Variant="Variant.Outlined" Lines="3" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Describe the objective(s) of the meeting, seminar, etc. What should be achieved?" Placeholder="Discuss the current project status and plan the next steps." Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputModerator" Validation="@this.ValidateModerator" Label="Moderator" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Person3" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Who will moderate the meeting, seminar, etc.?" Placeholder="Jane Doe" Class="mb-3" />
<MudTextField T="string" @bind-Text="@this.inputDuration" Validation="@this.ValidateDuration" Label="Duration" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Schedule" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="How long will the meeting, seminar, etc. last? E.g., '2 hours', or '2 days (first day 8 hours, then 4 hours)', etc." Placeholder="2 hours" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputStartTime" Validation="@this.ValidateStartTime" Label="Start time" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Schedule" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="When will the meeting, seminar, etc. start? E.g., '9:00 AM', or '9:00 AM (CET)', etc. When the meeting is a multi-day event, specify the start time for each day." Placeholder="9:00 AM" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputWhoIsPresenting" Label="(Optional) Who is presenting?" Variant="Variant.Outlined" Lines="6" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="(Optional) List the persons who will present at the meeting, seminar, etc. Use dashes (-) to separate the items." Placeholder="@PLACEHOLDER_WHO_IS_PRESENTING" Class="mb-3"/>
<MudTextSwitch Label="Do the participants need to get to know each other first?" @bind-Value="@this.introduceParticipants" LabelOn="Yes, introduce participants" LabelOff="No, participants know each other" />
<EnumSelection T="NumberParticipants" @bind-Value="@this.numberParticipants" NameFunc="@(participants => participants.Name())" Icon="@Icons.Material.Filled.Group" Label="Number of participants" ValidateSelection="@this.ValidateNumberParticipants"/>
<MudTextSwitch Label="Should the participants be involved passively or actively?" @bind-Value="@this.activeParticipation" LabelOn="Active participation, like world café, discussions, etc." LabelOff="Passive participation, like presentations, lectures, etc." />
<MudTextSwitch Label="Is this a virtual event, e.g., a call or webinar?" @bind-Value="@this.isMeetingVirtual" LabelOn="Yes, this is a virtual event" LabelOff="No, this is a physical event" />
@if (!this.isMeetingVirtual)
{
<MudPaper Class="pa-3 mb-8 border-dashed border rounded-lg">
<MudTextField T="string" @bind-Text="@this.inputLocation" Validation="@this.ValidateLocation" Label="Location" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.MyLocation" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Where will the meeting, seminar, etc. take place?" Placeholder="Hamburg, Germany" Class="mb-3"/>
<MudTextSwitch Label="Should there be a joint dinner?" @bind-Value="@this.goingToDinner" LabelOn="Yes, there should be a joint dinner" LabelOff="No, there should be no joint dinner" />
<MudTextSwitch Label="Should there be a social activity?" @bind-Value="@this.doingSocialActivity" LabelOn="Yes, there should be a social activity" LabelOff="No, there should be no social activity" />
<MudTextSwitch Label="Do participants need to arrive and depart?" @bind-Value="@this.needToArriveAndDepart" LabelOn="Yes, participants need to arrive and depart" LabelOff="No, participants do not need to arrive and depart" />
<MudStack Row="@true" Wrap="Wrap.Wrap">
<MudTextSlider T="int" Label="Approx. duration of the lunch break" @bind-Value="@this.durationLunchBreak" Min="30" Max="120" Step="5" Unit="minutes"/>
<MudTextSlider T="int" Label="Approx. duration of the coffee or tea breaks" @bind-Value="@this.durationBreaks" Min="10" Max="60" Step="5" Unit="minutes"/>
</MudStack>
</MudPaper>
}
<EnumSelection T="CommonLanguages" NameFunc="@(language => language.NameSelecting())" @bind-Value="@this.selectedTargetLanguage" ValidateSelection="@this.ValidateTargetLanguage" Icon="@Icons.Material.Filled.Translate" Label="Target language" AllowOther="@true" OtherValue="CommonLanguages.OTHER" @bind-OtherInput="@this.customTargetLanguage" ValidateOther="@this.ValidateCustomLanguage" LabelOther="Custom target language" />
<ProviderSelection @bind-ProviderSettings="@this.providerSettings" ValidateProvider="@this.ValidatingProvider"/>
<MudButton Variant="Variant.Filled" Class="mb-3" OnClick="() => this.CreateAgenda()">
Create agenda
</MudButton>
@@ -0,0 +1,507 @@
using System.Text;
using AIStudio.Chat;
using AIStudio.Tools;
namespace AIStudio.Assistants.Agenda;
public partial class AssistantAgenda : AssistantBaseCore
{
protected override string Title => "Agenda Planner";
protected override string Description =>
"""
This agenda planner helps you create a structured agenda for your meeting or seminar. Just provide some basic
information about the event, and the assistant will generate an agenda for you. You can also specify the
duration, the start time, the location, the target language, and other details.
""";
protected override string SystemPrompt =>
$"""
You are a friendly assistant who supports the planning and consultation of events. You receive
metadata about an event and create an agenda from it. Additionally, you provide advice on what
the organizer and moderator should consider. When creating the agenda, you take into account that
time for questions and discussions needs to be scheduled. For large events, you take into account
the logistical challenges that come with an increasing number of participants.
If the user is planning interactions with participants, you know various methods. For example:
- **Townhall Meeting**: An open assembly where participants can ask questions and provide feedback directly to leaders or speakers. Good moderation is necessary to queue contributions and hand the floor to the respective person. Additionally, one person should take notes visible to all. Ideally, this should not be the moderator.
- **Speed Dating**: Short, structured interaction rounds where participants get the chance to quickly introduce themselves and make initial connections. A long row of tables is needed so that two people can sit opposite each other. A moderator with a stopwatch must ensure that participants rotate and change seats every 3 to 5 minutes.
- **World Café**: Participants discuss in small groups at tables and rotate after set intervals to exchange thoughts and develop ideas further. Each table needs a host. Notes should be taken on a flipchart or digitally at each table. At the end, the table hosts could present their insights to all participants in a plenary session.
- **Fishbowl**: A group discusses in an inner circle while a larger group listens from the outside. Occasionally, listeners can move into the inner circle to actively participate.
- **BarCamp (Unconference)**: Participants contribute to part of the agenda themselves and can act as both presenters and listeners. Anyone can propose and lead a session. However, there should be initial moderation to guide this meta-process.
- **Open Space Technology**: A method for large groups where participants bring up their own topics and then work intensively in small groups. At the end, the groups can present their findings to all participants in a plenary session.
- **Panel Discussion**: A group of experts discusses a specific topic in front of an audience, followed by a question-and-answer session.
- **Breakout Sessions**: Larger groups are divided into smaller, topic-related groups to discuss specific issues more deeply and interactively.
- **Interactive Polling**: Real-time surveys during the meeting or seminar using digital technology to collect immediate feedback from participants. With an increasing number of participants, technical requirements also become more complex: not every Wi-Fi router can handle several hundred or thousand devices. Additionally, the moderator or speaker must have a stable network connection to display the results. It would be problematic if the speaker depends on the same Wi-Fi as the participants: if the Wi-Fi crashes due to the high number of participants, the speaker cannot show the results. Therefore, a LAN for the speaker or the use of a mobile hotspot would be a better choice.
- **Peer Learning Groups**: Small groups of participants work together to learn from each other and collaboratively develop solutions for specific challenges.
- **Role Play/Simulation**: Participants take on roles to simulate certain scenarios, gaining practical experience and promoting dynamic discussions.
- **Round Table Discussions**: Small group discussions on specific topics, often without formal moderation, to encourage open and equal dialogue.
- **Mind Mapping**: A method for visualizing ideas and concepts, which can foster creative exchange within groups.
- **Case Study Analysis**: Groups analyze real or hypothetical case studies and present their solutions or insights.
- **Silent Meeting/Writing**: Participants write down their thoughts and questions, which are then collected and discussed to balance out loud or dominant voices.
- **Debate**: Participants argue for or against a specific topic, often with a moderator who ensures that the discussion remains constructive.
- **Workshops**: Interactive sessions where participants work together on specific tasks or challenges.
- **Brainstorming**: A method for generating ideas in a group setting, often with a focus on quantity and creativity.
- **Design Thinking**: A structured approach to innovation solutions. Design thinking is structured in six phases: understand, observe, point of view, ideate, prototype, and test. Depending on the number of participants, there are two moderates needed. One moderator leads the process, the other supports the participants in their work. Design thinking may takes up to two days.
You output the agenda in the following Markdown format:
# [Agenda Title]
- 09:00 - 09:05 (5 minutes): Welcome
- 09:05 - 09:15 (10 minutes): Introduction
- ...
{this.SystemPromptSocialActivity()}
{this.SystemPromptDinner()}
# Organizational notes
[Your advice for the organizer goes here, like room setup, technical requirements, etc.]
# Moderation notes
[Your advice for the moderator goes here]
Output the agenda in the following language: {this.PromptLanguage()}.
""";
private const string PLACEHOLDER_CONTENT = """
- Project status
- We need to discuss how to proceed
- Problem solving in work package 3 possible?
- Concerns of the members
""";
private const string PLACEHOLDER_WHO_IS_PRESENTING = """
- John Doe: Project status
- Mary Jane: Work package 3
""";
protected override IReadOnlyList<IButtonData> FooterButtons =>
[
new SendToButton
{
Self = SendTo.AGENDA_ASSISTANT,
},
];
protected override ChatThread ConvertToChatThread => (this.chatThread ?? new()) with
{
SystemPrompt = SystemPrompts.DEFAULT,
};
protected override void ResetFrom()
{
this.inputContent = string.Empty;
this.contentLines.Clear();
this.selectedFoci = [];
this.justBriefly = [];
this.inputWhoIsPresenting = string.Empty;
if (!this.MightPreselectValues())
{
this.inputTopic = string.Empty;
this.inputName = string.Empty;
this.inputDuration = string.Empty;
this.inputStartTime = string.Empty;
this.inputObjective = string.Empty;
this.inputModerator = string.Empty;
this.selectedTargetLanguage = CommonLanguages.AS_IS;
this.customTargetLanguage = string.Empty;
this.introduceParticipants = false;
this.isMeetingVirtual = true;
this.inputLocation = string.Empty;
this.goingToDinner = false;
this.doingSocialActivity = false;
this.needToArriveAndDepart = false;
this.durationLunchBreak = 0;
this.durationBreaks = 0;
this.activeParticipation = false;
this.numberParticipants = NumberParticipants.NOT_SPECIFIED;
}
}
protected override bool MightPreselectValues()
{
if (this.SettingsManager.ConfigurationData.Agenda.PreselectOptions)
{
this.inputTopic = this.SettingsManager.ConfigurationData.Agenda.PreselectTopic;
this.inputName = this.SettingsManager.ConfigurationData.Agenda.PreselectName;
this.inputDuration = this.SettingsManager.ConfigurationData.Agenda.PreselectDuration;
this.inputStartTime = this.SettingsManager.ConfigurationData.Agenda.PreselectStartTime;
this.inputObjective = this.SettingsManager.ConfigurationData.Agenda.PreselectObjective;
this.inputModerator = this.SettingsManager.ConfigurationData.Agenda.PreselectModerator;
this.selectedTargetLanguage = this.SettingsManager.ConfigurationData.Agenda.PreselectedTargetLanguage;
this.customTargetLanguage = this.SettingsManager.ConfigurationData.Agenda.PreselectedOtherLanguage;
this.introduceParticipants = this.SettingsManager.ConfigurationData.Agenda.PreselectIntroduceParticipants;
this.isMeetingVirtual = this.SettingsManager.ConfigurationData.Agenda.PreselectIsMeetingVirtual;
this.inputLocation = this.SettingsManager.ConfigurationData.Agenda.PreselectLocation;
this.goingToDinner = this.SettingsManager.ConfigurationData.Agenda.PreselectJointDinner;
this.doingSocialActivity = this.SettingsManager.ConfigurationData.Agenda.PreselectSocialActivity;
this.needToArriveAndDepart = this.SettingsManager.ConfigurationData.Agenda.PreselectArriveAndDepart;
this.durationLunchBreak = this.SettingsManager.ConfigurationData.Agenda.PreselectLunchTime;
this.durationBreaks = this.SettingsManager.ConfigurationData.Agenda.PreselectBreakTime;
this.activeParticipation = this.SettingsManager.ConfigurationData.Agenda.PreselectActiveParticipation;
this.numberParticipants = this.SettingsManager.ConfigurationData.Agenda.PreselectNumberParticipants;
this.providerSettings = this.SettingsManager.ConfigurationData.Providers.FirstOrDefault(x => x.Id == this.SettingsManager.ConfigurationData.Agenda.PreselectedProvider);
return true;
}
return false;
}
private string inputTopic = string.Empty;
private string inputName = string.Empty;
private string inputContent = string.Empty;
private string inputDuration = string.Empty;
private string inputStartTime = string.Empty;
private IEnumerable<string> selectedFoci = new HashSet<string>();
private IEnumerable<string> justBriefly = new HashSet<string>();
private string inputObjective = string.Empty;
private string inputModerator = string.Empty;
private CommonLanguages selectedTargetLanguage;
private string customTargetLanguage = string.Empty;
private bool introduceParticipants;
private bool isMeetingVirtual = true;
private string inputLocation = string.Empty;
private bool goingToDinner;
private bool doingSocialActivity;
private bool needToArriveAndDepart;
private int durationLunchBreak;
private int durationBreaks;
private bool activeParticipation;
private NumberParticipants numberParticipants;
private string inputWhoIsPresenting = string.Empty;
private readonly List<string> contentLines = [];
#region Overrides of ComponentBase
protected override async Task OnInitializedAsync()
{
this.MightPreselectValues();
var deferredContent = MessageBus.INSTANCE.CheckDeferredMessages<string>(Event.SEND_TO_AGENDA_ASSISTANT).FirstOrDefault();
if (deferredContent is not null)
this.inputContent = deferredContent;
await base.OnInitializedAsync();
}
#endregion
private void OnContentChanged(string content)
{
var previousSelectedFoci = new HashSet<string>();
var previousJustBriefly = new HashSet<string>();
this.contentLines.Clear();
foreach (var line in content.AsSpan().EnumerateLines())
{
var trimmedLine = line.Trim();
if (trimmedLine.StartsWith("-"))
trimmedLine = trimmedLine[1..].Trim();
if (trimmedLine.Length == 0)
continue;
var finalLine = trimmedLine.ToString();
if(this.selectedFoci.Any(x => x.StartsWith(finalLine, StringComparison.InvariantCultureIgnoreCase)))
previousSelectedFoci.Add(finalLine);
if(this.justBriefly.Any(x => x.StartsWith(finalLine, StringComparison.InvariantCultureIgnoreCase)))
previousJustBriefly.Add(finalLine);
this.contentLines.Add(finalLine);
}
this.selectedFoci = previousSelectedFoci;
this.justBriefly = previousJustBriefly;
}
private string? ValidateLocation(string location)
{
if(!this.isMeetingVirtual && string.IsNullOrWhiteSpace(location))
return "Please provide a location for the meeting or the seminar.";
return null;
}
private string? ValidateNumberParticipants(NumberParticipants selectedSize)
{
if(selectedSize is NumberParticipants.NOT_SPECIFIED)
return "Please select the number of participants.";
return null;
}
private string? ValidateTargetLanguage(CommonLanguages language)
{
if(language is CommonLanguages.AS_IS)
return "Please select a target language for the agenda.";
return null;
}
private string? ValidateDuration(string duration)
{
if(string.IsNullOrWhiteSpace(duration))
return "Please provide a duration for the meeting or the seminar, e.g. '2 hours', or '2 days (8 hours and 4 hours)', etc.";
return null;
}
private string? ValidateStartTime(string startTime)
{
if(string.IsNullOrWhiteSpace(startTime))
return "Please provide a start time for the meeting or the seminar. When the meeting is a multi-day event, specify the start time for each day, e.g. '9:00 AM, 10:00 AM', etc.";
return null;
}
private string? ValidateCustomLanguage(string language)
{
if(this.selectedTargetLanguage == CommonLanguages.OTHER && string.IsNullOrWhiteSpace(language))
return "Please provide a custom language.";
return null;
}
private string? ValidateTopic(string topic)
{
if(string.IsNullOrWhiteSpace(topic))
return "Please provide a topic for the agenda. What is the meeting or the seminar about?";
return null;
}
private string? ValidateName(string name)
{
if(string.IsNullOrWhiteSpace(name))
return "Please provide a name for the meeting or the seminar.";
return null;
}
private string? ValidateContent(string content)
{
if(string.IsNullOrWhiteSpace(content))
return "Please provide some content for the agenda. What are the main points of the meeting or the seminar?";
var lines = content.Split('\n');
foreach (var line in lines)
if(!line.TrimStart().StartsWith('-'))
return "Please start each line of your content list with a dash (-) to create a bullet point list.";
return null;
}
private string? ValidateObjective(string objective)
{
if(string.IsNullOrWhiteSpace(objective))
return "Please provide an objective for the meeting or the seminar. What do you want to achieve?";
return null;
}
private string? ValidateModerator(string moderator)
{
if(string.IsNullOrWhiteSpace(moderator))
return "Please provide a moderator for the meeting or the seminar. Who will lead the discussion?";
return null;
}
private async Task CreateAgenda()
{
await this.form!.Validate();
if (!this.inputIsValid)
return;
this.CreateChatThread();
var time = this.AddUserRequest(
$"""
Create an agenda for the meeting or seminar wit the title '{this.inputName}' using the following details:
- The overall topic is '{this.inputTopic}'.
- The objective of the meeting is '{this.inputObjective}'.
- The moderator is '{this.inputModerator}'.
- The planned duration is '{this.inputDuration}'.
- The planned start time is '{this.inputStartTime}'.
{this.PromptGettingToKnowEachOther()}
- The number of participants is '{this.numberParticipants.Name()}'.
{this.PromptActiveParticipation()}
{this.PromptVirtualMeeting()}
{this.PromptPhysicalMeeting()}
Here is draft what was planned for the meeting:
{this.inputContent}
Please do not follow this draft strictly. It is just a suggestion.
{this.PromptFoci()}
{this.PromptBriefly()}
{this.PromptWhoIsPresenting()}
""");
await this.AddAIResponseAsync(time);
}
private string PromptLanguage()
{
if(this.selectedTargetLanguage is CommonLanguages.OTHER)
return this.customTargetLanguage;
return this.selectedTargetLanguage.Name();
}
private string PromptPhysicalMeeting()
{
if(this.isMeetingVirtual)
return string.Empty;
return $"""
- The meeting takes place at the following location: '{this.inputLocation}'.
{this.PromptJoiningDinner()}
{this.PromptSocialActivity()}
{this.PromptArriveAndDepart()}
- In case a lunch break is necessary, the break should about {this.durationLunchBreak} minutes long.
- In case any breaks are necessary, the breaks should be about {this.durationBreaks} minutes long.
""";
}
private string PromptArriveAndDepart()
{
if (this.needToArriveAndDepart)
return "- The participants should have time to arrive and depart.";
return "- The participants do not need to arrive and depart.";
}
private string PromptSocialActivity()
{
if (this.doingSocialActivity)
return "- The participants will engage in a social activity after the meeting or seminar. This can be a team-building exercise, a sightseeing tour, or a visit to a local attraction. Please make a recommendation for an activity at '{this.inputLocation}'.";
return "- The participants will not engage in a social activity after the meeting or seminar.";
}
private string SystemPromptSocialActivity()
{
if(this.doingSocialActivity)
return """
- 16:00 Departure to the social event [Consider the time needed to get to the location].
- 17:00 [Insert your advice for the social activity here].
""";
return string.Empty;
}
private string SystemPromptDinner()
{
if(this.goingToDinner)
return """
- 19:00 Departure to the restaurant [Consider the time needed to get to the restaurant].
- 20:00 [Insert your advice for the dinner here.].
""";
return string.Empty;
}
private string PromptJoiningDinner()
{
if (this.goingToDinner)
return $"- The participants will join for a dinner after the meeting or seminar. Please make a recommendation for a restaurant at '{this.inputLocation}'.";
return "- The participants will not join for a dinner after the meeting or seminar.";
}
private string PromptVirtualMeeting()
{
if (this.isMeetingVirtual)
return "- The meeting or seminar will be held virtually, e.g, a call or webinar. The participants will join online.";
return "- The meeting or seminar will be held in person.";
}
private string PromptActiveParticipation()
{
if (this.activeParticipation)
return "- The participants should actively participate in the meeting or seminar. This can be done through discussions, questions, and contributions to the content.";
return "- The participants do not need to actively participate.";
}
private string PromptGettingToKnowEachOther()
{
if (this.introduceParticipants)
return "- The participants should introduce themselves to get to know each other. This can be done in a round or in pairs. The moderator should ensure that everyone has the opportunity to speak.";
return "- The participants do not need to introduce themselves.";
}
private string PromptFoci()
{
if (this.selectedFoci.Any())
{
return $"""
Out of this content, the following points should be focused on:
{this.ConvertItemsToMarkdown(this.selectedFoci)}
""";
}
return string.Empty;
}
private string PromptBriefly()
{
if (this.justBriefly.Any())
{
return $"""
The following points should be just briefly mentioned:
{this.ConvertItemsToMarkdown(this.justBriefly)}
""";
}
return string.Empty;
}
private string PromptWhoIsPresenting()
{
if (!string.IsNullOrWhiteSpace(this.inputWhoIsPresenting))
{
return $"""
The following persons will present the content:
{this.inputWhoIsPresenting}
""";
}
return string.Empty;
}
private string ConvertItemsToMarkdown(IEnumerable<string> items)
{
var markdown = new StringBuilder();
foreach (var item in items)
markdown.AppendLine($"- {item}");
return markdown.ToString();
}
}
@@ -0,0 +1,18 @@
namespace AIStudio.Assistants.Agenda;
public enum NumberParticipants
{
NOT_SPECIFIED,
PEER_TO_PEER, // 2 participants
SMALL_GROUP, // 3 - 5 participants
LARGE_GROUP, // 6 - 12 participants
MULTIPLE_SMALL_GROUPS, // 13 - 20 participants
MULTIPLE_LARGE_GROUPS, // 21 - 30 participants
SYMPOSIUM, // 31 - 100 participants
CONFERENCE, // 101 - 200 participants
CONGRESS, // 201 - 1000 participants
LARGE_EVENT, // 1000+ participants
}
@@ -0,0 +1,24 @@
namespace AIStudio.Assistants.Agenda;
public static class NumberParticipantsExtensions
{
public static string Name(this NumberParticipants numberParticipants) => numberParticipants switch
{
NumberParticipants.NOT_SPECIFIED => "Please select how many participants are expected",
NumberParticipants.PEER_TO_PEER => "2 (peer to peer)",
NumberParticipants.SMALL_GROUP => "3 - 5 (small group)",
NumberParticipants.LARGE_GROUP => "6 - 12 (large group)",
NumberParticipants.MULTIPLE_SMALL_GROUPS => "13 - 20 (multiple small groups)",
NumberParticipants.MULTIPLE_LARGE_GROUPS => "21 - 30 (multiple large groups)",
NumberParticipants.SYMPOSIUM => "31 - 100 (symposium)",
NumberParticipants.CONFERENCE => "101 - 200 (conference)",
NumberParticipants.CONGRESS => "201 - 1,000 (congress)",
NumberParticipants.LARGE_EVENT => "1,000+ (large event)",
_ => "Unknown"
};
}
@@ -0,0 +1,77 @@
@using AIStudio.Chat
<MudText Typo="Typo.h3" Class="mb-2 mr-3">
@(this.Title)
</MudText>
<InnerScrolling HeaderHeight="12.3em">
<ChildContent>
<MudForm @ref="@(this.form)" @bind-IsValid="@(this.inputIsValid)" @bind-Errors="@(this.inputIssues)" Class="pr-2">
<MudText Typo="Typo.body1" Align="Align.Justify" Class="mb-6">
@(this.Description)
</MudText>
@if (this.Body is not null)
{
@(this.Body)
}
</MudForm>
<Issues IssuesData="@(this.inputIssues)"/>
@if (this.ShowDedicatedProgress && this.isProcessing)
{
<MudProgressLinear Color="Color.Primary" Indeterminate="true" Class="mb-6" />
}
<div id="@RESULT_DIV_ID" class="mr-2 mt-3">
@if (this.ShowResult && this.resultingContentBlock is not null)
{
<ContentBlockComponent Role="@(this.resultingContentBlock.Role)" Type="@(this.resultingContentBlock.ContentType)" Time="@(this.resultingContentBlock.Time)" Content="@(this.resultingContentBlock.Content)"/>
}
</div>
<div id="@AFTER_RESULT_DIV_ID" class="mt-3">
</div>
@if (this.FooterButtons.Count > 0)
{
<MudStack Row="@true" Wrap="Wrap.Wrap" Class="mt-3 mr-2">
@foreach (var button in this.FooterButtons)
{
switch (button)
{
case ButtonData buttonData when !string.IsNullOrWhiteSpace(buttonData.Tooltip):
<MudTooltip Text="@buttonData.Tooltip">
<MudButton Variant="Variant.Filled" Color="@buttonData.Color" StartIcon="@GetButtonIcon(buttonData.Icon)" OnClick="async () => await buttonData.AsyncAction()">
@buttonData.Text
</MudButton>
</MudTooltip>
break;
case ButtonData buttonData:
<MudButton Variant="Variant.Filled" Color="@buttonData.Color" StartIcon="@GetButtonIcon(buttonData.Icon)" OnClick="async () => await buttonData.AsyncAction()">
@buttonData.Text
</MudButton>
break;
case SendToButton sendToButton:
<MudMenu StartIcon="@Icons.Material.Filled.Apps" EndIcon="@Icons.Material.Filled.KeyboardArrowDown" Label="Send to ..." Variant="Variant.Filled" Color="Color.Info">
@foreach (var assistant in Enum.GetValues<SendTo>().OrderBy(n => n.Name().Length))
{
if(assistant is SendTo.NONE || sendToButton.Self == assistant)
continue;
<MudMenuItem OnClick="() => this.SendToAssistant(assistant, sendToButton)">
@assistant.Name()
</MudMenuItem>
}
</MudMenu>
break;
}
}
<MudButton Variant="Variant.Filled" Color="Color.Warning" StartIcon="@Icons.Material.Filled.Refresh" OnClick="() => this.InnerResetForm()">
Reset
</MudButton>
</MudStack>
}
</ChildContent>
</InnerScrolling>
@@ -0,0 +1,229 @@
using AIStudio.Chat;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Tools;
using Microsoft.AspNetCore.Components;
namespace AIStudio.Assistants;
public abstract partial class AssistantBase : ComponentBase
{
[Inject]
protected SettingsManager SettingsManager { get; set; } = null!;
[Inject]
protected IJSRuntime JsRuntime { get; init; } = null!;
[Inject]
protected ThreadSafeRandom RNG { get; init; } = null!;
[Inject]
protected ISnackbar Snackbar { get; init; } = null!;
[Inject]
protected Rust Rust { get; init; } = null!;
[Inject]
protected NavigationManager NavigationManager { get; init; } = null!;
internal const string AFTER_RESULT_DIV_ID = "afterAssistantResult";
internal const string RESULT_DIV_ID = "assistantResult";
protected abstract string Title { get; }
protected abstract string Description { get; }
protected abstract string SystemPrompt { get; }
protected abstract void ResetFrom();
protected abstract bool MightPreselectValues();
private protected virtual RenderFragment? Body => null;
protected virtual bool ShowResult => true;
protected virtual bool ShowDedicatedProgress => false;
protected virtual ChatThread ConvertToChatThread => this.chatThread ?? new();
protected virtual IReadOnlyList<IButtonData> FooterButtons => [];
protected static readonly Dictionary<string, object?> USER_INPUT_ATTRIBUTES = new();
protected AIStudio.Settings.Provider providerSettings;
protected MudForm? form;
protected bool inputIsValid;
protected ChatThread? chatThread;
private ContentBlock? resultingContentBlock;
private string[] inputIssues = [];
private bool isProcessing;
#region Overrides of ComponentBase
protected override async Task OnParametersSetAsync()
{
// Configure the spellchecking for the user input:
this.SettingsManager.InjectSpellchecking(USER_INPUT_ATTRIBUTES);
await base.OnParametersSetAsync();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
// Reset the validation when not editing and on the first render.
// We don't want to show validation errors when the user opens the dialog.
if(firstRender)
this.form?.ResetValidation();
await base.OnAfterRenderAsync(firstRender);
}
#endregion
protected string? ValidatingProvider(AIStudio.Settings.Provider provider)
{
if(provider.UsedProvider == Providers.NONE)
return "Please select a provider.";
return null;
}
protected void CreateChatThread()
{
this.chatThread = new()
{
WorkspaceId = Guid.Empty,
ChatId = Guid.NewGuid(),
Name = string.Empty,
Seed = this.RNG.Next(),
SystemPrompt = this.SystemPrompt,
Blocks = [],
};
}
protected DateTimeOffset AddUserRequest(string request)
{
var time = DateTimeOffset.Now;
this.chatThread!.Blocks.Add(new ContentBlock
{
Time = time,
ContentType = ContentType.TEXT,
Role = ChatRole.USER,
Content = new ContentText
{
Text = request,
},
});
return time;
}
protected async Task<string> AddAIResponseAsync(DateTimeOffset time)
{
var aiText = new ContentText
{
// We have to wait for the remote
// for the content stream:
InitialRemoteWait = true,
};
this.resultingContentBlock = new ContentBlock
{
Time = time,
ContentType = ContentType.TEXT,
Role = ChatRole.AI,
Content = aiText,
};
this.chatThread?.Blocks.Add(this.resultingContentBlock);
this.isProcessing = true;
this.StateHasChanged();
// Use the selected provider to get the AI response.
// By awaiting this line, we wait for the entire
// content to be streamed.
await aiText.CreateFromProviderAsync(this.providerSettings.CreateProvider(), this.JsRuntime, this.SettingsManager, this.providerSettings.Model, this.chatThread);
this.isProcessing = false;
this.StateHasChanged();
// Return the AI response:
return aiText.Text;
}
protected async Task CopyToClipboard(string text)
{
await this.Rust.CopyText2Clipboard(this.JsRuntime, this.Snackbar, text);
}
private static string? GetButtonIcon(string icon)
{
if(string.IsNullOrWhiteSpace(icon))
return null;
return icon;
}
private Task SendToAssistant(SendTo destination, SendToButton sendToButton)
{
var contentToSend = sendToButton.UseResultingContentBlockData switch
{
false => sendToButton.GetText(),
true => this.resultingContentBlock?.Content switch
{
ContentText textBlock => textBlock.Text,
_ => string.Empty,
},
};
var (eventItem, path) = destination switch
{
SendTo.AGENDA_ASSISTANT => (Event.SEND_TO_AGENDA_ASSISTANT, Routes.ASSISTANT_AGENDA),
SendTo.CODING_ASSISTANT => (Event.SEND_TO_CODING_ASSISTANT, Routes.ASSISTANT_CODING),
SendTo.REWRITE_ASSISTANT => (Event.SEND_TO_REWRITE_ASSISTANT, Routes.ASSISTANT_REWRITE),
SendTo.TRANSLATION_ASSISTANT => (Event.SEND_TO_TRANSLATION_ASSISTANT, Routes.ASSISTANT_TRANSLATION),
SendTo.ICON_FINDER_ASSISTANT => (Event.SEND_TO_ICON_FINDER_ASSISTANT, Routes.ASSISTANT_ICON_FINDER),
SendTo.GRAMMAR_SPELLING_ASSISTANT => (Event.SEND_TO_GRAMMAR_SPELLING_ASSISTANT, Routes.ASSISTANT_GRAMMAR_SPELLING),
SendTo.TEXT_SUMMARIZER_ASSISTANT => (Event.SEND_TO_TEXT_SUMMARIZER_ASSISTANT, Routes.ASSISTANT_SUMMARIZER),
SendTo.CHAT => (Event.SEND_TO_CHAT, Routes.CHAT),
_ => (Event.NONE, Routes.ASSISTANTS),
};
switch (destination)
{
case SendTo.CHAT:
MessageBus.INSTANCE.DeferMessage(this, eventItem, this.ConvertToChatThread);
break;
default:
MessageBus.INSTANCE.DeferMessage(this, eventItem, contentToSend);
break;
}
this.NavigationManager.NavigateTo(path);
return Task.CompletedTask;
}
private async Task InnerResetForm()
{
this.resultingContentBlock = null;
this.providerSettings = default;
await this.JsRuntime.ClearDiv(RESULT_DIV_ID);
await this.JsRuntime.ClearDiv(AFTER_RESULT_DIV_ID);
this.ResetFrom();
this.inputIsValid = false;
this.inputIssues = [];
this.form?.ResetValidation();
this.StateHasChanged();
this.form?.ResetValidation();
}
}
@@ -0,0 +1,19 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
namespace AIStudio.Assistants;
//
// See https://stackoverflow.com/a/77300384/2258393 for why this class is necessary
//
public abstract class AssistantBaseCore : AssistantBase
{
private protected sealed override RenderFragment Body => this.BuildRenderTree;
// Allow content to be provided by a .razor file but without
// overriding the content of the base class
protected new virtual void BuildRenderTree(RenderTreeBuilder builder)
{
}
}
@@ -0,0 +1,30 @@
@attribute [Route(Routes.ASSISTANT_CODING)]
@inherits AssistantBaseCore
<MudExpansionPanels Class="mb-3">
@for (var contextIndex = 0; contextIndex < this.codingContexts.Count; contextIndex++)
{
var codingContext = this.codingContexts[contextIndex];
<ExpansionPanel HeaderText="@codingContext.Id" HeaderIcon="@Icons.Material.Filled.Code">
<CodingContextItem @bind-CodingContext="@codingContext"/>
</ExpansionPanel>
}
</MudExpansionPanels>
<MudButton Variant="Variant.Filled" OnClick="() => this.AddCodingContext()" Class="mb-3">
Add context
</MudButton>
<MudStack Row="@false" Class="mb-3">
<MudTextSwitch Label="Do you want to provide compiler messages?" @bind-Value="@this.provideCompilerMessages" LabelOn="Yes, provide compiler messages" LabelOff="No, there are no compiler messages" />
@if (this.provideCompilerMessages)
{
<MudTextField T="string" @bind-Text="@this.compilerMessages" Validation="@this.ValidatingCompilerMessages" AdornmentIcon="@Icons.Material.Filled.Error" Adornment="Adornment.Start" Label="Compiler messages" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
}
</MudStack>
<MudTextField T="string" @bind-Text="@this.questions" Validation="@this.ValidateQuestions" AdornmentIcon="@Icons.Material.Filled.QuestionMark" Adornment="Adornment.Start" Label="Your question(s)" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<ProviderSelection @bind-ProviderSettings="@this.providerSettings" ValidateProvider="@this.ValidatingProvider"/>
<MudButton Variant="Variant.Filled" Color="Color.Info" OnClick="() => this.GetSupport()" Class="mb-3">
Get support
</MudButton>
@@ -0,0 +1,159 @@
using System.Text;
using AIStudio.Tools;
namespace AIStudio.Assistants.Coding;
public partial class AssistantCoding : AssistantBaseCore
{
protected override string Title => "Coding Assistant";
protected override string Description =>
"""
This coding assistant supports you in writing code. Provide some coding context by copying and pasting
your code into the input fields. You might assign an ID to your code snippet to easily reference it later.
When you have compiler messages, you can paste them into the input fields to get help with debugging as well.
""";
protected override string SystemPrompt =>
"""
You are a friendly, helpful senior software developer with extensive experience in various programming languages
and concepts. You are familiar with principles like DRY, KISS, YAGNI, and SOLID and can apply and explain them.
You know object-oriented programming, as well as functional programming and procedural programming. You are also
familiar with design patterns and can explain them. You are an expert of debugging and can help with compiler
messages. You can also help with code refactoring and optimization.
When the user asks in a different language than English, you answer in the same language!
""";
protected override IReadOnlyList<IButtonData> FooterButtons =>
[
new SendToButton
{
Self = SendTo.CODING_ASSISTANT,
},
];
protected override void ResetFrom()
{
this.codingContexts.Clear();
this.compilerMessages = string.Empty;
this.questions = string.Empty;
if (!this.MightPreselectValues())
{
this.provideCompilerMessages = false;
}
}
protected override bool MightPreselectValues()
{
if (this.SettingsManager.ConfigurationData.Coding.PreselectOptions)
{
this.provideCompilerMessages = this.SettingsManager.ConfigurationData.Coding.PreselectCompilerMessages;
this.providerSettings = this.SettingsManager.ConfigurationData.Providers.FirstOrDefault(x => x.Id == this.SettingsManager.ConfigurationData.Coding.PreselectedProvider);
return true;
}
return false;
}
private readonly List<CodingContext> codingContexts = new();
private bool provideCompilerMessages;
private string compilerMessages = string.Empty;
private string questions = string.Empty;
#region Overrides of ComponentBase
protected override async Task OnInitializedAsync()
{
this.MightPreselectValues();
var deferredContent = MessageBus.INSTANCE.CheckDeferredMessages<string>(Event.SEND_TO_CODING_ASSISTANT).FirstOrDefault();
if (deferredContent is not null)
this.questions = deferredContent;
await base.OnInitializedAsync();
}
#endregion
private string? ValidatingCompilerMessages(string checkCompilerMessages)
{
if(!this.provideCompilerMessages)
return null;
if(string.IsNullOrWhiteSpace(checkCompilerMessages))
return "Please provide the compiler messages.";
return null;
}
private string? ValidateQuestions(string checkQuestions)
{
if(string.IsNullOrWhiteSpace(checkQuestions))
return "Please provide your questions.";
return null;
}
private void AddCodingContext()
{
this.codingContexts.Add(new()
{
Id = $"Context {this.codingContexts.Count + 1}",
Language = this.SettingsManager.ConfigurationData.Coding.PreselectOptions ? this.SettingsManager.ConfigurationData.Coding.PreselectedProgrammingLanguage : default,
OtherLanguage = this.SettingsManager.ConfigurationData.Coding.PreselectOptions ? this.SettingsManager.ConfigurationData.Coding.PreselectedOtherProgrammingLanguage : string.Empty,
});
}
private async Task GetSupport()
{
await this.form!.Validate();
if (!this.inputIsValid)
return;
var sbContext = new StringBuilder();
if (this.codingContexts.Count > 0)
{
sbContext.AppendLine("I have the following coding context:");
sbContext.AppendLine();
foreach (var codingContext in this.codingContexts)
{
sbContext.AppendLine($"ID: {codingContext.Id}");
if(codingContext.Language is not CommonCodingLanguages.OTHER)
sbContext.AppendLine($"Language: {codingContext.Language.Name()}");
else
sbContext.AppendLine($"Language: {codingContext.OtherLanguage}");
sbContext.AppendLine("Content:");
sbContext.AppendLine("```");
sbContext.AppendLine(codingContext.Code);
sbContext.AppendLine("```");
sbContext.AppendLine();
}
}
var sbCompilerMessages = new StringBuilder();
if (this.provideCompilerMessages)
{
sbCompilerMessages.AppendLine("I have the following compiler messages:");
sbCompilerMessages.AppendLine();
sbCompilerMessages.AppendLine("```");
sbCompilerMessages.AppendLine(this.compilerMessages);
sbCompilerMessages.AppendLine("```");
sbCompilerMessages.AppendLine();
}
this.CreateChatThread();
var time = this.AddUserRequest(
$"""
{sbContext}
{sbCompilerMessages}
My questions are:
{this.questions}
""");
await this.AddAIResponseAsync(time);
}
}
@@ -0,0 +1,16 @@
namespace AIStudio.Assistants.Coding;
public sealed class CodingContext(string id, CommonCodingLanguages language, string otherLanguage, string code)
{
public CodingContext() : this(string.Empty, CommonCodingLanguages.NONE, string.Empty, string.Empty)
{
}
public string Id { get; set; } = id;
public CommonCodingLanguages Language { get; set; } = language;
public string OtherLanguage { get; set; } = otherLanguage;
public string Code { get; set; } = code;
}
@@ -0,0 +1,14 @@
<MudTextField T="string" @bind-Text="@this.CodingContext.Id" AdornmentIcon="@Icons.Material.Filled.Numbers" Adornment="Adornment.Start" Label="(Optional) Identifier" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<MudStack Row="@true" AlignItems="AlignItems.Center" Class="mb-3">
<MudSelect T="CommonCodingLanguages" @bind-Value="@this.CodingContext.Language" AdornmentIcon="@Icons.Material.Filled.Code" Adornment="Adornment.Start" Label="Language" Variant="Variant.Outlined" Margin="Margin.Dense">
@foreach (var language in Enum.GetValues<CommonCodingLanguages>())
{
<MudSelectItem Value="@language">@language.Name()</MudSelectItem>
}
</MudSelect>
@if (this.CodingContext.Language is CommonCodingLanguages.OTHER)
{
<MudTextField T="string" @bind-Text="@this.CodingContext.OtherLanguage" Validation="@this.ValidatingOtherLanguage" Label="Other language" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
}
</MudStack>
<MudTextField T="string" @bind-Text="@this.CodingContext.Code" Validation="@this.ValidatingCode" AdornmentIcon="@Icons.Material.Filled.DocumentScanner" Adornment="Adornment.Start" Label="Your code" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES" />
@@ -0,0 +1,50 @@
using AIStudio.Settings;
using Microsoft.AspNetCore.Components;
namespace AIStudio.Assistants.Coding;
public partial class CodingContextItem : ComponentBase
{
[Parameter]
public CodingContext CodingContext { get; set; } = new();
[Parameter]
public EventCallback<CodingContext> CodingContextChanged { get; set; }
[Inject]
protected SettingsManager SettingsManager { get; set; } = null!;
private static readonly Dictionary<string, object?> USER_INPUT_ATTRIBUTES = new();
#region Overrides of ComponentBase
protected override async Task OnParametersSetAsync()
{
// Configure the spellchecking for the user input:
this.SettingsManager.InjectSpellchecking(USER_INPUT_ATTRIBUTES);
await base.OnParametersSetAsync();
}
#endregion
private string? ValidatingCode(string code)
{
if(string.IsNullOrWhiteSpace(code))
return $"{this.CodingContext.Id}: Please provide your input.";
return null;
}
private string? ValidatingOtherLanguage(string language)
{
if(this.CodingContext.Language != CommonCodingLanguages.OTHER)
return null;
if(string.IsNullOrWhiteSpace(language))
return "Please specify the language.";
return null;
}
}
@@ -0,0 +1,43 @@
namespace AIStudio.Assistants.Coding;
public static class CommonCodingLanguageExtensions
{
public static string Name(this CommonCodingLanguages language) => language switch
{
CommonCodingLanguages.NONE => "None",
CommonCodingLanguages.BASH => "Bash",
CommonCodingLanguages.BLAZOR => ".NET Blazor",
CommonCodingLanguages.C => "C",
CommonCodingLanguages.CPP => "C++",
CommonCodingLanguages.CSHARP => "C#",
CommonCodingLanguages.CSS => "CSS",
CommonCodingLanguages.FORTRAN => "Fortran",
CommonCodingLanguages.GDSCRIPT => "GDScript",
CommonCodingLanguages.GO => "Go",
CommonCodingLanguages.HTML => "HTML",
CommonCodingLanguages.JAVA => "Java",
CommonCodingLanguages.JAVASCRIPT => "JavaScript",
CommonCodingLanguages.JSON => "JSON",
CommonCodingLanguages.JULIA => "Julia",
CommonCodingLanguages.KOTLIN => "Kotlin",
CommonCodingLanguages.LUA => "Lua",
CommonCodingLanguages.MARKDOWN => "Markdown",
CommonCodingLanguages.MATHEMATICA => "Mathematica",
CommonCodingLanguages.MATLAB => "MATLAB",
CommonCodingLanguages.PHP => "PHP",
CommonCodingLanguages.POWERSHELL => "PowerShell",
CommonCodingLanguages.PROLOG => "Prolog",
CommonCodingLanguages.PYTHON => "Python",
CommonCodingLanguages.R => "R",
CommonCodingLanguages.RUBY => "Ruby",
CommonCodingLanguages.RUST => "Rust",
CommonCodingLanguages.SQL => "SQL",
CommonCodingLanguages.SWIFT => "Swift",
CommonCodingLanguages.TYPESCRIPT => "TypeScript",
CommonCodingLanguages.XML => "XML",
CommonCodingLanguages.OTHER => "Other",
_ => "Unknown"
};
}
@@ -0,0 +1,39 @@
namespace AIStudio.Assistants.Coding;
public enum CommonCodingLanguages
{
NONE,
BASH,
BLAZOR,
C,
CPP,
CSHARP,
CSS,
FORTRAN,
GDSCRIPT,
GO,
HTML,
JAVA,
JAVASCRIPT,
JSON,
JULIA,
KOTLIN,
LUA,
MARKDOWN,
MATHEMATICA,
MATLAB,
PHP,
POWERSHELL,
PROLOG,
PYTHON,
R,
RUBY,
RUST,
SQL,
SWIFT,
TYPESCRIPT,
XML,
OTHER,
}
@@ -0,0 +1,10 @@
@attribute [Route(Routes.ASSISTANT_GRAMMAR_SPELLING)]
@inherits AssistantBaseCore
<MudTextField T="string" @bind-Text="@this.inputText" Validation="@this.ValidateText" AdornmentIcon="@Icons.Material.Filled.DocumentScanner" Adornment="Adornment.Start" Label="Your input to check" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<EnumSelection T="CommonLanguages" NameFunc="@(language => language.NameSelectingOptional())" @bind-Value="@this.selectedTargetLanguage" Icon="@Icons.Material.Filled.Translate" Label="Language" AllowOther="@true" OtherValue="CommonLanguages.OTHER" @bind-OtherInput="@this.customTargetLanguage" ValidateOther="@this.ValidateCustomLanguage" LabelOther="Custom language" />
<ProviderSelection @bind-ProviderSettings="@this.providerSettings" ValidateProvider="@this.ValidatingProvider"/>
<MudButton Variant="Variant.Filled" Class="mb-3" OnClick="() => this.ProofreadText()">
Proofread
</MudButton>
@@ -0,0 +1,132 @@
using AIStudio.Chat;
using AIStudio.Tools;
namespace AIStudio.Assistants.GrammarSpelling;
public partial class AssistantGrammarSpelling : AssistantBaseCore
{
protected override string Title => "Grammar & Spelling Checker";
protected override string Description =>
"""
Check the grammar and spelling of a text.
""";
protected override string SystemPrompt =>
$"""
You are an expert in languages and their rules. For example, you know how US and UK English or German in
Germany and German in Austria differ. You receive text as input. You check the spelling and grammar of
this text according to the rules of {this.SystemPromptLanguage()}. You never add information. You
never ask the user for additional information. You do not attempt to improve the wording of the text.
Your response includes only the corrected text. Do not explain your changes. If no changes are needed,
you return the text unchanged.
""";
protected override bool ShowResult => false;
protected override bool ShowDedicatedProgress => true;
protected override IReadOnlyList<IButtonData> FooterButtons =>
[
new ButtonData("Copy result", Icons.Material.Filled.ContentCopy, Color.Default, string.Empty, () => this.CopyToClipboard(this.correctedText)),
new SendToButton
{
Self = SendTo.GRAMMAR_SPELLING_ASSISTANT,
UseResultingContentBlockData = false,
GetText = () => string.IsNullOrWhiteSpace(this.correctedText) ? this.inputText : this.correctedText
},
];
protected override ChatThread ConvertToChatThread => (this.chatThread ?? new()) with
{
SystemPrompt = SystemPrompts.DEFAULT,
};
protected override void ResetFrom()
{
this.inputText = string.Empty;
this.correctedText = string.Empty;
if (!this.MightPreselectValues())
{
this.selectedTargetLanguage = CommonLanguages.AS_IS;
this.customTargetLanguage = string.Empty;
}
}
protected override bool MightPreselectValues()
{
if (this.SettingsManager.ConfigurationData.GrammarSpelling.PreselectOptions)
{
this.selectedTargetLanguage = this.SettingsManager.ConfigurationData.GrammarSpelling.PreselectedTargetLanguage;
this.customTargetLanguage = this.SettingsManager.ConfigurationData.GrammarSpelling.PreselectedOtherLanguage;
this.providerSettings = this.SettingsManager.ConfigurationData.Providers.FirstOrDefault(x => x.Id == this.SettingsManager.ConfigurationData.GrammarSpelling.PreselectedProvider);
return true;
}
return false;
}
#region Overrides of ComponentBase
protected override async Task OnInitializedAsync()
{
this.MightPreselectValues();
var deferredContent = MessageBus.INSTANCE.CheckDeferredMessages<string>(Event.SEND_TO_GRAMMAR_SPELLING_ASSISTANT).FirstOrDefault();
if (deferredContent is not null)
this.inputText = deferredContent;
await base.OnInitializedAsync();
}
#endregion
private string inputText = string.Empty;
private CommonLanguages selectedTargetLanguage;
private string customTargetLanguage = string.Empty;
private string correctedText = string.Empty;
private string? ValidateText(string text)
{
if(string.IsNullOrWhiteSpace(text))
return "Please provide a text as input. You might copy the desired text from a document or a website.";
return null;
}
private string? ValidateCustomLanguage(string language)
{
if(this.selectedTargetLanguage == CommonLanguages.OTHER && string.IsNullOrWhiteSpace(language))
return "Please provide a custom language.";
return null;
}
private string SystemPromptLanguage()
{
var lang = this.selectedTargetLanguage switch
{
CommonLanguages.AS_IS => "the source language",
CommonLanguages.OTHER => this.customTargetLanguage,
_ => $"{this.selectedTargetLanguage.Name()}",
};
if (string.IsNullOrWhiteSpace(lang))
return "the source language";
return lang;
}
private async Task ProofreadText()
{
await this.form!.Validate();
if (!this.inputIsValid)
return;
this.CreateChatThread();
var time = this.AddUserRequest(this.inputText);
this.correctedText = await this.AddAIResponseAsync(time);
await this.JsRuntime.GenerateAndShowDiff(this.inputText, this.correctedText);
}
}
@@ -0,0 +1,22 @@
@attribute [Route(Routes.ASSISTANT_ICON_FINDER)]
@inherits AssistantBaseCore
<MudTextField T="string" @bind-Text="@this.inputContext" Validation="@this.ValidatingContext" AdornmentIcon="@Icons.Material.Filled.Description" Adornment="Adornment.Start" Label="Your context" Variant="Variant.Outlined" Lines="3" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<MudStack Row="@true" AlignItems="AlignItems.Center" Class="mb-3">
<MudSelect T="IconSources" @bind-Value="@this.selectedIconSource" AdornmentIcon="@Icons.Material.Filled.Source" Adornment="Adornment.Start" Label="Your icon source" Variant="Variant.Outlined" Margin="Margin.Dense">
@foreach (var source in Enum.GetValues<IconSources>())
{
<MudSelectItem Value="@source">@source.Name()</MudSelectItem>
}
</MudSelect>
@if (this.selectedIconSource is not IconSources.GENERIC)
{
<MudButton Href="@this.selectedIconSource.URL()" Target="_blank" Variant="Variant.Filled" Size="Size.Medium">Open website</MudButton>
}
</MudStack>
<ProviderSelection @bind-ProviderSettings="@this.providerSettings" ValidateProvider="@this.ValidatingProvider"/>
<MudButton Variant="Variant.Filled" Class="mb-3" OnClick="() => this.FindIcon()">
Find icon
</MudButton>
@@ -0,0 +1,100 @@
using AIStudio.Tools;
namespace AIStudio.Assistants.IconFinder;
public partial class AssistantIconFinder : AssistantBaseCore
{
private string inputContext = string.Empty;
private IconSources selectedIconSource;
protected override string Title => "Icon Finder";
protected override string Description =>
"""
Finding the right icon for a context, such as for a piece of text, is not easy. The first challenge:
You need to extract a concept from your context, such as from a text. Let's take an example where
your text contains statements about multiple departments. The sought-after concept could be "departments."
The next challenge is that we need to anticipate the bias of the icon designers: under the search term
"departments," there may be no relevant icons or only unsuitable ones. Depending on the icon source,
it might be more effective to search for "buildings," for instance. LLMs assist you with both steps.
""";
protected override string SystemPrompt =>
"""
I can search for icons using US English keywords. Please help me come up with the right search queries.
I don't want you to translate my requests word-for-word into US English. Instead, you should provide keywords
that are likely to yield suitable icons. For example, I might ask for an icon about departments, but icons
related to the keyword "buildings" might be the best match. Provide your keywords in a Markdown list without
quotation marks.
""";
protected override IReadOnlyList<IButtonData> FooterButtons =>
[
new SendToButton
{
Self = SendTo.ICON_FINDER_ASSISTANT,
},
];
protected override void ResetFrom()
{
this.inputContext = string.Empty;
if (!this.MightPreselectValues())
{
this.selectedIconSource = IconSources.GENERIC;
}
}
protected override bool MightPreselectValues()
{
if (this.SettingsManager.ConfigurationData.IconFinder.PreselectOptions)
{
this.selectedIconSource = this.SettingsManager.ConfigurationData.IconFinder.PreselectedSource;
this.providerSettings = this.SettingsManager.ConfigurationData.Providers.FirstOrDefault(x => x.Id == this.SettingsManager.ConfigurationData.IconFinder.PreselectedProvider);
return true;
}
return false;
}
#region Overrides of ComponentBase
protected override async Task OnInitializedAsync()
{
this.MightPreselectValues();
var deferredContent = MessageBus.INSTANCE.CheckDeferredMessages<string>(Event.SEND_TO_ICON_FINDER_ASSISTANT).FirstOrDefault();
if (deferredContent is not null)
this.inputContext = deferredContent;
await base.OnInitializedAsync();
}
#endregion
private string? ValidatingContext(string context)
{
if(string.IsNullOrWhiteSpace(context))
return "Please provide a context. This will help the AI to find the right icon. You might type just a keyword or copy a sentence from your text, e.g., from a slide where you want to use the icon.";
return null;
}
private async Task FindIcon()
{
await this.form!.Validate();
if (!this.inputIsValid)
return;
this.CreateChatThread();
var time = this.AddUserRequest(
$"""
{this.selectedIconSource.Prompt()} I search for an icon for the following context:
```
{this.inputContext}
```
""");
await this.AddAIResponseAsync(time);
}
}
@@ -0,0 +1,40 @@
namespace AIStudio.Assistants.IconFinder;
public static class IconSourceExtensions
{
public static string Name(this IconSources iconSource) => iconSource switch
{
IconSources.FLAT_ICON => "Flaticon",
IconSources.FONT_AWESOME => "Font Awesome",
IconSources.MATERIAL_ICONS => "Material Icons",
IconSources.FEATHER_ICONS => "Feather Icons",
IconSources.BOOTSTRAP_ICONS => "Bootstrap Icons",
IconSources.ICONS8 => "Icons8",
_ => "Generic",
};
public static string Prompt(this IconSources iconSource) => iconSource switch
{
IconSources.FLAT_ICON => "My icon source is Flaticon.",
IconSources.FONT_AWESOME => "I look for an icon on Font Awesome. Please provide just valid icon names. Valid icon names are using the format `fa-icon-name`.",
IconSources.MATERIAL_ICONS => "I look for a Material icon. Please provide just valid icon names. Valid icon names are using the format `IconName`.",
IconSources.FEATHER_ICONS => "My icon source is Feather Icons. Please provide just valid icon names. Valid icon names usiing the format `icon-name`.",
IconSources.BOOTSTRAP_ICONS => "I look for an icon for Bootstrap. Please provide just valid icon names. Valid icon names are using the format `bi-icon-name`.",
IconSources.ICONS8 => "I look for an icon on Icons8.",
_ => string.Empty,
};
public static string URL(this IconSources iconSource) => iconSource switch
{
IconSources.FLAT_ICON => "https://www.flaticon.com/",
IconSources.FONT_AWESOME => "https://fontawesome.com/",
IconSources.MATERIAL_ICONS => "https://material.io/resources/icons/",
IconSources.FEATHER_ICONS => "https://feathericons.com/",
IconSources.BOOTSTRAP_ICONS => "https://icons.getbootstrap.com/",
IconSources.ICONS8 => "https://icons8.com/",
_ => string.Empty,
};
}
@@ -0,0 +1,13 @@
namespace AIStudio.Assistants.IconFinder;
public enum IconSources
{
GENERIC,
ICONS8,
FLAT_ICON,
FONT_AWESOME,
MATERIAL_ICONS,
FEATHER_ICONS,
BOOTSTRAP_ICONS,
}
@@ -0,0 +1,11 @@
@attribute [Route(Routes.ASSISTANT_REWRITE)]
@inherits AssistantBaseCore
<MudTextField T="string" @bind-Text="@this.inputText" Validation="@this.ValidateText" AdornmentIcon="@Icons.Material.Filled.DocumentScanner" Adornment="Adornment.Start" Label="Your input to improve" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<EnumSelection T="CommonLanguages" NameFunc="@(language => language.NameSelectingOptional())" @bind-Value="@this.selectedTargetLanguage" Icon="@Icons.Material.Filled.Translate" Label="Language" AllowOther="@true" OtherValue="CommonLanguages.OTHER" @bind-OtherInput="@this.customTargetLanguage" ValidateOther="@this.ValidateCustomLanguage" LabelOther="Custom language" />
<EnumSelection T="WritingStyles" NameFunc="@(style => style.Name())" @bind-Value="@this.selectedWritingStyle" Icon="@Icons.Material.Filled.Edit" Label="Writing style" AllowOther="@false" />
<ProviderSelection @bind-ProviderSettings="@this.providerSettings" ValidateProvider="@this.ValidatingProvider"/>
<MudButton Variant="Variant.Filled" Class="mb-3" OnClick="() => this.RewriteText()">
Improve
</MudButton>
@@ -0,0 +1,136 @@
using AIStudio.Chat;
using AIStudio.Tools;
namespace AIStudio.Assistants.RewriteImprove;
public partial class AssistantRewriteImprove : AssistantBaseCore
{
protected override string Title => "Rewrite & Improve Text";
protected override string Description =>
"""
Rewrite and improve your text. Please note, that the capabilities of the different LLM providers will vary.
""";
protected override string SystemPrompt =>
$"""
You are an expert in language and style. You receive a text as input. First, you review the text. If no
changes are needed, you return the text without modifications. If a change is necessary, you improve the
text. You can also correct spelling and grammar issues. You never add additional information. You never
ask the user for additional information. Your response only contains the improved text. You do not explain
your changes. If no changes are needed, you return the text unchanged.
The style of the text: {this.selectedWritingStyle.Prompt()}. You follow the rules according
to {this.SystemPromptLanguage()} in all your changes.
""";
protected override bool ShowResult => false;
protected override bool ShowDedicatedProgress => true;
protected override IReadOnlyList<IButtonData> FooterButtons =>
[
new ButtonData("Copy result", Icons.Material.Filled.ContentCopy, Color.Default, string.Empty, () => this.CopyToClipboard(this.rewrittenText)),
new SendToButton
{
Self = SendTo.REWRITE_ASSISTANT,
UseResultingContentBlockData = false,
GetText = () => string.IsNullOrWhiteSpace(this.rewrittenText) ? this.inputText : this.rewrittenText,
},
];
protected override ChatThread ConvertToChatThread => (this.chatThread ?? new()) with
{
SystemPrompt = SystemPrompts.DEFAULT,
};
protected override void ResetFrom()
{
this.inputText = string.Empty;
this.rewrittenText = string.Empty;
if (!this.MightPreselectValues())
{
this.selectedTargetLanguage = CommonLanguages.AS_IS;
this.customTargetLanguage = string.Empty;
this.selectedWritingStyle = WritingStyles.NOT_SPECIFIED;
}
}
protected override bool MightPreselectValues()
{
if (this.SettingsManager.ConfigurationData.RewriteImprove.PreselectOptions)
{
this.selectedTargetLanguage = this.SettingsManager.ConfigurationData.RewriteImprove.PreselectedTargetLanguage;
this.customTargetLanguage = this.SettingsManager.ConfigurationData.RewriteImprove.PreselectedOtherLanguage;
this.providerSettings = this.SettingsManager.ConfigurationData.Providers.FirstOrDefault(x => x.Id == this.SettingsManager.ConfigurationData.RewriteImprove.PreselectedProvider);
this.selectedWritingStyle = this.SettingsManager.ConfigurationData.RewriteImprove.PreselectedWritingStyle;
return true;
}
return false;
}
#region Overrides of ComponentBase
protected override async Task OnInitializedAsync()
{
this.MightPreselectValues();
var deferredContent = MessageBus.INSTANCE.CheckDeferredMessages<string>(Event.SEND_TO_REWRITE_ASSISTANT).FirstOrDefault();
if (deferredContent is not null)
this.inputText = deferredContent;
await base.OnInitializedAsync();
}
#endregion
private string inputText = string.Empty;
private CommonLanguages selectedTargetLanguage;
private string customTargetLanguage = string.Empty;
private string rewrittenText = string.Empty;
private WritingStyles selectedWritingStyle;
private string? ValidateText(string text)
{
if(string.IsNullOrWhiteSpace(text))
return "Please provide a text as input. You might copy the desired text from a document or a website.";
return null;
}
private string? ValidateCustomLanguage(string language)
{
if(this.selectedTargetLanguage == CommonLanguages.OTHER && string.IsNullOrWhiteSpace(language))
return "Please provide a custom language.";
return null;
}
private string SystemPromptLanguage()
{
var lang = this.selectedTargetLanguage switch
{
CommonLanguages.AS_IS => "the source language",
CommonLanguages.OTHER => this.customTargetLanguage,
_ => $"{this.selectedTargetLanguage.Name()}",
};
if (string.IsNullOrWhiteSpace(lang))
return "the source language";
return lang;
}
private async Task RewriteText()
{
await this.form!.Validate();
if (!this.inputIsValid)
return;
this.CreateChatThread();
var time = this.AddUserRequest(this.inputText);
this.rewrittenText = await this.AddAIResponseAsync(time);
await this.JsRuntime.GenerateAndShowDiff(this.inputText, this.rewrittenText);
}
}
@@ -0,0 +1,16 @@
namespace AIStudio.Assistants.RewriteImprove;
public enum WritingStyles
{
NOT_SPECIFIED = 0,
EVERYDAY,
BUSINESS,
SCIENTIFIC,
JOURNALISTIC,
LITERARY,
TECHNICAL,
MARKETING,
ACADEMIC,
LEGAL,
}
@@ -0,0 +1,40 @@
namespace AIStudio.Assistants.RewriteImprove;
public static class WritingStylesExtensions
{
public static string Name(this WritingStyles style)
{
return style switch
{
WritingStyles.EVERYDAY => "Everyday (personal texts, social media)",
WritingStyles.BUSINESS => "Business (business emails, reports, presentations)",
WritingStyles.SCIENTIFIC => "Scientific (scientific papers, research reports)",
WritingStyles.JOURNALISTIC => "Journalistic (magazines, newspapers, news)",
WritingStyles.LITERARY => "Literary (fiction, poetry)",
WritingStyles.TECHNICAL => "Technical (manuals, documentation)",
WritingStyles.MARKETING => "Marketing (advertisements, sales texts)",
WritingStyles.ACADEMIC => "Academic (essays, seminar papers)",
WritingStyles.LEGAL => "Legal (legal texts, contracts)",
_ => "Not specified",
};
}
public static string Prompt(this WritingStyles style)
{
return style switch
{
WritingStyles.EVERYDAY => "Use a everyday style like for personal texts, social media, and informal communication.",
WritingStyles.BUSINESS => "Use a business style like for business emails, reports, and presentations. Most important is clarity and professionalism.",
WritingStyles.SCIENTIFIC => "Use a scientific style like for scientific papers, research reports, and academic writing. Most important is precision and objectivity.",
WritingStyles.JOURNALISTIC => "Use a journalistic style like for magazines, newspapers, and news. Most important is readability and engaging content.",
WritingStyles.LITERARY => "Use a literary style like for fiction, poetry, and creative writing. Most important is creativity and emotional impact.",
WritingStyles.TECHNICAL => "Use a technical style like for manuals, documentation, and technical writing. Most important is clarity and precision.",
WritingStyles.MARKETING => "Use a marketing style like for advertisements, sales texts, and promotional content. Most important is persuasiveness and engagement.",
WritingStyles.ACADEMIC => "Use a academic style like for essays, seminar papers, and academic writing. Most important is clarity and objectivity.",
WritingStyles.LEGAL => "Use a legal style like for legal texts, contracts, and official documents. Most important is precision and legal correctness. Use formal legal language.",
_ => "Keep the style of the text as it is.",
};
}
}
@@ -0,0 +1,16 @@
@attribute [Route(Routes.ASSISTANT_SUMMARIZER)]
@inherits AssistantBaseCore
@if (!this.SettingsManager.ConfigurationData.TextSummarizer.HideWebContentReader)
{
<ReadWebContent @bind-Content="@this.inputText" ProviderSettings="@this.providerSettings" @bind-AgentIsRunning="@this.isAgentRunning" Preselect="@(this.SettingsManager.ConfigurationData.TextSummarizer.PreselectOptions && this.SettingsManager.ConfigurationData.TextSummarizer.PreselectWebContentReader)" PreselectContentCleanerAgent="@(this.SettingsManager.ConfigurationData.TextSummarizer.PreselectOptions && this.SettingsManager.ConfigurationData.TextSummarizer.PreselectContentCleanerAgent)"/>
}
<MudTextField T="string" Disabled="@this.isAgentRunning" @bind-Text="@this.inputText" Validation="@this.ValidatingText" AdornmentIcon="@Icons.Material.Filled.DocumentScanner" Adornment="Adornment.Start" Label="Your input" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<EnumSelection T="CommonLanguages" NameFunc="@(language => language.Name())" @bind-Value="@this.selectedTargetLanguage" Icon="@Icons.Material.Filled.Translate" Label="Target language" AllowOther="@true" @bind-OtherInput="@this.customTargetLanguage" OtherValue="CommonLanguages.OTHER" LabelOther="Custom target language" ValidateOther="@this.ValidateCustomLanguage" />
<EnumSelection T="Complexity" NameFunc="@(complexity => complexity.Name())" @bind-Value="@this.selectedComplexity" Icon="@Icons.Material.Filled.Layers" Label="Target complexity" AllowOther="@true" @bind-OtherInput="@this.expertInField" OtherValue="Complexity.SCIENTIFIC_LANGUAGE_OTHER_EXPERTS" LabelOther="Your expertise" ValidateOther="@this.ValidateExpertInField" />
<ProviderSelection @bind-ProviderSettings="@this.providerSettings" ValidateProvider="@this.ValidatingProvider"/>
<MudButton Variant="Variant.Filled" Class="mb-3" OnClick="() => this.SummarizeText()" Disabled="@this.isAgentRunning">
Summarize
</MudButton>
@@ -0,0 +1,133 @@
using AIStudio.Chat;
using AIStudio.Tools;
namespace AIStudio.Assistants.TextSummarizer;
public partial class AssistantTextSummarizer : AssistantBaseCore
{
protected override string Title => "Text Summarizer";
protected override string Description =>
"""
Summarize long text into a shorter version while retaining the main points.
You might want to change the language of the summary to make it more readable.
It is also possible to change the complexity of the summary to make it
easy to understand.
""";
protected override string SystemPrompt =>
"""
You get a long text as input. The user wants to get a summary of the text.
The user might want to change the language of the summary. In this case,
you should provide a summary in the requested language. Eventually, the user
want to change the complexity of the text. In this case, you should provide
a summary with the requested complexity. In any case, do not add any information.
""";
protected override IReadOnlyList<IButtonData> FooterButtons =>
[
new SendToButton
{
Self = SendTo.TEXT_SUMMARIZER_ASSISTANT,
},
];
protected override ChatThread ConvertToChatThread => (this.chatThread ?? new()) with
{
SystemPrompt = SystemPrompts.DEFAULT,
};
protected override void ResetFrom()
{
this.inputText = string.Empty;
if(!this.MightPreselectValues())
{
this.selectedTargetLanguage = CommonLanguages.AS_IS;
this.customTargetLanguage = string.Empty;
this.selectedComplexity = Complexity.NO_CHANGE;
this.expertInField = string.Empty;
}
}
protected override bool MightPreselectValues()
{
if (this.SettingsManager.ConfigurationData.TextSummarizer.PreselectOptions)
{
this.selectedTargetLanguage = this.SettingsManager.ConfigurationData.TextSummarizer.PreselectedTargetLanguage;
this.customTargetLanguage = this.SettingsManager.ConfigurationData.TextSummarizer.PreselectedOtherLanguage;
this.selectedComplexity = this.SettingsManager.ConfigurationData.TextSummarizer.PreselectedComplexity;
this.expertInField = this.SettingsManager.ConfigurationData.TextSummarizer.PreselectedExpertInField;
this.providerSettings = this.SettingsManager.ConfigurationData.Providers.FirstOrDefault(x => x.Id == this.SettingsManager.ConfigurationData.TextSummarizer.PreselectedProvider);
return true;
}
return false;
}
private string inputText = string.Empty;
private bool isAgentRunning;
private CommonLanguages selectedTargetLanguage;
private string customTargetLanguage = string.Empty;
private Complexity selectedComplexity;
private string expertInField = string.Empty;
#region Overrides of ComponentBase
protected override async Task OnInitializedAsync()
{
this.MightPreselectValues();
var deferredContent = MessageBus.INSTANCE.CheckDeferredMessages<string>(Event.SEND_TO_TEXT_SUMMARIZER_ASSISTANT).FirstOrDefault();
if (deferredContent is not null)
this.inputText = deferredContent;
await base.OnInitializedAsync();
}
#endregion
private string? ValidatingText(string text)
{
if(string.IsNullOrWhiteSpace(text))
return "Please provide a text as input. You might copy the desired text from a document or a website.";
return null;
}
private string? ValidateCustomLanguage(string language)
{
if(this.selectedTargetLanguage == CommonLanguages.OTHER && string.IsNullOrWhiteSpace(language))
return "Please provide a custom language.";
return null;
}
private string? ValidateExpertInField(string field)
{
if(this.selectedComplexity == Complexity.SCIENTIFIC_LANGUAGE_OTHER_EXPERTS && string.IsNullOrWhiteSpace(field))
return "Please provide your field of expertise.";
return null;
}
private async Task SummarizeText()
{
await this.form!.Validate();
if (!this.inputIsValid)
return;
this.CreateChatThread();
var time = this.AddUserRequest(
$"""
{this.selectedTargetLanguage.PromptSummarizing(this.customTargetLanguage)}
{this.selectedComplexity.Prompt(this.expertInField)}
Please summarize the following text:
```
{this.inputText}
```
""");
await this.AddAIResponseAsync(time);
}
}
@@ -0,0 +1,13 @@
namespace AIStudio.Assistants.TextSummarizer;
public enum Complexity
{
NO_CHANGE,
SIMPLE_LANGUAGE,
TEEN_LANGUAGE,
EVERYDAY_LANGUAGE,
POPULAR_SCIENCE_LANGUAGE,
SCIENTIFIC_LANGUAGE_FIELD_EXPERTS,
SCIENTIFIC_LANGUAGE_OTHER_EXPERTS,
}
@@ -0,0 +1,32 @@
namespace AIStudio.Assistants.TextSummarizer;
public static class ComplexityExtensions
{
public static string Name(this Complexity complexity) => complexity switch
{
Complexity.NO_CHANGE => "No change in complexity",
Complexity.SIMPLE_LANGUAGE => "Simple language, e.g., for children",
Complexity.TEEN_LANGUAGE => "Teen language, e.g., for teenagers",
Complexity.EVERYDAY_LANGUAGE => "Everyday language, e.g., for adults",
Complexity.POPULAR_SCIENCE_LANGUAGE => "Popular science language, e.g., for people interested in science",
Complexity.SCIENTIFIC_LANGUAGE_FIELD_EXPERTS => "Scientific language for experts in this field",
Complexity.SCIENTIFIC_LANGUAGE_OTHER_EXPERTS => "Scientific language for experts from other fields (interdisciplinary)",
_ => "No change in complexity",
};
public static string Prompt(this Complexity complexity, string expertInField) => complexity switch
{
Complexity.NO_CHANGE => "Do not change the complexity of the text.",
Complexity.SIMPLE_LANGUAGE => "Simplify the language, e.g., for 8 to 12-year-old children. Might use short sentences and simple words. You could use analogies to explain complex terms.",
Complexity.TEEN_LANGUAGE => "Use a language suitable for teenagers, e.g., 16 to 19 years old. Might use teenage slang and analogies to explain complex terms.",
Complexity.EVERYDAY_LANGUAGE => "Use everyday language suitable for adults. Avoid specific scientific terms. Use everday analogies to explain complex terms.",
Complexity.POPULAR_SCIENCE_LANGUAGE => "Use popular science language, e.g., for people interested in science. The text should be easy to understand, though. Use analogies to explain complex terms.",
Complexity.SCIENTIFIC_LANGUAGE_FIELD_EXPERTS => "Use scientific language for experts in the field of the texts subject. Use specific terms for this field.",
Complexity.SCIENTIFIC_LANGUAGE_OTHER_EXPERTS => $"The reader is an expert in {expertInField}. Change the language so that it is suitable. Explain specific terms, so that the reader within his field can understand the text. You might use analogies to explain complex terms.",
_ => "Do not change the complexity of the text.",
};
}
@@ -0,0 +1,24 @@
@attribute [Route(Routes.ASSISTANT_TRANSLATION)]
@inherits AssistantBaseCore
@if (!this.SettingsManager.ConfigurationData.Translation.HideWebContentReader)
{
<ReadWebContent @bind-Content="@this.inputText" ProviderSettings="@this.providerSettings" @bind-AgentIsRunning="@this.isAgentRunning" Preselect="@(this.SettingsManager.ConfigurationData.Translation.PreselectOptions && this.SettingsManager.ConfigurationData.Translation.PreselectWebContentReader)" PreselectContentCleanerAgent="@(this.SettingsManager.ConfigurationData.Translation.PreselectOptions && this.SettingsManager.ConfigurationData.Translation.PreselectContentCleanerAgent)"/>
}
<MudTextSwitch Label="Live translation" @bind-Value="@this.liveTranslation" LabelOn="Live translation" LabelOff="No live translation"/>
@if (this.liveTranslation)
{
<MudTextField T="string" Disabled="@this.isAgentRunning" @bind-Text="@this.inputText" Validation="@this.ValidatingText" AdornmentIcon="@Icons.Material.Filled.DocumentScanner" Adornment="Adornment.Start" Label="Your input" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" Immediate="@true" DebounceInterval="@this.SettingsManager.ConfigurationData.Translation.DebounceIntervalMilliseconds" OnDebounceIntervalElapsed="() => this.TranslateText(force: false)" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
}
else
{
<MudTextField T="string" Disabled="@this.isAgentRunning" @bind-Text="@this.inputText" Validation="@this.ValidatingText" AdornmentIcon="@Icons.Material.Filled.DocumentScanner" Adornment="Adornment.Start" Label="Your input" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
}
<EnumSelection T="CommonLanguages" NameFunc="@(language => language.NameSelecting())" @bind-Value="@this.selectedTargetLanguage" ValidateSelection="@this.ValidatingTargetLanguage" Icon="@Icons.Material.Filled.Translate" Label="Target language" AllowOther="@true" OtherValue="CommonLanguages.OTHER" @bind-OtherInput="@this.customTargetLanguage" ValidateOther="@this.ValidateCustomLanguage" LabelOther="Custom target language" />
<ProviderSelection @bind-ProviderSettings="@this.providerSettings" ValidateProvider="@this.ValidatingProvider"/>
<MudButton Disabled="@this.isAgentRunning" Variant="Variant.Filled" Class="mb-3" OnClick="() => this.TranslateText(force: true)">
Translate
</MudButton>
@@ -0,0 +1,130 @@
using AIStudio.Chat;
using AIStudio.Tools;
namespace AIStudio.Assistants.Translation;
public partial class AssistantTranslation : AssistantBaseCore
{
protected override string Title => "Translation";
protected override string Description =>
"""
Translate text from one language to another.
""";
protected override string SystemPrompt =>
"""
You get text in a source language as input. The user wants to get the text translated into a target language.
Provide the translation in the requested language. Do not add any information. Correct any spelling or grammar mistakes.
Do not ask for additional information. Do not mirror the user's language. Do not mirror the task. When the target
language requires, e.g., shorter sentences, you should split the text into shorter sentences.
""";
protected override IReadOnlyList<IButtonData> FooterButtons =>
[
new SendToButton
{
Self = SendTo.TRANSLATION_ASSISTANT,
},
];
protected override ChatThread ConvertToChatThread => (this.chatThread ?? new()) with
{
SystemPrompt = SystemPrompts.DEFAULT,
};
protected override void ResetFrom()
{
this.inputText = string.Empty;
this.inputTextLastTranslation = string.Empty;
if (!this.MightPreselectValues())
{
this.liveTranslation = false;
this.selectedTargetLanguage = CommonLanguages.AS_IS;
this.customTargetLanguage = string.Empty;
}
}
protected override bool MightPreselectValues()
{
if (this.SettingsManager.ConfigurationData.Translation.PreselectOptions)
{
this.liveTranslation = this.SettingsManager.ConfigurationData.Translation.PreselectLiveTranslation;
this.selectedTargetLanguage = this.SettingsManager.ConfigurationData.Translation.PreselectedTargetLanguage;
this.customTargetLanguage = this.SettingsManager.ConfigurationData.Translation.PreselectOtherLanguage;
this.providerSettings = this.SettingsManager.ConfigurationData.Providers.FirstOrDefault(x => x.Id == this.SettingsManager.ConfigurationData.Translation.PreselectedProvider);
return true;
}
return false;
}
private bool liveTranslation;
private bool isAgentRunning;
private string inputText = string.Empty;
private string inputTextLastTranslation = string.Empty;
private CommonLanguages selectedTargetLanguage;
private string customTargetLanguage = string.Empty;
#region Overrides of ComponentBase
protected override async Task OnInitializedAsync()
{
this.MightPreselectValues();
var deferredContent = MessageBus.INSTANCE.CheckDeferredMessages<string>(Event.SEND_TO_TRANSLATION_ASSISTANT).FirstOrDefault();
if (deferredContent is not null)
this.inputText = deferredContent;
await base.OnInitializedAsync();
}
#endregion
private string? ValidatingText(string text)
{
if(string.IsNullOrWhiteSpace(text))
return "Please provide a text as input. You might copy the desired text from a document or a website.";
return null;
}
private string? ValidatingTargetLanguage(CommonLanguages language)
{
if(language == CommonLanguages.AS_IS)
return "Please select a target language.";
return null;
}
private string? ValidateCustomLanguage(string language)
{
if(this.selectedTargetLanguage == CommonLanguages.OTHER && string.IsNullOrWhiteSpace(language))
return "Please provide a custom language.";
return null;
}
private async Task TranslateText(bool force)
{
await this.form!.Validate();
if (!this.inputIsValid)
return;
if(!force && this.inputText == this.inputTextLastTranslation)
return;
this.inputTextLastTranslation = this.inputText;
this.CreateChatThread();
var time = this.AddUserRequest(
$"""
{this.selectedTargetLanguage.PromptTranslation(this.customTargetLanguage)}
The given text is:
---
{this.inputText}
""");
await this.AddAIResponseAsync(time);
}
}
@@ -0,0 +1,4 @@
@using AIStudio
@using AIStudio.Tools
@using AIStudio.Components
@using MudBlazor