에이전트 실행
에이전트는 스스로 아무것도 하지 않습니다. Runner 클래스 또는 run() 유틸리티로 이를 실행합니다.
import { Agent, run } from '@openai/agents';
const agent = new Agent({ name: 'Assistant', instructions: 'You are a helpful assistant',});
const result = await run( agent, 'Write a haiku about recursion in programming.',);console.log(result.finalOutput);
// Code within the code,// Functions calling themselves,// Infinite loop's dance.사용자 지정 runner 가 필요하지 않다면 싱글톤 기본 Runner 인스턴스를 실행하는 run() 유틸리티를 사용할 수 있습니다.
또는 자체 runner 인스턴스를 만들 수도 있습니다:
import { Agent, Runner } from '@openai/agents';
const agent = new Agent({ name: 'Assistant', instructions: 'You are a helpful assistant',});
// You can pass custom configuration to the runnerconst runner = new Runner();
const result = await runner.run( agent, 'Write a haiku about recursion in programming.',);console.log(result.finalOutput);
// Code within the code,// Functions calling themselves,// Infinite loop's dance.에이전트를 실행한 후에는 최종 출력과 실행의 전체 기록을 포함하는 실행 결과 객체를 받게 됩니다.
에이전트 루프
섹션 제목: “에이전트 루프”Runner 에서 run 메서드를 사용할 때 시작 에이전트와 입력을 전달합니다. 입력은 문자열(사용자 메시지로 간주됨) 또는 OpenAI Responses API 의 항목과 동일한 입력 항목 목록일 수 있습니다.
runner 는 다음과 같은 루프를 실행합니다:
- 현재 입력으로 현재 에이전트의 모델을 호출합니다.
- LLM 응답을 검사합니다.
- 최종 출력 → 반환
- 핸드오프 → 새 에이전트로 전환, 누적된 대화 기록 유지, 1 로 이동
- 도구 호출 → 도구 실행, 그 결과를 대화에 추가, 1 로 이동
maxTurns에 도달하면MaxTurnsExceededError를 발생시킵니다.
Runner 수명 주기
섹션 제목: “Runner 수명 주기”앱이 시작될 때 Runner 를 만들고 요청 간에 재사용하세요. 인스턴스는 모델 제공자 및 트레이싱 옵션과 같은 전역 구성을 저장합니다. 완전히 다른 설정이 필요할 때만 다른 Runner 를 만드세요. 간단한 스크립트의 경우 내부적으로 기본 runner 를 사용하는 run() 을 호출할 수도 있습니다.
실행 인수
섹션 제목: “실행 인수”run() 메서드의 입력은 실행을 시작할 초기 에이전트, 실행에 대한 입력, 그리고 옵션 집합입니다.
입력은 문자열(사용자 메시지로 간주됨), 입력 항목 목록, 또는 휴먼 인 더 루프 (HITL) 에이전트를 구축하는 경우 RunState 객체일 수 있습니다.
추가 옵션은 다음과 같습니다:
| Option | Default | Description |
|---|---|---|
stream | false | true 이면 호출은 StreamedRunResult 를 반환하고 모델에서 도착하는 대로 이벤트를 발행합니다. |
context | – | 모든 tool / guardrail / handoff 에 전달되는 컨텍스트 객체입니다. 컨텍스트 관리에서 자세히 알아보세요. |
maxTurns | 10 | 안전 한도 – 도달 시 MaxTurnsExceededError를 던집니다. |
signal | – | 취소를 위한 AbortSignal 입니다. |
session | – | 세션 지속성 구현입니다. 세션 가이드를 참조하세요. |
sessionInputCallback | – | 모델 호출 전에 실행되는 세션 기록과 새 입력의 사용자 지정 병합 로직입니다. 세션을 참조하세요. |
callModelInputFilter | – | 모델 호출 직전에 모델 입력(항목 + 선택적 instructions)을 수정하는 훅입니다. Call model input filter를 참조하세요. |
tracing | – | 실행별 트레이싱 구성 재정의(예: 내보내기 API 키)입니다. |
conversationId | – | 서버 측 대화를 재사용합니다(OpenAI Responses API + Conversations API 전용). |
previousResponseId | – | 대화를 만들지 않고 이전 Responses API 호출에서 계속합니다(OpenAI Responses API 전용). |
스트리밍
섹션 제목: “스트리밍”스트리밍을 사용하면 LLM 이 실행되는 동안 추가로 스트리밍 이벤트를 받을 수 있습니다. 스트림이 시작되면 StreamedRunResult 에는 생성된 모든 새 출력을 포함하여 실행에 대한 완전한 정보가 포함됩니다. for await 루프를 사용해 스트리밍 이벤트를 반복 처리할 수 있습니다. 스트리밍 가이드에서 자세히 읽어보세요.
실행 구성
섹션 제목: “실행 구성”자체 Runner 인스턴스를 만드는 경우 runner 를 구성하기 위해 RunConfig 객체를 전달할 수 있습니다.
| Field | Type | Purpose |
|---|---|---|
model | string | Model | 실행의 모든 에이전트에 대해 특정 모델을 강제합니다. |
modelProvider | ModelProvider | 모델 이름을 확인합니다 – 기본값은 OpenAI provider 입니다. |
modelSettings | ModelSettings | 에이전트별 설정을 재정의하는 전역 튜닝 매개변수입니다. |
handoffInputFilter | HandoffInputFilter | 핸드오프를 수행할 때 입력 항목을 변경합니다(핸드오프 자체가 이미 정의하지 않은 경우). |
inputGuardrails | InputGuardrail[] | 초기 사용자 입력에 적용되는 가드레일입니다. |
outputGuardrails | OutputGuardrail[] | 최종 출력에 적용되는 가드레일입니다. |
tracingDisabled | boolean | OpenAI 트레이싱을 완전히 비활성화합니다. |
traceIncludeSensitiveData | boolean | 스팬은 유지하면서 트레이스에서 LLM/도구 입력 및 출력을 제외합니다. |
workflowName | string | Traces 대시보드에 표시됩니다 – 관련 실행을 그룹화하는 데 도움이 됩니다. |
traceId / groupId | string | SDK 가 생성하도록 두는 대신 트레이스 또는 그룹 ID 를 수동으로 지정합니다. |
traceMetadata | Record<string, string> | 모든 스팬에 첨부할 임의의 메타데이터입니다. |
tracing | TracingConfig | 실행별 트레이싱 재정의(예: 내보내기 API 키)입니다. |
sessionInputCallback | SessionInputCallback | 이 runner 의 모든 실행에 대한 기본 기록 병합 전략입니다. |
callModelInputFilter | CallModelInputFilter | 각 모델 호출 전에 모델 입력을 편집하는 전역 훅입니다. |
대화 / 채팅 스레드
섹션 제목: “대화 / 채팅 스레드”runner.run()(또는 run() 유틸리티)에 대한 각 호출은 애플리케이션 수준 대화에서 하나의 턴을 나타냅니다. 최종 사용자에게 RunResult 를 얼마나 보여줄지는 선택 사항입니다. 때로는 finalOutput 만, 다른 경우에는 생성된 모든 항목을 보여줄 수 있습니다.
import { Agent, run } from '@openai/agents';import type { AgentInputItem } from '@openai/agents';
let thread: AgentInputItem[] = [];
const agent = new Agent({ name: 'Assistant',});
async function userSays(text: string) { const result = await run( agent, thread.concat({ role: 'user', content: text }), );
thread = result.history; // Carry over history + newly generated items return result.finalOutput;}
await userSays('What city is the Golden Gate Bridge in?');// -> "San Francisco"
await userSays('What state is it in?');// -> "California"대화형 버전은 채팅 예제를 참조하세요.
서버 관리형 대화
섹션 제목: “서버 관리형 대화”OpenAI Responses API 가 매 턴마다 전체 로컬 기록을 보내는 대신 대화 기록을 유지하도록 할 수 있습니다. 이는 긴 대화나 여러 서비스를 조율할 때 유용합니다. 자세한 내용은 Conversation state guide를 참조하세요.
OpenAI 는 서버 측 상태를 재사용하는 두 가지 방법을 제공합니다:
1. 전체 대화를 위한 conversationId
섹션 제목: “1. 전체 대화를 위한 conversationId”Conversations API를 사용해 한 번 대화를 만들고 매 턴마다 그 ID 를 재사용할 수 있습니다. SDK 는 새로 생성된 항목만 자동으로 포함합니다.
import { Agent, run } from '@openai/agents';import { OpenAI } from 'openai';
const agent = new Agent({ name: 'Assistant', instructions: 'Reply very concisely.',});
async function main() { // Create a server-managed conversation: const client = new OpenAI(); const { id: conversationId } = await client.conversations.create({});
const first = await run(agent, 'What city is the Golden Gate Bridge in?', { conversationId, }); console.log(first.finalOutput); // -> "San Francisco"
const second = await run(agent, 'What state is it in?', { conversationId }); console.log(second.finalOutput); // -> "California"}
main().catch(console.error);2. 마지막 턴에서 계속하기 위한 previousResponseId
섹션 제목: “2. 마지막 턴에서 계속하기 위한 previousResponseId”어차피 Responses API 로만 시작하려는 경우 이전 응답에서 반환된 ID 를 사용해 각 요청을 체인할 수 있습니다. 이렇게 하면 전체 대화 리소스를 만들지 않고도 턴 간 컨텍스트가 유지됩니다.
import { Agent, run } from '@openai/agents';
const agent = new Agent({ name: 'Assistant', instructions: 'Reply very concisely.',});
async function main() { const first = await run(agent, 'What city is the Golden Gate Bridge in?'); console.log(first.finalOutput); // -> "San Francisco"
const previousResponseId = first.lastResponseId; const second = await run(agent, 'What state is it in?', { previousResponseId, }); console.log(second.finalOutput); // -> "California"}
main().catch(console.error);Call model input filter
섹션 제목: “Call model input filter”모델이 호출되기 직전에 모델 입력을 편집하려면 callModelInputFilter 를 사용하세요. 이 훅은 현재 에이전트, 컨텍스트, 결합된 입력 항목(세션 기록이 있는 경우 포함)을 받습니다. 업데이트된 input 배열과 선택적 instructions 를 반환하여 민감한 데이터를 마스킹하거나, 오래된 메시지를 제거하거나, 추가 시스템 지침을 주입할 수 있습니다.
runner.run(..., { callModelInputFilter }) 에서 실행별로 설정하거나 Runner 구성의 기본값으로 설정할 수 있습니다(RunConfig 의 callModelInputFilter).
SDK 는 다음과 같은 소수의 오류를 던지며, 이를 캐치할 수 있습니다:
MaxTurnsExceededError–maxTurns에 도달함ModelBehaviorError– 모델이 잘못된 출력 생성(예: JSON 형식 오류, 알 수 없는 도구)InputGuardrailTripwireTriggered/OutputGuardrailTripwireTriggered– 가드레일 위반GuardrailExecutionError– 가드레일 실행 실패ToolCallError– function tool 호출 중 하나 이상 실패UserError– 구성 또는 사용자 입력을 기반으로 발생한 오류
모두 기본 AgentsError 클래스를 확장하며, 현재 실행 상태에 접근할 수 있는 state 속성을 제공할 수 있습니다.
다음은 GuardrailExecutionError 를 처리하는 예제 코드입니다. 입력 가드레일은 실행의 첫 사용자 입력에서만 실행되므로, 예제는 원래 입력과 컨텍스트로 실행을 다시 시작합니다. 또한 모델을 다시 호출하지 않고 저장된 상태를 재사용해 출력 가드레일을 재시도하는 방법을 보여줍니다:
import { Agent, GuardrailExecutionError, InputGuardrail, InputGuardrailTripwireTriggered, OutputGuardrail, OutputGuardrailTripwireTriggered, run,} from '@openai/agents';import { z } from 'zod';
// Shared guardrail agent to avoid re-creating it on every fallback run.const guardrailAgent = new Agent({ name: 'Guardrail check', instructions: 'Check if the user is asking you to do their math homework.', outputType: z.object({ isMathHomework: z.boolean(), reasoning: z.string(), }),});
async function main() { const input = 'Hello, can you help me solve for x: 2x + 3 = 11?'; const context = { customerId: '12345' };
// Input guardrail example
const unstableInputGuardrail: InputGuardrail = { name: 'Math Homework Guardrail (unstable)', execute: async () => { throw new Error('Something is wrong!'); }, };
const fallbackInputGuardrail: InputGuardrail = { name: 'Math Homework Guardrail (fallback)', execute: async ({ input, context }) => { const result = await run(guardrailAgent, input, { context }); const isMathHomework = result.finalOutput?.isMathHomework ?? /solve for x|math homework/i.test(JSON.stringify(input)); return { outputInfo: result.finalOutput, tripwireTriggered: isMathHomework, }; }, };
const agent = new Agent({ name: 'Customer support agent', instructions: 'You are a customer support agent. You help customers with their questions.', inputGuardrails: [unstableInputGuardrail], });
try { // Input guardrails only run on the first turn of a run, so retries must start a fresh run. await run(agent, input, { context }); } catch (e) { if (e instanceof GuardrailExecutionError) { console.error(`Guardrail execution failed (input): ${e}`); try { agent.inputGuardrails = [fallbackInputGuardrail]; // Retry from scratch with the original input and context. await run(agent, input, { context }); } catch (ee) { if (ee instanceof InputGuardrailTripwireTriggered) { console.log('Math homework input guardrail tripped on retry'); } else { throw ee; } } } else { throw e; } }
// Output guardrail example
const replyOutputSchema = z.object({ reply: z.string() });
const unstableOutputGuardrail: OutputGuardrail<typeof replyOutputSchema> = { name: 'Answer review (unstable)', execute: async () => { throw new Error('Output guardrail crashed.'); }, };
const fallbackOutputGuardrail: OutputGuardrail<typeof replyOutputSchema> = { name: 'Answer review (fallback)', execute: async ({ agentOutput }) => { const outputText = typeof agentOutput === 'string' ? agentOutput : (agentOutput?.reply ?? JSON.stringify(agentOutput)); const flagged = /math homework|solve for x|x =/i.test(outputText); return { outputInfo: { flaggedOutput: outputText }, tripwireTriggered: flagged, }; }, };
const agent2 = new Agent<unknown, typeof replyOutputSchema>({ name: 'Customer support agent (output check)', instructions: 'You are a customer support agent. Answer briefly.', outputType: replyOutputSchema, outputGuardrails: [unstableOutputGuardrail], });
try { await run(agent2, input, { context }); } catch (e) { if (e instanceof GuardrailExecutionError && e.state) { console.error(`Guardrail execution failed (output): ${e}`); try { agent2.outputGuardrails = [fallbackOutputGuardrail]; // Output guardrails can be retried using the saved state without another model call. await run(agent2, e.state); } catch (ee) { if (ee instanceof OutputGuardrailTripwireTriggered) { console.log('Output guardrail tripped after retry with saved state'); } else { throw ee; } } } else { throw e; } }}
main().catch(console.error);입력 vs. 출력 재시도:
- 입력 가드레일은 실행의 맨 처음 사용자 입력에서만 실행되므로, 동일한 입력/컨텍스트로 새 실행을 시작해야 재시도할 수 있습니다. 저장된
state를 전달해도 입력 가드레일은 다시 트리거되지 않습니다. - 출력 가드레일은 모델 응답 이후에 실행되므로, 다른 모델 호출 없이도
GuardrailExecutionError로부터 저장된state를 재사용해 출력 가드레일을 다시 실행할 수 있습니다.
위 예제를 실행하면 다음 출력이 표시됩니다:
Guardrail execution failed (input): Error: Input guardrail failed to complete: Error: Something is wrong!Math homework input guardrail tripped on retryGuardrail execution failed (output): Error: Output guardrail failed to complete: Error: Output guardrail crashed.Output guardrail tripped after retry with saved state