BotSharp/src/Plugins/BotSharp.Plugin.ChatbotUI/ChatbotUiController.cs

131 lines
4.4 KiB
C#
Raw Normal View History

2023-05-27 01:58:31 +00:00
using BotSharp.Abstraction.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
2023-06-07 00:59:32 +00:00
using BotSharp.Plugin.ChatbotUI.ViewModels;
2023-06-13 03:27:31 +00:00
using Microsoft.Extensions.DependencyInjection;
2023-06-27 18:31:13 +00:00
using BotSharp.Abstraction.Conversations;
using BotSharp.Abstraction.Conversations.Models;
2023-07-21 15:15:30 +00:00
using Microsoft.AspNetCore.Authorization;
2023-08-15 15:41:34 +00:00
using BotSharp.Abstraction.Agents.Enums;
2024-01-18 15:27:52 +00:00
using BotSharp.Abstraction.MLTasks;
using BotSharp.Abstraction.MLTasks.Settings;
2024-03-27 18:50:27 +00:00
using BotSharp.Abstraction.Routing;
2023-05-27 01:58:31 +00:00
2023-06-07 00:59:32 +00:00
namespace BotSharp.Plugin.ChatbotUI.Controllers;
2023-05-27 01:58:31 +00:00
2023-07-21 15:15:30 +00:00
[Authorize]
2023-05-27 01:58:31 +00:00
[ApiController]
2023-12-27 15:53:54 +00:00
public class ChatbotUiController : ControllerBase
2023-05-27 01:58:31 +00:00
{
2023-06-13 03:27:31 +00:00
private readonly IServiceProvider _services;
2023-05-27 01:58:31 +00:00
private readonly ILogger<ChatbotUiController> _logger;
2023-06-13 03:27:31 +00:00
public ChatbotUiController(ILogger<ChatbotUiController> logger, IServiceProvider services)
2023-05-27 01:58:31 +00:00
{
_logger = logger;
2023-06-13 03:27:31 +00:00
_services = services;
2023-05-27 01:58:31 +00:00
}
[HttpGet("/v1/models")]
public OpenAiModels GetOpenAiModels()
{
2024-01-18 15:27:52 +00:00
var llm = _services.GetRequiredService<ILlmProviderService>();
var models = llm.GetProviderModels("azure-openai").Where(x => x.Type == LlmModelType.Chat)
.Select(x => new AiModel
{
Id = x.Id,
Model = x.Name,
Name = x.Name
}).ToList();
2023-05-27 01:58:31 +00:00
return new OpenAiModels
{
2024-01-18 15:27:52 +00:00
Data = models,
2023-05-27 01:58:31 +00:00
};
}
[HttpPost("/v1/chat/completions")]
2023-05-29 01:06:05 +00:00
public async Task SendMessage([FromBody] OpenAiMessageInput input)
2023-05-27 01:58:31 +00:00
{
Response.StatusCode = 200;
Response.Headers.Add(HeaderNames.ContentType, "text/event-stream");
Response.Headers.Add(HeaderNames.CacheControl, "no-cache");
Response.Headers.Add(HeaderNames.Connection, "keep-alive");
var outputStream = Response.Body;
2023-09-09 15:37:38 +00:00
var message = input.Messages
2023-08-15 15:41:34 +00:00
.Where(x => x.Role == AgentRole.User)
2023-09-14 01:41:51 +00:00
.Select(x => new RoleDialogModel(x.Role, x.Content))
.Last();
2023-05-29 01:06:05 +00:00
2024-01-18 15:27:52 +00:00
var llm = _services.GetRequiredService<ILlmProviderService>();
var model = llm.GetProviderModels("azure-openai")
.First(x => x.Type == LlmModelType.Chat && x.Id == input.Model)
.Name;
2023-09-06 03:19:36 +00:00
var conv = _services.GetRequiredService<IConversationService>();
2024-03-27 18:50:27 +00:00
var routing = _services.GetRequiredService<IRoutingService>();
routing.Context.SetMessageId(input.ConversationId, message.MessageId);
2023-09-14 01:41:51 +00:00
conv.SetConversationId(input.ConversationId, input.States);
2023-11-27 03:44:17 +00:00
conv.States.SetState("channel", input.Channel)
2024-01-18 15:27:52 +00:00
.SetState("provider", "azure-openai")
.SetState("model", model)
2023-11-27 03:04:48 +00:00
.SetState("temperature", input.Temperature)
.SetState("sampling_factor", input.SamplingFactor);
2023-06-13 03:27:31 +00:00
2023-11-27 03:04:48 +00:00
var result = await conv.SendMessage(input.AgentId,
2024-03-16 14:43:00 +00:00
message,
replyMessage: null,
async msg =>
2024-09-12 10:55:42 +00:00
await OnChunkReceived(outputStream, msg));
2023-06-13 03:27:31 +00:00
2023-05-29 01:06:05 +00:00
await OnEventCompleted(outputStream);
2023-05-27 01:58:31 +00:00
}
private async Task OnChunkReceived(Stream outputStream, RoleDialogModel message)
2023-05-27 01:58:31 +00:00
{
var response = new OpenAiChatOutput
{
Choices = new List<OpenAiChoice>
{
new OpenAiChoice
{
Delta = new RoleDialogModel(message.Role, message.Content)
2023-05-27 01:58:31 +00:00
}
}
};
var json = JsonConvert.SerializeObject(response, new JsonSerializerSettings
{
Formatting = Formatting.None,
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
var buffer = Encoding.UTF8.GetBytes($"data:{json}\n");
await outputStream.WriteAsync(buffer, 0, buffer.Length);
await Task.Delay(10);
2023-05-27 01:58:31 +00:00
buffer = Encoding.UTF8.GetBytes("\n");
await outputStream.WriteAsync(buffer, 0, buffer.Length);
}
private async Task OnEventCompleted(Stream outputStream)
{
var buffer = Encoding.UTF8.GetBytes("data:[DONE]\n");
await outputStream.WriteAsync(buffer, 0, buffer.Length);
buffer = Encoding.UTF8.GetBytes("\n");
await outputStream.WriteAsync(buffer, 0, buffer.Length);
await outputStream.FlushAsync();
}
}