Skip to content

Commit 7344891

Browse files
authored
docs: migrate generateObject/streamObject to generateText/streamText with Output (#12707)
## background preparing for v7 pre-releases by removing all usage of deprecated `generateObject` and `streamObject` from examples, docs, and cookbooks. the core implementation in `packages/ai/src/generate-object/` stays as-is for backwards compat ## summary - delete all `generate-object/` and `stream-object/` example files (equivalents already exist in `generate-text/` and `stream-text/`) - migrate e2e tests, framework examples (next, angular, nuxt, sveltekit) to `generateText`/`streamText` with `Output` - delete `generateObject` and `streamObject` reference pages - remove legacy section from structured data docs - update ~40 doc files (workflows, testing, tool calling, telemetry, troubleshooting, RSC, etc.) - update 19 cookbook files - update 22 provider doc files - add deprecation notes to telemetry docs for old span names api mapping: | before | after | |--------|-------| | `generateObject({ schema })` | `generateText({ output: Output.object({ schema }) })` | | `streamObject({ schema })` | `streamText({ output: Output.object({ schema }) })` | | `output: 'array'` + `schema` | `output: Output.array({ element: schema })` | | `output: 'enum'` + `enum` | `output: Output.choice({ options })` | | `output: 'no-schema'` | `output: Output.json()` | | `result.object` | `result.output` | | `partialObjectStream` | `partialOutputStream` | ## checklist - [x] tests have been added / updated (for bug fixes / features) - [x] documentation has been added / updated (for bug fixes / features) - [ ] a _patch_ changeset for relevant packages has been added (run `pnpm changeset` in root) - [x] i have reviewed this pull request (self-review) ## related issues fixes #12380
1 parent 57bd085 commit 7344891

File tree

215 files changed

+2853
-5187
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

215 files changed

+2853
-5187
lines changed

content/cookbook/00-guides/04-natural-language-postgres.mdx

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -259,35 +259,37 @@ Add a new action. This action should be asynchronous and take in one parameter -
259259
export const generateQuery = async (input: string) => {};
260260
```
261261

262-
In this action, you'll use the `generateObject` function from the AI SDK which allows you to constrain the model's output to a pre-defined schema. This process, sometimes called structured output, ensures the model returns only the SQL query without any additional prefixes, explanations, or formatting that would require manual parsing.
262+
In this action, you'll use the `generateText` function with `Output` from the AI SDK which allows you to constrain the model's output to a pre-defined schema. This process, sometimes called structured output, ensures the model returns only the SQL query without any additional prefixes, explanations, or formatting that would require manual parsing.
263263

264264
```ts filename="app/actions.ts"
265265
/* ...other imports... */
266-
import { generateObject } from 'ai';
266+
import { generateText, Output } from 'ai';
267267
import { z } from 'zod';
268268

269269
/* ...rest of the file... */
270270

271271
export const generateQuery = async (input: string) => {
272272
'use server';
273273
try {
274-
const result = await generateObject({
274+
const result = await generateText({
275275
model: 'openai/gpt-4o',
276276
system: `You are a SQL (postgres) ...`, // SYSTEM PROMPT AS ABOVE - OMITTED FOR BREVITY
277277
prompt: `Generate the query necessary to retrieve the data the user wants: ${input}`,
278-
schema: z.object({
279-
query: z.string(),
278+
output: Output.object({
279+
schema: z.object({
280+
query: z.string(),
281+
}),
280282
}),
281283
});
282-
return result.object.query;
284+
return result.output.query;
283285
} catch (e) {
284286
console.error(e);
285287
throw new Error('Failed to generate query');
286288
}
287289
};
288290
```
289291

290-
Note, you are constraining the output to a single string field called `query` using `zod`, a TypeScript schema validation library. This will ensure the model only returns the SQL query itself. The resulting generated query will then be returned.
292+
Note, you are constraining the output to a single string field called `query` using `zod`, a TypeScript schema validation library. This will ensure the model only returns the SQL query itself. The resulting output will then be returned.
291293

292294
### Update the frontend
293295

@@ -386,7 +388,7 @@ This action takes two parameters - the original natural language input and the g
386388
export const explainQuery = async (input: string, sqlQuery: string) => {
387389
'use server';
388390
try {
389-
const result = await generateObject({
391+
const result = await generateText({
390392
model: 'openai/gpt-4o',
391393
system: `You are a SQL (postgres) expert. ...`, // SYSTEM PROMPT AS ABOVE - OMITTED FOR BREVITY
392394
prompt: `Explain the SQL query you generated to retrieve the data the user wanted. Assume the user is not an expert in SQL. Break down the query into steps. Be concise.
@@ -397,15 +399,15 @@ export const explainQuery = async (input: string, sqlQuery: string) => {
397399
Generated SQL Query:
398400
${sqlQuery}`,
399401
});
400-
return result.object;
402+
return result.text;
401403
} catch (e) {
402404
console.error(e);
403405
throw new Error('Failed to generate query');
404406
}
405407
};
406408
```
407409

408-
This action uses the `generateObject` function again. However, you haven't defined the schema yet. Let's define it in another file so it can also be used as a type in your components.
410+
This action uses the `generateText` function. However, you haven't defined the output schema yet. Let's define it in another file so it can also be used as a type in your components.
409411

410412
Update your `lib/types.ts` file to include the schema for the explanations:
411413

@@ -433,7 +435,7 @@ import { explanationSchema } from '@/lib/types';
433435
export const explainQuery = async (input: string, sqlQuery: string) => {
434436
'use server';
435437
try {
436-
const result = await generateObject({
438+
const result = await generateText({
437439
model: 'openai/gpt-4o',
438440
system: `You are a SQL (postgres) expert. ...`, // SYSTEM PROMPT AS ABOVE - OMITTED FOR BREVITY
439441
prompt: `Explain the SQL query you generated to retrieve the data the user wanted. Assume the user is not an expert in SQL. Break down the query into steps. Be concise.
@@ -443,10 +445,9 @@ export const explainQuery = async (input: string, sqlQuery: string) => {
443445
444446
Generated SQL Query:
445447
${sqlQuery}`,
446-
schema: explanationSchema,
447-
output: 'array',
448+
output: Output.array({ element: explanationSchema }),
448449
});
449-
return result.object;
450+
return result.output;
450451
} catch (e) {
451452
console.error(e);
452453
throw new Error('Failed to generate query');
@@ -455,8 +456,8 @@ export const explainQuery = async (input: string, sqlQuery: string) => {
455456
```
456457

457458
<Note>
458-
You can use `output: "array"` to indicate to the model that you expect an
459-
array of objects matching the schema to be returned.
459+
You can use `Output.array()` to indicate to the model that you expect an array
460+
of objects matching the schema to be returned.
460461
</Note>
461462

462463
### Update query viewer
@@ -587,7 +588,7 @@ export const generateChartConfig = async (
587588
'use server';
588589

589590
try {
590-
const { object: config } = await generateObject({
591+
const { output: config } = await generateText({
591592
model: 'openai/gpt-4o',
592593
system: 'You are a data visualization expert.',
593594
prompt: `Given the following data from a SQL query result, generate the chart config that best visualises the data and answers the users query.
@@ -611,7 +612,7 @@ export const generateChartConfig = async (
611612
612613
Data:
613614
${JSON.stringify(results, null, 2)}`,
614-
schema: configSchema,
615+
output: Output.object({ schema: configSchema }),
615616
});
616617

617618
// Override with shadcn theme colors

content/cookbook/00-guides/19-openai-responses.mdx

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,20 +34,24 @@ const { text } = await generateText({
3434

3535
### Generating Structured Data
3636

37-
While text generation can be useful, you might want to generate structured JSON data. For example, you might want to extract information from text, classify data, or generate synthetic data. AI SDK Core provides two functions ([`generateObject`](/docs/reference/ai-sdk-core/generate-object) and [`streamObject`](/docs/reference/ai-sdk-core/stream-object)) to generate structured data, allowing you to constrain model outputs to a specific schema.
37+
While text generation can be useful, you might want to generate structured JSON data. For example, you might want to extract information from text, classify data, or generate synthetic data. AI SDK Core provides [`generateText`](/docs/reference/ai-sdk-core/generate-text) and [`streamText`](/docs/reference/ai-sdk-core/stream-text) with `Output` to generate structured data, allowing you to constrain model outputs to a specific schema.
3838

3939
```ts
40-
import { generateObject } from 'ai';
40+
import { generateText, Output } from 'ai';
4141
import { openai } from '@ai-sdk/openai';
4242
import { z } from 'zod';
4343

44-
const { object } = await generateObject({
44+
const { output } = await generateText({
4545
model: openai.responses('gpt-4o'),
46-
schema: z.object({
47-
recipe: z.object({
48-
name: z.string(),
49-
ingredients: z.array(z.object({ name: z.string(), amount: z.string() })),
50-
steps: z.array(z.string()),
46+
output: Output.object({
47+
schema: z.object({
48+
recipe: z.object({
49+
name: z.string(),
50+
ingredients: z.array(
51+
z.object({ name: z.string(), amount: z.string() }),
52+
),
53+
steps: z.array(z.string()),
54+
}),
5155
}),
5256
}),
5357
prompt: 'Generate a lasagna recipe.',

content/cookbook/00-guides/21-llama-3_1.mdx

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -89,20 +89,24 @@ const { textStream } = streamText({
8989

9090
### Generating Structured Data
9191

92-
While text generation can be useful, you might want to generate structured JSON data. For example, you might want to extract information from text, classify data, or generate synthetic data. AI SDK Core provides two functions ([`generateObject`](/docs/reference/ai-sdk-core/generate-object) and [`streamObject`](/docs/reference/ai-sdk-core/stream-object)) to generate structured data, allowing you to constrain model outputs to a specific schema.
92+
While text generation can be useful, you might want to generate structured JSON data. For example, you might want to extract information from text, classify data, or generate synthetic data. AI SDK Core provides [`generateText`](/docs/reference/ai-sdk-core/generate-text) and [`streamText`](/docs/reference/ai-sdk-core/stream-text) with `Output` to generate structured data, allowing you to constrain model outputs to a specific schema.
9393

9494
```ts
95-
import { generateObject } from 'ai';
95+
import { generateText, Output } from 'ai';
9696
import { deepinfra } from '@ai-sdk/deepinfra';
9797
import { z } from 'zod';
9898

99-
const { object } = await generateObject({
99+
const { output } = await generateText({
100100
model: deepinfra('meta-llama/Meta-Llama-3.1-70B-Instruct'),
101-
schema: z.object({
102-
recipe: z.object({
103-
name: z.string(),
104-
ingredients: z.array(z.object({ name: z.string(), amount: z.string() })),
105-
steps: z.array(z.string()),
101+
output: Output.object({
102+
schema: z.object({
103+
recipe: z.object({
104+
name: z.string(),
105+
ingredients: z.array(
106+
z.object({ name: z.string(), amount: z.string() }),
107+
),
108+
steps: z.array(z.string()),
109+
}),
106110
}),
107111
}),
108112
prompt: 'Generate a lasagna recipe.',

content/cookbook/00-guides/23-gpt-5.mdx

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -100,20 +100,24 @@ const { text } = await generateText({
100100

101101
### Generating Structured Data
102102

103-
While text generation can be useful, you might want to generate structured JSON data. For example, you might want to extract information from text, classify data, or generate synthetic data. AI SDK Core provides two functions ([`generateObject`](/docs/reference/ai-sdk-core/generate-object) and [`streamObject`](/docs/reference/ai-sdk-core/stream-object)) to generate structured data, allowing you to constrain model outputs to a specific schema.
103+
While text generation can be useful, you might want to generate structured JSON data. For example, you might want to extract information from text, classify data, or generate synthetic data. AI SDK Core provides [`generateText`](/docs/reference/ai-sdk-core/generate-text) and [`streamText`](/docs/reference/ai-sdk-core/stream-text) with `Output` to generate structured data, allowing you to constrain model outputs to a specific schema.
104104

105105
```ts
106-
import { generateObject } from 'ai';
106+
import { generateText, Output } from 'ai';
107107
import { openai } from '@ai-sdk/openai';
108108
import { z } from 'zod';
109109

110-
const { object } = await generateObject({
110+
const { output } = await generateText({
111111
model: openai('gpt-5'),
112-
schema: z.object({
113-
recipe: z.object({
114-
name: z.string(),
115-
ingredients: z.array(z.object({ name: z.string(), amount: z.string() })),
116-
steps: z.array(z.string()),
112+
output: Output.object({
113+
schema: z.object({
114+
recipe: z.object({
115+
name: z.string(),
116+
ingredients: z.array(
117+
z.object({ name: z.string(), amount: z.string() }),
118+
),
119+
steps: z.array(z.string()),
120+
}),
117121
}),
118122
}),
119123
prompt: 'Generate a lasagna recipe.',

content/cookbook/00-guides/23-o1.mdx

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -106,20 +106,24 @@ const { text } = await generateText({
106106

107107
### Generating Structured Data
108108

109-
While text generation can be useful, you might want to generate structured JSON data. For example, you might want to extract information from text, classify data, or generate synthetic data. AI SDK Core provides two functions ([`generateObject`](/docs/reference/ai-sdk-core/generate-object) and [`streamObject`](/docs/reference/ai-sdk-core/stream-object)) to generate structured data, allowing you to constrain model outputs to a specific schema.
109+
While text generation can be useful, you might want to generate structured JSON data. For example, you might want to extract information from text, classify data, or generate synthetic data. AI SDK Core provides [`generateText`](/docs/reference/ai-sdk-core/generate-text) and [`streamText`](/docs/reference/ai-sdk-core/stream-text) with `Output` to generate structured data, allowing you to constrain model outputs to a specific schema.
110110

111111
```ts
112-
import { generateObject } from 'ai';
112+
import { generateText, Output } from 'ai';
113113
import { openai } from '@ai-sdk/openai';
114114
import { z } from 'zod';
115115

116-
const { object } = await generateObject({
116+
const { output } = await generateText({
117117
model: openai('o1'),
118-
schema: z.object({
119-
recipe: z.object({
120-
name: z.string(),
121-
ingredients: z.array(z.object({ name: z.string(), amount: z.string() })),
122-
steps: z.array(z.string()),
118+
output: Output.object({
119+
schema: z.object({
120+
recipe: z.object({
121+
name: z.string(),
122+
ingredients: z.array(
123+
z.object({ name: z.string(), amount: z.string() }),
124+
),
125+
steps: z.array(z.string()),
126+
}),
123127
}),
124128
}),
125129
prompt: 'Generate a lasagna recipe.',

content/cookbook/00-guides/24-o3.mdx

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -92,20 +92,24 @@ const { text } = await generateText({
9292

9393
### Generating Structured Data
9494

95-
While text generation can be useful, you might want to generate structured JSON data. For example, you might want to extract information from text, classify data, or generate synthetic data. AI SDK Core provides two functions ([`generateObject`](/docs/reference/ai-sdk-core/generate-object) and [`streamObject`](/docs/reference/ai-sdk-core/stream-object)) to generate structured data, allowing you to constrain model outputs to a specific schema.
95+
While text generation can be useful, you might want to generate structured JSON data. For example, you might want to extract information from text, classify data, or generate synthetic data. AI SDK Core provides [`generateText`](/docs/reference/ai-sdk-core/generate-text) and [`streamText`](/docs/reference/ai-sdk-core/stream-text) with `Output` to generate structured data, allowing you to constrain model outputs to a specific schema.
9696

9797
```ts
98-
import { generateObject } from 'ai';
98+
import { generateText, Output } from 'ai';
9999
import { openai } from '@ai-sdk/openai';
100100
import { z } from 'zod';
101101

102-
const { object } = await generateObject({
102+
const { output } = await generateText({
103103
model: openai('o3-mini'),
104-
schema: z.object({
105-
recipe: z.object({
106-
name: z.string(),
107-
ingredients: z.array(z.object({ name: z.string(), amount: z.string() })),
108-
steps: z.array(z.string()),
104+
output: Output.object({
105+
schema: z.object({
106+
recipe: z.object({
107+
name: z.string(),
108+
ingredients: z.array(
109+
z.object({ name: z.string(), amount: z.string() }),
110+
),
111+
steps: z.array(z.string()),
112+
}),
109113
}),
110114
}),
111115
prompt: 'Generate a lasagna recipe.',

content/cookbook/01-next/122-caching-middleware.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ export default function Chat() {
5757

5858
Next, you will create a `LanguageModelMiddleware` that caches the assistant's responses in KV storage.
5959
`LanguageModelMiddleware` has two methods: `wrapGenerate` and `wrapStream`.
60-
`wrapGenerate` is called when using [`generateText`](/docs/reference/ai-sdk-core/generate-text) and [`generateObject`](/docs/reference/ai-sdk-core/generate-object), while `wrapStream` is called when using [`streamText`](/docs/reference/ai-sdk-core/stream-text) and [`streamObject`](/docs/reference/ai-sdk-core/stream-object).
60+
`wrapGenerate` is called when using [`generateText`](/docs/reference/ai-sdk-core/generate-text), while `wrapStream` is called when using [`streamText`](/docs/reference/ai-sdk-core/stream-text).
6161

6262
For `wrapGenerate`, you can cache the response directly.
6363
Instead, for `wrapStream`, you cache an array of the stream parts, which can then be used with [`simulateReadableStream`](/docs/reference/ai-sdk-core/simulate-readable-stream) function to create a simulated `ReadableStream` that returns the cached response.

content/cookbook/01-next/30-generate-object.mdx

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ tags: ['next', 'structured data']
66

77
# Generate Object
88

9-
Earlier functions like `generateText` and `streamText` gave us the ability to generate unstructured text. However, if you want to generate structured data like JSON, you can provide a schema that describes the structure of your desired object to the `generateObject` function.
9+
You can use `generateText` with `Output` to generate structured data like JSON. By providing a schema that describes the structure of your desired object, the SDK will validate the generated output and ensure that it conforms to the specified structure.
1010

11-
The function requires you to provide a schema using [zod](https://zod.dev), a library for defining schemas for JavaScript objects. By using zod, you can also use it to validate the generated object and ensure that it conforms to the specified structure.
11+
The `Output.object` function requires you to provide a schema using [zod](https://zod.dev), a library for defining schemas for JavaScript objects.
1212

1313
<Browser>
1414
<ObjectGeneration
@@ -83,31 +83,33 @@ export default function Page() {
8383

8484
## Server
8585

86-
Let's create a route handler for `/api/completion` that will generate an object based on the input prompt. The route will call the `generateObject` function from the `ai` module, which will then generate an object based on the input prompt and return it.
86+
Let's create a route handler for `/api/completion` that will generate an object based on the input prompt. The route will call the `generateText` function with `Output.object` from the `ai` module, which will then generate an object based on the input prompt and return it.
8787

8888
```typescript filename='app/api/completion/route.ts'
89-
import { generateObject } from 'ai';
89+
import { generateText, Output } from 'ai';
9090
import { z } from 'zod';
9191

9292
export async function POST(req: Request) {
9393
const { prompt }: { prompt: string } = await req.json();
9494

95-
const result = await generateObject({
95+
const result = await generateText({
9696
model: 'openai/gpt-4o',
9797
system: 'You generate three notifications for a messages app.',
9898
prompt,
99-
schema: z.object({
100-
notifications: z.array(
101-
z.object({
102-
name: z.string().describe('Name of a fictional person.'),
103-
message: z.string().describe('Do not use emojis or links.'),
104-
minutesAgo: z.number(),
105-
}),
106-
),
99+
output: Output.object({
100+
schema: z.object({
101+
notifications: z.array(
102+
z.object({
103+
name: z.string().describe('Name of a fictional person.'),
104+
message: z.string().describe('Do not use emojis or links.'),
105+
minutesAgo: z.number(),
106+
}),
107+
),
108+
}),
107109
}),
108110
});
109111

110-
return result.toJsonResponse();
112+
return Response.json(result.output);
111113
}
112114
```
113115

0 commit comments

Comments
 (0)