245 lines
8.3 KiB
C#
245 lines
8.3 KiB
C#
using ChatApi;
|
|
using ChatApi.Data;
|
|
using ChatApi.Middlewares;
|
|
using ChatApi.Services.Crypt;
|
|
using ChatApi.Settings;
|
|
using ChatRAG.Repositories;
|
|
using ChatRAG.Services;
|
|
using ChatRAG.Services.ResponseService;
|
|
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;
|
|
|
|
#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<DomvsDatabaseSettings>(
|
|
builder.Configuration.GetSection("DomvsDatabase"));
|
|
|
|
builder.Services.Configure<ChatRHSettings>(
|
|
builder.Configuration.GetSection("ChatRHSettings"));
|
|
|
|
builder.Services.AddSingleton<ChatHistoryService>();
|
|
builder.Services.AddScoped<TextDataService>();
|
|
builder.Services.AddSingleton<TextFilter>();
|
|
|
|
builder.Services.AddScoped<IResponseService, 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 notebook
|
|
//builder.Services.AddOllamaChatCompletion("phi3.5", 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"));
|
|
//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)
|
|
.AddJwtBearer(jwtBearerOptions =>
|
|
{
|
|
jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters()
|
|
{
|
|
ValidateActor = true,
|
|
ValidateAudience = true,
|
|
ValidateLifetime = true,
|
|
ValidateIssuerSigningKey = true,
|
|
ValidIssuer = builder.Configuration["Issuer"],
|
|
ValidAudience = builder.Configuration["Audience"],
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["SigningKey"]))
|
|
};
|
|
jwtBearerOptions.Events = new JwtBearerEvents()
|
|
{
|
|
OnTokenValidated = async context =>
|
|
{
|
|
var token = context.SecurityToken as JsonWebToken;
|
|
context.HttpContext.Items["Token"] = token.EncodedToken;
|
|
AppDomain.CurrentDomain.SetData("Token", token.EncodedToken);
|
|
}
|
|
};
|
|
})
|
|
;
|
|
|
|
//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.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.
|