66 PdfPaperDocumentSchema ,
77 PdfPaperQuestionSchema ,
88 buildPdfPaperMarkdown ,
9+ getPdfMarkdownLanguageModel ,
910 getPdfMarkdownModel ,
1011} from "@/lib/ai/pdf-markdown" ;
1112import type { PdfPaperQuestion } from "@/lib/ai/pdf-markdown" ;
@@ -183,6 +184,19 @@ function getSafePdfFileName(fileName: string) {
183184 return / \. p d f $ / i. test ( trimmed ) ? trimmed : `${ trimmed } .pdf` ;
184185}
185186
187+ function getErrorMessage ( error : unknown ) {
188+ return error instanceof Error ? error . message : String ( error || "" ) ;
189+ }
190+
191+ function getStreamErrorMessage ( error : unknown , streamError : unknown ) {
192+ const fallbackMessage = getErrorMessage ( error ) ;
193+ if ( streamError ) {
194+ return getErrorMessage ( streamError ) || fallbackMessage ;
195+ }
196+
197+ return fallbackMessage || "Failed to convert this PDF to Markdown." ;
198+ }
199+
186200async function fetchPdfBuffer ( fileUrl : URL ) {
187201 const response = await fetch ( fileUrl , {
188202 cache : "no-store" ,
@@ -287,9 +301,11 @@ export async function POST(request: NextRequest) {
287301 ) ;
288302 }
289303
290- const model = getPdfMarkdownModel ( ) ;
304+ const model = getPdfMarkdownLanguageModel ( ) ;
305+ const modelId = getPdfMarkdownModel ( ) ;
291306
292307 try {
308+ let streamError : unknown = null ;
293309 const result = streamText ( {
294310 model,
295311 system : PDF_MARKDOWN_SYSTEM_PROMPT ,
@@ -319,11 +335,19 @@ export async function POST(request: NextRequest) {
319335 "A faithful ordered list of only question numbers, question text, and marks." ,
320336 } ) ,
321337 abortSignal : request . signal ,
322- temperature : 0 ,
323338 maxOutputTokens : 12000 ,
324339 experimental_include : {
325340 requestBody : false ,
326341 } ,
342+ onError : ( { error } ) => {
343+ streamError = error ;
344+ console . error ( "[pdf-markdown] stream error" , error ) ;
345+ } ,
346+ providerOptions : {
347+ openai : {
348+ store : false ,
349+ } ,
350+ } ,
327351 } ) ;
328352
329353 const encoder = new TextEncoder ( ) ;
@@ -357,15 +381,12 @@ export async function POST(request: NextRequest) {
357381 type : "done" ,
358382 paper,
359383 markdown : buildPdfPaperMarkdown ( paper ) ,
360- model,
384+ model : modelId ,
361385 } ) ;
362386 } catch ( error ) {
363387 enqueue ( {
364388 type : "error" ,
365- error :
366- error instanceof Error
367- ? error . message
368- : "Failed to convert this PDF to Markdown." ,
389+ error : getStreamErrorMessage ( error , streamError ) ,
369390 } ) ;
370391 } finally {
371392 controller . close ( ) ;
@@ -381,7 +402,7 @@ export async function POST(request: NextRequest) {
381402 "Cache-Control" : "no-store" ,
382403 "Content-Type" : "application/x-ndjson; charset=utf-8" ,
383404 "X-Accel-Buffering" : "no" ,
384- "X-ExamCooker-AI-Model" : model ,
405+ "X-ExamCooker-AI-Model" : modelId ,
385406 } ,
386407 } ) ;
387408 } catch ( error ) {
0 commit comments