1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- using HTEXGpt.Models;
- namespace HTEXGpt.Services
- {
- public class AiAppServiceImpl : IAiAppService
- {
- private readonly IServiceProvider _serviceProvider;
- public AiAppServiceImpl(IServiceProvider serviceProvider)
- {
- _serviceProvider = serviceProvider;
- }
- public async Task<ChatResponse> ChatMessage(string? modelType, ChatRequest dto, HttpContext httpContext,HttpResponse response)
- {
- this.CheckMessages(dto.messages);
- IModelService? modelService = GetModelService(modelType!);
- return await modelService!.ChatMessage(dto,httpContext, response);
- }
- /// <summary>
- /// 根据模型类型获取对应的模型服务
- /// </summary>
- /// <param name="modelType"></param>
- /// <returns></returns>
- /// <exception cref="InvalidOperationException"></exception>
- private IModelService? GetModelService(string modelType)
- {
- try
- {
- // 将字符串转换为枚举值
- ModelTypeEnum modelTypeEnum = (ModelTypeEnum)Enum.Parse(typeof(ModelTypeEnum), modelType!);
- // 根据枚举值获取对应的服务类型
- Type? serviceType = typeof(IModelService).Assembly.GetTypes()
- .FirstOrDefault(t => t.IsClass && !t.IsAbstract && t.GetInterfaces().Contains(typeof(IModelService)) && t.Name.StartsWith(modelTypeEnum.ToString()));
- if (serviceType == null)
- {
- throw new InvalidOperationException($"未找到与模型类型 {modelType} 对应的服务。");
- }
- // 获取服务实例
- var s= _serviceProvider.GetRequiredService(serviceType);
- var s1 = _serviceProvider.GetService(serviceType);
- return (IModelService?)_serviceProvider.GetService(serviceType);
- }
- catch (ArgumentException e)
- {
- throw new InvalidOperationException("模型类型错误", e);
- }
- }
- /// <summary>
- /// 检查消息参数是否符合规范@param messages 消息参数
- /// </summary>
- /// <param name="messages"></param>
- /// <exception cref="RuntimeException"></exception>
- private void CheckMessages(List<MessageDTO> messages)
- {
- if (messages!=null && messages.Count>0)
- {
- // messages参数个数必须为奇数并且奇数个数的消息role必须为user,偶数个数的消息role必须为assistant
- if (messages.Count() % 2 == 0)
- {
- throw new Exception("messages参数个数必须为奇数");
- }
- for (int i = 0; i < messages.Count(); i++)
- {
- if (i % 2 == 0)
- {
- if (!"user".Equals(messages[i].role))
- {
- throw new Exception("messages奇数参数的role必须为user");
- }
- }
- else
- {
- if (!"assistant".Equals(messages[i].role))
- {
- throw new Exception("messages偶数参数的role必须为assistant");
- }
- }
- }
- }
- }
- }
- }
|