> ## Documentation Index
> Fetch the complete documentation index at: https://docs.core-ai.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# generateObject()

> Generate structured objects validated against Zod schemas

## Overview

The `generateObject()` function generates structured, type-safe objects from chat models using Zod schema validation. This ensures the model output conforms to your expected data structure.

## Function signature

```typescript theme={null}
export async function generateObject<TSchema extends z.ZodType>(
    params: GenerateObjectParams<TSchema>
): Promise<GenerateObjectResult<TSchema>>

export type GenerateObjectParams<TSchema extends z.ZodType> = 
    GenerateObjectOptions<TSchema> & {
        model: ChatModel;
    };
```

## Parameters

<ParamField path="model" type="ChatModel" required>
  The chat model instance to use for generation.
</ParamField>

<ParamField path="messages" type="Message[]" required>
  Array of messages in the conversation. Must not be empty.
</ParamField>

<ParamField path="schema" type="z.ZodType" required>
  Zod schema that defines the structure of the object to generate.
</ParamField>

<ParamField path="schemaName" type="string">
  Optional name for the schema. Used by some providers for better results.
</ParamField>

<ParamField path="schemaDescription" type="string">
  Optional description of the schema. Helps the model understand what to generate.
</ParamField>

<ParamField path="temperature" type="number">
  Sampling temperature (0-2).
</ParamField>

<ParamField path="maxTokens" type="number">
  Maximum number of tokens to generate.
</ParamField>

<ParamField path="topP" type="number">
  Nucleus sampling parameter (0-1).
</ParamField>

<ParamField path="reasoning" type="ReasoningConfig">
  Configuration for extended thinking/reasoning capabilities.

  <Expandable title="ReasoningConfig">
    <ParamField path="effort" type="ReasoningEffort" required>
      The effort level for reasoning: `'minimal'`, `'low'`, `'medium'`, `'high'`, or `'max'`.
    </ParamField>
  </Expandable>
</ParamField>

<ParamField path="providerOptions" type="GenerateProviderOptions">
  Provider-specific options, namespaced by provider name.
</ParamField>

<ParamField path="signal" type="AbortSignal">
  AbortSignal for cancelling the request.
</ParamField>

## Return value

Returns a `Promise<GenerateObjectResult<TSchema>>` with the following properties:

<ResponseField name="object" type="z.infer<TSchema>">
  The generated object, fully typed according to your Zod schema.
</ResponseField>

<ResponseField name="finishReason" type="FinishReason">
  Why generation stopped: `'stop'`, `'length'`, `'tool-calls'`, `'content-filter'`, or `'unknown'`.
</ResponseField>

<ResponseField name="usage" type="ChatUsage">
  Token usage statistics including input/output tokens and cache details.
</ResponseField>

## Examples

### Basic object generation

```typescript theme={null}
import { generateObject } from '@core-ai/core-ai';
import { createOpenAI } from '@core-ai/openai';
import { z } from 'zod';

const openai = createOpenAI();
const model = openai.chatModel('gpt-5-mini');

const schema = z.object({
  name: z.string(),
  age: z.number(),
  email: z.string().email()
});

const result = await generateObject({
  model,
  messages: [
    { role: 'user', content: 'Generate a person named John who is 30 years old' }
  ],
  schema
});

console.log(result.object.name);
console.log(result.object.age);
console.log(result.object.email);
```

### Complex schema

```typescript theme={null}
const schema = z.object({
  title: z.string(),
  author: z.object({
    name: z.string(),
    bio: z.string()
  }),
  chapters: z.array(
    z.object({
      title: z.string(),
      summary: z.string(),
      wordCount: z.number()
    })
  ),
  publishedAt: z.string().datetime()
});

const result = await generateObject({
  model,
  messages: [
    { role: 'user', content: 'Create a book outline about artificial intelligence' }
  ],
  schema,
  schemaName: 'BookOutline',
  schemaDescription: 'A structured book outline with chapters'
});

console.log(result.object.title);
console.log(result.object.chapters.length);
```

### With configuration

```typescript theme={null}
const result = await generateObject({
  model,
  messages: [
    { role: 'user', content: 'Generate creative character profiles' }
  ],
  schema: z.object({
    characters: z.array(
      z.object({
        name: z.string(),
        personality: z.string(),
        backstory: z.string()
      })
    )
  }),
  temperature: 1.2,
  maxTokens: 1000,
});
```

### Error handling

```typescript theme={null}
import {
  CoreAIError,
  StructuredOutputError,
  StructuredOutputNoObjectGeneratedError,
  StructuredOutputParseError,
  StructuredOutputValidationError,
} from '@core-ai/core-ai';

try {
  const result = await generateObject({
    model,
    messages: [
      { role: 'user', content: 'Generate user data' }
    ],
    schema: z.object({
      name: z.string(),
      age: z.number()
    })
  });
} catch (error) {
  if (error instanceof StructuredOutputValidationError) {
    console.error('Validation errors:', error.issues);
  } else if (error instanceof StructuredOutputParseError) {
    console.error('Parse error:', error.message);
  } else if (error instanceof StructuredOutputNoObjectGeneratedError) {
    console.error('No object generated');
  } else if (error instanceof CoreAIError) {
    console.error('Generation failed:', error.message);
  }
}
```

## Type safety

The return type is fully inferred from your Zod schema:

```typescript theme={null}
const userSchema = z.object({
  id: z.number(),
  username: z.string(),
  isActive: z.boolean()
});

const result = await generateObject({
  model,
  messages: [{ role: 'user', content: 'Generate a user' }],
  schema: userSchema
});

const id: number = result.object.id;
const username: string = result.object.username;
const isActive: boolean = result.object.isActive;
```
