---
title: "Reference: Agent.generate() | Agents"
description: "Documentation for the `Agent.generate()` method in Mastra agents, which enables non-streaming generation of responses with enhanced capabilities."
packages:
  - "@mastra/core"
---

import { MODEL_SETTINGS_OBJECT } from "@site/src/components/ModelSettingsProperties";

# Agent.generate()

The `.generate()` method enables non-streaming response generation from an agent with enhanced capabilities. It accepts messages and optional generation options.

## Usage example

```typescript
// Basic usage
const result = await agent.generate("message for agent");

// With model settings (e.g., limiting output tokens)
const limitedResult = await agent.generate("Write a short poem about coding", {
  modelSettings: {
    maxOutputTokens: 50,
    temperature: 0.7,
  },
});

// With structured output
const structuredResult = await agent.generate("Extract the user's name and age", {
  structuredOutput: {
    schema: z.object({
      name: z.string(),
      age: z.number(),
    }),
  },
});

// With memory for conversation persistence
const memoryResult = await agent.generate("Remember my favorite color is blue", {
  memory: {
    thread: "user-123-thread",
    resource: "user-123",
  },
});
```

:::info

**Model Compatibility**: This method requires AI SDK v5+ models. If you're using AI SDK v4 models, use the [`.generateLegacy()`](./generateLegacy) method instead. The framework automatically detects your model version and will throw an error if there's a mismatch.

:::

## Parameters

<PropertiesTable
  content={[
    {
      name: "messages",
      type: "string | string[] | CoreMessage[] | AiMessageType[] | UIMessageWithMetadata[]",
      description:
        "The messages to send to the agent. Can be a single string, array of strings, or structured message objects.",
    },
    {
      name: "options",
      type: "AgentExecutionOptions<Output, Format>",
      isOptional: true,
      description: "Optional configuration for the generation process.",
    },
  ]}
/>

### Options

<PropertiesTable
  content={[
    {
      name: "maxSteps",
      type: "number",
      isOptional: true,
      description: "Maximum number of steps to run during execution.",
    },
    {
      name: "stopWhen",
      type: "LoopOptions['stopWhen']",
      isOptional: true,
      description: "Conditions for stopping execution (e.g., step count, token limit).",
    },
    {
      name: "scorers",
      type: "MastraScorers | Record<string, { scorer: MastraScorer['name']; sampling?: ScoringSamplingConfig }>",
      isOptional: true,
      description: "Evaluation scorers to run on the execution results.",
      properties: [
        {
          parameters: [
            {
              name: "scorer",
              type: "string",
              isOptional: false,
              description: "Name of the scorer to use.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "sampling",
              type: "ScoringSamplingConfig",
              isOptional: true,
              description: "Sampling configuration for the scorer.",
              properties: [
                {
                  parameters: [
                    {
                      name: "type",
                      type: "'none' | 'ratio'",
                      isOptional: false,
                      description:
                        "Type of sampling strategy. Use 'none' to disable sampling or 'ratio' for percentage-based sampling.",
                    },
                  ],
                },
                {
                  parameters: [
                    {
                      name: "rate",
                      type: "number",
                      isOptional: true,
                      description:
                        "Sampling rate (0-1). Required when type is 'ratio'.",
                    },
                  ],
                },
              ],
            },
          ],
        },
      ],
    },
    {
      name: "returnScorerData",
      type: "boolean",
      isOptional: true,
      description: "Whether to return detailed scoring data in the response.",
    },
    {
      name: "onChunk",
      type: "(chunk: ChunkType) => Promise<void> | void",
      isOptional: true,
      description: "Callback function called for each chunk during generation.",
    },
    {
      name: "onError",
      type: "({ error }: { error: Error | string }) => Promise<void> | void",
      isOptional: true,
      description:
        "Callback function called when an error occurs during generation.",
    },
    {
      name: "onAbort",
      type: "(event: any) => Promise<void> | void",
      isOptional: true,
      description: "Callback function called when the generation is aborted.",
    },
    {
      name: "activeTools",
      type: "Array<keyof ToolSet> | undefined",
      isOptional: true,
      description:
        "Array of tool names that should be active during execution. If undefined, all available tools are active.",
    },
    {
      name: "abortSignal",
      type: "AbortSignal",
      isOptional: true,
      description:
        "Signal object that allows you to abort the agent's execution. When the signal is aborted, all ongoing operations will be terminated.",
    },
    {
      name: "prepareStep",
      type: "PrepareStepFunction",
      isOptional: true,
      description:
        "Callback function called before each step of multi-step execution.",
    },
    {
      name: "requireToolApproval",
      type: "boolean",
      isOptional: true,
      description: "Require approval for all tool calls before execution.",
    },
    {
      name: "autoResumeSuspendedTools",
      type: "boolean",
      isOptional: true,
      description: "Automatically resume suspended tools.",
    },
    {
      name: "toolCallConcurrency",
      type: "number",
      isOptional: true,
      description: "Maximum number of tool calls to execute concurrently. Defaults to 1 when approval may be required, otherwise 10.",
    },
    {
      name: "context",
      type: "ModelMessage[]",
      isOptional: true,
      description: "Additional context messages to provide to the agent.",
    },
    {
      name: "structuredOutput",
      type: "StructuredOutputOptions<S extends ZodTypeAny = ZodTypeAny>",
      isOptional: true,
      description: "Options to fine tune your structured output generation.",
      properties: [
        {
          parameters: [
            {
              name: "schema",
              type: "z.ZodSchema<S>",
              isOptional: false,
              description: "Zod schema defining the expected output structure.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "model",
              type: "MastraLanguageModel",
              isOptional: true,
              description:
                "Language model to use for structured output generation. If provided, enables the agent to respond in multi step with tool calls, text, and structured output",
            },
          ],
        },
        {
          parameters: [
            {
              name: "errorStrategy",
              type: "'strict' | 'warn' | 'fallback'",
              isOptional: true,
              description:
                "Strategy for handling schema validation errors. 'strict' throws errors, 'warn' logs warnings, 'fallback' uses fallback values.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "fallbackValue",
              type: "<S extends ZodTypeAny>",
              isOptional: true,
              description:
                "Fallback value to use when schema validation fails and errorStrategy is 'fallback'.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "instructions",
              type: "string",
              isOptional: true,
              description:
                "Additional instructions for the structured output model.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "jsonPromptInjection",
              type: "boolean",
              isOptional: true,
              description:
                "Injects system prompt into the main agent instructing it to return structured output, useful for when a model does not natively support structured outputs.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "logger",
              type: "IMastraLogger",
              isOptional: true,
              description:
                "Optional logger instance for structured logging during output generation.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "providerOptions",
              type: "ProviderOptions",
              isOptional: true,
              description:
                "Provider-specific options passed to the internal structuring agent. Use this to control model behavior like reasoning effort for thinking models (e.g., `{ openai: { reasoningEffort: 'low' } }`).",
            },
          ],
        },
      ],
    },
    {
      name: "outputProcessors",
      type: "OutputProcessorOrWorkflow[]",
      isOptional: true,
      description:
        "Output processors to use for this execution (overrides agent's default).",
    },
    {
      name: "maxProcessorRetries",
      type: "number",
      isOptional: true,
      description:
        "Maximum number of times processors can trigger a retry for this generation. Overrides agent's default maxProcessorRetries.",
    },
    {
      name: "inputProcessors",
      type: "InputProcessorOrWorkflow[]",
      isOptional: true,
      description:
        "Input processors to use for this execution (overrides agent's default).",
    },
    {
      name: "instructions",
      type: "string | string[] | CoreSystemMessage | SystemModelMessage | CoreSystemMessage[] | SystemModelMessage[]",
      isOptional: true,
      description:
        "Custom instructions that override the agent's default instructions for this execution. Can be a single string, message object, or array of either.",
    },
    {
      name: "system",
      type: "string | string[] | CoreSystemMessage | SystemModelMessage | CoreSystemMessage[] | SystemModelMessage[]",
      isOptional: true,
      description:
        "Custom system message(s) to include in the prompt. Can be a single string, message object, or array of either. System messages provide additional context or behavior instructions that supplement the agent's main instructions.",
    },
    {
      name: "output",
      type: "Zod schema | JsonSchema7",
      isOptional: true,
      description:
        "**Deprecated.** Use structuredOutput without a model to achieve the same thing. Defines the expected structure of the output. Can be a JSON Schema object or a Zod schema.",
    },
    {
      name: "memory",
      type: "object",
      isOptional: true,
      description:
        "Memory configuration for conversation persistence and retrieval.",
      properties: [
        {
          parameters: [
            {
              name: "thread",
              type: "string | { id: string; metadata?: Record<string, any>, title?: string }",
              isOptional: false,
              description:
                "Thread identifier for conversation continuity. Can be a string ID or an object with ID and optional metadata/title.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "resource",
              type: "string",
              isOptional: false,
              description:
                "Resource identifier for organizing conversations by user, session, or context.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "options",
              type: "MemoryConfig",
              isOptional: true,
              description:
                "Additional memory configuration options including lastMessages, readOnly, semanticRecall, and workingMemory.",
            },
          ],
        },
      ],
    },
    {
      name: "onFinish",
      type: "LoopConfig['onFinish']",
      isOptional: true,
      description:
        "Callback fired when generation completes.",
    },
    {
      name: "onStepFinish",
      type: "LoopConfig['onStepFinish']",
      isOptional: true,
      description:
        "Callback fired after each generation step.",
    },
    {
      name: "resourceId",
      type: "string",
      isOptional: true,
      description:
        "Deprecated. Use memory.resource instead. Identifier for the resource/user.",
    },
    {
      name: "telemetry",
      type: "TelemetrySettings",
      isOptional: true,
      description:
        "Settings for OTLP telemetry collection during generation (not Tracing).",
      properties: [
        {
          parameters: [
            {
              name: "isEnabled",
              type: "boolean",
              isOptional: true,
              description: "Whether telemetry collection is enabled.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "recordInputs",
              type: "boolean",
              isOptional: true,
              description: "Whether to record input data in telemetry.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "recordOutputs",
              type: "boolean",
              isOptional: true,
              description: "Whether to record output data in telemetry.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "functionId",
              type: "string",
              isOptional: true,
              description: "Identifier for the function being executed.",
            },
          ],
        },
      ],
    },
    MODEL_SETTINGS_OBJECT,
    {
      name: "threadId",
      type: "string",
      isOptional: true,
      description:
        "Deprecated. Use memory.thread instead. Thread identifier for conversation continuity.",
    },
    {
      name: "toolChoice",
      type: "'auto' | 'none' | 'required' | { type: 'tool'; toolName: string }",
      isOptional: true,
      description: "Controls how tools are selected during generation.",
      properties: [
        {
          parameters: [
            {
              name: "'auto'",
              type: "string",
              isOptional: false,
              description: "Let the model decide when to use tools (default).",
            },
          ],
        },
        {
          parameters: [
            {
              name: "'none'",
              type: "string",
              isOptional: false,
              description: "Disable tool usage entirely.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "'required'",
              type: "string",
              isOptional: false,
              description: "Force the model to use at least one tool.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "{ type: 'tool'; toolName: string }",
              type: "object",
              isOptional: false,
              description: "Force the model to use a specific tool.",
            },
          ],
        },
      ],
    },
    {
      name: "toolsets",
      type: "ToolsetsInput",
      isOptional: true,
      description: "Additional tool sets that can be used for this execution.",
    },
    {
      name: "clientTools",
      type: "ToolsInput",
      isOptional: true,
      description: "Client-side tools available during execution.",
    },
    {
      name: "savePerStep",
      type: "boolean",
      isOptional: true,
      description:
        "Save messages incrementally after each generation step completes (default: false).",
    },
    {
      name: "providerOptions",
      type: "Record<string, Record<string, JSONValue>>",
      isOptional: true,
      description: "Provider-specific options passed to the language model.",
      properties: [
        {
          parameters: [
            {
              name: "openai",
              type: "Record<string, JSONValue>",
              isOptional: true,
              description:
                "OpenAI-specific options like reasoningEffort, responseFormat, etc.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "anthropic",
              type: "Record<string, JSONValue>",
              isOptional: true,
              description: "Anthropic-specific options like maxTokens, etc.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "google",
              type: "Record<string, JSONValue>",
              isOptional: true,
              description: "Google-specific options.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "[providerName]",
              type: "Record<string, JSONValue>",
              isOptional: true,
              description: "Any provider-specific options.",
            },
          ],
        },
      ],
    },
    {
      name: "runId",
      type: "string",
      isOptional: true,
      description: "Unique identifier for this execution run.",
    },
    {
      name: "requestContext",
      type: "RequestContext",
      isOptional: true,
      description:
        "Request Context containing dynamic configuration and state.",
    },
    {
      name: "tracingContext",
      type: "TracingContext",
      isOptional: true,
      description:
        "Tracing context for creating child spans and adding metadata. Automatically injected when using Mastra's tracing system.",
      properties: [
        {
          parameters: [
            {
              name: "currentSpan",
              type: "Span",
              isOptional: true,
              description:
                "Current span for creating child spans and adding metadata. Use this to create custom child spans or update span attributes during execution.",
            },
          ],
        },
      ],
    },
    {
      name: "tracingOptions",
      type: "TracingOptions",
      isOptional: true,
      description: "Options for Tracing configuration.",
      properties: [
        {
          parameters: [
            {
              name: "metadata",
              type: "Record<string, any>",
              isOptional: true,
              description:
                "Metadata to add to the root trace span. Useful for adding custom attributes like user IDs, session IDs, or feature flags.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "requestContextKeys",
              type: "string[]",
              isOptional: true,
              description:
                "Additional RequestContext keys to extract as metadata for this trace. Supports dot notation for nested values (e.g., 'user.id').",
            },
          ],
        },
        {
          parameters: [
            {
              name: "traceId",
              type: "string",
              isOptional: true,
              description:
                "Trace ID to use for this execution (1-32 hexadecimal characters). If provided, this trace will be part of the specified trace.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "parentSpanId",
              type: "string",
              isOptional: true,
              description:
                "Parent span ID to use for this execution (1-16 hexadecimal characters). If provided, the root span will be created as a child of this span.",
            },
          ],
        },
        {
          parameters: [
            {
              name: "tags",
              type: "string[]",
              isOptional: true,
              description:
                "Tags to apply to this trace. String labels for categorizing and filtering traces.",
            },
          ],
        },
      ],
    },
    {
      name: "includeRawChunks",
      type: "boolean",
      isOptional: true,
      description:
        "Whether to include raw chunks in the stream output. Not available on all model providers.",
    },
  ]}
/>

## Returns

<PropertiesTable
  content={[
    {
      name: "result",
      type: "Awaited<ReturnType<MastraModelOutput<Output>['getFullOutput']>>",
      description:
        "Returns the full output of the generation process including text, object (if structured output), tool calls, tool results, usage statistics, and step information.",
    },
    {
      name: "text",
      type: "string",
      description:
        "The generated text response from the agent.",
    },
    {
      name: "object",
      type: "Output | undefined",
      isOptional: true,
      description:
        "The structured output object if structuredOutput was provided, validated against the schema.",
    },
    {
      name: "toolCalls",
      type: "ToolCall[]",
      description:
        "Array of tool calls made during generation.",
    },
    {
      name: "toolResults",
      type: "ToolResult[]",
      description:
        "Array of results from tool executions.",
    },
    {
      name: "usage",
      type: "TokenUsage",
      description:
        "Token usage statistics for the generation.",
    },
    {
      name: "steps",
      type: "Step[]",
      description:
        "Array of execution steps, useful for debugging multi-step generations.",
    },
    {
      name: "finishReason",
      type: "string",
      description:
        "The reason generation finished (e.g., 'stop', 'tool-calls', 'error').",
    },
    {
      name: "traceId",
      type: "string",
      isOptional: true,
      description:
        "The trace ID associated with this execution when Tracing is enabled. Use this to correlate logs and debug execution flow.",
    },
  ]}
/>
