콘텐츠로 이동

스키마 검증

SDK는 스키마를 사용해 구조화된 데이터를 모델에 설명하고 애플리케이션 내에서 데이터를 검증합니다. 로컬 검증과 타입 추론의 필요 여부에 따라 스키마 형식을 선택하세요.

스키마 형식로컬 검증 및 변환TypeScript 타입 추론지원되는 사용 지점
Zod 객체지원지원함수 도구 및 에이전트 도구의 parameters, 함수 도구의 outputSchema, 에이전트의 outputType, 핸드오프의 inputType
Standard JSON Schema 변환을 지원하는 Standard Schema동기 방식으로 지원검증 출력 타입에서 추론함수 도구 및 에이전트 도구의 parameters, 에이전트의 outputType, 핸드오프의 inputType
원문 JSON Schema미지원. SDK는 JSON 파싱만 수행미지원. 값의 타입은 unknown함수 도구 및 에이전트 도구의 parameters, 함수 도구의 outputSchema, 에이전트의 outputType, 핸드오프의 inputType

Zod가 애플리케이션에 이미 적합하다면 Zod를 사용하세요. 다른 호환 검증 라이브러리를 사용하면서 동일한 SDK 검증 기능과 출력 타입 추론이 필요하다면 Standard Schema를 사용하세요. 전송용 스키마를 이미 관리하고 있으며 다른 곳에서 값을 검증할 계획이라면 원문 JSON Schema를 사용하세요.

호환되는 값은 Standard Schema V1 검증과 Standard JSON Schema 변환을 구현해야 합니다. 일부 라이브러리는 두 기능을 모두 직접 제공하고, 다른 라이브러리는 어댑터를 제공합니다. 이 예제에서는 Valibot과 @valibot/to-json-schema의 toStandardJsonSchema()를 사용합니다.

이미 @openai/agents를 사용하는 애플리케이션에서 npm install valibot @valibot/to-json-schema로 예제의 의존성을 설치하세요.

도구, 에이전트 출력, 핸드오프용 Valibot 스키마
import { Agent, handoff, tool } from '@openai/agents';
import { toStandardJsonSchema } from '@valibot/to-json-schema';
import * as v from 'valibot';
const LookupOrderParameters = toStandardJsonSchema(
v.object({
orderId: v.pipe(v.string(), v.minLength(1)),
includeHistory: v.optional(v.boolean(), false),
}),
);
const lookupOrder = tool({
name: 'lookup_order',
description: 'Look up an order by ID.',
parameters: LookupOrderParameters,
// The argument type is inferred after Valibot validation and defaults run.
execute: async ({ orderId, includeHistory }) => ({
orderId,
status: 'shipped',
history: includeHistory ? ['placed', 'shipped'] : undefined,
}),
});
const Resolution = toStandardJsonSchema(
v.object({
orderId: v.string(),
message: v.string(),
}),
);
const supportAgent = new Agent({
name: 'Order support',
instructions: 'Resolve order questions and return a structured summary.',
tools: [lookupOrder],
// The final output is converted to JSON Schema, then validated by Valibot.
outputType: Resolution,
});
const supportAgentTool = supportAgent.asTool({
toolName: 'resolve_order',
toolDescription: 'Resolve an order question with the support specialist.',
parameters: LookupOrderParameters,
// inputBuilder receives the same validated and inferred parameter type.
inputBuilder: ({ params }) =>
`Resolve order ${params.orderId}. Include history: ${params.includeHistory}.`,
});
const EscalationDetails = toStandardJsonSchema(
v.object({
reason: v.pipe(v.string(), v.minLength(1)),
priority: v.optional(v.picklist(['normal', 'urgent']), 'normal'),
}),
);
const billingAgent = new Agent({
name: 'Billing specialist',
instructions: 'Resolve billing questions.',
});
const billingHandoff = handoff(billingAgent, {
inputType: EscalationDetails,
// The callback receives the validated value, including Valibot defaults.
onHandoff: async (_context, details) => {
if (details) {
await recordEscalation(details.reason, details.priority);
}
},
});
async function recordEscalation(_reason: string, _priority: string) {}
export { billingHandoff, supportAgent, supportAgentTool };

동일한 스키마 계약이 각 사용 지점에서 수행하는 역할은 다음과 같습니다.

  • tool({ parameters })는 모델에 전달할 스키마를 변환하고, 각 도구 호출을 로컬에서 검증하며, 라이브러리의 변환이나 기본값을 적용한 후 추론된 검증 출력을 execute에 전달합니다.
  • agent.asTool({ parameters })은 동일한 검증을 적용하고, 중첩된 에이전트가 실행되기 전에 추론된 검증 출력을 inputBuilder에 전달합니다.
  • new Agent({ outputType })는 구조화된 모델 출력을 요청하고, 파싱된 값을 로컬에서 검증하며, 추론된 검증 출력을 result.finalOutput을 통해 제공합니다.
  • handoff(..., { inputType })은 핸드오프 도구 호출 인수를 검증하고, 추론된 검증 출력을 onHandoff에 전달합니다.

Standard Schema 지원 계약의 범위는 의도적으로 좁게 제한되어 있습니다.

  • 값은 동기식 ~standard.validate 동작과 ~standard.jsonSchema.input(), ~standard.jsonSchema.output()을 모두 제공해야 합니다. 검증만 지원하는 Standard Schema 값은 지원되지 않습니다.
  • 이러한 SDK 사용 지점에서 사용하는 입력 JSON Schema는 루트에 type: "object"가 있어야 합니다. 스칼라 또는 배열 값은 객체 스키마로 감싸세요.
  • Standard Schema를 사용하는 함수 도구 매개변수에는 엄격 모드가 필요합니다. 이를 사용할 때는 strict: false를 설정하지 마세요.
  • 비동기 Standard Schema 검증은 지원되지 않습니다. 검증기가 Promise를 반환하면 도구 폴백이나 유효하지 않은 최종 출력에 대한 핸들러를 실행하는 대신 작업이 실패합니다.
  • 생성된 JSON Schema는 SDK의 엄격한 스키마 정규화에서 지원하는 구문을 사용해야 합니다. 지원되지 않는 구문이 있으면 모델 요청 전에 도구, 핸드오프 또는 에이전트를 생성하는 시점에 실패합니다.
  • 함수 도구의 outputSchema는 현재 Standard Schema를 허용하지 않습니다. Zod 스키마나 원문 JSON Schema를 사용하거나, 애플리케이션 코드에서 도구 결과를 검증하세요.

직접 어댑터를 작성한다면 @openai/agents에서 StandardSchemaWithJSON<Input, Output> 타입을 가져와 필수 검증 및 변환 메서드를 제공하는지 확인하세요. 라이브러리에서 유지 관리하는 어댑터가 있다면 이를 우선 사용하세요.