Skip to content

Commit

Permalink
Added planner APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
FilippoAdami committed Apr 29, 2024
1 parent b88805b commit 246280d
Show file tree
Hide file tree
Showing 38 changed files with 1,269 additions and 132 deletions.
103 changes: 103 additions & 0 deletions Controllers/AbstractNode.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// Import necessary namespaces from the ASP.NET Core framework
using Microsoft.AspNetCore.Mvc;
using Microsoft.SemanticKernel;
using Newtonsoft.Json;

// Declare the namespace for the AbstractNodeController
namespace SK_API.Controllers{
[ApiController]
[Route("[controller]")]
public partial class AbstractNodeController : ControllerBase
{
private readonly ILogger<AbstractNodeController> _logger;
private readonly IConfiguration _configuration;
private readonly Auth _auth;

public AbstractNodeController(ILogger<AbstractNodeController> logger, IConfiguration configuration, Auth auth)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_auth = auth;
}

// Define your Lesson POST action method here
[HttpPost("abstractnode")]
public async Task<IActionResult> LessonPlannerInputAsync([FromHeader(Name = "ApiKey")] string token, [FromHeader(Name = "SetupModel")] string setupModel, [FromBody] AbstractNodeRequestModel input){
string output = "";
try{
// Authentication with the token
if (token == null)
{
return Unauthorized("API token is required");
}
else if (!_auth.Authenticate(token)){
return BadRequest("API token is required");
}
else{
Console.WriteLine("Authenticated successfully");
}

// Validate the setup model
var LLMsetupModel = JsonConvert.DeserializeObject<LLM_SetupModel>(setupModel);
LLM_SetupModel LLM = LLMsetupModel ?? throw new ArgumentNullException(nameof(setupModel));
IKernel kernel = LLM.Validate();

// Generate the output
string prompt = PlanningPrompts.AbstractNodePrompt;
var generate = kernel.CreateSemanticFunction(prompt, "abstractPlanner" ,"AbstractPlanner", "generates a tailored lesson plan", null, input.Temperature);
var context = kernel.CreateNewContext();
context["language"] = input.Language;
context["level"] = input.Level.ToString();
context["macro_subject"] = input.MacroSubject;
context["title"] = input.Title;
context["correction"] = input.Correction;

context["format"] = FormatStrings.LessonPlanFormat;
context["activities"] = UtilsStrings.ActivitiesListB;
context["examples"] = ExamplesStrings.CustomPlanExamples;

var result = await generate.InvokeAsync(context);
output = result.ToString();
if (output.StartsWith("```json")){
output = output[7..];
if (output.EndsWith("```")){
output = output[..^3];
}
output = output.TrimStart('\n').TrimEnd('\n');
output = output.TrimStart(' ').TrimEnd(' ');
}
Console.WriteLine("Result: "+ output);
LessonPlan lessonPlan = new(output);
foreach (var node in lessonPlan.Nodes){
if(node.Type){
//map the value into TypeOfExercise enum
int exercise = (int)Enum.Parse<TypeOfExercise>(node.Details);
node.Details = exercise.ToString();
}
}
string json = lessonPlan.ToJson();

if (input.Language.ToLower() != "english"){
var InternalFunctions = new InternalFunctions();
var translation = await InternalFunctions.Translate(kernel, json, input.Language);
json = translation;
}
if (json.StartsWith("```json")){
json = json[7..];
if (json.EndsWith("```")){
json = json[..^3];
}
// remove all nelines and tabulation
json = json.Replace("\n", "").Replace("\t", "").Trim();
}
return Ok(json.ToString());
}
// Handle exceptions if something goes wrong during the material generation
catch (Exception ex){
_logger.LogError(ex, "Error during abstract node generation");
return StatusCode(500, "Internal Server Error. \n" + output);
}
}

}
}
88 changes: 88 additions & 0 deletions Controllers/CoursePlanner.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Import necessary namespaces from the ASP.NET Core framework
using Microsoft.AspNetCore.Mvc;
using Microsoft.SemanticKernel;
using Newtonsoft.Json;

// Declare the namespace for the CoursePlannerController
namespace SK_API.Controllers{
[ApiController]
[Route("[controller]")]
public partial class CoursePlannerController : ControllerBase
{
private readonly ILogger<CoursePlannerController> _logger;
private readonly IConfiguration _configuration;
private readonly Auth _auth;

public CoursePlannerController(ILogger<CoursePlannerController> logger, IConfiguration configuration, Auth auth)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_auth = auth;
}

// Define your Lesson POST action method here
[HttpPost("plancourse")]
public async Task<IActionResult> CoursePlannerInputAsync([FromHeader(Name = "ApiKey")] string token, [FromHeader(Name = "SetupModel")] string setupModel, [FromBody] CoursePlanRequestModel input){
string output = "";
try{
// Authentication with the token
if (token == null)
{
return Unauthorized("API token is required");
}
else if (!_auth.Authenticate(token)){
return BadRequest("API token is required");
}
else{
Console.WriteLine("Authenticated successfully");
}

// Validate the setup model
var LLMsetupModel = JsonConvert.DeserializeObject<LLM_SetupModel>(setupModel);
LLM_SetupModel LLM = LLMsetupModel ?? throw new ArgumentNullException(nameof(setupModel));
IKernel kernel = LLM.Validate();

// Generate the output
string prompt = PlanningPrompts.CoursePlanPrompt;
var generate = kernel.CreateSemanticFunction(prompt, "coursePlanner" ,"CoursePlanner", "generates a course plan about the given topic", null, input.Temperature);
var context = kernel.CreateNewContext();
context["language"] = input.Language;
context["level"] = input.Level.ToString();
context["macro_subject"] = input.MacroSubject;
context["topic"] = input.Topic;
context["number_of_lessons"] = input.NumberOfLessons.ToString();
context["lesson_duration"] = input.LessonDuration.ToString();
context["last_lesson"] = "";
if(input.Title != "" && input.Title != null && input.Title != "null" && input.Title != " " && input.Title.ToLower() != "string")
{
Console.WriteLine("Title: " + input.Title);
string ll = @$"You already taught everything up to '{input.Title}', so you need to continue from there.";
context["last_lesson"] = ll;
}
context["format"] = FormatStrings.CoursePlanFormat;
context["example"] = ExamplesStrings.CoursePlanExamples;

var result = await generate.InvokeAsync(context);
output = result.ToString();
if (output.StartsWith("```json")){
output = output[7..];
if (output.EndsWith("```")){
output = output[..^3];
}
output = output.TrimStart('\n').TrimEnd('\n');
output = output.TrimStart(' ').TrimEnd(' ');
}
Console.WriteLine("Result: "+ output);
CoursePlan coursePlan = new(output);
string json = coursePlan.ToJson();
return Ok(json.ToString());
}
// Handle exceptions if something goes wrong during the material generation
catch (Exception ex){
_logger.LogError(ex, "Error during course plan generation");
return StatusCode(500, "Internal Server Error. \n" + output);
}
}

}
}
7 changes: 4 additions & 3 deletions Controllers/ExercisesCorrector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public ExerciseCorrectorController(ILogger<ExerciseCorrectorController> logger,
// Define your Lesson POST action method here
[HttpPost("exercisecorrector")]
public async Task<IActionResult> LOAnaliserInputAsync([FromHeader(Name = "ApiKey")] string token, [FromHeader(Name = "SetupModel")] string setupModel, [FromBody] CorrectorRequestModel input){
string final = "";
try{
// Authentication with the token
if (token == null)
Expand Down Expand Up @@ -52,15 +53,15 @@ public async Task<IActionResult> LOAnaliserInputAsync([FromHeader(Name = "ApiKey
context["examples"] = ExamplesStrings.ExerciseCorrections;
// Generate the output
var result = await generate.InvokeAsync(context);
string final = result.ToString().Trim();
final = result.ToString().Trim();
Console.WriteLine("Result: " + final);
CorrectedAnswer correctedAnswer = new(final);
return Ok(correctedAnswer.ToJSON());
}
// Handle exceptions if something goes wrong during the text extraction
catch (Exception ex){
_logger.LogError(ex, "Error during learning objective generation");
return StatusCode(500, "Internal Server Error");
_logger.LogError(ex, "Error during exercise correction");
return StatusCode(500, "Internal Server Error\n"+ final);
}
}
}
Expand Down
8 changes: 5 additions & 3 deletions Controllers/ExercisesGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public ExercisesController(ILogger<ExercisesController> logger, IConfiguration c
// Define your Lesson POST action method here
[HttpPost("GenerateExercise")]
public async Task<IActionResult> ExercisesInputAsync([FromHeader(Name = "ApiKey")] string token, [FromHeader(Name = "SetupModel")] string setupModel, [FromBody] ExercisesInputModel input){
string output = "";
try{
// Authentication with the token
if (token == null)
Expand Down Expand Up @@ -160,15 +161,16 @@ public async Task<IActionResult> ExercisesInputAsync([FromHeader(Name = "ApiKey"
Console.WriteLine(resultString);
// Map the result to the ExercisesOutputModel
ExerciseFinalModel exercise = new(resultString);
if (type_of_exercise == TypeOfExercise.fill_in_the_blanks){
if (type_of_exercise == TypeOfExercise.information_search){
exercise = ExerciseFinalModel.ProcessExercise(exercise);
output = exercise.ToJSON();
}
return Ok(exercise.ToJSON());
return Ok(output);
}
// Handle exceptions if something goes wrong during the exercises generation
catch (Exception ex){
_logger.LogError(ex, "Error during exercises generation");
return StatusCode(500, "Internal Server Error");
return StatusCode(500, "Internal Server Error\n" + output);
}
}
}
Expand Down
6 changes: 4 additions & 2 deletions Controllers/LearningObjectiveAnalyser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public LOAnalyserController(ILogger<LOAnalyserController> logger, IConfiguration
// Define your Lesson POST action method here
[HttpPost("analyselearningobjective")]
public async Task<IActionResult> LOAnaliserInputAsync([FromHeader(Name = "ApiKey")] string token, [FromHeader(Name = "SetupModel")] string setupModel, [FromBody] LOAnalyserRequestModel input){
string output = "";
try{
// Authentication with the token
if (token == null)
Expand Down Expand Up @@ -53,12 +54,13 @@ public async Task<IActionResult> LOAnaliserInputAsync([FromHeader(Name = "ApiKey
var result = await generate.InvokeAsync(context);
Console.WriteLine("Result: " + result.ToString());
LOAnalysis analysis = new(result.ToString());
return Ok(analysis.ToJSON());
output = analysis.ToJSON();
return Ok(output);
}
// Handle exceptions if something goes wrong during the text extraction
catch (Exception ex){
_logger.LogError(ex, "Error during learning objective analysis");
return StatusCode(500, "Internal Server Error");
return StatusCode(500, "Internal Server Error\n"+ output);
}
}
}
Expand Down
6 changes: 4 additions & 2 deletions Controllers/LearningObjectiveGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public LOGeneratorController(ILogger<LOGeneratorController> logger, IConfigurati
// Define your Lesson POST action method here
[HttpPost("generatelearningobjective")]
public async Task<IActionResult> LOAnaliserInputAsync([FromHeader(Name = "ApiKey")] string token, [FromHeader(Name = "SetupModel")] string setupModel, [FromBody] LORM input){
string output = "";
try{
// Authentication with the token
if (token == null)
Expand Down Expand Up @@ -58,12 +59,13 @@ public async Task<IActionResult> LOAnaliserInputAsync([FromHeader(Name = "ApiKey
final = final.Substring(1, final.Length - 2);
Console.WriteLine("Result: " + final);
LOFM learningObjective = new(final);
return Ok(learningObjective.ToJSON());
output = learningObjective.ToJSON();
return Ok(output);
}
// Handle exceptions if something goes wrong during the text extraction
catch (Exception ex){
_logger.LogError(ex, "Error during learning objective generation");
return StatusCode(500, "Internal Server Error");
return StatusCode(500, "Internal Server Error\n" + output);
}
}
}
Expand Down
Empty file.
Loading

0 comments on commit 246280d

Please sign in to comment.