Skip to content

Commit

Permalink
feat (docs): error handling for generateObject (#2281)
Browse files Browse the repository at this point in the history
  • Loading branch information
lgrammel authored Jul 15, 2024
1 parent ea1d64e commit e7ed54a
Showing 1 changed file with 43 additions and 2 deletions.
45 changes: 43 additions & 2 deletions content/docs/03-ai-sdk-core/10-generating-structured-data.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<T>(
schema: z.Schema<T>,
): 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 };
}
}
}
```

0 comments on commit e7ed54a

Please sign in to comment.