我正在使用C#和ANGING开发一个聊天应用程序.我在C#中的控制器有一个定制的文本生成算法,它根据来自前端的用户输入生成响应.此响应是以块形式生成的.我希望在生成块时在前端显示响应(也称为聊天流,流允许模型以增量方式生成和显示文本,而不是等到生成整个响应).

我try 使用SignalR在客户端和服务器端进行实时通信,以便在生成块时像中那样显示它们.我使用URL"/MessageHub"创建了一个新的Hub连接,然后启动了Hub连接.构建和启动集线器时没有任何错误.然后,我try 使用Hub Connection的Invoke方法将用户消息从客户端发送到服务器端,但此时出现错误,因为无法建立连接.

C#中的MessageHub类中的代码:

        public async Task SendMessage(string message, int requestId)
        {
            var response = _chatbotProvider.GetResponse(message, requestId);

            try
            {
                await Clients.All.SendAsync("ReceiveMessage", response);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

以Angular 编码以创建和启动轮毂连接.

ngOnInit(): void {
    this._hubConnection = new HubConnectionBuilder().withUrl("/MessageHub").build();

    this._hubConnection.start().then(() => console.log('Connection Started!'))
    .catch(err => console.log('Error while establishing connection'));

  }

  sendMessage(){
    this.requestId = this.route.snapshot.params['requestId'];

    this._hubConnection.invoke('SendMessage', this.userMessage, this.requestId).catch(err => console.error(err));

    this.chatMessages.push({ role: 'user', content: this.userMessage });

    this._hubConnection.on("ReceiveMessage", (botResponse) => {
      this.chatMessages.push({ role: 'assistant', content: botResponse})
    });
    console.log(this.chatMessages)
    this.userMessage = '';
  }

Getting the error as below:

我期待的是我的应用程序中的聊天流功能(就像在ChatGPT中逐个块地生成响应一样).

或者,有没有其他方法可以让我达到同样的目的?

推荐答案

确保requestId的类型为int,与服务器端SendMessage中的类型相同

你可以试试

this.requestId = parseInt(this.route.snapshot.params['requestId'], 10);

Here is my test result.

enter image description here

    public async Task SendMessage(string message, int requestId)
    {
        var response = GenerateResponse(message, requestId); 

        foreach (char c in response)
        {
            await Clients.Caller.SendAsync("ReceiveMessage", c.ToString());
            await Task.Delay(50); 
        }
    }

    private string GenerateResponse(string message, int requestId)
    {
        return "In 2024, everyone will be happy in the new year."; 
    }

你可以参考我的示例代码,它是简单的html,而不是角.

@{
    ViewData["Title"] = "SignalR";
}
<!DOCTYPE html>
<html>
<head>
    <title>Chat App</title>
</head>
<body>
    <div>
        <input type="text" id="userMessage" placeholder="Enter message" />
        <button onclick="sendMessage()">Send Message</button>
    </div>
    <div id="chatWindow"></div>

    <script>
        //var connection = new signalR.HubConnectionBuilder().withUrl("/MessageHub").build();
        var chatWindow = document.getElementById("chatWindow");

        connection.on("ReceiveMessage", function (message) {
            chatWindow.innerHTML += message;
        });

        connection.start().catch(function (err) {
            return console.error(err.toString());
        });

        function sendMessage() {
            var message = document.getElementById("userMessage").value;
            // Using 1001 mock this.requestId
            connection.invoke("SendMessage", message, 1001).catch(function (err) {
                return console.error(err.toString());
            });
        }
    </script>
</body>
</html>

Csharp相关问答推荐

Autofac:如何防止丢弃通过ServicCollection注册的服务?

在ASP.NET中为数据注释 Select 合适的语言

如何禁用ASP.NET MVP按钮,以便无法使用开发人员控制台重新启用它

有没有一种方法可以在包含混合文本的标签中嵌入超链接?

如何使用ConcurentDictionary属性上的属性将自定义System.Text.Json JsonConverter应用于该属性的值?

Blazor服务器端的身份验证角色

JsonSerializer.Deserialize<;TValue>;(String,JsonSerializerOptions)何时返回空?

用C#调用由缓冲区指针参数组成的C API

使用C#HttpClient以多部分形式数据发送带有非ASCII文件名的文件的问题

Razor视图Razor页面指向同一端点时的优先级

如何在ASP.NET Core8中启用REST应用程序的序列化?

Automapper 12.x将GUID映射到字符串

使用带有参数和曲面的注入失败(&Q;)

Blazor Fluent UI DialogService,<;FluentDialogProvider/>;错误

解决方案:延长ABP框架和ANGING OpenIddict中的令牌生命周期

将J数组转换为列表,只保留一个嵌套的JToken

使用Blazor WebAssembly提高初始页面加载时间的性能

为什么连接到Google OAuth2后,结果.Credential为空?

实体框架允许您具有筛选的属性吗?

如果图表S批注包含使用LINQ的具有特定名称的批注,我如何签入C#