ChatRAG/Program.cs
Ricardo Carneiro e75abe7fc8 fix: groq e id
2025-06-21 23:58:18 -03:00

328 lines
12 KiB
C#

using ChatApi;
using ChatApi.Data;
using ChatApi.Middlewares;
using ChatApi.Services.Crypt;
using ChatApi.Settings;
using ChatRAG.Contracts.VectorSearch;
using ChatRAG.Data;
using ChatRAG.Extensions;
using ChatRAG.Services;
using ChatRAG.Services.Contracts;
using ChatRAG.Services.ResponseService;
using ChatRAG.Services.SearchVectors;
using ChatRAG.Services.TextServices;
using ChatRAG.Settings.ChatRAG.Configuration;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Microsoft.SemanticKernel;
using System.Text;
using static OllamaSharp.OllamaApiClient;
using static System.Net.Mime.MediaTypeNames;
using static System.Net.WebRequestMethods;
#pragma warning disable SKEXP0010 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Adicionar serviço CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder =>
{
builder
.WithOrigins("http://localhost:5094") // Sua origem específica
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "apichat", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer'[space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
builder.Services.Configure<ChatRHSettings>(
builder.Configuration.GetSection("ChatRHSettings"));
//builder.Services.AddScoped<IVectorSearchService, MongoVectorSearchService>();
builder.Services.AddScoped<QdrantVectorSearchService>();
builder.Services.AddScoped<MongoVectorSearchService>();
builder.Services.AddScoped<ChromaVectorSearchService>();
builder.Services.AddVectorDatabase(builder.Configuration);
builder.Services.AddScoped<IVectorSearchService>(provider =>
{
var useQdrant = builder.Configuration["Features:UseQdrant"] == "true";
var factory = provider.GetRequiredService<IVectorDatabaseFactory>();
return factory.CreateVectorSearchService();
});
builder.Services.AddScoped<QdrantProjectDataRepository>();
builder.Services.AddScoped<MongoProjectDataRepository>();
builder.Services.AddScoped<ChromaProjectDataRepository>();
builder.Services.AddScoped<IProjectDataRepository>(provider =>
{
var database = builder.Configuration["VectorDatabase:Provider"];
if (string.IsNullOrEmpty(database))
{
throw new InvalidOperationException("VectorDatabase:Provider is not configured.");
}
else if (database.Equals("Qdrant", StringComparison.OrdinalIgnoreCase))
{
return provider.GetRequiredService<QdrantProjectDataRepository>();
}
else if (database.Equals("MongoDB", StringComparison.OrdinalIgnoreCase))
{
return provider.GetRequiredService<MongoProjectDataRepository>();
}
else if (database.Equals("Chroma", StringComparison.OrdinalIgnoreCase))
{
return provider.GetRequiredService<ChromaProjectDataRepository>();
}
return provider.GetRequiredService<MongoProjectDataRepository>();
});
builder.Services.AddScoped<QdrantTextDataService>();
builder.Services.AddScoped<MongoTextDataService>();
builder.Services.AddScoped<ChromaTextDataService>();
builder.Services.AddScoped<ITextDataService>(provider =>
{
var database = builder.Configuration["VectorDatabase:Provider"];
if (string.IsNullOrEmpty(database))
{
throw new InvalidOperationException("VectorDatabase:Provider is not configured.");
}
else if (database.Equals("Qdrant", StringComparison.OrdinalIgnoreCase))
{
return provider.GetRequiredService<QdrantTextDataService>();
}
else if (database.Equals("MongoDB", StringComparison.OrdinalIgnoreCase))
{
return provider.GetRequiredService<MongoTextDataService>();
}
else if (database.Equals("Chroma", StringComparison.OrdinalIgnoreCase))
{
return provider.GetRequiredService<ChromaTextDataService>();
}
return provider.GetRequiredService<MongoTextDataService>();
});
builder.Services.AddSingleton<ChatHistoryService>();
builder.Services.AddScoped<TextDataRepository>();
builder.Services.AddSingleton<TextFilter>();
//builder.Services.AddScoped<IResponseService, ResponseRAGService>();
builder.Services.AddScoped<ResponseRAGService>();
builder.Services.AddScoped<HierarchicalRAGService>();
builder.Services.AddScoped<IResponseService>(provider =>
{
var configuration = provider.GetService<IConfiguration>();
var useHierarchical = configuration?.GetValue<bool>("Features:UseHierarchicalRAG") ?? false;
return useHierarchical
? provider.GetRequiredService<HierarchicalRAGService>()
: provider.GetRequiredService<ResponseRAGService>();
});
builder.Services.AddTransient<UserDataRepository>();
builder.Services.AddTransient<TextData>();
builder.Services.AddSingleton<CryptUtil>();
//builder.Services.AddOllamaChatCompletion("phi3.5", new Uri("http://localhost:11435"));
//builder.Services.AddOllamaChatCompletion("tinydolphin", new Uri("http://localhost:11435"));
//var apiClient = new OllamaApiClient(new Uri("http://localhost:11435"), "tinydolphin");
//Olllama
//Desktop
var key = "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";
//uilder.Services.AddOllamaChatCompletion("llama3.2", new Uri("http://localhost:11434"));
//var model = "llama-3.3-70b-versatile";
var model = "llama-3.1-8b-instant";
//var model = "meta-llama/llama-guard-4-12b";
//var url = "https://api.groq.com/openai/v1/chat/completions"; // Adicione o /v1/openai
var url = "https://api.groq.com/openai/v1";
builder.Services.AddOpenAIChatCompletion(model, new Uri(url), key);
//Notebook
//var model = "meta-llama/Llama-3.2-3B-Instruct";
//var url = "https://api.deepinfra.com/v1/openai"; // Adicione o /v1/openai
//builder.Services.AddOpenAIChatCompletion(model, new Uri(url), "HedaR4yPrp9N2XSHfwdZjpZvPIxejPFK");
//builder.Services.AddOllamaChatCompletion("llama3.2:3b", new Uri("http://localhost:11435"));
//builder.Services.AddOllamaChatCompletion("llama3.2:1b", new Uri("http://localhost:11435"));
//builder.Services.AddOllamaChatCompletion("tinydolphin", new Uri("http://localhost:11435"));
//builder.Services.AddOllamaChatCompletion("tinyllama", new Uri("http://localhost:11435"));
//builder.Services.AddOllamaChatCompletion("starling-lm", new Uri("http://localhost:11435"));
//ServerSpace - GPT Service
//builder.Services.AddOpenAIChatCompletion("openchat-3.5-0106", new Uri("https://gpt.serverspace.com.br/v1/chat/completions"), "tIAXVf3AkCkkpSX+PjFvktfEeSPyA1ZYam50UO3ye/qmxVZX6PIXstmJsLZXkQ39C33onFD/81mdxvhbGHm7tQ==");
//Ollama local server (scorpion)
//builder.Services.AddOllamaChatCompletion("llama3.1:latest", new Uri("http://192.168.0.150:11434"));
//builder.Services.AddOllamaTextEmbeddingGeneration("all-minilm", new Uri("http://192.168.0.150:11434"));
//Desktop
builder.Services.AddOllamaTextEmbeddingGeneration("all-minilm", new Uri("http://localhost:11434"));
//Notebook
//builder.Services.AddOllamaTextEmbeddingGeneration("all-minilm", new Uri("http://localhost:11435"));
//builder.Services.AddOllamaChatCompletion("phi3.5", new Uri("http://localhost:11435"));
//builder.Services.AddOpenAIChatCompletion("gpt-4o-mini", "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");
//builder.Services.AddGoogleAIGeminiChatCompletion("gemini-1.5-flash-latest", "AIzaSyDKBMX5yW77vxJFVJVE-5VLxlQRxCepck8");
//Anthropic / Claude
//builder.Services.AddAnthropicChatCompletion(
// modelId: "claude-3-5-sonnet-latest", // ou outro modelo Claude desejado
// apiKey: "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"
//);
builder.Services.AddKernel();
//builder.Services.AddKernel()
// .AddOllamaChatCompletion("phi3", new Uri("http://localhost:11435"))
// .AddOllamaTextEmbeddingGeneration()
// .Build();
//builder.Services.AddOllamaChatCompletion("phi3.5", new Uri("http://192.168.0.150:11436"));
builder.Services.AddHttpClient();
var tenantId = builder.Configuration.GetSection("AppTenantId");
var clientId = builder.Configuration.GetSection("AppClientID");
//builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
// .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllers();
//builder.Services.AddAuthentication(options =>
// {
// options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
// options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
// })
// .AddJwtBearer(options =>
// {
// // Configurações anteriores...
// // Eventos para log e tratamento de erros
// options.Events = new JwtBearerEvents
// {
// OnAuthenticationFailed = context =>
// {
// // Log de erros de autenticação
// Console.WriteLine($"Erro de autenticação: {context.Exception.Message}");
// return Task.CompletedTask;
// },
// OnTokenValidated = context =>
// {
// // Validações adicionais se necessário
// return Task.CompletedTask;
// }
// };
// });
builder.Services.AddSingleton<IConfigurationManager>(builder.Configuration);
builder.Services.Configure<IISServerOptions>(options =>
{
options.MaxRequestBodySize = int.MaxValue;
});
builder.Services.Configure<KestrelServerOptions>(options =>
{
options.Limits.MaxRequestBodySize = int.MaxValue;
});
builder.Services.Configure<FormOptions>(options =>
{
options.ValueLengthLimit = int.MaxValue;
options.MultipartBodyLengthLimit = int.MaxValue;
options.MultipartHeadersLengthLimit = int.MaxValue;
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseDeveloperExceptionPage(); // Isso mostra erros detalhados
}
//app.UseHttpsRedirection();
app.MapControllers();
app.Use(async (context, next) =>
{
var cookieOpt = new CookieOptions()
{
Path = "/",
Expires = DateTimeOffset.UtcNow.AddDays(1),
IsEssential = true,
HttpOnly = false,
Secure = false,
};
await next();
});
app.UseMiddleware<ErrorHandlingMiddleware>();
app.UseCors("AllowSpecificOrigin");
app.UseAuthentication();
app.UseAuthorization();
app.Run();
#pragma warning restore SKEXP0010 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.