Skip to content

Commit 87be5be

Browse files
authored
Merge pull request #670 from Joannall/master
improve data dictionary lookup and plan summary
2 parents 9798426 + 1f88b38 commit 87be5be

File tree

9 files changed

+53
-32
lines changed

9 files changed

+53
-32
lines changed

src/Plugins/BotSharp.Plugin.ExcelHandler/Functions/HandleExcelRequestFn.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ public async Task<bool> Execute(RoleDialogModel message)
5151
var args = JsonSerializer.Deserialize<LlmContextIn>(message.FunctionArgs, _options.JsonSerializerOptions);
5252
var conv = _serviceProvider.GetRequiredService<IConversationService>();
5353

54+
5455
if (_excelMimeTypes.IsNullOrEmpty())
5556
{
5657
_excelMimeTypes = FileUtility.GetMimeFileTypes(new List<string> { "excel", "spreadsheet" }).ToHashSet<string>();
@@ -70,7 +71,10 @@ public async Task<bool> Execute(RoleDialogModel message)
7071
else
7172
{
7273
var resultList = GetResponeFromDialogs(dialogs);
74+
var states = _serviceProvider.GetRequiredService<IConversationStateService>();
75+
7376
message.Content = GenerateSqlExecutionSummary(resultList);
77+
states.SetState("excel_import_result",message.Content);
7478
}
7579
return true;
7680
}

src/Plugins/BotSharp.Plugin.ExcelHandler/Services/MySqlService.cs

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System.Data;
2+
using BotSharp.Abstraction.Routing;
23
using BotSharp.Plugin.ExcelHandler.Helpers.MySql;
34
using BotSharp.Plugin.ExcelHandler.Models;
45
using MySql.Data.MySqlClient;
@@ -9,17 +10,19 @@ namespace BotSharp.Plugin.ExcelHandler.Services
910
public class MySqlService : IMySqlService
1011
{
1112
private readonly IMySqlDbHelper _mySqlDbHelpers;
12-
13+
private readonly IServiceProvider _services;
1314
private double _excelRowSize = 0;
1415
private double _excelColumnSize = 0;
1516
private string _tableName = "tempTable";
17+
private string _database = "";
1618
private string _currentFileName = string.Empty;
1719
private List<string> _headerColumns = new List<string>();
1820
private List<string> _columnTypes = new List<string>();
1921

20-
public MySqlService(IMySqlDbHelper mySqlDbHelpers)
22+
public MySqlService(IMySqlDbHelper mySqlDbHelpers, IServiceProvider services)
2123
{
2224
_mySqlDbHelpers = mySqlDbHelpers;
25+
_services = services;
2326
}
2427

2528
public bool DeleteTableSqlQuery()
@@ -185,10 +188,12 @@ private string ParseSheetData(ISheet singleSheet)
185188
{
186189
try
187190
{
188-
_tableName = $"excel_{sheet.SheetName}";
191+
var routing = _services.GetRequiredService<IRoutingContext>();
192+
_tableName = $"excel_{routing.ConversationId.Split('-').Last()}_{sheet.SheetName}";
189193
_headerColumns = ParseSheetColumn(sheet);
190194
string createTableSql = CreateDBTableSqlString(_tableName, _headerColumns, null ,true);
191195
ExecuteSqlQueryForInsertion(createTableSql);
196+
createTableSql = createTableSql.Replace(_tableName, $"{_database}.{_tableName}");
192197
return (true, createTableSql);
193198
}
194199
catch (Exception ex)
@@ -210,21 +215,26 @@ private List<string> ParseSheetColumn(ISheet sheet)
210215
}
211216
private string CreateDBTableSqlString(string tableName, List<string> headerColumns, List<string>? columnTypes = null, bool isMemory = false)
212217
{
213-
var createTableSql = $"CREATE TABLE if not exists {tableName} ( ";
214-
215218
_columnTypes = columnTypes.IsNullOrEmpty() ? headerColumns.Select(x => "VARCHAR(512)").ToList() : columnTypes;
216219

217-
headerColumns = headerColumns.Select((x, i) => $"`{x}`" + $" {_columnTypes[i]}").ToList();
218-
createTableSql += string.Join(", ", headerColumns);
220+
/*if (!headerColumns.Any(x => x.Equals("id", StringComparison.OrdinalIgnoreCase)))
221+
{
222+
headerColumns.Insert(0, "Id");
223+
_columnTypes?.Insert(0, "INT UNSIGNED AUTO_INCREMENT");
224+
}*/
225+
226+
var createTableSql = $"CREATE TABLE if not exists {tableName} ( \n";
227+
createTableSql += string.Join(", \n", headerColumns.Select((x, i) => $"`{x}` {_columnTypes[i]}"));
228+
var indexSql = string.Join(", \n", headerColumns.Select(x => $"KEY `idx_{tableName}_{x}` (`{x}`)"));
229+
createTableSql += $", \n{indexSql}\n);";
219230

220-
string engine = isMemory ? "ENGINE=MEMORY" : "";
221-
createTableSql += $") {engine};";
222231
return createTableSql;
223232
}
224233

225234
public void ExecuteSqlQueryForInsertion(string sqlQuery)
226235
{
227236
using var connection = _mySqlDbHelpers.GetDbConnection();
237+
_database = connection.Database;
228238
using (MySqlCommand cmd = new MySqlCommand(sqlQuery, connection))
229239
{
230240
cmd.ExecuteNonQuery();

src/Plugins/BotSharp.Plugin.Planner/Functions/SummaryPlanFn.cs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using BotSharp.Abstraction.Planning;
22
using BotSharp.Plugin.Planner.TwoStaging;
33
using BotSharp.Plugin.Planner.TwoStaging.Models;
4+
using Microsoft.EntityFrameworkCore.Metadata.Internal;
45

56
namespace BotSharp.Plugin.Planner.Functions;
67

@@ -36,26 +37,24 @@ public async Task<bool> Execute(RoleDialogModel message)
3637
var ddlStatements = string.Empty;
3738
var relevantKnowledge = states.GetState("planning_result");
3839
var dictionaryItems = states.GetState("dictionary_items");
40+
var excelImportResult = states.GetState("excel_import_result");
3941

4042
foreach (var step in steps)
4143
{
4244
allTables.AddRange(step.Tables);
4345
}
4446
var distinctTables = allTables.Distinct().ToList();
4547

46-
foreach (var table in distinctTables)
48+
var msgCopy = RoleDialogModel.From(message);
49+
msgCopy.FunctionArgs = JsonSerializer.Serialize(new
4750
{
48-
var msgCopy = RoleDialogModel.From(message);
49-
msgCopy.FunctionArgs = JsonSerializer.Serialize(new
50-
{
51-
table = table,
52-
});
53-
await fn.InvokeFunction("sql_table_definition", msgCopy);
54-
ddlStatements += "\r\n" + msgCopy.Content;
55-
}
51+
tables = distinctTables,
52+
});
53+
await fn.InvokeFunction("sql_table_definition", msgCopy);
54+
ddlStatements += "\r\n" + msgCopy.Content;
5655

5756
// Summarize and generate query
58-
var summaryPlanPrompt = await GetSummaryPlanPrompt(taskRequirement, relevantKnowledge, dictionaryItems, ddlStatements);
57+
var summaryPlanPrompt = await GetSummaryPlanPrompt(taskRequirement, relevantKnowledge, dictionaryItems, ddlStatements, excelImportResult);
5958
_logger.LogInformation($"Summary plan prompt:\r\n{summaryPlanPrompt}");
6059

6160
var plannerAgent = new Agent
@@ -75,7 +74,7 @@ await HookEmitter.Emit<IPlanningHook>(_services, x =>
7574
return true;
7675
}
7776

78-
private async Task<string> GetSummaryPlanPrompt(string taskDescription, string relevantKnowledge, string dictionaryItems, string ddlStatement)
77+
private async Task<string> GetSummaryPlanPrompt(string taskDescription, string relevantKnowledge, string dictionaryItems, string ddlStatement, string excelImportResult)
7978
{
8079
var agentService = _services.GetRequiredService<IAgentService>();
8180
var render = _services.GetRequiredService<ITemplateRender>();
@@ -97,6 +96,7 @@ await HookEmitter.Emit<IPlanningHook>(_services, async x =>
9796
{ "relevant_knowledges", relevantKnowledge },
9897
{ "dictionary_items", dictionaryItems },
9998
{ "table_structure", ddlStatement },
99+
{ "excel_import_result",excelImportResult }
100100
});
101101
}
102102
private async Task<RoleDialogModel> GetAiResponse(Agent plannerAgent)

src/Plugins/BotSharp.Plugin.Planner/data/agents/282a7128-69a1-44b0-878c-a9159b88f3b9/functions/plan_primary_stage.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@
1010
},
1111
"questions": {
1212
"type": "array",
13-
"description": "User requirements in detail, don't miss any information especially for those line items, values and numbers.",
13+
"description": "Rephrase user requirements in details and in multiple ways, don't miss any information especially for those line items, values and numbers.",
1414
"items": {
1515
"type": "string",
16-
"description": "Question converted from requirement in different ways to search in the knowledge base, be short and you can refer to the global knowledge."
16+
"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."
1717
}
1818
}
1919
},

src/Plugins/BotSharp.Plugin.Planner/data/agents/282a7128-69a1-44b0-878c-a9159b88f3b9/templates/two_stage.summarize.liquid

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,7 @@ Dictionary Items:
1818
=====
1919
Table Structure:
2020
{{ table_structure }}
21+
22+
=====
23+
Attached Excel Information:
24+
{{ excel_import_result }}

src/Plugins/BotSharp.Plugin.SqlDriver/Functions/GetTableDefinitionFn.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ public GetTableDefinitionFn(
2323
public async Task<bool> Execute(RoleDialogModel message)
2424
{
2525
var args = JsonSerializer.Deserialize<SqlStatement>(message.FunctionArgs);
26-
var tables = new string[] { args.Table };
26+
var tables = args.Tables;
2727
var agentService = _services.GetRequiredService<IAgentService>();
2828
var settings = _services.GetRequiredService<SqlDriverSetting>();
2929

src/Plugins/BotSharp.Plugin.SqlDriver/Models/SqlStatement.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ public class SqlStatement
1010
[JsonPropertyName("reason")]
1111
public string Reason { get; set; } = null!;
1212

13-
[JsonPropertyName("table")]
14-
public string Table { get; set; } = null!;
13+
[JsonPropertyName("tables")]
14+
public string[] Tables { get; set; } = null!;
1515

1616
[JsonPropertyName("parameters")]
1717
public SqlParameter[] Parameters { get; set; } = [];

src/Plugins/BotSharp.Plugin.SqlDriver/data/agents/6745151e-6d46-4a02-8de4-1c4f21c7da95/functions/sql_dictionary_lookup.json

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,14 @@
1212
"type": "string",
1313
"description": "the reason why you need to call sql_dictionary_lookup"
1414
},
15-
"table": {
16-
"type": "string",
17-
"description": "table name"
18-
}
19-
},
20-
"required": [ "sql_statement", "reason", "table" ]
15+
"tables": {
16+
"type": "array",
17+
"description": "all related tables",
18+
"items": {
19+
"type": "string",
20+
"description": "table name"
21+
}
22+
},
23+
"required": [ "sql_statement", "reason", "tables" ]
2124
}
2225
}
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
Output in human readable format.
1+
Output in human readable format. If there is large amount of information, shape it in tabular.

0 commit comments

Comments
 (0)