fix 执行code clear

This commit is contained in:
zyxucp
2024-03-09 19:19:05 +08:00
parent 2be438f9c3
commit 1dc274ce82
110 changed files with 684 additions and 1134 deletions

View File

@@ -1,10 +1,5 @@
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Common.DependencyInjection
{

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Common.DependencyInjection
namespace AntSK.Domain.Common.DependencyInjection
{
public class ServiceDescriptionAttribute : Attribute
{

View File

@@ -1,7 +1,4 @@
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Text;
namespace AntSK.Domain.Common.Map
{

View File

@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace AntSK.Domain.Common.Map
namespace AntSK.Domain.Common.Map
{
public static class MapperExtend
{

View File

@@ -1,8 +1,5 @@
using AutoMapper;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace AntSK.Domain.Common.Map
{

View File

@@ -2,11 +2,6 @@
using AntSK.Domain.Domain.Interface;
using AntSK.Domain.Model;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Domain.BackGroundTask
{

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Domain.Dto
namespace AntSK.Domain.Domain.Dto
{
public class KMFile
{

View File

@@ -1,11 +1,4 @@
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Models
namespace AntSK.Domain.Domain.Dto
{
public class OpenAIModel
{

View File

@@ -1,7 +1,6 @@
using Newtonsoft.Json;
using System.Text.Json.Serialization;
namespace AntSK.Models.OpenAPI
namespace AntSK.Domain.Domain.Dto
{
public class OpenAIResult
{
@@ -21,7 +20,7 @@ namespace AntSK.Models.OpenAPI
public OpenAIMessage message { get; set; }
}
public class OpenAIEmbeddingResult
public class OpenAIEmbeddingResult
{
[JsonProperty("object")]
public string obj { get; set; } = "list";
@@ -29,17 +28,17 @@ namespace AntSK.Models.OpenAPI
public UsageModel usage { get; set; } = new UsageModel();
public List<DataModel> data { get; set; } = new List<DataModel>() { new DataModel() };
public List<DataModel> data { get; set; } = new List<DataModel>() { new DataModel() };
}
public class UsageModel
public class UsageModel
{
public long prompt_tokens { get; set; } = 0;
public long total_tokens { get; set; } = 0;
}
public class DataModel
public class DataModel
{
[JsonProperty("object")]
public string obj { get; set; } = "embedding";

View File

@@ -1,9 +1,4 @@
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Domain.Interface
{

View File

@@ -1,9 +1,4 @@
using AntSK.Domain.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Domain.Interface
{

View File

@@ -1,11 +1,5 @@
using AntSK.Domain.Domain.Dto;
using Microsoft.KernelMemory.Configuration;
using Microsoft.KernelMemory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Domain.Interface
{

View File

@@ -1,10 +1,5 @@
using AntSK.Domain.Repositories;
using Microsoft.SemanticKernel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Domain.Interface
{

View File

@@ -1,30 +1,21 @@
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Domain.Interface;
using AntSK.Domain.Model;
using AntSK.Domain.Utils;
using Microsoft.KernelMemory;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Domain.Service
{
[ServiceDescription(typeof(IHttpService), ServiceLifetime.Scoped)]
public class HttpService: IHttpService
public class HttpService : IHttpService
{
public async Task< RestResponse> PostAsync(string url ,Object jsonBody)
public async Task<RestResponse> PostAsync(string url, Object jsonBody)
{
RestClient client = new RestClient();
RestRequest request= new RestRequest(url, Method.Post);
RestRequest request = new RestRequest(url, Method.Post);
string josn = JsonConvert.SerializeObject(jsonBody);
request.AddJsonBody(jsonBody);
var result =await client.ExecuteAsync(request);
return result;
var result = await client.ExecuteAsync(request);
return result;
}
}
}

View File

@@ -3,13 +3,6 @@ using AntSK.Domain.Domain.Interface;
using AntSK.Domain.Model;
using AntSK.Domain.Repositories;
using Microsoft.KernelMemory;
using Microsoft.KernelMemory.Configuration;
using Microsoft.SemanticKernel.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Domain.Service
{
@@ -34,12 +27,12 @@ namespace AntSK.Domain.Domain.Service
case ImportType.File:
//导入文件
{
var importResult= _memory.ImportDocumentAsync(new Document(fileid)
.AddFile(req.FilePath)
.AddTag("kmsid", req.KmsId)
, index: "kms").Result;
var importResult = _memory.ImportDocumentAsync(new Document(fileid)
.AddFile(req.FilePath)
.AddTag("kmsid", req.KmsId)
, index: "kms").Result;
//查询文档数量
var docTextList = _kMService.GetDocumentByFileID(km.Id,fileid).Result;
var docTextList = _kMService.GetDocumentByFileID(km.Id, fileid).Result;
string fileGuidName = Path.GetFileName(req.FilePath);
req.KmsDetail.FileName = req.FileName;
req.KmsDetail.FileGuidName = fileGuidName;
@@ -53,7 +46,7 @@ namespace AntSK.Domain.Domain.Service
var importResult = _memory.ImportWebPageAsync(req.Url, fileid, new TagCollection() { { "kmsid", req.KmsId } }
, index: "kms").Result;
//查询文档数量
var docTextList = _kMService.GetDocumentByFileID(km.Id,fileid).Result;
var docTextList = _kMService.GetDocumentByFileID(km.Id, fileid).Result;
req.KmsDetail.Url = req.Url;
req.KmsDetail.DataCount = docTextList.Count;
}
@@ -64,7 +57,7 @@ namespace AntSK.Domain.Domain.Service
var importResult = _memory.ImportTextAsync(req.Text, fileid, new TagCollection() { { "kmsid", req.KmsId } }
, index: "kms").Result;
//查询文档数量
var docTextList = _kMService.GetDocumentByFileID(km.Id,fileid).Result;
var docTextList = _kMService.GetDocumentByFileID(km.Id, fileid).Result;
req.KmsDetail.Url = req.Url;
req.KmsDetail.DataCount = docTextList.Count;
@@ -72,14 +65,14 @@ namespace AntSK.Domain.Domain.Service
break;
}
req.KmsDetail.Status = Model.Enum.ImportKmsStatus.Success;
_kmsDetails_Repositories.Update(req.KmsDetail);
//_kmsDetails_Repositories.GetList(p => p.KmsId == req.KmsId);
_kmsDetails_Repositories.Update(req.KmsDetail);
//_kmsDetails_Repositories.GetList(p => p.KmsId == req.KmsId);
Console.WriteLine("后台导入任务成功:" + req.KmsDetail.DataCount);
}
catch (Exception ex)
{
req.KmsDetail.Status = Model.Enum.ImportKmsStatus.Fail;
_kmsDetails_Repositories.Update(req.KmsDetail);
_kmsDetails_Repositories.Update(req.KmsDetail);
Console.WriteLine("后台导入任务异常:" + ex.Message);
}
}

View File

@@ -1,21 +1,16 @@
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Domain.Interface;
using Microsoft.KernelMemory;
using AntSK.Domain.Utils;
using AntSK.Domain.Domain.Dto;
using AntSK.Domain.Options;
using AntSK.Domain.Domain.Interface;
using AntSK.Domain.Repositories;
using AntSK.Domain.Utils;
using LLama;
using LLamaSharp.KernelMemory;
using Microsoft.Extensions.Configuration;
using Microsoft.KernelMemory;
using Microsoft.KernelMemory.Configuration;
using Microsoft.KernelMemory.ContentStorage.DevTools;
using Microsoft.KernelMemory.FileSystem.DevTools;
using Microsoft.KernelMemory.Postgres;
using System.Net.Http;
using Microsoft.Extensions.Options;
using Microsoft.KernelMemory.Configuration;
using Microsoft.Extensions.Configuration;
using AntSK.Domain.Repositories;
using LLamaSharp.KernelMemory;
using LLama.Common;
using DocumentFormat.OpenXml.Spreadsheet;
using LLama;
namespace AntSK.Domain.Domain.Service
{
@@ -60,7 +55,7 @@ namespace AntSK.Domain.Domain.Service
//加载huihu 模型
WithTextGenerationByAIType(memory, chatModel, chatHttpClient);
//加载向量模型
WithTextEmbeddingGenerationByAIType(memory,embedModel, embeddingHttpClient);
WithTextEmbeddingGenerationByAIType(memory, embedModel, embeddingHttpClient);
//加载向量库
WithMemoryDbByVectorDB(memory, _config);
@@ -69,7 +64,7 @@ namespace AntSK.Domain.Domain.Service
}
private void WithTextEmbeddingGenerationByAIType(IKernelMemoryBuilder memory,AIModels embedModel, HttpClient embeddingHttpClient )
private void WithTextEmbeddingGenerationByAIType(IKernelMemoryBuilder memory, AIModels embedModel, HttpClient embeddingHttpClient)
{
switch (embedModel.AIType)
{
@@ -98,7 +93,7 @@ namespace AntSK.Domain.Domain.Service
}
}
private void WithTextGenerationByAIType(IKernelMemoryBuilder memory,AIModels chatModel, HttpClient chatHttpClient )
private void WithTextGenerationByAIType(IKernelMemoryBuilder memory, AIModels chatModel, HttpClient chatHttpClient)
{
switch (chatModel.AIType)
{
@@ -106,7 +101,7 @@ namespace AntSK.Domain.Domain.Service
memory.WithOpenAITextGeneration(new OpenAIConfig()
{
APIKey = chatModel.ModelKey,
TextModel = chatModel.ModelName
TextModel = chatModel.ModelName
}, null, chatHttpClient);
break;
case Model.Enum.AIType.AzureOpenAI:
@@ -128,7 +123,7 @@ namespace AntSK.Domain.Domain.Service
}
}
private void WithMemoryDbByVectorDB(IKernelMemoryBuilder memory,IConfiguration _config)
private void WithMemoryDbByVectorDB(IKernelMemoryBuilder memory, IConfiguration _config)
{
string VectorDb = _config["KernelMemory:VectorDb"].ConvertToString();
string ConnectionString = _config["KernelMemory:ConnectionString"].ConvertToString();
@@ -157,7 +152,7 @@ namespace AntSK.Domain.Domain.Service
}
}
public async Task<List<KMFile>> GetDocumentByFileID(string kmsid,string fileid)
public async Task<List<KMFile>> GetDocumentByFileID(string kmsid, string fileid)
{
var _memory = GetMemoryByKMS(kmsid);
var memories = await _memory.ListIndexesAsync();
@@ -187,6 +182,6 @@ namespace AntSK.Domain.Domain.Service
return docTextList;
}
}
}

View File

@@ -1,40 +1,28 @@
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Domain.Interface;
using AntSK.Domain.Model;
using AntSK.Domain.Options;
using AntSK.Domain.Repositories;
using AntSK.Domain.Utils;
using DocumentFormat.OpenXml.EMMA;
using LLama;
using LLamaSharp.KernelMemory;
using LLamaSharp.SemanticKernel.ChatCompletion;
using LLamaSharp.SemanticKernel.TextCompletion;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.KernelMemory;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Plugins.Core;
using Microsoft.SemanticKernel.TextGeneration;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using ServiceLifetime = AntSK.Domain.Common.DependencyInjection.ServiceLifetime;
namespace AntSK.Domain.Domain.Service
{
[ServiceDescription(typeof(IKernelService), ServiceLifetime.Scoped)]
public class KernelService: IKernelService
public class KernelService : IKernelService
{
private readonly IApis_Repositories _apis_Repositories;
private readonly IAIModels_Repositories _aIModels_Repositories;
public KernelService(
IApis_Repositories apis_Repositories,
IAIModels_Repositories aIModels_Repositories
)
)
{
_apis_Repositories = apis_Repositories;
_aIModels_Repositories = aIModels_Repositories;
@@ -48,15 +36,15 @@ namespace AntSK.Domain.Domain.Service
/// <returns></returns>
public Kernel GetKernelByApp(Apps app)
{
var chatModel= _aIModels_Repositories.GetFirst(p => p.Id == app.ChatModelID);
var chatModel = _aIModels_Repositories.GetFirst(p => p.Id == app.ChatModelID);
var chatHttpClient = OpenAIHttpClientHandlerUtil.GetHttpClient(chatModel.EndPoint);
var builder = Kernel.CreateBuilder();
WithTextGenerationByAIType(builder, chatModel, chatHttpClient);
var kernel= builder.Build();
var kernel = builder.Build();
RegisterPluginsWithKernel(kernel);
return kernel;
}
@@ -73,7 +61,7 @@ namespace AntSK.Domain.Domain.Service
break;
case Model.Enum.AIType.AzureOpenAI:
builder.AddAzureOpenAIChatCompletion(
deploymentName:chatModel.ModelName,
deploymentName: chatModel.ModelName,
apiKey: chatModel.ModelKey,
endpoint: chatModel.EndPoint
);
@@ -189,7 +177,7 @@ namespace AntSK.Domain.Domain.Service
/// <param name="questions"></param>
/// <param name="history"></param>
/// <returns></returns>
public async Task<string> HistorySummarize(Kernel _kernel,string questions, string history)
public async Task<string> HistorySummarize(Kernel _kernel, string questions, string history)
{
KernelFunction sunFun = _kernel.Plugins.GetFunction("ConversationSummaryPlugin", "SummarizeConversation");
var summary = await _kernel.InvokeAsync(sunFun, new() { ["input"] = $"内容是:{history.ToString()} {Environment.NewLine} 请注意用中文总结" });

View File

@@ -1,11 +1,6 @@
using LLama.Common;
using LLama;
using LLama;
using LLama.Common;
using LLamaSharp.KernelMemory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Domain.Service
{
@@ -16,7 +11,7 @@ namespace AntSK.Domain.Domain.Service
/// 避免模型重复加载,本地缓存
/// </summary>
static Dictionary<string, (LLamaWeights, ModelParams)> dicLLamaWeights = new Dictionary<string, (LLamaWeights, ModelParams)>();
public static (LLamaWeights, ModelParams) GetLLamaConfig(string modelPath, LLamaSharpConfig config =null)
public static (LLamaWeights, ModelParams) GetLLamaConfig(string modelPath, LLamaSharpConfig config = null)
{
lock (lockobj)
{
@@ -28,7 +23,7 @@ namespace AntSK.Domain.Domain.Service
{
InferenceParams infParams = new() { AntiPrompts = ["\n\n"] };
LLamaSharpConfig lsConfig = new(modelPath) { DefaultInferenceParams = infParams };
if (config!=null)
if (config != null)
{
lsConfig = config;
}
@@ -43,7 +38,7 @@ namespace AntSK.Domain.Domain.Service
dicLLamaWeights.Add(modelPath, (weights, parameters));
return (weights, parameters);
}
}
}
}
}
}

View File

@@ -1,9 +1,4 @@
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Map
{

View File

@@ -1,9 +1,4 @@
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Map
{

View File

@@ -1,10 +1,5 @@
using AutoMapper;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Map
{

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Model.Enum
namespace AntSK.Domain.Model.Enum
{
/// <summary>
/// AI类型
@@ -13,7 +7,7 @@ namespace AntSK.Domain.Model.Enum
{
OpenAI = 1,
AzureOpenAI = 2,
LLamaSharp=3
LLamaSharp = 3
}
/// <summary>

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Model
namespace AntSK.Domain.Model
{
public enum HttpMethodType
{

View File

@@ -1,15 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Model.Enum
namespace AntSK.Domain.Model.Enum
{
public enum ImportKmsStatus
{
Loadding=0,
Success=1,
Fail=2
Loadding = 0,
Success = 1,
Fail = 2
}
}

View File

@@ -1,10 +1,4 @@
using AntSK.Domain.Repositories;
using Microsoft.KernelMemory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Model
{
@@ -26,14 +20,15 @@ namespace AntSK.Domain.Model
}
public class ImportKMSTaskReq: ImportKMSTaskDTO
public class ImportKMSTaskReq : ImportKMSTaskDTO
{
public KmsDetails KmsDetail { get; set; } = new KmsDetails();
}
public enum ImportType {
File=1,
Url=2,
Text=3
public enum ImportType
{
File = 1,
Url = 2,
Text = 3
}
}

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Model
namespace AntSK.Domain.Model
{
public class MessageInfo
{

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Model
namespace AntSK.Domain.Model
{
public class PageList<T>
{

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Options
namespace AntSK.Domain.Options
{
public class DBConnectionOption
{

View File

@@ -1,16 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Options
namespace AntSK.Domain.Options
{
public class KernelMemoryOption
{
/// <summary>
/// 向量库
/// </summary>
/// <summary>
/// 向量库
/// </summary>
public static string VectorDb { get; set; }
/// <summary>
/// 连接字符串

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Options
namespace AntSK.Domain.Options
{
public class LLamaSharpOption
{

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Options
namespace AntSK.Domain.Options
{
public class LoginOption
{

View File

@@ -1,11 +1,6 @@
using AntSK.Domain.Model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Repositories
{

View File

@@ -1,11 +1,6 @@

using AntSK.Domain.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Repositories.Base;
namespace AntSK.Domain.Repositories
{

View File

@@ -1,9 +1,4 @@
using AntSK.Domain.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Repositories
{

View File

@@ -1,10 +1,5 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Repositories
{
@@ -47,7 +42,7 @@ namespace AntSK.Domain.Repositories
/// 温度
/// </summary>
[SugarColumn(DefaultValue = "70")]
public double Temperature { get; set; }=70f;
public double Temperature { get; set; } = 70f;
/// <summary>
/// 提示词

View File

@@ -1,11 +1,6 @@

using AntSK.Domain.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Repositories.Base;
namespace AntSK.Domain.Repositories
{

View File

@@ -1,9 +1,4 @@
using AntSK.Domain.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Repositories
{

View File

@@ -1,9 +1,4 @@
using AntSK.Domain.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Repositories
{

View File

@@ -1,10 +1,5 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Repositories
{
@@ -60,6 +55,6 @@ namespace AntSK.Domain.Repositories
[SugarColumn(DefaultValue = "49")]
public int OverlappingTokens { get; set; } = 49;
}
}

View File

@@ -1,11 +1,6 @@

using AntSK.Domain.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Repositories.Base;
namespace AntSK.Domain.Repositories
{

View File

@@ -1,9 +1,4 @@
using AntSK.Domain.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Repositories
{

View File

@@ -1,10 +1,5 @@
using AntSK.Domain.Model.Enum;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Repositories
{

View File

@@ -1,11 +1,6 @@

using AntSK.Domain.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Repositories.Base;
namespace AntSK.Domain.Repositories
{

View File

@@ -1,11 +1,6 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using AntSK.Domain.Model;
using SqlSugar;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using AntSK.Domain.Model;
namespace AntSK.Domain.Repositories.Base
{

View File

@@ -1,13 +1,7 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using AntSK.Domain.Map;
using AntSK.Domain.Map;
using AntSK.Domain.Model;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using System.Linq.Expressions;
namespace AntSK.Domain.Repositories.Base
@@ -15,7 +9,7 @@ namespace AntSK.Domain.Repositories.Base
public class Repository<T> : SimpleClient<T> where T : class, new()
{
public Repository( ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null
public Repository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null
{
if (context == null)

View File

@@ -1,13 +1,6 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AntSK.Domain.Options;
using AntSK.Domain.Utils;
using AntSK.Domain.Options;
using SqlSugar;
using System.Reflection;
using Microsoft.Extensions.Configuration;
namespace AntSK.Domain.Repositories.Base
{
@@ -17,7 +10,8 @@ namespace AntSK.Domain.Repositories.Base
/// <summary>
/// sqlserver连接
/// </summary>
public static SqlSugarScope SqlScope() {
public static SqlSugarScope SqlScope()
{
string DBType = DBConnectionOption.DbType;
string ConnectionString = DBConnectionOption.ConnectionStrings;
@@ -43,12 +37,12 @@ namespace AntSK.Domain.Repositories.Base
}
};
DbType dbType = (DbType)Enum.Parse(typeof(DbType), DBType);
config.DbType = dbType;
var scope= new SqlSugarScope(config, Db =>
config.DbType = dbType;
var scope = new SqlSugarScope(config, Db =>
{
});
return scope;
}
}
}
}

View File

@@ -1,11 +1,6 @@
using AntSK.Domain.Model.Enum;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Repositories
{
@@ -25,7 +20,7 @@ namespace AntSK.Domain.Repositories
/// 模型类型
/// </summary>
[Required]
public AIModelType AIModelType { get; set; }= AIModelType.Chat;
public AIModelType AIModelType { get; set; } = AIModelType.Chat;
/// <summary>
/// 模型地址
/// </summary>

View File

@@ -1,11 +1,6 @@

using AntSK.Domain.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Repositories.Base;
namespace AntSK.Domain.Repositories
{

View File

@@ -1,9 +1,4 @@
using AntSK.Domain.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Repositories
{

View File

@@ -1,9 +1,4 @@
using AntSK.Domain.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Repositories
{

View File

@@ -1,10 +1,5 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Repositories
{

View File

@@ -1,11 +1,6 @@

using AntSK.Domain.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Repositories.Base;
namespace AntSK.Domain.Repositories
{

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AntSK.Domain.Utils
namespace AntSK.Domain.Utils
{
public static class ConvertUtils
{

View File

@@ -1,10 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace AntSK.Domain.Utils
{

View File

@@ -1,5 +1,4 @@
using System;
using System.Buffers.Text;
using System.Buffers.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

View File

@@ -1,11 +1,4 @@
using AntSK.Domain.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace AntSK.Domain.Utils
{
@@ -23,7 +16,7 @@ namespace AntSK.Domain.Utils
Regex regex = new Regex(@"(https?)://([^/:]+)(:\d+)?/(.*)");
Match match = regex.Match(_endPoint);
if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development" && request.Content != null)
{
{
string requestBody = await request.Content.ReadAsStringAsync();
//便于调试查看请求prompt
Console.WriteLine(requestBody);
@@ -47,14 +40,14 @@ namespace AntSK.Domain.Utils
{
// 这里是你要修改的 URL
Scheme = $"{xieyi}://{hostnew}/",
Host = host,
Host = host,
Path = route + "v1/chat/completions",
};
if (port.ConvertToInt32() != 0)
{
uriBuilder.Port = port.ConvertToInt32();
}
request.RequestUri = uriBuilder.Uri;
break;
@@ -83,9 +76,9 @@ namespace AntSK.Domain.Utils
}
public class OpenAIHttpClientHandlerUtil
public class OpenAIHttpClientHandlerUtil
{
public static HttpClient GetHttpClient( string endPoint)
public static HttpClient GetHttpClient(string endPoint)
{
var handler = new OpenAIHttpClientHandler(endPoint.ConvertToString());
var httpClient = new HttpClient(handler);

View File

@@ -1,6 +1,4 @@
using BCrypt.Net;
namespace AntSK.Domain.Utils
namespace AntSK.Domain.Utils
{
public class PasswordUtil
{

View File

@@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace AntSK.Domain.Utils
{

View File

@@ -22,13 +22,13 @@
</summary>
<param name="_taskBroker"></param>
</member>
<member name="M:AntSK.Controllers.LLamaSharpController.chat(AntSK.Models.OpenAIModel)">
<member name="M:AntSK.Controllers.LLamaSharpController.chat(AntSK.Domain.Domain.Dto.OpenAIModel)">
<summary>
本地会话接口
</summary>
<returns></returns>
</member>
<member name="M:AntSK.Controllers.LLamaSharpController.embedding(AntSK.Models.OpenAIEmbeddingModel)">
<member name="M:AntSK.Controllers.LLamaSharpController.embedding(AntSK.Domain.Domain.Dto.OpenAIEmbeddingModel)">
<summary>
本地嵌入接口
</summary>
@@ -45,7 +45,7 @@
对外接口
</summary>
</member>
<member name="M:AntSK.Controllers.OpenController.chat(AntSK.Models.OpenAIModel)">
<member name="M:AntSK.Controllers.OpenController.chat(AntSK.Domain.Domain.Dto.OpenAIModel)">
<summary>
对话接口
</summary>
@@ -136,7 +136,7 @@
<param name="app"></param>
<returns></returns>
</member>
<member name="M:AntSK.Services.OpenApi.OpenApiService.HistorySummarize(AntSK.Domain.Repositories.Apps,AntSK.Models.OpenAIModel)">
<member name="M:AntSK.Services.OpenApi.OpenApiService.HistorySummarize(AntSK.Domain.Repositories.Apps,AntSK.Domain.Domain.Dto.OpenAIModel)">
<summary>
历史会话的会话总结
</summary>

View File

@@ -1,15 +1,12 @@
using AntDesign;
using AntDesign.ProLayout;
using Microsoft.AspNetCore.Components;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AntSK.Domain.Options;
using AntSK.Models;
using AntSK.Services;
using AntSK.Services.Auth;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using System.Security.Claims;
using AntSK.Services.Auth;
using AntSK.Domain.Options;
namespace AntSK.Components
{
@@ -56,7 +53,7 @@ namespace AntSK.Components
[Inject] public AuthenticationStateProvider AuthenticationStateProvider { get; set; }
[Inject] protected MessageService? Message { get; set; }
private ClaimsPrincipal context => ((AntSKAuthProvider)AuthenticationStateProvider).GetCurrentUser();
private ClaimsPrincipal context => ((AntSKAuthProvider)AuthenticationStateProvider).GetCurrentUser();
protected override async Task OnInitializedAsync()
{
@@ -86,7 +83,7 @@ namespace AntSK.Components
{
NavigationManager.NavigateTo("/setting/user/info/" + context.Identity.Name);
}
else
else
{
_ = Message.Info("管理员无需设置", 2);
}

View File

@@ -1,7 +1,4 @@
using AntDesign;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Net.NetworkInformation;
using Microsoft.AspNetCore.Mvc;
namespace AntSK.Controllers
{
@@ -32,10 +29,10 @@ namespace AntSK.Controllers
}
string extension = Path.GetExtension(file.FileName);
string fileid=Guid.NewGuid().ToString();
string fileid = Guid.NewGuid().ToString();
// 组合目标路径
var uploads = Path.Combine(uploadsFolderPath, fileid+extension);
var uploads = Path.Combine(uploadsFolderPath, fileid + extension);
// 保存文件至目标路径
using var fileStream = System.IO.File.Create(uploads);
using var uploadStream = file.OpenReadStream();

View File

@@ -1,6 +1,5 @@
using Microsoft.AspNetCore.Http;
using AntSK.Domain.Repositories;
using Microsoft.AspNetCore.Mvc;
using AntSK.Domain.Repositories;
namespace AntSK.Controllers
{

View File

@@ -1,14 +1,10 @@
using AntSK.Domain.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using static AntSK.Pages.KmsPage.KmsDetail;
using System;
using AntSK.Domain.Repositories;
using AntSK.BackgroundTask;
using AntSK.Domain.Domain.Interface;
using Microsoft.KernelMemory.Configuration;
using AntSK.Domain.Model.Enum;
using AntSK.Domain.Map;
using AntSK.BackgroundTask;
using AntSK.Domain.Model;
using AntSK.Domain.Model.Enum;
using AntSK.Domain.Repositories;
using Microsoft.AspNetCore.Mvc;
namespace AntSK.Controllers
{
@@ -27,14 +23,14 @@ namespace AntSK.Controllers
IKmsDetails_Repositories kmsDetails_Repositories,
IKMService iKMService,
BackgroundTaskBroker<ImportKMSTaskReq> taskBroker
)
)
{
_kmsDetails_Repositories = kmsDetails_Repositories;
_iKMService = iKMService;
_taskBroker = taskBroker;
}
[HttpPost]
public async Task<IActionResult> ImportKMSTask(ImportKMSTaskDTO model)
public async Task<IActionResult> ImportKMSTask(ImportKMSTaskDTO model)
{
Console.WriteLine("api/kms/ImportKMSTask 开始");
ImportKMSTaskReq req = model.ToDTO<ImportKMSTaskReq>();

View File

@@ -1,8 +1,6 @@
using AntSK.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using AntSK.Domain.Utils;
using AntSK.Domain.Domain.Dto;
using AntSK.Services.LLamaSharp;
using Microsoft.AspNetCore.Mvc;
namespace AntSK.Controllers
{
@@ -39,7 +37,7 @@ namespace AntSK.Controllers
public async Task embedding(OpenAIEmbeddingModel model)
{
Console.WriteLine("开始llama/v1/embeddings");
await _lLamaSharpService.Embedding(model,HttpContext);
await _lLamaSharpService.Embedding(model, HttpContext);
Console.WriteLine("结束llama/v1/embeddings");
}

View File

@@ -1,10 +1,6 @@
using AntSK.Domain.Model;
using AntSK.Domain.Repositories;
using AntSK.Domain.Domain.Dto;
using AntSK.Domain.Utils;
using AntSK.Models;
using AntSK.Models.OpenAPI;
using AntSK.Services.OpenApi;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace AntSK.Controllers
@@ -25,7 +21,7 @@ namespace AntSK.Controllers
public async Task chat(OpenAIModel model)
{
string sk = HttpContext.Request.Headers["Authorization"].ConvertToString();
await _openApiService.Chat(model,sk, HttpContext);
await _openApiService.Chat(model, sk, HttpContext);
}
}
}

View File

@@ -1,6 +1,4 @@
using System;
namespace AntSK
namespace AntSK
{
public static class DateTimeExtension
{

View File

@@ -1,5 +1,3 @@
using System;
namespace AntSK.Models
{
public class ActivitiesType

View File

@@ -1,6 +1,4 @@
using System;
namespace AntSK.Models
namespace AntSK.Models
{
public class StepFormModel
{

View File

@@ -1,6 +1,5 @@
using System;
using System.Text.Json.Serialization;
using AntSK.Domain.Utils;
using System.Text.Json.Serialization;
namespace AntSK.Models
{

View File

@@ -1,8 +1,6 @@
using AntDesign;
using Microsoft.AspNetCore.Components;
using AntSK.Domain.Repositories;
using AntSK.Models;
using System.IO;
using Microsoft.AspNetCore.Components;
using System.Text.RegularExpressions;
namespace AntSK.Pages.ApiPage
@@ -20,7 +18,7 @@ namespace AntSK.Pages.ApiPage
[Inject]
protected MessageService? Message { get; set; }
private Apis _apiModel = new Apis() ;
private Apis _apiModel = new Apis();
protected override async Task OnInitializedAsync()
@@ -38,7 +36,7 @@ namespace AntSK.Pages.ApiPage
{
//新增
_apiModel.Id = Guid.NewGuid().ToString();
if (_apis_Repositories.IsAny(p => p.Name == _apiModel.Name))
{
_ = Message.Error("名称已存在!", 2);
@@ -54,7 +52,8 @@ namespace AntSK.Pages.ApiPage
_apis_Repositories.Insert(_apiModel);
}
else {
else
{
//修改
_apis_Repositories.Update(_apiModel);
@@ -64,7 +63,8 @@ namespace AntSK.Pages.ApiPage
}
private void Back() {
private void Back()
{
NavigationManager.NavigateTo("/plugins/apilist");
}
}

View File

@@ -1,16 +1,14 @@
using AntDesign;
using Microsoft.AspNetCore.Components;
using AntSK.Domain.Repositories;
using AntSK.Models;
using AntSK.Services;
using Microsoft.AspNetCore.Components;
namespace AntSK.Pages.ApiPage
{
public partial class ApiList
{
private Apis [] _data = { };
private Apis[] _data = { };
[Inject]
[Inject]
protected IApis_Repositories _apis_Repositories { get; set; }
[Inject]
IConfirmService _confirmService { get; set; }
@@ -33,7 +31,7 @@ namespace AntSK.Pages.ApiPage
{
data = await _apis_Repositories.GetListAsync(p => p.Name.Contains(searchKey));
}
list.AddRange(data);
_data = list.ToArray();
await InvokeAsync(StateHasChanged);
@@ -62,7 +60,7 @@ namespace AntSK.Pages.ApiPage
if (result == ConfirmResult.Yes)
{
await _apis_Repositories.DeleteAsync(id);
await InitData("");
await InitData("");
}
}
}

View File

@@ -1,9 +1,7 @@
using AntDesign;
using Microsoft.AspNetCore.Components;
using AntSK.Domain.Repositories;
using AntSK.Models;
using System.IO;
using AntSK.Domain.Model.Enum;
using AntSK.Domain.Repositories;
using Microsoft.AspNetCore.Components;
namespace AntSK.Pages.AppPage
{
@@ -27,9 +25,9 @@ namespace AntSK.Pages.AppPage
[Inject]
protected IAIModels_Repositories _aimodels_Repositories { get; set; }
private Apps _appModel = new Apps() ;
private Apps _appModel = new Apps();
IEnumerable <string> kmsIds;
IEnumerable<string> kmsIds;
private List<Kmss> _kmsList = new List<Kmss>();
@@ -43,16 +41,16 @@ namespace AntSK.Pages.AppPage
{
await base.OnInitializedAsync();
_kmsList = _kmss_Repositories.GetList();
_apiList= _apis_Repositories.GetList();
_apiList = _apis_Repositories.GetList();
_chatList= _aimodels_Repositories.GetList(p => p.AIModelType == AIModelType.Chat);
_chatList = _aimodels_Repositories.GetList(p => p.AIModelType == AIModelType.Chat);
if (!string.IsNullOrEmpty(AppId))
{
//查看
_appModel= _apps_Repositories.GetFirst(p => p.Id == AppId);
_appModel = _apps_Repositories.GetFirst(p => p.Id == AppId);
kmsIds = _appModel.KmsIdList?.Split(",");
apiIds= _appModel.ApiFunctionList?.Split(",");
apiIds = _appModel.ApiFunctionList?.Split(",");
}
@@ -80,27 +78,29 @@ namespace AntSK.Pages.AppPage
//新增
_appModel.Id = Guid.NewGuid().ToString();
//秘钥
_appModel.SecretKey="sk-"+ Guid.NewGuid().ToString();
_appModel.SecretKey = "sk-" + Guid.NewGuid().ToString();
if (_apps_Repositories.IsAny(p => p.Name == _appModel.Name))
{
_ = Message.Error("名称已存在!", 2);
return;
}
_apps_Repositories.Insert(_appModel);
}
else {
else
{
//修改
_apps_Repositories.Update(_appModel);
}
//NavigationManager.NavigateTo($"/app/detail/{_appModel.Id}");
NavigationManager.NavigateTo($"/applist");
}
private void Back() {
private void Back()
{
NavigationManager.NavigateTo("/applist");
}
}

View File

@@ -1,16 +1,14 @@
using AntDesign;
using Microsoft.AspNetCore.Components;
using AntSK.Domain.Repositories;
using AntSK.Models;
using AntSK.Services;
using Microsoft.AspNetCore.Components;
namespace AntSK.Pages.AppPage
{
public partial class AppList
{
private Apps [] _data = { };
private Apps[] _data = { };
[Inject]
[Inject]
protected IApps_Repositories _apps_Repositories { get; set; }
[Inject]
IConfirmService _confirmService { get; set; }
@@ -33,7 +31,7 @@ namespace AntSK.Pages.AppPage
{
data = await _apps_Repositories.GetListAsync(p => p.Name.Contains(searchKey));
}
list.AddRange(data);
_data = list.ToArray();
await InvokeAsync(StateHasChanged);
@@ -68,7 +66,7 @@ namespace AntSK.Pages.AppPage
if (result == ConfirmResult.Yes)
{
await _apps_Repositories.DeleteAsync(id);
await InitData("");
await InitData("");
}
}
}

View File

@@ -1,9 +1,7 @@
using AntDesign;
using AntSK.Domain.Model;
using AntSK.Domain.Domain.Dto;
using AntSK.Domain.Repositories;
using AntSK.Models;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.AspNetCore.Components;
using Newtonsoft.Json;
@@ -53,7 +51,7 @@ namespace AntSK.Pages.AppPage
await base.OnInitializedAsync();
_appModel = _apps_Repositories.GetFirst(p => p.Id == AppId);
_openApiUrl = NavigationManager.BaseUri + "api/v1/chat/completions";
_openChatUrl= NavigationManager.BaseUri + "openchat/"+AppId;
_openChatUrl = NavigationManager.BaseUri + "openchat/" + AppId;
GetDesc();
GetScript();
}
@@ -63,7 +61,7 @@ namespace AntSK.Pages.AppPage
_desc = @$"为了方便其他应用对接接口符合openai规范省略了温度TopP等参数。{Environment.NewLine}BaseUrl:{Environment.NewLine}{_openApiUrl} {Environment.NewLine}headers:{Environment.NewLine}Authorization: ""{_appModel.SecretKey}"" {Environment.NewLine}Body: {Environment.NewLine}{JsonConvert.SerializeObject(new OpenAIModel() { messages = new List<OpenAIMessage>() { new OpenAIMessage() { role = "user", content = "" } } }, Formatting.Indented)}";
}
private void GetScript()
private void GetScript()
{
_script = $"<script src=\"{NavigationManager.BaseUri}js/iframe.js\" data-width=\"40rem\" data-height=\"80vh\" id=\"antsk-iframe\" data-src=\"{NavigationManager.BaseUri}openchat/{AppId}\" data-color=\"#4e83fd\" data-message-icon-url=\"{NavigationManager.BaseUri}assets/ai.png\"></script>";
}

View File

@@ -3,22 +3,12 @@ using AntSK.Domain.Domain.Interface;
using AntSK.Domain.Model;
using AntSK.Domain.Repositories;
using AntSK.Domain.Utils;
using Azure.AI.OpenAI;
using Azure.Core;
using DocumentFormat.OpenXml.EMMA;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Wordprocessing;
using MarkdownSharp;
using Microsoft.AspNetCore.Components;
using Microsoft.KernelMemory;
using Microsoft.OpenApi.Models;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Newtonsoft.Json;
using RestSharp;
using SqlSugar;
using System;
using System.Text;
namespace AntSK.Pages.ChatPage
@@ -95,7 +85,7 @@ namespace AntSK.Pages.ChatPage
{
Sendding = false;
Console.WriteLine("异常:" + ex.Message);
_ = Message.Error("异常:"+ex.Message, 2);
_ = Message.Error("异常:" + ex.Message, 2);
}
}
protected async Task OnCopyAsync(MessageInfo item)
@@ -106,7 +96,8 @@ namespace AntSK.Pages.ChatPage
});
}
protected async Task OnClearAsync() {
protected async Task OnClearAsync()
{
if (MessageList.Count > 0)
{
var content = "是否要清理会话记录";
@@ -130,7 +121,7 @@ namespace AntSK.Pages.ChatPage
Apps app = _apps_Repositories.GetFirst(p => p.Id == AppId);
if (MessageList.Count > 0)
{
msg = await HistorySummarize(app,questions);
msg = await HistorySummarize(app, questions);
}
switch (app.Type)
@@ -167,7 +158,7 @@ namespace AntSK.Pages.ChatPage
{
filters.Add(new MemoryFilter().ByTag("kmsid", kmsid));
}
var xlresult = await _memory.SearchAsync(questions, index: "kms", filters: filters);
var xlresult = await _memory.SearchAsync(questions, index: "kms", filters: filters);
string dataMsg = "";
if (xlresult != null)
{
@@ -175,7 +166,7 @@ namespace AntSK.Pages.ChatPage
{
foreach (var part in item.Partitions)
{
dataMsg += $"[file:{item.SourceName};Relevance:{(part.Relevance*100).ToString("F2")}%]:{part.Text}{Environment.NewLine}";
dataMsg += $"[file:{item.SourceName};Relevance:{(part.Relevance * 100).ToString("F2")}%]:{part.Text}{Environment.NewLine}";
//输出调试信息
var markdown = new Markdown();
string sourceName = item.SourceName;
@@ -187,10 +178,10 @@ namespace AntSK.Pages.ChatPage
RelevantSources.Add(new RelevantSource() { SourceName = sourceName, Text = markdown.Transform(part.Text), Relevance = part.Relevance });
}
}
KernelFunction jsonFun = _kernel.Plugins.GetFunction("KMSPlugin", "Ask");
var chatResult = _kernel.InvokeStreamingAsync(function: jsonFun,
arguments: new KernelArguments() { ["doc"] = dataMsg, ["history"] = msg, ["questions"]=questions });
var chatResult = _kernel.InvokeStreamingAsync(function: jsonFun,
arguments: new KernelArguments() { ["doc"] = dataMsg, ["history"] = msg, ["questions"] = questions });
MessageInfo info = null;
var markdown1 = new Markdown();
@@ -233,19 +224,19 @@ namespace AntSK.Pages.ChatPage
private async Task SendChat(string questions, string msg, Apps app)
{
var _kernel = _kernelService.GetKernelByApp(app);
if (string.IsNullOrEmpty(app.Prompt)||!app.Prompt.Contains("{{$input}}"))
if (string.IsNullOrEmpty(app.Prompt) || !app.Prompt.Contains("{{$input}}"))
{
//如果模板为空,给默认提示词
app.Prompt = app.Prompt.ConvertToString()+"{{$input}}";
app.Prompt = app.Prompt.ConvertToString() + "{{$input}}";
}
var temperature = app.Temperature/100;//存的是0~100需要缩小
OpenAIPromptExecutionSettings settings = new() {Temperature= temperature };
var temperature = app.Temperature / 100;//存的是0~100需要缩小
OpenAIPromptExecutionSettings settings = new() { Temperature = temperature };
if (!string.IsNullOrEmpty(app.ApiFunctionList))
{
_kernelService.ImportFunctionsByApp(app, _kernel);
settings.ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions;
}
var func = _kernel.CreateFunctionFromPrompt(app.Prompt, settings);
var chatResult = _kernel.InvokeStreamingAsync(function: func, arguments: new KernelArguments() { ["input"] = msg });
MessageInfo info = null;
@@ -265,7 +256,7 @@ namespace AntSK.Pages.ChatPage
else
{
info.HtmlAnswers += content.ConvertToString();
await Task.Delay(50);
await Task.Delay(50);
}
await InvokeAsync(StateHasChanged);
}
@@ -274,18 +265,18 @@ namespace AntSK.Pages.ChatPage
{
info!.HtmlAnswers = markdown.Transform(info.HtmlAnswers);
}
await InvokeAsync(StateHasChanged);
}
/// <summary>
/// 历史会话的会话总结
/// </summary>
/// <param name="questions"></param>
/// <returns></returns>
private async Task<string> HistorySummarize(Apps app,string questions)
private async Task<string> HistorySummarize(Apps app, string questions)
{
var _kernel = _kernelService.GetKernelByApp(app);
if (MessageList.Count > 1)
@@ -308,13 +299,13 @@ namespace AntSK.Pages.ChatPage
var msg = await _kernelService.HistorySummarize(_kernel, questions, history.ToString());
return msg;
}
else
else
{
var msg = $"history{history.ToString()}{Environment.NewLine} user{questions}"; ;
return msg;
}
}
}
else
else
{
return questions;
}

View File

@@ -1,24 +1,15 @@
using AntDesign;
using AntSK.Domain.Domain.Interface;
using AntSK.Domain.Model;
using AntSK.Domain.Repositories;
using AntSK.Domain.Utils;
using Azure.AI.OpenAI;
using Azure.Core;
using DocumentFormat.OpenXml.EMMA;
using MarkdownSharp;
using Microsoft.AspNetCore.Components;
using Microsoft.KernelMemory;
using Microsoft.OpenApi.Models;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Text;
using AntSK.Domain.Utils;
using AntSK.Domain.Domain.Interface;
using AntSK.Domain.Domain.Service;
namespace AntSK.Pages.ChatPage
{
@@ -26,7 +17,7 @@ namespace AntSK.Pages.ChatPage
{
[Parameter]
public string AppId { get; set; }
[Inject]
[Inject]
protected MessageService? Message { get; set; }
[Inject]
protected IApps_Repositories _apps_Repositories { get; set; }
@@ -52,7 +43,7 @@ namespace AntSK.Pages.ChatPage
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
app = _apps_Repositories.GetFirst(p=>p.Id==AppId);
app = _apps_Repositories.GetFirst(p => p.Id == AppId);
}
protected async Task OnClearAsync()
@@ -101,7 +92,7 @@ namespace AntSK.Pages.ChatPage
{
Sendding = false;
Console.WriteLine("异常:" + ex.Message);
_ = Message.Error("异常:"+ex.Message, 2);
_ = Message.Error("异常:" + ex.Message, 2);
}
}
@@ -125,10 +116,10 @@ namespace AntSK.Pages.ChatPage
{
string msg = "";
//处理多轮会话
Apps app=_apps_Repositories.GetFirst(p => p.Id == AppId);
Apps app = _apps_Repositories.GetFirst(p => p.Id == AppId);
if (MessageList.Count > 0)
{
msg = await HistorySummarize(app,questions);
msg = await HistorySummarize(app, questions);
}
switch (app.Type)
{
@@ -221,7 +212,7 @@ namespace AntSK.Pages.ChatPage
/// <returns></returns>
private async Task SendChat(string questions, string msg, Apps app)
{
var _kernel= _kernelService.GetKernelByApp(app);
var _kernel = _kernelService.GetKernelByApp(app);
if (string.IsNullOrEmpty(app.Prompt) || !app.Prompt.Contains("{{$input}}"))
{
//如果模板为空,给默认提示词
@@ -246,7 +237,7 @@ namespace AntSK.Pages.ChatPage
{
info = new MessageInfo();
info.ID = Guid.NewGuid().ToString();
info.Context = content.ConvertToString();
info.Context = content.ConvertToString();
info.HtmlAnswers = content.ConvertToString();
info.CreateTime = DateTime.Now;
@@ -255,7 +246,7 @@ namespace AntSK.Pages.ChatPage
else
{
info.HtmlAnswers += content.ConvertToString();
await Task.Delay(50);
await Task.Delay(50);
}
await InvokeAsync(StateHasChanged);
}
@@ -269,7 +260,7 @@ namespace AntSK.Pages.ChatPage
/// </summary>
/// <param name="questions"></param>
/// <returns></returns>
private async Task<string> HistorySummarize(Apps app,string questions)
private async Task<string> HistorySummarize(Apps app, string questions)
{
var _kernel = _kernelService.GetKernelByApp(app);
if (MessageList.Count > 1)
@@ -298,7 +289,7 @@ namespace AntSK.Pages.ChatPage
return msg;
}
}
else
else
{
return questions;
}

View File

@@ -1,10 +1,7 @@
using AntDesign;
using Microsoft.AspNetCore.Components;
using AntSK.Domain.Repositories;
using AntSK.Models;
using System.IO;
using AntSK.Domain.Model.Enum;
using DocumentFormat.OpenXml.Wordprocessing;
using AntSK.Domain.Repositories;
using Microsoft.AspNetCore.Components;
namespace AntSK.Pages.KmsPage
{
@@ -31,12 +28,12 @@ namespace AntSK.Pages.KmsPage
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
_chatList = _aimodels_Repositories.GetList(p=>p.AIModelType==AIModelType.Chat);
_chatList = _aimodels_Repositories.GetList(p => p.AIModelType == AIModelType.Chat);
_embeddingList = _aimodels_Repositories.GetList(p => p.AIModelType == AIModelType.Embedding);
if (!string.IsNullOrEmpty(KmsId))
{
//查看
_kmsModel =await _kmss_Repositories.GetFirstAsync(p => p.Id == KmsId);
_kmsModel = await _kmss_Repositories.GetFirstAsync(p => p.Id == KmsId);
}
}
private void HandleSubmit()
@@ -60,7 +57,7 @@ namespace AntSK.Pages.KmsPage
{
_ = Message.Error("名称已存在!", 2);
return;
}
}
_kmss_Repositories.Insert(_kmsModel);
}
else
@@ -71,5 +68,5 @@ namespace AntSK.Pages.KmsPage
NavigationManager.NavigateTo("/kmslist");
}
}
}
}

View File

@@ -1,23 +1,13 @@
using AntDesign;
using AntSK.BackgroundTask;
using AntSK.Domain.Domain.Dto;
using AntSK.Domain.Domain.Interface;
using AntSK.Domain.Domain.Service;
using AntSK.Domain.Model;
using AntSK.Domain.Repositories;
using AntSK.Domain.Utils;
using AntSK.Models;
using AntSK.Services;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Vml.Spreadsheet;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.KernelMemory;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Security.Claims;
using System.Security.Policy;
namespace AntSK.Pages.KmsPage
{
@@ -54,7 +44,7 @@ namespace AntSK.Pages.KmsPage
{"success", ProgressStatus.Success}
};
private List<KmsDetails> _data =new List<KmsDetails>();
private List<KmsDetails> _data = new List<KmsDetails>();
[Inject]
protected IConfirmService _confirmService { get; set; }
@@ -62,7 +52,7 @@ namespace AntSK.Pages.KmsPage
protected IKmsDetails_Repositories _kmsDetails_Repositories { get; set; }
[Inject]
protected IKmss_Repositories _kmss_Repositories { get; set; }
protected IKmss_Repositories _kmss_Repositories { get; set; }
private MemoryServerless _memory { get; set; }
[Inject]
@@ -78,14 +68,14 @@ namespace AntSK.Pages.KmsPage
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
_data =await _kmsDetails_Repositories.GetListAsync(p => p.KmsId == KmsId);
_data = await _kmsDetails_Repositories.GetListAsync(p => p.KmsId == KmsId);
var km = _kmss_Repositories.GetFirst(p => p.Id == KmsId);
//使用知识库设置的参数,
_memory = iKMService.GetMemoryByKMS(km.Id);
}
//刷新
private async Task Refresh()
private async Task Refresh()
{
_data = await _kmsDetails_Repositories.GetListAsync(p => p.KmsId == KmsId);
}
@@ -105,7 +95,7 @@ namespace AntSK.Pages.KmsPage
{
try
{
var result= await _httpService.PostAsync(NavigationManager.BaseUri + "api/KMS/ImportKMSTask", new ImportKMSTaskDTO()
var result = await _httpService.PostAsync(NavigationManager.BaseUri + "api/KMS/ImportKMSTask", new ImportKMSTaskDTO()
{
ImportType = ImportType.Url,
KmsId = KmsId,
@@ -117,7 +107,7 @@ namespace AntSK.Pages.KmsPage
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message+" ---- "+ex.StackTrace);
Console.WriteLine(ex.Message + " ---- " + ex.StackTrace);
}
}
private void UrlHandleCancel(MouseEventArgs e)
@@ -141,7 +131,7 @@ namespace AntSK.Pages.KmsPage
{
try
{
var result =await _httpService.PostAsync(NavigationManager.BaseUri + "api/KMS/ImportKMSTask", new ImportKMSTaskDTO()
var result = await _httpService.PostAsync(NavigationManager.BaseUri + "api/KMS/ImportKMSTask", new ImportKMSTaskDTO()
{
ImportType = ImportType.Text,
KmsId = KmsId,
@@ -215,17 +205,17 @@ namespace AntSK.Pages.KmsPage
"text/x-markdown",
"text/markdown"
};
var IsType = types.Contains( file.Type );
if (!IsType&& file.Ext != ".md")
var IsType = types.Contains(file.Type);
if (!IsType && file.Ext != ".md")
{
_message.Error("文件格式错误,请重新选择!");
}
var IsLt500K = file.Size < 1024 *1024* 100;
var IsLt500K = file.Size < 1024 * 1024 * 100;
if (!IsLt500K)
{
_message.Error("文件需不大于100MB!");
}
return IsType && IsLt500K;
}
private void OnSingleCompleted(UploadInfo fileinfo)
@@ -233,8 +223,8 @@ namespace AntSK.Pages.KmsPage
if (fileinfo.File.State == UploadState.Success)
{
filePath=fileinfo.File.Url = fileinfo.File.Response;
fileName= fileinfo.File.FileName;
filePath = fileinfo.File.Url = fileinfo.File.Response;
fileName = fileinfo.File.FileName;
}
}
@@ -244,7 +234,7 @@ namespace AntSK.Pages.KmsPage
}
private async Task DeleteFile(string fileid)
{
{
try
{
var content = "是否确认删除此文档?";

View File

@@ -1,6 +1,5 @@
using AntSK.Domain.Domain.Dto;
using AntSK.Domain.Domain.Interface;
using DocumentFormat.OpenXml.Office2010.Excel;
using Microsoft.AspNetCore.Components;
namespace AntSK.Pages.KmsPage
@@ -15,7 +14,7 @@ namespace AntSK.Pages.KmsPage
[Inject]
protected IKMService iKMService { get; set; }
private List<KMFile> _data = new List<KMFile>() ;
private List<KMFile> _data = new List<KMFile>();
protected override async Task OnInitializedAsync()
{
@@ -23,8 +22,9 @@ namespace AntSK.Pages.KmsPage
_data = await iKMService.GetDocumentByFileID(KmsId, FileId);
}
private void NavigateBack() {
private void NavigateBack()
{
NavigationManager.NavigateTo($"/kms/detail/{KmsId}");
}
}
}
}

View File

@@ -1,14 +1,7 @@
using AntDesign;
using Microsoft.AspNetCore.Components;
using AntSK.Domain.Repositories;
using AntSK.Models;
using AntSK.Services;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Drawing.Charts;
using System.Collections.Generic;
using System;
using Microsoft.KernelMemory;
using AntSK.Domain.Domain.Interface;
using AntSK.Domain.Repositories;
using Microsoft.AspNetCore.Components;
namespace AntSK.Pages
{
@@ -53,11 +46,11 @@ namespace AntSK.Pages
{
data = await _kmss_Repositories.GetListAsync();
}
else
else
{
data = await _kmss_Repositories.GetListAsync(p => p.Name.Contains(searchKey));
}
list.AddRange(data);
_data = list.ToArray();
await InvokeAsync(StateHasChanged);
@@ -88,7 +81,7 @@ namespace AntSK.Pages
var content = "删除知识库会一起删除导入的知识文档,无法还原。是否确认删除此知识库?";
var title = "删除";
var result= await _confirmService.Show(content, title, ConfirmButtons.YesNo);
var result = await _confirmService.Show(content, title, ConfirmButtons.YesNo);
if (result == ConfirmResult.Yes)
{
var _memory = _kMService.GetMemoryByKMS(id);
@@ -104,7 +97,7 @@ namespace AntSK.Pages
await _kmss_Repositories.DeleteAsync(id);
await InitData("");
}
}
}
}
}

View File

@@ -1,9 +1,7 @@
using AntDesign.ProLayout;
using Microsoft.AspNetCore.Components;
using System.Collections.Generic;
using System.Threading.Tasks;
using AntSK.Models;
using AntSK.Services;
using Microsoft.AspNetCore.Components;
namespace AntSK.Pages.Profile
{

View File

@@ -1,7 +1,6 @@
using Microsoft.AspNetCore.Components;
using System.Threading.Tasks;
using AntSK.Models;
using AntSK.Services;
using Microsoft.AspNetCore.Components;
namespace AntSK.Pages.Profile
{

View File

@@ -1,12 +1,8 @@
using AntDesign;
using AntDesign.ProLayout;
using AntSK.Domain.Options;
using AntSK.Domain.Repositories;
using AntSK.Domain.Utils;
using DocumentFormat.OpenXml.InkML;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.AspNetCore.Components;
using System;
namespace AntSK.Pages.Setting.AIModel
{
@@ -28,7 +24,7 @@ namespace AntSK.Pages.Setting.AIModel
await base.OnInitializedAsync();
if (!string.IsNullOrEmpty(ModelId))
{
_aiModel= _aimodels_Repositories.GetFirst(p => p.Id == ModelId);
_aiModel = _aimodels_Repositories.GetFirst(p => p.Id == ModelId);
}
}
@@ -54,7 +50,7 @@ namespace AntSK.Pages.Setting.AIModel
//新增
_aiModel.Id = Guid.NewGuid().ToString();
if (_aimodels_Repositories.IsAny(p => p.ModelDescription == _aiModel.ModelDescription ))
if (_aimodels_Repositories.IsAny(p => p.ModelDescription == _aiModel.ModelDescription))
{
_ = Message.Error("模型描述已存在!", 2);
return;
@@ -69,7 +65,7 @@ namespace AntSK.Pages.Setting.AIModel
Back();
}
private void Back()
private void Back()
{
NavigationManager.NavigateTo("/setting/modellist");
}

View File

@@ -1,8 +1,6 @@
using AntDesign;
using AntSK.Domain.Repositories;
using AntSK.Models;
using AntSK.Services;
using DocumentFormat.OpenXml.Office2010.Excel;
using Microsoft.AspNetCore.Components;
namespace AntSK.Pages.Setting.AIModel
@@ -15,7 +13,7 @@ namespace AntSK.Pages.Setting.AIModel
private string _searchKeyword;
[Inject]
[Inject]
protected IAIModels_Repositories _aIModels_Repositories { get; set; }
[Inject]
@@ -27,7 +25,7 @@ namespace AntSK.Pages.Setting.AIModel
await base.OnInitializedAsync();
await InitData();
}
private async Task InitData(string searchKey=null)
private async Task InitData(string searchKey = null)
{
if (string.IsNullOrEmpty(searchKey))
{
@@ -35,21 +33,23 @@ namespace AntSK.Pages.Setting.AIModel
}
else
{
_data = _aIModels_Repositories.GetList(p=>p.ModelName.Contains(searchKey)||p.ModelDescription.Contains(searchKey));
_data = _aIModels_Repositories.GetList(p => p.ModelName.Contains(searchKey) || p.ModelDescription.Contains(searchKey));
}
await InvokeAsync(StateHasChanged);
}
public async Task OnSearch() {
public async Task OnSearch()
{
await InitData(_searchKeyword);
}
public async Task AddModel() {
public async Task AddModel()
{
NavigationManager.NavigateTo("/setting/model/add");
}
public void Edit(string modelid)
{
NavigationManager.NavigateTo("/setting/model/add/"+ modelid);
NavigationManager.NavigateTo("/setting/model/add/" + modelid);
}
public async Task Delete(string modelid)

View File

@@ -3,8 +3,6 @@ using AntDesign.ProLayout;
using AntSK.Domain.Options;
using AntSK.Domain.Repositories;
using AntSK.Domain.Utils;
using DocumentFormat.OpenXml.InkML;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.AspNetCore.Components;
namespace AntSK.Pages.Setting.User
@@ -27,11 +25,11 @@ namespace AntSK.Pages.Setting.User
await base.OnInitializedAsync();
if (!string.IsNullOrEmpty(UserId))
{
_userModel= _users_Repositories.GetFirst(p => p.Id == UserId);
_password= _userModel.Password;
_userModel = _users_Repositories.GetFirst(p => p.Id == UserId);
_password = _userModel.Password;
}
menuList = (await HttpClient.GetFromJsonAsync<MenuDataItem[]>("data/menu.json")).ToList().Where(p=>p.Key!= "setting").ToList();
_menuKeys= _userModel.MenuRole?.Split(",");
menuList = (await HttpClient.GetFromJsonAsync<MenuDataItem[]>("data/menu.json")).ToList().Where(p => p.Key != "setting").ToList();
_menuKeys = _userModel.MenuRole?.Split(",");
}
private void HandleSubmit()
@@ -52,13 +50,13 @@ namespace AntSK.Pages.Setting.User
_ = Message.Error("工号已存在!", 2);
return;
}
_userModel.Password=PasswordUtil.HashPassword(_userModel.Password);
_userModel.Password = PasswordUtil.HashPassword(_userModel.Password);
_users_Repositories.Insert(_userModel);
}
else
{
//修改
if (_userModel.Password!=_password)
if (_userModel.Password != _password)
{
_userModel.Password = PasswordUtil.HashPassword(_userModel.Password);
}
@@ -68,7 +66,7 @@ namespace AntSK.Pages.Setting.User
Back();
}
private void Back()
private void Back()
{
NavigationManager.NavigateTo("/setting/userlist");
}

View File

@@ -1,9 +1,7 @@
using AntDesign;
using AntSK.Domain.Repositories;
using AntSK.Domain.Utils;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
namespace AntSK.Pages.Setting.User
{
@@ -22,16 +20,16 @@ namespace AntSK.Pages.Setting.User
await base.OnInitializedAsync();
if (!string.IsNullOrEmpty(UserNo))
{
_userModel= _users_Repositories.GetFirst(p => p.No == UserNo);
_password= _userModel.Password;
_userModel = _users_Repositories.GetFirst(p => p.No == UserNo);
_password = _userModel.Password;
}
}
private async Task HandleSubmit()
{
//修改
if (_userModel.Password!=_password)
//修改
if (_userModel.Password != _password)
{
_userModel.Password = PasswordUtil.HashPassword(_userModel.Password);
}
@@ -41,7 +39,7 @@ namespace AntSK.Pages.Setting.User
_ = Message.Info("保存成功!", 2);
}
private async Task Back()
private async Task Back()
{
NavigationManager.NavigateTo("/");
}

View File

@@ -1,7 +1,6 @@
using AntDesign;
using AntSK.Domain.Repositories;
using AntSK.Models;
using AntSK.Services;
using Microsoft.AspNetCore.Components;
namespace AntSK.Pages.Setting.User
@@ -14,7 +13,7 @@ namespace AntSK.Pages.Setting.User
private string _searchKeyword;
[Inject]
[Inject]
protected IUsers_Repositories _users_Repositories { get; set; }
[Inject]
IConfirmService _confirmService { get; set; }
@@ -24,7 +23,7 @@ namespace AntSK.Pages.Setting.User
await base.OnInitializedAsync();
await InitData();
}
private async Task InitData(string searchKey=null)
private async Task InitData(string searchKey = null)
{
if (string.IsNullOrEmpty(searchKey))
{
@@ -32,21 +31,23 @@ namespace AntSK.Pages.Setting.User
}
else
{
_data = _users_Repositories.GetList(p=>p.Name.Contains(searchKey)||p.Describe.Contains(searchKey)||p.No.Contains(searchKey));
_data = _users_Repositories.GetList(p => p.Name.Contains(searchKey) || p.Describe.Contains(searchKey) || p.No.Contains(searchKey));
}
await InvokeAsync(StateHasChanged);
}
public async Task OnSearch() {
public async Task OnSearch()
{
await InitData(_searchKeyword);
}
public async Task AddUser() {
public async Task AddUser()
{
NavigationManager.NavigateTo("/setting/user/add");
}
public void Edit(string userid)
{
NavigationManager.NavigateTo("/setting/user/add/"+userid);
NavigationManager.NavigateTo("/setting/user/add/" + userid);
}
public async Task Delete(string modelid)

View File

@@ -1,13 +1,7 @@
using AntDesign;
using Microsoft.AspNetCore.Components;
using System.Threading.Tasks;
using AntSK.Models;
using AntSK.Services;
using AntSK.Domain.Options;
using SqlSugar;
using AntSK.Services.Auth;
using AntSK.Domain.Repositories;
using AntSK.Domain.Utils;
using Microsoft.AspNetCore.Components;
namespace AntSK.Pages.User
{
@@ -22,7 +16,7 @@ namespace AntSK.Pages.User
public async Task HandleSubmit()
{
//判断是否管理员
var loginFailed = await((AntSKAuthProvider)AuthenticationStateProvider).SignIn(_model.UserName, _model.Password);
var loginFailed = await ((AntSKAuthProvider)AuthenticationStateProvider).SignIn(_model.UserName, _model.Password);
if (loginFailed)
{
NavigationManager.NavigateTo("/");
@@ -32,6 +26,6 @@ namespace AntSK.Pages.User
{
Message.Error("账号密码错误", 2);
}
}
}
}
}

View File

@@ -1,28 +1,20 @@
using AntDesign.ProLayout;
using Microsoft.AspNetCore.Components;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using AntSK.Domain.Utils;
using AntSK.Services;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Common.Map;
using AntSK.Domain.Domain.BackGroundTask;
using AntSK.Domain.Model;
using AntSK.Domain.Options;
using AntSK.Domain.Repositories;
using AntSK.Domain.Utils;
using AntSK.Services.Auth;
using LLama.Native;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
using AntSK.Domain.Options;
using Microsoft.KernelMemory.ContentStorage.DevTools;
using Microsoft.KernelMemory.FileSystem.DevTools;
using Microsoft.KernelMemory;
using Microsoft.SemanticKernel;
using Microsoft.KernelMemory.Postgres;
using AntSK.Domain.Repositories;
using Microsoft.SemanticKernel.Plugins.Core;
using Microsoft.AspNetCore.Components.Authorization;
using AntSK.Services.Auth;
using LLama.Native;
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;
using AntSK.Domain.Model;
using AntSK.Domain.Common.Map;
using AntSK.Domain.Domain.BackGroundTask;
using System.Text.Encodings.Web;
using System.Text.Unicode;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
@@ -90,7 +82,7 @@ builder.Services.AddBackgroundTaskBroker().AddHandler<ImportKMSTaskReq, BackGrou
.WithCuda(false)
.WithLogs(true);
}
else if(LLamaSharpOption.RunType.ToUpper() == "GPU")
else if (LLamaSharpOption.RunType.ToUpper() == "GPU")
{
NativeLibraryConfig
.Instance
@@ -130,7 +122,7 @@ app.UseEndpoints(endpoints =>
endpoints.MapControllers();
});
app.Run();
void InitDB(WebApplication app)
void InitDB(WebApplication app)
{
using (var scope = app.Services.CreateScope())
{

View File

@@ -5,7 +5,6 @@ using AntSK.Models;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using System.Security.Claims;
using System.Security.Principal;
namespace AntSK.Services.Auth
{
@@ -30,7 +29,7 @@ namespace AntSK.Services.Auth
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
return true;
}
else
else
{
if (user.IsNull())
{
@@ -49,7 +48,7 @@ namespace AntSK.Services.Auth
}
}
public ClaimsPrincipal GetCurrentUser()
public ClaimsPrincipal GetCurrentUser()
{
//var userSessionStorageResult =await _protectedSessionStore.GetAsync<UserSession>("UserSession");
//var userSession = userSessionStorageResult.Success ? userSessionStorageResult.Value : null;

View File

@@ -1,11 +1,7 @@
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Options;
using AntSK.Models.OpenAPI;
using AntSK.Models;
using LLama;
using LLama.Common;
using Newtonsoft.Json;
using static Azure.Core.HttpHeader;
namespace AntSK.Services.LLamaSharp
{

View File

@@ -1,10 +1,7 @@
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Options;
using AntSK.Models.OpenAPI;
using AntSK.Models;
using LLama;
using LLama.Common;
using Newtonsoft.Json;
namespace AntSK.Services.LLamaSharp
{
@@ -21,7 +18,8 @@ namespace AntSK.Services.LLamaSharp
{
private LLamaEmbedder _embedder;
public LLamaEmbeddingService() {
public LLamaEmbeddingService()
{
var @params = new ModelParams(LLamaSharpOption.Embedding) { EmbeddingMode = true };
using var weights = LLamaWeights.LoadFromFile(@params);
@@ -34,9 +32,9 @@ namespace AntSK.Services.LLamaSharp
public async Task<List<float>> Embedding(string text)
{
float[] embeddings =await _embedder.GetEmbeddings(text);
float[] embeddings = await _embedder.GetEmbeddings(text);
//PG只有1536维
return embeddings.ToList();
return embeddings.ToList();
}
}
}

View File

@@ -1,19 +1,8 @@
using AntDesign;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Domain.Service;
using AntSK.Domain.Options;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Domain.Dto;
using AntSK.Domain.Utils;
using AntSK.Models;
using AntSK.Models.OpenAPI;
using AntSK.Services.OpenApi;
using Azure;
using DocumentFormat.OpenXml.EMMA;
using LLama;
using LLama.Common;
using Newtonsoft.Json;
using System.Text;
using System.Threading;
using static Azure.Core.HttpHeader;
using ServiceLifetime = AntSK.Domain.Common.DependencyInjection.ServiceLifetime;
namespace AntSK.Services.LLamaSharp
@@ -32,7 +21,7 @@ namespace AntSK.Services.LLamaSharp
ILLamaChatService _lLamaChatService
) : ILLamaSharpService
{
public async Task ChatStream(OpenAIModel model, HttpContext HttpContext)
{
HttpContext.Response.Headers.Add("Content-Type", "text/event-stream");
@@ -60,7 +49,7 @@ namespace AntSK.Services.LLamaSharp
result.created = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
result.choices = new List<ChoicesModel>() { new ChoicesModel() { message = new OpenAIMessage() { role = "assistant" } } };
result.choices[0].message.content =await _lLamaChatService.ChatAsync(questions); ;
result.choices[0].message.content = await _lLamaChatService.ChatAsync(questions); ;
HttpContext.Response.ContentType = "application/json";
await HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(result));
await HttpContext.Response.CompleteAsync();

View File

@@ -1,29 +1,14 @@
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Model;
using AntSK.Domain.Domain.Dto;
using AntSK.Domain.Domain.Interface;
using AntSK.Domain.Repositories;
using AntSK.Domain.Utils;
using AntSK.Models;
using AntSK.Models.OpenAPI;
using AntSK.Pages.ChatPage;
using MarkdownSharp;
using Microsoft.KernelMemory;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Microsoft.SemanticKernel;
using System.Text;
using System;
using ServiceLifetime = AntSK.Domain.Common.DependencyInjection.ServiceLifetime;
using AntDesign.Core.Extensions;
using Azure.AI.OpenAI;
using Azure;
using Azure.Core;
using Microsoft.AspNetCore.Http.HttpResults;
using AntDesign;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Newtonsoft.Json;
using System.Text.Json;
using AntSK.Domain.Domain.Interface;
using static LLama.Common.ChatHistory;
using DocumentFormat.OpenXml.Wordprocessing;
using AntSK.Domain.Domain.Service;
using System.Text;
using ServiceLifetime = AntSK.Domain.Common.DependencyInjection.ServiceLifetime;
namespace AntSK.Services.OpenApi
{
@@ -41,12 +26,12 @@ namespace AntSK.Services.OpenApi
IKMService _kMService
) : IOpenApiService
{
public async Task Chat(OpenAIModel model,string sk, HttpContext HttpContext)
public async Task Chat(OpenAIModel model, string sk, HttpContext HttpContext)
{
Apps app = _apps_Repositories.GetFirst(p => p.SecretKey == sk);
Apps app = _apps_Repositories.GetFirst(p => p.SecretKey == sk);
if (app.IsNotNull())
{
string msg= await HistorySummarize(app,model);
string msg = await HistorySummarize(app, model);
switch (app.Type)
{
case "chat":
@@ -56,13 +41,13 @@ namespace AntSK.Services.OpenApi
OpenAIStreamResult result1 = new OpenAIStreamResult();
result1.created = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
result1.choices = new List<StreamChoicesModel>() { new StreamChoicesModel() { delta = new OpenAIMessage() { role = "assistant" } } };
await SendChatStream( HttpContext, result1, app, msg);
await SendChatStream(HttpContext, result1, app, msg);
HttpContext.Response.ContentType = "application/json";
await HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(result1));
await HttpContext.Response.CompleteAsync();
return;
}
else
else
{
OpenAIResult result2 = new OpenAIResult();
result2.created = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
@@ -78,17 +63,17 @@ namespace AntSK.Services.OpenApi
OpenAIResult result3 = new OpenAIResult();
result3.created = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
result3.choices = new List<ChoicesModel>() { new ChoicesModel() { message = new OpenAIMessage() { role = "assistant" } } };
result3.choices[0].message.content = await SendKms( msg, app);
result3.choices[0].message.content = await SendKms(msg, app);
HttpContext.Response.ContentType = "application/json";
await HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(result3));
await HttpContext.Response.CompleteAsync();
break;
}
}
}
private async Task SendChatStream( HttpContext HttpContext, OpenAIStreamResult result, Apps app, string msg)
private async Task SendChatStream(HttpContext HttpContext, OpenAIStreamResult result, Apps app, string msg)
{
var _kernel = _kernelService.GetKernelByApp(app);
var temperature = app.Temperature / 100;//存的是0~100需要缩小
@@ -138,7 +123,7 @@ namespace AntSK.Services.OpenApi
/// <param name="msg"></param>
/// <param name="app"></param>
/// <returns></returns>
private async Task<string> SendChat( string msg, Apps app)
private async Task<string> SendChat(string msg, Apps app)
{
string result = "";
if (string.IsNullOrEmpty(app.Prompt) || !app.Prompt.Contains("{{$input}}"))
@@ -206,7 +191,7 @@ namespace AntSK.Services.OpenApi
{
string answers = chatResult.GetValue<string>();
result = answers;
}
}
}
return result;
}
@@ -216,12 +201,12 @@ namespace AntSK.Services.OpenApi
/// <param name="questions"></param>
/// <param name="msg"></param>
/// <returns></returns>
private async Task<string> HistorySummarize(Apps app,OpenAIModel model)
private async Task<string> HistorySummarize(Apps app, OpenAIModel model)
{
var _kernel = _kernelService.GetKernelByApp(app);
StringBuilder history = new StringBuilder();
string questions = model.messages[model.messages.Count-1].content;
for(int i=0;i<model.messages.Count()-1;i++)
string questions = model.messages[model.messages.Count - 1].content;
for (int i = 0; i < model.messages.Count() - 1; i++)
{
var item = model.messages[i];
history.Append($"{item.role}:{item.content}{Environment.NewLine}");

View File

@@ -1,7 +1,4 @@
using System;
using System.Threading.Tasks;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Repositories;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Models;
using ServiceLifetime = AntSK.Domain.Common.DependencyInjection.ServiceLifetime;

View File

@@ -1,7 +1,4 @@
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Models;
using ServiceLifetime = AntSK.Domain.Common.DependencyInjection.ServiceLifetime;

View File

@@ -1,7 +1,4 @@
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Models;
using ServiceLifetime = AntSK.Domain.Common.DependencyInjection.ServiceLifetime;

View File

@@ -1,7 +1,3 @@
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Models;
using ServiceLifetime = AntSK.Domain.Common.DependencyInjection.ServiceLifetime;

View File

@@ -1,7 +1,4 @@
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Domain.Common.DependencyInjection;
using AntSK.Models;
using ServiceLifetime = AntSK.Domain.Common.DependencyInjection.ServiceLifetime;

View File

@@ -1,158 +1,158 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace AntSK.BackgroundTask
{
public class BackgroundTaskBroker<TItem> : IBackgroundTaskBroker
{
private class BackgroundTaskWorker<T>
{
private readonly BackgroundTaskBroker<T> _broker;
public class BackgroundTaskBroker<TItem> : IBackgroundTaskBroker
{
private class BackgroundTaskWorker<T>
{
private readonly BackgroundTaskBroker<T> _broker;
private readonly IServiceProvider _serviceProvider;
private readonly IServiceProvider _serviceProvider;
private readonly ILogger _logger;
private readonly ILogger _logger;
private readonly IBackgroundTaskHandler<T> _handler;
private readonly IBackgroundTaskHandler<T> _handler;
public Task WorkerTask { get; private set; }
public Task WorkerTask { get; private set; }
public BackgroundTaskWorker(IServiceProvider serviceProvider, BackgroundTaskBroker<T> broker)
{
_broker = broker;
_serviceProvider = serviceProvider;
_logger = _serviceProvider.GetRequiredService<ILogger<BackgroundTaskWorker<T>>>();
_handler = serviceProvider.GetRequiredService<IBackgroundTaskHandler<T>>();
}
public BackgroundTaskWorker(IServiceProvider serviceProvider, BackgroundTaskBroker<T> broker)
{
_broker = broker;
_serviceProvider = serviceProvider;
_logger = _serviceProvider.GetRequiredService<ILogger<BackgroundTaskWorker<T>>>();
_handler = serviceProvider.GetRequiredService<IBackgroundTaskHandler<T>>();
}
public void Start(CancellationToken cancellationToken)
{
WorkerTask = Task.Factory.StartNew((Func<Task>)async delegate
{
while (!cancellationToken.IsCancellationRequested && !_broker.IsCompleted)
{
try
{
List<Task> tasks = new List<Task>();
foreach (T item in _broker.TakeMany())
{
Task t2 = _handler.ExecuteAsync(item);
Task cont = t2.ContinueWith(delegate(Task ct)
{
AggregateException exception2 = ct.Exception;
if (exception2 != null)
{
_logger.LogError(exception2.ToString());
}
});
tasks.Add(cont);
}
if (tasks.Any())
{
try
{
_logger.LogInformation($"等待所有 tasks {tasks.Count}");
await Task.WhenAll(tasks).ConfigureAwait(continueOnCapturedContext: false);
_logger.LogInformation("所有任务已完成");
}
catch (Exception ex3)
{
Exception ex2 = ex3;
_logger.LogError(ex2.ToString());
}
}
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
}
}
if (cancellationToken.IsCancellationRequested)
{
_logger.LogInformation("Cancellation was requested");
}
if (_broker.IsCompleted)
{
_logger.LogInformation("Broker 已完成");
}
}, cancellationToken, TaskCreationOptions.LongRunning | TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Unwrap();
WorkerTask.ContinueWith(delegate(Task t)
{
AggregateException exception = t.Exception;
if (exception != null)
{
_logger.LogError("报错了: {0}", exception);
}
}, TaskContinuationOptions.OnlyOnFaulted);
}
}
public void Start(CancellationToken cancellationToken)
{
WorkerTask = Task.Factory.StartNew((Func<Task>)async delegate
{
while (!cancellationToken.IsCancellationRequested && !_broker.IsCompleted)
{
try
{
List<Task> tasks = new List<Task>();
foreach (T item in _broker.TakeMany())
{
Task t2 = _handler.ExecuteAsync(item);
Task cont = t2.ContinueWith(delegate (Task ct)
{
AggregateException exception2 = ct.Exception;
if (exception2 != null)
{
_logger.LogError(exception2.ToString());
}
});
tasks.Add(cont);
}
if (tasks.Any())
{
try
{
_logger.LogInformation($"等待所有 tasks {tasks.Count}");
await Task.WhenAll(tasks).ConfigureAwait(continueOnCapturedContext: false);
_logger.LogInformation("所有任务已完成");
}
catch (Exception ex3)
{
Exception ex2 = ex3;
_logger.LogError(ex2.ToString());
}
}
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
}
}
if (cancellationToken.IsCancellationRequested)
{
_logger.LogInformation("Cancellation was requested");
}
if (_broker.IsCompleted)
{
_logger.LogInformation("Broker 已完成");
}
}, cancellationToken, TaskCreationOptions.LongRunning | TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Unwrap();
WorkerTask.ContinueWith(delegate (Task t)
{
AggregateException exception = t.Exception;
if (exception != null)
{
_logger.LogError("报错了: {0}", exception);
}
}, TaskContinuationOptions.OnlyOnFaulted);
}
}
private readonly BlockingCollection<TItem> _data = new BlockingCollection<TItem>();
private readonly BlockingCollection<TItem> _data = new BlockingCollection<TItem>();
private readonly List<BackgroundTaskWorker<TItem>> _workers = new List<BackgroundTaskWorker<TItem>>();
private readonly List<BackgroundTaskWorker<TItem>> _workers = new List<BackgroundTaskWorker<TItem>>();
private readonly object _lockWorkers = new object();
private readonly object _lockWorkers = new object();
private readonly IServiceProvider _serviceProvider;
private readonly IServiceProvider _serviceProvider;
private readonly ILogger _logger;
private readonly ILogger _logger;
private bool IsCompleted => _data.IsCompleted;
private bool IsCompleted => _data.IsCompleted;
private bool IsRunning { get; set; }
private bool IsRunning { get; set; }
public BackgroundTaskBroker(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
_logger = _serviceProvider.GetRequiredService<ILogger<BackgroundTaskBroker<TItem>>>();
}
public BackgroundTaskBroker(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
_logger = _serviceProvider.GetRequiredService<ILogger<BackgroundTaskBroker<TItem>>>();
}
public void QueueWorkItem(TItem workItem)
{
_data.Add(workItem);
}
public void QueueWorkItem(TItem workItem)
{
_data.Add(workItem);
}
private IEnumerable<TItem> TakeMany()
{
return _data.GetConsumingEnumerable();
}
private IEnumerable<TItem> TakeMany()
{
return _data.GetConsumingEnumerable();
}
public void Start(int workerCount, CancellationToken cancellationToken)
{
if (workerCount <= 0)
{
throw new ArgumentException("workerCount 必须大于0");
}
IsRunning = true;
lock (_lockWorkers)
{
while (_workers.Count < workerCount)
{
BackgroundTaskWorker<TItem> backgroundTaskWorker = new BackgroundTaskWorker<TItem>(_serviceProvider, this);
_workers.Add(backgroundTaskWorker);
backgroundTaskWorker.Start(cancellationToken);
}
}
}
public void Start(int workerCount, CancellationToken cancellationToken)
{
if (workerCount <= 0)
{
throw new ArgumentException("workerCount 必须大于0");
}
IsRunning = true;
lock (_lockWorkers)
{
while (_workers.Count < workerCount)
{
BackgroundTaskWorker<TItem> backgroundTaskWorker = new BackgroundTaskWorker<TItem>(_serviceProvider, this);
_workers.Add(backgroundTaskWorker);
backgroundTaskWorker.Start(cancellationToken);
}
}
}
public void Stop()
{
IsRunning = false;
_data.CompleteAdding();
lock (_lockWorkers)
{
Task[] tasks = _workers.Select((BackgroundTaskWorker<TItem> sw) => sw.WorkerTask).ToArray();
_logger.LogInformation("开始停止所有tasks");
Task.WaitAll(tasks);
_logger.LogInformation("所有task已停止");
_workers.Clear();
}
}
}
public void Stop()
{
IsRunning = false;
_data.CompleteAdding();
lock (_lockWorkers)
{
Task[] tasks = _workers.Select((BackgroundTaskWorker<TItem> sw) => sw.WorkerTask).ToArray();
_logger.LogInformation("开始停止所有tasks");
Task.WaitAll(tasks);
_logger.LogInformation("所有task已停止");
_workers.Clear();
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More