From e7ed54a48f03285c9cf8bfca34c5db23637af406 Mon Sep 17 00:00:00 2001 From: Lars Grammel Date: Mon, 15 Jul 2024 15:31:48 +0200 Subject: [PATCH] feat (docs): error handling for generateObject (#2281) --- .../10-generating-structured-data.mdx | 45 ++++++++++++++++++- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/content/docs/03-ai-sdk-core/10-generating-structured-data.mdx b/content/docs/03-ai-sdk-core/10-generating-structured-data.mdx index bb2e717793c9..04f9ff0e5861 100644 --- a/content/docs/03-ai-sdk-core/10-generating-structured-data.mdx +++ b/content/docs/03-ai-sdk-core/10-generating-structured-data.mdx @@ -63,9 +63,9 @@ for await (const partialObject of partialObjectStream) { You can use `streamObject` to stream generated UIs in combination with React Server Components (see [Generative UI](../ai-sdk-rsc))) or the [`useObject`](/docs/reference/ai-sdk-ui/use-object) hook. -## Guide +## Schema Writing Tips -The mapping from Zod schemas to LLM inputs (typically JSON schema) is not always straightforward. +The mapping from Zod schemas to LLM inputs (typically JSON schema) is not always straightforward, since the mapping is not one-to-one. Please checkout the following tips and the [Prompt Engineering with Tools](/docs/ai-sdk-core/tools-and-tool-calling#prompt-engineering-with-tools) guide. ### Generating Arrays @@ -111,3 +111,44 @@ const result = await generateObject({ prompt: 'Generate a fake user profile for testing.', }); ``` + +## Error Handling + +When you use `generateObject`, errors are thrown when the model fails to generate proper JSON (`JSONParseError`) +or when the generated JSON does not match the schema (`TypeValidationError`). +Both error types contain additional information, e.g. the generated text or the invalid value. + +You can use this to e.g. design a function that safely process the result object and also returns values in error cases: + +```ts +import { openai } from '@ai-sdk/openai'; +import { JSONParseError, TypeValidationError, generateObject } from 'ai'; +import { z } from 'zod'; + +async function generateLasagnaRecipe( + schema: z.Schema, +): Promise< + | { type: 'success'; object: T } + | { type: 'parse-error'; text: string } + | { type: 'validation-error'; value: unknown } + | { type: 'unknown-error'; error: unknown } +> { + try { + const result = await generateObject({ + model: openai('gpt-4-turbo'), + schema, + prompt: 'Generate a lasagna recipe.', + }); + + return { type: 'success', object: result.object }; + } catch (error) { + if (TypeValidationError.isTypeValidationError(error)) { + return { type: 'validation-error', value: error.value }; + } else if (JSONParseError.isJSONParseError(error)) { + return { type: 'parse-error', text: error.text }; + } else { + return { type: 'unknown-error', error }; + } + } +} +```