@@ -4,7 +4,6 @@ import { CREATE_CHAT } from '@/graphql/request';
4
4
import { Message } from '@/const/MessageType' ;
5
5
import { toast } from 'sonner' ;
6
6
import { logger } from '@/app/log/logger' ;
7
- import { startChatStream } from '@/utils/chatStream' ;
8
7
import { useAuthContext } from '@/providers/AuthProvider' ;
9
8
10
9
interface UseChatStreamProps {
@@ -63,14 +62,84 @@ export const useChatStream = ({
63
62
} ,
64
63
} ) ;
65
64
65
+ const startChatStream = async (
66
+ targetChatId : string ,
67
+ message : string ,
68
+ model : string ,
69
+ stream : boolean = false // Default to non-streaming for better performance
70
+ ) : Promise < string > => {
71
+ if ( ! token ) {
72
+ throw new Error ( 'Not authenticated' ) ;
73
+ }
74
+
75
+ const response = await fetch ( '/api/chat' , {
76
+ method : 'POST' ,
77
+ headers : {
78
+ 'Content-Type' : 'application/json' ,
79
+ Authorization : `Bearer ${ token } ` ,
80
+ } ,
81
+ body : JSON . stringify ( {
82
+ chatId : targetChatId ,
83
+ message,
84
+ model,
85
+ stream,
86
+ } ) ,
87
+ } ) ;
88
+
89
+ if ( ! response . ok ) {
90
+ throw new Error (
91
+ `Network response was not ok: ${ response . status } ${ response . statusText } `
92
+ ) ;
93
+ }
94
+ // TODO: Handle streaming responses properly
95
+ // if (stream) {
96
+ // // For streaming responses, aggregate the streamed content
97
+ // let fullContent = '';
98
+ // const reader = response.body?.getReader();
99
+ // if (!reader) {
100
+ // throw new Error('No reader available');
101
+ // }
102
+
103
+ // while (true) {
104
+ // const { done, value } = await reader.read();
105
+ // if (done) break;
106
+
107
+ // const text = new TextDecoder().decode(value);
108
+ // const lines = text.split('\n\n');
109
+
110
+ // for (const line of lines) {
111
+ // if (line.startsWith('data: ')) {
112
+ // const data = line.slice(5);
113
+ // if (data === '[DONE]') break;
114
+ // try {
115
+ // const { content } = JSON.parse(data);
116
+ // if (content) {
117
+ // fullContent += content;
118
+ // }
119
+ // } catch (e) {
120
+ // console.error('Error parsing SSE data:', e);
121
+ // }
122
+ // }
123
+ // }
124
+ // }
125
+ // return fullContent;
126
+ // } else {
127
+ // // For non-streaming responses, return the content directly
128
+ // const data = await response.json();
129
+ // return data.content;
130
+ // }
131
+
132
+ const data = await response . json ( ) ;
133
+ return data . content ;
134
+ } ;
135
+
66
136
const handleChatResponse = async ( targetChatId : string , message : string ) => {
67
137
try {
68
138
setInput ( '' ) ;
69
139
const response = await startChatStream (
70
140
targetChatId ,
71
141
message ,
72
- selectedModel ,
73
- token
142
+ selectedModel
74
143
) ;
75
144
76
145
setMessages ( ( prev ) => [
@@ -147,5 +216,6 @@ export const useChatStream = ({
147
216
stop,
148
217
isStreaming : loadingSubmit ,
149
218
currentChatId,
219
+ startChatStream,
150
220
} ;
151
221
} ;
0 commit comments