Как передавать большой объем данных в качестве контекста через плагин в семантическом ядре C# .net 8.0C#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Как передавать большой объем данных в качестве контекста через плагин в семантическом ядре C# .net 8.0

Сообщение Anonymous »

Я использую Microsoft Semantic ядра в проекте C#, и я хочу работать с большим количеством структурированных данных из базы данных SQL Server. Моя цель состоит в том, чтобы включить семантический поиск и ответы с учетом контекста путем внедрения и хранения этих данных, используя систему памяти семантического ядра.
Мой вопрос:
Какой лучший способ пригласить и косой большие данные Sql Server для использования в SK? от SQL Server с использованием ADO.NET. < /p>
Передача строк в пользовательский плагин семантического ядра. < /p>
using DinkToPdf;
using DinkToPdf.Contracts;
using Microsoft.SemanticKernel;
using TaskIntel.API.Plugins;
using TaskIntel.API.Services.Implementation;
using TaskIntel.API.Services.Interface;

namespace TaskIntel.API;

public static class DependencyInjection_
{
public static IServiceCollection AddDependencies(this IServiceCollection services, IConfiguration configuration)
{

// Add Employee Service as Scoped
services.AddScoped(serviceProvider =>
{
var connStr = configuration.GetConnectionString("TaskIntel");
if (string.IsNullOrEmpty(connStr))
throw new InvalidOperationException("TaskIntel connection string is required");

return new EmployeeService(connStr);
});

// Add DinkToPdf converter as Singleton (stateless)
services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));

// Add PDF Service as Scoped
services.AddScoped();

// Semantic Kernel with Google Gemini
services.AddScoped(provider =>
{
var config = provider.GetRequiredService();
var geminiApiKey = config["GoogleAI:ApiKey"];
var geminiModel = config["GoogleAI:Model"] ?? "gemini-1.5-flash";

if (string.IsNullOrWhiteSpace(geminiApiKey))
{
Console.WriteLine("❌ Google AI ApiKey is missing!");
Console.WriteLine("🔑 Get your FREE API key from: https://makersuite.google.com/app/apikey");
throw new InvalidOperationException("Google AI ApiKey is required. Get it from: https://makersuite.google.com/app/apikey");
}

try
{
Console.WriteLine($"🤖 Configuring Google Gemini AI...");
var builder = Kernel.CreateBuilder();

// Suppress the warning right here at the source
#pragma warning disable SKEXP0070
builder.AddGoogleAIGeminiChatCompletion(
modelId: geminiModel,
apiKey: geminiApiKey
);
#pragma warning restore SKEXP0070

var kernel = builder.Build();

Console.WriteLine($"✅ Google Gemini AI configured successfully!");
Console.WriteLine($"🆓 Model: {geminiModel} (FREE!)");
Console.WriteLine($"⚡ Ready for intelligent analysis");

return kernel;
}
catch (Exception ex)
{
Console.WriteLine($"❌ Failed to configure Google Gemini: {ex.Message}");
Console.WriteLine($"🔑 Verify your API key from: https://makersuite.google.com/app/apikey");
throw;
}
});

// Register OpenAI Semantic Kernel
//services.AddSingleton(provider =>
//{
// var config = provider.GetRequiredService();
// var openAiApiKey = config["OpenAI:ApiKey"];
// var openAiModel = config["OpenAI:Model"];

// if (string.IsNullOrWhiteSpace(openAiApiKey) || string.IsNullOrWhiteSpace(openAiModel))
// {
// throw new InvalidOperationException("OpenAI ApiKey or Model is not configured properly.");
// }

// var builder = Kernel.CreateBuilder();
// builder.AddOpenAIChatCompletion(openAiModel, openAiApiKey);

// var kernel = builder.Build();
// return kernel;
//});

services.AddScoped();

return services;
}

private static string GetValidGeminiModel(string? requestedModel)
{
// List of available Gemini models (in order of preference)
var availableModels = new[]
{
"gemini-1.5-flash", // Latest, fastest, most cost-effective
"gemini-1.5-pro", // Most capable, higher cost
"gemini-1.0-pro", // Stable, reliable
"gemini-pro" // Fallback
};

// If requested model is specified and valid, use it
if (!string.IsNullOrEmpty(requestedModel) && availableModels.Contains(requestedModel))
{
return requestedModel;
}

// Default to most cost-effective model
Console.WriteLine($"⚠️ Model '{requestedModel}' not specified, using gemini-1.5-flash");
return "gemini-1.5-flash";
}

}


Подробнее здесь: https://stackoverflow.com/questions/796 ... el-c-sharp
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»