ai 6.0.92 → 6.0.94

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/index.d.mts +357 -13
  3. package/dist/index.d.ts +357 -13
  4. package/dist/index.js +198 -26
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.mjs +198 -26
  7. package/dist/index.mjs.map +1 -1
  8. package/dist/internal/index.js +1 -1
  9. package/dist/internal/index.mjs +1 -1
  10. package/docs/02-foundations/03-prompts.mdx +1 -1
  11. package/docs/02-getting-started/01-navigating-the-library.mdx +1 -1
  12. package/docs/03-agents/02-building-agents.mdx +8 -7
  13. package/docs/03-agents/03-workflows.mdx +71 -55
  14. package/docs/03-ai-sdk-core/01-overview.mdx +2 -4
  15. package/docs/03-ai-sdk-core/05-generating-text.mdx +54 -0
  16. package/docs/03-ai-sdk-core/10-generating-structured-data.mdx +8 -172
  17. package/docs/03-ai-sdk-core/15-tools-and-tool-calling.mdx +48 -6
  18. package/docs/03-ai-sdk-core/20-prompt-engineering.mdx +14 -12
  19. package/docs/03-ai-sdk-core/55-testing.mdx +8 -8
  20. package/docs/03-ai-sdk-core/60-telemetry.mdx +13 -53
  21. package/docs/05-ai-sdk-rsc/02-streaming-react-components.mdx +1 -1
  22. package/docs/05-ai-sdk-rsc/05-streaming-values.mdx +2 -3
  23. package/docs/05-ai-sdk-rsc/10-migrating-to-ui.mdx +9 -9
  24. package/docs/06-advanced/04-caching.mdx +1 -1
  25. package/docs/07-reference/01-ai-sdk-core/01-generate-text.mdx +667 -146
  26. package/docs/07-reference/01-ai-sdk-core/index.mdx +3 -8
  27. package/docs/07-reference/05-ai-sdk-errors/ai-no-object-generated-error.mdx +2 -2
  28. package/docs/09-troubleshooting/09-client-stream-error.mdx +1 -1
  29. package/docs/09-troubleshooting/14-tool-calling-with-structured-outputs.mdx +4 -4
  30. package/docs/09-troubleshooting/20-no-object-generated-content-filter.mdx +18 -14
  31. package/package.json +2 -2
  32. package/src/generate-text/execute-tool-call.ts +83 -0
  33. package/src/generate-text/generate-text.ts +534 -11
  34. package/src/generate-text/index.ts +4 -0
  35. package/src/generate-text/step-result.ts +52 -0
  36. package/src/generate-text/stream-text.ts +15 -1
  37. package/docs/07-reference/01-ai-sdk-core/03-generate-object.mdx +0 -780
  38. package/docs/07-reference/01-ai-sdk-core/04-stream-object.mdx +0 -1152
@@ -153,7 +153,7 @@ var import_provider_utils2 = require("@ai-sdk/provider-utils");
153
153
  var import_provider_utils3 = require("@ai-sdk/provider-utils");
154
154
 
155
155
  // src/version.ts
156
- var VERSION = true ? "6.0.92" : "0.0.0-test";
156
+ var VERSION = true ? "6.0.94" : "0.0.0-test";
157
157
 
158
158
  // src/util/download/download.ts
159
159
  var download = async ({
@@ -132,7 +132,7 @@ import {
132
132
  } from "@ai-sdk/provider-utils";
133
133
 
134
134
  // src/version.ts
135
- var VERSION = true ? "6.0.92" : "0.0.0-test";
135
+ var VERSION = true ? "6.0.94" : "0.0.0-test";
136
136
 
137
137
  // src/util/download/download.ts
138
138
  var download = async ({
@@ -19,7 +19,7 @@ Text prompts are strings.
19
19
  They are ideal for simple generation use cases,
20
20
  e.g. repeatedly generating content for variants of the same prompt text.
21
21
 
22
- You can set text prompts using the `prompt` property made available by AI SDK functions like [`streamText`](/docs/reference/ai-sdk-core/stream-text) or [`generateObject`](/docs/reference/ai-sdk-core/generate-object).
22
+ You can set text prompts using the `prompt` property made available by AI SDK functions like [`streamText`](/docs/reference/ai-sdk-core/stream-text) or [`generateText`](/docs/reference/ai-sdk-core/generate-text).
23
23
  You can structure the text in any way and inject variables, e.g. using a template literal.
24
24
 
25
25
  ```ts highlight="3"
@@ -19,7 +19,7 @@ When deciding which part of the AI SDK to use, your first consideration should b
19
19
 
20
20
  | Library | Purpose | Environment Compatibility |
21
21
  | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
22
- | [AI SDK Core](/docs/ai-sdk-core/overview) | Call any LLM with unified API (e.g. [generateText](/docs/reference/ai-sdk-core/generate-text) and [generateObject](/docs/reference/ai-sdk-core/generate-object)) | Any JS environment (e.g. Node.js, Deno, Browser) |
22
+ | [AI SDK Core](/docs/ai-sdk-core/overview) | Call any LLM with unified API (e.g. [generateText](/docs/reference/ai-sdk-core/generate-text) and [streamText](/docs/reference/ai-sdk-core/stream-text)) | Any JS environment (e.g. Node.js, Deno, Browser) |
23
23
  | [AI SDK UI](/docs/ai-sdk-ui/overview) | Build streaming chat and generative UIs (e.g. [useChat](/docs/reference/ai-sdk-ui/use-chat)) | React & Next.js, Vue & Nuxt, Svelte & SvelteKit |
24
24
  | [AI SDK RSC](/docs/ai-sdk-rsc/overview) | Stream generative UIs from Server to Client (e.g. [streamUI](/docs/reference/ai-sdk-rsc/stream-ui)). Development is currently experimental and we recommend using [AI SDK UI](/docs/ai-sdk-ui/overview). | Any framework that supports React Server Components (e.g. Next.js) |
25
25
 
@@ -331,13 +331,14 @@ export async function POST(request: Request) {
331
331
 
332
332
  ### Track Step Progress
333
333
 
334
- Use `onStepFinish` to track each step's progress, including token usage:
334
+ Use `onStepFinish` to track each step's progress, including token usage.
335
+ The callback receives a `stepNumber` (zero-based) to identify which step just completed:
335
336
 
336
337
  ```ts
337
338
  const result = await myAgent.generate({
338
339
  prompt: 'Research and summarize the latest AI trends',
339
- onStepFinish: async ({ usage, finishReason, toolCalls }) => {
340
- console.log('Step completed:', {
340
+ onStepFinish: async ({ stepNumber, usage, finishReason, toolCalls }) => {
341
+ console.log(`Step ${stepNumber} completed:`, {
341
342
  inputTokens: usage.inputTokens,
342
343
  outputTokens: usage.outputTokens,
343
344
  finishReason,
@@ -352,18 +353,18 @@ You can also define `onStepFinish` in the constructor for agent-wide tracking. W
352
353
  ```ts
353
354
  const agent = new ToolLoopAgent({
354
355
  model: __MODEL__,
355
- onStepFinish: async ({ usage }) => {
356
+ onStepFinish: async ({ stepNumber, usage }) => {
356
357
  // Agent-wide logging
357
- console.log('Agent step:', usage.totalTokens);
358
+ console.log(`Agent step ${stepNumber}:`, usage.totalTokens);
358
359
  },
359
360
  });
360
361
 
361
362
  // Method-level callback runs after constructor callback
362
363
  const result = await agent.generate({
363
364
  prompt: 'Hello',
364
- onStepFinish: async ({ usage }) => {
365
+ onStepFinish: async ({ stepNumber, usage }) => {
365
366
  // Per-call tracking (e.g., for billing)
366
- await trackUsage(usage);
367
+ await trackUsage(stepNumber, usage);
367
368
  },
368
369
  });
369
370
  ```
@@ -40,7 +40,7 @@ These patterns, adapted from [Anthropic's guide on building effective agents](ht
40
40
  The simplest workflow pattern executes steps in a predefined order. Each step's output becomes input for the next step, creating a clear chain of operations. Use this pattern for tasks with well-defined sequences, like content generation pipelines or data transformation processes.
41
41
 
42
42
  ```ts
43
- import { generateText, generateObject } from 'ai';
43
+ import { generateText, Output } from 'ai';
44
44
  __PROVIDER_IMPORT__;
45
45
  import { z } from 'zod';
46
46
 
@@ -54,12 +54,14 @@ async function generateMarketingCopy(input: string) {
54
54
  });
55
55
 
56
56
  // Perform quality check on copy
57
- const { object: qualityMetrics } = await generateObject({
57
+ const { output: qualityMetrics } = await generateText({
58
58
  model,
59
- schema: z.object({
60
- hasCallToAction: z.boolean(),
61
- emotionalAppeal: z.number().min(1).max(10),
62
- clarity: z.number().min(1).max(10),
59
+ output: Output.object({
60
+ schema: z.object({
61
+ hasCallToAction: z.boolean(),
62
+ emotionalAppeal: z.number().min(1).max(10),
63
+ clarity: z.number().min(1).max(10),
64
+ }),
63
65
  }),
64
66
  prompt: `Evaluate this marketing copy for:
65
67
  1. Presence of call to action (true/false)
@@ -96,7 +98,7 @@ async function generateMarketingCopy(input: string) {
96
98
  This pattern lets the model decide which path to take through a workflow based on context and intermediate results. The model acts as an intelligent router, directing the flow of execution between different branches of your workflow. Use this when handling varied inputs that require different processing approaches. In the example below, the first LLM call's results determine the second call's model size and system prompt.
97
99
 
98
100
  ```ts
99
- import { generateObject, generateText } from 'ai';
101
+ import { generateText, Output } from 'ai';
100
102
  __PROVIDER_IMPORT__;
101
103
  import { z } from 'zod';
102
104
 
@@ -104,12 +106,14 @@ async function handleCustomerQuery(query: string) {
104
106
  const model = __MODEL__;
105
107
 
106
108
  // First step: Classify the query type
107
- const { object: classification } = await generateObject({
109
+ const { output: classification } = await generateText({
108
110
  model,
109
- schema: z.object({
110
- reasoning: z.string(),
111
- type: z.enum(['general', 'refund', 'technical']),
112
- complexity: z.enum(['simple', 'complex']),
111
+ output: Output.object({
112
+ schema: z.object({
113
+ reasoning: z.string(),
114
+ type: z.enum(['general', 'refund', 'technical']),
115
+ complexity: z.enum(['simple', 'complex']),
116
+ }),
113
117
  }),
114
118
  prompt: `Classify this customer query:
115
119
  ${query}
@@ -147,7 +151,7 @@ async function handleCustomerQuery(query: string) {
147
151
  Break down tasks into independent subtasks that execute simultaneously. This pattern uses parallel execution to improve efficiency while maintaining the benefits of structured workflows. For example, analyze multiple documents or process different aspects of a single input concurrently (like code review).
148
152
 
149
153
  ```ts
150
- import { generateText, generateObject } from 'ai';
154
+ import { generateText, Output } from 'ai';
151
155
  __PROVIDER_IMPORT__;
152
156
  import { z } from 'zod';
153
157
 
@@ -158,40 +162,46 @@ async function parallelCodeReview(code: string) {
158
162
  // Run parallel reviews
159
163
  const [securityReview, performanceReview, maintainabilityReview] =
160
164
  await Promise.all([
161
- generateObject({
165
+ generateText({
162
166
  model,
163
167
  system:
164
168
  'You are an expert in code security. Focus on identifying security vulnerabilities, injection risks, and authentication issues.',
165
- schema: z.object({
166
- vulnerabilities: z.array(z.string()),
167
- riskLevel: z.enum(['low', 'medium', 'high']),
168
- suggestions: z.array(z.string()),
169
+ output: Output.object({
170
+ schema: z.object({
171
+ vulnerabilities: z.array(z.string()),
172
+ riskLevel: z.enum(['low', 'medium', 'high']),
173
+ suggestions: z.array(z.string()),
174
+ }),
169
175
  }),
170
176
  prompt: `Review this code:
171
177
  ${code}`,
172
178
  }),
173
179
 
174
- generateObject({
180
+ generateText({
175
181
  model,
176
182
  system:
177
183
  'You are an expert in code performance. Focus on identifying performance bottlenecks, memory leaks, and optimization opportunities.',
178
- schema: z.object({
179
- issues: z.array(z.string()),
180
- impact: z.enum(['low', 'medium', 'high']),
181
- optimizations: z.array(z.string()),
184
+ output: Output.object({
185
+ schema: z.object({
186
+ issues: z.array(z.string()),
187
+ impact: z.enum(['low', 'medium', 'high']),
188
+ optimizations: z.array(z.string()),
189
+ }),
182
190
  }),
183
191
  prompt: `Review this code:
184
192
  ${code}`,
185
193
  }),
186
194
 
187
- generateObject({
195
+ generateText({
188
196
  model,
189
197
  system:
190
198
  'You are an expert in code quality. Focus on code structure, readability, and adherence to best practices.',
191
- schema: z.object({
192
- concerns: z.array(z.string()),
193
- qualityScore: z.number().min(1).max(10),
194
- recommendations: z.array(z.string()),
199
+ output: Output.object({
200
+ schema: z.object({
201
+ concerns: z.array(z.string()),
202
+ qualityScore: z.number().min(1).max(10),
203
+ recommendations: z.array(z.string()),
204
+ }),
195
205
  }),
196
206
  prompt: `Review this code:
197
207
  ${code}`,
@@ -199,9 +209,9 @@ async function parallelCodeReview(code: string) {
199
209
  ]);
200
210
 
201
211
  const reviews = [
202
- { ...securityReview.object, type: 'security' },
203
- { ...performanceReview.object, type: 'performance' },
204
- { ...maintainabilityReview.object, type: 'maintainability' },
212
+ { ...securityReview.output, type: 'security' },
213
+ { ...performanceReview.output, type: 'performance' },
214
+ { ...maintainabilityReview.output, type: 'maintainability' },
205
215
  ];
206
216
 
207
217
  // Aggregate results using another model instance
@@ -221,23 +231,25 @@ async function parallelCodeReview(code: string) {
221
231
  A primary model (orchestrator) coordinates the execution of specialized workers. Each worker optimizes for a specific subtask, while the orchestrator maintains overall context and ensures coherent results. This pattern excels at complex tasks requiring different types of expertise or processing.
222
232
 
223
233
  ```ts
224
- import { generateObject } from 'ai';
234
+ import { generateText, Output } from 'ai';
225
235
  __PROVIDER_IMPORT__;
226
236
  import { z } from 'zod';
227
237
 
228
238
  async function implementFeature(featureRequest: string) {
229
239
  // Orchestrator: Plan the implementation
230
- const { object: implementationPlan } = await generateObject({
240
+ const { output: implementationPlan } = await generateText({
231
241
  model: __MODEL__,
232
- schema: z.object({
233
- files: z.array(
234
- z.object({
235
- purpose: z.string(),
236
- filePath: z.string(),
237
- changeType: z.enum(['create', 'modify', 'delete']),
238
- }),
239
- ),
240
- estimatedComplexity: z.enum(['low', 'medium', 'high']),
242
+ output: Output.object({
243
+ schema: z.object({
244
+ files: z.array(
245
+ z.object({
246
+ purpose: z.string(),
247
+ filePath: z.string(),
248
+ changeType: z.enum(['create', 'modify', 'delete']),
249
+ }),
250
+ ),
251
+ estimatedComplexity: z.enum(['low', 'medium', 'high']),
252
+ }),
241
253
  }),
242
254
  system:
243
255
  'You are a senior software architect planning feature implementations.',
@@ -258,11 +270,13 @@ async function implementFeature(featureRequest: string) {
258
270
  'You are an expert at safely removing code while ensuring no breaking changes.',
259
271
  }[file.changeType];
260
272
 
261
- const { object: change } = await generateObject({
273
+ const { output: change } = await generateText({
262
274
  model: __MODEL__,
263
- schema: z.object({
264
- explanation: z.string(),
265
- code: z.string(),
275
+ output: Output.object({
276
+ schema: z.object({
277
+ explanation: z.string(),
278
+ code: z.string(),
279
+ }),
266
280
  }),
267
281
  system: workerSystemPrompt,
268
282
  prompt: `Implement the changes for ${file.filePath} to support:
@@ -291,7 +305,7 @@ async function implementFeature(featureRequest: string) {
291
305
  Add quality control to workflows with dedicated evaluation steps that assess intermediate results. Based on the evaluation, the workflow proceeds, retries with adjusted parameters, or takes corrective action. This creates robust workflows capable of self-improvement and error recovery.
292
306
 
293
307
  ```ts
294
- import { generateText, generateObject } from 'ai';
308
+ import { generateText, Output } from 'ai';
295
309
  __PROVIDER_IMPORT__;
296
310
  import { z } from 'zod';
297
311
 
@@ -313,15 +327,17 @@ async function translateWithFeedback(text: string, targetLanguage: string) {
313
327
  // Evaluation-optimization loop
314
328
  while (iterations < MAX_ITERATIONS) {
315
329
  // Evaluate current translation
316
- const { object: evaluation } = await generateObject({
330
+ const { output: evaluation } = await generateText({
317
331
  model: __MODEL__,
318
- schema: z.object({
319
- qualityScore: z.number().min(1).max(10),
320
- preservesTone: z.boolean(),
321
- preservesNuance: z.boolean(),
322
- culturallyAccurate: z.boolean(),
323
- specificIssues: z.array(z.string()),
324
- improvementSuggestions: z.array(z.string()),
332
+ output: Output.object({
333
+ schema: z.object({
334
+ qualityScore: z.number().min(1).max(10),
335
+ preservesTone: z.boolean(),
336
+ preservesNuance: z.boolean(),
337
+ culturallyAccurate: z.boolean(),
338
+ specificIssues: z.array(z.string()),
339
+ improvementSuggestions: z.array(z.string()),
340
+ }),
325
341
  }),
326
342
  system: 'You are an expert in evaluating literary translations.',
327
343
  prompt: `Evaluate this translation:
@@ -23,10 +23,8 @@ These functions take a standardized approach to setting up [prompts](./prompts)
23
23
  This function is ideal for non-interactive use cases such as automation tasks where you need to write text (e.g. drafting email or summarizing web pages) and for agents that use tools.
24
24
  - [`streamText`](/docs/ai-sdk-core/generating-text): Stream text and tool calls.
25
25
  You can use the `streamText` function for interactive use cases such as [chat bots](/docs/ai-sdk-ui/chatbot) and [content streaming](/docs/ai-sdk-ui/completion).
26
- - [`generateObject`](/docs/ai-sdk-core/generating-structured-data): Generates a typed, structured object that matches a [Zod](https://zod.dev/) schema.
27
- You can use this function to force the language model to return structured data, e.g. for information extraction, synthetic data generation, or classification tasks.
28
- - [`streamObject`](/docs/ai-sdk-core/generating-structured-data): Stream a structured object that matches a Zod schema.
29
- You can use this function to [stream generated UIs](/docs/ai-sdk-ui/object-generation).
26
+
27
+ Both `generateText` and `streamText` support [structured output](/docs/ai-sdk-core/generating-structured-data) via the `output` property (e.g. `Output.object()`, `Output.array()`), allowing you to generate typed, schema-validated data for information extraction, synthetic data generation, classification tasks, and [streaming generated UIs](/docs/ai-sdk-ui/object-generation).
30
28
 
31
29
  ## API Reference
32
30
 
@@ -105,6 +105,60 @@ const result = await generateText({
105
105
  });
106
106
  ```
107
107
 
108
+ ### Lifecycle callbacks (experimental)
109
+
110
+ <Note type="warning">
111
+ Experimental callbacks are subject to breaking changes in incremental package
112
+ releases.
113
+ </Note>
114
+
115
+ `generateText` provides several experimental lifecycle callbacks that let you hook into different phases of the generation process.
116
+ These are useful for logging, observability, debugging, and custom telemetry.
117
+ Errors thrown inside these callbacks are silently caught and do not break the generation flow.
118
+
119
+ ```tsx
120
+ import { generateText } from 'ai';
121
+ __PROVIDER_IMPORT__;
122
+
123
+ const result = await generateText({
124
+ model: __MODEL__,
125
+ prompt: 'What is the weather in San Francisco?',
126
+ tools: {
127
+ // ... your tools
128
+ },
129
+
130
+ experimental_onStart({ model, settings, functionId }) {
131
+ console.log('Generation started', { model, functionId });
132
+ },
133
+
134
+ experimental_onStepStart({ stepNumber, model, promptMessages }) {
135
+ console.log(`Step ${stepNumber} starting`, { model: model.modelId });
136
+ },
137
+
138
+ experimental_onToolCallStart({ toolName, toolCallId, input }) {
139
+ console.log(`Tool call starting: ${toolName}`, { toolCallId });
140
+ },
141
+
142
+ experimental_onToolCallFinish({ toolName, durationMs, error }) {
143
+ console.log(`Tool call finished: ${toolName} (${durationMs}ms)`, {
144
+ success: !error,
145
+ });
146
+ },
147
+
148
+ onStepFinish({ stepNumber, finishReason, usage }) {
149
+ console.log(`Step ${stepNumber} finished`, { finishReason, usage });
150
+ },
151
+ });
152
+ ```
153
+
154
+ The available lifecycle callbacks are:
155
+
156
+ - **`experimental_onStart`**: Called once when the `generateText` operation begins, before any LLM calls. Receives model info, prompt, settings, and telemetry metadata.
157
+ - **`experimental_onStepStart`**: Called before each step (LLM call). Receives the step number, model, prompt messages being sent, tools, and prior steps.
158
+ - **`experimental_onToolCallStart`**: Called right before a tool's `execute` function runs. Receives the tool name, call ID, and input.
159
+ - **`experimental_onToolCallFinish`**: Called right after a tool's `execute` function completes or errors. Receives the tool name, call ID, input, output (or undefined on error), error (or undefined on success), and `durationMs`.
160
+ - **`onStepFinish`**: Called after each step finishes. Now also includes `stepNumber` (zero-based index of the completed step).
161
+
108
162
  ## `streamText`
109
163
 
110
164
  Depending on your model and prompt, it can take a large language model (LLM) up to a minute to finish generating its response. This delay can be unacceptable for interactive use cases such as chatbots or real-time applications, where users expect immediate responses.
@@ -451,190 +451,26 @@ try {
451
451
  }
452
452
  ```
453
453
 
454
- ## generateObject and streamObject (Legacy)
455
-
456
- <Note type="warning">
457
- `generateObject` and `streamObject` are deprecated. Use `generateText` and
458
- `streamText` with the `output` property instead. The legacy functions will be
459
- removed in a future major version.
460
- </Note>
461
-
462
- The `generateObject` and `streamObject` functions are the legacy way to generate structured data. They work similarly to `generateText` and `streamText` with `Output.object()`, but as standalone functions.
463
-
464
- ### generateObject
465
-
466
- ```ts
467
- import { generateObject } from 'ai';
468
- __PROVIDER_IMPORT__;
469
- import { z } from 'zod';
470
-
471
- const { object } = await generateObject({
472
- model: __MODEL__,
473
- schema: z.object({
474
- recipe: z.object({
475
- name: z.string(),
476
- ingredients: z.array(z.object({ name: z.string(), amount: z.string() })),
477
- steps: z.array(z.string()),
478
- }),
479
- }),
480
- prompt: 'Generate a lasagna recipe.',
481
- });
482
- ```
483
-
484
- ### streamObject
485
-
486
- ```ts
487
- import { streamObject } from 'ai';
488
- __PROVIDER_IMPORT__;
489
- import { z } from 'zod';
490
-
491
- const { partialObjectStream } = streamObject({
492
- model: __MODEL__,
493
- schema: z.object({
494
- recipe: z.object({
495
- name: z.string(),
496
- ingredients: z.array(z.object({ name: z.string(), amount: z.string() })),
497
- steps: z.array(z.string()),
498
- }),
499
- }),
500
- prompt: 'Generate a lasagna recipe.',
501
- });
502
-
503
- for await (const partialObject of partialObjectStream) {
504
- console.log(partialObject);
505
- }
506
- ```
507
-
508
- ### Schema Name and Description (Legacy)
509
-
510
- You can optionally specify a name and description for the schema. These are used by some providers for additional LLM guidance, e.g. via tool or schema name.
511
-
512
- ```ts highlight="4-5"
513
- import { generateObject } from 'ai';
514
- __PROVIDER_IMPORT__;
515
- import { z } from 'zod';
516
-
517
- const { object } = await generateObject({
518
- model: __MODEL__,
519
- schemaName: 'Recipe',
520
- schemaDescription: 'A recipe for a dish.',
521
- schema: z.object({
522
- name: z.string(),
523
- ingredients: z.array(z.object({ name: z.string(), amount: z.string() })),
524
- steps: z.array(z.string()),
525
- }),
526
- prompt: 'Generate a lasagna recipe.',
527
- });
528
- ```
529
-
530
- ### Output Strategy (Legacy)
531
-
532
- The legacy functions support different output strategies via the `output` parameter:
533
-
534
- #### Array
535
-
536
- Generate an array of objects. The schema specifies the shape of an array element.
537
-
538
- ```ts highlight="7"
539
- import { streamObject } from 'ai';
540
- __PROVIDER_IMPORT__;
541
- import { z } from 'zod';
542
-
543
- const { elementStream } = streamObject({
544
- model: __MODEL__,
545
- output: 'array',
546
- schema: z.object({
547
- name: z.string(),
548
- class: z
549
- .string()
550
- .describe('Character class, e.g. warrior, mage, or thief.'),
551
- description: z.string(),
552
- }),
553
- prompt: 'Generate 3 hero descriptions for a fantasy role playing game.',
554
- });
555
-
556
- for await (const hero of elementStream) {
557
- console.log(hero);
558
- }
559
- ```
560
-
561
- #### Enum
562
-
563
- Generate a specific enum value for classification tasks.
564
-
565
- ```ts highlight="5-6"
566
- import { generateObject } from 'ai';
567
- __PROVIDER_IMPORT__;
568
-
569
- const { object } = await generateObject({
570
- model: __MODEL__,
571
- output: 'enum',
572
- enum: ['action', 'comedy', 'drama', 'horror', 'sci-fi'],
573
- prompt:
574
- 'Classify the genre of this movie plot: ' +
575
- '"A group of astronauts travel through a wormhole in search of a ' +
576
- 'new habitable planet for humanity."',
577
- });
578
- ```
579
-
580
- #### No Schema
581
-
582
- Generate unstructured JSON without a schema.
583
-
584
- ```ts highlight="6"
585
- import { generateObject } from 'ai';
586
- __PROVIDER_IMPORT__;
587
-
588
- const { object } = await generateObject({
589
- model: __MODEL__,
590
- output: 'no-schema',
591
- prompt: 'Generate a lasagna recipe.',
592
- });
593
- ```
594
-
595
- ### Repairing Invalid JSON (Legacy)
596
-
597
- <Note type="warning">
598
- The `repairText` function is experimental and may change in the future.
599
- </Note>
600
-
601
- Sometimes the model will generate invalid or malformed JSON.
602
- You can use the `repairText` function to attempt to repair the JSON.
603
-
604
- ```ts highlight="7-10"
605
- import { generateObject } from 'ai';
606
-
607
- const { object } = await generateObject({
608
- model,
609
- schema,
610
- prompt,
611
- experimental_repairText: async ({ text, error }) => {
612
- // example: add a closing brace to the text
613
- return text + '}';
614
- },
615
- });
616
- ```
617
-
618
454
  ## More Examples
619
455
 
620
- You can see `generateObject` and `streamObject` in action using various frameworks in the following examples:
456
+ You can see structured output generation in action using various frameworks in the following examples:
621
457
 
622
- ### `generateObject`
458
+ ### `generateText` with Output
623
459
 
624
460
  <ExampleLinks
625
461
  examples={[
626
462
  {
627
- title: 'Learn to generate objects in Node.js',
463
+ title: 'Learn to generate structured data in Node.js',
628
464
  link: '/examples/node/generating-structured-data/generate-object',
629
465
  },
630
466
  {
631
467
  title:
632
- 'Learn to generate objects in Next.js with Route Handlers (AI SDK UI)',
468
+ 'Learn to generate structured data in Next.js with Route Handlers (AI SDK UI)',
633
469
  link: '/examples/next-pages/basics/generating-object',
634
470
  },
635
471
  {
636
472
  title:
637
- 'Learn to generate objects in Next.js with Server Actions (AI SDK RSC)',
473
+ 'Learn to generate structured data in Next.js with Server Actions (AI SDK RSC)',
638
474
  link: '/examples/next-app/basics/generating-object',
639
475
  },
640
476
  ]}
@@ -645,17 +481,17 @@ You can see `generateObject` and `streamObject` in action using various framewor
645
481
  <ExampleLinks
646
482
  examples={[
647
483
  {
648
- title: 'Learn to stream objects in Node.js',
484
+ title: 'Learn to stream structured data in Node.js',
649
485
  link: '/examples/node/streaming-structured-data/stream-object',
650
486
  },
651
487
  {
652
488
  title:
653
- 'Learn to stream objects in Next.js with Route Handlers (AI SDK UI)',
489
+ 'Learn to stream structured data in Next.js with Route Handlers (AI SDK UI)',
654
490
  link: '/examples/next-pages/basics/streaming-object-generation',
655
491
  },
656
492
  {
657
493
  title:
658
- 'Learn to stream objects in Next.js with Server Actions (AI SDK RSC)',
494
+ 'Learn to stream structured data in Next.js with Server Actions (AI SDK RSC)',
659
495
  link: '/examples/next-app/basics/streaming-object-generation',
660
496
  },
661
497
  ]}