我正在使用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 = '';
}
我期待的是我的应用程序中的聊天流功能(就像在ChatGPT中逐个块地生成响应一样).
或者,有没有其他方法可以让我达到同样的目的?