에이전트 실행
에이전트는 스스로 아무것도 하지 않습니다. 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
인스턴스를 실행하는 run()
유틸리티를 사용할 수 있습니다.
또는 직접 러너 인스턴스를 생성할 수 있습니다:
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의 항목에 해당하는 입력 항목 목록일 수 있습니다.
러너는 다음 루프를 실행합니다:
- 현재 입력으로 현재 에이전트의 모델을 호출합니다
- LLM 응답을 검사합니다
- 최종 출력 → 반환
- 핸드오프 → 새로운 에이전트로 전환, 누적된 대화 기록 유지, 1로 이동
- 도구 호출 → 도구 실행, 그 결과를 대화에 추가, 1로 이동
maxTurns
에 도달하면MaxTurnsExceededError
를 던집니다
Runner 수명 주기
섹션 제목: “Runner 수명 주기”앱 시작 시 Runner
를 생성하고 요청 간 재사용하세요. 인스턴스는 모델 프로바이더와 트레이싱 옵션 같은 전역 구성을 저장합니다. 완전히 다른 설정이 필요할 때만 다른 Runner
를 만드세요. 간단한 스크립트에서는 내부적으로 기본 러너를 사용하는 run()
을 호출할 수도 있습니다.
실행 인수
섹션 제목: “실행 인수”run()
메서드의 입력은 실행을 시작할 초기 에이전트, 실행 입력, 옵션 집합입니다.
입력은 문자열(사용자 메시지로 간주), 입력 항목 목록, 또는 휴먼 인 더 루프 (HITL) 에이전트를 구축하는 경우 RunState
객체일 수 있습니다.
추가 옵션은 다음과 같습니다:
Option | Default | Description |
---|---|---|
stream | false | true 이면 호출이 StreamedRunResult 를 반환하고 모델에서 도착하는 대로 이벤트를 내보냅니다 |
context | – | 모든 tool / guardrail / handoff에 전달되는 컨텍스트 객체. 자세한 내용은 컨텍스트 관리를 참고하세요 |
maxTurns | 10 | 안전 한도 – 도달 시 MaxTurnsExceededError 발생 |
signal | – | 취소를 위한 AbortSignal |
스트리밍
섹션 제목: “스트리밍”스트리밍을 사용하면 LLM이 실행되는 동안 스트리밍 이벤트를 추가로 받을 수 있습니다. 스트림이 시작되면 StreamedRunResult
에는 새로 생성된 모든 출력 등을 포함해 실행에 대한 완전한 정보가 담깁니다. for await
루프로 스트리밍 이벤트를 순회할 수 있습니다. 자세한 내용은 스트리밍 가이드를 참고하세요.
실행 구성
섹션 제목: “실행 구성”직접 Runner
인스턴스를 생성하는 경우 러너를 구성하기 위해 RunConfig
객체를 전달할 수 있습니다.
Field | Type | Purpose |
---|---|---|
model | string | Model | 실행의 모든 에이전트에 특정 모델을 강제 적용 |
modelProvider | ModelProvider | 모델 이름 해석 – 기본값은 OpenAI 프로바이더 |
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, any> | 모든 스팬에 첨부할 임의의 메타데이터 |
대화 / 채팅 스레드
섹션 제목: “대화 / 채팅 스레드”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"
대화형 버전은 채팅 code examples를 참고하세요.
SDK는 다음과 같은 소수의 오류를 던지며, 이를 캐치할 수 있습니다:
MaxTurnsExceededError
–maxTurns
에 도달ModelBehaviorError
– 모델이 잘못된 출력 생성(예: 잘못된 JSON, 알 수 없는 도구)InputGuardrailTripwireTriggered
/OutputGuardrailTripwireTriggered
– 가드레일 위반GuardrailExecutionError
– 가드레일 실행 실패ToolCallError
– 함수 도구 호출 중 하나 이상 실패UserError
– 구성 또는 사용자 입력에 기반해 발생한 오류
모두 기본 AgentsError
클래스를 확장하며, 현재 실행 상태에 접근할 수 있는 state
속성을 제공할 수 있습니다.
다음은 GuardrailExecutionError
를 처리하는 예시 코드입니다:
import { Agent, run, GuardrailExecutionError, InputGuardrail, InputGuardrailTripwireTriggered,} from '@openai/agents';import { z } from 'zod';
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(), }),});
const unstableGuardrail: InputGuardrail = { name: 'Math Homework Guardrail (unstable)', execute: async () => { throw new Error('Something is wrong!'); },};
const fallbackGuardrail: InputGuardrail = { name: 'Math Homework Guardrail (fallback)', execute: async ({ input, context }) => { const result = await run(guardrailAgent, input, { context }); return { outputInfo: result.finalOutput, tripwireTriggered: result.finalOutput?.isMathHomework ?? false, }; },};
const agent = new Agent({ name: 'Customer support agent', instructions: 'You are a customer support agent. You help customers with their questions.', inputGuardrails: [unstableGuardrail],});
async function main() { try { const input = 'Hello, can you help me solve for x: 2x + 3 = 11?'; const result = await run(agent, input); console.log(result.finalOutput); } catch (e) { if (e instanceof GuardrailExecutionError) { console.error(`Guardrail execution failed: ${e}`); // If you want to retry the execution with different settings, // you can reuse the runner's latest state this way: if (e.state) { try { agent.inputGuardrails = [fallbackGuardrail]; // fallback const result = await run(agent, e.state); console.log(result.finalOutput); } catch (ee) { if (ee instanceof InputGuardrailTripwireTriggered) { console.log('Math homework guardrail tripped'); } } } } else { throw e; } }}
main().catch(console.error);
위 예시를 실행하면 다음 출력이 표시됩니다:
Guardrail execution failed: Error: Input guardrail failed to complete: Error: Something is wrong!Math homework guardrail tripped