Skip to content

Commit 81dd5c8

Browse files
committed
Fix SqliteService table creation
1 parent 5a7a6f2 commit 81dd5c8

File tree

12 files changed

+83
-87
lines changed

12 files changed

+83
-87
lines changed

src/Infrastructure/BotSharp.Abstraction/Agents/Models/Agent.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
using BotSharp.Abstraction.Functions.Models;
22
using BotSharp.Abstraction.Plugins.Models;
33
using BotSharp.Abstraction.Tasks.Models;
4+
using System.Diagnostics;
45

56
namespace BotSharp.Abstraction.Agents.Models;
67

8+
[DebuggerStepThrough]
79
public class Agent
810
{
911
public string Id { get; set; } = string.Empty;

src/Infrastructure/BotSharp.Core/Instructs/Services/InstructService.Execute.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,8 @@ private async Task<string> GetChatCompletion(
336336
{
337337
Id = agent.Id,
338338
Name = agent.Name,
339-
Instruction = instruction
339+
Instruction = instruction,
340+
LlmConfig = agent.LlmConfig
340341
}, new List<RoleDialogModel>
341342
{
342343
new RoleDialogModel(AgentRole.User, text)

src/Infrastructure/BotSharp.Core/data/agents/01fcc3e5-0af7-49e6-ad7a-a760bd12dc4d/agent.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"isPublic": true,
1010
"llmConfig": {
1111
"provider": "openai",
12-
"model": "gpt-4o-mini"
12+
"model": "gpt-5-mini"
1313
},
1414
"profiles": [ "fallback" ]
1515
}

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

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -146,26 +146,14 @@ private List<SqlContextOut> GetResponeFromDialogs(List<RoleDialogModel> dialogs)
146146
private string GenerateSqlExecutionSummary(List<SqlContextOut> results)
147147
{
148148
var stringBuilder = new StringBuilder();
149-
if (results.Any(x => x.isSuccessful))
150-
{
151-
stringBuilder.Append("---Success---");
152-
stringBuilder.Append("\r\n");
153-
foreach (var result in results.Where(x => x.isSuccessful))
154-
{
155-
stringBuilder.Append(result.Message);
156-
stringBuilder.Append("\r\n\r\n");
157-
}
158-
}
159-
if (results.Any(x => !x.isSuccessful))
149+
150+
stringBuilder.Append("\r\n");
151+
foreach (var result in results)
160152
{
161-
stringBuilder.Append("---Failed---");
162-
stringBuilder.Append("\r\n");
163-
foreach (var result in results.Where(x => !x.isSuccessful))
164-
{
165-
stringBuilder.Append(result.Message);
166-
stringBuilder.Append("\r\n");
167-
}
153+
stringBuilder.Append(result.Message);
154+
stringBuilder.Append("\r\n\r\n");
168155
}
156+
169157
return stringBuilder.ToString();
170158
}
171159

src/Plugins/BotSharp.Plugin.ExcelHandler/Models/SqlContextOut.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ namespace BotSharp.Plugin.ExcelHandler.Models;
22

33
public class SqlContextOut
44
{
5-
public bool isSuccessful { get; set; }
6-
public string Message { get; set; }
7-
public string FileName { get; set; }
5+
public bool IsSuccessful { get; set; }
6+
public string Message { get; set; } = string.Empty;
87
}

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

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,8 @@ public IEnumerable<SqlContextOut> WriteExcelDataToDB(IWorkbook workbook)
4949
{
5050
results.Add(new SqlContextOut
5151
{
52-
isSuccessful = isCreateSuccess,
53-
Message = message,
54-
FileName = _currentFileName
52+
IsSuccessful = isCreateSuccess,
53+
Message = message
5554
});
5655
continue;
5756
}
@@ -64,9 +63,8 @@ public IEnumerable<SqlContextOut> WriteExcelDataToDB(IWorkbook workbook)
6463

6564
results.Add(new SqlContextOut
6665
{
67-
isSuccessful = isInsertSuccess,
68-
Message = $"{insertMessage}\r\nExample Data: {exampleData}. \r\n The remaining data contains different values. ",
69-
FileName = _currentFileName
66+
IsSuccessful = isInsertSuccess,
67+
Message = $"{insertMessage}\r\nExample Data: {exampleData}. \r\n The remaining data contains different values. "
7068
});
7169
}
7270
return results;

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

Lines changed: 54 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,12 @@ namespace BotSharp.Plugin.ExcelHandler.Services;
66
public class SqliteService : IDbService
77
{
88
private readonly IServiceProvider _services;
9-
private readonly ILogger<SqliteService> _logger;
9+
private readonly ILogger _logger;
1010
private readonly ExcelHandlerSettings _settings;
1111

12-
private string _dbFilePath = string.Empty;
13-
private SqliteConnection _inMemoryDbConnection = null;
1412
private double _excelRowSize = 0;
1513
private double _excelColumnSize = 0;
1614
private string _tableName = "tempTable";
17-
private string _currentFileName = string.Empty;
1815
private List<string> _headerColumns = new List<string>();
1916
private List<string> _columnTypes = new List<string>();
2017

@@ -38,24 +35,23 @@ public IEnumerable<SqlContextOut> WriteExcelDataToDB(IWorkbook workbook)
3835
for (int sheetIdx = 0; sheetIdx < numTables; sheetIdx++)
3936
{
4037
ISheet sheet = workbook.GetSheetAt(sheetIdx);
38+
39+
// create table
4140
var (isCreateSuccess, message) = SqlCreateTableFn(sheet);
4241

43-
if (!isCreateSuccess)
42+
results.Add(new SqlContextOut
4443
{
45-
results.Add(new SqlContextOut
46-
{
47-
isSuccessful = isCreateSuccess,
48-
Message = message,
49-
FileName = _currentFileName
50-
});
51-
continue;
52-
}
44+
IsSuccessful = isCreateSuccess,
45+
Message = message
46+
});
47+
48+
// insert data
5349
var (isInsertSuccess, insertMessage) = SqlInsertDataFn(sheet);
50+
5451
results.Add(new SqlContextOut
5552
{
56-
isSuccessful = isInsertSuccess,
57-
Message = insertMessage,
58-
FileName = _currentFileName
53+
IsSuccessful = isInsertSuccess,
54+
Message = insertMessage
5955
});
6056
}
6157
return results;
@@ -69,13 +65,17 @@ public IEnumerable<SqlContextOut> WriteExcelDataToDB(IWorkbook workbook)
6965
{
7066
string dataSql = ParseSheetData(sheet);
7167
string insertDataSql = ProcessInsertSqlQuery(dataSql);
72-
ExecuteSqlQueryForInsertion(insertDataSql);
68+
var insertedRowCount = ExecuteSqlQueryForInsertion(insertDataSql);
7369

74-
return (true, $"{_currentFileName}: \r\n {_excelRowSize} records have been successfully inserted into `{_tableName}` table");
70+
// List top 3 rows
71+
var top3rows = dataSql.Split("\r").Take(3);
72+
var dataSample = string.Join("\r", dataSql.Split("\r").Take(3)).Trim(',', ' ');
73+
74+
return (true, $"{insertedRowCount} records have been successfully inserted into `{_tableName}` table. Top {top3rows.Count()} rows:\r\n{dataSample}");
7575
}
7676
catch (Exception ex)
7777
{
78-
return (false, $"{_currentFileName}: Failed to parse excel data into `{_tableName}` table. ####Error: {ex.Message}");
78+
return (false, $"Failed to parse excel data into `{_tableName}` table. ####Error: {ex.Message}");
7979
}
8080
}
8181

@@ -86,8 +86,10 @@ public IEnumerable<SqlContextOut> WriteExcelDataToDB(IWorkbook workbook)
8686
_tableName = sheet.SheetName;
8787
_headerColumns = ParseSheetColumn(sheet);
8888
string createTableSql = CreateDBTableSqlString(_tableName, _headerColumns, null);
89-
ExecuteSqlQueryForInsertion(createTableSql);
90-
return (true, $"{_tableName} has been successfully created.");
89+
var rowCount = ExecuteSqlQueryForInsertion(createTableSql);
90+
// Get table schema using sqlite query
91+
var schema = GenerateTableSchema();
92+
return (true, $"Table `{_tableName}` has been successfully created in {Provider}. Table schema:\r\n{schema}");
9193
}
9294
catch (Exception ex)
9395
{
@@ -166,25 +168,19 @@ private string ProcessInsertSqlQuery(string dataSql)
166168
{
167169
var wrapUpCols = _headerColumns.Select(x => $"`{x}`").ToList();
168170
var transferedCols = '(' + string.Join(',', wrapUpCols) + ')';
169-
string insertSqlQuery = $"Insert into {_tableName} {transferedCols} Values {dataSql}";
171+
string insertSqlQuery = $"INSERT INTO {_tableName} {transferedCols} VALUES {dataSql}";
170172
return insertSqlQuery;
171173
}
172174

173-
private void ExecuteSqlQueryForInsertion(string query)
175+
private int ExecuteSqlQueryForInsertion(string query)
174176
{
175-
var physicalDbConnection = GetPhysicalDbConnection();
176-
var inMemoryDbConnection = GetInMemoryDbConnection();
177+
using var conn = GetDbConnection();
177178

178-
physicalDbConnection.BackupDatabase(inMemoryDbConnection, "main", "main");
179-
physicalDbConnection.Close();
179+
using var command = new SqliteCommand();
180+
command.CommandText = query;
181+
command.Connection = conn;
180182

181-
using (var command = new SqliteCommand())
182-
{
183-
command.CommandText = query;
184-
command.Connection = inMemoryDbConnection;
185-
command.ExecuteNonQuery();
186-
}
187-
inMemoryDbConnection.BackupDatabase(physicalDbConnection);
183+
return command.ExecuteNonQuery();
188184
}
189185

190186
private void DeleteTableSqlQuery()
@@ -198,8 +194,8 @@ private void DeleteTableSqlQuery()
198194
type = 'table' AND
199195
name NOT LIKE 'sqlite_%'
200196
";
201-
var physicalDbConnection = GetPhysicalDbConnection();
202-
using var selectCmd = new SqliteCommand(deleteTableSql, physicalDbConnection);
197+
using var conn = GetDbConnection();
198+
using var selectCmd = new SqliteCommand(deleteTableSql, conn);
203199
using var reader = selectCmd.ExecuteReader();
204200
if (reader.HasRows)
205201
{
@@ -212,11 +208,11 @@ name NOT LIKE 'sqlite_%'
212208
}
213209
dropTableQueries.ForEach(query =>
214210
{
215-
using var dropTableCommand = new SqliteCommand(query, physicalDbConnection);
211+
using var dropTableCommand = new SqliteCommand(query, conn);
216212
dropTableCommand.ExecuteNonQuery();
217213
});
218214
}
219-
physicalDbConnection.Close();
215+
conn.Close();
220216
}
221217

222218
private string GenerateTableSchema()
@@ -237,26 +233,30 @@ private string GenerateTableSchema()
237233
#endregion
238234

239235
#region Db connection
240-
private SqliteConnection GetInMemoryDbConnection()
236+
private SqliteConnection GetDbConnection()
241237
{
242-
if (_inMemoryDbConnection == null)
243-
{
244-
_logger.LogInformation($"Init in-memory Sqlite database connection");
245-
246-
_inMemoryDbConnection = new SqliteConnection("Data Source=:memory:;Mode=ReadWrite");
247-
_inMemoryDbConnection.Open();
248-
}
249-
return _inMemoryDbConnection;
250-
}
238+
var connectionString = _settings.Database.ConnectionString;
239+
240+
// Extract the database file path from the connection string
241+
var builder = new SqliteConnectionStringBuilder(connectionString);
242+
var dbFilePath = builder.DataSource;
251243

252-
private SqliteConnection GetPhysicalDbConnection()
253-
{
254-
if (string.IsNullOrEmpty(_dbFilePath))
244+
_logger.LogInformation("Database file path: {DbFilePath}", dbFilePath);
245+
246+
// If it's not an in-memory database, ensure the directory exists
247+
if (!string.IsNullOrEmpty(dbFilePath) &&
248+
!dbFilePath.Equals(":memory:", StringComparison.OrdinalIgnoreCase))
255249
{
256-
_dbFilePath = _settings.Database.ConnectionString;
250+
var directory = Path.GetDirectoryName(dbFilePath);
251+
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
252+
{
253+
Directory.CreateDirectory(directory);
254+
_logger.LogInformation("Created directory: {Directory}", directory);
255+
}
257256
}
258-
259-
var dbConnection = new SqliteConnection($"Data Source={_dbFilePath};Mode=ReadWrite");
257+
258+
// SQLite automatically creates the database file when opening the connection
259+
var dbConnection = new SqliteConnection(connectionString);
260260
dbConnection.Open();
261261
return dbConnection;
262262
}

src/Plugins/BotSharp.Plugin.OpenAI/Providers/Chat/ChatCompletionProvider.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,14 @@ public async Task<RoleDialogModel> GetChatCompletions(Agent agent, List<RoleDial
6969
responseMessage.FunctionName = responseMessage.FunctionName.Split('.').Last();
7070
}
7171
}
72+
else if (reason == ChatFinishReason.Length)
73+
{
74+
responseMessage = new RoleDialogModel(AgentRole.Function, $"AI response execeed max output length {options.MaxOutputTokenCount}")
75+
{
76+
CurrentAgentId = agent.Id,
77+
MessageId = conversations.LastOrDefault()?.MessageId ?? string.Empty
78+
};
79+
}
7280
else
7381
{
7482
responseMessage = new RoleDialogModel(AgentRole.Assistant, text)

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
"utilities": [],
1414
"llmConfig": {
1515
"provider": "openai",
16-
"model": "gpt-4o-2024-11-20",
16+
"model": "gpt-5-mini",
1717
"max_recursion_depth": 10
1818
}
1919
}

src/Plugins/BotSharp.Plugin.Planner/data/agents/3e75e818-a139-48a8-9e22-4662548c13a3/agent.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
"utilities": [],
1414
"llmConfig": {
1515
"provider": "openai",
16-
"model": "gpt-4o-2024-11-20",
16+
"model": "gpt-5-mini",
1717
"max_recursion_depth": 10
1818
}
1919
}

0 commit comments

Comments
 (0)