-
Notifications
You must be signed in to change notification settings - Fork 6
/
message.service.ts
95 lines (84 loc) · 2.5 KB
/
message.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { inject, Injectable, signal } from '@angular/core';
import { filter, map, Observable, startWith } from 'rxjs';
import {
HttpClient,
HttpDownloadProgressEvent,
HttpEvent,
HttpEventType,
HttpResponse,
} from '@angular/common/http';
export interface Message {
id: string;
text: string;
fromUser: boolean;
generating?: boolean;
}
@Injectable({
providedIn: 'root',
})
export class MessageService {
private readonly http = inject(HttpClient);
private readonly _completeMessages = signal<Message[]>([]);
private readonly _messages = signal<Message[]>([]);
private readonly _generatingInProgress = signal<boolean>(false);
readonly messages = this._messages.asReadonly();
readonly generatingInProgress = this._generatingInProgress.asReadonly();
sendMessage(prompt: string): void {
this._generatingInProgress.set(true);
this._completeMessages.set([
...this._completeMessages(),
{
id: window.crypto.randomUUID(),
text: prompt,
fromUser: true,
},
]);
this.getChatResponseStream(prompt).subscribe({
next: (message) =>
this._messages.set([...this._completeMessages(), message]),
complete: () => {
this._completeMessages.set(this._messages());
this._generatingInProgress.set(false);
},
error: () => this._generatingInProgress.set(false),
});
}
private getChatResponseStream(prompt: string): Observable<Message> {
const id = window.crypto.randomUUID();
return this.http
.post('http://localhost:3000/message', prompt, {
responseType: 'text',
observe: 'events',
reportProgress: true,
})
.pipe(
filter(
(event: HttpEvent<string>): boolean =>
event.type === HttpEventType.DownloadProgress ||
event.type === HttpEventType.Response,
),
map(
(event: HttpEvent<string>): Message =>
event.type === HttpEventType.DownloadProgress
? {
id,
text: (event as HttpDownloadProgressEvent).partialText!,
fromUser: false,
generating: true,
}
: {
id,
text: (event as HttpResponse<string>).body!,
fromUser: false,
generating: false,
},
),
startWith<Message>({
id,
text: '',
fromUser: false,
generating: true,
}),
);
}
}