@@ -95,12 +95,19 @@ export async function POST(req: NextRequest) {
9595 {
9696 stream,
9797 historyLength : history . length ,
98+ endpoint : useWandAzure ? azureEndpoint : 'api.openai.com' ,
99+ model : useWandAzure ? wandModelName : 'gpt-4o' ,
100+ apiVersion : useWandAzure ? azureApiVersion : 'N/A' ,
98101 }
99102 )
100103
101104 // For streaming responses
102105 if ( stream ) {
103106 try {
107+ logger . debug (
108+ `[${ requestId } ] Starting streaming request to ${ useWandAzure ? 'Azure OpenAI' : 'OpenAI' } `
109+ )
110+
104111 const streamCompletion = await client . chat . completions . create ( {
105112 model : useWandAzure ? wandModelName : 'gpt-4o' ,
106113 messages : messages ,
@@ -109,6 +116,8 @@ export async function POST(req: NextRequest) {
109116 stream : true ,
110117 } )
111118
119+ logger . debug ( `[${ requestId } ] Stream connection established successfully` )
120+
112121 return new Response (
113122 new ReadableStream ( {
114123 async start ( controller ) {
@@ -118,31 +127,34 @@ export async function POST(req: NextRequest) {
118127 for await ( const chunk of streamCompletion ) {
119128 const content = chunk . choices [ 0 ] ?. delta ?. content || ''
120129 if ( content ) {
121- // Use the same format as codegen API for consistency
130+ // Use SSE format identical to chat streaming
122131 controller . enqueue (
123- encoder . encode ( `${ JSON . stringify ( { chunk : content , done : false } ) } \n` )
132+ encoder . encode ( `data: ${ JSON . stringify ( { chunk : content } ) } \n \n` )
124133 )
125134 }
126135 }
127136
128- // Send completion signal
129- controller . enqueue ( encoder . encode ( `${ JSON . stringify ( { chunk : '' , done : true } ) } \n` ) )
137+ // Send completion signal in SSE format
138+ controller . enqueue ( encoder . encode ( `data: ${ JSON . stringify ( { done : true } ) } \n \n` ) )
130139 controller . close ( )
131140 logger . info ( `[${ requestId } ] Wand generation streaming completed` )
132141 } catch ( streamError : any ) {
133142 logger . error ( `[${ requestId } ] Streaming error` , { error : streamError . message } )
134143 controller . enqueue (
135- encoder . encode ( `${ JSON . stringify ( { error : 'Streaming failed' , done : true } ) } \n` )
144+ encoder . encode (
145+ `data: ${ JSON . stringify ( { error : 'Streaming failed' , done : true } ) } \n\n`
146+ )
136147 )
137148 controller . close ( )
138149 }
139150 } ,
140151 } ) ,
141152 {
142153 headers : {
143- 'Content-Type' : 'text/plain ' ,
144- 'Cache-Control' : 'no-cache, no-transform ' ,
154+ 'Content-Type' : 'text/event-stream ' ,
155+ 'Cache-Control' : 'no-cache' ,
145156 Connection : 'keep-alive' ,
157+ 'X-Accel-Buffering' : 'no' ,
146158 } ,
147159 }
148160 )
0 commit comments