The code is in c#
I want to execute the code where user will ask the question to the database in the human language and Ollama model should check in the database and answer the question from the database.
For Example : How many tables are there?
Ans – It should count and display the result .
I don’t know the approach to do that,. A guidance will be appreciated
Below is the code I have done so far
The code is working as
Question – Show tables; (Here question is written as the sql query)
Ans – displaying all the tables
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.Extensions.Logging; // Added for logging
using Microsoft.Extensions.Logging.Debug;
using Microsoft.Extensions.DependencyInjection;
using System;
using MySql.Data.MySqlClient;
using System.Net.Http;
using MySqlConnector;
//Configure the Semantic Kernel
var kernelBuilder = Kernel.CreateBuilder();
#pragma warning disable SKEXP0010
var kernel = kernelBuilder
.AddOpenAIChatCompletion(
modelId: "llama2",
apiKey: "",
endpoint: new Uri("")
)
.Build();
// Create the chat service
var aiModel = kernel.GetRequiredService<IChatCompletionService>();
// MySQL connection configuration
var connectionString = ""; // Replace with actual values
using var connection = new MySqlConnector.MySqlConnection(connectionString);
try
{
await connection.OpenAsync();
Console.WriteLine("Connection to the database was successful.");
}
catch (Exception ex)
{
Console.WriteLine($"Error connecting to the database: {ex.Message}");
return;
}
//Conversation loop
while (true)
{
Console.Write("Your question: ");
var question = Console.ReadLine();
// Attempt to execute the input as a SQL query
try
{
var command = new MySqlConnector.MySqlCommand(question, connection);
using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Console.Write($"{reader.GetName(i)}: {reader.GetValue(i)}t");
}
Console.WriteLine();
}
}
catch (Exception ex)
{
Console.WriteLine($"Error executing query: {ex.Message}");
// If an error occurs, assume the input might be a question for the AI model
try
{
await foreach (var message in aiModel.GetStreamingChatMessageContentsAsync(prompt: question, kernel: kernel))
{
Console.Write(message);
}
Console.WriteLine();
}
catch (Exception aiEx)
{
// Log the error details
Console.WriteLine($"Error: {aiEx.Message}");
}
}
}