{"record":{"id":"c48863ab3bb73460","repo":"mastra-ai/mastra","slug":"structured-output-object-undefined","errorCode":"STRUCTURED_OUTPUT_OBJECT_UNDEFINED","errorMessage":"structuredOutput object is undefined","messagePattern":"structuredOutput object is undefined","errorType":"error_code","errorClass":"MastraError","httpStatus":null,"severity":"error","filePath":"packages/core/src/agent/utils.ts","lineNumber":60,"sourceCode":"  options: AgentExecutionOptions<OUTPUT>,\n): Promise<FullOutput<OUTPUT>> {\n  if (!options.structuredOutput?.schema) {\n    throw new MastraError({\n      id: 'STRUCTURED_OUTPUT_OPTIONS_REQUIRED',\n      domain: ErrorDomain.AGENT,\n      category: ErrorCategory.USER,\n      text: 'structuredOutput is required to use tryGenerateWithJsonFallback',\n    });\n  }\n\n  try {\n    const result = await agent.generate(prompt, options);\n    // Some models resolve without throwing but produce no parseable structured\n    // object (empty/malformed JSON). Treat that the same as a thrown error so the\n    // caller still gets the json-prompt-injection retry instead of a downstream\n    // crash when it reads `result.object`. Mirrors tryStreamWithJsonFallback.\n    if (result.object === undefined) {\n      throw new MastraError({\n        id: 'STRUCTURED_OUTPUT_OBJECT_UNDEFINED',\n        domain: ErrorDomain.AGENT,\n        category: ErrorCategory.USER,\n        text: 'structuredOutput object is undefined',\n      });\n    }\n    return result;\n  } catch (error) {\n    if (!isStructuredOutputFormatError(error)) throw error;\n\n    console.warn('Error in tryGenerateWithJsonFallback. Attempting fallback.', error);\n    const result = await agent.generate(prompt, {\n      ...options,\n      structuredOutput: {\n        ...options.structuredOutput,\n        jsonPromptInjection:\n          options.structuredOutput.jsonPromptInjection === 'inline' ||\n          options.structuredOutput.jsonPromptInjection === 'system'","sourceCodeStart":42,"sourceCodeEnd":78,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/agent/utils.ts#L42-L78","documentation":"After the first agent.generate() attempt, if the model resolves without throwing but produces no parseable structured object (result.object is undefined — e.g. empty or malformed JSON), tryGenerateWithJsonFallback converts that into a MastraError STRUCTURED_OUTPUT_OBJECT_UNDEFINED. This lets the caller get the json-prompt-injection retry instead of crashing later when reading result.object.","triggerScenarios":"The model returns a response whose structured object cannot be parsed (empty content, non-JSON text, truncated JSON) during the initial structured-output generate attempt.","commonSituations":"Weak/small models ignoring the JSON schema instruction; very large schemas where output gets truncated; providers returning tool-call-free plain text; low maxOutputTokens cutting JSON mid-stream.","solutions":["Let the built-in fallback retry run — catch this error only at the outermost boundary; the function itself retries with JSON prompt injection.","Increase maxOutputTokens and/or use a model that reliably supports structured output/native tool calling.","Simplify or loosen the schema (fewer required fields, avoid deeply nested unions) to make valid JSON more likely."],"exampleFix":"// before\nconst { object } = await tryGenerateWithJsonFallback(agent, prompt, opts); // crashes here if object undefined\n// after\ntry {\n  const { object } = await tryGenerateWithJsonFallback(agent, prompt, opts);\n} catch (e) {\n  if (e instanceof MastraError && e.id === 'STRUCTURED_OUTPUT_OBJECT_UNDEFINED') {\n    // model produced unparseable output after retries — handle or rethrow with context\n  }\n}","handlingStrategy":"try-catch","validationCode":null,"typeGuard":"function isStructuredResult<O>(r: FullOutput<O>): r is FullOutput<O> & { object: O } {\n  return r.object !== undefined;\n}","tryCatchPattern":"try {\n  const result = await tryGenerateWithJsonFallback(agent, prompt, options);\n  return result.object;\n} catch (e) {\n  if (e instanceof MastraError && e.id === 'STRUCTURED_OUTPUT_OBJECT_UNDEFINED') {\n    // model output unparseable — retry with a stronger model or fall back to manual parsing\n  }\n  throw e;\n}","preventionTips":["Use models known to follow JSON/schema instructions","Raise maxOutputTokens so JSON isn't truncated","Keep schemas simple; avoid deep nesting and exotic unions","Set jsonPromptInjection: 'system' for models that ignore user-level instructions"],"tags":["structured-output","llm-output","json-parsing","retry"],"backgroundTag":"structured-output-parse-failed","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}