diff --git a/src/Infrastructure/BotSharp.Core/data/agents/01fcc3e5-9af7-49e6-ad7a-a760bd12dc4a/agent.json b/src/Infrastructure/BotSharp.Core/data/agents/01fcc3e5-9af7-49e6-ad7a-a760bd12dc4a/agent.json index cfd0d779..5e4186dc 100644 --- a/src/Infrastructure/BotSharp.Core/data/agents/01fcc3e5-9af7-49e6-ad7a-a760bd12dc4a/agent.json +++ b/src/Infrastructure/BotSharp.Core/data/agents/01fcc3e5-9af7-49e6-ad7a-a760bd12dc4a/agent.json @@ -16,7 +16,7 @@ }, { "type": "planner", - "field": "Two-Stage-Planner" + "field": "SQL-Planner" } ] } \ No newline at end of file diff --git a/src/Plugins/BotSharp.Plugin.Planner/BotSharp.Plugin.Planner.csproj b/src/Plugins/BotSharp.Plugin.Planner/BotSharp.Plugin.Planner.csproj index f80327cc..886964b5 100644 --- a/src/Plugins/BotSharp.Plugin.Planner/BotSharp.Plugin.Planner.csproj +++ b/src/Plugins/BotSharp.Plugin.Planner/BotSharp.Plugin.Planner.csproj @@ -69,6 +69,36 @@ PreserveNewest + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + diff --git a/src/Plugins/BotSharp.Plugin.Planner/Enums/PlannerAgentId.cs b/src/Plugins/BotSharp.Plugin.Planner/Enums/PlannerAgentId.cs index 0776d7f1..ce603861 100644 --- a/src/Plugins/BotSharp.Plugin.Planner/Enums/PlannerAgentId.cs +++ b/src/Plugins/BotSharp.Plugin.Planner/Enums/PlannerAgentId.cs @@ -1,9 +1,8 @@ -using Microsoft.AspNetCore.Http; - namespace BotSharp.Plugin.Planner.Enums; public class PlannerAgentId { public const string TwoStagePlanner = "282a7128-69a1-44b0-878c-a9159b88f3b9"; public const string SequentialPlanner = "3e75e818-a139-48a8-9e22-4662548c13a3"; + public const string SqlPlanner = "da7aad2c-8112-48a2-ab7b-1f87da524741"; } diff --git a/src/Plugins/BotSharp.Plugin.Planner/Functions/SummaryPlanFn.cs b/src/Plugins/BotSharp.Plugin.Planner/Functions/SummaryPlanFn.cs index cfc306f4..b89bcc35 100644 --- a/src/Plugins/BotSharp.Plugin.Planner/Functions/SummaryPlanFn.cs +++ b/src/Plugins/BotSharp.Plugin.Planner/Functions/SummaryPlanFn.cs @@ -68,15 +68,6 @@ public class SummaryPlanFn : IFunctionCallback var summary = await GetAiResponse(plannerAgent); message.Content = summary.Content; - // Emit event if the sql statement is generated by planner - var args = JsonSerializer.Deserialize(message.FunctionArgs); - if (args != null && !args.IsSqlTemplate && args.ContainsSqlStatements) - { - await HookEmitter.Emit(_services, async hook => - await hook.OnSourceCodeGenerated(nameof(TwoStageTaskPlanner), message, "sql") - ); - } - await HookEmitter.Emit(_services, async hook => await hook.OnPlanningCompleted(nameof(TwoStageTaskPlanner), message) ); diff --git a/src/Plugins/BotSharp.Plugin.Planner/PlannerPlugin.cs b/src/Plugins/BotSharp.Plugin.Planner/PlannerPlugin.cs index b139cde2..9ece599f 100644 --- a/src/Plugins/BotSharp.Plugin.Planner/PlannerPlugin.cs +++ b/src/Plugins/BotSharp.Plugin.Planner/PlannerPlugin.cs @@ -1,4 +1,5 @@ using BotSharp.Plugin.Planner.Sequential; +using BotSharp.Plugin.Planner.SqlGeneration; using BotSharp.Plugin.Planner.TwoStaging; namespace BotSharp.Plugin.Planner; @@ -16,13 +17,15 @@ public class PlannerPlugin : IBotSharpPlugin public string[] AgentIds => [ PlannerAgentId.TwoStagePlanner, - PlannerAgentId.SequentialPlanner + PlannerAgentId.SequentialPlanner, + PlannerAgentId.SqlPlanner ]; public void RegisterDI(IServiceCollection services, IConfiguration config) { services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); } diff --git a/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Functions/SqlGenerationFn.cs b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Functions/SqlGenerationFn.cs new file mode 100644 index 00000000..e89f533a --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Functions/SqlGenerationFn.cs @@ -0,0 +1,127 @@ +using BotSharp.Plugin.Planner.TwoStaging; +using BotSharp.Plugin.Planner.TwoStaging.Models; + +namespace BotSharp.Plugin.Planner.Functions; + +public class SqlGenerationFn : IFunctionCallback +{ + public string Name => "sql_generation"; + public string Indication => "Organizing and summarizing the final SQL statements."; + + private readonly IServiceProvider _services; + private readonly ILogger _logger; + + public SqlGenerationFn( + IServiceProvider services, + ILogger logger) + { + _services = services; + _logger = logger; + } + + public async Task Execute(RoleDialogModel message) + { + var fn = _services.GetRequiredService(); + var agentService = _services.GetRequiredService(); + var states = _services.GetRequiredService(); + + states.SetState("max_tokens", "4096"); + var currentAgent = await agentService.LoadAgent(message.CurrentAgentId); + var taskRequirement = states.GetState("requirement_detail"); + + // Get table names + var steps = states.GetState("planning_result").JsonArrayContent(); + var allTables = new List(); + var ddlStatements = string.Empty; + var domainKnowledge = states.GetState("planning_result"); + domainKnowledge += "\r\n" + states.GetState("domain_knowledges"); + var dictionaryItems = states.GetState("dictionary_items"); + var excelImportResult = states.GetState("excel_import_result"); + + foreach (var step in steps) + { + allTables.AddRange(step.Tables); + } + var distinctTables = allTables.Distinct().ToList(); + + var msgCopy = RoleDialogModel.From(message); + msgCopy.FunctionArgs = JsonSerializer.Serialize(new + { + tables = distinctTables, + }); + await fn.InvokeFunction("sql_table_definition", msgCopy); + ddlStatements += "\r\n" + msgCopy.Content; + states.SetState("table_ddls", ddlStatements); + + // Summarize and generate query + var prompt = await GetSummaryPlanPrompt(msgCopy, taskRequirement, domainKnowledge, dictionaryItems, ddlStatements, excelImportResult); + _logger.LogInformation($"Summary plan prompt:\r\n{prompt}"); + + var plannerAgent = new Agent + { + Id = PlannerAgentId.TwoStagePlanner, + Name = Name, + Instruction = prompt, + LlmConfig = currentAgent.LlmConfig + }; + + var summary = await GetAiResponse(plannerAgent); + message.Content = summary.Content; + + /*await HookEmitter.Emit(_services, async hook => + await hook.OnPlanningCompleted(nameof(TwoStageTaskPlanner), message) + );*/ + + return true; + } + + private async Task GetSummaryPlanPrompt(RoleDialogModel message, string taskDescription, string domainKnowledge, string dictionaryItems, string ddlStatement, string excelImportResult) + { + var agentService = _services.GetRequiredService(); + var render = _services.GetRequiredService(); + var knowledgeHooks = _services.GetServices(); + + var agent = await agentService.GetAgent(PlannerAgentId.TwoStagePlanner); + var template = agent.Templates.FirstOrDefault(x => x.Name == "two_stage.summarize")?.Content ?? string.Empty; + + var additionalRequirements = new List(); + await HookEmitter.Emit(_services, async x => + { + var requirement = await x.GetSummaryAdditionalRequirements(nameof(TwoStageTaskPlanner), message); + additionalRequirements.Add(requirement); + }); + + var globalKnowledges = new List(); + foreach (var hook in knowledgeHooks) + { + var k = await hook.GetGlobalKnowledges(message); + globalKnowledges.AddRange(k); + } + + return render.Render(template, new Dictionary + { + { "task_description", taskDescription }, + { "summary_requirements", string.Join("\r\n", additionalRequirements) }, + { "global_knowledges", globalKnowledges }, + { "domain_knowledges", domainKnowledge }, + { "dictionary_items", dictionaryItems }, + { "table_structure", ddlStatement }, + { "excel_import_result", excelImportResult } + }); + } + private async Task GetAiResponse(Agent plannerAgent) + { + var conv = _services.GetRequiredService(); + var wholeDialogs = conv.GetDialogHistory(); + + // Append text + wholeDialogs.Last().Content += "\n\nIf the table structure didn't mention auto incremental, the data field id needs to insert id manually and you need to use max(id).\nFor example, you should use SET @id = select max(id) from table;"; + wholeDialogs.Last().Content += "\n\nTry if you can generate a single query to fulfill the needs."; + + var completion = CompletionProvider.GetChatCompletion(_services, + provider: plannerAgent.LlmConfig.Provider, + model: plannerAgent.LlmConfig.Model); + + return await completion.GetChatCompletions(plannerAgent, wholeDialogs); + } +} diff --git a/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Functions/SqlReviewFn.cs b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Functions/SqlReviewFn.cs new file mode 100644 index 00000000..7c14d5f4 --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Functions/SqlReviewFn.cs @@ -0,0 +1,38 @@ +using BotSharp.Plugin.Planner.SqlGeneration.Models; +using BotSharp.Plugin.Planner.TwoStaging; +using BotSharp.Plugin.Planner.TwoStaging.Models; + +namespace BotSharp.Plugin.Planner.SqlGeneration.Functions; + +public class SqlReviewFn : IFunctionCallback +{ + public string Name => "sql_review"; + public string Indication => "Currently reviewing SQL statement"; + + private readonly IServiceProvider _services; + private readonly ILogger _logger; + + public SqlReviewFn( + IServiceProvider services, + ILogger logger) + { + _services = services; + _logger = logger; + } + + public async Task Execute(RoleDialogModel message) + { + var args = JsonSerializer.Deserialize(message.FunctionArgs); + if (!message.Content.StartsWith("```sql")) + { + message.Content = $"```sql\r\n{args.SqlStatement}\r\n```"; + } + if (args != null && !args.IsSqlTemplate && args.ContainsSqlStatements) + { + await HookEmitter.Emit(_services, async hook => + await hook.OnSourceCodeGenerated(nameof(TwoStageTaskPlanner), message, "sql") + ); + } + return true; + } +} diff --git a/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Models/FirstStagePlan.cs b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Models/FirstStagePlan.cs new file mode 100644 index 00000000..17ca9f0e --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Models/FirstStagePlan.cs @@ -0,0 +1,39 @@ +namespace BotSharp.Plugin.Planner.SqlGeneration.Models; + +public class FirstStagePlan +{ + [JsonPropertyName("task_detail")] + public string Task { get; set; } = ""; + + //[JsonPropertyName("reason")] + //public string Reason { get; set; } = ""; + + [JsonPropertyName("step")] + public int Step { get; set; } = -1; + + [JsonPropertyName("need_breakdown_task")] + public bool NeedAdditionalInformation { get; set; } = false; + + [JsonPropertyName("need_lookup_dictionary")] + public bool NeedLookupDictionary { get; set; } = false; + + [JsonPropertyName("related_tables")] + public string[] Tables { get; set; } = []; + + [JsonPropertyName("has_found_relevant_knowledge")] + public bool HasFoundRelevantKnowledge { get; set; } = false; + + //[JsonPropertyName("related_urls")] + //public string[] Urls { get; set; } = []; + + //[JsonPropertyName("input_args")] + //public JsonDocument[] Parameters { get; set; } = []; + + //[JsonPropertyName("output_results")] + //public string[] Results { get; set; } = []; + + public override string ToString() + { + return $"STEP {Step}: {Task}"; + } +} diff --git a/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Models/PrimaryRequirementRequest.cs b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Models/PrimaryRequirementRequest.cs new file mode 100644 index 00000000..6a15faba --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Models/PrimaryRequirementRequest.cs @@ -0,0 +1,13 @@ +namespace BotSharp.Plugin.Planner.SqlGeneration.Models; + +public class PrimaryRequirementRequest +{ + [JsonPropertyName("requirement_detail")] + public string Requirements { get; set; } = null!; + + [JsonPropertyName("questions")] + public string[] Questions { get; set; } = []; + + [JsonPropertyName("norm_questions")] + public string[] NormQuestions { get; set; } = []; +} diff --git a/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Models/SecondStagePlan.cs b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Models/SecondStagePlan.cs new file mode 100644 index 00000000..49f78f23 --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Models/SecondStagePlan.cs @@ -0,0 +1,19 @@ +namespace BotSharp.Plugin.Planner.SqlGeneration.Models; + +public class SecondStagePlan +{ + [JsonPropertyName("related_tables")] + public string[] Tables { get; set; } = []; + + [JsonPropertyName("need_lookup_dictionary")] + public bool NeedLookupDictionary { get; set; } = false; + + [JsonPropertyName("description")] + public string Description { get; set; } = ""; + + [JsonPropertyName("input_args")] + public JsonDocument[] Parameters { get; set; } = []; + + [JsonPropertyName("output_results")] + public string[] Results { get; set; } = []; +} diff --git a/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Models/SecondaryBreakdownTask.cs b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Models/SecondaryBreakdownTask.cs new file mode 100644 index 00000000..671c6353 --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Models/SecondaryBreakdownTask.cs @@ -0,0 +1,13 @@ +namespace BotSharp.Plugin.Planner.SqlGeneration.Models; + +public class SecondaryBreakdownTask +{ + [JsonPropertyName("task_description")] + public string TaskDescription { get; set; } = null!; + + [JsonPropertyName("solution_search_question")] + public string SolutionQuestion { get; set; } = null!; + + [JsonPropertyName("need_lookup_dictionary")] + public bool NeedLookupDictionary { get; set; } +} diff --git a/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Models/SqlReviewArgs.cs b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Models/SqlReviewArgs.cs new file mode 100644 index 00000000..29ec186f --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/Models/SqlReviewArgs.cs @@ -0,0 +1,13 @@ +namespace BotSharp.Plugin.Planner.SqlGeneration.Models; + +public class SqlReviewArgs +{ + [JsonPropertyName("is_sql_template")] + public bool IsSqlTemplate { get; set; } = false; + + [JsonPropertyName("contains_sql_statements")] + public bool ContainsSqlStatements { get; set; } = false; + + [JsonPropertyName("sql_statement")] + public string SqlStatement { get; set; } = string.Empty; +} diff --git a/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/SqlGenerationPlanner.cs b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/SqlGenerationPlanner.cs new file mode 100644 index 00000000..52571578 --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/SqlGeneration/SqlGenerationPlanner.cs @@ -0,0 +1,107 @@ +namespace BotSharp.Plugin.Planner.SqlGeneration; + +public class SqlGenerationPlanner : ITaskPlanner +{ + private readonly IServiceProvider _services; + private readonly ILogger _logger; + public string Name => "SQL-Planner"; + public int MaxLoopCount => 10; + + public SqlGenerationPlanner(IServiceProvider services, ILogger logger) + { + _services = services; + _logger = logger; + } + + public async Task GetNextInstruction(Agent router, string messageId, List dialogs) + { + var inst = new FunctionCallFromLlm(); + var nextStepPrompt = await GetNextStepPrompt(router); + + // chat completion + var completion = CompletionProvider.GetChatCompletion(_services, + provider: router?.LlmConfig?.Provider, + model: router?.LlmConfig?.Model); + + // text completion + dialogs = new List + { + new RoleDialogModel(AgentRole.User, nextStepPrompt) + { + FunctionName = nameof(SqlGenerationPlanner), + MessageId = messageId + } + }; + var response = await completion.GetChatCompletions(router, dialogs); + inst = response.Content.JsonContent(); + + // Fix LLM malformed response + ReasonerHelper.FixMalformedResponse(_services, inst); + return inst; + } + + public List BeforeHandleContext(FunctionCallFromLlm inst, RoleDialogModel message, List dialogs) + { + var question = inst.Response; + + var taskAgentDialogs = new List + { + new RoleDialogModel(AgentRole.User, question) + { + MessageId = message.MessageId, + } + }; + + return taskAgentDialogs; + } + + public bool AfterHandleContext(List dialogs, List taskAgentDialogs) + { + dialogs.AddRange(taskAgentDialogs.Skip(1)); + + return true; + } + + public async Task AgentExecuting(Agent router, FunctionCallFromLlm inst, RoleDialogModel message, List dialogs) + { + // Set user content as Planner's question + message.FunctionName = inst.Function; + message.FunctionArgs = inst.Arguments == null ? "{}" : JsonSerializer.Serialize(inst.Arguments); + return true; + } + + public async Task AgentExecuted(Agent router, FunctionCallFromLlm inst, RoleDialogModel message, List dialogs) + { + var context = _services.GetRequiredService(); + + if (message.StopCompletion) + { + context.Empty(reason: $"Agent queue is cleared by {nameof(SqlGenerationPlanner)}"); + return false; + } + + if (dialogs.Last().Role == AgentRole.Assistant) + { + context.Empty(); + return false; + } + + var routing = _services.GetRequiredService(); + routing.Context.ResetRecursiveCounter(); + return true; + } + + private async Task GetNextStepPrompt(Agent router) + { + var agentService = _services.GetRequiredService(); + var planner = await agentService.LoadAgent(PlannerAgentId.TwoStagePlanner); + var template = planner.Templates.First(x => x.Name == "two_stage.next").Content; + var states = _services.GetRequiredService(); + var render = _services.GetRequiredService(); + return render.Render(template, new Dictionary + { + { StateConst.EXPECTED_ACTION_AGENT, states.GetState(StateConst.EXPECTED_ACTION_AGENT) }, + { StateConst.EXPECTED_GOAL_AGENT, states.GetState(StateConst.EXPECTED_GOAL_AGENT) } + }); + } +} diff --git a/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/agent.json b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/agent.json new file mode 100644 index 00000000..4d01b4e2 --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/agent.json @@ -0,0 +1,19 @@ +{ + "id": "da7aad2c-8112-48a2-ab7b-1f87da524741", + "name": "SQL-Planner", + "description": "Plan feasible steps for user task related to sql generation, generate sql statement and/or review the sql statement that can be derived from context", + "type": "planning", + "createdDateTime": "2023-08-27T10:39:00Z", + "updatedDateTime": "2023-08-27T14:39:00Z", + "iconUrl": "https://e7.pngegg.com/pngimages/775/350/png-clipart-action-plan-computer-icons-plan-miscellaneous-text-thumbnail.png", + "disabled": false, + "isPublic": true, + "profiles": [ "planning" ], + "mergeUtility": true, + "utilities": [], + "llmConfig": { + "provider": "openai", + "model": "gpt-4o-2024-11-20", + "max_recursion_depth": 10 + } +} \ No newline at end of file diff --git a/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/functions/plan_primary_stage.json b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/functions/plan_primary_stage.json new file mode 100644 index 00000000..5fefe691 --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/functions/plan_primary_stage.json @@ -0,0 +1,47 @@ +{ + "name": "plan_primary_stage", + "description": "Plan the high level steps to finish the task", + "parameters": { + "type": "object", + "properties": { + "requirement_detail": { + "type": "string", + "description": "User requirements related to data tasks in detail, don't miss any information especially for those line items, values and numbers." + }, + "questions": { + "type": "array", + "description": "Break down user data requirements in details and in multiple ways, don't miss any entity type/value. The output format must be string array.", + "items": { + "type": "string", + "description": "Question converted from requirement in different ways to search in the knowledge base, be short and you can refer to the global knowledge.One question should contain only one main topic that with one entity type." + } + }, + "norm_questions": { + "type": "array", + "description": "normalize the generated questions, remove specific entity value. The output format must be string array.", + "items": { + "type": "string", + "description": "Normalized question" + } + }, + "entities": { + "type": "array", + "description": "entities with type and value", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "description": "entity type" + }, + "value": { + "type": "string", + "description": "entity value" + } + } + } + } + }, + "required": [ "requirement_detail", "questions" ] + } +} diff --git a/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/functions/plan_secondary_stage.json b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/functions/plan_secondary_stage.json new file mode 100644 index 00000000..ca6b3d0b --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/functions/plan_secondary_stage.json @@ -0,0 +1,18 @@ +{ + "name": "plan_secondary_stage", + "description": "Based on the primary stage planning, make more detail steps of the second stage if the primary stage needs more information.", + "parameters": { + "type": "object", + "properties": { + "task_description": { + "type": "string", + "description": "task description from primary steps" + }, + "solution_search_question": { + "type": "string", + "description": "Generate question to find the knowledge for text. Be short" + } + }, + "required": [ "task_description", "solution_search_question" ] + } +} \ No newline at end of file diff --git a/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/functions/sql_generation.json b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/functions/sql_generation.json new file mode 100644 index 00000000..98e40785 --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/functions/sql_generation.json @@ -0,0 +1,26 @@ +{ + "name": "sql_generation", + "description": "Based on the planning steps, summarize the planning steps and output final steps.", + "parameters": { + "type": "object", + "properties": { + "is_sql_template": { + "type": "boolean", + "description": "If user request is to generate sql template instead of actual sql statement." + }, + "contains_sql_statements": { + "type": "boolean", + "description": "Set to true if the response contains sql statements." + }, + "related_tables": { + "type": "array", + "description": "table name in planning steps", + "items": { + "type": "string", + "description": "table name" + } + } + }, + "required": [ "related_tables", "is_sql_template", "contains_sql_statements" ] + } +} \ No newline at end of file diff --git a/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/functions/sql_review.json b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/functions/sql_review.json new file mode 100644 index 00000000..ad360e3c --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/functions/sql_review.json @@ -0,0 +1,22 @@ +{ + "name": "sql_review", + "description": "Verify and optimize sql statement", + "parameters": { + "type": "object", + "properties": { + "sql_statement": { + "type": "string", + "description": "sql statement, must including sql identifier that wrapped with ```sql \r\n```" + }, + "is_sql_template": { + "type": "boolean", + "description": "If user request is to generate sql template instead of actual sql statement." + }, + "contains_sql_statements": { + "type": "boolean", + "description": "Set to true if the response contains sql statements." + } + }, + "required": [ "sql_statement", "is_sql_template", "contains_sql_statements" ] + } +} \ No newline at end of file diff --git a/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/instructions/instruction.liquid b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/instructions/instruction.liquid new file mode 100644 index 00000000..52e498e5 --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/instructions/instruction.liquid @@ -0,0 +1,33 @@ +You're a SQL planner and reviewer, your goal is using function sql_generation and sql_review to response. +You are going convert the user requirement into sql statements. +The user is dealing with a complex problem, and you need to break this complex problem into several small tasks to more easily solve the user's needs. +Follow these steps strictly and in order. + +1. If user raised a new task, call plan_primary_stage to generate the primary plan. + If the sql response can be generate directly based on the context, directly go to step 6 to call function sql_review. +2. If need_lookup_dictionary is True, call verify_dictionary_term to verify or get the enum/term/dictionary value. Pull id and name. + * If you no items retured, you can pull 100 records from the table and look for the match. + * If need_lookup_dictionary is False, skip calling verify_dictionary_term. +3. If need_breakdown_task is true, call plan_secondary_stage for the specific primary stage. +4. Repeat step 3 until you processed all the primary steps. +5. Call sql_generation function to generate SQL statements. +6. Call sql_review function to review SQL statements. This is the step you must go through before reply to the user. + + +{% if global_knowledges != empty -%} +===== +Global Knowledge: +Current date time is: {{ "now" | date: "%Y-%m-%d %H:%M" }} +{% for k in global_knowledges %} +{{ k }} +{% endfor %} +===== +{%- endif %} + + +==== IMPORTANT SYSTEM INSTRUCTION ==== +* The verify_dictionary_term function CAN'T generate INSERT SQL Statement. +* The table name must come from the relevant knowledge. has_found_relevant_knowledge must be true. +* Do not introduce your actions or intentions in any way. +* You MUST explicitly call function sql_review even the sql query is provided in previous context. + diff --git a/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/templates/two_stage.1st.plan.liquid b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/templates/two_stage.1st.plan.liquid new file mode 100644 index 00000000..306f4214 --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/templates/two_stage.1st.plan.liquid @@ -0,0 +1,39 @@ +You are a Task Planner. you will breakdown user business requirements into excutable sub-tasks. + +Thinking process: +1. Reference to "Domain Knowledge" if there is relevant knowledge; +2. Breakdown task into subtasks. + - The subtask should contain all needed parameters for subsequent steps. + - If limited information provided and there are furture information needed, or miss relationship between steps, set the need_breakdown_task to true. + - If there is extra knowledge or relationship needed between steps, set the need_breakdown_task to true for both steps. + - If the solution mentioned "related solutions" is needed, set the need_breakdown_task to true. + - You should find the relationships between data structure based on the domain knowledge strictly. If lack of information, set the need_breakdown_task to true. + - If you need to lookup the dictionary to verify or get the enum/term/dictionary value(exclude example data from attachment), set the need_lookup_dictionary to true. + - Don't set need_lookup_dictionary to true for attachment data. + - Seperate the dictionary lookup and need additional information/knowledge into different subtask. +3. Input argument must reference to corresponding variable name that retrieved by previous steps, variable name must start with '@'; +4. Output all the subtasks as much detail as possible in JSON: [{{ response_format }}] +5. You can NOT generate the final query before calling function plan_summary. + +Note: +* If the task includes repeat steps,e.g.same steps for multiple elements, only generate a single detailed solution without repeating steps for each elements. + +{% if global_knowledges != empty -%} +===== +Global Knowledge: +{% for k in global_knowledges %} +{{ k }} +{% endfor %} +{%- endif %} + +{% if domain_knowledges != empty -%} +===== +Domain Knowledge: +{% for k in domain_knowledges %} +{{ k }} +{% endfor %} +{%- endif %} +===== + +Task description: +{{ task_description }} \ No newline at end of file diff --git a/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/templates/two_stage.2nd.plan.liquid b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/templates/two_stage.2nd.plan.liquid new file mode 100644 index 00000000..81e22fe8 --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/templates/two_stage.2nd.plan.liquid @@ -0,0 +1,22 @@ +Reference to "Primary Planning" and the additional knowledge included. Breakdown task into multiple steps. +* The step should contains all needed parameters. +* The parameters can be extracted from the original task. +* You need to list all the steps in detail. Finding relationships should also be a step. +* When generate the steps, you should find the relationships between data structure based on the provided knowledge strictly. +* If need_lookup_dictionary is true, call verify_dictionary_term to verify or get the enum/term/dictionary value. Pull id and name/code. +* Output all the steps as much detail as possible in JSON: [{{ response_format }}] + +Additional Requirements: +* "output_results" is variable name that needed to be used in the next step. + +===== +Sub Task Description: +{{ task_description }} + +===== +Primary Planning: +{{ primary_plan }} + +===== +Additional Knowledge: +{{ additional_knowledge }} \ No newline at end of file diff --git a/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/templates/two_stage.next.liquid b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/templates/two_stage.next.liquid new file mode 100644 index 00000000..f7388be6 --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/templates/two_stage.next.liquid @@ -0,0 +1,12 @@ +What is the next step based on the CONVERSATION? +Route to the last handling agent in priority. +{% if expected_next_action_agent != empty -%} +Expected next action agent is {{ expected_next_action_agent }}. +{%- else -%} +Next action agent is inferred based on user lastest response. +{%- endif %} +{% if expected_user_goal_agent != empty -%} +Expected user goal agent is {{ expected_user_goal_agent }}. +{%- else -%} +User goal agent is inferred based on user initial request. +{%- endif %} diff --git a/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/templates/two_stage.summarize.liquid b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/templates/two_stage.summarize.liquid new file mode 100644 index 00000000..ef0e3ae3 --- /dev/null +++ b/src/Plugins/BotSharp.Plugin.Planner/data/agents/da7aad2c-8112-48a2-ab7b-1f87da524741/templates/two_stage.summarize.liquid @@ -0,0 +1,29 @@ +You are a planning summarizer. You will generate the final output in JSON format based on the task description, knowledge and related table structure and relationship. +Generate a simple business explaination of the quried data for the non tech audience. call sql_review as the final step after generating the sql statement. + +Requirements: +{{ summary_requirements }} + +===== +Task description: +{{ task_description }} + +===== +Global Knowledges: +{{ global_knowledges }} + +===== +Domain Knowledges: +{{ domain_knowledges }} + +===== +Dictionary Items: +{{ dictionary_items }} + +===== +Table Structure: +{{ table_structure }} + +===== +Attached Excel Information: +{{ excel_import_result }} \ No newline at end of file diff --git a/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/6745151e-6d46-4a02-8de4-1c4f21c7da95/functions/util-db-sql_table_definition.json b/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/6745151e-6d46-4a02-8de4-1c4f21c7da95/functions/util-db-sql_table_definition.json index 6e4b946c..0f808afe 100644 --- a/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/6745151e-6d46-4a02-8de4-1c4f21c7da95/functions/util-db-sql_table_definition.json +++ b/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/6745151e-6d46-4a02-8de4-1c4f21c7da95/functions/util-db-sql_table_definition.json @@ -4,15 +4,19 @@ "parameters": { "type": "object", "properties": { - "table": { - "type": "string", - "description": "table name" + "tables": { + "type": "array", + "description": "table name in planning steps", + "items": { + "type": "string", + "description": "table name" + } }, "reason": { "type": "string", "description": "the reason why you need to call sql_table_definition" } }, - "required": [ "table", "reason" ] + "required": [ "tables", "reason" ] } } \ No newline at end of file diff --git a/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/beda4c12-e1ec-4b4b-b328-3df4a6687c4f/agent.json b/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/beda4c12-e1ec-4b4b-b328-3df4a6687c4f/agent.json index 00d1e0b3..9f902a01 100644 --- a/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/beda4c12-e1ec-4b4b-b328-3df4a6687c4f/agent.json +++ b/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/beda4c12-e1ec-4b4b-b328-3df4a6687c4f/agent.json @@ -1,7 +1,7 @@ { "id": "beda4c12-e1ec-4b4b-b328-3df4a6687c4f", "name": "SQL Driver", - "description": "Transfer to this Agent only when executable SQL statements are explicitly provided in the context.", + "description": "Transfer to this Agent when user mentions to execute the sql statement. Only call when executable SQL statements are explicitly provided in the context.", "iconUrl": "https://cdn-icons-png.flaticon.com/512/3161/3161158.png", "type": "task", "createdDateTime": "2023-11-15T13:49:00Z", diff --git a/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/beda4c12-e1ec-4b4b-b328-3df4a6687c4f/functions/sql_table_definition.json b/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/beda4c12-e1ec-4b4b-b328-3df4a6687c4f/functions/sql_table_definition.json index 748202b4..580ee339 100644 --- a/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/beda4c12-e1ec-4b4b-b328-3df4a6687c4f/functions/sql_table_definition.json +++ b/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/beda4c12-e1ec-4b4b-b328-3df4a6687c4f/functions/sql_table_definition.json @@ -4,11 +4,15 @@ "parameters": { "type": "object", "properties": { - "table": { - "type": "string", - "description": "table need to check" + "tables": { + "type": "array", + "description": "table name in planning steps", + "items": { + "type": "string", + "description": "table name" + } } }, - "required": [ "table" ] + "required": [ "tables" ] } } \ No newline at end of file diff --git a/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/beda4c12-e1ec-4b4b-b328-3df4a6687c4f/instructions/instruction.liquid b/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/beda4c12-e1ec-4b4b-b328-3df4a6687c4f/instructions/instruction.liquid index 8daddf49..7cc97bb0 100644 --- a/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/beda4c12-e1ec-4b4b-b328-3df4a6687c4f/instructions/instruction.liquid +++ b/src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/beda4c12-e1ec-4b4b-b328-3df4a6687c4f/instructions/instruction.liquid @@ -1,4 +1,4 @@ -You're a SQL driver who can find the database information or query the data. +You're a SQL driver who can execute the sql statement. Your response must meet below requirements: * You can only execute the SQL from the conversation. You can't generate one by yourself;