@@ -236,10 +236,17 @@ export const POST: APIRoute = async ({ request }) => {
236236 ( async ( ) => {
237237 try {
238238 let hasOutput = false ;
239- for await ( const chunk of result . textStream ) {
240- if ( chunk ) {
239+ for await ( const part of result . stream ) {
240+ if ( part . type === "text-delta" ) {
241241 hasOutput = true ;
242- await writer . write ( encoder . encode ( chunk ) ) ;
242+ await writer . write ( encoder . encode ( part . text ) ) ;
243+ } else if ( part . type === "error" ) {
244+ console . error ( "[Stream Part Error]" , ( part as any ) . error ) ;
245+ await writer . write (
246+ encoder . encode (
247+ `\n\n[Model Stream Error: ${ ( part as any ) . error instanceof Error ? ( part as any ) . error . message : JSON . stringify ( ( part as any ) . error ) } ]` ,
248+ ) ,
249+ ) ;
243250 }
244251 }
245252 if ( ! hasOutput ) {
@@ -252,25 +259,23 @@ export const POST: APIRoute = async ({ request }) => {
252259 if ( allText ) {
253260 await writer . write ( encoder . encode ( allText ) ) ;
254261 } else {
255- const lastStep = steps [ steps . length - 1 ] ;
256- const firstToolResult = lastStep ?. toolResults ?. [ 0 ] as any ;
257- const directResult = firstToolResult ?. output ?? firstToolResult ?. result ;
258- if ( directResult ?. result ?. length ) {
259- const titles = directResult . result
260- . map ( ( item : any ) => `• ${ item . title || item . _id } ` )
261- . join ( "\n" ) ;
262- await writer . write (
263- encoder . encode (
264- `Here are the relevant items found in CodingCat.dev:\n\n${ titles } ` ,
265- ) ,
266- ) ;
267- } else {
268- await writer . write (
269- encoder . encode (
270- "I searched the CodingCat.dev Sanity content lake for your query, but did not find any matching articles or episodes." ,
271- ) ,
272- ) ;
273- }
262+ const stepTrace = steps . map ( ( s , idx ) => ( {
263+ step : idx + 1 ,
264+ finishReason : s . finishReason ,
265+ toolCalls : s . toolCalls ?. map ( ( tc ) => ( {
266+ name : tc . toolName ,
267+ args : ( tc as any ) . args ?? ( tc as any ) . input ,
268+ } ) ) ,
269+ toolResults : s . toolResults ?. map ( ( tr ) => ( {
270+ name : tr . toolName ,
271+ output : ( tr as any ) . output ?? ( tr as any ) . result ,
272+ } ) ) ,
273+ } ) ) ;
274+ await writer . write (
275+ encoder . encode (
276+ `I searched the CodingCat.dev Sanity content lake. Diagnostic trace:\n${ JSON . stringify ( stepTrace , null , 2 ) } ` ,
277+ ) ,
278+ ) ;
274279 }
275280 }
276281 } catch ( streamErr ) {
0 commit comments