-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathdata-stream-handler.tsx
96 lines (81 loc) · 2.41 KB
/
data-stream-handler.tsx
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
96
'use client';
import { useChat } from '@ai-sdk/react';
import { useEffect, useRef } from 'react';
import { artifactDefinitions, ArtifactKind } from './artifact';
import { Suggestion } from '@/lib/db/schema';
import { initialArtifactData, useArtifact } from '@/hooks/use-artifact';
export type DataStreamDelta = {
type:
| 'text-delta'
| 'code-delta'
| 'sheet-delta'
| 'image-delta'
| 'title'
| 'id'
| 'suggestion'
| 'clear'
| 'finish'
| 'kind';
content: string | Suggestion;
};
export function DataStreamHandler({ id }: { id: string }) {
const { data: dataStream } = useChat({ id });
const { artifact, setArtifact, setMetadata } = useArtifact();
const lastProcessedIndex = useRef(-1);
useEffect(() => {
if (!dataStream?.length) return;
const newDeltas = dataStream.slice(lastProcessedIndex.current + 1);
lastProcessedIndex.current = dataStream.length - 1;
(newDeltas as DataStreamDelta[]).forEach((delta: DataStreamDelta) => {
const artifactDefinition = artifactDefinitions.find(
(artifactDefinition) => artifactDefinition.kind === artifact.kind,
);
if (artifactDefinition?.onStreamPart) {
artifactDefinition.onStreamPart({
streamPart: delta,
setArtifact,
setMetadata,
});
}
setArtifact((draftArtifact) => {
if (!draftArtifact) {
return { ...initialArtifactData, status: 'streaming' };
}
switch (delta.type) {
case 'id':
return {
...draftArtifact,
documentId: delta.content as string,
status: 'streaming',
};
case 'title':
return {
...draftArtifact,
title: delta.content as string,
status: 'streaming',
};
case 'kind':
return {
...draftArtifact,
kind: delta.content as ArtifactKind,
status: 'streaming',
};
case 'clear':
return {
...draftArtifact,
content: '',
status: 'streaming',
};
case 'finish':
return {
...draftArtifact,
status: 'idle',
};
default:
return draftArtifact;
}
});
});
}, [dataStream, setArtifact, setMetadata, artifact]);
return null;
}