본문으로 건너뛰기

구조화된 출력

구조화된 출력을 사용하면 Agent가 텍스트를 반환하는 대신 스키마에 정의된 모양과 일치하는 개체를 반환할 수 있습니다. 스키마는 생성할 필드를 Model에 알려주고 Model은 최종 결과가 해당 형태에 맞는지 확인합니다.

구조화된 출력을 사용해야 하는 경우
구조화된 출력을 사용해야 하는 경우에 대한 직접 링크

Agent가 텍스트가 아닌 데이터 개체를 반환해야 하는 경우 구조화된 출력을 사용합니다. 필드를 잘 정의하면 API 호출, UI 렌더링 또는 애플리케이션 로직에 필요한 값을 더 쉽게 가져올 수 있습니다.

스키마 정의
스키마 정의에 대한 직접 링크

Agent는 다음 중 하나를 사용하여 예상 출력을 정의하여 구조화된 데이터를 반환할 수 있습니다.Standard JSON Schema (Zod, Valibot, 방주 유형등) 또는JSON 스키마. Zod와 같은 라이브러리는 TypeScript 유형 추론 및 런타임 유효성 검사를 제공하므로 권장되는 반면, JSON 스키마는 언어에 구애받지 않는 형식이 필요할 때 유용합니다.

정의output shape using Zod:

import { z } from 'zod'

const response = await testAgent.generate('Help me plan my day.', {
structuredOutput: {
schema: z.array(
z.object({
name: z.string(),
activities: z.array(z.string()),
}),
),
},
})

console.log(response.object)

방문하다.generate() for a full list of configuration options.

예제 출력:그만큼response.object 에는 스키마에 정의된 구조화된 데이터가 포함됩니다.

[
{
"name": "Morning Routine",
"activities": ["Wake up at 7am", "Exercise", "Shower", "Breakfast"]
},
{
"name": "Work",
"activities": ["Check emails", "Team meeting", "Lunch break"]
},
{
"name": "Evening",
"activities": ["Dinner", "Relax", "Read a book", "Sleep by 10pm"]
}
]

스트림 구조화된 출력
스트림 구조화된 출력에 대한 직접 링크

스트리밍은 구조화된 출력도 지원합니다. 최종 구조화된 객체는 다음에서 사용할 수 있습니다.stream.fullStream and after the stream completes on stream.object. 텍스트 스트림 청크는 계속 내보내지지만, 구조화된 데이터가 아닌 자연어 텍스트를 포함합니다.

import { z } from 'zod'

const stream = await testAgent.stream('Help me plan my day.', {
structuredOutput: {
schema: z.array(
z.object({
name: z.string(),
activities: z.array(z.string()),
}),
),
},
})

for await (const chunk of stream.fullStream) {
if (chunk.type === 'object-result') {
console.log('\n', JSON.stringify(chunk, null, 2))
}
process.stdout.write(JSON.stringify(chunk))
}

console.log(await stream.object)

for await (const chunk of stream.textStream) {
process.stdout.write(chunk)
}

구조화 대리인
구조화 대리인에 대한 직접 링크

주 Agent가 구조화된 출력을 생성하는 데 능숙하지 않은 경우model to structuredOutput. 이 경우 Mastra는 내부적으로 두 번째 Agent를 사용하여 기본 Agent의 자연어 응답에서 구조화된 데이터를 추출합니다. 이 과정에서는 응답을 생성하기 위한 호출과 해당 응답을 구조화된 객체로 변환하기 위한 호출, 총 두 번의 LLM 호출이 이루어집니다. 이로 인해 지연 시간과 비용이 다소 증가하지만 복잡한 구조화 작업의 정확도를 높일 수 있습니다.

import { z } from 'zod'

const response = await testAgent.generate('Analyze the TypeScript programming language.', {
structuredOutput: {
schema: z.object({
overview: z.string(),
strengths: z.array(z.string()),
weaknesses: z.array(z.string()),
useCases: z.array(
z.object({
scenario: z.string(),
reasoning: z.string(),
}),
),
comparison: z.object({
similarTo: z.array(z.string()),
differentiators: z.array(z.string()),
}),
}),
model: 'openai/gpt-5.6-sol',
},
})

console.log(response.object)

Tool와 구조화된 출력 결합
Tool와 구조화된 출력 결합에 대한 직접 링크

Agent에 Tool와 구조화된 출력이 모두 구성된 경우 일부 Model은 두 기능을 함께 사용하는 것을 지원하지 않을 수 있습니다. 이는 Mastra 자체가 아닌 기본 Model API의 제한 사항입니다.

구조화된 출력이 활성화되었을 때 Tool이 호출되지 않거나 두 기능을 결합할 때 오류가 발생하는 경우 아래 해결 방법 중 하나를 시도해 보세요.

해결 방법 옵션
해결 방법 옵션에 대한 직접 링크

Model이 Tool와 구조화된 출력을 함께 지원하지 않는 경우 세 가지 옵션이 있습니다.

  1. 사용jsonPromptInjection: 다음으로 설정하세요.'auto' 를 사용하여 지원되는 경우 네이티브 구조화 출력을 선택하고, 그 외에는 인라인 Prompt 삽입을 선택하거나 명시적인 삽입 모드를 선택하세요
  2. 별도의 구조화 Model 사용: 통과model to structuredOutput to use a second LLM for structuring
  3. 사용prepareStep: Tool와 구조화된 출력을 별도의 단계로 처리합니다.

각 접근 방식은 아래 섹션에 자세히 설명되어 있습니다.

LLM 구조화된 출력 지원
LLM 구조화된 출력 지원에 대한 직접 링크

구조화된 출력 지원은 API의 차이로 인해 LLM마다 다릅니다. 아래 섹션에서는 구조화된 출력을 완전히 지원하지 않거나 이를 Tool와 결합하지 않는 Model에 대한 해결 방법을 다룹니다.

jsonPromptInjection
jsonpromptinjection에 대한 직접 링크

기본적으로 Mastra는 다음을 사용하여 스키마를 Model 제공자에게 전달합니다.response_format API parameter. Set jsonPromptInjection: 'auto' 를 사용하여 Mastra가 Model 기능 데이터에 따라 모드를 선택하도록 하세요. Mastra는 지원되는 Model에는 네이티브 구조화 출력을 사용하고, 지원되지 않는 Model이나 기능 데이터가 없는 Model에는 인라인 Prompt 삽입을 사용합니다.

import { z } from 'zod'

const response = await testAgent.generate('Help me plan my day.', {
structuredOutput: {
schema: z.array(
z.object({
name: z.string(),
activities: z.array(z.string()),
}),
),
jsonPromptInjection: 'auto',
},
})

console.log(response.object)

기능 기반 선택을 재정의해야 하는 경우 명시적 모드를 사용합니다.

  • false또는 생략됨: 공급자의 기본 구조화된 출력을 사용합니다.
  • 'inline': 최신 사용자 메시지에 스키마 지침을 추가합니다.
  • true또는'system': 시스템 메시지에 스키마 지침을 추가합니다.
  • 'auto': Model이 지원하는 경우 기본 구조화된 출력을 사용합니다. 그렇지 않으면 인라인 Prompt 삽입을 사용하세요.

:::참고[Tool이 포함된 Gemini 2.5]

Gemini 2.5 Model은 결합을 지원하지 않습니다.response_format (구조화된 출력)을 동일한 API 호출에서 함수 호출(Tool)과 함께 사용할 수 없습니다. Agent에 Tool이 있고 structuredOutput with a Gemini 2.5 model, you must set jsonPromptInjection: true to avoid the error Function calling with a response mime type: 'application/json' is unsupported.

const response = await agentWithTools.generate('Your prompt', {
structuredOutput: {
schema: yourSchema,
jsonPromptInjection: true, // Required for Gemini 2.5 when tools are present
},
})

:::

별도의 구조화 Model 사용
별도의 구조화 Model 사용에 대한 직접 링크

언제model is provided to the structuredOutput 속성을 사용하면 Mastra는 구조화된 출력을 처리하기 위해 별도의 내부 Agent를 사용합니다. 기본 Agent는 Tool 호출을 포함한 모든 단계를 처리하고, 구조화된 출력 Model은 구조화된 출력 생성만 처리합니다.

const response = await testAgent.generate('Tell me about TypeScript.', {
structuredOutput: {
schema: yourSchema,
model: 'openai/gpt-5.6-sol',
},
})

해당 구조화 Model이 현재 대화 기록도 볼 수 있도록 하려면 다음을 설정하세요.useAgent: true alongside model. Mastra는 별도의 구조화 Model과 함께 상위 Agent를 재사용하며, thread를 사용할 수 있는 경우 읽기 전용 Memory 컨텍스트를 연결합니다.

const response = await testAgent.generate('Return my profile as structured data.', {
memory: {
thread: 'thread-123',
resource: 'user-123',
},
structuredOutput: {
schema: z.object({
favoriteColor: z.string(),
hometown: z.string(),
petName: z.string(),
}),
model: 'openai/gpt-5.6-sol',
useAgent: true,
},
})

떠나다useAgent 별도의 구조화 Model이 현재 응답만을 기반으로 작동하고 이전 대화 Memory를 상속하지 않게 하려면 설정하지 않은 상태로 두세요.

다단계 접근 방식prepareStep
multi-step-approach-with-preparestep에 대한 직접 링크

Tool와 구조화된 출력을 함께 지원하지 않는 Model의 경우 다음을 사용할 수 있습니다.prepareStep to handle them in separate steps.

const result = await agent.stream('weather in vancouver?', {
prepareStep: async ({ stepNumber }) => {
if (stepNumber === 0) {
return {
model: 'openai/gpt-5.6-sol',
tools: {
weatherTool,
},
toolChoice: 'required',
}
}
return {
model: 'openai/gpt-5.6-sol',
tools: undefined,
structuredOutput: {
schema: z.object({
temperature: z.number(),
humidity: z.number(),
windSpeed: z.number(),
}),
},
}
},
})

오류 처리
오류 처리에 대한 직접 링크

스키마 유효성 검사가 실패하면 다음을 사용하여 오류 처리 방법을 제어할 수 있습니다.errorStrategy. The default strict strategy throws an error, while warn logs a warning and continues. The fallback strategy returns the values provided using fallbackValue.

const response = await testAgent.generate('Tell me about TypeScript.', {
structuredOutput: {
schema: z.object({
summary: z.string(),
keyFeatures: z.array(z.string()),
}),
errorStrategy: 'fallback',
fallbackValue: {
summary: 'TypeScript is a typed superset of JavaScript',
keyFeatures: ['Static typing', 'Compiles to JavaScript', 'Better tooling'],
},
},
})

console.log(response.object)