> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # 단계 수업 Step 클래스는 Workflow 내의 개별 작업 단위를 정의하여 실행 논리, 데이터 유효성 검사 및 입력/출력 처리를 캡슐화합니다. Tool나 Agent를 매개변수로 사용하여 자동으로 단계를 생성할 수 있습니다. ## 사용예 ```typescript import { createWorkflow, createStep } from '@mastra/core/workflows' import { z } from 'zod' const step1 = createStep({ id: 'step-1', description: 'passes value from input to output', inputSchema: z.object({ value: z.number(), }), outputSchema: z.object({ value: z.number(), }), execute: async ({ inputData }) => { const { value } = inputData return { value, } }, }) ``` ## 스키마 정의 [표준 JSON 스키마](https://standardschema.dev/json-schema)를 지원하는 모든 라이브러리로 단계의 `inputSchema`와 `outputSchema`를 정의할 수 있습니다. 여기에는 [Zod](https://zod.dev/), [Valibot](https://valibot.dev/), [ArkType](https://arktype.io/)과 같은 라이브러리가 포함됩니다. **Zod**: ```typescript import { createStep } from '@mastra/core/workflows' import { z } from 'zod' const step1 = createStep({ id: 'step-1', inputSchema: z.object({ message: z.string(), }), outputSchema: z.object({ formatted: z.string(), }), execute: async ({ inputData }) => { const { message } = inputData return { formatted: message.toUpperCase(), } }, }) ``` **Valibot**: ```typescript import { createStep } from '@mastra/core/workflows' import * as v from 'valibot' import { toStandardJsonSchema } from '@valibot/to-json-schema' const step1 = createStep({ id: 'step-1', inputSchema: toStandardJsonSchema( v.object({ message: v.string(), }), ), outputSchema: toStandardJsonSchema( v.object({ formatted: v.string(), }), ), execute: async ({ inputData }) => { const { message } = inputData return { formatted: message.toUpperCase(), } }, }) ``` **ArkType**: ```typescript import { createStep } from '@mastra/core/workflows' import { type } from 'arktype' const step1 = createStep({ id: 'step-1', inputSchema: type({ message: 'string', }), outputSchema: type({ formatted: 'string', }), execute: async ({ inputData }) => { const { message } = inputData return { formatted: message.toUpperCase(), } }, }) ``` ## Agent에서 단계 만들기 Agent에서 직접 단계를 생성할 수 있습니다. 이 단계에서는 Agent 이름을 ID로 사용합니다. ### 기본 Agent 단계 ```typescript import { testAgent } from '../agents/test-agent' const agentStep = createStep(testAgent) // inputSchema: { prompt: string } // outputSchema: { text: string } ``` ### 구조화된 출력이 포함된 Agent 단계 Agent가 형식이 지정된 구조화 데이터를 반환하도록 하려면 `structuredOutput`을 전달하세요. ```typescript const articleSchema = z.object({ title: z.string(), summary: z.string(), tags: z.array(z.string()), }) const agentStep = createStep(testAgent, { structuredOutput: { schema: articleSchema }, }) // inputSchema: { prompt: string } // outputSchema: { title: string, summary: string, tags: string[] } ``` ### Agent 단계 옵션 **structuredOutput** (`{ schema: StandardJSONSchemaV1 }`): 제공하면 Agent가 일반 텍스트 대신 이 스키마와 일치하는 구조화 데이터를 반환합니다. 단계의 outputSchema는 제공된 스키마로 설정됩니다. **onFinish** (`(result: AgentResult) => void`): Agent가 생성을 완료할 때 호출되는 콜백입니다. ## 생성자 매개변수 **id** (`string`): 단계의 고유 식별자입니다 **description** (`string`): 단계가 수행하는 작업에 대한 선택적 설명입니다 **inputSchema** (`StandardJSONSchemaV1`): 입력 구조를 정의하는 표준 JSON 스키마입니다 **outputSchema** (`StandardJSONSchemaV1`): 출력 구조를 정의하는 표준 JSON 스키마입니다 **resumeSchema** (`StandardJSONSchemaV1`): 단계를 재개하기 위한 선택적 표준 JSON 스키마입니다 **suspendSchema** (`StandardJSONSchemaV1`): 단계를 일시 중지하기 위한 선택적 표준 JSON 스키마입니다 **stateSchema** (`StandardJSONSchemaV1`): 단계 상태를 위한 선택적 표준 JSON 스키마입니다. Mastra의 상태 시스템을 사용할 때 자동으로 주입됩니다. stateSchema는 Workflow의 stateSchema의 하위 집합이어야 합니다. 지정하지 않으면 타입은 'any'입니다. **requestContextSchema** (`StandardJSONSchemaV1`): 요청 컨텍스트 값을 검증하기 위한 표준 JSON 스키마입니다. 제공하면 단계의 execute()가 실행되기 전에 컨텍스트를 검증하며, 검증에 실패하면 단계가 실패합니다. **execute** (`(params: ExecuteParams) => Promise`): 단계 로직을 포함하는 비동기 함수입니다 **execute.inputData** (`z.infer`): inputSchema와 일치하는 입력 데이터입니다 **execute.resumeData** (`z.infer`): 일시 중지 상태에서 단계를 재개할 때 resumeSchema와 일치하는 재개 데이터입니다. 단계를 재개하는 경우에만 존재합니다. **execute.suspendData** (`z.infer`): 단계가 일시 중지될 때 suspend()에 처음 전달된 일시 중지 데이터입니다. 단계를 재개하고 있으며 이전에 데이터와 함께 일시 중지된 경우에만 존재합니다. **execute.mastra** (`Mastra`): Mastra 서비스(Agent, Tool 등)에 대한 접근 권한입니다 **execute.getStepResult** (`(step: Step | string) => any`): 다른 단계의 결과에 접근하는 함수입니다 **execute.getInitData** (`() => any`): 어느 단계에서든 Workflow의 초기 입력 데이터에 접근하는 함수입니다 **execute.suspend** (`(suspendPayload: any, suspendOptions?: { resumeLabel?: string }) => Promise`): Workflow 실행을 일시 중지하는 함수입니다 **execute.state** (`z.infer`): 현재 Workflow 상태입니다. 모든 단계와 일시 중지/재개 주기에 걸쳐 유지되는 공유 값을 포함합니다. 구조는 단계의 stateSchema로 정의됩니다. **execute.setState** (`(state: z.infer) => void`): Workflow 상태를 설정하는 함수입니다. 'setState({ ...state, ...newState })'와 같은 리듀서 유사 패턴으로 주입합니다 **execute.runId** (`string`): 현재 실행 ID입니다 **execute.requestContext** (`RequestContext`): 의존성 주입과 컨텍스트 정보를 위한 Request Context입니다. **execute.retryCount** (`number`): 이 특정 단계의 재시도 횟수이며, 단계가 재시도될 때마다 자동으로 증가합니다 **scorers** (`MastraScorers | (({ requestContext }) => MastraScorers | Promise)`): 단계가 성공적으로 완료된 후 자동으로 실행되는 채점기입니다. 각 채점기는 단계 자체의 입력과 출력을 평가하며, 결과는 저장되어 단계의 Trace에 연결됩니다. { \[name]: { scorer, sampling? } } 맵이나 이를 반환하는 함수를 제공하세요. 채점은 비동기적으로 실행되며 Workflow를 차단하지 않습니다. 단계 출력 채점을 참조하세요. **retries** (`number`): 단계의 execute 함수가 예외를 던질 경우 재시도할 횟수입니다. **metadata** (`Record`): 추가 단계 정보를 저장하기 위한 선택적 키-값 쌍입니다. 값은 직렬화할 수 있어야 합니다(함수, 순환 참조 등은 사용할 수 없음). ## 채점 단계 출력 Workflow의 최종 답변만 채점하는 대신 실행 시점에 해당 단계의 출력을 자동으로 평가하려면 단계에 `scorers`를 연결하세요. 이는 어느 단계에서 품질이 저하되었는지 확인하려는 다단계 및 RAG Workflow에 유용합니다. 예를 들어 이후 단계에서 추론하기 전에 검색 단계가 관련 청크를 반환했는지 확인할 수 있습니다. 각 채점기는 해당 단계 자체의 `input`과 `output`을 받습니다. 채점은 단계가 성공한 후 비동기적으로 실행되며, 결과는 단계의 Trace에 저장됩니다. `sampling`을 사용하여 채점기의 실행 빈도를 제어하세요. 다음 예에서는 모든 실행에 점수가 매겨지도록 채점자를 검색 단계에 연결합니다. ```typescript import { createStep } from '@mastra/core/workflows' import { z } from 'zod' import { retrievalRelevanceScorer } from '../scorers/retrieval-relevance' const retrievalStep = createStep({ id: 'retrieval', inputSchema: z.object({ query: z.string() }), outputSchema: z.object({ query: z.string(), chunks: z.array(z.string()) }), scorers: { retrievalRelevance: { scorer: retrievalRelevanceScorer(), sampling: { type: 'ratio', rate: 1 }, }, }, execute: async ({ inputData }) => { const chunks = await retrieve(inputData.query) return { query: inputData.query, chunks } }, }) ``` 측정하려는 각 단계에 채점자를 연결하여 다단계 Workflow 전반에 걸쳐 단계별 점수를 구축하세요. 채점 범위는 단일 단계로 지정되므로 품질이 변경되는 위치를 확인하기 위해 전용 교차 단계 측정항목이 필요하지 않습니다. [`Workflow.agent()`](https://mastra.zisheng.pro/ko/reference/workflows/workflow-methods/agent) 및 [`Workflow.tool()`](https://mastra.zisheng.pro/ko/reference/workflows/workflow-methods/tool)으로 추가한 Agent와 Tool 단계도 단계 옵션에서 동일한 `scorers` 옵션을 지원합니다. :::참고 실시간 평가의 실행 방식과 결과 저장 위치를 알아보려면 [채점기 개요](https://mastra.zisheng.pro/ko/docs/evals/overview)를, 직접 채점기를 만들려면 [사용자 정의 채점기](https://mastra.zisheng.pro/ko/docs/evals/custom-scorers)를 참조하세요. ::: ## 관련된 - [Workflow 상태](https://mastra.zisheng.pro/ko/docs/workflows/workflow-state) - [제어 흐름](https://mastra.zisheng.pro/ko/docs/workflows/control-flow) - [Agent 및 Tool 사용](https://mastra.zisheng.pro/ko/docs/workflows/agents-and-tools)