-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathchat.ts
More file actions
50 lines (44 loc) · 1.63 KB
/
chat.ts
File metadata and controls
50 lines (44 loc) · 1.63 KB
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
import { ChatResponseResult, FlowerIntelligence, Message } from '@flwr/flwr';
const fi: FlowerIntelligence = FlowerIntelligence.instance;
// Global chat history with an initial system message.
export const history: Message[] = [
{ role: 'system', content: 'You are a friendly assistant that loves using emojis.' },
];
export async function chatWithMessages(messages: Message[]): Promise<Message> {
try {
const response: ChatResponseResult = await fi.chat({
messages,
});
if (!response || (response.ok && !response.message)) {
throw new Error('Invalid response structure from the chat service.');
}
if (!response.ok) {
console.error(response);
throw new Error('Failed to get a valid response.');
}
return response.message;
} catch (error) {
console.error('Error in chatWithMessages:', error);
throw new Error('Failed to get a valid response from the chat service.');
}
}
export async function chatWithHistory(question: string): Promise<string> {
try {
history.push({ role: 'user', content: question });
const response: ChatResponseResult = await fi.chat({
messages: history,
});
if (!response || (response.ok && !response.message)) {
throw new Error('Invalid response structure from the chat service.');
}
if (!response.ok) {
console.error(response);
throw new Error('Failed to get a valid response.');
}
history.push(response.message);
return response.message.content;
} catch (error) {
console.error('Error in chatWithHistory:', error);
throw new Error('Failed to get a valid response from the chat service.');
}
}