> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 구조화된 출력 구조화된 출력을 사용하면 Agent가 텍스트를 반환하는 대신 스키마에 정의된 모양과 일치하는 개체를 반환할 수 있습니다. 스키마는 생성할 필드를 Model에 알려주고 Model은 최종 결과가 해당 형태에 맞는지 확인합니다. ## 구조화된 출력을 사용해야 하는 경우 Agent가 텍스트가 아닌 데이터 개체를 반환해야 하는 경우 구조화된 출력을 사용합니다. 필드를 잘 정의하면 API 호출, UI 렌더링 또는 애플리케이션 로직에 필요한 값을 더 쉽게 가져올 수 있습니다. ## 스키마 정의 Agent는 다음 중 하나를 사용하여 예상 출력을 정의하여 구조화된 데이터를 반환할 수 있습니다.[Standard JSON Schema](https://standardschema.dev/json-schema) ([Zod](https://zod.dev/), [Valibot](https://valibot.dev/), [방주 유형](https://arktype.io/)등) 또는[JSON 스키마](https://json-schema.org/). Zod와 같은 라이브러리는 TypeScript 유형 추론 및 런타임 유효성 검사를 제공하므로 권장되는 반면, JSON 스키마는 언어에 구애받지 않는 형식이 필요할 때 유용합니다. **Zod**: 정의`output` shape using [Zod](https://zod.dev/): ```typescript 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) ``` **Valibot**: 정의`output` shape using [Valibot](https://valibot.dev/): ```typescript import * as v from 'valibot' import { toStandardJsonSchema } from '@valibot/to-json-schema' const response = await testAgent.generate('Help me plan my day.', { structuredOutput: { schema: toStandardJsonSchema( v.array( v.object({ name: v.string(), activities: v.array(v.string()), }), ), ), }, }) console.log(response.object) ``` **ArkType**: 정의`output` shape using [ArkType](https://arktype.io/): ```typescript import { type } from 'arktype' const response = await testAgent.generate('Help me plan my day.', { structuredOutput: { schema: type({ name: 'string', activities: 'string[]', }).array(), }, }) console.log(response.object) ``` **JSON Schema**: JSON 스키마를 사용하여 출력 구조를 정의할 수도 있습니다. ```typescript const response = await testAgent.generate('Help me plan my day.', { structuredOutput: { schema: { type: 'array', items: { type: 'object', properties: { name: { type: 'string' }, activities: { type: 'array', items: { type: 'string' }, }, }, required: ['name', 'activities'], }, }, }, }) console.log(response.object) ``` 방문하다[`.generate()`](https://mastra.zisheng.pro/ko/reference/agents/generate) for a full list of configuration options. **예제 출력:**그만큼`response.object` 에는 스키마에 정의된 구조화된 데이터가 포함됩니다. ```json [ { "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`. 텍스트 스트림 청크는 계속 내보내지지만, 구조화된 데이터가 아닌 자연어 텍스트를 포함합니다. ```typescript 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 호출이 이루어집니다. 이로 인해 지연 시간과 비용이 다소 증가하지만 복잡한 구조화 작업의 정확도를 높일 수 있습니다. ```typescript 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와 구조화된 출력 결합 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 구조화된 출력 지원 구조화된 출력 지원은 API의 차이로 인해 LLM마다 다릅니다. 아래 섹션에서는 구조화된 출력을 완전히 지원하지 않거나 이를 Tool와 결합하지 않는 Model에 대한 해결 방법을 다룹니다. ### `jsonPromptInjection` 기본적으로 Mastra는 다음을 사용하여 스키마를 Model 제공자에게 전달합니다.`response_format` API parameter. Set `jsonPromptInjection: 'auto'` 를 사용하여 Mastra가 Model 기능 데이터에 따라 모드를 선택하도록 하세요. Mastra는 지원되는 Model에는 네이티브 구조화 출력을 사용하고, 지원되지 않는 Model이나 기능 데이터가 없는 Model에는 인라인 Prompt 삽입을 사용합니다. ```typescript 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`. ```typescript const response = await agentWithTools.generate('Your prompt', { structuredOutput: { schema: yourSchema, jsonPromptInjection: true, // Required for Gemini 2.5 when tools are present }, }) ``` ::: ### 별도의 구조화 Model 사용 언제`model` is provided to the `structuredOutput` 속성을 사용하면 Mastra는 구조화된 출력을 처리하기 위해 별도의 내부 Agent를 사용합니다. 기본 Agent는 Tool 호출을 포함한 모든 단계를 처리하고, 구조화된 출력 Model은 구조화된 출력 생성만 처리합니다. **AI Agent의 경우:**그만큼`model` 속성은 Mastra의 Model 라우터 형식을 따르는 문자열입니다: `provider/model`, for example `openai/gpt-5.6-sol`, `openai/gpt-5-mini`, `anthropic/claude-sonnet-4-6` or `google/gemini-2.5-pro`. Use `/` and not `:` as a separator. Example: `openai/`, not `openai:`형식을 사용하고 Provider 객체는 전달하지 마세요. 이 형식에는 Provider import가 필요하지 않습니다. Mastra 문서에서 별도로 안내하지 않는 한 AI SDK 패키지를 설치하지 마세요. Model을 `provider/model` 형식으로 정의하면 Mastra는 지정된 Provider에 해당하는 환경 변수를 자동으로 찾습니다. 정의된 Model을 사용하려면 해당 Provider의 환경 변수가 설정되어 있어야 합니다. OpenAI: `OPENAI_API_KEY`. Anthropic: `ANTHROPIC_API_KEY`. Google: `GOOGLE_API_KEY`. ```typescript 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 컨텍스트를 연결합니다. ```typescript 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` Tool와 구조화된 출력을 함께 지원하지 않는 Model의 경우 다음을 사용할 수 있습니다.`prepareStep` to handle them in separate steps. ```typescript 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`. ```typescript 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) ```